tthtlc

pycommand

Apr 3rd, 2014
1,107
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 312.09 KB | None | 0 0
  1. #/usr/bin/env python
  2.  
  3. import getopt
  4. import struct
  5. import immutils
  6. from immlib import *
  7.  
  8. copyright="(C) Immunity, Inc."
  9. DESC = "Dumps Acrobat Reader Cache state"
  10.  
  11. class AdobeHeap:
  12. def __init__(self,AcroPool):
  13. '''
  14. AcroManagingPool (hardcoded address depens on version of the AcroRd32.dll)
  15. From this address it's possible to access all managing structures of their custom heap implementation.
  16. '''
  17. self.AcroPool = AcroPool
  18. self.imm = Debugger()
  19. self.pAcroCacheList = []
  20. self.CacheHeadersInfo = []
  21. self.AcroManagingPool()
  22.  
  23. def AcroManagingPool(self):
  24. self.AcroPool += 0xC #Reserved
  25. self.mem = self.imm.readMemory(self.AcroPool,128) #Managing structures for AcroCache
  26. self.lpCacheManaging = struct.unpack("32L",self.mem)
  27. self.AcroPool += (0x90 - 0xC) #Header of the first AcroBlock
  28. self.FirstAcroBlock = self.imm.readLong(self.AcroPool)
  29.  
  30. def CacheManager(self,addr):
  31. self.AcroPool = self.imm.readMemory(addr,0x10)
  32. (pAcroPool,pFreeBlocksList,pAcroCacheList,blocksize) = struct.unpack("4L",self.AcroPool)
  33. self.imm.log("pAcroPool: 0x%08x pFreeBlocksList: 0x%08x pAcroCacheList: 0x%08x blocksize: 0x%08x" % (pAcroPool,pFreeBlocksList,pAcroCacheList,\
  34. blocksize), address = pAcroCacheList)
  35. return pAcroCacheList
  36.  
  37. def CacheHeader(self,addr):
  38. self.AcroPool = self.imm.readMemory(addr,0x18)
  39. (pCacheManager,allocatedBlocks,flag,blink,flink,size) = struct.unpack("6L",self.AcroPool)
  40.  
  41. self.imm.log("CacheManager: 0x%08x AllocatedBlocks: 0x%08x Flags: 0x%08x BLINK: 0x%08x FLINK: 0x%08x Size: 0x%08x" % (pCacheManager,allocatedBlocks\
  42. ,flag,blink,flink,size), address = addr)
  43. return flink
  44.  
  45. def walkCache(self,addr):
  46. isAcroBlock = False
  47. isCache = False
  48.  
  49. flag = self.imm.readLong(addr+0x8)
  50. if flag == 2:
  51. isAcroBlock = True
  52. size = self.imm.readLong(addr+0x18)
  53. elif flag == 0:
  54. isCache = True
  55. size = self.imm.readLong(addr+0x14)
  56. self.imm.log("")
  57. self.imm.log("***Walking through 0x%08x bytes cache***"%size)
  58.  
  59. i = 0
  60. while 1:
  61. Flink = self.imm.readLong(addr+0x10)
  62. AllocatedBlocks = self.imm.readLong(addr+0x04)
  63. AcroBlockSize = self.imm.readLong(addr+0x14)
  64. if not Flink:
  65. self.imm.log("***Walk Done***")
  66. break
  67. if isCache:
  68. self.imm.log("Cache[%d]: 0x%08x | Allocated Blocks: [%d/128]" % (i,addr,AllocatedBlocks), address = addr)
  69. elif isAcroBlock:
  70. self.imm.log("AcroBlock: 0x%08x | Size: 0x08%x" % (Flink,AcroBlockSize), address = Flink)
  71. addr = Flink
  72. i += 1
  73.  
  74. def getCacheManagers(self):
  75. self.imm.log("")
  76. self.imm.log("CacheManagers List:")
  77. i=0
  78. for x in self.lpCacheManaging:
  79. self.imm.log("lpCacheManaging[%d]: 0x%08x" % (i,x))
  80. i += 1
  81.  
  82. def getCacheManagersInfo(self):
  83. self.imm.log("")
  84. self.imm.log("[Cache Managers Info]")
  85. for x in self.lpCacheManaging:
  86. self.pAcroCacheList.append(self.CacheManager(x))
  87.  
  88. def getCacheHeaders(self):
  89. self.imm.log("")
  90. self.imm.log("[Cache Headers]")
  91. for x in self.pAcroCacheList:
  92. try:
  93. self.CacheHeadersInfo.append(self.CacheHeader(x))
  94. except:
  95. pass
  96.  
  97. def dumpCache(self):
  98. self.getCacheManagers()
  99. self.getCacheManagersInfo()
  100. self.getCacheHeaders()
  101. self.pAcroCacheList.pop(0) #unused entry
  102.  
  103. for x in self.pAcroCacheList:
  104. self.walkCache(x)
  105.  
  106. def DumpAcroBlocks(self):
  107. addr = self.FirstAcroBlock
  108. self.AcroPool = self.imm.readMemory(addr,0x18)
  109. (pAcroPool,reserved,flag,blink,flink,size) = struct.unpack("6L",self.AcroPool)
  110. self.walkCache(flink)
  111.  
  112.  
  113. def usage(imm):
  114. imm.log("!acrocache")
  115. imm.log(" -c Dump AcroCache state")
  116. imm.log(" -f CACHEBLOCKADDR Follow CacheBlocks of same size and show allocations count")
  117. imm.log(" -b Dump AcroBlocks")
  118.  
  119. def main(args):
  120. imm = Debugger()
  121. pAcroManagingPool = 0x014D38A0 #Acrobat Reader 9.4.0
  122.  
  123. try:
  124. AcroManagingPool = imm.readLong(pAcroManagingPool)
  125. except:
  126. return "Couldn't read from AcroManagingPool pointer. Are you on Reader 9.4.0?"
  127. adobe = AdobeHeap(AcroManagingPool)
  128.  
  129.  
  130. if not args:
  131. usage(imm)
  132. try:
  133. opts, argo = getopt.getopt(args, "bcf:")
  134. except getopt.GetoptError:
  135. usage(imm)
  136. for o,a in opts:
  137. if o == "-f":
  138. try:
  139. adobe.walkCache(int(a, 16))
  140. except ValueError, msg:
  141. return "Invalid address: %s" % a
  142. if o == "-b":
  143. adobe.DumpAcroBlocks()
  144. if o == "-c":
  145. adobe.dumpCache()
  146.  
  147. return "done"
  148. """
  149. This is just a little script for ImmunityDebugger that will resolve
  150. exposed COM functions to their relative address. Check usage for some TODO items.
  151.  
  152. NOTE: Requires comtypes http://sourceforge.net/projects/comtypes/
  153. Also comtypes .exe requires MS VC 9.0 redistributables:
  154. http://www.microsoft.com/downloads/thankyou.aspx?familyId=9b2da534-3e03-4391-8a4d-074b9f2bc1bf&displayLang=en
  155.  
  156. You will need to register your activex that you are auditing. Use "regsvr32 activexthing.dll"
  157. IUf you're doing this on Vista, remember to run regsvr32 from an elevated cmd.exe!
  158. """
  159. from ctypes import *
  160. from ctypes.wintypes import *
  161. try:
  162. from comtypes import *
  163. from comtypes.typeinfo import *
  164. from comtypes.automation import *
  165. except ImportError:
  166. raise Exception("Comtypes library needed")
  167.  
  168. from immlib import *
  169.  
  170. ole32 = windll.ole32
  171. kernel32 = windll.kernel32
  172.  
  173. class MEMORY_BASIC_INFORMATION(Structure):
  174.  
  175. _fields_ = [
  176. ('BaseAddress', c_void_p),
  177. ('AllocationBase', c_void_p),
  178. ('AllocationProtect', c_ulong),
  179. ('RegionSize', c_ulong),
  180. ('State', c_ulong),
  181. ('Protect', c_ulong),
  182. ('Type', c_ulong),
  183. ]
  184.  
  185. def get_linear_address(address):
  186.  
  187. mbi = MEMORY_BASIC_INFORMATION()
  188. kernel32.VirtualQuery(address,byref(mbi),sizeof(mbi))
  189. return mbi.AllocationBase
  190.  
  191. def enum_type_info_members(p_iref_type_info,p_reftype_attr,p_iunknown,imm, base_addr, mode):
  192.  
  193. if p_reftype_attr.cFuncs == 0:
  194. return
  195.  
  196. vtable = 0x0
  197. code_base = imm.getKnowledge("codebase")
  198.  
  199. for i in range(p_reftype_attr.cFuncs):
  200.  
  201. func_desc = p_iref_type_info.GetFuncDesc(i)
  202. method_name = p_iref_type_info.GetNames(func_desc.memid)
  203. inv_kind = func_desc.invkind
  204.  
  205.  
  206. lpVtbl = cast(p_iunknown, POINTER(POINTER(c_void_p)))
  207.  
  208. value = get_linear_address(lpVtbl[0][func_desc.oVft])
  209. if str(method_name[0]) == "QueryInterface":
  210. import struct
  211. address = (((lpVtbl[0][i])-(value+0x1000)))
  212. address = address + code_base
  213. #activex = activex.split(".")[0]
  214. pages = imm.getMemoryPageByOwnerAddress( base_addr ) # workaround
  215. for page in pages:
  216. mem = page.getMemory()
  217. ndx = mem.find( struct.pack("L", address) )
  218. if ndx != -1:
  219. vtable = page.getBaseAddress() + ndx
  220. break
  221.  
  222. #imm.log("values %s" % str(method_name[0]))
  223.  
  224. if value is not None and lpVtbl[0][i] is not None:
  225.  
  226. if func_desc.invkind == INVOKE_FUNC or func_desc.invkind == INVOKE_PROPERTYPUT or func_desc.invkind == INVOKE_PROPERTYPUTREF:
  227. address = (((lpVtbl[0][i])-(value+0x1000)))
  228.  
  229. address = address + code_base
  230. else:
  231. if func_desc.invkind == INVOKE_FUNC or func_desc.invkind == INVOKE_PROPERTYPUT or func_desc.invkind == INVOKE_PROPERTYPUTREF:
  232. try:
  233. address = imm.readLong( vtable + i*4)
  234. except Exception:
  235. address = 0
  236.  
  237. imm.log("Method: %s Address: 0x%08x" % (str(method_name[0]),address),address)
  238. if mode == "label_func":
  239. imm.setLabel(address, str(method_name[0]) )
  240.  
  241. def usage(imm):
  242.  
  243. imm.log("This is a helper for RE/bughunting ActiveX controls.")
  244. imm.log("!activex <name of Control> - this outputs all functions and their addresses.")
  245. imm.log("!activex <name of Control> break <function name> - set a breakpoint on a function name.")
  246. imm.log("!activex <name of Control> exec <function name> - call the function internally.")
  247. imm.log("!activex <name of Control> fuzz <function name> - fuzz this function.")
  248. imm.log("!activex <name of Control> label - Label all the activex methods.")
  249.  
  250.  
  251. def main(args):
  252. imm = Debugger()
  253. imm.log("Args to activex: %s"%repr(args))
  254. mode=None
  255. func = None
  256. try:
  257. if args[0]:
  258. activex = args[0]
  259. if len(args) > 1:
  260. if args[1]:
  261.  
  262. if args[1] == "break":
  263. mode = "break_on_func"
  264. func = args[2]
  265.  
  266. elif args[1] == "exec":
  267. mode = "exec_func"
  268. func = args[2]
  269.  
  270. elif args[1] == "fuzz":
  271. mode = "fuzz_func"
  272. func = args[2]
  273.  
  274. elif args[1] == "label":
  275. mode = "label_func"
  276.  
  277. else:
  278. activex = args[0]
  279. else:
  280. usage(imm)
  281. return "Usage Information Outputted to log view (Alt-L)"
  282. except:
  283. usage(imm)
  284. return "Usage Information Outputted to Log View (Alt-L)"
  285.  
  286. module = imm.getModule(activex)
  287. if not module:
  288. return "Module \"%s\" not found. Chech the Executable modules (Alt+E)" % activex
  289.  
  290. imm.addKnowledge("codebase",module.getCodebase(),force_add=1)
  291.  
  292. tlib = LoadTypeLib(module.getPath())
  293.  
  294. ticount = tlib.GetTypeInfoCount()
  295.  
  296. i = 0
  297.  
  298. while i < ticount:
  299.  
  300. p_itype_info = tlib.GetTypeInfo(i)
  301.  
  302. if p_itype_info:
  303. p_type_attr = p_itype_info.GetTypeAttr()
  304.  
  305. if p_type_attr.typekind is TKIND_COCLASS:
  306.  
  307. for ref in range(p_type_attr.cImplTypes):
  308. h_ref_type = p_itype_info.GetRefTypeOfImplType(ref)
  309.  
  310. if h_ref_type:
  311.  
  312. p_iref_type_info = p_itype_info.GetRefTypeInfo(h_ref_type)
  313.  
  314. if p_iref_type_info:
  315. p_reftype_attr = p_iref_type_info.GetTypeAttr()
  316. imm.log("CLSID: %s " % str(p_type_attr.guid))
  317. #try:
  318.  
  319. p_iunknown = CoCreateInstance(p_type_attr.guid)
  320. #except:
  321. # pass
  322.  
  323. if p_iunknown:
  324.  
  325. enum_type_info_members(p_iref_type_info,p_reftype_attr,p_iunknown,imm, module.getBaseAddress(), mode)
  326.  
  327.  
  328.  
  329. i+=1
  330.  
  331. return "ActiveX Methods Trapped"
  332. # apitrace PyCommand - (c)Immunity Inc.
  333. # Justin Seitz <justin@immunityinc.com>
  334. # TODO:
  335. # - dereference stack params if the function doesn't contain symbols
  336.  
  337. import getopt
  338.  
  339. from immlib import *
  340.  
  341. NAME = "apitrace"
  342.  
  343. def usage(imm):
  344. imm.log("!%s Hooks all intermodular function calls" % (NAME))
  345. imm.log(" (excluding Rtl* by default). The -i and -e options")
  346. imm.log(" specify strings that if found in a function name")
  347. imm.log(" result in it being included or excluded from the")
  348. imm.log(" trace")
  349. imm.log("-i Include pattern")
  350. imm.log("-e Exclude pattern")
  351. imm.log(" ")
  352. imm.log("e.g. !apitrace -i msvcrt -e printf")
  353. imm.log("The above will hook all calls with msvcrt in the name")
  354. imm.log("excluding those with printf. So msvcrt.memset will be")
  355. imm.log("logged but not msvcrt._vsnwprintf")
  356.  
  357. class ExportHooks(LoadDLLHook):
  358.  
  359. def __init__(self):
  360. LoadDLLHook.__init__(self)
  361. self.imm = Debugger()
  362. self.hooker = InterCallHook()
  363.  
  364. def run(self, regs):
  365.  
  366. # We gotta new DLL loaded, time to find all it's functions
  367. # and set breakpoints on them, hopefully to bypass the pain
  368. # of having to rebuild IATs.
  369. event = self.imm.getEvent()
  370. self.imm.log("Module that just got loaded: %s" % event.lpImageName)
  371. #module = self.imm.getModule( event.lpImageName )
  372.  
  373. # Force analysis
  374. self.imm.analyseCode( module.getCodebase() )
  375.  
  376. # Now walk all the functions and set breakpoints on the functions
  377. # that we can resolve correctly
  378. function_list = self.imm.getAllFunctions( module.getCodebase() )
  379.  
  380. for i in function_list:
  381.  
  382. function = self.imm.getFunction( i )
  383. function_name = self.imm.decodeAddress( i )
  384.  
  385. # Now we add all of our breakpoints to the main hook
  386. self.hooker.add( function_name, i )
  387.  
  388.  
  389. class InterCallHook(LogBpHook):
  390.  
  391. def __init__(self):
  392. LogBpHook.__init__(self)
  393. self.imm = Debugger()
  394.  
  395. def run(self, regs):
  396.  
  397. # We have hit the function head, now we decode
  398. # the function and all of its parameters, quite handy
  399. call_stack = self.imm.callStack()
  400.  
  401.  
  402. # Now we just do some funky workarounds to make sure
  403. # we are decoding the information correctly
  404. main_call = False
  405.  
  406. for i in call_stack:
  407.  
  408. if i.getProcedure().startswith(" ") == False:
  409. if main_call == True:
  410. break
  411. else:
  412. main_call == True
  413. self.imm.log("")
  414. self.imm.log("Function Call -> %s" % i.getProcedure(), address = regs['EIP'])
  415. else:
  416. self.imm.log("%s" % i.getProcedure() )
  417.  
  418. def main(args):
  419.  
  420. imm = Debugger()
  421. include_pattern = exclude_pattern = None
  422.  
  423. try:
  424. opts, args = getopt.getopt(args, "i:e:")
  425. except getopt.GetoptError:
  426. usage(imm)
  427. return "Incorrect arguments (Check log window)"
  428.  
  429. for o, a in opts:
  430. if o == "-i":
  431. include_pattern = a
  432. elif o == "-e":
  433. exclude_pattern = a
  434. else:
  435. usage(imm)
  436. return "Incorrect arguments (Check log window)"
  437.  
  438. # Find all intermodular commands in the executable
  439. # and set a logging BP hook on them. Ignore all calls
  440. # to Rtl* as they need to be instrumented with fast hooks
  441. module = imm.getModule( imm.getDebuggedName() )
  442.  
  443. # We use a LoadDLLHook so that if libraries get added
  444. # we automagically add the new functions to the global hook
  445. loaddll_hook = ExportHooks()
  446. loaddll_hook.add("Generic DLL handler.")
  447.  
  448. hooker = InterCallHook()
  449.  
  450. if not module.isAnalysed():
  451. imm.analyseCode( module.getCodebase() )
  452.  
  453. call_list = imm.getInterCalls( module.getCodebase() )
  454.  
  455. for call in call_list.keys():
  456.  
  457. function_name = imm.decodeAddress( int(call_list[call][0][2]) )
  458. function_suffix = function_name.split(".")[1]
  459.  
  460. # Skip any Rtl* calls, we are just splitting a string like kernel32.LoadLibraryA
  461. if function_suffix.startswith("Rtl"):
  462. continue
  463.  
  464. if exclude_pattern is not None and \
  465. function_name.find(exclude_pattern) != -1:
  466. continue
  467.  
  468. if include_pattern is not None and \
  469. function_name.find(include_pattern) == -1:
  470. continue
  471.  
  472. hooker.add( function_name, call_list[call][0][2] )
  473.  
  474.  
  475. imm.log("From: 0x%08x -> To: 0x%08x (decoded: %s) " % \
  476. (int(call),int(call_list[call][0][2]),function_name))
  477.  
  478.  
  479. return "[*] All intermodular calls found and hooked."
  480. #!/usr/bin/env python
  481.  
  482. #-------------------------------------------------------------------------------
  483. #
  484. # By BoB -> Team PEiD
  485. # http://www.SecretAsHell.com/BobSoft/
  486. # BobSoft@GMail.Com
  487. #
  488. #-------------------------------------------------------------------------------
  489. #
  490. # Thanks to JMS for some TLS code used in this script .. ;)
  491. #
  492. #-------------------------------------------------------------------------------
  493. #
  494. # V1.01
  495. # Fixed a missing var in getAddressInTlsCallbacks() ..
  496. #
  497. #-------------------------------------------------------------------------------
  498.  
  499. import immlib
  500. import pefile
  501.  
  502. __VERSION__ = '1.01'
  503. DESC = "Sets a breakpoint on entrypoint of main module .."
  504. ProgName = 'BpxEP'
  505. ProgVers = __VERSION__
  506.  
  507.  
  508. #-------------------------------------------------------------------------------
  509.  
  510. def usage(imm):
  511. imm.log(" ")
  512. imm.log("%s v%s By BoB -> Team PEiD" % (ProgName, ProgVers),focus=1, highlight=1)
  513. imm.log("Description:")
  514. imm.log(" Sets Breakpoint on entrypoint of main module and optionally runs until entrypoint reached ..")
  515. imm.log(" For use when a packed file fails to stop at entrypoint, EG [MSLRH], UPack ..")
  516. imm.log(" Debugging these files results in ImmDbg starting at system startup breakpoint ..")
  517. imm.log(" Also there is ability to place breakpoint at TLS callbacks, this is for packers that")
  518. imm.log(" run code from TLS callbacks, or unpack from TLS, EG: ASDPack v1.0 ..")
  519. imm.log(" With ASDPack the target PE File loaded into ImmDbg will run instead of stopping, so ")
  520. imm.log(" you must set Debugging Options -> Event -> Start at system breakpoint - then run script")
  521. imm.log(" with -tls and -go params.. ")
  522. imm.log(" ")
  523. imm.log("Usage:")
  524. imm.log(" !%s [-go] [-tls]" % ProgName.lower())
  525. imm.log(" ")
  526. imm.log("Options:")
  527. imm.log(" -go : After setting breakpoint on EP, run (F9)")
  528. imm.log(" -tls : Set Bpx on TLS callbacks too .. (Uses code by JMS)")
  529. imm.log(" ")
  530. return "See log window (Alt-L) for usage .. "
  531.  
  532.  
  533. #-------------------------------------------------------------------------------
  534. # Some of this TLS code from JMS, thanks :)
  535. # Returns 0 if no callbacks, else address of first callback ..
  536.  
  537. def hasTlsCallbacks(pe, imm):
  538. addr = 0
  539. # Maybe no TLS table ?
  540. if hasattr(pe, "DIRECTORY_ENTRY_TLS"):
  541. tls_callbacks_table = pe.DIRECTORY_ENTRY_TLS.struct.AddressOfCallBacks
  542. # Maybe no TLS callbacks pointer?
  543. if tls_callbacks_table:
  544. addr = imm.readLong(tls_callbacks_table)
  545. # Maybe has TLS table, has Callbacks pointer, but points to null .. (Delphi does this)
  546. if addr != 0:
  547. return tls_callbacks_table
  548. return addr
  549.  
  550.  
  551. #-------------------------------------------------------------------------------
  552. # Returns fixed callback address if imagebase changed ..
  553.  
  554. def getAddressInTlsCallbacks(pe, imm, index):
  555. # This was missing in v.00 .. ;/
  556. addr = 0
  557. a = hasTlsCallbacks(pe, imm)
  558. if a != 0:
  559. addr = imm.readLong(a + (index * 4)) # Zero-Based index !
  560. # Maybe relocated ?
  561. if imm.getModule(imm.getDebuggedName()).getBaseAddress() != pe.OPTIONAL_HEADER.ImageBase:
  562. # Fix the TLS Callback Virtual Address ..
  563. addr = (addr - pe.OPTIONAL_HEADER.ImageBase) + imm.getModule(imm.getDebuggedName()).getBaseAddress()
  564. return addr
  565.  
  566.  
  567. #-------------------------------------------------------------------------------
  568.  
  569. def isAddressInTlsCallbacks(pe, imm, addr):
  570. for i in range(1000):
  571. TlsAddr = getAddressInTlsCallbacks(pe, imm, i)
  572. if TlsAddr == addr:
  573. return True
  574. if TlsAddr == 0:
  575. return False
  576.  
  577.  
  578. #-------------------------------------------------------------------------------
  579.  
  580. def main(args):
  581. imm = immlib.Debugger()
  582. Mod = imm.getModule(imm.getDebuggedName())
  583. pe = pefile.PE(name=Mod.getPath())
  584. ep = pe.OPTIONAL_HEADER.AddressOfEntryPoint + Mod.getBaseAddress()
  585. imm.log(" ")
  586. imm.log("%s v%s By BoB -> Team PEiD" % (ProgName, ProgVers), highlight=1)
  587.  
  588. TlsBpx = False
  589. RunAfter = False
  590. if args:
  591. for i in range(len(args)):
  592. if (args[i].lower() == "-tls"):
  593. TlsBpx = not TlsBpx
  594. if (args[i].lower() == "-go"):
  595. RunAfter = not RunAfter
  596.  
  597. if TlsBpx == True:
  598. # Do we have a Tls table and callbacks ?
  599. addr = getAddressInTlsCallbacks(pe, imm, 0)
  600. if (addr == 0):
  601. # Stop and display error, else we could be running with -go .. :/
  602. imm.log("This file has no TLS callbacks ..")
  603. imm.log(" ")
  604. return "There were errors, please see log window (Alt-L)"
  605.  
  606. count = 0
  607. while addr != 0:
  608. imm.setTemporaryBreakpoint(addr)
  609. count += 1
  610. imm.log("Set Breakpoint on TLS callback #%d .." % count, address=addr)
  611. imm.setComment(addr, "TLS callback #%d" % count)
  612. addr = getAddressInTlsCallbacks(pe, imm, count)
  613.  
  614. # Get current EIP in ImmDbg ..
  615. EIP = imm.getCurrentAddress()
  616. # User error check .. :)
  617. if EIP != ep:
  618. imm.setTemporaryBreakpoint(ep)
  619. imm.log("Breakpoint set at EntryPoint ..", address=ep)
  620. imm.setComment(ep, "EntryPoint of \"%s\" .. " % imm.getDebuggedName())
  621. # Only run if not at EP .. :)
  622. if RunAfter == True:
  623. imm.log("Running ..")
  624. imm.run()
  625. else:
  626. imm.log("You are already at entrypoint ..")
  627. imm.log(" ")
  628. return "Program entry point"
  629.  
  630. imm.log(" ")
  631.  
  632. EIP = imm.getCurrentAddress()
  633. # If we ran then we should be at EP ..
  634. if EIP == ep:
  635. if imm.isAnalysed(ep) == 0:
  636. # Try to analyse code at entrypoint ..
  637. imm.analyseCode(ep)
  638. return "Program entry point"
  639.  
  640. # Maybe we have hit a TLS Callback ?
  641. elif isAddressInTlsCallbacks(pe, imm, EIP):
  642. if imm.isAnalysed(EIP) == 0:
  643. # Try to analyse code at callback entrypoint ..
  644. imm.analyseCode(EIP)
  645. return imm.getComment(EIP)
  646.  
  647. else:
  648. return "Breakpoint set at EntryPoint of \"%s\" .." % imm.getDebuggedName()
  649.  
  650. #!/usr/bin/env python
  651.  
  652. """
  653. (c) Immunity, Inc. 2004-2007
  654.  
  655.  
  656. U{Immunity Inc.<http://www.immunityinc.com>}
  657. """
  658.  
  659. import immlib
  660. import getopt
  661. from libheap import *
  662. from immlib import LogBpHook
  663. import libdatatype
  664.  
  665. DESC = "Analize a Specific Chunk at a specific moment"
  666.  
  667. def usage(imm):
  668. imm.log("!chunkanalyzehook -a ADDRESS < exp >", focus=1)
  669. imm.log(" ADDRESS of the place where you want to set a hook")
  670. imm.log(" < exp > expression to calculate the chunk address")
  671. imm.log("ex: !chunkanalyzehook -a 0x1006868 EDI - 4")
  672.  
  673. FunctionsType = [ "+", "-", "*", "/", "&", "^"]
  674.  
  675. # Hook and Dump some Chunks based on the Expression
  676. class HookAndInform(LogBpHook):
  677. Functions = { "+": lambda a,b: a+b,
  678. "-": lambda a,b: a-b,
  679. "*": lambda a,b: a*c,
  680. "/": lambda a,b: a/c,
  681. "&": lambda a,b: a&c,
  682. "^": lambda a,b: a^c
  683. }
  684.  
  685. def __init__(self, exp, discover = False, nchunks = 3, heap = 0):
  686. LogBpHook.__init__(self)
  687. self.Expression = exp
  688. self.discover = discover
  689. self.nchunks = nchunks
  690. self.heap = heap
  691.  
  692.  
  693. def run(self, regs):
  694. imm = immlib.Debugger()
  695.  
  696. accumulator = 0
  697. second = 0
  698. func = '+'
  699. # Calculate the Chunk Address based on the Expression
  700. for value in self.Expression:
  701. if value in self.Functions.keys():
  702. func = value
  703. else:
  704. if type(value) == type(0):
  705. second = value
  706. elif regs.has_key(value.upper()):
  707. second = regs[ value.upper() ]
  708. elif value[0]=='[' and value[-1] ==']' and regs.has_key(value[1:-1].upper()):
  709. second = imm.readLong( regs[ value[1:-1].upper()] )
  710. else:
  711.  
  712. self.unHook()
  713. accumulator = self.Functions[func]( accumulator, second)
  714. imm.log("> Hit Hook 0x%08x, checking chunk: 0x%08x" % (self.address, accumulator), address = accumulator)
  715. imm.log("=" * 47)
  716.  
  717. pheap = PHeap( imm, self.heap )
  718. plookaddr = 0
  719. if self.heap:
  720. plookaddr = pheap.Lookaddr
  721. hlook = None
  722. if plookaddr:
  723. hlook = PHeapLookaside( imm, plookaddr )
  724. dt = None
  725. if self.discover:
  726. dt = libdatatype.DataTypes(imm)
  727. pheap = PHeap( imm )
  728. for chk in pheap.getChunks( accumulator, self.nchunks ):
  729. if chk.size < 0x7F and hlook:
  730. l = hlook[ chk.size ]
  731. if not l.isEmpty():
  732. if chk.addr+8 in l.getList():
  733. imm.log("- LOOKASIDE -")
  734. chk.printchunk(uselog = imm.log, dt = dt)
  735. imm.log("=-" * 0x23 + "=")
  736.  
  737.  
  738.  
  739. def main(args):
  740. imm = immlib.Debugger()
  741. if not args:
  742. usage(imm)
  743. return "Wrong Arguments (Check usage on the Log Window)"
  744. try:
  745. opts, argo = getopt.getopt(args, "h:n:a:d")
  746. except getopt.GetoptError:
  747. return "Wrong Arguments (Check usage on the Log Window)"
  748.  
  749. address = None
  750. expression = argo
  751. discover = False
  752. nchunks = 3
  753. heap = 0
  754.  
  755. for o,a in opts:
  756. if o == '-a':
  757. try:
  758. address = int( a, 16 )
  759. except ValueError:
  760. usage(imm)
  761. return "Wrong Address (%s) % " % a
  762. elif o == '-d':
  763. discover = True
  764. elif o == '-n':
  765. nchunks = int( a, 16 )
  766. elif o == '-h':
  767. heap = int( a, 16 )
  768.  
  769. imm.log("Expression: %s" % argo)
  770. if not address and not expression:
  771. usage( imm )
  772. return "Wrong usage (Check usage on the Log Window)"
  773.  
  774. accumulator = 0
  775. func = '+'
  776. regs = {'EIP': 0L, 'ESP': 0L, 'EDI': 0L, 'EAX': 0L, 'EBP': 0L, 'EDX': 0L, 'EBX': 0L, 'ESI': 0L, 'ECX': 0L}
  777. # normalizing and checking the expression
  778. for ndx in range(0, len(expression) ):
  779. value = expression[ndx]
  780. if value not in FunctionsType:
  781. if value.upper() in regs.keys():
  782. expression[ndx] = value.upper()
  783. elif value[0]=='[' and value[-1] ==']' and regs.has_key(value[1:-1].upper()):
  784. expression[ndx] = value.upper()
  785. else:
  786. try:
  787. value = int(value, 16)
  788. expression[ndx] = value
  789. except ValueError:
  790. imm.log("Wrong Argument: %s" % value)
  791. return "Wrong Argument, Hook not setted"
  792.  
  793. imm.log("Hooking on expression: '%s'" % str(expression) )
  794.  
  795. hook = HookAndInform( expression, discover, nchunks = nchunks, heap = heap )
  796. hook.add("hook_inform_0x%08x" % address, address)
  797. return "Hooked on 0x%08x" % address
  798.  
  799.  
  800.  
  801. #!/usr/bin/env python
  802.  
  803. """
  804. (c) Immunity, Inc. 2004-2007
  805.  
  806. U{Immunity Inc.<http://www.immunityinc.com>}
  807. """
  808.  
  809. import immlib
  810. from libheap import *
  811. import getopt, string
  812. import immutils
  813.  
  814. DESC = "Compare memory with a file (file been a dump from prettyhexprint)"
  815. NAME = "cmpmemp"
  816.  
  817. def usage(imm):
  818. imm.log("!%s -a ADDR -f FILE_PATH" % NAME)
  819. imm.log("%s" % DESC)
  820.  
  821. def main(args):
  822. imm = immlib.Debugger()
  823. address = 0x0
  824. f_name = None
  825. try:
  826. opts, argo = getopt.getopt(args, "a:f:")
  827. except getopt.GetoptError:
  828. return "Usage: !cmpmem -a ADDRESS -f FILETOCMP" % str(args)
  829.  
  830. for o,a in opts:
  831. if o == "-a":
  832. try:
  833. address = int(a, 16)
  834. except ValueError, msg:
  835. return "Invalid heap address: %s" % a
  836. elif o == "-f":
  837. f_name = a
  838.  
  839. if f_name and address:
  840. lines = open(f_name).readlines()
  841. fmem = []
  842. for line in lines:
  843. line = line.strip().split(" ")
  844. for number in line:
  845. try:
  846. fmem.append( chr( int(number, 16) ) )
  847. except ValueError:
  848. continue
  849. fmem = fmem
  850. mem = imm.readMemory(address, len(fmem) )
  851. for a in range(0, len(fmem)):
  852. try:
  853. if fmem[a] != mem[a]:
  854. imm.log("Unmatched at offset: %d" % a)
  855. imm.log(" File: %s" % immutils.prettyhexprint( string.joinfields(fmem[ a: a + 8 ], "") ) )
  856. imm.log(" Mem : %s" % immutils.prettyhexprint( mem[ a: a + 8 ] ) )
  857. return "Unmatched: Check log window for the dump"
  858. except IndexError:
  859. log_str = "Unmatch: Different string sizes= File: %d Memory: %d" % (len(fmem), len(mem))
  860. imm.log("%s" % log_str)
  861. return log_str
  862.  
  863. imm.log("Match!")
  864. return "Match!"
  865.  
  866. return "No match"
  867. """pycmd example"""
  868.  
  869. DESC="""Find a exported function on the loaded dll"""
  870.  
  871. import immlib
  872. def usage(imm):
  873. imm.log("!dependencies Find an exported function on the loaded dll")
  874. imm.log("!dependencies module.function")
  875. imm.log("ex: !dependencies rpcrt4.rpcserveruseprotseqw")
  876.  
  877. def main(args):
  878. imm=immlib.Debugger()
  879. if len(args) !=1:
  880. usage(imm)
  881. return "Error: Wrong arguments"
  882.  
  883. result = imm.findDependecies( [ args[0] ] )
  884. ret = 0
  885. for modname in result.keys():
  886. for mod in result[modname]:
  887. imm.log("Found: %20s on %s" % (modname, mod.name), address = mod.address)
  888. ret +=1
  889. return "Found %d dependencies" % retimport immlib, immutils
  890.  
  891. DESC = "Looks for mapped address that can be 'transformed' into opcodes"
  892.  
  893. def str2int24_swapped( value ):
  894. return istr2int( value + "\x00" )
  895.  
  896. def usage(imm):
  897. imm.log("!duality Looks for mapped address that can be 'transformed' into opcodes")
  898. imm.log("!duality <asm code>")
  899.  
  900.  
  901. def main(args):
  902. imm = immlib.Debugger()
  903. found = 0
  904. searchf = {1:ord, 2: immutils.str2int16_swapped,\
  905. 3:str2int24_swapped}
  906. searchm = {1:0xff, 2:0xffff, 3: 0xffffff}
  907.  
  908. code = imm.assemble( " ".join(args) )
  909. mask = len(code)
  910. currentmask = searchm[mask]
  911.  
  912. try:
  913. what = searchf[ mask ]( code )
  914. except KeyError:
  915. return "Error, Code too big"
  916.  
  917. imm.log("What: 0x%08x -> %s" % (what, " ".join(args)) )
  918. imm.getMemoryPages()
  919.  
  920. for a in imm.MemoryPages.keys():
  921.  
  922. mem = imm.MemoryPages[a]
  923. size = mem.getSize()
  924. start = mem.getBaseAddress()
  925. end = start + size
  926.  
  927. ouraddr = ( start & ~currentmask) | what
  928.  
  929. if ouraddr > start and ouraddr < end:
  930. imm.log("Found: 0x%08x %s" % (ouraddr, mem.getSection()), address = ouraddr)
  931. found+=1
  932. else:
  933. ouraddr+= currentmask+1
  934. if ouraddr > start and ouraddr < end:
  935. imm.log("Found: 0x%08x (%s)" % ( ouraddr, mem.getSection() ), address = ouraddr)
  936. found+=1
  937. return "Addresses founded: %d (Check the Log Window)" % foundimport immlib
  938. import immutils
  939.  
  940. NAME = "findantidep"
  941. DESC="""Find address to bypass software DEP"""
  942.  
  943. def usage(imm):
  944. imm.log("!%s" % NAME)
  945. imm.log("%s" % DESC)
  946.  
  947. def tAddr(addr):
  948. buf = immutils.int2str32_swapped(addr)
  949. return "\\x%02x\\x%02x\\x%02x\\x%02x" % ( ord(buf[0]) , ord(buf[1]), ord(buf[2]), ord(buf[3]) )
  950.  
  951. def main(args):
  952. imm=immlib.Debugger()
  953. addylist = []
  954. mod = imm.getModule("ntdll.dll")
  955. if not mod:
  956. return "Error: Ntdll.dll not found!"
  957.  
  958. # Finding the first ADDRESS
  959. ret = imm.searchCommands("MOV AL,1\nRET")
  960. if not ret:
  961. return "Error: Sorry, the first addy cannot be found"
  962. for a in ret:
  963. addylist.append( "0x%08x: %s" % (a[0], a[2]) )
  964. ret = imm.comboBox("Please, choose the First Address [sets AL to 1]", addylist)
  965. firstaddy = int(ret[0:10], 16)
  966. imm.log("First Address: 0x%08x" % firstaddy, address = firstaddy)
  967.  
  968. # Finding the Second ADDRESS
  969. ret = imm.searchCommandsOnModule(mod.getBase(), "CMP AL,0x1\n PUSH 0x2\n POP ESI\n" )
  970. if not ret:
  971. return "Error: Sorry, the second addy cannot be found"
  972. secondaddy = ret[0][0]
  973. imm.log( "Second Address %x" % secondaddy , address= secondaddy)
  974.  
  975. # Finding the Third ADDRESS
  976. ret = imm.inputBox("Insert the Asm code to search for")
  977. ret = imm.searchCommands(ret)
  978. if not ret:
  979. return "Error: Sorry, the third address cannot be found"
  980. addylist = []
  981. for a in ret:
  982. addylist.append( "0x%08x: %s" % (a[0], a[2]) )
  983. ret = imm.comboBox("Please, choose the Third return Address [jumps to shellcode]", addylist)
  984. thirdaddy = int(ret[0:10], 16)
  985. imm.log( "Third Address: 0x%08x" % thirdaddy, thirdaddy )
  986. imm.log( 'stack = "%s\\xff\\xff\\xff\\xff%s\\xff\\xff\\xff\\xff" + "A" * 0x54 + "%s" + shellcode ' %\
  987. ( tAddr(firstaddy), tAddr(secondaddy), tAddr(thirdaddy) ) )
  988.  
  989. import immlib
  990. import immutils
  991. import libdatatype
  992.  
  993. NAME = "finddatatype"
  994.  
  995. def usage(imm):
  996. imm.log("!%s" % NAME)
  997. imm.log("!%s ADDRESS SIZE" % NAME)
  998. imm.log("Attempts to find the type of the data spanning")
  999. imm.log("ADDRESS to ADDRESS + SIZE")
  1000.  
  1001. return "Usage: !%s ADDRESS SIZE" % NAME
  1002.  
  1003. def main(args):
  1004. imm = immlib.Debugger()
  1005. if not args:
  1006. return usage( imm )
  1007. if len( args ) != 2:
  1008. return usage( imm )
  1009.  
  1010. addr = int(args[0], 16)
  1011. size = int(args[1], 16)
  1012.  
  1013. dt = libdatatype.DataTypes(imm)
  1014. mem = imm.readMemory( addr, size )
  1015. if not mem:
  1016. return "Error: Couldn't read anything at address: 0x%08x" % addr
  1017.  
  1018. ret = dt.Discover( mem, addr, what = 'all' )
  1019. imm.log( "Found: %d data types" % len(ret) )
  1020.  
  1021. for obj in ret:
  1022. t = "obj: %d" % obj.size
  1023. if obj.data:
  1024. msg = obj.Print()
  1025. imm.log( "obj: %s: %s %d" % (obj.name, msg, obj.getSize() ), address = obj.address)
  1026.  
  1027. return "Found: %d data types" % len(ret)
  1028. """
  1029. (c) Immunity, Inc. 2004-2008
  1030.  
  1031.  
  1032. U{Immunity Inc.<http://www.immunityinc.com>}
  1033.  
  1034. findloop
  1035.  
  1036. """
  1037.  
  1038.  
  1039. from immlib import *
  1040. from immutils import *
  1041. import getopt
  1042.  
  1043. DESC=""" Find natural loops given a function start address """
  1044.  
  1045. def usage(imm):
  1046. imm.log("!findloop -a <address>")
  1047. imm.log("-a (function start address)")
  1048. imm.log("-h This help")
  1049.  
  1050. def main(args):
  1051. imm = Debugger()
  1052. try:
  1053. opts,argo = getopt.getopt(args, "a:")
  1054. except:
  1055. return usage(imm)
  1056. for o,a in opts:
  1057. if o == "-a":
  1058. loops = imm.findLoops(int(a,16))
  1059. for loop in loops:
  1060. imm.log("LOOP! from:0x%08x, to:0x%08x"%(loop[0],loop[1]),loop[0])
  1061.  
  1062. func = imm.getFunction(int(a,16))
  1063. bbs = func.getBasicBlocks()
  1064.  
  1065. #find first and last node
  1066. first = 0xffffffff
  1067. last = 0
  1068. for node in loop[2]:
  1069. if node < first: first = node
  1070. if node > last: last = node
  1071.  
  1072. #mark loop nodes, but NOT change anything if there's any kind of comment
  1073. for node in loop[2]:
  1074. imm.log(" Loop node:0x%08x"%node,node)
  1075. for bb in bbs:
  1076. if bb.getStart() == node:
  1077. instrs = bb.getInstructions(imm)
  1078. for op in instrs:
  1079. if not imm.getComment(op.getAddress()) and op.getAddress() != node:
  1080. if node == last and op.getAddress() == instrs[-1].getAddress():
  1081. #last instruction of last node
  1082. imm.setComment(op.getAddress(), "/")
  1083. else:
  1084. imm.setComment(op.getAddress(), "|")
  1085.  
  1086. if not imm.getComment(node):
  1087. if node == first:
  1088. imm.setComment(node, "\ Loop 0x%08X Node"%(loop[0]))
  1089. else:
  1090. imm.setComment(node, "| Loop 0x%08X Node"%(loop[0]))
  1091.  
  1092. return "Done!"
  1093. if o =="-h":
  1094. return usage(imm)
  1095. #!/usr/bin/env python
  1096.  
  1097. """
  1098. (c) Immunity, Inc. 2004-2007
  1099.  
  1100.  
  1101. U{Immunity Inc.<http://www.immunityinc.com>}
  1102.  
  1103. TODO:
  1104. Fix the Offset in order to actually point to the address where the ID was found. (This is just a really beta version of this script)
  1105. """
  1106.  
  1107.  
  1108. __VERSION__ = '1.0'
  1109.  
  1110. import immlib
  1111. import getopt
  1112. import struct
  1113.  
  1114. DESC = """Find a Packer/Cryptor on a Module (Note: It might take some times due to the amount of signature on our db)"""
  1115.  
  1116. def usage(imm):
  1117. imm.log("!findpacker [-f] -m filename/module Get the RPC information of a loaded dll or for all loaded DLL's",focus=1)
  1118. imm.log(" -m filename/module File or Module to search for")
  1119. imm.log(" -f When set, it look in the file instead of the loaded module")
  1120. imm.log(" ex: !findpacker -m notepad")
  1121. imm.log("NOTE: It might take some times due to the amount of signature on our db")
  1122.  
  1123. def main(args):
  1124. imm = immlib.Debugger()
  1125. if not args:
  1126. usage(imm)
  1127. return "No args"
  1128. try:
  1129. opts, argo = getopt.getopt(args, "m:f")
  1130. except getopt.GetoptError:
  1131. usage(imm)
  1132. return "Bad heap argument %s" % args[0]
  1133.  
  1134. module = None
  1135. OnMemory = 1
  1136.  
  1137. for o,a in opts:
  1138. if o == "-m":
  1139. module = a
  1140. elif o == '-f':
  1141. OnMemory = 0
  1142.  
  1143. if not module:
  1144. usage(imm)
  1145. return "No module provided, see the Log Window for details of usage"
  1146.  
  1147. try:
  1148. ret = imm.findPacker( module, OnMemory = OnMemory)
  1149. except Exception, msg:
  1150. return "Error: %s" % msg
  1151.  
  1152. if not ret:
  1153. return "No Packer found"
  1154.  
  1155. for (addr, name) in ret:
  1156. imm.log("Packer found!: %s at 0x%08x" % (name, addr), address = addr)
  1157. return "Packers found on %s: %d" % (module, len(ret))
  1158. #!/usr/bin/env python
  1159.  
  1160. """
  1161. (c) Immunity, Inc. 2004-2007
  1162.  
  1163.  
  1164. U{Immunity Inc.<http://www.immunityinc.com>}
  1165.  
  1166. """
  1167.  
  1168.  
  1169.  
  1170. DESC="""Analize the heap pattern of a executed function"""
  1171.  
  1172. import immlib
  1173. import immutils
  1174. import struct
  1175. from immlib import LogBpHook
  1176. from libheap import *
  1177. import libdatatype
  1178. import getopt
  1179.  
  1180. # RtlAllocateHeap Hook class
  1181. ALLOCLABEL = "Alloc Hook"
  1182. class RtlAllocateHeapHook(LogBpHook):
  1183. def __init__(self, address):
  1184. LogBpHook.__init__(self)
  1185. #self.Heap = heap
  1186. self.hookaddr = address
  1187. self.Called = []
  1188. def run(self,regs):
  1189. """This will be executed when hooktype happens"""
  1190. imm = immlib.Debugger()
  1191. readaddr=""
  1192. size=""
  1193.  
  1194. res=imm.readMemory( regs['EBP'] + 8, 0xc)
  1195. if len(res) != 0xc or not res:
  1196. imm.log("RtlAllocateHeap: ESP seems to broken, unable to get args")
  1197. return 0x0
  1198. (heap, flags, size) = struct.unpack("LLL", res)
  1199. #imm.log("RtlAllocateHeap(0x%08x, 0x%08x, 0x%08x)" % (heap, flags, size))
  1200. called = imm.getKnowledge( "heap_%08x" % self.hookaddr )
  1201. if not called:
  1202. called = []
  1203. try:
  1204. callstack = imm.readLong( regs['EBP'] + 4)
  1205. except Exception:
  1206. callstack = 0x0
  1207.  
  1208. called.append( (1, callstack, heap, flags, size, regs['EAX'] ) )
  1209. imm.addKnowledge("heap_%08x" % self.hookaddr, called, force_add = 0x1)
  1210.  
  1211. # RtlFreeHeap Hook class
  1212. FREELABEL = "Free Hook"
  1213. class RtlFreeHeapHook(LogBpHook):
  1214. def __init__(self, address):
  1215. LogBpHook.__init__(self)
  1216. self.hookaddr = address
  1217.  
  1218. def run(self,regs):
  1219. """This will be executed when hooktype happens"""
  1220. imm = immlib.Debugger()
  1221.  
  1222. readaddr=""
  1223. size=""
  1224.  
  1225. res=imm.readMemory( regs['ESP'] + 4, 0xc)
  1226. if len(res) != 0xc:
  1227. imm.log("RtlFreeHeap: ESP seems to broken, unable to get args")
  1228. return 0x0
  1229. (heap, flags, size) = struct.unpack("LLL", res)
  1230. called = imm.getKnowledge( "heap_%08x" % self.hookaddr )
  1231.  
  1232. if not called:
  1233. called = []
  1234. try:
  1235. callstack = imm.readLong( regs['EBP'] + 4)
  1236. except Exception:
  1237. callstack = 0x0
  1238.  
  1239. called.append( (0, callstack, heap, flags, size) )
  1240. imm.addKnowledge("heap_%08x" % self.hookaddr, called, force_add = 0x1)
  1241.  
  1242. class EndHook(LogBpHook):
  1243. def __init__( self, retaddr ):
  1244. LogBpHook.__init__(self)
  1245. self.retaddr = retaddr
  1246.  
  1247. def run(self, regs):
  1248. imm = immlib.Debugger()
  1249.  
  1250. called = imm.getKnowledge("heap_%08x" % self.retaddr)
  1251. (ahook, fhook) = imm.getKnowledge("end_%08x" % self.retaddr)
  1252. ahook.UnHook()
  1253. fhook.UnHook()
  1254. win = imm.createTable("Function Sniffing", ["Address", "Data"] )
  1255. memleak = {}
  1256. freelist = {}
  1257. win.Log("Dumping the Heap Flow")
  1258. if called:
  1259. for res in called:
  1260. if res[0] == 1:
  1261. type, callstack, heap, flag, size, ret = res
  1262. memleak[ ret ] = (callstack, heap, flag, size, ret)
  1263. win.Log("Alloc(0x%08x, 0x%08x, 0x%08x) -> 0x%08x" %\
  1264. ( heap, flag, size, ret ), address = callstack )
  1265. elif res[0] == 0:
  1266. type, callstack, heap, flag, size = res
  1267. if memleak.has_key( size):
  1268. del memleak[ size ]
  1269. else:
  1270. freelist[ size ] = (callstack, heap, flag, size)
  1271.  
  1272. win.Log("Free (0x%08x, 0x%08x, 0x%08x)" %\
  1273. ( heap, flag, size ), address = callstack )
  1274.  
  1275. win.Log("Chunk freed but not allocated on this heap flow")
  1276. pheap = PHeap( imm )
  1277. dt = libdatatype.DataTypes(imm)
  1278.  
  1279. for a in freelist.keys():
  1280. (callstack, heap, flag, base) = freelist[a]
  1281. win.Log("Free (0x%08x, 0x%08x, 0x%08x)" %\
  1282. ( heap, flag, base ), address = callstack )
  1283.  
  1284.  
  1285. win.Log("Memleak detected")
  1286. for a in memleak.keys():
  1287. (callstack, heap, flag, size, ret) = memleak[a]
  1288. win.Log("Alloc(0x%08x, 0x%08x, 0x%08x) -> 0x%08x" %\
  1289. ( heap, flag, size, ret ), address = callstack )
  1290.  
  1291. chk = pheap.getChunks( ret - 8, 1)[0]
  1292. chk.printchunk( uselog = win.Log, dt = dt )
  1293. imm.log("Funsniff finished, check the newly created window")
  1294. self.UnHook()
  1295.  
  1296. # Function Hook class
  1297. class FunctionHook(LogBpHook):
  1298. def __init__( self, allocaddr, freeaddr, continuos = False):
  1299. LogBpHook.__init__(self)
  1300. #self.threadid = threadid
  1301. self.allocaddr = allocaddr
  1302. self.freeaddr = freeaddr
  1303. self.continuos = continuos
  1304.  
  1305. def run(self, regs):
  1306. """This will be executed when hooktype happens"""
  1307. imm = immlib.Debugger()
  1308. # We will probably gonna need the threadid. Gather it through getEvent()
  1309. readaddr=""
  1310. size=""
  1311. retaddr = imm.readLong( regs['EBP'] + 4)
  1312. for a in regs:
  1313. imm.log("%s:%08x" % (a, regs[a]))
  1314.  
  1315. if not retaddr:
  1316. self.UnHook()
  1317. imm.log("Unhooking, wrong ESP")
  1318. return
  1319.  
  1320.  
  1321. endhook = EndHook( retaddr )
  1322. endhook.add("EndHook_%x" % retaddr, retaddr)
  1323.  
  1324. ahook = RtlAllocateHeapHook( retaddr)
  1325. ahook.add( "Alloc_%08x"% retaddr, self.allocaddr)
  1326.  
  1327. fhook = RtlFreeHeapHook( retaddr)
  1328. fhook.add( "Free_%08x" % retaddr, self.freeaddr)
  1329. imm.addKnowledge("end_%08x" % retaddr, (ahook, fhook) )
  1330.  
  1331. imm.log("o Sniffing the selected Function", address = regs['EIP'])
  1332. if not self.continuos:
  1333. self.UnHook()
  1334.  
  1335.  
  1336. def getRet(imm, allocaddr, max_opcodes = 500):
  1337. addr = allocaddr
  1338. for a in range(0, max_opcodes):
  1339. op = imm.disasmForward( addr )
  1340. if op.isRet():
  1341. if op.getImmConst() == 0xc:
  1342. op = imm.disasmBackward( addr, 3)
  1343. return op.getAddress()
  1344. addr = op.getAddress()
  1345.  
  1346. return 0x0
  1347.  
  1348. def usage(imm):
  1349. imm.log( "!funsniff -a ADDRESS (-c) Analize the heap pattern of a executed function" )
  1350. imm.log( " -a ADDRESS Address of Function to fingerprint")
  1351. imm.log( " -c Continuos")
  1352.  
  1353. def main(args):
  1354. imm = immlib.Debugger()
  1355.  
  1356. address = 0x0
  1357. continuos = False
  1358. if not args:
  1359. usage(imm)
  1360. return "Wrong Arguments (Check usage on the Log Window)"
  1361.  
  1362. try:
  1363. opts, argo = getopt.getopt(args, "a:c")
  1364. except getopt.GetoptError:
  1365. return "Wrong Arguments (Check usage on the Log Window)"
  1366.  
  1367. for o,a in opts:
  1368. if o == '-a':
  1369. try:
  1370. address = int( a, 16 )
  1371. except ValueError:
  1372. usage(imm)
  1373. return "Wrong Address (%s) % " % a
  1374. elif o == '-c':
  1375. continuos = True
  1376.  
  1377. if not address:
  1378. return "Wrong Arguments (Check usage on the Log Window)"
  1379.  
  1380. allocaddr = imm.getAddress("ntdll.RtlAllocateHeap" )
  1381. freeaddr = imm.getAddress("ntdll.RtlFreeHeap" )
  1382. allocaddr = getRet(imm, allocaddr, 800)
  1383.  
  1384. if not allocaddr or not freeaddr:
  1385. imm.log("Error, couldn't find the address of allocateHeap or freeHeap")
  1386. return "Error resolving Address"
  1387.  
  1388. imm.log("Func Sniffing starting")
  1389. imm.log("o Setting the first hook")
  1390. hook = FunctionHook( allocaddr, freeaddr )
  1391. hook.add( "Func_%08x" % address, address)
  1392. return "Hook set"
  1393.  
  1394. import immlib
  1395. from libevent import ExceptionEvent
  1396.  
  1397. DESC = "Get a log of current debugevent"
  1398. NAME = "getevent"
  1399.  
  1400. def usage(imm):
  1401. imm.log("!%s" % NAME)
  1402. imm.log("%s" % DESC)
  1403.  
  1404. def main(args):
  1405. imm=immlib.Debugger()
  1406. evento = imm.getEvent()
  1407. if evento:
  1408. if isinstance(evento, ExceptionEvent):
  1409. for a in evento.Exception:
  1410. imm.log("Exception: %s (0x%08x)" % (a.getType(), a.ExceptionCode), focus = 1)
  1411. imm.log("Exception address: 0x%08x" % a.ExceptionAddress)
  1412. imm.log("Exception num param: %d" % a.NumberParameters)
  1413. for value in a.ExceptionInformation:
  1414. imm.log(hex(value))
  1415. else:
  1416. imm.log("Last event type: 0x%08x (%s) " % (evento.dwDebugEventCode, str(evento) ) )
  1417. return "Works"
  1418. else:
  1419. return "Cannot handle this exception"
  1420. #!/usr/bin/env python
  1421.  
  1422. """
  1423. (c) Immunity, Inc. 2004-2007
  1424.  
  1425.  
  1426. U{Immunity Inc.<http://www.immunityinc.com>}
  1427.  
  1428. Additional feature of iterating through all DLL's added by Justin Seitz <jms@bughunter.ca>
  1429.  
  1430. """
  1431.  
  1432. import immlib
  1433. import getopt
  1434. import struct
  1435.  
  1436. DESC = """Get the RPC information of a loaded dll"""
  1437.  
  1438. def usage(imm):
  1439. imm.log("!getrpc filename|all Get the RPC information of a loaded dll or for all loaded DLL's",focus=1)
  1440.  
  1441. def get_rpc_info(imm,mod,module_name):
  1442.  
  1443. codeaddr = mod.getBase()
  1444. size = mod.getSize()
  1445. mem = imm.readMemory(codeaddr, size)
  1446. ndx = 0
  1447. offset = ndx
  1448. Found = 0
  1449. while 1:
  1450. offset = mem[ndx:].find("\x04\x5d\x88\x8a")
  1451. if offset == -1:
  1452. break
  1453. offset -= 0x18
  1454.  
  1455. try:
  1456. length = struct.unpack("L", mem[ndx+offset : ndx+offset+4])[0]
  1457. if length == 0x44:
  1458. Found += 1
  1459. addr = codeaddr + ndx + offset
  1460.  
  1461. imm.log("RPC SERVER INTERFACE found at: 0x%08x" % addr, address = addr)
  1462. hu= struct.unpack("LHH", mem[ndx+offset+4 : ndx+offset+0xc])
  1463. hu2 = struct.unpack("!HLH", mem[ndx+offset+0xc : ndx+offset+0x14])
  1464. uuid = "%08x-%04x-%04x-%04x-%08x%04x" % (hu[0], hu[1], hu[2], hu2[0], hu2[1], hu2[2])
  1465. major,minor = struct.unpack("HH", mem[ndx+offset+0x14 : ndx+offset+0x18])
  1466. imm.log("RPC UUID: %s (v%d.%d)" % (uuid, major, minor))
  1467. imm.gotodisasmWindow(addr)
  1468. imm.setComment(offset + codeaddr, "Length")
  1469. imm.setComment(offset + codeaddr+4, "Interface UUID: %s (v%d.%d)" % (uuid, major, minor))
  1470. imm.setComment(offset + codeaddr+0x18, "Transfer syntax")
  1471. imm.setComment(offset + codeaddr+0x2c, "Dispatch Table")
  1472. imm.setComment(offset + codeaddr+0x30, "RpcProtseqEndpointCount")
  1473. imm.setComment(offset + codeaddr+0x34, "RpcProtseqEndpoint")
  1474. imm.setComment(offset + codeaddr+0x38, "Default Manager")
  1475. imm.setComment(offset + codeaddr+0x3c, "Interpreter Info")
  1476. imm.setComment(offset + codeaddr+0x40, "Flags")
  1477. interpreter_info = struct.unpack("L", mem[ndx+offset+0x3c : ndx+offset+0x3c+4] )[0]
  1478. function_list_addr = imm.readLong( interpreter_info + 4)
  1479. dispatch_table = struct.unpack("L", mem[ndx+offset+0x2c : ndx+offset+0x2c+4] )[0]
  1480. number = imm.readLong( dispatch_table )
  1481. function_ptr = imm.readLong( dispatch_table + 4 )
  1482. for a in range(0, number):
  1483. func = imm.readLong(function_list_addr+a*4)
  1484. imm.log("Function[%d]: 0x%08x" % (a , func), address = func, focus=1)
  1485. for a in range(0, number):
  1486. func = imm.readLong(function_ptr+a*4)
  1487. imm.log("Function pointer [%d]: 0x%08x" % (a , func), address = function_ptr+a*4)
  1488.  
  1489. except Exception, msg:
  1490. pass
  1491. ndx += offset+0x20
  1492. del mem
  1493. if Found:
  1494. imm.log("Module: %s END ===============================================================================" % module_name)
  1495. return "Found %d interfaces on %s" % (Found, module_name)
  1496. else:
  1497. return "No interface found on %s" % module_name
  1498.  
  1499.  
  1500. def main(args):
  1501. imm = immlib.Debugger()
  1502. module_exists = False
  1503. if not args:
  1504. usage(imm)
  1505. return "Incorrect number of arguments (No args)"
  1506. if len(args) != 1:
  1507. usage(imm)
  1508. return "Incorrect number of arguments"
  1509.  
  1510.  
  1511.  
  1512. if args[0].lower() == "all":
  1513. mod_list = imm.getAllModules()
  1514. for mod in mod_list.iteritems():
  1515. module = imm.getModule(mod[0])
  1516. sys_dll = module.getIssystemdll()
  1517.  
  1518. if sys_dll == 0:
  1519. imm.setStatusBar("Fetching RPC information for: %s" % mod[0])
  1520. get_rpc_info(imm,module,mod[0])
  1521. module_exists = True
  1522. else:
  1523.  
  1524. mod = imm.getModule(args[0])
  1525.  
  1526. if mod:
  1527. module_exists = True
  1528. imm.setStatusBar("Fetching RPC information for: %s" % args[0])
  1529. get_rpc_info(imm,mod,args[0])
  1530.  
  1531.  
  1532. if module_exists == False:
  1533. return "Module not found"
  1534. else:
  1535. return "Module information outputted, check the Log."
  1536. #!/usr/bin/env python
  1537.  
  1538. """
  1539. (c) Immunity, Inc. 2004-2007
  1540.  
  1541.  
  1542. U{Immunity Inc.<http://www.immunityinc.com>}
  1543.  
  1544. """
  1545.  
  1546. DESC="""gflags"""
  1547.  
  1548. import getopt
  1549. import immlib
  1550. import libregistry
  1551.  
  1552. def usage(imm):
  1553. imm.log("!gflags -[a|d|c] -m module Enable and Disable Global Flags", focus=1)
  1554. imm.log("-m module Module to set the global flags")
  1555. imm.log("-a tag Set a Flag")
  1556. imm.log("-d tag Unset a Flag")
  1557. imm.log("-c Clear Flags")
  1558. imm.log("tags: ")
  1559. for tag in libregistry.GFlagsTags:
  1560. r = libregistry.GFlagsRef[tag]
  1561. imm.log( " %s - %s" % ( tag, r[0] ) )
  1562.  
  1563. def main(args):
  1564. imm = immlib.Debugger()
  1565.  
  1566. try:
  1567. opts, argo = getopt.getopt(args, "m:a:d:c", ["module=", "add=", "delete=", "clear"])
  1568. except getopt.GetoptError:
  1569. usage(imm)
  1570. return "Wrong Argument (Check Log Window)"
  1571.  
  1572. add_f = []
  1573. delete_f = []
  1574. clear_f = False
  1575. module = ""
  1576. for o,a in opts:
  1577. if o in ('-a', "--add"):
  1578. add_f.append( a )
  1579. elif o in ('-d', "--delete"):
  1580. delete_f.append( a )
  1581. elif o in ('-c', "--clear"):
  1582. clear_f = True
  1583. elif o in ('-m', "--module"):
  1584. module = a
  1585.  
  1586. gf = libregistry.GFlags( module)
  1587.  
  1588. if not clear_f:
  1589. if add_f:
  1590. curr = 0
  1591. for tag in add_f:
  1592. try:
  1593. r = gf.GetReferencebyName( tag )
  1594. except Exception, msg:
  1595. usage(imm)
  1596. return "Error: %s" % str(msg)
  1597. curr = curr | r[1]
  1598. gf.Set( curr )
  1599. imm.log("Global Flags added")
  1600. if delete_f:
  1601. curr = 0
  1602. for tag in delete_f:
  1603. try:
  1604. r = gf.GetReferencebyName( tag )
  1605. except Exception, msg:
  1606. usage(imm)
  1607. return "Error: %s" % str(msg)
  1608. curr = curr | r[1]
  1609. gf.UnSet( curr )
  1610. imm.log("Global Flags Deleted")
  1611.  
  1612. else:
  1613. gf.Clear()
  1614. return "Global Flag cleared"
  1615.  
  1616. if not clear_f:
  1617. try:
  1618. ret = gf.Print()
  1619. except Exception:
  1620. return "GlobalFlag not found"
  1621. if module:
  1622. txt = "Current Flags for module %s" % module
  1623. else:
  1624. txt = "Current Global Flags:"
  1625. imm.log(txt)
  1626. for (tag, r) in ret:
  1627. imm.log(" %s: %s" % (tag, r[0]))
  1628. return "Done"
  1629.  
  1630. #!/usr/bin/env python
  1631.  
  1632. """
  1633. (c) Immunity, Inc. 2004-2007
  1634.  
  1635.  
  1636. U{Immunity Inc.<http://www.immunityinc.com>}
  1637. """
  1638.  
  1639. import immlib
  1640. import getopt
  1641. from libheap import *
  1642. import libdatatype
  1643.  
  1644. DESC= "Immunity Heap Dump"
  1645. def usage(imm):
  1646. imm.log("!heap Heap dump of currents heaps")
  1647. imm.log("!heap [-h HEAP_ADDR] [-s] [-r] [-f] [-c]")
  1648. imm.log(" -h HEAPADDR Set the heap address to inspect")
  1649. imm.log(" -a CHUNKADDR Set the begging of a chunk to partially inspect")
  1650. imm.log(" -s Save heap's state")
  1651. imm.log(" -r Dump heap using restored value (in case of a broken chunk)")
  1652. imm.log(" -f Inspect the FreeList only")
  1653. imm.log(" -c Inspect the chunks only")
  1654. imm.log(" -k Shows the first 16 bytes of a chunk")
  1655. imm.log(" -d Inspect data on Chunks")
  1656. imm.log(" -q Dont show FreeList information")
  1657. imm.log(" -l Inspect all the Low Fragmentation Information")
  1658. imm.log(" -t PACK_SIZE Filter by Packed Size ( Real Size / 8 )")
  1659. imm.log(" -u Inspect LFH UserBlocks")
  1660. imm.log(" -z Inspect LFH Chunks", focus = 1 )
  1661.  
  1662. def main(args):
  1663. imm = immlib.Debugger()
  1664. window = None
  1665.  
  1666. if not args:
  1667. imm.log("### Immunity's Heapdump ###")
  1668. for hndx in imm.getHeapsAddress():
  1669. imm.log("Heap: 0x%08x" % hndx, address = hndx, focus = 1)
  1670. return "Heap command successful"
  1671.  
  1672. # options:
  1673. # -h HEAP
  1674. # -s (save heap's state)
  1675. # -r (restore in case of broken heap)
  1676. # -f dump just the freelist
  1677. # -c dump just chunks
  1678. # -d discover
  1679. try:
  1680. opts, argo = getopt.getopt(args, "h:lsurfcqknzda:t:")
  1681. except getopt.GetoptError:
  1682. #imm.setStatusBar("Bad heap argument %s" % args[0])
  1683. usage(imm)
  1684. return "Bad heap argument %s" % args[0]
  1685. heap = 0x0
  1686. save = False
  1687. restore = False
  1688. freelist = False
  1689. chunksflags = False
  1690. chunkdisplay = 0
  1691. opennewwindow = False
  1692. discover = None
  1693. chunkaddress = None
  1694. LFH = False
  1695. userblock = False
  1696. lfhchunk = False
  1697. showf = True
  1698. fsize = -1
  1699.  
  1700. for o,a in opts:
  1701. if o == "-h":
  1702. try:
  1703. heap = int(a, 16)
  1704. except ValueError, msg:
  1705. return "Invalid heap address: %s" % a
  1706. if o == "-a":
  1707. try:
  1708. chunkaddress = int(a, 16)
  1709. except ValueError, msg:
  1710. return "Invalid chunk address: %s" % a
  1711. if o == "-t":
  1712. try:
  1713. fsize = int(a, 16)
  1714. except ValueError, msg:
  1715. return "Incorrect filter size : %s" % a
  1716.  
  1717. elif o == "-s":
  1718. save = True
  1719. elif o == "-r":
  1720. restore = True
  1721. elif o == "-f":
  1722. freelist = True
  1723. elif o == "-c":
  1724. chunksflags = True
  1725. elif o == "-k":
  1726. chunkdisplay = SHOWCHUNK_FULL
  1727. elif o == "-n":
  1728. opennewwindow = True
  1729. elif o == "-d":
  1730. discover = libdatatype.DataTypes(imm)
  1731. elif o == '-l':
  1732. LFH = True
  1733. elif o == '-u':
  1734. userblock = True
  1735. elif o == '-z':
  1736. lfhchunk = True
  1737. elif o == '-q':
  1738. showf = False
  1739.  
  1740. if heap and ( heap in imm.getHeapsAddress() ):
  1741. tag = "heap_%08x" % heap
  1742.  
  1743. if not opennewwindow:
  1744. window = imm.getKnowledge(tag)
  1745. if window and not window.isValidHandle():
  1746. imm.forgetKnowledge(tag)
  1747. del window
  1748. window = None
  1749.  
  1750. if not window:
  1751. imm.log( "%s %s " % (str(type(tag)), str(type(heap))) )
  1752. window = imm.createTable("Heap dump 0x%08x" % heap, ["Address", "Chunks"] )
  1753. imm.addKnowledge(tag, window, force_add = 1)
  1754.  
  1755. # in case none of them are select, dump *
  1756. if showf and (not chunksflags and not freelist):
  1757. chunksflags = True
  1758. freelist = True
  1759.  
  1760. pheap = imm.getHeap( heap, restore )
  1761. if save:
  1762. imm.addKnowledge("saved_heap_%08x" % pheap.address , pheap, force_add = 1)
  1763.  
  1764. window.Log("### Immunity's Heapdump ###")
  1765. window.Log("Dumping heap: 0x%08x" % heap, address = heap, focus = 1 )
  1766. window.Log("Flags: 0x%08x Forceflags: 0x%08x" % (pheap.Flags, pheap.ForceFlags), address = heap)
  1767. window.Log("Total Free Size: 0x%08x VirtualMemoryThreshold: 0x%08x" % (pheap.TotalFreeSize, pheap.VirtualMemoryThreshold), address = heap)
  1768. if showf:
  1769. for a in range(0, len(pheap.Segments)):
  1770. if not pheap.Segments[a]:
  1771. break
  1772. window.Log("Segment[%d]: 0x%08x" % (a, pheap.Segments[a].BaseAddress) )
  1773.  
  1774. if freelist:
  1775. if pheap.HeapCache:
  1776. pheap.printHeapCache(uselog = window.Log)
  1777. if hasattr(pheap, 'FreeListInUseLong'):
  1778. pheap.printFreeListInUse(uselog = window.Log )
  1779.  
  1780. pheap.printFreeList( uselog = window.Log)
  1781. if hasattr(pheap, "Lookaside"):
  1782. if pheap.Lookaside:
  1783. pheap.printLookaside( uselog = window.Log )
  1784.  
  1785. if chunksflags:
  1786. for chunk in pheap.chunks:
  1787. chunk.printchunk(uselog = window.Log, option = chunkdisplay, dt = discover)
  1788. if userblock or lfhchunk:
  1789. LFH = True
  1790.  
  1791. if LFH and pheap.LFH:
  1792. if not userblock and not lfhchunk:
  1793. userblock = True
  1794. lfhchunk = True
  1795. window.Log("~" * 0x47)
  1796. if pheap.LFH.LocalData:
  1797. for seginfo in pheap.LFH.LocalData.SegmentInfo:
  1798. subseg_list = seginfo.SubSegment
  1799. for subseg in subseg_list:
  1800. if fsize == -1 or subseg.BlockSize == fsize:
  1801. if userblock:
  1802. window.Log("UserBlock size: 0x%04x %-8s: 0x%08x offset: %08x Depth: %x (0x%08x)" % (subseg.BlockSize, subseg.type, subseg.UserBlocks, subseg.Offset, subseg.Depth, subseg.Next), address = subseg.UserBlocks)
  1803. if lfhchunk:
  1804. for chk in subseg.chunks:
  1805. chk.printchunk(uselog = window.Log, option = chunkdisplay, dt = discover)
  1806.  
  1807. window.Log("=-" * 0x23 + "=")
  1808. return "Heap 0x%x dumped" % heap
  1809.  
  1810. elif chunkaddress:
  1811.  
  1812. tag = "chunks_%08x" % chunkaddress
  1813.  
  1814. if not opennewwindow:
  1815. window = imm.getKnowledge(tag)
  1816.  
  1817. if not window:
  1818. window = imm.createTable("Heap dump 0x%08x" % chunkaddress, ["Address", "Chunks"] )
  1819. imm.addKnowledge(tag, window, force_add = 1)
  1820.  
  1821. pheap = PHeap( imm )
  1822.  
  1823. window.Log("### Immunity's Heapdump ###")
  1824. window.Log("Dumping Chunks from address: 0x%08x" % chunkaddress, address = chunkaddress, focus = 1 )
  1825.  
  1826. for chunk in pheap.getChunks( chunkaddress ):
  1827. chunk.printchunk(uselog = window.Log, option = chunkdisplay, dt = discover)
  1828.  
  1829. window.Log("=-" * 0x23 + "=")
  1830. return "Heap 0x%x dumped" % heap
  1831. else:
  1832. imm.log("Error: A proper heap needs to be defined")
  1833. return "Error: A proper heap needs to be defined"
  1834. #!/usr/bin/env python
  1835.  
  1836. #-------------------------------------------------------------------------------
  1837. #
  1838. # By BoB -> Team PEiD
  1839. # http://www.PEiD.info/BobSoft/
  1840. # BobSoft@GMail.Com
  1841. #
  1842. #-------------------------------------------------------------------------------
  1843.  
  1844. import immlib
  1845. import getopt
  1846. import random
  1847. import ctypes
  1848.  
  1849. #-------------------------------------------------------------------------------
  1850.  
  1851. __VERSION__ = '1.00'
  1852. ProgName = 'HideDebug'
  1853. ProgVers = __VERSION__
  1854. DESC = "Patches lots of anti-debug protection .. (try \"!usage %s\" for details)" % ProgName.lower()
  1855.  
  1856. #-------------------------------------------------------------------------------
  1857.  
  1858. Docs = """
  1859.  
  1860. Loosely based on patch.py (c) Immunity inc .. :)
  1861.  
  1862. Patches:
  1863. o IsDebuggerPresent (With Poly-patch code, as too easy to detect Xor EAX, EAX)
  1864. o ZwQueryInformationProcess
  1865. o CheckRemoteDebuggerPresent
  1866. o PEB.IsDebugged
  1867. o PEB.ProcessHeap.Flag
  1868. o PEB.NtGlobalFlag
  1869. o PEB.Ldr 0xFEEEFEEE filling
  1870. o GetTickCount (With poly-patch code, as too easy to detect Mov EAX, xxxxxxxx)
  1871. o ZwQuerySystemInformation (Used by CreateToolHelp32Snapshot / Process32First / Process32Next and others)
  1872. o FindWindowA
  1873. o FindWindowW
  1874. o FindWindowExA
  1875. o FindWindowExW
  1876. o EnumWindows
  1877.  
  1878.  
  1879. Types:
  1880. o Anti-Debug Types:
  1881. IsDebuggerPresent
  1882. ZwQueryInformationProcess
  1883. CheckRemoteDebuggerPresent
  1884. PEB (All PEB patches are done)
  1885. GetTickCount
  1886. All_Debug - Applies ALL Debug detect patches ..
  1887.  
  1888. o Anti-Process-finding Types:
  1889. ZwQuerySystemInformation (All other process apis use this)
  1890. All_Process - Applies the debugger-process finding Api patch ..
  1891.  
  1892. o Anti-Window-finding Types:
  1893. FindWindowA
  1894. FindWindowW
  1895. FindWindowExA
  1896. FindWindowExW
  1897. EnumWindows
  1898. All_Window - Applies ALL debugger-window finding Api patches ..
  1899.  
  1900.  
  1901. <dodgy excuse>
  1902. Sorry for any weird code, I've only been using Python for 2 weeks .. :)
  1903. </dodgy excuse>
  1904.  
  1905.  
  1906. Description:
  1907. Most of the functions are patched to return Debugger Found = False ..
  1908. The PEB patches are to the various flags in PEB used by anti-debug ..
  1909. Patch for ZwQueryInformationProcess is if DebugPort is checked, returns not debugged ..
  1910. Patch for GetTickCount is to return same number everytime ..
  1911. Patch for ZwQuerySystemInformation is to replace all ImmunityDebugger.exe with SVCHost.EXE ..
  1912. Patch for Window finding apis call Api and if "ID" is classname then return not found ..
  1913.  
  1914.  
  1915. Maybe ToDo:
  1916. o Patch CreateThread ?
  1917.  
  1918. """
  1919.  
  1920.  
  1921. #-------------------------------------------------------------------------------
  1922. # Show usage ..
  1923.  
  1924. def usage(imm):
  1925. imm.log(" ")
  1926. imm.log("%s v%s By BoB -> Team PEiD" % (ProgName, ProgVers),focus=1, highlight=1)
  1927. imm.log("Description:")
  1928. imm.log(" Patches many different flags and apis used to detect debuggers ..")
  1929. imm.log(" Different combinations of patches will defeat most protections, ")
  1930. imm.log(" and some common anti-debug apis are patched with poly code ")
  1931. imm.log(" to avoid detection by packers like RL!Pack .. ")
  1932. imm.log(" All apis return usual valid data, the patches do not affect normal use .. ")
  1933. imm.log(" EG: FindWindowA('NotePad.EXE', Null) will work same if patched or not..")
  1934. imm.log(" ")
  1935. imm.log("Usage:")
  1936. imm.log(" !%s <Type>" % ProgName.lower())
  1937. imm.log(" ")
  1938. imm.log("Type can be ..")
  1939. imm.log(" Debugger-Detect Types:")
  1940. imm.log(" . IsDebuggerPresent - Patches the Kernel32 Api to return false ..")
  1941. imm.log(" . CheckRemoteDebuggerPresent - Patches the Kernel32 Api ..")
  1942. imm.log(" . ZwQueryInformationProcess - Patches the NtDll Api only for getting DebugPort ..")
  1943. imm.log(" . GetTickCount - Patches the Kernel32 Api to always return same value ..")
  1944. imm.log(" . Peb - Patches PEB.IsDebugged, PEB.ProcessHeap.Flag, PEB.NtGlobalFlag and fill bytes ..")
  1945. imm.log(" . All_Debug - Applies patches for all of the above .. ")
  1946. imm.log(" ")
  1947. imm.log(" Debugger-Detect by Process Types: ")
  1948. imm.log(" . ZwQuerySystemInformation - Patches the NtDll Api to remove ImmDbg from list ..")
  1949. imm.log(" . All_Process - Applies all process patches above .. ")
  1950. imm.log(" ")
  1951. imm.log(" Debugger-Detect by Window Types: (User32.DLL must be loaded)")
  1952. imm.log(" . FindWindowA - Reports false if process looks for ImmDbg win classname ..")
  1953. imm.log(" . FindWindowW - Reports false if process looks for ImmDbg win classname ..")
  1954. imm.log(" . FindWindowExA - Reports false if process looks for ImmDbg win classname ..")
  1955. imm.log(" . FindWindowExW - Reports false if process looks for ImmDbg win classname ..")
  1956. imm.log(" . EnumWindows - Own callback function calls user callback if not ImmDbg HWnd ..")
  1957. imm.log(" . All_Window - Applies all window patches above .. ")
  1958. imm.log(" ")
  1959. return "See log window (Alt-L) for usage .. "
  1960.  
  1961.  
  1962. #-------------------------------------------------------------------------------
  1963. # Misc functions ..
  1964. #-------------------------------------------------------------------------------
  1965.  
  1966. #-------------------------------------------------------------------------------
  1967. # Write Poly instructions to patch an EAX = Dword-Value instruction onto an Api ..
  1968.  
  1969. def Poly_ReturnDW(imm, Value):
  1970. I = random.randint(1, 3)
  1971. if I == 1:
  1972. if random.randint(1, 2) == 1:
  1973. # 7 bytes ..
  1974. return imm.assemble( "Sub EAX, EAX\n Add EAX, 0x%08x" % Value )
  1975. else:
  1976. # 7 bytes ..
  1977. return imm.assemble( "Sub EAX, EAX\n Sub EAX, -0x%08x" % Value )
  1978. if I == 2:
  1979. # 6 bytes
  1980. return imm.assemble( "Push 0x%08x\n Pop EAX\n" % Value )
  1981. if I == 3:
  1982. if random.randint(1, 2) == 1:
  1983. # 7 bytes with optimized instruction ..
  1984. return imm.assemble( "XChg EAX, EDI\n DB 0xBF\n DD 0x%08x\n XChg EAX, EDI" % Value )
  1985. else:
  1986. # 8 bytes cos not optimized ..
  1987. return imm.assemble( "XChg EAX, EDI\n Mov EDI, 0x%08x\n XChg EAX, EDI" % Value )
  1988.  
  1989.  
  1990. #-------------------------------------------------------------------------------
  1991. # Write Poly instructions to patch a simple EAX = 0 onto an Api ..
  1992.  
  1993. def Poly_Return0(imm):
  1994. I = random.randint(1, 4)
  1995. if I == 1:
  1996. # 2 bytes
  1997. return imm.assemble( "Sub EAX, EAX" )
  1998. if I == 2:
  1999. if random.randint(1, 2) == 1:
  2000. # 6 bytes
  2001. return imm.assemble( "Push 0\n Pop EAX" )
  2002. else:
  2003. # 3 bytes
  2004. return imm.assemble( "DB 0x6A, 0x00\n Pop EAX" )
  2005. if I == 3:
  2006. # 4 bytes
  2007. return imm.assemble( "XChg EAX, EDI\n Sub EDI, EDI\n XChg EAX, EDI" )
  2008. if I == 4:
  2009. return Poly_ReturnDW(imm, 0)
  2010.  
  2011.  
  2012. #-------------------------------------------------------------------------------
  2013. # Debug Detection Patches ..
  2014. #-------------------------------------------------------------------------------
  2015.  
  2016. #-------------------------------------------------------------------------------
  2017. # Clear various debug flags in PEB ..
  2018.  
  2019. def Patch_PEB(imm):
  2020. PEB = imm.getPEBAddress()
  2021. # Just incase .. ;)
  2022. if PEB == 0:
  2023. imm.log( "No PEB to patch .. !?" )
  2024. return
  2025.  
  2026. imm.log( "Patching PEB.IsDebugged ..", address = PEB + 0x02 )
  2027. imm.writeMemory(PEB + 0x02, imm.assemble( "db 0" ) )
  2028.  
  2029. a = imm.readLong(PEB + 0x18)
  2030. a += 0x10
  2031. imm.log( "Patching PEB.ProcessHeap.Flag ..", address = a )
  2032. imm.writeLong( a, 0 )
  2033.  
  2034. imm.log( "Patching PEB.NtGlobalFlag ..", address = PEB + 0x68 )
  2035. imm.writeLong(PEB + 0x68, 0)
  2036.  
  2037. # Patch PEB_LDR_DATA 0xFEEEFEEE fill bytes .. (about 3000 of them ..)
  2038. a = imm.readLong(PEB + 0x0C)
  2039. imm.log("Patching PEB.LDR_DATA filling ..", address = a)
  2040. while a != 0:
  2041. a += 1
  2042. try:
  2043. b = imm.readLong(a)
  2044. c = imm.readLong(a + 4)
  2045. # Only patch the filling runs ..
  2046. if (b == 0xFEEEFEEE) and (c == 0xFEEEFEEE):
  2047. imm.writeLong(a, 0)
  2048. imm.writeLong(a + 4, 0)
  2049. a += 7
  2050. except:
  2051. break
  2052.  
  2053.  
  2054. #-------------------------------------------------------------------------------
  2055. # IsDebuggerPresent ..
  2056. # Note: This Api checks a value in PEB, so if patching PEB then no need to patch Api ..
  2057.  
  2058. def Patch_IsDebuggerPresent(imm):
  2059. ispresent = imm.getAddress( "kernel32.IsDebuggerPresent" )
  2060. # Just incase .. ;)
  2061. if (ispresent <= 0):
  2062. imm.log( "No IsDebuggerPresent to patch .." )
  2063. return
  2064.  
  2065. imm.log( "Patching IsDebuggerPresent...", address = ispresent )
  2066. Code = imm.assemble("DB 0x64\n Mov EAX, DWORD PTR DS:[18]") + Poly_Return0(imm) + imm.assemble( "ret" )
  2067. # Careful for Win2k ..
  2068. while len(Code) > 0x0E:
  2069. Code = imm.assemble("DB 0x64\n Mov EAX, DWORD PTR DS:[18]") + Poly_Return0(imm) + imm.assemble( "ret" )
  2070. imm.writeMemory( ispresent, Code )
  2071.  
  2072.  
  2073. #-------------------------------------------------------------------------------
  2074. # CheckRemoteDebuggerPresent ..
  2075. # Note: This Api calls ZwQueryInformationProcess Api, so usually no need to patch both ..
  2076.  
  2077. def Patch_CheckRemoteDebuggerPresent(imm):
  2078. deb = imm.getAddress( "kernel32.CheckRemoteDebuggerPresent" )
  2079. # Just incase on Win2k .. ;)
  2080. if (deb <= 0):
  2081. imm.log( "No CheckRemoteDebuggerPresent to patch .." )
  2082. return
  2083.  
  2084. imm.log( "Patching CheckRemoteDebuggerPresent ..", address = deb )
  2085. imm.writeMemory( deb, imm.assemble( " \
  2086. Mov EDI, EDI \n \
  2087. Push EBP \n \
  2088. Mov EBP, ESP \n \
  2089. Mov EAX, [EBP + C] \n \
  2090. Push 0 \n \
  2091. Pop [EAX] \n \
  2092. Xor EAX, EAX \n \
  2093. Pop EBP \n \
  2094. Ret 8 \
  2095. " ) )
  2096.  
  2097.  
  2098. #-------------------------------------------------------------------------------
  2099. # ZwQueryInformationProcess ..
  2100.  
  2101. def Patch_ZwQueryInformationProcess(imm):
  2102. qip = imm.getAddress( "ntdll.ZwQueryInformationProcess" )
  2103. # Just incase .. ;)
  2104. if (qip <= 0):
  2105. imm.log( "No ZwQueryInformationProcess to patch .." )
  2106. return
  2107.  
  2108. imm.log( "Patching ZwQueryInformationProcess ..", address = qip )
  2109. IsPatched = False
  2110. a = 0
  2111. s = 0
  2112. # Scan Api and get size of first 2 instructions ..
  2113. # On Win2k SysCall starts with Mov EAX, xxxxxxxx\n Lea EDX, [ESP + 4] ..
  2114. # On WinXP, Win2k3 + Vista, SysCall always starts with Mov EAX, xxxxxxxx\n MOV EDX, 0x7FFE0300 ..
  2115. while a < 2:
  2116. a += 1
  2117. s += imm.disasmSizeOnly(qip + s).opsize
  2118.  
  2119. # Check if already patched ..
  2120. FakeCode = imm.readMemory(qip, 1) + imm.assemble("DD 0x12345678") + imm.readMemory(qip + 5, 1)
  2121. if FakeCode == imm.assemble( "Push 0x12345678\n Ret"):
  2122. # Definately found a push jump ..
  2123. IsPatched = True
  2124. # Get address of where it points to ..
  2125. a = imm.readLong(qip + 1)
  2126. # Get length of the 2 instructions before patch code ..
  2127. i = 0
  2128. s = 0
  2129. while i < 2:
  2130. i += 1
  2131. s += imm.disasmSizeOnly(a + s).opsize
  2132.  
  2133. # If not patched already, allocate some memory for patch code ..
  2134. if IsPatched == False:
  2135. # Allocate memory for hook code ..
  2136. a = imm.remoteVirtualAlloc(size=0x1000)
  2137. # Write 2 instructions from api to allocated mem ..
  2138. imm.writeMemory( a, imm.readMemory(qip, s) )
  2139.  
  2140. # If ProcessInformationClass = ProcessDebugPort then return 0 in
  2141. # ProcessInformation; else call ZwQueryInformationProcess as normal ..
  2142. PatchCode = " \
  2143. Cmp DWord [ESP + 8], 7 \n \
  2144. DB 0x74, 0x06 \n \
  2145. \n \
  2146. Push 0x%08X \n \
  2147. Ret \n \
  2148. \n \
  2149. Mov EAX, DWord [ESP + 0x0C] \n \
  2150. Push 0 \n \
  2151. Pop [EAX] \n \
  2152. Xor EAX, EAX \n \
  2153. Ret 14 \n \
  2154. " % (qip + s)
  2155.  
  2156. # Write patch code in allocated memory after the original first 2 instructions ..
  2157. imm.writeMemory( a + s, imm.assemble( PatchCode ) )
  2158.  
  2159. # If not patched, write Push Jmp to redirect Api to my code ..
  2160. if IsPatched == False:
  2161. imm.writeMemory( qip, imm.assemble( "Push 0x%08X\n Ret" % a) )
  2162.  
  2163.  
  2164. #-------------------------------------------------------------------------------
  2165. # GetTickCount ..
  2166. # Poly return cos it's an obvious one for a packer to check for Mov EAX, xxxxxxxx or Xor EAX, EAX ..
  2167.  
  2168. def Patch_GetTickCount(imm):
  2169. a = imm.getAddress("kernel32.GetTickCount")
  2170. # Just incase .. ;)
  2171. if (a <= 0):
  2172. imm.log( "No GetTickCount to patch .." )
  2173. return
  2174.  
  2175. imm.log("Patching GetTickCount ..", address = a)
  2176.  
  2177. # Keep first instruction to avoid checks ..
  2178. Code = imm.assemble("Mov EDX, 0x7FFE0000") + Poly_ReturnDW(imm, 0xB0B1560D) + imm.assemble("Ret")
  2179. # Careful of Win2k's lack of alignment ..
  2180. while len(Code) > 0x0F:
  2181. Code = imm.assemble("Mov EDX, 0x7FFE0000") + Poly_ReturnDW(imm, 0xB0B1560D) + imm.assemble("Ret")
  2182.  
  2183. imm.writeMemory( a, Code )
  2184.  
  2185.  
  2186. #-------------------------------------------------------------------------------
  2187. # ImmunityDbg.Exe Process detection Patches ..
  2188. #-------------------------------------------------------------------------------
  2189.  
  2190. #-------------------------------------------------------------------------------
  2191. # ZwQuerySystemInformation ..
  2192. # If called with size < needed size then just returns size ..
  2193. # If called with size >= needed size then fills buffer with list of all processes and lots of info about them ..
  2194.  
  2195. def Patch_ZwQuerySystemInformation(imm):
  2196. qsi = imm.getAddress( "ntdll.ZwQuerySystemInformation" )
  2197. # Just incase .. ;)
  2198. if (qsi <= 0):
  2199. imm.log( "No ZwQuerySystemInformation to patch .." )
  2200. return
  2201.  
  2202. imm.log("Patching ZwQuerySystemInformation ..", address = qsi)
  2203. IsPatched = False
  2204. a = 0
  2205. s = 0
  2206. # Scan Api and get size of first 3 instructions ..
  2207. # On Win2k thats: Mov EAX, xxxxxxxx\n Lea EDX, [ESP + 4]\n Int 0x2E ..
  2208. # On WinXP, Win2k3 + Vista thats: Mov EAX, xxxxxxxx\n MOV EDX, 0x7FFE0300\n Call [EDX] ..
  2209. # So patch code will call SysCall before doing anything else ..
  2210. while a < 3:
  2211. a += 1
  2212. s += imm.disasmSizeOnly(qsi + s).opsize
  2213.  
  2214. # Check if already patched ..
  2215. FakeCode = imm.readMemory(qsi, 1) + imm.assemble("DD 0x12345678") + imm.readMemory(qsi + 5, 1)
  2216. if FakeCode == imm.assemble( "Push 0x12345678\n Ret"):
  2217. # Definately found a push jump ..
  2218. IsPatched = True
  2219. # Get address of where it points to ..
  2220. a = imm.readLong(qsi + 1)
  2221. # Get length of the 3 instructions before patch code ..
  2222. i = 0
  2223. s = 0
  2224. while i < 3:
  2225. i += 1
  2226. s += imm.disasmSizeOnly(a + s).opsize
  2227.  
  2228. # If not patched already, allocate some memory for patch code ..
  2229. if IsPatched == False:
  2230. # Allocate memory for hook code ..
  2231. a = imm.remoteVirtualAlloc(size=0x1000)
  2232. # Write 3 instructions from api to allocated mem ..
  2233. imm.writeMemory( a, imm.readMemory(qsi, s) )
  2234.  
  2235. # If SystemInformationClass == SystemProcessesAndThreadsInformation then
  2236. # replace ImmunityDebugger.Exe with SVCHOST.EXE in returned process list .. :)
  2237. # There are no labels, so all jmps, calls etc are written as bytes ..
  2238. # Also, due to some weird bug LodsW assembles as LodsD so I put
  2239. # "DB 0x66\n LodsD" to force LodsW, and same for MovsW .. (should work after bug fix)
  2240.  
  2241. PatchCode = " \
  2242. \n\
  2243. Cmp EAX, 0 \n\
  2244. DB 0x74, 0x03 \n\
  2245. Ret 0x10 \n\
  2246. \n\
  2247. PushAD \n\
  2248. Mov EAX, [ESP + 0x24] \n\
  2249. Lea EBX, [ESP + 0x28] \n\
  2250. Mov ECX, [ESP + 0x2C] \n\
  2251. \n\
  2252. DB 0xE8 \n\
  2253. DD 0x2C \n\
  2254. DW 'I', 'M', 'M', 'U' \n\
  2255. DW 'N', 'I', 'T', 'Y' \n\
  2256. DW 'D', 'E', 'B', 'U' \n\
  2257. DW 'G', 'G', 'E', 'R' \n\
  2258. DW '.', 'E', 'X', 'E' \n\
  2259. DW 0x00,0x00 \n\
  2260. \n\
  2261. Pop EDI \n\
  2262. Cmp EAX, 5 \n\
  2263. DB 0x74, 0x04 \n\
  2264. PopAD \n\
  2265. Ret 0x10 \n\
  2266. \n\
  2267. Cmp ECX, 0 \n\
  2268. DB 0x74, 0xF4 \n\
  2269. Cmp EBX, 0 \n\
  2270. DB 0x74, 0xEC \n\
  2271. \n\
  2272. Mov EBX, [EBX] \n\
  2273. PushAD \n\
  2274. Xor EAX, EAX \n\
  2275. Mov ESI, [EBX + 0x3C] \n\
  2276. Cmp ESI, 0 \n\
  2277. DB 0x74, 0x0A \n\
  2278. DB 0x66 \n\
  2279. LodsD \n\
  2280. Cmp EAX, 0 \n\
  2281. DB 0x75, 0x0C \n\
  2282. \n\
  2283. Pop EDI \n\
  2284. Push EDI \n\
  2285. DB 0x8B, 0x03 \n\
  2286. Or EAX, EAX \n\
  2287. DB 0x74, 0x6F \n\
  2288. Add EBX, EAX \n\
  2289. DB 0xEB, 0xDA \n\
  2290. \n\
  2291. Cmp AL, 0x61 \n\
  2292. DB 0x7C, 0x03 \n\
  2293. Sub AL, 0x20 \n\
  2294. Cmp [EDI], AL \n\
  2295. DB 0x75, 0xE8 \n\
  2296. Inc EDI \n\
  2297. Inc EDI \n\
  2298. Cmp DWORD [EDI], 0 \n\
  2299. DB 0x75, 0xD4 \n\
  2300. \n\
  2301. Sub ESI, 0x28 \n\
  2302. \n\
  2303. DB 0xE8 \n\
  2304. DD 0x28 \n\
  2305. DW 'S', 'V', 'C', 'H' \n\
  2306. DW 'O', 'S', 'T', '.' \n\
  2307. DW 'E', 'X', 'E', 0x00 \n\
  2308. DD 0x00,0x00,0x00,0x00 \n\
  2309. \n\
  2310. XChg ESI, EDI \n\
  2311. Pop ESI \n\
  2312. Mov ECX, 0x14 \n\
  2313. DB 0x66 \n\
  2314. Rep MovsD \n\
  2315. \n\
  2316. Mov DWord [EBX + 0x40], 2 \n\
  2317. Mov DWord [EBX + 0x44], 0 \n\
  2318. DB 0xEB, 0x89 \n\
  2319. \n\
  2320. PopAD \n\
  2321. PopAD \n\
  2322. Ret 0x10 \n\
  2323. \
  2324. "
  2325.  
  2326. # Write patch code in allocated memory after the original first 3 instructions ..
  2327. imm.writeMemory( a + s, imm.assemble( PatchCode ) )
  2328.  
  2329. # If not patched, write Push Jmp to redirect Api to my code ..
  2330. if IsPatched == False:
  2331. imm.writeMemory( qsi, imm.assemble( "Push 0x%08X\n Ret" % a) )
  2332.  
  2333.  
  2334. #-------------------------------------------------------------------------------
  2335. # Window Detection Patches ..
  2336. #-------------------------------------------------------------------------------
  2337.  
  2338. #-------------------------------------------------------------------------------
  2339. # Patch for FindWindowA, FindWindowW, FindWindowExA, FindWindowExW ..
  2340.  
  2341. def Patch_FindWindow(imm, ex = False, suffix = "A"):
  2342. suffix = suffix.upper()
  2343.  
  2344. RetVal = 0x08
  2345. if ex:
  2346. suffix = "Ex" + suffix
  2347. RetVal = 0x10
  2348.  
  2349. FW = imm.getAddress("user32.FindWindow%s" % suffix)
  2350. # Just incase .. ;)
  2351. if (FW <= 0):
  2352. imm.log("No FindWindow%s to patch .. (Is User32 Loaded?)" % suffix)
  2353. return False
  2354.  
  2355. # Find place for jmp in Api ..
  2356. p = 0
  2357. d = imm.disasm(FW)
  2358. l = d
  2359. dis = ""
  2360. FoundCall = False
  2361. while p < 100:
  2362. if d.getDisasm() == "POP EBP":
  2363. dis = l.getDisasm()
  2364. p -= l.getSize()
  2365. if l.isCall():
  2366. FoundCall = True
  2367. break
  2368. # Try to continue without expected call instrucion ..
  2369. dis = l.getDisasm()
  2370. break
  2371. # Did we already patch this api ?
  2372. if d.getDisasm() == "RETN":
  2373. if l.isPush():
  2374. imm.log("FindWindow%s already patched .." % suffix, address = FW)
  2375. return False
  2376. p += d.getSize()
  2377. l = d
  2378. d = imm.disasm(FW + p)
  2379.  
  2380. imm.log("Patching FindWindow%s .." % suffix, address = FW)
  2381. HookMem = imm.remoteVirtualAlloc(size=0x1000)
  2382. HookCode = imm.assemble("Push 0x%08X\n Ret" % HookMem)
  2383.  
  2384. if FoundCall == True:
  2385. # Get address pointed to by call instruction ..
  2386. a = l.getJmpAddr()
  2387. # Fix Call instruction in patch function to point to original call address ..
  2388. a = ((a - HookMem) - 5)
  2389. dis = "DB 0xE8\n DD 0x%08X" % a
  2390.  
  2391. # Get HWnd of ImmDbg .. If this is exposed by ImmLib, I didn't find it.. :)
  2392. ImmHWnd = ctypes.windll.LoadLibrary("User32.DLL").FindWindowA("ID", 0)
  2393.  
  2394. # Code calls Api, if HWnd matches ImmDbg return 0 ..
  2395. # Else all works as before ..
  2396. # Again, all jumps are as bytes cos no labels ..
  2397.  
  2398. PatchCode = " \
  2399. %s \n\
  2400. Cmp EAX, 0x%08X \n\
  2401. DB 0x74, 0x02 \n\
  2402. DB 0xEB, 0x02 \n\
  2403. Xor EAX, EAX \n\
  2404. Pop EBP \n\
  2405. Ret 0x%02X \n\
  2406. " % (dis, ImmHWnd, RetVal)
  2407.  
  2408. imm.writeMemory(HookMem, imm.assemble(PatchCode))
  2409. imm.writeMemory(FW + p, HookCode)
  2410. return True
  2411.  
  2412.  
  2413. #-------------------------------------------------------------------------------
  2414.  
  2415. def Patch_EnumWindows(imm):
  2416. EW = imm.getAddress("user32.EnumWindows")
  2417. # Just incase .. ;)
  2418. if (EW <= 0):
  2419. imm.log("No EnumWindows to patch .. (Is User32 Loaded?)")
  2420. return False
  2421.  
  2422. # Find place for jmp in Api ..
  2423. p = 0
  2424. d = imm.disasm(EW)
  2425. l = d
  2426. dis = ""
  2427. FoundCall = False
  2428. while p < 100:
  2429. if d.getDisasm() == "POP EBP":
  2430. dis = l.getDisasm()
  2431. p -= l.getSize()
  2432. if l.isCall():
  2433. FoundCall = True
  2434. break
  2435. # Try to continue without expected call instrucion ..
  2436. dis = l.getDisasm()
  2437. break
  2438. # Did we already patch this api ?
  2439. if d.getDisasm() == "RETN":
  2440. if l.isPush():
  2441. imm.log("EnumWindows already patched ..", address = EW)
  2442. return False
  2443. p += d.getSize()
  2444. l = d
  2445. d = imm.disasm(EW + p)
  2446.  
  2447. imm.log("Patching EnumWindows ..", address = EW)
  2448. HookMem = imm.remoteVirtualAlloc(size=0x1000)
  2449. HookCode = imm.assemble("Push 0x%08X\n Ret" % HookMem)
  2450.  
  2451. if FoundCall == True:
  2452. # Get address pointed to by call instruction ..
  2453. a = l.getJmpAddr()
  2454. # Fix Call instruction in patch function to point to original call address ..
  2455. a = ((a - (HookMem + 0x5B)) - 5) # 0x5B = offset of call instruction in patch code ..
  2456. dis = "DB 0xE8\n DD 0x%08X" % a
  2457.  
  2458. # Get HWnd of ImmDbg ..
  2459. ImmHWnd = ctypes.windll.LoadLibrary("User32.DLL").FindWindowA("ID", 0)
  2460.  
  2461. # Code calls Api, using own callback function ..
  2462. # My callback calls user's callback function (if hwnd not ImmDbg) ..
  2463. # Else all works as before ..
  2464. PatchCode = " \
  2465. DB 0xEB,0x31 \n\
  2466. \n\
  2467. Sub EAX, EAX \n\
  2468. Inc EAX \n\
  2469. PushAD \n\
  2470. DB 0x81,0x7C,0x24,0x24 \n\
  2471. DD 0x%08X \n\
  2472. DB 0x74,0x1B \n\
  2473. Push [ESP + 0x28] \n\
  2474. Push [ESP + 0x28] \n\
  2475. Call [0x0000002F] \n\
  2476. Mov [ESP + 0x1C], EAX \n\
  2477. PopAD \n\
  2478. Ret 8 \n\
  2479. \n\
  2480. DD 0xB0b1560d \n\
  2481. \n\
  2482. DB 0xE8 \n\
  2483. DD 0x00000000 \n\
  2484. Pop EAX \n\
  2485. Sub EAX, 0x38 \n\
  2486. Add [EAX + 0x20], EAX \n\
  2487. Push [EBP + 0x08] \n\
  2488. Pop [EAX + 0x2F] \n\
  2489. \n\
  2490. Inc EAX \n\
  2491. Inc EAX \n\
  2492. Push EAX \n\
  2493. Pop [ESP + 0x08] \n\
  2494. %s \n\
  2495. Pop EBP \n\
  2496. Ret 8 \n\
  2497. " % (ImmHWnd, dis)
  2498.  
  2499. imm.writeMemory(HookMem, imm.assemble(PatchCode))
  2500. imm.writeMemory(EW + p, HookCode)
  2501. return True
  2502.  
  2503.  
  2504. #-------------------------------------------------------------------------------
  2505. # Main Function ..
  2506.  
  2507. def main(args):
  2508. ptypes={
  2509. # Debug types
  2510. 'isdebuggerpresent':0, 'peb':1, 'checkremotedebuggerpresent':2,
  2511. 'zwqueryinformationprocess':3, 'gettickcount':4, 'all_debug':10,
  2512. # Process Types
  2513. 'zwquerysysteminformation':20, 'all_process':21,
  2514. # Window Types
  2515. 'findwindowa':30, 'findwindoww':31, 'findwindowexa':32, 'findwindowexw':33,
  2516. 'enumwindows':34, 'all_window':35,
  2517. # Packers (some example ones - of course many more are supported, add them as you find them)
  2518. 'upx-lock':100, 'nspack':101, 'exestealth':102, 'escargot':103, 'rlpack':104
  2519. }
  2520.  
  2521. imm = immlib.Debugger()
  2522.  
  2523. if not args:
  2524. usage(imm)
  2525. return "Error : No patch type .. See log window for usage (Alt-L) .."
  2526.  
  2527. ptype = args[0].lower()
  2528. if ptypes.has_key( ptype ):
  2529. ptype = ptypes[ ptype ]
  2530. else:
  2531. return "Invalid type: %s" % ptype
  2532.  
  2533. # Intro text ..
  2534. imm.log(" ")
  2535. imm.log("%s v%s By BoB -> Team PEiD" % (ProgName, ProgVers), highlight=1)
  2536.  
  2537.  
  2538. # --------------------------------------------------------------------------
  2539.  
  2540. # IsDebuggerPresent ..
  2541. # If patch PEB then no need for this ..
  2542. if ptype == 0:
  2543. Patch_IsDebuggerPresent(imm)
  2544. return "IsDebuggerPresent patched .."
  2545.  
  2546. # PEB ..
  2547. elif ptype == 1:
  2548. Patch_PEB(imm)
  2549. return "PEB Flags patched .."
  2550.  
  2551. # CheckRemoteDebuggerPresent ..
  2552. # If patch ZwQueryInformationProcess then no need for this ..
  2553. elif ptype == 2:
  2554. Patch_CheckRemoteDebuggerPresent(imm)
  2555. return "CheckRemoteDebuggerPresent patched .."
  2556.  
  2557. # ZwQueryInformationProcess ..
  2558. elif ptype == 3:
  2559. Patch_ZwQueryInformationProcess(imm)
  2560. return "ZwQueryInformationProcess patched .."
  2561.  
  2562. # GetTickCount ..
  2563. elif ptype == 4:
  2564. Patch_GetTickCount(imm)
  2565. return "GetTickCount patched .."
  2566.  
  2567. # Patch all anti-debug / debug-detection Apis and flags ..
  2568. elif ptype == 10:
  2569. Patch_PEB(imm)
  2570. Patch_IsDebuggerPresent(imm)
  2571. Patch_CheckRemoteDebuggerPresent(imm)
  2572. Patch_ZwQueryInformationProcess(imm)
  2573. Patch_GetTickCount(imm)
  2574. return "All Anti-debug Apis and flags patched .."
  2575.  
  2576.  
  2577. # --------------------------------------------------------------------------
  2578. # ZwQuerySystemInformation ..
  2579. elif ptype == 20:
  2580. Patch_ZwQuerySystemInformation(imm)
  2581. return "ZwQuerySystemInformation patched .."
  2582.  
  2583. # Patch all Process Apis to not return ImmDbg.EXE ..
  2584. elif ptype == 21:
  2585. Patch_ZwQuerySystemInformation(imm)
  2586. return "All debugger process finding Apis patched .."
  2587.  
  2588.  
  2589. # --------------------------------------------------------------------------
  2590. # User32.DLL isn't always in memory, so these are done slightly differently ..
  2591.  
  2592. # FindWindowA ..
  2593. elif ptype == 30:
  2594. if Patch_FindWindow(imm) == True:
  2595. return "FindWindowA patched .."
  2596. return "FindWindowA not patched .."
  2597.  
  2598. # FindWindowW ..
  2599. elif ptype == 31:
  2600. if Patch_FindWindow(imm, "W") == True:
  2601. return "FindWindowW patched .."
  2602. return "FindWindowW not patched .."
  2603.  
  2604. # FindWindowExA ..
  2605. elif ptype == 32:
  2606. if Patch_FindWindow(imm, True) == True:
  2607. return "FindWindowExA patched .."
  2608. return "FindWindowExA not patched .."
  2609.  
  2610. # FindWindowExW ..
  2611. elif ptype == 33:
  2612. if Patch_FindWindow(imm, True, "W") == True:
  2613. return "FindWindowExW patched .."
  2614. return "FindWindowExW not patched .."
  2615.  
  2616. # EnumWindows ..
  2617. elif ptype == 34:
  2618. if Patch_EnumWindows(imm) == True:
  2619. return "EnumWindows patched .."
  2620. return "EnumWindows not patched .."
  2621.  
  2622. # All Window functions ..
  2623. elif ptype == 35:
  2624. a = True
  2625. b = Patch_FindWindow(imm)
  2626. if b == False:
  2627. a = b
  2628. b = Patch_FindWindow(imm, suffix = "W")
  2629. if b == False:
  2630. a = b
  2631. b = Patch_FindWindow(imm, True, "A")
  2632. if b == False:
  2633. a = b
  2634. b = Patch_FindWindow(imm, True, "W")
  2635. if b == False:
  2636. a = b
  2637. b = Patch_EnumWindows(imm)
  2638. if b == False:
  2639. a = b
  2640. if a:
  2641. return "All debugger Window finding Apis patched .."
  2642. return "Some Window Apis not patched .. See Log .."
  2643.  
  2644.  
  2645. # --------------------------------------------------------------------------
  2646.  
  2647. # Fix Anti-Debug of Upx-Lock ..
  2648. elif ptype == 100:
  2649. Patch_IsDebuggerPresent(imm)
  2650. Patch_GetTickCount(imm)
  2651. return "ImmDbg hidden from Upx-Lock .."
  2652.  
  2653. # Fix Anti-Debug of NsPack ..
  2654. elif ptype == 101:
  2655. Patch_PEB(imm)
  2656. return "ImmDbg hidden from NsPack .."
  2657.  
  2658. # Fix Anti-Debug of ExeStealth ..
  2659. elif ptype == 102:
  2660. Patch_PEB(imm)
  2661. return "ImmDbg hidden from ExeStealth .."
  2662.  
  2663. # Fix Anti-Debug of Escargot ..
  2664. elif ptype == 103:
  2665. Patch_IsDebuggerPresent(imm)
  2666. return "ImmDbg hidden from Escargot .."
  2667.  
  2668. # Fix Anti-Debug of RL!Pack (v1.18+ Still detects debug by guard page) ..
  2669. elif ptype == 104:
  2670. Patch_PEB(imm)
  2671. Patch_ZwQueryInformationProcess(imm)
  2672. Patch_EnumWindows(imm)
  2673. return "ImmDbg hidden from RL!Pack .."
  2674.  
  2675.  
  2676. #!/usr/bin/env python
  2677.  
  2678. """
  2679. (c) Immunity, Inc. 2004-2007
  2680.  
  2681.  
  2682. U{Immunity Inc.<http://www.immunityinc.com>}
  2683.  
  2684. """
  2685.  
  2686. DESC="""Heap logging function"""
  2687.  
  2688. import immlib
  2689. import immutils
  2690. import getopt
  2691.  
  2692. # We need to find this specific place
  2693. def getRet(imm, allocaddr, max_opcodes = 300):
  2694. addr = allocaddr
  2695.  
  2696. for a in range(0, max_opcodes):
  2697. op = imm.disasmForward( addr )
  2698. if op.isRet():
  2699. if op.getImmConst() == 0xc:
  2700. op = imm.disasmBackward( addr, 3)
  2701. return op.getAddress()
  2702. addr = op.getAddress()
  2703.  
  2704. return 0x0
  2705.  
  2706. def usage( imm ):
  2707. imm.log("!hippie -[o|s|d|p|c] InjectHook on Allocate/Free Heap", focus=1)
  2708. #imm.log("-n Name Tag Name ")
  2709. imm.log("-o Enable Hook")
  2710. imm.log("-s Show Hook results")
  2711. imm.log("-d Delete Hooks")
  2712. imm.log("-p Pause Hook")
  2713. imm.log("-C Clear Hook")
  2714. imm.log("-c Continue Hook")
  2715. imm.log("-h Filter by Heap")
  2716. imm.log("-a Filter by Chunk Address")
  2717.  
  2718. SWITCH = 1
  2719. SHOW = 2
  2720. DELETE = 3
  2721. PAUSE = 4
  2722. CONTINUE = 5
  2723. CLEAR = 6
  2724.  
  2725. def showresult(imm, a, rtlallocate, extra = ""):
  2726. if a[0] == rtlallocate:
  2727. imm.log("RtlAllocateHeap(0x%08x, 0x%08x, 0x%08x) <- 0x%08x %s" % ( a[1][0], a[1][1], a[1][2], a[1][3], extra), address = a[1][3] )
  2728. else:
  2729. imm.log("RtlFreeHeap(0x%08x, 0x%08x, 0x%08x) %s" % (a[1][0], a[1][1], a[1][2], extra) )
  2730.  
  2731.  
  2732. def main(args):
  2733. imm = immlib.Debugger()
  2734.  
  2735. try:
  2736. opts, argo = getopt.getopt(args, "osdpch:a:C")
  2737. except getopt.GetoptError:
  2738. usage(imm)
  2739. return "Wrong Argument (Check Log Window)"
  2740.  
  2741. FlagCmd = 0
  2742. heap = None
  2743. chunkaddress = None
  2744.  
  2745. for o,a in opts:
  2746. if o == '-o':
  2747. FlagCmd = SWITCH
  2748. elif o == '-s':
  2749. FlagCmd = SHOW
  2750. elif o == '-d':
  2751. FlagCmd = DELETE
  2752. elif o == '-p':
  2753. FlagCmd = PAUSE
  2754. elif o == '-c':
  2755. FlagCmd = CONTINUE
  2756. elif o == '-C':
  2757. FlagCmd = CLEAR
  2758. elif o == '-h':
  2759. heap = int(a, 16)
  2760. elif o == '-a':
  2761. chunkaddress = int(a, 16)
  2762.  
  2763. Name = "hippiehook"
  2764.  
  2765.  
  2766. if FlagCmd == SWITCH:
  2767. if imm.getKnowledge(Name):
  2768. usage(imm)
  2769. return "Cannot set Hooks: Hooks are already set"
  2770. imm.pause()
  2771. rtlfree = imm.getAddress("ntdll.RtlFreeHeap")
  2772. allocate = imm.getAddress("ntdll.RtlAllocateHeap")
  2773. # We need to hook on the the ret point of RtlAllocateHeap so we can
  2774. # get the result of the allocation.
  2775. mod = imm.getModule("ntdll.dll")
  2776. if not mod.isAnalysed():
  2777. imm.analyseCode( mod.getCodebase() )
  2778. #imm.log("oOoo: 0x%08x" % allocate)
  2779. rtlallocate = getRet(imm, allocate, 1000)
  2780. imm.addKnowledge("FuncNames", ( rtlallocate, rtlfree ) )
  2781.  
  2782. #imm.log("0x%08x 0x%08x (0x%08x)" % (rtlallocate, rtlfree, allocate))
  2783.  
  2784. fast = immlib.STDCALLFastLogHook( imm )
  2785. imm.log("Logging on Free 0x%08x" % rtlfree)
  2786. fast.logFunction( rtlfree, 3 )
  2787.  
  2788. imm.log("Logging on Alloc 0x%08x" % rtlallocate)
  2789. fast.logFunction( rtlallocate, 0)
  2790. fast.logBaseDisplacement( "EBP", 8)
  2791. fast.logBaseDisplacement( "EBP", 0xC)
  2792. fast.logBaseDisplacement( "EBP", 0x10)
  2793. fast.logRegister( "EAX" )
  2794.  
  2795. # Manual Way to do it
  2796. #fast = immlib.FastLogHook( imm )
  2797. #imm.log("Logging on 0x%08x" % rtlallocate)
  2798. #fast.logFunction( rtlallocate )
  2799. #fast.logBaseDisplacement("ESP", 4)
  2800. #fast.logBaseDisplacement("ESP", 8)
  2801. #fast.logBaseDisplacement("ESP", 12)
  2802. #fast.logRegister("EAX")
  2803.  
  2804. #fast.logFunction( rtlfree )
  2805. #imm.log("Logging on 0x%08x" % rtlfree)
  2806. #fast.logBaseDisplacement("ESP", 4)
  2807. #fast.logBaseDisplacement("ESP", 8)
  2808. #fast.logBaseDisplacement("ESP", 12)
  2809.  
  2810. fast.Hook()
  2811. imm.addKnowledge(Name, fast, force_add = 1)
  2812.  
  2813. elif FlagCmd == DELETE:
  2814. fast = imm.getKnowledge( Name )
  2815. if not fast:
  2816. return "Couldn't find the name tag"
  2817. fast.unHook()
  2818. imm.forgetKnowledge( Name )
  2819. return "Hook removed: %s" % Name
  2820.  
  2821. elif FlagCmd == CLEAR:
  2822. fast = imm.getKnowledge(Name)
  2823. if not fast:
  2824. return "Couldn't find the name tag"
  2825. fast.Clear()
  2826. return "Hook has been clear"
  2827.  
  2828. elif FlagCmd == SHOW:
  2829. fast = imm.getKnowledge(Name)
  2830. if not fast:
  2831. return "Couldn't find the name tag"
  2832.  
  2833. rtlallocate, rtlfree = imm.getKnowledge("FuncNames")
  2834. ret = fast.getAllLog()
  2835. NDX = {rtlallocate: 3, rtlfree: 2}
  2836. for a in ret:
  2837. extra = ""
  2838. if heap:
  2839. if heap == a[1][0]:
  2840. if chunkaddress:
  2841. if a[1][ NDX[ a[0] ] ] == chunkaddress:
  2842. extra = "<---- * FOUND *"
  2843. showresult(imm, a, rtlallocate, extra)
  2844. #else:
  2845. # showresult(imm, a, rtlallocate)
  2846. else:
  2847. if chunkaddress:
  2848. if a[1][ NDX[ a[0] ] ] == chunkaddress:
  2849. extra = "<---- * FOUND *"
  2850.  
  2851. showresult(imm, a, rtlallocate, extra)
  2852. #else:
  2853. # showresult(imm, a, rtlallocate)
  2854.  
  2855. imm.log("=" * 0x2f)
  2856. return "Traced %d functions" % len(ret)
  2857.  
  2858. elif FlagCmd == PAUSE:
  2859. fast = imm.getKnowledge(Name)
  2860. if not fast:
  2861. return "Couldn't find the name tag"
  2862. if not fast.Pause():
  2863. return "Error: not been able to pause %s hook " % Name
  2864. imm.addKnowledge(Name, fast, force_add = 1)
  2865. return "Hook %s paused" % Name
  2866.  
  2867. elif FlagCmd == CONTINUE:
  2868. fast = imm.getKnowledge(Name)
  2869. if not fast:
  2870. return "Couldn't find the name tag"
  2871. if not fast.Continue():
  2872. return "Error: not been able to continue %s hook " % Name
  2873. imm.addKnowledge(Name, fast, force_add = 1)
  2874. return "Hook %s continued" % Name
  2875.  
  2876. return "Done"
  2877. #!/usr/bin/env python
  2878. """
  2879. Hook on RtlAllocateHeap
  2880. """
  2881.  
  2882. DESC = """Hook on RtlAllocateHeap/RtlFreeHeap and display information """
  2883. import immlib
  2884. from immlib import LogBpHook
  2885. import getopt
  2886. import struct
  2887.  
  2888. # RtlAllocateHeap Hook class
  2889. ALLOCLABEL = "Alloc Hook"
  2890. class RtlAllocateHeapHook(LogBpHook):
  2891. def __init__(self, heap):
  2892. LogBpHook.__init__(self)
  2893. self.Heap = heap
  2894.  
  2895. def run(self,regs):
  2896. """This will be executed when hooktype happens"""
  2897. imm = immlib.Debugger()
  2898. #for a in regs:
  2899. #imm.log("%s:%08x" % (a, regs[a]))
  2900. readaddr=""
  2901. size=""
  2902.  
  2903. res=imm.readMemory( regs['ESP'] + 4, 0xc)
  2904. if len(res) != 0xc:
  2905. imm.log("RtlAllocateHeap: ESP seems to broken, unable to get args")
  2906. return 0x0
  2907. (heap, flags, size) = struct.unpack("LLL", res)
  2908. if heap == self.Heap:
  2909. imm.log("RtlAllocateHeap(0x%08x, 0x%08x, 0x%08x)" % (heap, flags, size))
  2910.  
  2911. # RtlFreeHeap Hook class
  2912. FREELABEL = "Free Hook"
  2913. class RtlFreeHeapHook(LogBpHook):
  2914. def __init__(self, heap):
  2915. LogBpHook.__init__(self)
  2916. self.Heap = heap
  2917.  
  2918. def run(self,regs):
  2919. """This will be executed when hooktype happens"""
  2920. imm = immlib.Debugger()
  2921. #for a in regs:
  2922. #imm.log("%s:%08x" % (a, regs[a]))
  2923. readaddr=""
  2924. size=""
  2925.  
  2926. res=imm.readMemory( regs['ESP'] + 4, 0xc)
  2927. if len(res) != 0xc:
  2928. imm.log("RtlFreeHeap: ESP seems to broken, unable to get args")
  2929. return 0x0
  2930. (heap, flags, size) = struct.unpack("LLL", res)
  2931. if heap == self.Heap:
  2932. imm.log("RtlFreeHeap(0x%08x, 0x%08x, 0x%08x)" % (heap, flags, size))
  2933.  
  2934.  
  2935. def usage(imm):
  2936. imm.log("!hookalloc Hook on RtlAllocateHeap/RtlFreeHeap and display information")
  2937. imm.log("-h Heap to hook")
  2938. imm.log("-a Hook on RtlAllocateHeap")
  2939. imm.log("-f Hook on RtlFreeHeap")
  2940. imm.log("-u Disable Hooks")
  2941.  
  2942. def HookOn(imm, heap, LABEL, HeapHook, bp_address, Disable):
  2943. hookalloc = imm.getKnowledge( LABEL + "_%08x" % heap )
  2944. if Disable:
  2945. if not hookalloc:
  2946. imm.log("Error %s: No hook for heap 0x%08x to disable" % (LABEL, heap))
  2947. return "No %s to disable for heap 0x%08x" % (LABEL, heap)
  2948. else:
  2949. hookalloc.UnHook()
  2950. imm.log("UnHooked %s" % LABEL)
  2951. imm.forgetKnowledge( LABEL + "_%08x" % heap )
  2952. return "%s for 0x%08x heap unhooked" % (LABEL, heap)
  2953. else:
  2954. if not hookalloc:
  2955. hookalloc= HeapHook( heap )
  2956. hookalloc.add( LABEL + "_%08x" % heap, bp_address)
  2957. imm.log("Placed %s" % LABEL)
  2958. imm.addKnowledge( LABEL + "_%08x" % heap, hookalloc )
  2959. else:
  2960. imm.log("HookAlloc for heap 0x%08x is already running" % heap)
  2961. return "Hooking on RtlAllocateHeap"
  2962. #!/usr/bin/env python
  2963.  
  2964. """
  2965. (c) Immunity, Inc. 2004-2007
  2966.  
  2967.  
  2968. U{Immunity Inc.<http://www.immunityinc.com>}
  2969. """
  2970.  
  2971. def main(args):
  2972. if not args:
  2973. return "No arguments given"
  2974.  
  2975. heap = None
  2976. Disable = False
  2977. AllocFlag = False
  2978. FreeFlag = False
  2979. imm = immlib.Debugger()
  2980.  
  2981. try:
  2982. opts, argo = getopt.getopt(args, "h:uaf")
  2983. except getopt.GetoptError:
  2984. imm.setStatusBar("Bad argument %s" % str(args))
  2985. usage(imm)
  2986. return 0
  2987.  
  2988. for o,a in opts:
  2989. if o == "-h" :
  2990. try:
  2991. heap = int(a, 16)
  2992. except ValueError, msg:
  2993. return "Invalid heap address: %s" % a
  2994. elif o == "-u" :
  2995. Disable = True
  2996. elif o == "-a":
  2997. AllocFlag = True
  2998. elif o == "-f":
  2999. FreeFlag = True
  3000.  
  3001. ret = ""
  3002.  
  3003. if heap:
  3004. if AllocFlag:
  3005. allocaddr = imm.getAddress("ntdll.RtlAllocateHeap" )
  3006. ret = "Alloc Hook <%s>" % HookOn(imm, heap, ALLOCLABEL, RtlAllocateHeapHook, allocaddr, Disable)
  3007. if FreeFlag:
  3008. freeaddr = imm.getAddress("ntdll.RtlFreeHeap" )
  3009. if ret:
  3010. ret+= " - "
  3011. ret +="Free Hook <%s>" % HookOn(imm, heap, FREELABEL, RtlFreeHeapHook, freeaddr, Disable)
  3012. return ret
  3013. else:
  3014. return "Please, select a correct Heap"
  3015.  
  3016.  
  3017.  
  3018.  
  3019.  
  3020.  
  3021.  
  3022.  
  3023.  
  3024.  
  3025.  
  3026.  
  3027.  
  3028.  
  3029.  
  3030.  
  3031. import socket
  3032. import struct
  3033. import xmlrpclib
  3034. import traceback
  3035. import base64
  3036. from immlib import *
  3037. from immutils import *
  3038. import getopt
  3039.  
  3040. DESC="""Hooks the NDR unmarshalling routines and prints them out so you can see which ones worked"""
  3041.  
  3042.  
  3043. #############################################################################
  3044. class set_hooks(LogBpHook):
  3045. def __init__(self):
  3046. LogBpHook.__init__(self)
  3047. self.description=""
  3048.  
  3049. return
  3050.  
  3051. #########################################################################
  3052. def run(self,regs):
  3053. '''
  3054.  
  3055. '''
  3056. imm = Debugger()
  3057. imm.log("%s"%self.description)
  3058. return
  3059.  
  3060. def usage(imm):
  3061. imm.log("!hookndr.py")
  3062. imm.log("%s" % DESC)
  3063. imm.log("-D (to uninstall hook)")
  3064. imm.log("-h This help")
  3065.  
  3066. # The main routine that gets run when you type !packets
  3067. def main(args):
  3068.  
  3069. imm = Debugger()
  3070. imm.ignoreSingleStep("CONTINUE")
  3071. try:
  3072. opts,argo = getopt.getopt(args, "Dh")
  3073. except:
  3074. return usage(imm)
  3075. xmlhost=""
  3076. xmlport=0
  3077. for o,a in opts:
  3078. if o == "-D":
  3079. ndrhooks=imm.getKnowledge("ndrhooks")
  3080. if not ndrhooks:
  3081. imm.log("Could not find hooks to delete!")
  3082. return "Did not find hook to delete"
  3083. for hooker in ndrhooks:
  3084. imm.removeHook(hooker)
  3085. #now forget about that hook
  3086. imm.forgetKnowledge("ndrhooks")
  3087. return "Unhooked our ndr hooks"
  3088. if o =="-h":
  3089. return usage(imm)
  3090.  
  3091. #otherwise it's time to hook some functions! Horray!
  3092. #these functions are all in RPCRT4.dll
  3093. #you know what would be good, being able to get all these automatically by listing names
  3094. #and then looking for Ndr*Unmarshall!
  3095. names= ["NdrPointerUnmarshall","NdrNonConformantStringUnmarshall","NdrNonEncapsulatedUnionUnmarshall"]
  3096. names+=["NdrRangeUnmarshall","NdrSimpleStructUnmarshall","NdrSimpleTypeUnmarshall","NdrUserMarshalUnmarshall"]
  3097. names+=["NdrVaryingArrayUnmarshall","NdrXmitOrRepAsUnmarshall","NdrByteCountPointerUnmarshall","NdrClientContextUnmarshall"]
  3098. names+=["NdrComplexArrayUnmarshall","NdrConformantArrayUnmarshall","NdrConformantStringUnmarshall","NdrConformantStructUnmarshall"]
  3099. names+=["NdrConformantVaryingArrayUnmarshall","NdrConformantVaryingStructUnmarshall","NdrEncapsulatedUnionUnmarshall"]
  3100. names+=["NdrFixedArrayUnmarshall","NdrInterfacePointerUnmarshall"]
  3101. hooks=[]
  3102. for functionname in names:
  3103. # Find the addresses of the functions we want to hook
  3104. # Then register the hooks
  3105. addy = imm.getAddress("RPCRT4."+functionname)
  3106. imm.log(functionname+ " found at 0x%x"%addy)
  3107. if addy == -1:
  3108. imm.log("Could not locate %s"%functionname)
  3109. continue
  3110.  
  3111. # Set the hooks - this is the start hook
  3112. hooker = set_hooks()
  3113. hooker.description="Entering: %s"%functionname
  3114. ret=hooker.add(hooker.description, addy)
  3115. if ret==-1:
  3116. imm.log("Hooking add failed!")
  3117. else:
  3118. hooks+=[hooker.description]
  3119.  
  3120. func = imm.getFunction( addy )
  3121. endaddies=imm.getFunctionEnd( func) #get the address of all the rets of the function
  3122. for addy in endaddies:
  3123. # Set the hooks
  3124. hooker = set_hooks()
  3125. #hooker.description="Leaving: %s"%functionname
  3126. ret=hooker.add(hooker.description, addy)
  3127. if ret==-1:
  3128. imm.log("Hooking add failed!")
  3129. else:
  3130. hooks+=[hooker.description]
  3131.  
  3132. imm.log("Added %d hooks"%(len(hooks)))
  3133. imm.addKnowledge("ndrhooks",hooks)
  3134. return "Network hooks in place."
  3135.  
  3136.  
  3137. import socket
  3138. import struct
  3139. import xmlrpclib
  3140. import traceback
  3141. import base64
  3142. from immlib import *
  3143. from immutils import *
  3144. import getopt
  3145.  
  3146. DESC="""Creates a table that displays packets received on the network."""
  3147.  
  3148.  
  3149. #############################################################################
  3150. class set_hooks(LogBpHook):
  3151. def __init__(self):
  3152. LogBpHook.__init__(self)
  3153. self.xmlhost = ""
  3154. self.xmlport = 0
  3155. return
  3156. #########################################################################
  3157. def run(self,regs):
  3158. '''
  3159. This routine is the first one hit, when a socket operation occurs.
  3160. '''
  3161. imm = Debugger()
  3162.  
  3163.  
  3164. # Retrieve the function name
  3165. function_name = imm.getKnowledge("%08x" % regs['EIP'])
  3166. imm.log("Hook hit for %s"%function_name)
  3167. self.retrieve_packet(imm,function_name,regs)
  3168. return
  3169.  
  3170. #########################################################################
  3171. def retrieve_packet(self,imm,function_name,regs):
  3172. '''
  3173. This function logs the packet data into cap_win
  3174. '''
  3175. imm.log("Retrieving packet from %s"%function_name)
  3176. # Determine what function we have hooked, based on this, retrieve the packet contents
  3177. if function_name == "SSL3DecryptMessage":
  3178. #nothing yet
  3179. return
  3180. elif function_name == "SSL3EncryptMessage":
  3181. imm.log("Looking at SSL3EncryptMessage data")
  3182. #The payload ptr is at esp+24
  3183. pbuffer_ptr = imm.readMemory( regs['ESP'] + 0x24, 4)
  3184. pbuffer_ptr = int(struct.unpack("L", pbuffer_ptr)[0])
  3185.  
  3186. #the size of the buffer is at esp+0x20
  3187. pbuffer_len = imm.readMemory( regs['ESP'] + 0x20, 4)
  3188. pbuffer_len = int(struct.unpack("L", pbuffer_len)[0])
  3189.  
  3190. imm.log("pbuffer_Size=%d"%pbuffer_len)
  3191. #imm.log("Buffer Location: 0x%08x" % pbuffer_ptr[0])
  3192. imm.log("pbuffer_ptr=%s"%repr(pbuffer_ptr))
  3193. # Get the pointer to the packet payload
  3194. payload = imm.readMemory(pbuffer_ptr, pbuffer_len)
  3195. imm.log("Payload=%s"%repr(payload))
  3196. #payload= "Payload!"
  3197. decoded_payload = ""
  3198. # Build the list thats table-friendly
  3199. log_items = [function_name,repr(payload),decoded_payload]
  3200.  
  3201. # Get a handle to the window and add the items, along with the related
  3202. # address, this is sweet cause you can double-click on a packet and
  3203. # see in the disassembly where it was sent/received :)
  3204.  
  3205.  
  3206. #save this data to a file called payloads.txt
  3207. #file("payloads.txt","ab").write(repr(payload)+"\n")
  3208. using_xml_rpc = False
  3209.  
  3210. if self.xmlport != 0:
  3211. server = xmlrpclib.ServerProxy("http://%s:%d/"%(self.xmlhost,self.xmlport), allow_none=True)
  3212. imm.log("Using server: %s:%d"%(self.xmlhost, self.xmlport))
  3213. using_xml_rpc = True
  3214. else:
  3215. server = None
  3216.  
  3217. if using_xml_rpc:
  3218. #send our xml request to the remove side
  3219. #if self.filter matches...(stub for now)
  3220. try:
  3221. result = server.senddata(("ssldata",[base64.encodestring(payload)]))
  3222. except:
  3223. data=traceback.format_exc()
  3224. imm.log("Failed to connect to remote server, sorry")
  3225. imm.logLines("Error was: %s"%data)
  3226. return
  3227.  
  3228. #Now parse what we got back - a command and list of arguments
  3229. command, arguments = result
  3230. if command=="LEAVEALONE":
  3231. imm.log("Leaving alone")
  3232. return
  3233. elif command=="REPLACE":
  3234. payload=arguments[0]
  3235. payload=base64.decodestring(payload) #decode it
  3236. imm.log("New Payload recved: %s"%repr(payload))
  3237.  
  3238. #they encrypt messages in place, so we need to use their original
  3239. #buffer to put our message into.
  3240. #The payload ptr is at esp+24
  3241. pbuffer_ptr = imm.readLong( regs['ESP'] + 0x24)
  3242. imm.log("Replacing buffer at %8.8x with data of length %d"%(pbuffer_ptr, len(payload)))
  3243. imm.writeMemory(pbuffer_ptr, payload)
  3244.  
  3245.  
  3246. #add more commands from XML-RPC here
  3247.  
  3248.  
  3249.  
  3250. return
  3251.  
  3252. def usage(imm):
  3253. imm.log("!hookssl.py")
  3254. imm.log("-D (to uninstall hook)")
  3255. imm.log("-s host:port (Server to send XML-RPC data to)")
  3256. imm.log("-h This help")
  3257. return
  3258.  
  3259. # The main routine that gets run when you type !packets
  3260. def main(args):
  3261.  
  3262. imm = Debugger()
  3263. imm.ignoreSingleStep("CONTINUE")
  3264. try:
  3265. opts,argo = getopt.getopt(args, "Dhs:")
  3266. except:
  3267. return usage(imm)
  3268. xmlhost=""
  3269. xmlport=0
  3270. for o,a in opts:
  3271. if o == "-D":
  3272. hooker=imm.getKnowledge("ssl3hook")
  3273. if not hooker:
  3274. imm.log("Could not find hook to delete!")
  3275. return "Did not find hook to delete"
  3276. imm.removeHook("SSL 3 Encrypt Message")
  3277. imm.removeHook("SSL 3 Decrypt Message")
  3278. #now forget about that hook
  3279. imm.forgetKnowledge("ssl3hook")
  3280. return "Unhooked our ssl3hook"
  3281. if o == "-s":
  3282. xmlhost,xmlport = a.split(":")
  3283. xmlport=int(xmlport)
  3284. if o =="-h":
  3285. return usage(imm)
  3286.  
  3287. hooker = set_hooks()
  3288. hooker.xmlhost=xmlhost
  3289. hooker.xmlport=xmlport
  3290.  
  3291.  
  3292. # Find the addresses of the functions we want to hook
  3293. # Then register the hooks
  3294. ssl3encryptmessage = imm.getAddress("schannel._Ssl3EncryptMessage@12")
  3295. imm.log("SSL3 Encrypt Message found at 0x%x"%ssl3encryptmessage)
  3296. if ssl3encryptmessage == -1:
  3297. imm.log("Could not locate ssl3encryptmessage")
  3298. return "Failed to find address to hook!"
  3299.  
  3300. ssl3decryptmessage = imm.getAddress("schannel._Ssl3DecryptMessage@12")
  3301. imm.log("SSL3 Decrypt Message found at 0x%x"%ssl3encryptmessage)
  3302. if ssl3decryptmessage == -1:
  3303. imm.log("Could not locate ssl3encryptmessage")
  3304. return "Failed to find address to hook!"
  3305.  
  3306.  
  3307. # Set the hooks
  3308. ret=hooker.add("SSL 3 Encrypt Message", ssl3encryptmessage)
  3309. ret=hooker.add("SSL 3 Decrypt Message", ssl3decryptmessage)
  3310. imm.addKnowledge("ssl3hook",hooker)
  3311. imm.log("Hooker.add returned %s"%ret)
  3312. if ret==-1:
  3313. imm.log("Hooker add failed! :<")
  3314. return "Failed to add hook!"
  3315. # Register the hook-address pair with the knowledgebase
  3316. imm.addKnowledge("%08x" % ssl3encryptmessage, "SSL3EncryptMessage")
  3317. imm.addKnowledge("%08x" % ssl3decryptmessage, "SSL3DecryptMessage")
  3318. return "Network hooks in place."
  3319.  
  3320.  
  3321. #!/usr/bin/env python
  3322.  
  3323. ##Copyright IBM Corp. 2010
  3324. ##
  3325. ##Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at
  3326. ##
  3327. ##http://www.apache.org/licenses/LICENSE-2.0
  3328. ##
  3329. ##Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.
  3330.  
  3331. import immlib
  3332. import getopt
  3333. from libheap import *
  3334. import libdatatype
  3335.  
  3336. DESC= "Low Fragmentation Heap Viewer"
  3337. def usage(imm):
  3338. imm.log("!horse [-h HEAP_ADDR] [-b BLOCKS_ADDR] [-s Heap Bucket / SubSegment Info")
  3339. imm.log(" -h HEAPADDR Set the heap address to inspect")
  3340. imm.log(" -b BLOCKSADDR Set the _HEAP_LIST_LOOKUP block to inspect")
  3341. imm.log(" -n Find bins which are NOT being managed by the LFH")
  3342.  
  3343. def main(args):
  3344. imm = immlib.Debugger()
  3345. window = None
  3346.  
  3347. if not args:
  3348. imm.log("Please supply a valid _HEAP")
  3349. return "NO HEAP PASSED"
  3350.  
  3351. # options:
  3352. # -h HEAP
  3353. # -b Only look at specific _HEAP_LIST_LOOKUP
  3354. # -n Look for empty bins
  3355. try:
  3356. opts, argo = getopt.getopt(args, "h:nsb:")
  3357. except getopt.GetoptError:
  3358. #imm.setStatusBar("Bad heap argument %s" % args[0])
  3359. usage(imm)
  3360. return "Bad heap argument %s" % args[0]
  3361.  
  3362. heap = 0x0
  3363. lfhthreshold = 0x12
  3364. singleblock = False
  3365. blockindex = 0x0
  3366. emptybins = False
  3367. restore = False
  3368. opennewwindow = False
  3369.  
  3370. for o,a in opts:
  3371. if o == "-h":
  3372. try:
  3373. heap = int(a, 16)
  3374. except ValueError, msg:
  3375. return "Invalid heap address: %s" % a
  3376. elif o == "-b":
  3377. singleblock = True
  3378. try:
  3379. blockindex = int(a, 16)
  3380. except ValueError, msg:
  3381. return "Invalid heap address: %s" % a
  3382. elif o == "-n":
  3383. emptybins = True
  3384. elif o == "-r":
  3385. restore = True
  3386.  
  3387. if (heap and ( heap in imm.getHeapsAddress() )) or blockindex:
  3388. tag = "heap_%08x" % heap
  3389.  
  3390. if not opennewwindow:
  3391. window = imm.getKnowledge(tag)
  3392. if window and not window.isValidHandle():
  3393. imm.forgetKnowledge(tag)
  3394. del window
  3395. window = None
  3396.  
  3397. if not window:
  3398. window = imm.createTable("Heap dump 0x%08x" % heap, ["Address", "Chunks"] )
  3399. imm.addKnowledge(tag, window, force_add = 1)
  3400.  
  3401. if not heap and blockindex:
  3402. pheap = imm.getHeap(blockindex & 0xFFFF0000, restore)
  3403. else:
  3404. pheap = imm.getHeap( heap, restore )
  3405.  
  3406. if pheap and pheap.FrontEndHeapType == 0x2 and pheap.FrontEndHeap:
  3407. lfhthreshold = 0x11
  3408.  
  3409. for i in (0, len(pheap.blocks)-1):
  3410. block = pheap.blocks[i]
  3411.  
  3412. #we're looking for a specific blockindex
  3413. if singleblock:
  3414. if block.address != blockindex:
  3415. continue
  3416.  
  3417. num_of_freelists = block.ArraySize - block.BaseIndex
  3418. window.Log("Printing Block information for 0x%08x" % block.address)
  3419. window.Log("ExtendedLookup => 0x%08x" % block.ExtendedLookup)
  3420. window.Log("ArraySize [max permitted in blocks] => 0x%08x" % block.ArraySize)
  3421. window.Log("BaseIdex => 0x%08x" % block.BaseIndex)
  3422. window.Log("End Block information for 0x%08x" % block.address)
  3423. window.Log("Block has [0x%x] FreeLists starting at 0x%08x:" % (num_of_freelists, block.ListHints))
  3424.  
  3425. memory = imm.readMemory( block.ListHints, num_of_freelists * 8 )
  3426.  
  3427. for a in range(0, num_of_freelists):
  3428. free_entry = []
  3429. # Previous and Next Chunk of the head of the double linked list
  3430. (flink, heap_bucket) = struct.unpack("LL", memory[a *8 : a * 8 + 8] )
  3431.  
  3432. bin = a + block.BaseIndex
  3433.  
  3434. freelist_addr = block.ListHints + (bin - block.BaseIndex) * 8
  3435.  
  3436. if heap_bucket != 0 and not emptybins:
  3437. if heap_bucket & 1:
  3438. window.Log("Flink => 0x%08x | Bin[0x%x] enabled | Bucket => 0x%08x" % (flink, bin, heap_bucket - 1), address = freelist_addr)
  3439. elif (heap_bucket & 0x0000FFFF) >= 0x22: #there appears to be a case where the LFH isn't activated when it should be...
  3440. window.Log("Flink => 0x%08x | Bin[0x%x] ??????? | Bucket => 0x%08x" % (flink, bin, heap_bucket), address = freelist_addr)
  3441. else:
  3442. allocations = heap_bucket & 0x0000FFFF
  3443. allocations = allocations / 2
  3444. amount_needed = lfhthreshold - allocations
  3445. window.Log("Flink => 0x%08x | Bin[0x%x] has had 0x%x allocations | Needs 0x%x more" % (flink, bin, allocations, amount_needed), address = freelist_addr)
  3446. else:
  3447. if emptybins and heap_bucket == 0 and bin != 0x1 and bin != 0x0:
  3448. window.Log("Flink => 0x%08x | Bin[0x%x] is Emtpy!" % (flink, bin), address = freelist_addr)
  3449.  
  3450. window.Log("")
  3451. window.Log("=-" * 0x23 + "=")
  3452. return "Heap 0x%x dumped" % heap
  3453. else:
  3454. imm.log("Error: A proper heap or blockindex needs to be defined")
  3455. return "Error: A proper heap or blockindex needs to be defined"
  3456. #!/usr/bin/env python
  3457.  
  3458. """
  3459. (c) Immunity, Inc. 2004-2007
  3460.  
  3461.  
  3462. U{Immunity Inc.<http://www.immunityinc.com>}
  3463.  
  3464. List all pycommands with its descriptions in log window
  3465.  
  3466. """
  3467.  
  3468. DESC="""List PyCommands"""
  3469.  
  3470. import immlib
  3471. import os
  3472.  
  3473. CMD_DIR = "./PyCommands"
  3474.  
  3475. def do_dir_list(imm, path):
  3476. dir_list = os.listdir(path)
  3477. for name in dir_list:
  3478. if name[-3:] == ".py":
  3479. imm.log("* %s" % name)
  3480.  
  3481. def main(args):
  3482. imm=immlib.Debugger()
  3483.  
  3484. dir_list = os.listdir(CMD_DIR)
  3485. imm.log("List of available PyCommands")
  3486.  
  3487. for name in dir_list:
  3488. path = os.path.join(CMD_DIR, name)
  3489. if os.path.isdir(path):
  3490. do_dir_list(imm, path)
  3491. elif name[-3:] == ".py":
  3492. imm.log("* %s" % name)
  3493.  
  3494. imm.log("",focus=1)
  3495. return "See log window for results"
  3496.  
  3497. #!/usr/bin/env python
  3498.  
  3499. """
  3500. (c) Immunity, Inc. 2004-2007
  3501.  
  3502.  
  3503. U{Immunity Inc.<http://www.immunityinc.com>}
  3504. """
  3505.  
  3506. __VERSION__ = '1.0'
  3507.  
  3508. DESC = """Shows the Lookaside of the Heap structure"""
  3509.  
  3510. import immlib
  3511. from libheap import *
  3512. import getopt
  3513. import libdatatype
  3514.  
  3515. def usage(imm):
  3516. imm.log("!lookaside Shows the Lookaside of the Heap structure")
  3517. imm.log("-h Heap Address", focus=1)
  3518. imm.log("-d Discovery DataType")
  3519.  
  3520. def main(args):
  3521. imm = immlib.Debugger()
  3522. heap = 0x0
  3523. discover = None
  3524.  
  3525. if not args:
  3526. usage(imm)
  3527. return "Wrong args (Check the Log Window)"
  3528.  
  3529. try:
  3530. opts, argo = getopt.getopt(args, "h:d")
  3531. except getopt.GetoptError:
  3532. usage(imm)
  3533. return "Bad heap argument %s" % args[0]
  3534.  
  3535. for o,a in opts:
  3536. if o == "-h":
  3537. try:
  3538. heap = int(a, 16)
  3539. except ValueError, msg:
  3540. self.InfoLine("Invalid heap address: %s" % a)
  3541. return 0
  3542. elif o == '-d':
  3543. discover = libdatatype.DataTypes(imm)
  3544.  
  3545. if heap:
  3546. pheap = PHeap( imm, heap )
  3547. lookaddr = pheap.Lookaddr
  3548. imm.log("Dumping Lookaside: 0x%08x (0x%08x) " % (lookaddr, heap) )
  3549. if lookaddr:
  3550. plook = PHeapLookaside( imm, lookaddr )
  3551.  
  3552. for ndx in range(0, len(plook) ):
  3553. l = plook[ndx]
  3554. if not l.isEmpty():
  3555. imm.log("Lookaside[%02x]: " % ndx, address = l.addr)
  3556. for a in l.getList():
  3557. imm.log(" " * 15 +"> 0x%08x (%d)" % (a, ndx * 8), address = a, focus=1)
  3558. if discover:
  3559. list = discover.Get( a+4, ndx*8 - 4)
  3560. for obj in list:
  3561. imm.log(" " * 15 + "[%s] %s" % (obj.name, obj.Print()), address = obj.address )
  3562.  
  3563. return "Lookaside at 0x%08x dumped" % lookaddr
  3564. else:
  3565. usage(imm)
  3566. return "No Heap Provided"
  3567. #!/usr/bin/env python
  3568.  
  3569. """
  3570. (c) Immunity, Inc. 2004-2007
  3571.  
  3572.  
  3573. U{Immunity Inc.<http://www.immunityinc.com>}
  3574. """
  3575.  
  3576. import immlib
  3577. import getopt
  3578.  
  3579.  
  3580. __VERSION__ = '1.1'
  3581.  
  3582. DESC= "Static Analysis: Mark the tiny ones"
  3583.  
  3584. def usage(imm):
  3585. """ All the options"""
  3586. imm.log("!mark search and mark given function")
  3587. imm.log("!mark [-f NAME ] [-c COMMENT] [-m MODULE]")
  3588. imm.log("Example: mark with DANGER_MOUSE string all the strcpy ones")
  3589. imm.log("!mark -f strcpy -c DANGER_MOUSE -m ALL")
  3590.  
  3591.  
  3592. def main(args):
  3593. imm = immlib.Debugger()
  3594.  
  3595. if not args:
  3596. imm.log("### Immunity's Mark the tiny ones script###",focus=1)
  3597. imm.log("Command ok, but no args, using defaults")
  3598. try:
  3599. opts, argo = getopt.getopt(args, "f:c:m:")
  3600. except getopt.GetoptError: #get args, if error, show usage
  3601. usage(imm)
  3602. return "Bad argument %s" % args[0]
  3603.  
  3604.  
  3605. #tiny ones default list
  3606. tinyones=[]
  3607. tinyones.append("strcpy")
  3608. tinyones.append("memcpy")
  3609. tinyones.append("memmov")
  3610.  
  3611.  
  3612. module=None
  3613. function=None
  3614. function_address=0
  3615. comment="default comment"
  3616.  
  3617.  
  3618. #parsing args
  3619. for o,a in opts:
  3620. if o == "-f":
  3621. try:
  3622. function = a
  3623. function_address=imm.getAddress(function)
  3624. imm.log("%s address: 0x%8x" % (function,function_address),focus=1)
  3625. except ValueError, msg:
  3626. imm.log("No function given, using the tiny ones")
  3627. if o == "-c":
  3628. comment = a
  3629. imm.log("Comment: %s" %comment)
  3630. if o == "-m":
  3631. if a and a != "ALL":
  3632. try:
  3633. module = imm.getModule(a)
  3634. if not module:
  3635. return "Invalid module: %s" % a
  3636. else:
  3637. imm.log("module: %s" %module.getName())
  3638. base = module.getBase()
  3639. except ValueError, msg:
  3640. return "Invalid module: %s" % a
  3641. else:
  3642. regs=imm.getRegs()
  3643. module = imm.findModule(regs['EIP']) # if no module given, use the one we are standing on
  3644. if not module:
  3645. return "Module?"
  3646. else:
  3647. imm.log("module: %s" %module[0])
  3648. base=module[1]
  3649.  
  3650. #all data, find and mark
  3651. if module == "ALL":
  3652. mods = imm.getAllModules()
  3653. for mod in mods:
  3654. refaddr=imm.getInterCalls(mod.getBase())
  3655. for a in refaddr.keys():
  3656. op = imm.disasm(a)
  3657. #imm.log("op: %s"% op.comment)
  3658. decoded=imm.decodeAddress(refaddr[a][0][2]) # decode destination
  3659. if function_address != 0:
  3660. if function in decoded: #and ask if function name is in destination
  3661. imm.log("From: 0x%08x - to 0x%08x" %(a,refaddr[a][0][0]))
  3662. imm.log("Decoded destination: %s" % decoded)
  3663. imm.setComment(a,comment) #so, set your comment
  3664. else:
  3665. for function in tinyones:
  3666. if function in decoded: #and ask if function name is in destination
  3667. imm.log("From: 0x%08x - to 0x%08x" %(a,refaddr[a][0][0]))
  3668. imm.log("Decoded destination: %s" % decoded)
  3669. imm.setComment(a,comment) #so, set your comment
  3670.  
  3671.  
  3672.  
  3673. else:
  3674. regs=imm.getRegs()
  3675. refaddr=imm.getInterCalls(regs['EIP'])
  3676. for a in refaddr.keys():
  3677. op = imm.disasm(a)
  3678. #imm.log("op: %s"% op.comment)
  3679. decoded=imm.decodeAddress(refaddr[a][0][2]) # decode destination
  3680. if function_address != 0:
  3681. if function in decoded: #and ask if function name is in destination
  3682. imm.log("From: 0x%08x - to 0x%08x" %(a,refaddr[a][0][0]))
  3683. imm.log("Decoded destination: %s" % decoded)
  3684. imm.setComment(a,comment) #so, set your comment
  3685. else:
  3686. for function in tinyones:
  3687. if function in decoded: #and ask if function name is in destination
  3688. imm.log("From: 0x%08x - to 0x%08x" %(a,refaddr[a][0][0]))
  3689. imm.log("Decoded destination: %s" % decoded)
  3690. imm.setComment(a,comment) #so, set your comment
  3691.  
  3692.  
  3693. return "mark finished executing"
  3694.  
  3695.  
  3696. import getopt
  3697. import struct
  3698. import time
  3699. import sys
  3700. import threading
  3701.  
  3702. from immutils import *
  3703. from immlib import *
  3704. from libstackanalyze import *
  3705. from graphclass import *
  3706. from immvcglib import *
  3707. from socket import *
  3708.  
  3709. DESC="""Attempts to automate tracing the lifecycle of a packet's contents."""
  3710.  
  3711. #############################################################################
  3712. '''
  3713. Some defines for re-use.
  3714. '''
  3715. PACKET_TYPE_SEND = "Send "
  3716. PACKET_TYPE_RECV = "Recv "
  3717. PACKET_PROTOCOL_UDP = "(UDP)"
  3718. PACKET_PROTOCOL_TCP = "(TCP)"
  3719.  
  3720. #############################################################################
  3721. class packet_analyzer(BpHook):
  3722.  
  3723. #########################################################################
  3724. def __init__(self, address, hook_type):
  3725.  
  3726. BpHook.__init__(self)
  3727. self.begin_address = address
  3728. self.imm = Debugger()
  3729. self.graph = Graph()
  3730. self.draw = Draw()
  3731. self.buf = []
  3732. self.nodes_buf = []
  3733. self.nodes = []
  3734. self.edges_buf = []
  3735. self.func_start = None
  3736. self.func_end = None
  3737. self.graph_handler = None
  3738. self.last_bb = None
  3739. self.hook_type = hook_type
  3740. self.first_func_finished = False
  3741. self.bb_end = True
  3742. self.node_count = 0
  3743. self.node_covered = {}
  3744. self.active_node = ""
  3745.  
  3746. #########################################################################
  3747. def run(self, regs):
  3748. '''
  3749. This is the main hook routine that occurs at [ESP] of a socket
  3750. function call. It kicks off the whole process of sniffing the
  3751. packet, graphing, and analyzing it.
  3752. '''
  3753.  
  3754. session = self.imm.getKnowledge("session")
  3755. if session == True:
  3756. self.imm.forgetKnowledge("session")
  3757. self.imm.addKnowledge("session", False, force_add=0x1)
  3758. else:
  3759. self.imm.run()
  3760. return
  3761.  
  3762.  
  3763. # Now we determine what type of packet sniff we need to do
  3764. if self.hook_type == "simple":
  3765. if self.simple_packet_sniff(regs) == False:
  3766. return
  3767. else:
  3768. if self.extended_packet_sniff(regs) == False:
  3769. return
  3770.  
  3771. # Make sure that the module has been analyzed.
  3772. if self.imm.isAnalysed(self.begin_address) != 1:
  3773. self.imm.analyseCode(self.begin_address)
  3774.  
  3775. # Workaround for EIP == functionBegin address
  3776. if self.begin_address == regs['EIP']:
  3777. self.func_start = self.regs['EIP']
  3778. else:
  3779. self.func_start = self.imm.getFunctionBegin(self.begin_address)
  3780.  
  3781. # Once we have the function information set some variables
  3782. func = self.imm.getFunction(self.func_start)
  3783. self.func_end = func.getEnd()
  3784. func_name = func.getName()
  3785.  
  3786. # Setup the VCG header, add the first basic block and return
  3787. self.start_graph(func_name)
  3788.  
  3789. # Now we enter into a step-over routine where we will begin
  3790. # tracing the execution/data flow of our packet, initialize the
  3791. # code coverage counter beforehand
  3792. self.imm.addKnowledge("code_coverage",0,force_add = 0x1)
  3793. self.deep_analysis_loop(regs)
  3794.  
  3795. # This stitches all the buffers together and splashes the graph
  3796. self.render_graph()
  3797.  
  3798. # We need to clear out the knowledgebase so let's grab the information
  3799. # we want to keep first
  3800. boo_address = self.imm.getKnowledge("boo_address")
  3801. boo_port = self.imm.getKnowledge("boo_port")
  3802. test_port = self.imm.getKnowledge("test_port")
  3803. test_protocol = self.imm.getKnowledge("test_protocol")
  3804.  
  3805. # Disable the breakpoint or this hooer will get hit again
  3806. #self.imm.disableBreakpoint(self.begin_address)
  3807.  
  3808. boo = boo_comm(boo_address,boo_port,test_port,test_protocol)
  3809. boo.prepare_next_case()
  3810.  
  3811.  
  3812.  
  3813. self.imm.run()
  3814. # Give it some time to finish up any of its previous loops
  3815. #packet.send_test_packet()
  3816.  
  3817.  
  3818.  
  3819. #########################################################################
  3820. def deep_analysis_loop(self, regs):
  3821. '''
  3822. This is the loop that steps the instruction pointer, determines
  3823. branching decisions, and does the data analysis.
  3824. '''
  3825.  
  3826. loop_status = True
  3827.  
  3828. # We do the first instruction first, then enter a loop of stepping
  3829. # to analyze the rest of the code paths
  3830. self.imm.gotodisasmWindow(regs['EIP'])
  3831. loop_status, processed_reg, step_type = self.opcode_processor(regs)
  3832.  
  3833. # Begin the analysis loop, go grab a coffee this can take awhile
  3834. while loop_status == True:
  3835.  
  3836. # Determine whether we want to step over or in
  3837. if step_type == "in":
  3838. self.imm.stepIn()
  3839. else:
  3840. self.imm.stepOver()
  3841.  
  3842. stepped_regs = self.imm.getRegs()
  3843.  
  3844. if self.imm.isAnalysed(stepped_regs['EIP']) != 1:
  3845. self.imm.analyseCode(stepped_regs['EIP'])
  3846.  
  3847. # Test if we landed inside a system DLL
  3848. if self.test_system_dll(stepped_regs['EIP']) == True and self.first_func_finished == True or self.imm.isRunning() == True:
  3849. break
  3850.  
  3851. # The opcode processor does all of the dirty work
  3852. loop_status, processed_reg, step_type = self.opcode_processor(stepped_regs)
  3853.  
  3854. return
  3855.  
  3856.  
  3857.  
  3858. #########################################################################
  3859. def opcode_processor(self, regs):
  3860.  
  3861. step_type = "over"
  3862. loop_status = True
  3863.  
  3864.  
  3865. # Grab the opcode from the address (EIP)
  3866. opcode = self.imm.disasm(regs['EIP'])
  3867.  
  3868. # Register the code coverage hit
  3869. code_coverage = self.imm.getKnowledge("code_coverage")
  3870. self.imm.forgetKnowledge("code_coverage")
  3871. code_coverage += 1
  3872. self.imm.addKnowledge("code_coverage",code_coverage,force_add=0x1)
  3873.  
  3874. # For call instructions, if its calling into a non-system module
  3875. # then we want to follow it. Otherwise the graph would explode.
  3876. if opcode.isCall() == 1:
  3877. if self.test_system_dll(opcode.jmpaddr) == False:
  3878. step_type = "in"
  3879.  
  3880.  
  3881. # The threshold is a way to prematurely terminate the analysis, otherwise
  3882. # you can go wandering off in threading routines, garbage collection stuff, etc.
  3883. # Break the loop if the threshold has been hit.
  3884. threshold = self.imm.getKnowledge("threshold")
  3885.  
  3886. if code_coverage >= threshold:
  3887. loop_status = False
  3888.  
  3889.  
  3890. if self.first_func_finished == True:
  3891.  
  3892. # Now let's send the information off to our graphing function
  3893. if self.bb_end == True:
  3894. self.add_node_header(regs['EIP'])
  3895. self.bb_end = False
  3896.  
  3897. if opcode.isJmp() == 1 or opcode.isRet() == 1 or opcode.isConditionalJmp() == 1 or loop_status == False or step_type == "in":
  3898. self.bb_end = True
  3899.  
  3900.  
  3901.  
  3902. info_panel = self.imm.getInfoPanel()
  3903. comment = self.imm.getComment(regs['EIP'])
  3904.  
  3905. # Add the instructions, information and comments to the graph.
  3906. self.add_node_instructions(regs['EIP'],opcode,comment,info_panel)
  3907.  
  3908. # We want to step into RET instructions so that we correctly get
  3909. # back to the callee
  3910. if opcode.isRet() == 1:
  3911. #self.imm.log("Ret Destination: 0x%08x" % opcode.jmpaddr)
  3912.  
  3913. if self.first_func_finished == False:
  3914. self.first_func_finished = True
  3915.  
  3916. if self.test_system_dll(opcode.jmpaddr) == True:
  3917. loop_status = False
  3918.  
  3919. return loop_status, regs['EIP'], step_type
  3920.  
  3921.  
  3922. #########################################################################
  3923. def test_system_dll(self, address):
  3924. '''
  3925. This function is designed to take an address and return whether
  3926. it lies within a system DLL.
  3927. '''
  3928.  
  3929. jmp_module = self.imm.getModuleByAddress(address)
  3930.  
  3931. if jmp_module is not None:
  3932. system_dll = jmp_module.getIssystemdll()
  3933.  
  3934. # We test here, as well the msvcr71.dll is really a system dll
  3935. # but a lot of developers redistribute, treat it as such
  3936. if system_dll == 1 or jmp_module.name.lower() == "msvcr71.dll":
  3937. return True
  3938. else:
  3939. return False
  3940.  
  3941. return None
  3942.  
  3943. #########################################################################
  3944. def start_graph(self, func_name):
  3945. '''
  3946. This just sets up the graphing header, and initializes the graphing routine.
  3947. '''
  3948.  
  3949. # Now we do a bunch of VCG lovin to get the graph setup the way we want it
  3950. # this part of the code was taken directly from immvcglib.py and should not
  3951. # be included as part of the judging criteria
  3952. iteration = self.imm.getKnowledge("current_iteration")
  3953. if iteration != 0 and iteration is not None:
  3954. self.node_covered = self.imm.getKnowledge("node_covered")
  3955. else:
  3956. iteration = 0
  3957.  
  3958. self.buf.append('graph: {\x0d\x0a')
  3959. self.buf.append('title: "Packet Life (%s - Iteration: %d)"\r\n' % (self.imm.getDebuggedName(),iteration))
  3960. self.buf.append("manhattan_edges: yes\r\n")
  3961. self.buf.append("layoutalgorithm: mindepth\r\n")
  3962. self.buf.append("finetuning: no\r\n")
  3963. self.buf.append("layout_downfactor: 100\r\n")
  3964. self.buf.append("layout_upfactor: 0\r\n")
  3965. self.buf.append("layout_nearfactor: 0\r\n")
  3966. self.buf.append("xlspace: 12\r\n")
  3967. self.buf.append("yspace: 30\r\n")
  3968. self.buf.append("display_edge_labels: yes\r\n")
  3969. self.buf.append("colorentry 99: 193 255 193\r\n")
  3970. self.buf.append("colorentry 100: 238 233 233\r\n")
  3971. self.buf.append("colorentry 98: 255 69 0\r\n")
  3972. self.buf.append("colorentry 97: 0 139 0\r\n")
  3973.  
  3974. #########################################################################
  3975. def add_node_header(self,address):
  3976. '''
  3977. Adds the first node to the graph, this will be the function that called
  3978. the receive socket operation.
  3979. '''
  3980. decode_address = self.imm.decodeAddress(address)
  3981.  
  3982. # Start a new node by creating the header.
  3983. if self.node_covered.has_key(address):
  3984. self.active_node += 'node: { title: "%s" color: \f100 vertical_order: %d label:"\r\n\x0c31%s\x0c31\r\n\r\n' % (decode_address,self.node_count,decode_address)
  3985. else:
  3986. self.active_node += 'node: { title: "%s" color: \f99 vertical_order: %d label:"\r\n\x0c31%s\x0c31\r\n\r\n' % (decode_address,self.node_count,decode_address)
  3987. self.node_covered[address] = True
  3988.  
  3989. self.nodes.append(decode_address)
  3990. self.node_count += 1
  3991.  
  3992. #########################################################################
  3993. def add_node_instructions(self, address,opcode,comment=None,infopanel=None):
  3994. '''
  3995. Adds the current instruction, associated comments and information.
  3996. '''
  3997.  
  3998. self.active_node += "\f310x%08x: \f12%s\r\n" % (address, opcode.result)
  3999.  
  4000. if comment is not None and comment != "":
  4001. if opcode.isCall() == 1:
  4002. self.active_node += " \t\t\t\f98%s\r\n" % (comment.replace("\"", ""))
  4003. else:
  4004. self.active_node += " \t\t\t\f01%s\r\n" % (comment.replace("\"", ""))
  4005.  
  4006. if infopanel is not None and infopanel != "":
  4007. # Here we do matching against the packet contents and
  4008. # what is registered in the infopanel
  4009. self.data_match(opcode,infopanel)
  4010.  
  4011. self.active_node += "\r\n"
  4012. if self.bb_end == True:
  4013. self.active_node += "\r\n\"}\r\n"
  4014. self.last_bb = address
  4015. self.nodes_buf.append(self.active_node)
  4016. self.active_node = ""
  4017.  
  4018.  
  4019. #########################################################################
  4020. def data_match(self,opcode,infopanel):
  4021.  
  4022. self.imm.log("In Data Match ++++++++++++++")
  4023.  
  4024. matched = False
  4025. sub_info = []
  4026.  
  4027. # Clean up the output a little
  4028. for info in infopanel:
  4029. if info != "":
  4030. sub_info.append(info)
  4031.  
  4032. for data in sub_info:
  4033.  
  4034. if data.find("=") != -1:
  4035.  
  4036. clean_data = data.split("=")[1]
  4037.  
  4038. op_left = opcode.result.split(" ")[0]
  4039. self.imm.log("Front Opcode: %s" % cmp)
  4040.  
  4041. # Check for the packet length
  4042. packet_length = "%08x" % self.imm.getKnowledge("packet_length")
  4043.  
  4044. self.imm.log("Comparing %s <-> %s" % (packet_length,clean_data))
  4045. if clean_data.lower() == packet_length.lower():
  4046. self.active_node += " \t\t\t\f08%s \f02(Packet Length)\r\n" % data.replace("\"","\\\"")
  4047. self.imm.log("Possible Packet Length Match++++++++++++++++++++++++++++")
  4048. matched = True
  4049.  
  4050. if matched == False:
  4051. ascii_packet = self.imm.getKnowledge("ascii_packet")
  4052. binary_packet = self.imm.getKnowledge("binary_packet")
  4053.  
  4054. # Now let's begin matching the payload junk (I suck at this, many improvements can be made)
  4055. # Check for ASCII references
  4056. clean_data = data.split("ASCII")
  4057. self.imm.log("Cleaned Split: %s" % clean_data)
  4058. if clean_data != "" and clean_data[0] != data:
  4059. match = clean_data[1].replace("\"","").replace(")","").strip()
  4060. self.imm.log("MATCH: %s -------------------------------------------------" % match)
  4061. self.imm.log("PACKE: %s -------------------------------------------------" % ascii_packet)
  4062. if ascii_packet.rfind(match) != -1:
  4063. self.active_node += " \t\t\t\f08%s \f09(Packet Payload)\r\n" % data.replace("\"","\\\"")
  4064. self.imm.log("Wooot========================================")
  4065. matched = True
  4066.  
  4067. # Now let's see if there is any binary matches such as ESI=41424344
  4068. # again, not perfect but it should work well
  4069. if matched == False:
  4070. clean_data = data.split("=")
  4071. if clean_data != "" and clean_data[0] != data:
  4072.  
  4073. for bin in clean_data:
  4074. match = bin.replace("\"","").replace("(","").replace("[","").replace("]","").strip()
  4075. self.imm.log("MATCH: %s -------------------------------------------------" % match)
  4076. self.imm.log("PACKE: %s -------------------------------------------------" % binary_packet)
  4077.  
  4078. if binary_packet.rfind(match) != -1 or binary_packet[::-1].rfind(match) != -1:
  4079. self.active_node += " \t\t\t\f08%s \f97(Packet Payload)\r\n" % data.replace("\"","\\\"")
  4080. self.imm.log("Wooot========================================")
  4081. matched = True
  4082.  
  4083. # We didn't find any matches at all, output default info
  4084. if matched == False:
  4085. self.active_node += " \t\t\t\f08%s\r\n" % data.replace("\"","\\\"")
  4086.  
  4087. else:
  4088. self.active_node += " \t\t\t\f08%s\r\n" % data.replace("\"","\\\"")
  4089.  
  4090.  
  4091.  
  4092.  
  4093.  
  4094.  
  4095.  
  4096. #########################################################################
  4097. def render_graph(self):
  4098. '''
  4099. This function assembles the nodes_buf and the edges_buf for the overall
  4100. graph, and pushes it to the screen.
  4101. '''
  4102.  
  4103. for a in range(0,len(self.nodes_buf)):
  4104. self.buf.append(self.nodes_buf[a])
  4105.  
  4106. self.buf.append("\r\n")
  4107. for a in range(0,len(self.nodes)):
  4108. if a < len(self.nodes)-1:
  4109. self.buf.append('edge: { sourcename: "%s" targetname: "%s" color: darkgreen }\r\n' % (self.nodes[a],self.nodes[a+1]))
  4110.  
  4111. self.buf.append("\n}\r\n")
  4112.  
  4113. # Send the graph back to Boo for storage
  4114. boo_port = self.imm.getKnowledge("boo_port")
  4115. boo_address = self.imm.getKnowledge("boo_address")
  4116. test_port = self.imm.getKnowledge("test_port")
  4117. test_protocol = self.imm.getKnowledge("test_protocol")
  4118. iteration = self.imm.getKnowledge("current_iteration")
  4119. version = self.imm.getModule(self.imm.getDebuggedName()).getVersion()
  4120.  
  4121. s = socket(AF_INET,SOCK_STREAM)
  4122.  
  4123. s.connect((boo_address,int(boo_port)))
  4124.  
  4125.  
  4126. message = "graph|%s|%s|%d|%s|%d|%s||\r\n" % (self.imm.getDebuggedName(),version,int(test_port),test_protocol,int(iteration),"".join(self.buf))
  4127. self.imm.log("%s" % message)
  4128. s.send(message)
  4129.  
  4130.  
  4131.  
  4132.  
  4133. self.imm.addKnowledge("node_covered", self.node_covered,force_add=0x1)
  4134.  
  4135. #########################################################################
  4136. def simple_packet_sniff(self, regs):
  4137. '''
  4138. The simple packet sniff is one where we merely have a pointer
  4139. to the buffer and a length. It's very easy to read the packets
  4140. out of memory.
  4141. '''
  4142.  
  4143. (payload_ptr, type, function_name) = self.imm.getKnowledge("%08x" % regs['EIP'])
  4144.  
  4145. # The length is stored as a function return argument, so let's read EAX
  4146. length = regs['EAX']
  4147.  
  4148. try:
  4149. # Because return codes can be -1 (error) we have to test for that.
  4150. if length > 1 and length != 0xffffffff:
  4151.  
  4152. counter = 0
  4153. payload = ""
  4154. bin_payload = ""
  4155.  
  4156. # Get the raw packet payload and the length of the bytes
  4157. raw_payload = self.imm.readMemory(payload_ptr, length)
  4158. pack_len = str(length)+"c"
  4159.  
  4160. if raw_payload is not None:
  4161.  
  4162. final_payload = struct.unpack(pack_len, raw_payload)
  4163.  
  4164. # Iterate through the unpacked string, only outputting printable
  4165. # ascii characters, output the standard dots if non-printable
  4166. while counter < int(length):
  4167. if ord(final_payload[counter]) >= 32 and ord(final_payload[counter]) <= 126:
  4168. payload += final_payload[counter]
  4169. else:
  4170. payload += "."
  4171.  
  4172. bin_payload += "%02x" % ord(final_payload[counter])
  4173. counter += 1
  4174.  
  4175. # Build the list thats table-friendly
  4176. log_items = [function_name, type, "%d" % int(length), bin_payload[:512], payload[:512]]
  4177.  
  4178. # Add the packet to the knowledgebase
  4179. self.imm.addKnowledge("binary_packet", bin_payload, force_add=0x1)
  4180. self.imm.addKnowledge("ascii_packet", payload, force_add=0x1)
  4181. self.imm.addKnowledge("packet_length", int(length[0]),force_add=0x1)
  4182.  
  4183. # Get a handle to the window and add the items, along with the related
  4184. # address, this is sweet cause you can double-click on a packet and
  4185. # see in the disassembly where it was sent/received :)
  4186. cap_win = self.imm.getKnowledge("cap_win")
  4187. cap_win.add(regs['EIP'], log_items)
  4188.  
  4189. #self.imm.disableBreakpoint(regs['EIP'])
  4190. except:
  4191. return False
  4192.  
  4193. #########################################################################
  4194. def extended_packet_sniff(self, regs):
  4195. '''
  4196. This is for the WSA* family of socket functions where we have to
  4197. do more pointer manipulation and there's a bit more work involved
  4198. in getting the packets.
  4199. '''
  4200.  
  4201. (payload_ptr, recv_ptr, type, function_name) = self.imm.getKnowledge("%08x" % regs['EIP'])
  4202.  
  4203. # This is an [out] pointer that let's us know how much data was
  4204. # received on a socket (non-overlapped)
  4205. length = self.imm.readMemory(recv_ptr, 4)
  4206. length = struct.unpack("l", length)
  4207.  
  4208. try:
  4209. # Network apps are chatty, we don't want to grab garbage packets
  4210. if length[0] > 1:
  4211.  
  4212. counter = 0
  4213. payload = ""
  4214. bin_payload = ""
  4215.  
  4216. # Get the raw packet payload and the length of the bytes
  4217. raw_payload = self.imm.readMemory(payload_ptr, int(length[0]))
  4218. pack_len = str(int(length[0]))+"c"
  4219.  
  4220. if raw_payload is not None:
  4221.  
  4222. final_payload = struct.unpack(pack_len, raw_payload)
  4223.  
  4224. # Iterate through the unpacked string, only outputting printable
  4225. # ascii characters, output the standard dots if non-printable
  4226. while counter < int(length[0]):
  4227. if ord(final_payload[counter]) >= 32 and ord(final_payload[counter]) <= 126:
  4228. payload += final_payload[counter]
  4229. else:
  4230. payload += "."
  4231.  
  4232. bin_payload += "%02x" % ord(final_payload[counter])
  4233. counter += 1
  4234.  
  4235. # Build the list thats table-friendly
  4236. log_items = [function_name, type, "%d" % int(length[0]), bin_payload[:512], payload[:512]]
  4237.  
  4238. # Add the packet to the knowledgebase
  4239. self.imm.addKnowledge("binary_packet", bin_payload, force_add=0x1)
  4240. self.imm.addKnowledge("ascii_packet", payload, force_add=0x1)
  4241. self.imm.addKnowledge("packet_length", int(length[0]),force_add=0x1)
  4242.  
  4243. # Get a handle to the window and add the items, along with the related
  4244. # address, this is sweet cause you can double-click on a packet and
  4245. # see in the disassembly where it was sent/received :)
  4246. cap_win = self.imm.getKnowledge("cap_win")
  4247. cap_win.add(regs['EIP'], log_items)
  4248.  
  4249. #self.imm.disableBreakpoint(regs['EIP'])
  4250. except:
  4251. return False
  4252. #############################################################################
  4253. class set_hooks(LogBpHook):
  4254.  
  4255. #########################################################################
  4256. def __init__(self):
  4257.  
  4258. LogBpHook.__init__(self)
  4259. self.imm = Debugger()
  4260.  
  4261.  
  4262. #########################################################################
  4263. def create_hooks(self):
  4264. '''
  4265. This creates the original hooks on the common socket receive functions,
  4266. this is not comprehensive but it should catch most socket operations.
  4267. Future enhancements will include all possible socket operations.
  4268. '''
  4269.  
  4270. ws_wsarecv = self.imm.getAddress("ws2_32.WSARecv")
  4271. ws_wsasend = self.imm.getAddress("ws2_32.WSASend")
  4272. ws_recv = self.imm.getAddress("ws2_32.recv")
  4273. ws_recvfrom = self.imm.getAddress("ws2_32.recvfrom")
  4274.  
  4275. # Set the hooks
  4276. current_iteration = self.imm.getKnowledge("current_iteration")
  4277. if current_iteration == 0:
  4278. self.add("WSARecv", ws_wsarecv)
  4279. self.add("WSASend", ws_wsasend)
  4280. self.add("recv", ws_recv)
  4281. self.add("recvfrom", ws_recvfrom)
  4282.  
  4283. # Register the hook-address pair with the knowledgebase
  4284. self.imm.addKnowledge("%08x" % ws_wsarecv, "WSARecv",force_add=0x1)
  4285. self.imm.addKnowledge("%08x" % ws_wsasend, "WSASend",force_add=0x1)
  4286. self.imm.addKnowledge("%08x" % ws_recv, "recv",force_add=0x1)
  4287. self.imm.addKnowledge("%08x" % ws_recvfrom, "recvfrom",force_add=0x1)
  4288.  
  4289. #########################################################################
  4290. def retrieve_packet(self, function_name, regs):
  4291. '''
  4292. This function determines how to handle the packet data. Some socket
  4293. operations require more work (such as WSARecv), and others less (recv).
  4294.  
  4295. If necessary this function will register a hook on [ESP], where any
  4296. [out] pointers from a function will be set.
  4297. '''
  4298.  
  4299. extended_hook = None
  4300.  
  4301. # Determine what function we have hooked, based on this, retrieve the packet contents
  4302. if function_name == "WSARecv":
  4303. type = PACKET_TYPE_RECV+PACKET_PROTOCOL_TCP
  4304. extended_hook = True
  4305.  
  4306. if function_name == "WSASend":
  4307. type=PACKET_TYPE_SEND+PACKET_PROTOCOL_TCP
  4308. extended_hook = True
  4309.  
  4310. if function_name == "recvfrom":
  4311. type=PACKET_TYPE_RECV+PACKET_PROTOCOL_UDP
  4312. extended_hook = False
  4313.  
  4314. if function_name =="recv":
  4315. type=PACKET_TYPE_RECV+PACKET_PROTOCOL_TCP
  4316. extended_hook = False
  4317.  
  4318. if extended_hook is None:
  4319. self.imm.addKnowledge("session", False, force_add=0x1)
  4320. return
  4321.  
  4322. # An extended hook requires a bit more work to pull out the packet info
  4323. if extended_hook == True:
  4324.  
  4325. # Get the pointer to the payload pointer :(
  4326. pbuffer_ptr = self.imm.readMemory(regs['ESP'] + 8, 4)
  4327. pbuffer_ptr = struct.unpack("L", pbuffer_ptr)
  4328.  
  4329. # Get the pointer to the packet payload
  4330. payload_ptr = self.imm.readMemory(pbuffer_ptr[0]+4, 4)
  4331. payload_ptr = struct.unpack("<L", payload_ptr)
  4332.  
  4333. # Get the [out] pointer of the received bytes
  4334. recv_ptr = self.imm.readMemory(regs['ESP'] + 0x10, 4)
  4335. recv_ptr = struct.unpack("L", recv_ptr)
  4336.  
  4337. # Figure out [esp]
  4338. esp_ptr = self.imm.readMemory(regs['ESP'], 4)
  4339. esp_ptr = struct.unpack("<L", esp_ptr)
  4340.  
  4341. # Now we hook [esp] if this isn't the first iteration, don't reset the hook
  4342. ret_hook = packet_analyzer(esp_ptr[0], "ext_hook")
  4343. ret_hook.add("%08x" % esp_ptr[0], esp_ptr[0])
  4344.  
  4345. # Add this ret hook to the knowledgebase
  4346. self.imm.addKnowledge("%08x" % esp_ptr[0], (payload_ptr[0], recv_ptr[0], type, function_name),force_add=0x1)
  4347.  
  4348. else:
  4349.  
  4350. # Get the pointer to the buffer
  4351. payload_ptr = self.imm.readMemory(regs['ESP'] + 8, 4)
  4352. payload_ptr = struct.unpack("L", payload_ptr)
  4353.  
  4354. # Figure out where [ESP] points to
  4355. esp_ptr = self.imm.readMemory(regs['ESP'], 4)
  4356. esp_ptr = struct.unpack("<L", esp_ptr)
  4357.  
  4358. # Add the [ESP] hook for when the function returns
  4359.  
  4360. simple_hook = packet_analyzer(esp_ptr[0], "simple")
  4361. simple_hook.add("%08x" % esp_ptr[0], esp_ptr[0])
  4362.  
  4363. # Add our pertinent information to the knowledgebase
  4364. self.imm.addKnowledge("%08x" % esp_ptr[0], (payload_ptr[0], type, function_name),force_add=0x1)
  4365.  
  4366.  
  4367.  
  4368. #########################################################################
  4369. def run(self, regs):
  4370. '''
  4371. This routine is the first one hit, when a socket operation occurs.
  4372. '''
  4373.  
  4374. # Determine if we are in the middle of an analysis session
  4375. session = self.imm.getKnowledge("session")
  4376.  
  4377. # Retrieve the function name
  4378. function_name = self.imm.getKnowledge("%08x" % regs['EIP'])
  4379.  
  4380. # Clear the breakpoint
  4381. self.retrieve_packet(function_name, regs)
  4382.  
  4383.  
  4384. class boo_comm():
  4385.  
  4386. def __init__(self,boo_address,boo_port,test_port,test_protocol):
  4387.  
  4388. self.imm = Debugger()
  4389. self.boo_address = boo_address
  4390. self.boo_port = int(boo_port)
  4391. self.boo_sock = socket(AF_INET,SOCK_STREAM)
  4392. self.test_port = int(test_port)
  4393. self.test_protocol = test_protocol
  4394.  
  4395. def notify(self,message):
  4396.  
  4397. self.imm.log("Boo Port: %d Boo Address: %s" % (self.boo_port,self.boo_address))
  4398.  
  4399. if message == "begin_test":
  4400. self.imm.addKnowledge("session", True, force_add=0x1)
  4401.  
  4402. message = message + "|" + str(self.test_port) + "|" + self.test_protocol
  4403.  
  4404. try:
  4405. self.boo_sock.connect((self.boo_address,self.boo_port))
  4406. except:
  4407. self.imm.log("Couldn't connect to Boo! Poor thing...")
  4408. return
  4409. # We notify boo we are ready to begin
  4410.  
  4411. # Double pipe is our delimiter
  4412. message = message + "||\r\n"
  4413.  
  4414.  
  4415. self.boo_sock.send(message)
  4416.  
  4417. self.boo_sock.close()
  4418.  
  4419.  
  4420.  
  4421. def prepare_next_case(self):
  4422.  
  4423. # We need to clear the knowledgebase so grab the packet first, as well the capture window
  4424. binary_packet = self.imm.getKnowledge("binary_packet")
  4425. ascii_packet = self.imm.getKnowledge("ascii_packet")
  4426. code_coverage = self.imm.getKnowledge("code_coverage")
  4427. current_iteration = self.imm.getKnowledge("current_iteration")
  4428. threshold = self.imm.getKnowledge("threshold")
  4429. new_threshold = threshold + 25
  4430.  
  4431. # Now re-add the information in a list called iteration
  4432. self.imm.addKnowledge("iteration_%d" % current_iteration, (code_coverage,binary_packet,ascii_packet),force_add=0x1)
  4433.  
  4434. # Output some test results
  4435. self.imm.log("=====================================================")
  4436. self.imm.log("Test Results for Iteration: %d" % current_iteration)
  4437. self.imm.log("")
  4438. self.imm.log("Code Coverage: %d (Threshold %d)" % (code_coverage,threshold))
  4439. self.imm.log("Binary Packet: %s" % binary_packet)
  4440. self.imm.log("ASCII Packet: %s" % ascii_packet)
  4441. self.imm.log("")
  4442. self.imm.log("Increasing Threshold to: %d" % new_threshold)
  4443. self.imm.log("=====================================================")
  4444.  
  4445.  
  4446.  
  4447. # Track the iteration number
  4448. self.imm.addKnowledge("threshold", new_threshold, force_add=0x1)
  4449.  
  4450. current_iteration += 1
  4451. self.imm.addKnowledge("current_iteration", current_iteration, force_add=0x1)
  4452. self.imm.run()
  4453.  
  4454.  
  4455.  
  4456. #############################################################################
  4457. def usage(imm):
  4458. '''
  4459. Prints the usage information for this pycommand.
  4460. '''
  4461.  
  4462. imm.log("!mike BOOADDRESS BOOPORT TESTPORT PROTOCOL - Sulley's best friend, it analyzes a protocol and outputs graphs and Sulley scripts. Get the process running first!")
  4463. imm.log("eg. !mike 192.168.7.1 1337")
  4464.  
  4465.  
  4466.  
  4467. #############################################################################
  4468. def main(args):
  4469. '''
  4470. This is the main routine when a PyCommand is run. This creates the window object,
  4471. sets the hooks and then fires out a test packet.
  4472. '''
  4473.  
  4474. imm = Debugger()
  4475. # Check commandline args, I hate this part :)
  4476. if not args:
  4477. usage(imm)
  4478. return "Usage information outputted please check the log window"
  4479.  
  4480. imm.ignoreSingleStep("CONTINUE")
  4481.  
  4482. # Create the packet capture window
  4483. column_titles = ["Function", "Type", "Length", "Binary", "ASCII"]
  4484. cap_win = imm.createWindow("Captured Packets", column_titles)
  4485.  
  4486. # Add the window to the knowledge base, and monitor whether the
  4487. # analysis session is active
  4488. imm.addKnowledge("cap_win", cap_win, force_add=0x1)
  4489.  
  4490.  
  4491. # Set the hooks on the socket operations.
  4492. try:
  4493. hooker = set_hooks()
  4494. hooker.create_hooks()
  4495.  
  4496. except:
  4497.  
  4498. return "Can't find exported socket functions."
  4499.  
  4500. # Track the iteration number
  4501. imm.addKnowledge("current_iteration", 0, force_add = 0x1)
  4502.  
  4503.  
  4504. # We kick the testing off by using a known test packet to begin
  4505. # the attempt at reversing the protocol
  4506. boo_address = args[0]
  4507. boo_port = args[1]
  4508. test_port = args[2]
  4509. test_protocol = args[3]
  4510. threshold = 50
  4511.  
  4512. imm.addKnowledge("boo_address", boo_address,force_add=0x1)
  4513. imm.addKnowledge("boo_port", boo_port,force_add=0x1)
  4514. imm.addKnowledge("threshold", threshold,force_add=0x1)
  4515. imm.addKnowledge("test_port", test_port,force_add=0x1)
  4516. imm.addKnowledge("test_protocol", test_protocol,force_add=0x1)
  4517.  
  4518. boo = boo_comm(boo_address,boo_port,test_port,test_protocol)
  4519. boo.notify("begin_test")
  4520.  
  4521. return "Network hooks in place."
  4522.  
  4523.  
  4524.  
  4525. #!/usr/bin/env python
  4526.  
  4527. """
  4528. (c) Immunity, Inc. 2004-2007
  4529.  
  4530.  
  4531. U{Immunity Inc.<http://www.immunityinc.com>}
  4532.  
  4533. modptr
  4534. """
  4535. __VERSION__ = '1.0'
  4536.  
  4537. DESC="""!modptr Patch all Function Pointers and detect when they triggered """
  4538.  
  4539.  
  4540. import immlib
  4541. import immutils
  4542. import libdatatype
  4543. import getopt
  4544. from immlib import AccessViolationHook
  4545.  
  4546. INDEXER = 0xb4000000
  4547. INDEX_MASK = 0xFF000000
  4548. FNDX_MASK = 0x00FFFFFF
  4549.  
  4550. def usage(imm):
  4551. imm.log("!modptr Patch all Function Pointers and detect when they triggered")
  4552. imm.log("! -a address")
  4553. imm.log("! -x 0xADDR[,0xADDR...] (Addresses to exclude)")
  4554. imm.log(" [Note: it will patch all the function pointer on the memory pages of the given address]")
  4555. return "Usage: !modptr -a ADDRESS"
  4556.  
  4557. # Access Violation Hook class
  4558. class FunctionTriggeredHook(AccessViolationHook):
  4559. def __init__( self, fn_ptr):
  4560. AccessViolationHook.__init__( self )
  4561. #self.threadid = threadid
  4562. self.fn_ptr = fn_ptr
  4563.  
  4564. # found the access violation we force by patching every function pointer.
  4565. # Recognise what pointer is and show it on Log Window
  4566. def run(self, regs):
  4567. imm = immlib.Debugger()
  4568.  
  4569. eip = regs['EIP']
  4570. # Checking if we are on the correct Access Violation
  4571. if ( eip & INDEX_MASK ) != INDEXER:
  4572. return ""
  4573. fndx = eip & FNDX_MASK
  4574. if fndx >= len( self.fn_ptr ) :
  4575. return ""
  4576.  
  4577. obj = self.fn_ptr[ fndx ] # it shouldn't be out of index
  4578.  
  4579. # Print info and Unhook
  4580. imm.log("Found a pointer at 0x%08x that triggers: " % obj.address, address = obj.address, focus =1 )
  4581. imm.log(" %s: %s" % ( obj.name, obj.Print() ), address = obj.address)
  4582.  
  4583. imm.setReg("EIP", int(obj.data) )
  4584. imm.run()
  4585. #self.UnHook()
  4586.  
  4587. def main(args):
  4588. imm = immlib.Debugger()
  4589. if not args:
  4590. return usage(imm)
  4591.  
  4592. exclude = []
  4593. address = None
  4594.  
  4595. try:
  4596. opts, argo = getopt.getopt(args, "a:x:")
  4597. except getopt.GetoptError:
  4598. usage(imm)
  4599. return "Wrong Argument (Check Log Window)"
  4600.  
  4601. for o,a in opts:
  4602. if o == '-a':
  4603. address = int( a, 16 )
  4604. elif o == '-x':
  4605. x_list = a.split(',')
  4606. for x_addr in x_list:
  4607. try:
  4608. exclude.append(int(x_addr, 16))
  4609. except ValueError:
  4610. return "Invalid exclude value %s" % str(x_addr)
  4611. else:
  4612. usage(imm)
  4613. return "Invalid option %s" % o
  4614.  
  4615. if address is None:
  4616. usage(imm)
  4617. return "You must specify an address (-a)"
  4618.  
  4619. page = imm.getMemoryPageByAddress( address )
  4620.  
  4621. if not page:
  4622. return "Failed to grab Memory Page, wrong addres: 0x%08x" % address
  4623.  
  4624. addr = page.getBaseAddress()
  4625. mem = imm.readMemory( page.getBaseAddress(), page.getSize() )
  4626. ndx = INDEXER
  4627. fn_ptr = []
  4628.  
  4629. # Discovering Function Pointers
  4630. dt = libdatatype.DataTypes( imm )
  4631. ret = dt.Discover( mem, addr, what = 'pointers' )
  4632. if ret:
  4633. for obj in ret:
  4634. if obj.isFunctionPointer() and obj.address not in exclude:
  4635. # Writing a dword that would make the Function Pointer crash on AV
  4636. # and later we will identify on our AV Hook
  4637. imm.log( "Modifying: 0x%08x" % obj.address )
  4638. imm.writeLong( obj.address, ndx )
  4639. ndx += 1
  4640. fn_ptr.append( obj )
  4641.  
  4642. hook = FunctionTriggeredHook( fn_ptr )
  4643. hook.add( "modptr_%08x" % addr )
  4644. return "Hooking on %d Functions" % len( fn_ptr )
  4645. else:
  4646. return "No Function pointers found on the page of 0x%08x" % address
  4647.  
  4648.  
  4649. #!/usr/bin/env python
  4650. """
  4651.  
  4652. nohooks
  4653.  
  4654. """
  4655.  
  4656. __VERSION__ = '0.1'
  4657.  
  4658. DESC="""Clean all hooks from memory"""
  4659.  
  4660. import immlib
  4661.  
  4662. def main(args):
  4663. imm = immlib.Debugger()
  4664. for hook in imm.listHooks():
  4665. imm.removeHook(hook)
  4666. imm.log("Removed \"%s\" hook from memory" % str(hook))
  4667. return "Hooks removed"
  4668. #!/usr/bin/env python
  4669.  
  4670. """
  4671. (c) Immunity, Inc. 2004-2007
  4672.  
  4673.  
  4674. U{Immunity Inc.<http://www.immunityinc.com>}
  4675.  
  4676. openfile example
  4677.  
  4678. """
  4679.  
  4680. __VERSION__ = '1.0'
  4681.  
  4682. DESC="""Open a File"""
  4683.  
  4684. import immlib
  4685.  
  4686. def usage(imm):
  4687. imm.log("!openfile file")
  4688. imm.log("ex: !openfile c:\\boot.ini", focus=1)
  4689.  
  4690. def main(args):
  4691. imm=immlib.Debugger()
  4692. if not args:
  4693. usage(imm)
  4694. return "Wrong Arguments (Check Log Windows for the usage information)"
  4695. ret = imm.openTextFile( args[0] )
  4696. if ret == 0:
  4697. return "File %s open" % args[0]
  4698. else:
  4699. return "Cannot open %s" % args[0]
  4700.  
  4701. import socket
  4702. import struct
  4703.  
  4704. from immlib import *
  4705.  
  4706.  
  4707. DESC="""Creates a table that displays packets received on the network."""
  4708.  
  4709. #############################################################################
  4710. '''
  4711. Some defines for re-use.
  4712. '''
  4713. PACKET_TYPE_SEND = "Send "
  4714. PACKET_TYPE_RECV = "Recv "
  4715. PACKET_PROTOCOL_UDP = "(UDP)"
  4716. PACKET_PROTOCOL_TCP = "(TCP)"
  4717.  
  4718.  
  4719. #############################################################################
  4720. class simple_hooks(LogBpHook):
  4721.  
  4722. #########################################################################
  4723. def __init__(self):
  4724. LogBpHook.__init__(self)
  4725.  
  4726.  
  4727. #########################################################################
  4728. def run(self,regs):
  4729.  
  4730. imm = Debugger()
  4731.  
  4732. (payload_ptr,type,function_name) = imm.getKnowledge("%08x" % regs['EIP'])
  4733.  
  4734. # The length is stored as a function return argument, so let's read EAX
  4735. length = regs['EAX']
  4736.  
  4737.  
  4738. # Because return codes can be -1 (error) we have to test for that.
  4739. if length > 1 and length != 0xffffffff:
  4740.  
  4741. counter = 0
  4742. payload = ""
  4743. bin_payload = ""
  4744.  
  4745. # Get the raw packet payload and the length of the bytes
  4746. raw_payload = imm.readMemory(payload_ptr,length)
  4747.  
  4748.  
  4749.  
  4750. pack_len = str(length)+"c"
  4751. imm.log("Pack Len: %s " % pack_len)
  4752. if raw_payload is not None:
  4753.  
  4754. final_payload = struct.unpack(pack_len,raw_payload)
  4755.  
  4756. # Iterate through the unpacked string, only outputting printable
  4757. # ascii characters, output the standard dots if non-printable
  4758. while counter < int(length):
  4759. if ord(final_payload[counter]) >= 32 and ord(final_payload[counter]) <= 126:
  4760. payload += final_payload[counter]
  4761. else:
  4762. payload += "."
  4763.  
  4764. bin_payload += "%02x" % ord(final_payload[counter])
  4765. counter += 1
  4766.  
  4767. # Build the list thats table-friendly
  4768. log_items = [function_name,type,"%d" % int(length),bin_payload[:512],payload[:512]]
  4769.  
  4770. # Get a handle to the window and add the items, along with the related
  4771. # address, this is sweet cause you can double-click on a packet and
  4772. # see in the disassembly where it was sent/received :)
  4773. cap_win = imm.getKnowledge("cap_win")
  4774. cap_win.add(regs['EIP'],log_items)
  4775.  
  4776. # Drop the entry in the KB, disable the BP, and unHook.
  4777. imm.forgetKnowledge("%08x" % regs['EIP'])
  4778. imm.disableBreakpoint(regs['EIP'])
  4779. self.UnHook()
  4780.  
  4781.  
  4782. #############################################################################
  4783. class ext_hooks(LogBpHook):
  4784.  
  4785.  
  4786. #########################################################################
  4787. def __init__(self):
  4788. LogBpHook.__init__(self)
  4789.  
  4790.  
  4791. #########################################################################
  4792. def run(self,regs):
  4793.  
  4794. imm = Debugger()
  4795.  
  4796. (payload_ptr,recv_ptr,type,function_name) = imm.getKnowledge("%08x" % regs['EIP'])
  4797.  
  4798. # This is an [out] pointer that let's us know how much data was
  4799. # received on a socket (non-overlapped)
  4800. length = imm.readMemory(recv_ptr,4)
  4801. length = struct.unpack("l",length)
  4802.  
  4803. # Network apps are chatty, we don't want to grab garbage packets
  4804. if length[0] > 1:
  4805.  
  4806. counter = 0
  4807. payload = ""
  4808. bin_payload = ""
  4809.  
  4810. # Get the raw packet payload and the length of the bytes
  4811. raw_payload = imm.readMemory(payload_ptr,int(length[0]))
  4812. pack_len = str(int(length[0]))+"c"
  4813.  
  4814. if raw_payload is not None:
  4815.  
  4816. final_payload = struct.unpack(pack_len,raw_payload)
  4817.  
  4818. # Iterate through the unpacked string, only outputting printable
  4819. # ascii characters, output the standard dots if non-printable
  4820. while counter < int(length[0]):
  4821. if ord(final_payload[counter]) >= 32 and ord(final_payload[counter]) <= 126:
  4822. payload += final_payload[counter]
  4823. else:
  4824. payload += "."
  4825.  
  4826. bin_payload += "%02x" % ord(final_payload[counter])
  4827. counter += 1
  4828.  
  4829. # Build the list thats table-friendly
  4830. log_items = [function_name,type,"%d" % int(length[0]),bin_payload[:512],payload[:512]]
  4831.  
  4832. # Get a handle to the window and add the items, along with the related
  4833. # address, this is sweet cause you can double-click on a packet and
  4834. # see in the disassembly where it was sent/received :)
  4835. cap_win = imm.getKnowledge("cap_win")
  4836. cap_win.add(regs['EIP'],log_items)
  4837.  
  4838.  
  4839. # Drop the entry in the KB, disable the BP, and unHook.
  4840. imm.forgetKnowledge("%08x" % regs['EIP'])
  4841. imm.disableBreakpoint(regs['EIP'])
  4842. self.UnHook()
  4843.  
  4844.  
  4845. #############################################################################
  4846. class set_hooks(LogBpHook):
  4847. def __init__(self):
  4848. LogBpHook.__init__(self)
  4849.  
  4850. #########################################################################
  4851. def run(self,regs):
  4852. '''
  4853. This routine is the first one hit, when a socket operation occurs.
  4854. '''
  4855. imm = Debugger()
  4856.  
  4857.  
  4858. # Retrieve the function name
  4859. function_name = imm.getKnowledge("%08x" % regs['EIP'])
  4860.  
  4861. self.retrieve_packet(imm,function_name,regs)
  4862.  
  4863.  
  4864. #########################################################################
  4865. def retrieve_packet(self,imm,function_name,regs):
  4866. '''
  4867. This function determines how to handle the packet data. Some socket
  4868. operations require more work (such as WSARecv), and others less (recv).
  4869.  
  4870. If necessary this function will register a hook on [ESP], where any
  4871. [out] pointers from a function will be set.
  4872. '''
  4873.  
  4874. # Determine what function we have hooked, based on this, retrieve the packet contents
  4875. if function_name == "WSARecv":
  4876. type = PACKET_TYPE_RECV+PACKET_PROTOCOL_TCP
  4877. extended_hook = True
  4878.  
  4879. if function_name == "WSASend":
  4880. type=PACKET_TYPE_SEND+PACKET_PROTOCOL_TCP
  4881. extended_hook = True
  4882.  
  4883. if function_name == "recvfrom":
  4884. type=PACKET_TYPE_RECV+PACKET_PROTOCOL_UDP
  4885. extended_hook = False
  4886.  
  4887. if function_name =="recv":
  4888. type=PACKET_TYPE_RECV+PACKET_PROTOCOL_TCP
  4889. extended_hook = False
  4890.  
  4891. # An extended hook requires a bit more work to pull out the packet info
  4892. if extended_hook == True:
  4893.  
  4894. # Get the pointer to the payload pointer :(
  4895. pbuffer_ptr = imm.readMemory( regs['ESP'] + 8, 4)
  4896. pbuffer_ptr = struct.unpack("L", pbuffer_ptr)
  4897. #imm.log("Buffer Location: 0x%08x" % pbuffer_ptr[0])
  4898.  
  4899. # Get the pointer to the packet payload
  4900. payload_ptr = imm.readMemory(pbuffer_ptr[0]+4,4)
  4901. payload_ptr = struct.unpack("<L", payload_ptr)
  4902. #imm.log("Payload Pointer: %08x" % payload_ptr[0])
  4903.  
  4904. # Get the [out] pointer of the received bytes
  4905. recv_ptr = imm.readMemory(regs['ESP'] + 0x10, 4)
  4906. recv_ptr = struct.unpack("L",recv_ptr)
  4907. #imm.log("Receive Pointer: %08x" % recv_ptr[0])
  4908.  
  4909. # Figure out [esp]
  4910. esp_ptr = imm.readMemory(regs['ESP'],4)
  4911. esp_ptr = struct.unpack("<L", esp_ptr)
  4912. #imm.log("[ESP] at 0x%08x" % esp_ptr[0])
  4913.  
  4914. # Now we hook [esp]
  4915. ret_hook = ext_hooks()
  4916. ret_hook.add("%08x" % esp_ptr[0],esp_ptr[0])
  4917.  
  4918. # Add this ret hook to the knowledgebase
  4919. imm.addKnowledge("%08x" % esp_ptr[0],(payload_ptr[0],recv_ptr[0],type,function_name))
  4920.  
  4921. else:
  4922.  
  4923. # Get the pointer to the buffer
  4924. payload_ptr = imm.readMemory(regs['ESP'] + 8, 4)
  4925. payload_ptr = struct.unpack("L", payload_ptr)
  4926.  
  4927. # Figure out where [ESP] points to
  4928. esp_ptr = imm.readMemory(regs['ESP'],4)
  4929. esp_ptr = struct.unpack("<L", esp_ptr)
  4930.  
  4931. # Add the [ESP] hook for when the function returns
  4932. simple_hook = simple_hooks()
  4933. simple_hook.add("%08x" % esp_ptr[0],esp_ptr[0])
  4934.  
  4935. # Add our pertinent information to the knowledgebase
  4936. imm.addKnowledge("%08x" % esp_ptr[0],(payload_ptr[0],type,function_name))
  4937.  
  4938.  
  4939. # The main routine that gets run when you type !packets
  4940. def main(args):
  4941.  
  4942. imm = Debugger()
  4943. imm.ignoreSingleStep("CONTINUE")
  4944. hooker = set_hooks()
  4945.  
  4946. # Create the packet capture window
  4947. column_titles = ["Function","Type","Length","Binary","ASCII"]
  4948. cap_win = imm.createWindow("Captured Packets", column_titles )
  4949.  
  4950. # Add the window to the knowledge base
  4951. imm.addKnowledge("cap_win", cap_win,force_add=0x1)
  4952.  
  4953. # Find the addresses of the functions we want to hook
  4954. # Then register the hooks
  4955. ws_wsarecv = imm.getAddress("ws2_32.WSARecv")
  4956. ws_wsasend = imm.getAddress("ws2_32.WSASend")
  4957. ws_recv = imm.getAddress("ws2_32.recv")
  4958. ws_recvfrom = imm.getAddress("ws2_32.recvfrom")
  4959.  
  4960. # Set the hooks
  4961. hooker.add("WSARecv", ws_wsarecv)
  4962. hooker.add("WSASend", ws_wsasend)
  4963. hooker.add("recv", ws_recv)
  4964. hooker.add("recvfrom", ws_recvfrom)
  4965.  
  4966.  
  4967. # Register the hook-address pair with the knowledgebase
  4968. imm.addKnowledge("%08x" % ws_wsarecv, "WSARecv")
  4969. imm.addKnowledge("%08x" % ws_wsasend, "WSASend")
  4970. imm.addKnowledge("%08x" % ws_recv, "recv")
  4971. imm.addKnowledge("%08x" % ws_recvfrom, "recvfrom")
  4972.  
  4973.  
  4974. return "Network hooks in place."
  4975.  
  4976.  
  4977. #!/usr/bin/env python
  4978.  
  4979. """
  4980. (c) Immunity, Inc. 2004-2007
  4981.  
  4982.  
  4983. U{Immunity Inc.<http://www.immunityinc.com>}
  4984. """
  4985. __VERSION__ = '1.0'
  4986.  
  4987. import immlib, string
  4988. import traceback
  4989. import sys
  4990.  
  4991. DESC = "Non interactive python shell [immlib already imported]"
  4992.  
  4993. def usage(imm):
  4994. imm.log("!pyexec code")
  4995. imm.log("%s" % DESC)
  4996.  
  4997. def main(args):
  4998. imm = immlib.Debugger()
  4999. if args:
  5000. commands = string.joinfields(args, "")
  5001. try:
  5002. exec commands
  5003. except:
  5004. error = traceback.format_exception_only(sys.exc_type, sys.exc_value)
  5005. imm.log("Error on: %s" % commands, focus = 1)
  5006. for line in error: # Its just one line anyways, for format_exception_only
  5007. line = line.strip()
  5008. imm.log(line)
  5009. return line
  5010. else:
  5011. return "No python command given"
  5012. """
  5013. recognize.py - Function Recongnizing using heuristic patterns.
  5014.  
  5015. (c) Immunity, Inc. 2004-2007
  5016.  
  5017.  
  5018. U{Immunity Inc.<http://www.immunityinc.com>}
  5019.  
  5020. """
  5021.  
  5022.  
  5023. __VERSION__ = '1.0'
  5024. import immlib
  5025. import immutils
  5026. import getopt
  5027. import string
  5028. import os
  5029. import csv
  5030. from librecognition import *
  5031.  
  5032. DESC="Function Recognizing using heuristic patterns."
  5033.  
  5034. def usage(imm):
  5035. imm.log("!recognize -{a|m} -n name [ -x address ] [ -i filename ] [-v version/extra]")
  5036. imm.log("!recognize -d [ -i filename ] -n name")
  5037. imm.log("!recognize -l [-i filename] [-n name]")
  5038. imm.log("!recognize -f -n name [-i filename] [-v version/extra] [-o module] [-h heuristic_threasold]")
  5039. imm.log("!recognize -r -x address [-i filename] [-h heuristic_threasold]")
  5040. imm.log(" ex (find a pattern, accept 80%% of match): !recognize -f -n iTunes.AntiDebuggers -h 80 -o iTunes.exe")
  5041. imm.log(" ex (resolv an address, accept 93%% of match): !recognize -r -x 004EDE00 -h 93")
  5042. imm.log(" ex (add a pattern): !recognize -a -x 004EDE00 -n iTunes.AntiDebuggers -i itunes.dat -v 7.4.1")
  5043. imm.log(" ex (add a pattern guessing the address from labels or symbols): !recognize -a -n _SPExternalAlloc@4")
  5044. imm.log(" ex (modify a pattern): !recognize -m -x 004EDE00 -n iTunes.AntiDebuggers -i itunes.dat -v protections_disabled")
  5045. imm.log(" ex (delete a pattern): !recognize -d -i itunes.dat -n iTunes.AntiDebuggers")
  5046. imm.log(" ex (list patterns): !recognize -l -i itunes.dat -n antidebug", focus=1)
  5047. return ""
  5048.  
  5049. def main(args):
  5050. imm = immlib.Debugger()
  5051.  
  5052. imm.log("################# Immunity's Function Recognizing ################")
  5053. imm.markBegin()
  5054.  
  5055. if not args:
  5056. usage(imm)
  5057. return "not enough args"
  5058.  
  5059. try:
  5060. opts, notused = getopt.getopt(args, "amdlfrx:n:i:h:v:o:")
  5061. except getopt.GetoptError:
  5062. usage(imm)
  5063. return "Wrong Arguments (Check usage on the Log Window)"
  5064.  
  5065. defaultfilename = os.path.join("Data", "default.dat")
  5066. name = address = id = action = module = filename = None
  5067. version = ""
  5068. heuristic = 90
  5069. for o,a in opts:
  5070. if o == '-x':
  5071. address = imm.getAddress(a)
  5072. if address < 0:
  5073. imm.log("invalid address or expresion")
  5074. usage(imm)
  5075. return "address error!"
  5076. if o == '-o':
  5077. module = a
  5078. if o == '-n':
  5079. name = string.strip(a, " '\"\\{}%;,")
  5080. if o == "-i":
  5081. filename = os.path.basename(string.strip(a, " '\"{}%;,"))+".dat"
  5082. if not filename:
  5083. usage(imm)
  5084. return "invalid filename"
  5085. filename = os.path.join("Data",filename)
  5086. if o == '-v':
  5087. version = string.strip(a, " '\"\\{}%;,")
  5088. if o == "-h":
  5089. try:
  5090. heuristic = int(a)
  5091. except:
  5092. imm.log("invalid heuristic threasold")
  5093. usage(imm)
  5094. return "heuristic theashold error!"
  5095. if o in ["-a","-m","-d","-l","-f","-r"]:
  5096. action = o[1]
  5097.  
  5098. if not action:
  5099. usage(imm)
  5100. return "no action set"
  5101.  
  5102. #add/modify an element
  5103. if action == "a" or action == "m":
  5104. if not filename: filename = defaultfilename
  5105. if not name:
  5106. usage(imm)
  5107. return "insufficient arguments to add/modify an entry"
  5108.  
  5109. if not address:
  5110. tmp = imm.getAddressOfExpression(name)
  5111. if tmp > 0:
  5112. address = tmp
  5113. else:
  5114. return "name hasn't a known address"
  5115.  
  5116. modif = False
  5117. recon = FunctionRecognition(imm, filename)
  5118. for d in recon.dictionaries:
  5119. if name == d[0]:
  5120. if action == "a":
  5121. usage(imm)
  5122. return "the name '%s' is already in the selected dictionary" % name
  5123. if action == "m":
  5124. modif = True
  5125. break
  5126. if action == "m" and not modif:
  5127. usage(imm)
  5128. return "the name '%s' wasn't found in the selected dictionary" % name
  5129.  
  5130. tmp = recon.makeFunctionHash(address, compressed=True)
  5131. file = extractFile(imm, address)
  5132. definition = [ name, tmp[0], tmp[1][0], tmp[1][1], tmp[2], version, file, string.join(tmp[3],"|") ]
  5133. remakeDictionary(imm, recon, filename, definition, action)
  5134. imm.log("Element '%s' added/modified" % name, focus=1)
  5135.  
  5136. #delete an element
  5137. if action == "d":
  5138. if not name:
  5139. usage(imm)
  5140. return "incomplete information to delete an element"
  5141. if not filename: filename = defaultfilename
  5142. delete = False
  5143. recon = FunctionRecognition(imm, filename)
  5144. for d in recon.dictionaries:
  5145. if name == d[0]:
  5146. delete = True
  5147. break
  5148. if not delete:
  5149. usage(imm)
  5150. return "the function '%s' wasn't found in the selected dictionary" % name
  5151. remakeDictionary(imm, recon, filename, name, action)
  5152. imm.log("Element '%s' deleted" % name, focus=1)
  5153.  
  5154. #list elements
  5155. if action == "l":
  5156. recon = FunctionRecognition(imm, filename)
  5157. list = []
  5158. for values in recon.dictionaries:
  5159. if not name or name.lower() in values[0].lower():
  5160. list.append([values[0],values[5],values[6],values[4], os.path.basename(values[-1])[:-4]])
  5161. if not list:
  5162. return "the name '%s' wasn't found in the dictionaries" % name
  5163. else:
  5164. imm.log("-" * 156)
  5165. imm.log("|%-30s|%-40s|%-20s|%-40s|%-20s|" % ("real name","version/extra","binary file","SHA1","repository"))
  5166. imm.log("-" * 156)
  5167. for v in list:
  5168. imm.log("|%-30s|%-40s|%-20s|%-40s|%-20s|" % (v[0][0:30],v[1][0:40],v[2][0:20],v[3][0:40], v[4][0:20]), focus=1)
  5169. imm.log("-" * 156)
  5170.  
  5171. #search for an element
  5172. if action == "f":
  5173. if not name:
  5174. usage(imm)
  5175. return "incomplete information to search"
  5176.  
  5177. #we need to maintain separated csv indexes
  5178. dict = FunctionRecognition(imm, filename)
  5179. recon = FunctionRecognition(imm, filename)
  5180. addy = None
  5181. for values in dict.dictionaries:
  5182. if name.lower() in values[0].lower():
  5183. tmp = recon.searchFunctionByName(values[0], heuristic, module, version)
  5184. if tmp:
  5185. for addy,heu in tmp:
  5186. imm.log("Function '%s' address: %08X (%d%%)" % (values[0], addy,heu), addy, focus=1)
  5187. if addy:
  5188. imm.gotoDisasmWindow(addy)
  5189. else:
  5190. imm.log("We can't find a function that fullfit all the requirements", focus=1)
  5191.  
  5192. #resolv an address to a function name
  5193. if action == "r":
  5194. if not address:
  5195. usage(imm)
  5196. return "we need an address to resolv"
  5197.  
  5198. recon = FunctionRecognition(imm, filename)
  5199. name = recon.resolvFunctionByAddress(address)
  5200. if name:
  5201. imm.log("function at %08X FOUND: %s" % (address, name), address, focus=1)
  5202. imm.gotoDisasmWindow(address)
  5203. else:
  5204. imm.log("function not found", focus=1)
  5205.  
  5206. return "Done in %d secs! see the log for details" % imm.markEnd()
  5207.  
  5208. def remakeDictionary(imm, recon, filename, data, action):
  5209. tmpfd = os.tmpfile()
  5210. writer = csv.writer(tmpfd)
  5211. if action == "a" or action == "m":
  5212. writer.writerow(data)
  5213.  
  5214. for row in recon.dictionaries:
  5215. row.pop() #drop the filename added by the CSV iterator (always the last element)
  5216. if action == "a":
  5217. writer.writerow(row)
  5218. if action == "m" and data[0] != row[0]:
  5219. writer.writerow(row)
  5220. if action == "d" and data != row[0]:
  5221. writer.writerow(row)
  5222. tmpfd.flush()
  5223. del recon
  5224. del writer
  5225.  
  5226. fd = open(filename, "wb")
  5227. tmpfd.seek(0)
  5228. for line in tmpfd:
  5229. fd.write(line)
  5230. tmpfd.close()
  5231. fd.close()
  5232.  
  5233. def extractFile(imm, address):
  5234. for mod in imm.getAllModules().values():
  5235. if mod.getBaseAddress() <= address and address <= mod.getBaseAddress()+mod.getSize():
  5236. return os.path.basename(mod.getPath())
  5237. return ""
  5238. #!/usr/bin/env python
  5239. """
  5240. Immunity Debugger safeseh search
  5241.  
  5242. (c) Immunity, Inc. 2004-2007
  5243.  
  5244.  
  5245. U{Immunity Inc.<http://www.immunityinc.com>}
  5246. """
  5247.  
  5248. __VERSION__ = '1.1'
  5249.  
  5250. import immlib
  5251. import getopt
  5252. from immutils import *
  5253. import struct
  5254.  
  5255. LOG_HANDLERS=True
  5256.  
  5257. DESC= "Looks for exception handlers registered with SafeSEH"
  5258.  
  5259. def usage(imm):
  5260. imm.log("!safeseh (-m module)",focus=1)
  5261.  
  5262. def main(args):
  5263. imm = immlib.Debugger()
  5264.  
  5265. module = None
  5266.  
  5267. try:
  5268. opts, argo = getopt.getopt(args, "m:s")
  5269. except getopt.GetoptError:
  5270. usage(imm)
  5271. return "Bad argument %s" % args[0]
  5272.  
  5273. for o,a in opts:
  5274. if o == "-m":
  5275. module = a
  5276.  
  5277. allmodules=imm.getAllModules()
  5278. table=imm.createTable('SafeSEH Table',['Module','Handler'])
  5279. for key in allmodules.keys():
  5280. if module is not None and module != key:
  5281. continue
  5282.  
  5283. mod=imm.getModule(key)
  5284. mzbase=mod.getBaseAddress()
  5285. peoffset=struct.unpack('<L',imm.readMemory(mzbase+0x3c,4))[0]
  5286. pebase=mzbase+peoffset
  5287. flags=struct.unpack('<H',imm.readMemory(pebase+0x5e,2))[0]
  5288. if (flags&0x400)!=0:
  5289. imm.log('%s: SafeSEH protected'%(key))
  5290. imm.log('%s: No handler'%(key))
  5291. continue
  5292. numberofentries=struct.unpack('<L',imm.readMemory(pebase+0x74,4))[0]
  5293. if numberofentries>10:
  5294. sectionaddress,sectionsize=struct.unpack('<LL',imm.readMemory(pebase+0x78+8*10,8))
  5295. sectionaddress+=mzbase
  5296. data=struct.unpack('<L',imm.readMemory(sectionaddress,4))[0]
  5297. condition=(sectionsize!=0) and ((sectionsize==0x40) or (sectionsize==data))
  5298. #imm.log('%s: %08x %04x %08x %08x %d'%(key,mzbase,flags,sectionaddress,sectionsize,condition))
  5299. if condition==False:
  5300. imm.log('%s: *** SafeSEH unprotected ***'%(key))
  5301. continue
  5302. if data<0x48:
  5303. imm.log('%s: TODO check section 0xe!'%(key)) #checked in RtlCaptureImageExceptionValues() though I have never seen such a DLL/EXE
  5304. continue
  5305. sehlistaddress,sehlistsize=struct.unpack('<LL',imm.readMemory(sectionaddress+0x40,8))
  5306. #imm.log('%s: %08x %d'%(key,sehlistaddress,sehlistsize))
  5307. if sehlistaddress!=0 and sehlistsize!=0:
  5308. imm.log('%s: SafeSEH protected'%(key))
  5309. imm.log('%s: %d handler(s)'%(key,sehlistsize))
  5310. if LOG_HANDLERS==True:
  5311. for i in range(sehlistsize):
  5312. sehaddress=struct.unpack('<L',imm.readMemory(sehlistaddress+4*i,4))[0]
  5313. sehaddress+=mzbase
  5314. table.add(sehaddress,[key,'0x%08x'%(sehaddress)])
  5315. imm.log('0x%08x'%(sehaddress))
  5316. continue
  5317. else:
  5318. imm.log('%s: TODO check section 0xe!'%(key)) #checked in RtlCaptureImageExceptionValues() though I have never seen such a DLL/EXE
  5319. continue
  5320. imm.log('%s: *** SafeSEH unprotected ***'%(key))
  5321.  
  5322.  
  5323. return "Check your table and log window for results"
  5324.  
  5325.  
  5326. #!/usr/bin/env python
  5327.  
  5328. #-------------------------------------------------------------------------------
  5329. #
  5330. # By BoB -> Team PEiD
  5331. # http://www.SecretAsHell.com/BobSoft/
  5332. # BobSoft@GMail.Com
  5333. #
  5334. #-------------------------------------------------------------------------------
  5335. #
  5336. # Based on findpacker.py, this script will scan the entrypoint or whole file of
  5337. # the main module, using Ero's PEFile and my UserDB.txt as before ..
  5338. # Also added is logging of the entropy of the file and a guess based on the
  5339. # entropy as to whether the file is packed or not.
  5340. #
  5341. # By BoB, whilst freezing in England.. ;)
  5342. # I only started with Python a week ago, and this is my first ever script ..
  5343. # So, please excuse any bad Python coding :P
  5344. #
  5345. # Thanks to JMS for checking my dodgy code .. :)
  5346. #
  5347. #-------------------------------------------------------------------------------
  5348.  
  5349.  
  5350. __VERSION__ = '1.00'
  5351. ProgName = 'ScanPE'
  5352. ProgVers = __VERSION__
  5353. DESC = "Detect a Packer/Cryptor of Main Module, also scan just EntryPoint .."
  5354.  
  5355.  
  5356. import immlib
  5357. import math
  5358. import pefile
  5359. import peutils
  5360.  
  5361.  
  5362. #-------------------------------------------------------------------------------
  5363.  
  5364. def usage(imm):
  5365. imm.log(" ")
  5366. imm.log("%s v%s By BoB -> Team PEiD" % (ProgName, ProgVers), focus=1, highlight=1)
  5367. imm.log("This script will scan the loaded module for any matching signatures in .\Data\UserDB.TXT ..")
  5368. imm.log("Usage:")
  5369. imm.log(" !%s [-h]" % ProgName.lower())
  5370. imm.log(" ")
  5371. imm.log("Options:")
  5372. imm.log(" -h : Hardcore mode - Scan whole file .. (default is to scan just the Entrypoint)")
  5373. imm.log(" ")
  5374. return "See log window (Alt-L) for usage .. "
  5375.  
  5376.  
  5377. #-------------------------------------------------------------------------------
  5378. # RawToRva - Convert offset to Rva ..
  5379.  
  5380. def rawToRva(pe, Raw):
  5381. sections = [s for s in pe.sections if s.contains_offset(Raw)]
  5382. if sections:
  5383. section = sections[0]
  5384. return (Raw - section.PointerToRawData) + section.VirtualAddress
  5385. else:
  5386. return 0
  5387.  
  5388.  
  5389. #-------------------------------------------------------------------------------
  5390. # GetSectionInfo - Returns info about section as string ..
  5391.  
  5392. def getSectionInfo(pe, Va):
  5393. sec = pe.get_section_by_rva(Va - pe.OPTIONAL_HEADER.ImageBase)
  5394. if sec:
  5395. # Get section number ..
  5396. sn = 0
  5397. for i in range(pe.FILE_HEADER.NumberOfSections):
  5398. if pe.sections[i] == sec:
  5399. sn = i + 1
  5400. break
  5401. # Get section name ..
  5402. name = ""
  5403. for j in range(7):
  5404. # Only until first null ..
  5405. if sec.Name[j] == chr(0):
  5406. break
  5407. name = "%s%s" % (name, sec.Name[j])
  5408. # If name is not blank then set name string to ', "<name>"'' ..
  5409. if name != "":
  5410. name = ", \"%s\"" % name
  5411. # Return section number and name (if exist) ..
  5412. return " (section #%02d%s)" % (sn, name)
  5413. return " (not in a section)"
  5414.  
  5415.  
  5416. #-------------------------------------------------------------------------------
  5417. # GetEntropy - Returns entropy of some data - Taken from Ero's PEFile.py ..
  5418.  
  5419. def getEntropy(data):
  5420. """Calculate the entropy of a chunk of data."""
  5421.  
  5422. if not data:
  5423. return 0
  5424.  
  5425. entropy = 0
  5426. for x in range(256):
  5427. p_x = float(data.count(chr(x)))/len(data)
  5428. if p_x > 0:
  5429. entropy += - p_x*math.log(p_x, 2)
  5430.  
  5431. return entropy
  5432.  
  5433.  
  5434. #-------------------------------------------------------------------------------
  5435.  
  5436. def main(args):
  5437. imm = immlib.Debugger()
  5438. name = imm.getDebuggedName()
  5439.  
  5440. EP_Only = 1
  5441. if args:
  5442. if args[0].lower() == '-h':
  5443. EP_Only = 0
  5444. try:
  5445. Mod = imm.getModule(name)
  5446. if not Mod:
  5447. raise Exception, "Couldn't find %s .." % name
  5448. except Exception, msg:
  5449. return "Error: %s" % msg
  5450.  
  5451. imm.log(" ")
  5452. imm.log("%s v%s By BoB -> Team PEiD" % (ProgName, ProgVers), focus=1, highlight=1)
  5453. imm.log("Processing \"%s\" .." % name)
  5454.  
  5455. # Load PE File ..
  5456. pe = pefile.PE(name = Mod.getPath())
  5457.  
  5458. # Displays same guessed results as PEiD -> Extra information -> Entropy ..
  5459. e = getEntropy( pe.__data__ )
  5460. if e < 6.0:
  5461. a = "Not packed"
  5462. elif e < 7.0:
  5463. a = "Maybe packed"
  5464. else: # 7.0 .. 8.0
  5465. a = "Packed"
  5466.  
  5467. # Start processing ..
  5468. imm.log(" o File Entropy : %.2f (%s)" % (e, a))
  5469. imm.log(" o Loading signatures ..")
  5470. imm.setStatusBar("Loading signatures ..")
  5471. # Show now as sigs take a few seconds to load ..
  5472. imm.updateLog()
  5473.  
  5474. # Load signatures ..
  5475. sig_db = peutils.SignatureDatabase('Data/UserDB.TXT')
  5476. imm.log(" o %d total sigs in database .." % (sig_db.signature_count_eponly_true + sig_db.signature_count_eponly_false + sig_db.signature_count_section_start))
  5477. # Display number of signatures to scan ..
  5478. if EP_Only == 1:
  5479. imm.log(" o %d EntryPoint sigs to scan .." % sig_db.signature_count_eponly_true)
  5480. imm.log(" o Scanning Entrypoint ..")
  5481. imm.setStatusBar("Scanning Entrypoint ..")
  5482. else:
  5483. imm.log(" o %d sigs to scan in hardcore mode .." % sig_db.signature_count_eponly_false)
  5484. imm.log(" o Scanning whole file ..")
  5485. imm.setStatusBar("Scanning whole file .. This may take a few minutes, so go make a coffee ..")
  5486. imm.log(" ")
  5487. # Force update now or user will not know any info until scan finished ..
  5488. # Which can take minutes for a large file scanned with -a option ..
  5489. imm.updateLog()
  5490.  
  5491. # Do the scan, EP only or hardcore mode ..
  5492. ret = sig_db.match( pe, EP_Only == 1 )
  5493.  
  5494. # Display results of scan ..
  5495. imm.log("Result:")
  5496. if not ret:
  5497. imm.log(" Nothing found ..")
  5498. imm.log(" ")
  5499. return "Nothing found .."
  5500.  
  5501. if EP_Only == 1:
  5502. # If EP detection then result is a string and we know EP address ..
  5503. va = pe.OPTIONAL_HEADER.ImageBase + pe.OPTIONAL_HEADER.AddressOfEntryPoint
  5504. addr = pe.get_offset_from_rva(pe.OPTIONAL_HEADER.AddressOfEntryPoint)
  5505. imm.log(" Found \"%s\" at offset 0x%08X %s" % (ret[0], addr, getSectionInfo(pe, va)), address = va)
  5506. imm.log(" ")
  5507. return "Found \"%s\" at 0x%08X .." % (ret[0], va)
  5508. else:
  5509. # If more than 1 returned detection, then display all possibilities ..
  5510. if len(ret) > 1:
  5511. a = 1
  5512. for (addr, name) in ret:
  5513. va = pe.OPTIONAL_HEADER.ImageBase + rawToRva(pe, addr)
  5514. imm.log(' %02d : \"%s\" at offset 0x%08X %s' % (a, name[0], addr, getSectionInfo(pe, va)), address = va)
  5515. a += 1
  5516. imm.log(" ")
  5517. return "Found %d possible matches .." % len(ret)
  5518. else:
  5519. # If only 1 detection then display result ..
  5520. for (addr, name) in ret:
  5521. va = pe.OPTIONAL_HEADER.ImageBase + rawToRva(pe, addr)
  5522. imm.log(' Found \"%s\" at offset 0x%08X %s' % (name[0], addr, getSectionInfo(pe, va)), address = va)
  5523. imm.log(" ")
  5524. return "Found \"%s\" at 0x%08X .." % (name[0], va)
  5525.  
  5526. """
  5527. Immunity Debugger Regexp Search
  5528.  
  5529. (c) Immunity, Inc. 2004-2007
  5530.  
  5531.  
  5532. U{Immunity Inc.<http://www.immunityinc.com>}
  5533.  
  5534. search.py - simple script that lets you quickie search for regexp
  5535. """
  5536.  
  5537. __VERSION__ = '1.1'
  5538.  
  5539.  
  5540. import immlib
  5541.  
  5542. # TODO: -a <ASM> -m <modname>, search all on no -m
  5543. # TODO: migrate/replace searchcode.py
  5544.  
  5545. DESC = "Search for given assembly code"
  5546.  
  5547. def usage(imm):
  5548. imm.log("!search <ASM>")
  5549. imm.log("For example: !search pop r32\\npop r32\\nret")
  5550.  
  5551. def main(args):
  5552. if not args:
  5553. return "Usage: !search <ASM>"
  5554. imm = immlib.Debugger()
  5555. code = " ".join(args).replace("\\n","\n")
  5556. ret = imm.searchCommands(code.upper())
  5557. for a in ret:
  5558. result=imm.disasm(a[0])
  5559. imm.log("Found %s at 0x%X (%s)"% (result.result, a[0], a[2]), address=a[0], focus=1)
  5560. return "Search completed!"
  5561.  
  5562. #!/usr/bin/env python
  5563.  
  5564. """
  5565. (c) Immunity, Inc. 2004-2007
  5566.  
  5567.  
  5568. U{Immunity Inc.<http://www.immunityinc.com>}
  5569. """
  5570.  
  5571.  
  5572. __VERSION__ = '1.0'
  5573. import immlib
  5574.  
  5575. DESC = "Search code in memory"
  5576.  
  5577. def usage(imm):
  5578. imm.log("!searchcode Search code in memory")
  5579. imm.log("!searchcode <asm code>")
  5580.  
  5581. def main(args):
  5582. imm = immlib.Debugger()
  5583.  
  5584. look = " ".join(args)
  5585. ret = imm.search( imm.assemble( look ) )
  5586.  
  5587. for a in ret:
  5588.  
  5589. module = imm.findModule(a)
  5590. if not module:
  5591. module = "none"
  5592. else:
  5593. module = module[0]
  5594.  
  5595. # Grab the memory access type for this address
  5596. page = imm.getMemoryPageByAddress( a )
  5597. access = page.getAccess( human = True )
  5598.  
  5599. imm.log("Found %s at 0x%08x [%s] Access: (%s)" % (look, a, module, access), address = a)
  5600. if ret:
  5601. return "Found %d address (Check the Log Windows for details)" % len(ret)
  5602. else:
  5603. return "Sorry, no code found"
  5604. """
  5605. (c) Immunity, Inc. 2004-2007
  5606.  
  5607.  
  5608. U{Immunity Inc.<http://www.immunityinc.com>}
  5609.  
  5610. Search a defined memory range looking for cryptographic routines
  5611. """
  5612.  
  5613.  
  5614. __VERSION__ = '1.0'
  5615. import immlib
  5616. import getopt
  5617. from immutils import *
  5618.  
  5619. DESC = "Search a defined memory range looking for cryptographic routines"
  5620.  
  5621. def usage(imm):
  5622. imm.log("!searchcrypt [-a FROMADDRESS] [-t TOADDRESS] [-o OWNER]", focus=1)
  5623. imm.log(" FROMADDRESS start address")
  5624. imm.log(" TOADDRESS end address")
  5625. imm.log(" OWNER memory page owner")
  5626. imm.log("ex: !searchcrypt -a 0x70000000")
  5627.  
  5628. def main(args):
  5629. imm = immlib.Debugger()
  5630.  
  5631. try:
  5632. opts, notused = getopt.getopt(args, "a:t:o:")
  5633. except getopt.GetoptError:
  5634. usage(imm)
  5635. return "Wrong Arguments (Check usage on the Log Window)"
  5636.  
  5637. fromaddy = toaddy = owner = None
  5638.  
  5639. for o,a in opts:
  5640. if o == '-a':
  5641. try:
  5642. fromaddy = int( a, 16 )
  5643. except ValueError:
  5644. usage(imm)
  5645. return "Wrong Address (%s) % " % a
  5646. if o == '-t':
  5647. try:
  5648. toaddy = int( a, 16 )
  5649. except ValueError:
  5650. usage(imm)
  5651. return "Wrong Address (%s) % " % a
  5652. if o == '-o':
  5653. owner = a
  5654.  
  5655. if isinstance(toaddy, int) and isinstance(fromaddy, int) and toaddy <= fromaddy:
  5656. usage(imm)
  5657. return "end address can't be less than start address"
  5658.  
  5659. result = []
  5660.  
  5661. #the first dword has to be unique in the complete dictionary to get an accurate address
  5662. consts = {
  5663. "AES": [ 0xc66363a5, 0xf87c7c84, 0xee777799, 0xf67b7b8d, 0xfff2f20d, 0xd66b6bbd, 0xde6f6fb1, 0x91c5c554, 0x60303050, 0x02010103, 0xce6767a9, 0x562b2b7d, 0xe7fefe19, 0xb5d7d762, 0x4dababe6, 0xec76769a, 0x8fcaca45, 0x1f82829d, 0x89c9c940, 0xfa7d7d87, 0xeffafa15, 0xb25959eb, 0x8e4747c9, 0xfbf0f00b, 0x41adadec, 0xb3d4d467, 0x5fa2a2fd, 0x45afafea, 0x239c9cbf, 0x53a4a4f7, 0xe4727296, 0x9bc0c05b, 0x75b7b7c2, 0xe1fdfd1c, 0x3d9393ae, 0x4c26266a, 0x6c36365a, 0x7e3f3f41, 0xf5f7f702, 0x83cccc4f, 0x6834345c, 0x51a5a5f4, 0xd1e5e534, 0xf9f1f108, 0xe2717193, 0xabd8d873, 0x62313153, 0x2a15153f, 0x0804040c, 0x95c7c752, 0x46232365, 0x9dc3c35e, 0x30181828, 0x379696a1, 0x0a05050f, 0x2f9a9ab5 ], \
  5664. "BLOWFISH": [ 0x243f6a88, 0x85a308d3, 0x13198a2e, 0x03707344, 0xa4093822, 0x299f31d0, 0x082efa98, 0xec4e6c89, 0x452821e6, 0x38d01377, 0xbe5466cf, 0x34e90c6c, 0xc0ac29b7, 0xc97c50dd, 0x3f84d5b5, 0xb5470917, 0x9216d5d9, 0x8979fb1b ], \
  5665. "CAMELLIA": [ 0xA09E667F, 0x3BCC908B, 0xB67AE858, 0x4CAA73B2, 0xC6EF372F, 0xE94F82BE, 0x54FF53A5, 0xF1D36F1C, 0x10E527FA, 0xDE682D1D, 0xB05688C2, 0xB3E6C1FD ], \
  5666. "CAST": [ 0x30fb40d4, 0x9fa0ff0b, 0x6beccd2f, 0x3f258c7a, 0x1e213f2f, 0x9c004dd3, 0x6003e540, 0xcf9fc949, 0xbfd4af27, 0x88bbbdb5, 0xe2034090, 0x98d09675, 0x6e63a0e0, 0x15c361d2, 0xc2e7661d, 0x22d4ff8e, 0x28683b6f, 0xc07fd059, 0xff2379c8, 0x775f50e2, 0x43c340d3, 0xdf2f8656, 0x887ca41a, 0xa2d2bd2d, 0xa1c9e0d6, 0x346c4819, 0x61b76d87, 0x22540f2f, 0x2abe32e1, 0xaa54166b, 0x22568e3a, 0xa2d341d0, 0x66db40c8, 0xa784392f, 0x004dff2f, 0x2db9d2de, 0x97943fac, 0x4a97c1d8, 0x527644b7, 0xb5f437a7, 0xb82cbaef, 0xd751d159, 0x6ff7f0ed, 0x5a097a1f, 0x827b68d0, 0x90ecf52e, 0x22b0c054, 0xbc8e5935, 0x4b6d2f7f, 0x50bb64a2, 0xd2664910, 0xbee5812d, 0xb7332290, 0xe93b159f, 0xb48ee411, 0x4bff345d, 0xfd45c240, 0xad31973f, 0xc4f6d02e, 0x55fc8165, 0xd5b1caad, 0xa1ac2dae, 0xa2d4b76d, 0xc19b0c50, 0x882240f2, 0x0c6e4f38, 0xa4e4bfd7, 0x4f5ba272, 0x564c1d2f, 0xc59c5319, 0xb949e354, 0xb04669fe, 0xb1b6ab8a, 0xc71358dd, 0x6385c545, 0x110f935d, 0x57538ad5, 0x6a390493, 0xe63d37e0, 0x2a54f6b3, 0x3a787d5f, 0x6276a0b5, 0x19a6fcdf, 0x7a42206a, 0x29f9d4d5, 0xf61b1891, 0xbb72275e, 0xaa508167, 0x38901091, 0xc6b505eb, 0x84c7cb8c, 0x2ad75a0f, 0x874a1427, 0xa2d1936b, 0x2ad286af, 0xaa56d291, 0xd7894360, 0x425c750d, 0x93b39e26, 0x187184c9, 0x6c00b32d, 0x73e2bb14, 0xa0bebc3c, 0x54623779 ], \
  5667. "MD5": [ 0xd76aa478, 0x67452301, 0xEFCDAB89, 0x98BADCFE, 0x10325476, 0xe8c7b756, 0x242070db, 0xc1bdceee, 0xf57c0faf, 0x4787c62a, 0xa8304613, 0xfd469501, 0x698098d8, 0x8b44f7af, 0xffff5bb1, 0x895cd7be, 0x6b901122, 0xfd987193, 0xa679438e, 0x49b40821 ], \
  5668. "RC2": [ 0xc4f978d9, 0xedb5dd19, 0x79fde928, 0x9dd8a04a, 0x83377ec6, 0x8e53762b, 0x88644c62, 0xa2fb8b44, 0xf5599a17, 0x134fb387, 0x8d6d4561, 0x327d8109, 0xeb408fbd, 0x0b7bb786, 0x222195f0, 0x824e6b5c, 0x9365d654, 0x1cb260ce, 0x14c05673, 0xdcf18ca7, 0x1fca7512, 0xd1e4be3b, 0x30d43d42, 0x26b63ca3, 0xda0ebf6f, 0x57076946, 0x9b1df227, 0x034394bc, 0xf6c711f8, 0xe73eef90, 0x2fd5c306, 0xd71e66c8, 0xdeeae808, 0xf7ee5280, 0xac72aa84, 0x2a6a4d35, 0x71d21a96, 0x7449155a, 0x5ed09f4b, 0xeca41804, 0x6e41e0c2, 0xcccb510f, 0x50af9124, 0x3970f4a1, 0x853a7c99, 0x7ab4b823, 0x5b3602fc, 0x31975525, 0x98fa5d2d, 0xae928ae3, 0x1029df05, 0xc9ba6c67, 0xcfe600d3, 0x2ca89ee1, 0x3f011663, 0xa989e258, 0x1b34380d, 0xb0ff33ab, 0x5f0c48bb, 0x2ecdb1b9, 0x47dbf3c5, 0x779ca5e5, 0x6820a60a, 0xadc17ffe ], \
  5669. "RC5": [ 0xb7e15163, 0x9e3779b9 ], \
  5670. "RIPEMD160": [ 0x50A28BE6, 0x67452301, 0xEFCDAB89, 0x98BADCFE, 0x10325476, 0xC3D2E1F0, 0x00000000, 0x5A827999, 0x6ED9EBA1, 0x8F1BBCDC, 0xA953FD4E, 0x5C4DD124, 0x6D703EF3, 0x7A6D76E9 ], \
  5671. "SHA1": [ 0xCA62C1D6, 0x67452301, 0xEFCDAB89, 0x98BADCFE, 0x10325476, 0xC3D2E1F0, 0x5A827999, 0x6ED9EBA1, 0x8F1BBCDC ], \
  5672. "SHA256": [ 0xc67178f2, 0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19, 0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5, 0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174, 0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da, 0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967, 0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85, 0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070, 0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3, 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7 ], \
  5673. "SHA512": [ 0xf3bcc908, 0x6a09e667, 0xbb67ae85, 0x84caa73b, 0x3c6ef372, 0xfe94f82b, 0xa54ff53a, 0x5f1d36f1, 0x510e527f, 0xade682d1, 0x9b05688c, 0x2b3e6c1f, 0x1f83d9ab, 0xfb41bd6b, 0x5be0cd19, 0x137e2179, 0x428a2f98, 0xd728ae22, 0x71374491, 0x23ef65cd, 0xb5c0fbcf, 0xec4d3b2f, 0xe9b5dba5, 0x8189dbbc, 0x3956c25b, 0xf348b538, 0x59f111f1, 0xb605d019, 0x923f82a4, 0xaf194f9b, 0xab1c5ed5, 0xda6d8118, 0xd807aa98, 0xa3030242, 0x12835b01, 0x45706fbe, 0x243185be, 0x4ee4b28c, 0x550c7dc3, 0xd5ffb4e2, 0x72be5d74, 0xf27b896f, 0x80deb1fe, 0x3b1696b1, 0x9bdc06a7, 0x25c71235, 0xc19bf174, 0xcf692694, 0xe49b69c1, 0x9ef14ad2, 0xefbe4786, 0x384f25e3, 0x0fc19dc6, 0x8b8cd5b5, 0x240ca1cc, 0x77ac9c65, 0x2de92c6f, 0x592b0275, 0x4a7484aa, 0x6ea6e483 ] \
  5674. }
  5675.  
  5676. result = MultiSearch(imm, consts, fromaddy, toaddy, owner)
  5677.  
  5678. for name,addy in result:
  5679. mem = imm.getMemoryPageByAddress(addy)
  5680. imm.log("Const Found: %10s Owner: %s - Section: %s" % ( name, mem.getOwner(), \
  5681. mem.getSection() ), addy )
  5682.  
  5683. return "search finished"
  5684.  
  5685.  
  5686. def MultiSearch(imm, consts, fromaddy, toaddy, arg_owner):
  5687. if not consts:
  5688. return []
  5689.  
  5690. found = []
  5691. hits = {}
  5692. addys = {}
  5693.  
  5694. for a in imm.getMemoryPages().keys():
  5695. if isinstance(fromaddy, int) and a < fromaddy:
  5696. continue
  5697.  
  5698. if isinstance(toaddy, int) and a > toaddy:
  5699. continue
  5700.  
  5701. owner = imm.MemoryPages[a].getOwner()
  5702.  
  5703. if isinstance(arg_owner, str) and owner.upper() != arg_owner.upper():
  5704. continue
  5705.  
  5706. mem = imm.MemoryPages[a].getMemory()
  5707.  
  5708. if not mem:
  5709. continue
  5710.  
  5711. for name,consts_list in consts.iteritems():
  5712.  
  5713. if not isinstance(consts_list,list):
  5714. consts_list = [ consts_list ]
  5715.  
  5716. count = 0
  5717. for const in consts_list:
  5718. const = int2str32_swapped(const)
  5719.  
  5720. f = mem.find ( const )
  5721.  
  5722. if f == -1:
  5723. continue
  5724.  
  5725. #check if it's outside the scope of my search
  5726. if isinstance(toaddy, int) and (f + a) > toaddy:
  5727. break
  5728.  
  5729. #we save the hits by owner
  5730. try:
  5731. hits[name][owner] += 1
  5732. except KeyError:
  5733. if not hits.has_key(name):
  5734. hits[name] = {}
  5735. hits[name][owner] = 1
  5736.  
  5737. #get the address of the first hit
  5738. if not addys.has_key(name):
  5739. addys[name] = {}
  5740. if not addys[name].has_key(owner):
  5741. addys[name][owner] = f + a
  5742.  
  5743.  
  5744. # it has to match every const to get a real match
  5745. for name,consts_list in consts.iteritems():
  5746. if hits.has_key(name):
  5747. for owner,count in hits[name].iteritems():
  5748. if count >= len(consts_list):
  5749. found.append( [name, addys[name][owner] ] )
  5750.  
  5751. return found
  5752. #!/usr/bin/env python
  5753.  
  5754. """
  5755. (c) Immunity, Inc. 2004-2007
  5756.  
  5757.  
  5758. U{Immunity Inc.<http://www.immunityinc.com>}
  5759. """
  5760.  
  5761.  
  5762. __VERSION__ = '1.0'
  5763.  
  5764. import immlib
  5765. import getopt
  5766. from libheap import *
  5767.  
  5768. DESC = "Search the heap for specific chunks"
  5769.  
  5770. def usage(imm):
  5771. imm.log("!searchheap Search the heap for specific chunks")
  5772. imm.log("!searchheap [-h HEAP_ADDR] [-s] [-r] [-f] [-c]")
  5773. imm.log(" -h HEAPADDR Set the heap address to inspect")
  5774. imm.log(" -w what What to search for: size, prevsize, flags, address, next, prev")
  5775. imm.log(" -a action Search action: =, !=, >, <, >=, <=, &, not")
  5776. imm.log(" -v value Value to be searched")
  5777. imm.log(" -k Show the content of the chunk")
  5778. imm.log(" -r Use the restored heap (see !heap for more details)")
  5779.  
  5780.  
  5781. def main(args):
  5782. imm = immlib.Debugger()
  5783. imm.log("### Immunity's Search Heap ###")
  5784.  
  5785. try:
  5786. opts, argo = getopt.getopt(args, "h:w:a:v:rk", ["heap=", "what=", "action=", "value="])
  5787. except getopt.GetoptError:
  5788. imm.setStatusBar("Bad heap argument %s" % args[0])
  5789. usage(imm)
  5790. return 0
  5791.  
  5792. heap = 0x0
  5793. what = None
  5794. action = None
  5795. value = None
  5796. restore = False
  5797. chunkdisplay = 0
  5798.  
  5799. for o,a in opts:
  5800. if o == "-h":
  5801. try:
  5802. heap = int(a, 16)
  5803. except ValueError, msg:
  5804. imm.InfoLine("Invalid heap address: %s" % a)
  5805. return 0
  5806. elif o == "-r":
  5807. restore = True
  5808. elif o == "-k":
  5809. chunkdisplay = SHOWCHUNK_FULL
  5810. elif o in ("-w", "--what"):
  5811. what = a
  5812. elif o in ("-a", "--action"):
  5813. action = a
  5814. elif o in ("-v", "--value"):
  5815. try:
  5816. value = int(a, 16)
  5817. except ValueError, msg:
  5818. return "Invalid value: %s" % a
  5819. return 0
  5820.  
  5821. if not heap or ( heap in imm.getHeapsAddress() ):
  5822. s = SearchHeap(imm, what, action, value, heap = heap, restore = restore, option = chunkdisplay)
  5823. if heap:
  5824. return "Heap 0x%x dumped" % heap
  5825. else:
  5826. return "Heap dumped"
  5827. return "Wrong Heap"# -*- coding: utf-8 -*-
  5828. from immlib import *
  5829. import getopt
  5830.  
  5831. def main(args):
  5832. """
  5833. Script to search all occurences of a string in memory and
  5834. display them on a table. Useful (for me) to visualize heap
  5835. layout created by heap spray.
  5836.  
  5837. !searchspray -h fe ca fe ca 11 11 11 11
  5838. !searchspray -s I am evil homer
  5839. """
  5840. imm = Debugger()
  5841.  
  5842. try:
  5843. opts, argo = getopt.getopt(args, "s:h:", ["string", "hex"])
  5844. except getopt.GetoptError, err:
  5845. usage(dbg)
  5846. return str(err)
  5847.  
  5848. opt = " ".join(args[1:]).strip('"')
  5849.  
  5850. if args[0] == "-s":
  5851. string = opt
  5852. elif args[0] == "-h":
  5853. string = "".join(["%c" % int(i, 16) for i in opt.split()])
  5854.  
  5855. log = imm.createTable("Heap Spray", ["#", "Adddress", "What?"])
  5856. i = 0
  5857. for a in imm.search(string):
  5858. i += 1
  5859. log.add(a, [str(i), str(hex(a)), " ".join(["%x" %ord(j) for j in string])])
  5860.  
  5861. return "Logging to Heap Spray Window"
  5862. import socket
  5863. import struct
  5864.  
  5865. from immlib import *
  5866.  
  5867.  
  5868. DESC="""Creates a table that displays packets received on the network."""
  5869.  
  5870. #############################################################################
  5871. '''
  5872. Some defines for re-use.
  5873. '''
  5874. PACKET_TYPE_SEND = "Send "
  5875. PACKET_TYPE_RECV = "Recv "
  5876. PACKET_PROTOCOL_UDP = "(UDP)"
  5877. PACKET_PROTOCOL_TCP = "(TCP)"
  5878.  
  5879.  
  5880. #############################################################################
  5881. class simple_hooks(LogBpHook):
  5882.  
  5883. #########################################################################
  5884. def __init__(self):
  5885. LogBpHook.__init__(self)
  5886.  
  5887.  
  5888. #########################################################################
  5889. def run(self,regs):
  5890.  
  5891. imm = Debugger()
  5892.  
  5893. (payload_ptr,type,function_name) = imm.getKnowledge("%08x" % regs['EIP'])
  5894.  
  5895. # The length is stored as a function return argument, so let's read EAX
  5896. length = regs['EAX']
  5897.  
  5898.  
  5899. # Because return codes can be -1 (error) we have to test for that.
  5900. if length > 1 and length != 0xffffffff:
  5901.  
  5902. counter = 0
  5903. payload = ""
  5904. bin_payload = ""
  5905.  
  5906. # Get the raw packet payload and the length of the bytes
  5907. raw_payload = imm.readMemory(payload_ptr,length)
  5908.  
  5909.  
  5910.  
  5911. pack_len = str(length)+"c"
  5912. imm.log("Pack Len: %s " % pack_len)
  5913. if raw_payload is not None:
  5914.  
  5915. final_payload = struct.unpack(pack_len,raw_payload)
  5916.  
  5917. # Iterate through the unpacked string, only outputting printable
  5918. # ascii characters, output the standard dots if non-printable
  5919. while counter < int(length):
  5920. if ord(final_payload[counter]) >= 32 and ord(final_payload[counter]) <= 126:
  5921. payload += final_payload[counter]
  5922. else:
  5923. payload += "."
  5924.  
  5925. bin_payload += "%02x" % ord(final_payload[counter])
  5926. counter += 1
  5927.  
  5928. # Build the list thats table-friendly
  5929. log_items = [function_name,type,"%d" % int(length),bin_payload[:512],payload[:512]]
  5930.  
  5931. # Get a handle to the window and add the items, along with the related
  5932. # address, this is sweet cause you can double-click on a packet and
  5933. # see in the disassembly where it was sent/received :)
  5934. cap_win = imm.getKnowledge("cap_win")
  5935. cap_win.add(regs['EIP'],log_items)
  5936.  
  5937. # Drop the entry in the KB, disable the BP, and unHook.
  5938. imm.forgetKnowledge("%08x" % regs['EIP'])
  5939. imm.disableBreakpoint(regs['EIP'])
  5940. self.UnHook()
  5941.  
  5942.  
  5943. #############################################################################
  5944. class ext_hooks(LogBpHook):
  5945.  
  5946.  
  5947. #########################################################################
  5948. def __init__(self):
  5949. LogBpHook.__init__(self)
  5950.  
  5951.  
  5952. #########################################################################
  5953. def run(self,regs):
  5954.  
  5955. imm = Debugger()
  5956.  
  5957. (payload_ptr,recv_ptr,type,function_name) = imm.getKnowledge("%08x" % regs['EIP'])
  5958.  
  5959. # This is an [out] pointer that let's us know how much data was
  5960. # received on a socket (non-overlapped)
  5961. length = imm.readMemory(recv_ptr,4)
  5962. length = struct.unpack("l",length)
  5963.  
  5964. # Network apps are chatty, we don't want to grab garbage packets
  5965. if length[0] > 1:
  5966.  
  5967. counter = 0
  5968. payload = ""
  5969. bin_payload = ""
  5970.  
  5971. # Get the raw packet payload and the length of the bytes
  5972. raw_payload = imm.readMemory(payload_ptr,int(length[0]))
  5973. pack_len = str(int(length[0]))+"c"
  5974.  
  5975. if raw_payload is not None:
  5976.  
  5977. final_payload = struct.unpack(pack_len,raw_payload)
  5978.  
  5979. # Iterate through the unpacked string, only outputting printable
  5980. # ascii characters, output the standard dots if non-printable
  5981. while counter < int(length[0]):
  5982. if ord(final_payload[counter]) >= 32 and ord(final_payload[counter]) <= 126:
  5983. payload += final_payload[counter]
  5984. else:
  5985. payload += "."
  5986.  
  5987. bin_payload += "%02x" % ord(final_payload[counter])
  5988. counter += 1
  5989.  
  5990. # Build the list thats table-friendly
  5991. log_items = [function_name,type,"%d" % int(length[0]),bin_payload[:512],payload[:512]]
  5992.  
  5993. # Get a handle to the window and add the items, along with the related
  5994. # address, this is sweet cause you can double-click on a packet and
  5995. # see in the disassembly where it was sent/received :)
  5996. cap_win = imm.getKnowledge("cap_win")
  5997. cap_win.add(regs['EIP'],log_items)
  5998.  
  5999.  
  6000. # Drop the entry in the KB, disable the BP, and unHook.
  6001. imm.forgetKnowledge("%08x" % regs['EIP'])
  6002. imm.disableBreakpoint(regs['EIP'])
  6003. self.UnHook()
  6004.  
  6005.  
  6006. #############################################################################
  6007. class set_hooks(LogBpHook):
  6008. def __init__(self):
  6009. LogBpHook.__init__(self)
  6010.  
  6011. #########################################################################
  6012. def run(self,regs):
  6013. '''
  6014. This routine is the first one hit, when a socket operation occurs.
  6015. '''
  6016. imm = Debugger()
  6017.  
  6018.  
  6019. # Retrieve the function name
  6020. function_name = imm.getKnowledge("%08x" % regs['EIP'])
  6021.  
  6022. #self.retrieve_packet(imm,function_name,regs)
  6023. self.display_mem_reg(imm,function_name,regs)
  6024.  
  6025.  
  6026. #########################################################################
  6027. def display_mem_reg(self,imm,function_name,regs):
  6028. '''
  6029. display info in log
  6030. '''
  6031. #Figure out [esp]
  6032. #esp_ptr = imm.readMemory(regs['ESP'],4)
  6033. #esp_ptr = struct.unpack("<L", esp_ptr)
  6034. imm.log("%s" % function_name)
  6035. imm.log("[ESP] @ 0x%08x" % regs['ESP'])
  6036. imm.log("[EIP] @ 0x%08x" % regs['EIP'])
  6037. imm.log("[EAX] @ 0x%08x" % regs['EAX'])
  6038.  
  6039. ## #########################################################################
  6040. ## def retrieve_packet(self,imm,function_name,regs):
  6041. ## '''
  6042. ## This function determines how to handle the packet data. Some socket
  6043. ## operations require more work (such as WSARecv), and others less (recv).
  6044. ##
  6045. ## If necessary this function will register a hook on [ESP], where any
  6046. ## [out] pointers from a function will be set.
  6047. ## '''
  6048. ##
  6049. ## # Determine what function we have hooked, based on this, retrieve the packet contents
  6050. ## if function_name == "WSARecv":
  6051. ## type = PACKET_TYPE_RECV+PACKET_PROTOCOL_TCP
  6052. ## extended_hook = True
  6053. ##
  6054. ## if function_name == "WSASend":
  6055. ## type=PACKET_TYPE_SEND+PACKET_PROTOCOL_TCP
  6056. ## extended_hook = True
  6057. ##
  6058. ## if function_name == "recvfrom":
  6059. ## type=PACKET_TYPE_RECV+PACKET_PROTOCOL_UDP
  6060. ## extended_hook = False
  6061. ##
  6062. ## if function_name =="recv":
  6063. ## type=PACKET_TYPE_RECV+PACKET_PROTOCOL_TCP
  6064. ## extended_hook = False
  6065. ##
  6066. ## # An extended hook requires a bit more work to pull out the packet info
  6067. ## if extended_hook == True:
  6068. ##
  6069. ## # Get the pointer to the payload pointer :(
  6070. ## pbuffer_ptr = imm.readMemory( regs['ESP'] + 8, 4)
  6071. ## pbuffer_ptr = struct.unpack("L", pbuffer_ptr)
  6072. ## #imm.log("Buffer Location: 0x%08x" % pbuffer_ptr[0])
  6073. ##
  6074. ## # Get the pointer to the packet payload
  6075. ## payload_ptr = imm.readMemory(pbuffer_ptr[0]+4,4)
  6076. ## payload_ptr = struct.unpack("<L", payload_ptr)
  6077. ## #imm.log("Payload Pointer: %08x" % payload_ptr[0])
  6078. ##
  6079. ## # Get the [out] pointer of the received bytes
  6080. ## recv_ptr = imm.readMemory(regs['ESP'] + 0x10, 4)
  6081. ## recv_ptr = struct.unpack("L",recv_ptr)
  6082. ## #imm.log("Receive Pointer: %08x" % recv_ptr[0])
  6083. ##
  6084. ## # Figure out [esp]
  6085. ## esp_ptr = imm.readMemory(regs['ESP'],4)
  6086. ## esp_ptr = struct.unpack("<L", esp_ptr)
  6087. ## #imm.log("[ESP] at 0x%08x" % esp_ptr[0])
  6088. ##
  6089. ## # Now we hook [esp]
  6090. ## ret_hook = ext_hooks()
  6091. ## ret_hook.add("%08x" % esp_ptr[0],esp_ptr[0])
  6092. ##
  6093. ## # Add this ret hook to the knowledgebase
  6094. ## imm.addKnowledge("%08x" % esp_ptr[0],(payload_ptr[0],recv_ptr[0],type,function_name))
  6095. ##
  6096. ## else:
  6097. ##
  6098. ## # Get the pointer to the buffer
  6099. ## payload_ptr = imm.readMemory(regs['ESP'] + 8, 4)
  6100. ## payload_ptr = struct.unpack("L", payload_ptr)
  6101. ##
  6102. ## # Figure out where [ESP] points to
  6103. ## esp_ptr = imm.readMemory(regs['ESP'],4)
  6104. ## esp_ptr = struct.unpack("<L", esp_ptr)
  6105. ##
  6106. ## # Add the [ESP] hook for when the function returns
  6107. ## simple_hook = simple_hooks()
  6108. ## simple_hook.add("%08x" % esp_ptr[0],esp_ptr[0])
  6109. ##
  6110. ## # Add our pertinent information to the knowledgebase
  6111. ## imm.addKnowledge("%08x" % esp_ptr[0],(payload_ptr[0],type,function_name))
  6112.  
  6113.  
  6114. # The main routine that gets run when you type !packets
  6115. def main(args):
  6116.  
  6117. imm = Debugger()
  6118. imm.ignoreSingleStep("CONTINUE")
  6119. hooker = set_hooks()
  6120.  
  6121. # Find the addresses of the functions we want to hook
  6122. # Then register the hooks
  6123. ws_send = imm.getAddress("ws2_32.send")
  6124. ws_sendto = imm.getAddress("ws2_32.sendto")
  6125. ws_wsarecv = imm.getAddress("ws2_32.WSARecv")
  6126. ws_wsasend = imm.getAddress("ws2_32.WSASend")
  6127. ws_recv = imm.getAddress("ws2_32.recv")
  6128. ws_recvfrom = imm.getAddress("ws2_32.recvfrom")
  6129.  
  6130. # Set the hooks
  6131. hooker.add("send", ws_send)
  6132. hooker.add("sendto", ws_sendto)
  6133. hooker.add("WSARecv", ws_wsarecv)
  6134. hooker.add("WSASend", ws_wsasend)
  6135. hooker.add("recv", ws_recv)
  6136. hooker.add("recvfrom", ws_recvfrom)
  6137.  
  6138.  
  6139. # Register the hook-address pair with the knowledgebase
  6140. imm.addKnowledge("%08x" % ws_wsarecv, "WSARecv")
  6141. imm.addKnowledge("%08x" % ws_wsasend, "WSASend")
  6142. imm.addKnowledge("%08x" % ws_recv, "recv")
  6143. imm.addKnowledge("%08x" % ws_recvfrom, "recvfrom")
  6144.  
  6145.  
  6146. return "Network hooks in place."
  6147.  
  6148.  
  6149. #!/usr/bin/env python
  6150.  
  6151. """
  6152. (c) Immunity, Inc. 2004-2008
  6153.  
  6154.  
  6155. U{Immunity Inc.<http://www.immunityinc.com>}
  6156.  
  6157. Shellcode diff
  6158.  
  6159. """
  6160.  
  6161. DESC="""Check for badchars"""
  6162.  
  6163. from immlib import *
  6164. import sys
  6165.  
  6166. NAME = "shellcodediff"
  6167. USAGE = "address"
  6168.  
  6169. def main(args):
  6170. imm = Debugger()
  6171.  
  6172. if len(args) != 1:
  6173. imm.log("Usage: !" + NAME + " " + USAGE)
  6174. return "See log window for usage info"
  6175.  
  6176. address = 0
  6177. length = 0
  6178. bad_byte_offset = 0
  6179. mangled = False
  6180.  
  6181. address = int(args[0],16)
  6182.  
  6183. fd = open("shellcode.txt","r")
  6184. canvas_byte_list = fd.readlines()
  6185. fd.close()
  6186.  
  6187. canvas_shellcode = ""
  6188. # Just pretty this up
  6189. for i in canvas_byte_list:
  6190. canvas_shellcode += i.rstrip("\x0a")
  6191. length = len(canvas_shellcode) / 2
  6192.  
  6193. id_shellcode = imm.readMemory( address, length )
  6194. id_shellcode = id_shellcode.encode("HEX")
  6195. imm.log("Address: 0x%08x" % address)
  6196. imm.log("SC Len : %d" % length)
  6197.  
  6198. imm.log("CANVAS Shellcode: %s" % canvas_shellcode[:512])
  6199. imm.log("ID Shellcode: %s" % id_shellcode[:512])
  6200.  
  6201. count = 0
  6202.  
  6203. # We use the CANVAS shellcode length here again cause
  6204. # presumably its not mangled
  6205. while count <= (length*2):
  6206.  
  6207. if id_shellcode[count] != canvas_shellcode[count]:
  6208.  
  6209. imm.log("Missed at byte: %d" % count)
  6210. bad_byte_offset = count
  6211. mangled = True
  6212. break
  6213.  
  6214. count += 1
  6215.  
  6216. if mangled:
  6217. imm.log(" ")
  6218. imm.log("Bad byte is centered in output with three leading and three trailing bytes.")
  6219. imm.log(" ")
  6220. imm.log("Bad byte at offset: %d" % bad_byte_offset)
  6221. imm.log("Bad byte value from attacker: %s" % canvas_shellcode[bad_byte_offset:bad_byte_offset+2])
  6222. imm.log("====================\n\n")
  6223.  
  6224. imm.log("CANVAS: %s %s %s" % (canvas_shellcode[bad_byte_offset-6:bad_byte_offset],canvas_shellcode[bad_byte_offset:bad_byte_offset+2],canvas_shellcode[bad_byte_offset+2:bad_byte_offset+6]))
  6225. imm.log("ID : %s %s %s" % (id_shellcode[bad_byte_offset-6:bad_byte_offset], id_shellcode[bad_byte_offset:bad_byte_offset+2],id_shellcode[bad_byte_offset+2:bad_byte_offset+6]))
  6226.  
  6227. imm.log("\n\n====================")
  6228.  
  6229.  
  6230.  
  6231. return "Shellcode diff output to log window."
  6232. #/usr/bin/env python
  6233.  
  6234. import getopt
  6235. import xmlrpclib
  6236. import traceback
  6237. import struct
  6238. import debugger #needed on old ID for removeHook
  6239.  
  6240. from immlib import *
  6241.  
  6242. LICENSE="BSD 3-clause non-attribution" #yay!
  6243. copyright="(C) Immunity, Inc., jms@bughunter.ca"
  6244.  
  6245. """
  6246.  
  6247. This script supports the SQLOLEDB method of executing queries and, when
  6248. combined with sql_listener.py will send you all the queries executed by a web
  6249. application. Server-side filtering (necessary to avoid sending thousands of
  6250. queries a second to you on a busy server) is stubbed in for later. We hooked
  6251. IIS rather than SQL Server because common practice is to have your SQL tier
  6252. un-routable, but the web tier is likely to have Internet access.
  6253.  
  6254. Somewhat later we'll have this integrate into SPIKE Proxy and other tools to
  6255. automate detection of blind-sql attacks/detection and sql injection in
  6256. general.
  6257.  
  6258. In order to use this script:
  6259.  
  6260. 1. Run a few queries against your target server, this will start up two
  6261. dllhost.exe's
  6262.  
  6263. 2. Load Immunity Debugger and attach to the second dllhost.exe (this can be
  6264. slightly tricky if the PID for the second one is lower than the first, but
  6265. eventually we'll automate it)
  6266.  
  6267. 3. run !sqlhooker -s myhostip:myport. For example, I use !sqlhooker
  6268. 192.168.1.1:8081, and then on my .1 machine I run "python sql_listener.py
  6269. 8081".
  6270.  
  6271. Here's an example snippet of ASP script this would work against:
  6272. _start cut_
  6273. set conn = server.createObject("ADODB.Connection")
  6274. set rs = server.createObject("ADODB.Recordset")
  6275.  
  6276. query = "select count(*) from users where userName='" & userName & "' and userPass='" & password & "'"
  6277.  
  6278. conn.Open "Provider=SQLOLEDB; Data Source=(local); Initial Catalog=myDB; User Id=sa; Password="
  6279. rs.activeConnection = conn
  6280. rs.open query
  6281. _end cut_
  6282. We currently support:
  6283.  
  6284. WinXPPro Sp2, IIS 5.0 SQLServer 2000
  6285. Win2K3, IIS 6.0, SQLServer 2000
  6286. Win2K, IIS 5.0, SQLServer 2000
  6287. Win2K Old,IIS 5.0, SQLServer 2000
  6288.  
  6289. If anyone has requests for other database systems, they should email us, along
  6290. with the necessary information to get an application running, and we will
  6291. spend the time to find you hook spots. Or just submit a patch to
  6292. forum.immunityinc.com.
  6293.  
  6294.  
  6295. """
  6296.  
  6297. class ole_hooker(LogBpHook):
  6298.  
  6299. def __init__(self,hook_version,xmlhost=None,xmlport=0):
  6300.  
  6301. LogBpHook.__init__(self)
  6302.  
  6303. self.imm = Debugger()
  6304. self.hook_version = hook_version
  6305. self.xmlhost = xmlhost
  6306. self.xmlport = int(xmlport)
  6307.  
  6308. def run(self,regs):
  6309. '''
  6310. Called everytime the SQL hook is hit.
  6311. '''
  6312.  
  6313. self.imm.log("Hook version: %s" % self.hook_version)
  6314.  
  6315. if self.hook_version == "winxp_pro_sp2" or self.hook_version == "win2k3":
  6316. sql_addr = regs['EDI']
  6317.  
  6318. if self.hook_version == "win2k":
  6319. sql_addr = regs['ESI']
  6320.  
  6321. if self.hook_version == "win2k_old":
  6322. buffer_ptr = self.imm.readMemory(regs['ESP'] + 4, 4)
  6323. buffer_ptr = struct.unpack("L", buffer_ptr)
  6324. sql_addr = buffer_ptr[0]
  6325.  
  6326. sql_query = self.imm.readWString(sql_addr)
  6327. sql_query = sql_query.replace("\x00","")
  6328.  
  6329. self.imm.log("SQL Query: %s" % sql_query)
  6330.  
  6331. using_xml_rpc = False
  6332.  
  6333. if self.xmlport != 0:
  6334. server = xmlrpclib.ServerProxy("http://%s:%d/"%(self.xmlhost,self.xmlport), allow_none=True)
  6335. self.imm.log("Using server: %s:%d"%(self.xmlhost, self.xmlport))
  6336. using_xml_rpc = True
  6337. else:
  6338. server = None
  6339.  
  6340. if using_xml_rpc:
  6341. #send our xml request to the remove side
  6342. #if self.filter matches...(stub for now)
  6343. try:
  6344. result = server.sendsql(("sqlquery",[sql_query]))
  6345. except:
  6346. data=traceback.format_exc()
  6347. self.imm.log("Failed to connect to remote server, sorry")
  6348. self.imm.logLines("Error was: %s"%data)
  6349. return
  6350.  
  6351. #Now parse what we got back - a command and list of arguments
  6352. command, arguments = result
  6353. if command=="NEWFILTER":
  6354. #stub
  6355. self.filter=arguments[0]
  6356. elif command=="UNHOOK":
  6357. #stub
  6358. self.imm.log("Unhook called")
  6359. #etc
  6360. return
  6361.  
  6362. def usage(imm):
  6363. imm.log("!sqlhooker.py")
  6364. imm.log("-u (to uninstall hook)")
  6365. imm.log("-s host:port (Server to send XML-RPC data to)")
  6366.  
  6367. def main(args):
  6368.  
  6369. imm = Debugger()
  6370.  
  6371. xmlhost = None
  6372. xmlport = 0
  6373.  
  6374. sql_oledb = imm.getModule("sqloledb.dll")
  6375.  
  6376. if not sql_oledb.isAnalysed():
  6377. imm.analyseCode(sql_oledb.getCodebase())
  6378.  
  6379. try:
  6380. opts,argo = getopt.getopt(args, "ius:")
  6381. except:
  6382. return usage(imm)
  6383.  
  6384. for o,a in opts:
  6385. if o == "-u":
  6386. if hasattr(imm, "removeHook"):
  6387. imm.removeHook("query")
  6388. elif hasattr(debugger, "remove_hook"):
  6389. debugger.remove_hook("query")
  6390. else:
  6391. imm.log("Could not remove hook - no remove hook function found!")
  6392. return "Removed hook on SQL function."
  6393. if o == "-s":
  6394. xmlhost,xmlport = a.split(":")
  6395.  
  6396.  
  6397. # Various versions, we need to match on
  6398. winxp_pro_sp2 = "2000.085.1117.00 (xpsp_sp2_rtm."
  6399. win2k3 = "2000.086.3959.00 (srv03_sp2_rtm"
  6400. win2k = "2000.081.9031.018"
  6401. win2k_old = "2000.080.0194"
  6402.  
  6403. version = sql_oledb.getVersion()
  6404.  
  6405. sql_base = sql_oledb.getBaseAddress()
  6406.  
  6407. if version == winxp_pro_sp2:
  6408. offset = 0xF6F5
  6409. hook_version = "winxp_pro_sp2"
  6410.  
  6411. if version == win2k3:
  6412. offset = 0x6522
  6413. hook_version = "win2k3"
  6414.  
  6415. if version == win2k:
  6416. offset = 0xFA2D
  6417. hook_version = "win2k"
  6418.  
  6419. if version == win2k_old:
  6420. offset = 0x4034
  6421. hook_version = "win2k_old"
  6422.  
  6423. bp_address = sql_base + offset
  6424.  
  6425. # Set a hook
  6426. hooker = ole_hooker(hook_version,xmlhost,xmlport)
  6427. hooker.add("query",bp_address)
  6428.  
  6429. return "SQL Hooks in Place. Ready for Test Cases."
  6430. import socket
  6431. import struct
  6432.  
  6433. from immlib import *
  6434.  
  6435.  
  6436. DESC="""packets received on the network."""
  6437.  
  6438. #############################################################################
  6439. '''
  6440. Some defines for re-use.
  6441. '''
  6442. PACKET_TYPE_SEND = "Send "
  6443. PACKET_TYPE_RECV = "Recv "
  6444. PACKET_PROTOCOL_UDP = "(UDP)"
  6445. PACKET_PROTOCOL_TCP = "(TCP)"
  6446.  
  6447.  
  6448. #############################################################################
  6449. class simple_hooks(LogBpHook):
  6450.  
  6451. #########################################################################
  6452. def __init__(self):
  6453. LogBpHook.__init__(self)
  6454.  
  6455.  
  6456. #########################################################################
  6457. def run(self,regs):
  6458.  
  6459. imm = Debugger()
  6460.  
  6461.  
  6462. # The length is stored as a function return argument, so let's read EAX
  6463. length = regs['EAX']
  6464. imm.log("fff %d" % length)
  6465.  
  6466.  
  6467. # imm.disableBreakpoint(regs['EIP'])
  6468. # self.UnHook()
  6469.  
  6470.  
  6471. #############################################################################
  6472. class ext_hooks(LogBpHook):
  6473.  
  6474.  
  6475. #########################################################################
  6476. def __init__(self):
  6477. LogBpHook.__init__(self)
  6478.  
  6479.  
  6480. #########################################################################
  6481. def run(self,regs):
  6482.  
  6483. imm = Debugger()
  6484. imm.log("ext_hookdebugger")
  6485.  
  6486.  
  6487. #############################################################################
  6488. class set_hooks(LogBpHook):
  6489. def __init__(self):
  6490. LogBpHook.__init__(self)
  6491.  
  6492. #########################################################################
  6493. def run(self,regs):
  6494. '''
  6495. This routine is the first one hit, when a socket operation occurs.
  6496. '''
  6497. imm = Debugger()
  6498.  
  6499. imm.log("set")
  6500.  
  6501.  
  6502. self.display_mem_reg(imm,regs)
  6503.  
  6504.  
  6505. #########################################################################
  6506. def display_mem_reg(self,imm,regs):
  6507. '''
  6508. display info in log
  6509. '''
  6510. #Figure out [esp]
  6511. #esp_ptr = imm.readMemory(regs['ESP'],4)
  6512. #esp_ptr = struct.unpack("<L", esp_ptr)
  6513. #imm.log("%s" % function_name)
  6514. imm.log("[ESP] @ 0x%08x" % regs['ESP'])
  6515. imm.log("[EIP] @ 0x%08x" % regs['EIP'])
  6516. imm.log("[EAX] @ 0x%08x" % regs['EAX'])
  6517.  
  6518.  
  6519. # The main routine that gets run when you type !packets
  6520. def main(args):
  6521.  
  6522. imm = Debugger()
  6523. imm.ignoreSingleStep("CONTINUE")
  6524. hooker = set_hooks()
  6525.  
  6526. # Find the addresses of the functions we want to hook
  6527. # Then register the hooks
  6528. ws_send = imm.getAddress("ws2_32.send")
  6529. ws_sendto = imm.getAddress("ws2_32.sendto")
  6530. ws_wsarecv = imm.getAddress("ws2_32.WSARecv")
  6531. ws_wsasend = imm.getAddress("ws2_32.WSASend")
  6532. ws_recv = imm.getAddress("ws2_32.recv")
  6533. ws_recvfrom = imm.getAddress("ws2_32.recvfrom")
  6534.  
  6535. # Set the hooks
  6536. hooker.add("send", ws_send)
  6537. hooker.add("sendto", ws_sendto)
  6538. hooker.add("WSARecv", ws_wsarecv)
  6539. hooker.add("WSASend", ws_wsasend)
  6540. hooker.add("recv", ws_recv)
  6541. hooker.add("recvfrom", ws_recvfrom)
  6542.  
  6543.  
  6544. # Register the hook-address pair with the knowledgebase
  6545. # imm.addKnowledge("%08x" % ws_wsarecv, "WSARecv")
  6546. # imm.addKnowledge("%08x" % ws_wsasend, "WSASend")
  6547. # imm.addKnowledge("%08x" % ws_recv, "recv")
  6548. # imm.addKnowledge("%08x" % ws_recvfrom, "recvfrom")
  6549.  
  6550.  
  6551. return "i hooks in place."
  6552.  
  6553.  
  6554. #!/usr/bin/env python
  6555. """
  6556. Immunity Debugger stackvars
  6557.  
  6558. (c) Immunity, Inc. 2004-2007
  6559.  
  6560.  
  6561. U{Immunity Inc.<http://www.immunityinc.com>} Debugger API for python
  6562.  
  6563. stackvars.py - set comments around the code to follow stack variables size and content.
  6564.  
  6565. """
  6566.  
  6567. __VERSION__ = "1.2"
  6568.  
  6569. import immlib
  6570. import immutils
  6571. import getopt
  6572. from libstackanalyze import *
  6573.  
  6574. DESC="Set comments around the code to follow stack variables size and content"
  6575.  
  6576. def usage(imm):
  6577. imm.log("!stackvars address_or_expresion [steps_to_decode]")
  6578. imm.log("%s" % DESC)
  6579. imm.log("Note: each step represent one call further from the base function")
  6580.  
  6581. def main(args):
  6582. imm = immlib.Debugger()
  6583.  
  6584. if not args:
  6585. imm.log("you must define the address of the function to analyze")
  6586. usage(imm)
  6587. return "not enough args"
  6588.  
  6589. address = imm.getAddress(args[0])
  6590. if address < 0:
  6591. imm.log("invalid address or expresion")
  6592. usage(imm)
  6593. return "address error!"
  6594.  
  6595. if len(args) > 1:
  6596. steps_after = int(args[1])
  6597. else:
  6598. steps_after = 1
  6599.  
  6600. imm.log("################# Immunity's StackVars ################")
  6601. imm.log("Analyzing function %08X - %s..." % (address, imm.decodeAddress(address)))
  6602.  
  6603. flow = FlowAnalyzer(imm, address, steps_after)
  6604. Calls,varsHits,argsHits,varsSize = flow.getFlowInformation()
  6605.  
  6606.  
  6607. imm.log("----------- code flow -------------")
  6608. for start,data in Calls.iteritems():
  6609. imm.log("function: %s" % imm.decodeAddress(start))
  6610. for k,v in data.iteritems():
  6611. imm.log("from: %s - to: %s - argc: %d - args:" % \
  6612. (imm.decodeAddress(k), imm.decodeAddress(v[0]), len(v[1])))
  6613. for kk,vv in v[1].iteritems():
  6614. imm.log("arg %d - data: %s" % (kk,str(vv)))
  6615. imm.setComment(vv['addy'], flow.argInfo(start,k,kk))
  6616.  
  6617. #paint args
  6618. for start,data in argsHits.iteritems():
  6619. for const in data:
  6620. for hit in data[const]:
  6621. imm.setComment(hit, "using arg[%d] of function: %s" % ((const-4)/4, imm.decodeAddress(start)))
  6622.  
  6623. #paint vars
  6624. for start,data in varsHits.iteritems():
  6625. for const in data:
  6626. try:
  6627. size = varsSize[start][const]
  6628. except KeyError:
  6629. imm.log("local var size not found: addr: %08X, value: %d" % (start,const))
  6630. size = "unknown"
  6631.  
  6632. for hit in data[const]:
  6633. imm.setComment(hit, "Local Var: %X - size: %s" % (const, size))
  6634.  
  6635. imm.log("functionBegin: %08X" % flow.getFunctionBegin())
  6636.  
  6637. imm.log("-------- size of variables --------")
  6638. for start,data in varsSize.iteritems():
  6639. imm.log("function: %s" % imm.decodeAddress(start))
  6640. for const,size in data.iteritems():
  6641. imm.log("lvar %X: %d" % (const,size))
  6642.  
  6643. return "Done! see the log for details"
  6644. # (c) Immunity Inc.
  6645. # This is a port of Ero Carrera's script that he wrote for
  6646. # IDAPython. This is the same deal, however it can be easily
  6647. # expanded to track hits to these calls. The beauty of a debugger.
  6648. #
  6649. # http://www.openrce.org/blog/view/1077/Digging_up_system_call_ordinals
  6650. #
  6651. import getopt
  6652. from immlib import *
  6653.  
  6654. syscall_table = {'2003':
  6655. {'0x0103': 'NtSignalAndWaitForSingleObject',
  6656. '0x009e': 'NtQueryInformationFile',
  6657. '0x0079': 'NtOpenEventPair',
  6658. '0x0078': 'NtOpenEvent',
  6659. '0x00c9': 'NtReplaceKey',
  6660. '0x0073': 'NtModifyDriverEntry',
  6661. '0x0072': 'NtModifyBootEntry',
  6662. '0x0071': 'NtMapViewOfSection',
  6663. '0x0070': 'NtMapUserPhysicalPagesScatter',
  6664. '0x0077': 'NtOpenDirectoryObject',
  6665. '0x0076': 'NtNotifyChangeMultipleKeys',
  6666. '0x0075': 'NtNotifyChangeKey',
  6667. '0x0074': 'NtNotifyChangeDirectoryFile',
  6668. '0x008f': 'NtProtectVirtualMemory',
  6669. '0x00db': 'NtSetBootEntryOrder',
  6670. '0x008d': 'NtPrivilegeObjectAuditAlarm',
  6671. '0x008e': 'NtPrivilegedServiceAuditAlarm',
  6672. '0x008b': 'NtPowerInformation',
  6673. '0x008c': 'NtPrivilegeCheck',
  6674. '0x008a': 'NtPlugPlayControl',
  6675. '0x00ba': 'NtQueryVirtualMemory',
  6676. '0x00bb': 'NtQueryVolumeInformationFile',
  6677. '0x00bc': 'NtQueueApcThread',
  6678. '0x00bd': 'NtRaiseException',
  6679. '0x00be': 'NtRaiseHardError',
  6680. '0x00bf': 'NtReadFile',
  6681. '0x00da': 'NtSecureConnectPort',
  6682. '0x00a9': 'NtQueryMutant',
  6683. '0x00a8': 'NtQueryMultipleValueKey',
  6684. '0x000f': 'NtAllocateLocallyUniqueId',
  6685. '0x00a4': 'NtQueryInstallUILanguage',
  6686. '0x000d': 'NtAlertResumeThread',
  6687. '0x000e': 'NtAlertThread',
  6688. '0x000b': 'NtAdjustGroupsToken',
  6689. '0x000c': 'NtAdjustPrivilegesToken',
  6690. '0x00a3': 'NtQueryInformationToken',
  6691. '0x000a': 'NtAddDriverEntry',
  6692. '0x00df': 'NtSetDefaultHardErrorPort',
  6693. '0x00dd': 'NtSetContextThread',
  6694. '0x007c': 'NtOpenJobObject',
  6695. '0x007b': 'NtOpenIoCompletion',
  6696. '0x007a': 'NtOpenFile',
  6697. '0x00de': 'NtSetDebugFilterState',
  6698. '0x007f': 'NtOpenObjectAuditAlarm',
  6699. '0x007e': 'NtOpenMutant',
  6700. '0x007d': 'NtOpenKey',
  6701. '0x010f': 'NtUnloadDriver',
  6702. '0x00c3': 'NtRegisterThreadTerminatePort',
  6703. '0x0120': 'NtYieldExecution',
  6704. '0x00f9': 'NtSetSystemInformation',
  6705. '0x0008': 'NtAddAtom',
  6706. '0x0009': 'NtAddBootEntry',
  6707. '0x0006': 'NtAccessCheckByTypeResultListAndAuditAlarm',
  6708. '0x0007': 'NtAccessCheckByTypeResultListAndAuditAlarmByHandle',
  6709. '0x0004': 'NtAccessCheckByTypeAndAuditAlarm',
  6710. '0x0005': 'NtAccessCheckByTypeResultList',
  6711. '0x0002': 'NtAccessCheckAndAuditAlarm',
  6712. '0x0003': 'NtAccessCheckByType',
  6713. '0x0000': 'NtAcceptConnectPort',
  6714. '0x0001': 'NtAccessCheck',
  6715. '0x0086': 'NtOpenThread',
  6716. '0x0087': 'NtOpenThreadToken',
  6717. '0x0084': 'NtOpenSemaphore',
  6718. '0x0085': 'NtOpenSymbolicLinkObject',
  6719. '0x0082': 'NtOpenProcessTokenEx',
  6720. '0x0083': 'NtOpenSection',
  6721. '0x0080': 'NtOpenProcess',
  6722. '0x0081': 'NtOpenProcessToken',
  6723. '0x00b0': 'NtQuerySecurityObject',
  6724. '0x00b1': 'NtQuerySemaphore',
  6725. '0x00b2': 'NtQuerySymbolicLinkObject',
  6726. '0x00b3': 'NtQuerySystemEnvironmentValue',
  6727. '0x00b4': 'NtQuerySystemEnvironmentValueEx',
  6728. '0x00b5': 'NtQuerySystemInformation',
  6729. '0x0088': 'NtOpenThreadTokenEx',
  6730. '0x0089': 'NtOpenTimer',
  6731. '0x0109': 'NtTerminateJobObject',
  6732. '0x00af': 'NtQuerySection',
  6733. '0x00aa': 'NtQueryObject',
  6734. '0x010d': 'NtTraceEvent',
  6735. '0x00f1': 'NtSetIoCompletion',
  6736. '0x00ac': 'NtQueryOpenSubKeysEx',
  6737. '0x00ab': 'NtQueryOpenSubKeys',
  6738. '0x00c7': 'NtRemoveProcessDebug',
  6739. '0x00b8': 'NtQueryTimerResolution',
  6740. '0x00c5': 'NtReleaseSemaphore',
  6741. '0x00c4': 'NtReleaseMutant',
  6742. '0x0019': 'NtCancelTimer',
  6743. '0x0018': 'NtCancelIoFile',
  6744. '0x00c1': 'NtReadRequestData',
  6745. '0x00b9': 'NtQueryValueKey',
  6746. '0x0015': 'NtAssignProcessToJobObject',
  6747. '0x0014': 'NtAreMappedFilesTheSame',
  6748. '0x0017': 'NtCancelDeviceWakeupRequest',
  6749. '0x0016': 'NtCallbackReturn',
  6750. '0x0011': 'NtAllocateUuids',
  6751. '0x0010': 'NtAllocateUserPhysicalPages',
  6752. '0x0013': 'NtApphelpCacheControl',
  6753. '0x0012': 'NtAllocateVirtualMemory',
  6754. '0x0095': 'NtQueryDefaultLocale',
  6755. '0x0094': 'NtQueryDebugFilterState',
  6756. '0x0097': 'NtQueryDirectoryFile',
  6757. '0x0096': 'NtQueryDefaultUILanguage',
  6758. '0x0091': 'NtQueryAttributesFile',
  6759. '0x0090': 'NtPulseEvent',
  6760. '0x0093': 'NtQueryBootOptions',
  6761. '0x0092': 'NtQueryBootEntryOrder',
  6762. '0x002a': 'NtCreateJobSet',
  6763. '0x002b': 'NtCreateKey',
  6764. '0x002c': 'NtCreateMailslotFile',
  6765. '0x002d': 'NtCreateMutant',
  6766. '0x002e': 'NtCreateNamedPipeFile',
  6767. '0x002f': 'NtCreatePagingFile',
  6768. '0x00ae': 'NtQueryQuotaInformationFile',
  6769. '0x00c2': 'NtReadVirtualMemory',
  6770. '0x0028': 'NtCreateIoCompletion',
  6771. '0x0029': 'NtCreateJobObject',
  6772. '0x00d0': 'NtRequestWaitReplyPort',
  6773. '0x009f': 'NtQueryInformationJobObject',
  6774. '0x009a': 'NtQueryEaFile',
  6775. '0x00a0': 'NtQueryInformationPort',
  6776. '0x009c': 'NtQueryFullAttributesFile',
  6777. '0x009b': 'NtQueryEvent',
  6778. '0x0020': 'NtCompressKey',
  6779. '0x0021': 'NtConnectPort',
  6780. '0x0022': 'NtContinue',
  6781. '0x0023': 'NtCreateDebugObject',
  6782. '0x0024': 'NtCreateDirectoryObject',
  6783. '0x0025': 'NtCreateEvent',
  6784. '0x0026': 'NtCreateEventPair',
  6785. '0x0027': 'NtCreateFile',
  6786. '0x00cf': 'NtRequestPort',
  6787. '0x00ce': 'NtRequestDeviceWakeup',
  6788. '0x00cd': 'NtReplyWaitReplyPort',
  6789. '0x00cc': 'NtReplyWaitReceivePortEx',
  6790. '0x00b6': 'NtQuerySystemTime',
  6791. '0x00ca': 'NtReplyPort',
  6792. '0x00e8': 'NtSetInformationDebugObject',
  6793. '0x001e': 'NtCompareTokens',
  6794. '0x001d': 'NtCompactKeys',
  6795. '0x001f': 'NtCompleteConnectPort',
  6796. '0x001a': 'NtClearEvent',
  6797. '0x001c': 'NtCloseObjectAuditAlarm',
  6798. '0x001b': 'NtClose',
  6799. '0x004b': 'NtEnumerateKey',
  6800. '0x004c': 'NtEnumerateSystemEnvironmentValuesEx',
  6801. '0x004a': 'NtEnumerateDriverEntries',
  6802. '0x004f': 'NtFilterToken',
  6803. '0x011b': 'NtWaitLowEventPair',
  6804. '0x004d': 'NtEnumerateValueKey',
  6805. '0x004e': 'NtExtendSection',
  6806. '0x0037': 'NtCreateThread',
  6807. '0x0036': 'NtCreateSymbolicLinkObject',
  6808. '0x0035': 'NtCreateSemaphore',
  6809. '0x0034': 'NtCreateSection',
  6810. '0x0033': 'NtCreateProfile',
  6811. '0x0032': 'NtCreateProcessEx',
  6812. '0x0031': 'NtCreateProcess',
  6813. '0x0030': 'NtCreatePort',
  6814. '0x0039': 'NtCreateToken',
  6815. '0x0038': 'NtCreateTimer',
  6816. '0x00e1': 'NtSetDefaultUILanguage',
  6817. '0x00e0': 'NtSetDefaultLocale',
  6818. '0x00e3': 'NtSetEaFile',
  6819. '0x00e2': 'NtSetDriverEntryOrder',
  6820. '0x00e5': 'NtSetEventBoostPriority',
  6821. '0x00e4': 'NtSetEvent',
  6822. '0x00e7': 'NtSetHighWaitLowEventPair',
  6823. '0x00e6': 'NtSetHighEventPair',
  6824. '0x00e9': 'NtSetInformationFile',
  6825. 'NA': 'NtWriteErrorLogEntry',
  6826. '0x00f2': 'NtSetLdtEntries',
  6827. '0x00fd': 'NtSetTimer',
  6828. '0x00fe': 'NtSetTimerResolution',
  6829. '0x00ff': 'NtSetUuidSeed',
  6830. '0x0108': 'NtSystemDebugControl',
  6831. '0x0102': 'NtShutdownSystem',
  6832. '0x00fa': 'NtSetSystemPowerState',
  6833. '0x00fb': 'NtSetSystemTime',
  6834. '0x00fc': 'NtSetThreadExecutionState',
  6835. '0x003f': 'NtDeleteBootEntry',
  6836. '0x003e': 'NtDeleteAtom',
  6837. '0x003d': 'NtDelayExecution',
  6838. '0x003c': 'NtDebugContinue',
  6839. '0x003b': 'NtDebugActiveProcess',
  6840. '0x003a': 'NtCreateWaitablePort',
  6841. '0x009d': 'NtQueryInformationAtom',
  6842. '0x00d1': 'NtRequestWakeupLatency',
  6843. '0x0042': 'NtDeleteKey',
  6844. '0x0043': 'NtDeleteObjectAuditAlarm',
  6845. '0x0040': 'NtDeleteDriverEntry',
  6846. '0x0041': 'NtDeleteFile',
  6847. '0x0046': 'NtDisplayString',
  6848. '0x0047': 'NtDuplicateObject',
  6849. '0x0044': 'NtDeleteValueKey',
  6850. '0x0045': 'NtDeviceIoControlFile',
  6851. '0x00d6': 'NtResumeThread',
  6852. '0x0048': 'NtDuplicateToken',
  6853. '0x0049': 'NtEnumerateBootEntries',
  6854. '0x00a7': 'NtQueryKey',
  6855. '0x00d7': 'NtSaveKey',
  6856. '0x00a6': 'NtQueryIoCompletion',
  6857. '0x00f8': 'NtSetSystemEnvironmentValueEx',
  6858. '0x00d4': 'NtRestoreKey',
  6859. '0x0125': 'NtQueryPortInformationProcess',
  6860. '0x00a1': 'NtQueryInformationProcess',
  6861. '0x00f6': 'NtSetSecurityObject',
  6862. '0x0126': 'NtGetCurrentProcessorNumber',
  6863. '0x0121': 'NtCreateKeyedEvent',
  6864. '0x00d2': 'NtResetEvent',
  6865. '0x0123': 'NtReleaseKeyedEvent',
  6866. '0x0122': 'NtOpenKeyedEvent',
  6867. '0x00ea': 'NtSetInformationJobObject',
  6868. '0x00ec': 'NtSetInformationObject',
  6869. '0x00eb': 'NtSetInformationKey',
  6870. '0x00ee': 'NtSetInformationThread',
  6871. '0x00ed': 'NtSetInformationProcess',
  6872. '0x00f7': 'NtSetSystemEnvironmentValue',
  6873. '0x00ef': 'NtSetInformationToken',
  6874. '0x00a2': 'NtQueryInformationThread',
  6875. '0x00d8': 'NtSaveKeyEx',
  6876. '0x00f4': 'NtSetLowWaitHighEventPair',
  6877. '0x010e': 'NtTranslateFilePath',
  6878. '0x00d9': 'NtSaveMergedKeys',
  6879. '0x010c': 'NtTestAlert',
  6880. '0x010b': 'NtTerminateThread',
  6881. '0x010a': 'NtTerminateProcess',
  6882. '0x00a5': 'NtQueryIntervalProfile',
  6883. '0x006d': 'NtMakePermanentObject',
  6884. '0x006e': 'NtMakeTemporaryObject',
  6885. '0x006f': 'NtMapUserPhysicalPages',
  6886. '0x00d3': 'NtResetWriteWatch',
  6887. '0x006a': 'NtLockProductActivationKeys',
  6888. '0x006b': 'NtLockRegistryKey',
  6889. '0x006c': 'NtLockVirtualMemory',
  6890. '0x0051': 'NtFlushBuffersFile',
  6891. '0x0050': 'NtFindAtom',
  6892. '0x0053': 'NtFlushKey',
  6893. '0x0052': 'NtFlushInstructionCache',
  6894. '0x0055': 'NtFlushWriteBuffer',
  6895. '0x0054': 'NtFlushVirtualMemory',
  6896. '0x0057': 'NtFreeVirtualMemory',
  6897. '0x0056': 'NtFreeUserPhysicalPages',
  6898. '0x0059': 'NtGetContextThread',
  6899. '0x0058': 'NtFsControlFile',
  6900. '0x00c8': 'NtRenameKey',
  6901. '0x00f5': 'NtSetQuotaInformationFile',
  6902. '0x0118': 'NtWaitForMultipleObjects',
  6903. '0x0119': 'NtWaitForSingleObject',
  6904. '0x0124': 'NtWaitForKeyedEvent',
  6905. '0x00d5': 'NtResumeProcess',
  6906. '0x0110': 'NtUnloadKey',
  6907. '0x0111': 'NtUnloadKey2',
  6908. '0x00f3': 'NtSetLowEventPair',
  6909. '0x0113': 'NtUnlockFile',
  6910. '0x0114': 'NtUnlockVirtualMemory',
  6911. '0x0115': 'NtUnmapViewOfSection',
  6912. '0x0116': 'NtVdmControl',
  6913. '0x0117': 'NtWaitForDebugEvent',
  6914. '0x00cb': 'NtReplyWaitReceivePort',
  6915. '0x005a': 'NtGetDevicePowerState',
  6916. '0x005c': 'NtGetWriteWatch',
  6917. '0x005b': 'NtGetPlugPlayEvent',
  6918. '0x005e': 'NtImpersonateClientOfPort',
  6919. '0x005d': 'NtImpersonateAnonymousToken',
  6920. '0x005f': 'NtImpersonateThread',
  6921. '0x011a': 'NtWaitHighEventPair',
  6922. '0x0107': 'NtSuspendThread',
  6923. '0x0106': 'NtSuspendProcess',
  6924. '0x0105': 'NtStopProfile',
  6925. '0x0099': 'NtQueryDriverEntryOrder',
  6926. '0x0068': 'NtLoadKeyEx',
  6927. '0x0069': 'NtLockFile',
  6928. '0x0101': 'NtSetVolumeInformationFile',
  6929. '0x0100': 'NtSetValueKey',
  6930. '0x0064': 'NtListenPort',
  6931. '0x0065': 'NtLoadDriver',
  6932. '0x0066': 'NtLoadKey',
  6933. '0x0067': 'NtLoadKey2',
  6934. '0x0060': 'NtInitializeRegistry',
  6935. '0x0061': 'NtInitiatePowerAction',
  6936. '0x0062': 'NtIsProcessInJob',
  6937. '0x0063': 'NtIsSystemResumeAutomatic',
  6938. '0x00f0': 'NtSetIntervalProfile',
  6939. '0x00dc': 'NtSetBootOptions',
  6940. '0x00b7': 'NtQueryTimer',
  6941. '0x0104': 'NtStartProfile',
  6942. '0x011e': 'NtWriteRequestData',
  6943. '0x0098': 'NtQueryDirectoryObject',
  6944. '0x00c6': 'NtRemoveIoCompletion',
  6945. '0x00c0': 'NtReadFileScatter',
  6946. '0x011c': 'NtWriteFile',
  6947. '0x011d': 'NtWriteFileGather',
  6948. '0x0112': 'NtUnloadKeyEx',
  6949. '0x011f': 'NtWriteVirtualMemory',
  6950. '0x00ad': 'NtQueryPerformanceCounter'},
  6951. '2000': {
  6952. '0x009e': 'NtQueueApcThread',
  6953. '0x0079': 'NtQueryInformationAtom',
  6954. '0x0078': 'NtPulseEvent',
  6955. '0x00c9': 'NtSetIntervalProfile',
  6956. '0x0073': 'NtPowerInformation',
  6957. '0x0072': 'NtPlugPlayControl',
  6958. '0x0071': 'NtOpenTimer',
  6959. '0x0070': 'NtOpenThreadToken',
  6960. '0x0077': 'NtProtectVirtualMemory',
  6961. '0x0076': 'NtPrivilegeObjectAuditAlarm',
  6962. '0x0075': 'NtPrivilegedServiceAuditAlarm',
  6963. '0x0074': 'NtPrivilegeCheck',
  6964. '0x008f': 'NtQueryOpenSubKeys',
  6965. '0x00d3': 'NtSetThreadExecutionState',
  6966. '0x008d': 'NtQueryMutant',
  6967. '0x008e': 'NtQueryObject',
  6968. '0x008b': 'NtQueryKey',
  6969. '0x008c': 'NtQueryMultipleValueKey',
  6970. '0x008a': 'NtQueryIntervalProfile',
  6971. '0x00ba': 'NtSetContextThread',
  6972. '0x00bb': 'NtSetDefaultHardErrorPort',
  6973. '0x00bc': 'NtSetDefaultLocale',
  6974. '0x00bd': 'NtSetDefaultUILanguage',
  6975. '0x00be': 'NtSetEaFile',
  6976. '0x00bf': 'NtSetEvent',
  6977. '0x00da': 'NtSignalAndWaitForSingleObject',
  6978. '0x00a9': 'NtReplaceKey',
  6979. '0x00a8': 'NtRemoveIoCompletion',
  6980. '0x000f': 'NtAllocateUuids',
  6981. '0x00a4': 'NtReadVirtualMemory',
  6982. '0x000d': 'NtAllocateLocallyUniqueId',
  6983. '0x000e': 'NtAllocateUserPhysicalPages',
  6984. '0x000b': 'NtAlertResumeThread',
  6985. '0x000c': 'NtAlertThread',
  6986. '0x00a3': 'NtReadRequestData',
  6987. '0x000a': 'NtAdjustPrivilegesToken',
  6988. '0x00df': 'NtTerminateJobObject',
  6989. '0x00dd': 'NtSuspendThread',
  6990. '0x00b9': 'NtSetIoCompletion',
  6991. '0x007c': 'NtQueryDefaultUILanguage',
  6992. '0x007b': 'NtQueryDefaultLocale',
  6993. '0x007a': 'NtQueryAttributesFile',
  6994. '0x00de': 'NtSystemDebugControl',
  6995. '0x007f': 'NtQueryEaFile',
  6996. '0x007e': 'NtQueryDirectoryObject',
  6997. '0x007d': 'NtQueryDirectoryFile',
  6998. '0x00c3': 'NtSetInformationJobObject',
  6999. '0x0008': 'NtAddAtom',
  7000. '0x0009': 'NtAdjustGroupsToken',
  7001. '0x0006': 'NtAccessCheckByTypeResultListAndAuditAlarm',
  7002. '0x0007': 'NtAccessCheckByTypeResultListAndAuditAlarmByHandle',
  7003. '0x0004': 'NtAccessCheckByTypeAndAuditAlarm',
  7004. '0x0005': 'NtAccessCheckByTypeResultList',
  7005. '0x0002': 'NtAccessCheckAndAuditAlarm',
  7006. '0x0003': 'NtAccessCheckByType',
  7007. '0x0000': 'NtAcceptConnectPort',
  7008. '0x0001': 'NtAccessCheck',
  7009. '0x0086': 'NtQueryInformationProcess',
  7010. '0x0087': 'NtQueryInformationThread',
  7011. '0x0084': 'NtQueryIoCompletion',
  7012. '0x0085': 'NtQueryInformationPort',
  7013. '0x0082': 'NtQueryInformationFile',
  7014. '0x0083': 'NtQueryInformationJobObject',
  7015. '0x0080': 'NtQueryEvent',
  7016. '0x0081': 'NtQueryFullAttributesFile',
  7017. '0x00b0': 'NtRequestWaitReplyPort',
  7018. '0x00b1': 'NtRequestWakeupLatency',
  7019. '0x00b2': 'NtResetEvent',
  7020. '0x00b3': 'NtResetWriteWatch',
  7021. '0x00b4': 'NtRestoreKey',
  7022. '0x00b5': 'NtResumeThread',
  7023. '0x0088': 'NtQueryInformationToken',
  7024. '0x0089': 'NtQueryInstallUILanguage',
  7025. '0x00af': 'NtRequestPort',
  7026. '0x00aa': 'NtReplyPort',
  7027. '0x00ac': 'NtReplyWaitReceivePortEx',
  7028. '0x00ab': 'NtReplyWaitReceivePort',
  7029. '0x00c7': 'NtSetInformationThread',
  7030. '0x00b8': 'NtSecureConnectPort',
  7031. '0x00c5': 'NtSetInformationObject',
  7032. '0x00c4': 'NtSetInformationKey',
  7033. '0x0019': 'NtCloseObjectAuditAlarm',
  7034. '0x0018': 'NtClose',
  7035. '0x00c1': 'NtSetHighWaitLowEventPair',
  7036. '0x00c0': 'NtSetHighEventPair',
  7037. '0x0015': 'NtCancelTimer',
  7038. '0x0014': 'NtCancelIoFile',
  7039. '0x0017': 'NtClearEvent',
  7040. '0x0016': 'NtCancelDeviceWakeupRequest',
  7041. '0x0011': 'NtAreMappedFilesTheSame',
  7042. '0x0010': 'NtAllocateVirtualMemory',
  7043. '0x0013': 'NtCallbackReturn',
  7044. '0x0012': 'NtAssignProcessToJobObject',
  7045. '0x0095': 'NtQuerySymbolicLinkObject',
  7046. '0x0094': 'NtQuerySemaphore',
  7047. '0x0097': 'NtQuerySystemInformation',
  7048. '0x0096': 'NtQuerySystemEnvironmentValue',
  7049. '0x0091': 'NtQueryQuotaInformationFile',
  7050. '0x0090': 'NtQueryPerformanceCounter',
  7051. '0x0093': 'NtQuerySecurityObject',
  7052. '0x0092': 'NtQuerySection',
  7053. '0x002a': 'NtCreateProfile',
  7054. '0x002b': 'NtCreateSection',
  7055. '0x002c': 'NtCreateSemaphore',
  7056. '0x002d': 'NtCreateSymbolicLinkObject',
  7057. '0x002e': 'NtCreateThread',
  7058. '0x002f': 'NtCreateTimer',
  7059. '0x00ae': 'NtRequestDeviceWakeup',
  7060. '0x00c2': 'NtSetInformationFile',
  7061. '0x0028': 'NtCreatePort',
  7062. '0x0029': 'NtCreateProcess',
  7063. '0x00d0': 'NtSetSystemInformation',
  7064. '0x009f': 'NtRaiseException',
  7065. '0x009a': 'NtQueryTimerResolution',
  7066. '0x00a0': 'NtRaiseHardError',
  7067. '0x009c': 'NtQueryVirtualMemory',
  7068. '0x009b': 'NtQueryValueKey',
  7069. '0x0020': 'NtCreateFile',
  7070. '0x0021': 'NtCreateIoCompletion',
  7071. '0x0022': 'NtCreateJobObject',
  7072. '0x0023': 'NtCreateKey',
  7073. '0x0024': 'NtCreateMailslotFile',
  7074. '0x0025': 'NtCreateMutant',
  7075. '0x0026': 'NtCreateNamedPipeFile',
  7076. '0x0027': 'NtCreatePagingFile',
  7077. '0x00cf': 'NtSetSystemEnvironmentValue',
  7078. '0x00ce': 'NtSetSecurityObject',
  7079. '0x00cd': 'NtSetQuotaInformationFile',
  7080. '0x00cc': 'NtSetLowWaitHighEventPair',
  7081. '0x00b6': 'NtSaveKey',
  7082. '0x00ca': 'NtSetLdtEntries',
  7083. '0x00e8': 'NtVdmControl',
  7084. '0x001e': 'NtCreateEvent',
  7085. '0x001d': 'NtCreateDirectoryObject',
  7086. '0x001f': 'NtCreateEventPair',
  7087. '0x001a': 'NtCompleteConnectPort',
  7088. '0x001c': 'NtContinue',
  7089. '0x001b': 'NtConnectPort',
  7090. '0x004b': 'NtGetPlugPlayEvent',
  7091. '0x004c': 'NtGetTickCount',
  7092. '0x004a': 'NtGetDevicePowerState',
  7093. '0x004f': 'NtImpersonateClientOfPort',
  7094. '0x004d': 'NtGetWriteWatch',
  7095. '0x004e': 'NtImpersonateAnonymousToken',
  7096. '0x0037': 'NtDeleteValueKey',
  7097. '0x0036': 'NtDeleteObjectAuditAlarm',
  7098. '0x0035': 'NtDeleteKey',
  7099. '0x0034': 'NtDeleteFile',
  7100. '0x0033': 'NtDeleteAtom',
  7101. '0x0032': 'NtDelayExecution',
  7102. '0x0031': 'NtCreateWaitablePort',
  7103. '0x0030': 'NtCreateToken',
  7104. '0x0039': 'NtDisplayString',
  7105. '0x0038': 'NtDeviceIoControlFile',
  7106. '0x00e1': 'NtTerminateThread',
  7107. '0x00e0': 'NtTerminateProcess',
  7108. '0x00e3': 'NtUnloadDriver',
  7109. '0x00e2': 'NtTestAlert',
  7110. '0x00e5': 'NtUnlockFile',
  7111. '0x00e4': 'NtUnloadKey',
  7112. '0x00e7': 'NtUnmapViewOfSection',
  7113. '0x00e6': 'NtUnlockVirtualMemory',
  7114. '0x00e9': 'NtWaitForMultipleObjects',
  7115. 'NA': 'NtWriteErrorLogEntry',
  7116. '0x003f': 'NtFilterToken',
  7117. '0x003e': 'NtExtendSection',
  7118. '0x003d': 'NtEnumerateValueKey',
  7119. '0x003c': 'NtEnumerateKey',
  7120. '0x003b': 'NtDuplicateToken',
  7121. '0x003a': 'NtDuplicateObject',
  7122. '0x009d': 'NtQueryVolumeInformationFile',
  7123. '0x00d1': 'NtSetSystemPowerState',
  7124. '0x0042': 'NtFlushInstructionCache',
  7125. '0x0043': 'NtFlushKey',
  7126. '0x0040': 'NtFindAtom',
  7127. '0x0041': 'NtFlushBuffersFile',
  7128. '0x0046': 'NtFreeUserPhysicalPages',
  7129. '0x0047': 'NtFreeVirtualMemory',
  7130. '0x0044': 'NtFlushVirtualMemory',
  7131. '0x0045': 'NtFlushWriteBuffer',
  7132. '0x00d6': 'NtSetUuidSeed',
  7133. '0x0048': 'NtFsControlFile',
  7134. '0x0049': 'NtGetContextThread',
  7135. '0x00a7': 'NtReleaseSemaphore',
  7136. '0x00d7': 'NtSetValueKey',
  7137. '0x00a6': 'NtReleaseMutant',
  7138. '0x00d4': 'NtSetTimer',
  7139. '0x00f4': 'NtReplyWaitSendChannel',
  7140. '0x00a1': 'NtReadFile',
  7141. '0x00f6': 'NtSetContextChannel',
  7142. '0x00d5': 'NtSetTimerResolution',
  7143. '0x00f0': 'NtWriteVirtualMemory',
  7144. '0x00f1': 'NtCreateChannel',
  7145. '0x00f2': 'NtListenChannel',
  7146. '0x00f3': 'NtOpenChannel',
  7147. '0x00ea': 'NtWaitForSingleObject',
  7148. '0x00ec': 'NtWaitLowEventPair',
  7149. '0x00eb': 'NtWaitHighEventPair',
  7150. '0x00ee': 'NtWriteFileGather',
  7151. '0x00ed': 'NtWriteFile',
  7152. '0x00f7': 'NtYieldExecution',
  7153. '0x00ef': 'NtWriteRequestData',
  7154. '0x00a2': 'NtReadFileScatter',
  7155. '0x00d8': 'NtSetVolumeInformationFile',
  7156. '0x00d9': 'NtShutdownSystem',
  7157. '0x00a5': 'NtRegisterThreadTerminatePort',
  7158. '0x006d': 'NtOpenSemaphore',
  7159. '0x006e': 'NtOpenSymbolicLinkObject',
  7160. '0x006f': 'NtOpenThread',
  7161. '0x00d2': 'NtSetSystemTime',
  7162. '0x006a': 'NtOpenProcess',
  7163. '0x006b': 'NtOpenProcessToken',
  7164. '0x006c': 'NtOpenSection',
  7165. '0x0051': 'NtInitializeRegistry',
  7166. '0x0050': 'NtImpersonateThread',
  7167. '0x0053': 'NtIsSystemResumeAutomatic',
  7168. '0x0052': 'NtInitiatePowerAction',
  7169. '0x0055': 'NtLoadDriver',
  7170. '0x0054': 'NtListenPort',
  7171. '0x0057': 'NtLoadKey2',
  7172. '0x0056': 'NtLoadKey',
  7173. '0x0059': 'NtLockVirtualMemory',
  7174. '0x0058': 'NtLockFile',
  7175. '0x00c8': 'NtSetInformationToken',
  7176. '0x00f5': 'NtSendWaitReplyChannel',
  7177. '0x00cb': 'NtSetLowEventPair',
  7178. '0x005a': 'NtMakeTemporaryObject',
  7179. '0x005c': 'NtMapUserPhysicalPagesScatter',
  7180. '0x005b': 'NtMapUserPhysicalPages',
  7181. '0x005e': 'NtNotifyChangeDirectoryFile',
  7182. '0x005d': 'NtMapViewOfSection',
  7183. '0x005f': 'NtNotifyChangeKey',
  7184. '0x00db': 'NtStartProfile',
  7185. '0x0099': 'NtQueryTimer',
  7186. '0x0068': 'NtOpenMutant',
  7187. '0x0069': 'NtOpenObjectAuditAlarm',
  7188. '0x0064': 'NtOpenFile',
  7189. '0x0065': 'NtOpenIoCompletion',
  7190. '0x0066': 'NtOpenJobObject',
  7191. '0x0067': 'NtOpenKey',
  7192. '0x0060': 'NtNotifyChangeMultipleKeys',
  7193. '0x0061': 'NtOpenDirectoryObject',
  7194. '0x0062': 'NtOpenEvent',
  7195. '0x0063': 'NtOpenEventPair',
  7196. '0x00dc': 'NtStopProfile',
  7197. '0x00b7': 'NtSaveMergedKeys',
  7198. '0x0098': 'NtQuerySystemTime',
  7199. '0x00c6': 'NtSetInformationProcess',
  7200. '0x00ad': 'NtReplyWaitReplyPort'},
  7201. 'NT':{
  7202. '0x009e': 'NtSetHighEventPair',
  7203. '0x0079': 'NtQuerySemaphore',
  7204. '0x0078': 'NtQuerySecurityObject',
  7205. '0x00c9': 'NtWriteFileGather',
  7206. '0x0073': 'NtQueryMutant',
  7207. '0x0072': 'NtQueryMultipleValueKey',
  7208. '0x0071': 'NtQueryKey',
  7209. '0x0070': 'NtQueryIntervalProfile',
  7210. '0x0077': 'NtQuerySection',
  7211. '0x0076': 'NtQueryPerformanceCounter',
  7212. '0x0075': 'NtQueryOleDirectoryFile',
  7213. '0x0074': 'NtQueryObject',
  7214. '0x008f': 'NtReplyPort',
  7215. '0x008d': 'NtRemoveIoCompletion',
  7216. '0x008e': 'NtReplaceKey',
  7217. '0x008b': 'NtReleaseMutant',
  7218. '0x008c': 'NtReleaseSemaphore',
  7219. '0x008a': 'NtRegisterThreadTerminatePort',
  7220. '0x00ba': 'NtSystemDebugControl',
  7221. '0x00bb': 'NtTerminateProcess',
  7222. '0x00bc': 'NtTerminateThread',
  7223. '0x00bd': 'NtTestAlert',
  7224. '0x00be': 'NtUnloadDriver',
  7225. '0x00bf': 'NtUnloadKey',
  7226. '0x00a9': 'NtSetLowEventPair',
  7227. '0x00a8': 'NtSetLdtEntries',
  7228. '0x000f': 'NtClose',
  7229. '0x00a4': 'NtSetInformationProcess',
  7230. '0x000d': 'NtCancelTimer',
  7231. '0x000e': 'NtClearEvent',
  7232. '0x000b': 'NtCallbackReturn',
  7233. '0x000c': 'NtCancelIoFile',
  7234. '0x00a3': 'NtSetInformationObject',
  7235. '0x000a': 'NtAllocateVirtualMemory',
  7236. '0x007c': 'NtQuerySystemInformation',
  7237. '0x007b': 'NtQuerySystemEnvironmentValue',
  7238. '0x007a': 'NtQuerySymbolicLinkObject',
  7239. '0x007f': 'NtQueryTimerResolution',
  7240. '0x007e': 'NtQueryTimer',
  7241. '0x007d': 'NtQuerySystemTime',
  7242. '0x00c3': 'NtVdmControl',
  7243. '0x0008': 'NtAllocateLocallyUniqueId',
  7244. '0x0009': 'NtAllocateUuids',
  7245. '0x0006': 'NtAlertResumeThread',
  7246. '0x0007': 'NtAlertThread',
  7247. '0x0004': 'NtAdjustGroupsToken',
  7248. '0x0005': 'NtAdjustPrivilegesToken',
  7249. '0x0002': 'NtAccessCheckAndAuditAlarm',
  7250. '0x0003': 'NtAddAtom',
  7251. '0x0000': 'NtAcceptConnectPort',
  7252. '0x0001': 'NtAccessCheck',
  7253. '0x0086': 'NtReadFile',
  7254. '0x0087': 'NtReadFileScatter',
  7255. '0x0084': 'NtRaiseException',
  7256. '0x0085': 'NtRaiseHardError',
  7257. '0x0082': 'NtQueryVolumeInformationFile',
  7258. '0x0083': 'NtQueueApcThread',
  7259. '0x0080': 'NtQueryValueKey',
  7260. '0x0081': 'NtQueryVirtualMemory',
  7261. '0x00b0': 'NtSetSystemTime',
  7262. '0x00b1': 'NtSetTimer',
  7263. '0x00b2': 'NtSetTimerResolution',
  7264. '0x00b3': 'NtSetValueKey',
  7265. '0x00b4': 'NtSetVolumeInformationFile',
  7266. '0x00b5': 'NtShutdownSystem',
  7267. '0x0088': 'NtReadRequestData',
  7268. '0x0089': 'NtReadVirtualMemory',
  7269. '0x00af': 'NtSetSystemPowerState',
  7270. '0x00aa': 'NtSetLowWaitHighEventPair',
  7271. '0x00ac': 'NtSetSecurityObject',
  7272. '0x00ab': 'NtSetLowWaitHighThread',
  7273. '0x00c7': 'NtWaitLowEventPair',
  7274. '0x00b8': 'NtStopProfile',
  7275. '0x00c5': 'NtWaitForSingleObject',
  7276. '0x00c4': 'NtWaitForMultipleObjects',
  7277. '0x0019': 'NtCreateKey',
  7278. '0x0018': 'NtCreateIoCompletion',
  7279. '0x00c1': 'NtUnlockVirtualMemory',
  7280. '0x00b9': 'NtSuspendThread',
  7281. '0x0015': 'NtCreateEvent',
  7282. '0x0014': 'NtCreateDirectoryObject',
  7283. '0x0017': 'NtCreateFile',
  7284. '0x0016': 'NtCreateEventPair',
  7285. '0x0011': 'NtCompleteConnectPort',
  7286. '0x0010': 'NtCloseObjectAuditAlarm',
  7287. '0x0013': 'NtContinue',
  7288. '0x0012': 'NtConnectPort',
  7289. '0x0095': 'NtRestoreKey',
  7290. '0x0094': 'NtResetEvent',
  7291. '0x0097': 'NtSaveKey',
  7292. '0x0096': 'NtResumeThread',
  7293. '0x0091': 'NtReplyWaitReplyPort',
  7294. '0x0090': 'NtReplyWaitReceivePort',
  7295. '0x0093': 'NtRequestWaitReplyPort',
  7296. '0x0092': 'NtRequestPort',
  7297. '0x002a': 'NtDeleteKey',
  7298. '0x002b': 'NtDeleteObjectAuditAlarm',
  7299. '0x002c': 'NtDeleteValueKey',
  7300. '0x002d': 'NtDeviceIoControlFile',
  7301. '0x002e': 'NtDisplayString',
  7302. '0x002f': 'NtDuplicateObject',
  7303. '0x00ae': 'NtSetSystemInformation',
  7304. '0x00c2': 'NtUnmapViewOfSection',
  7305. '0x0028': 'NtDeleteAtom',
  7306. '0x0029': 'NtDeleteFile',
  7307. '0x00d0': 'NtReplyWaitSendChannel',
  7308. '0x00d1': 'NtSendWaitReplyChannel',
  7309. '0x009a': 'NtSetDefaultHardErrorPort',
  7310. '0x009c': 'NtSetEaFile',
  7311. '0x009b': 'NtSetDefaultLocale',
  7312. '0x0020': 'NtCreateProfile',
  7313. '0x0021': 'NtCreateSection',
  7314. '0x0022': 'NtCreateSemaphore',
  7315. '0x0023': 'NtCreateSymbolicLinkObject',
  7316. '0x0024': 'NtCreateThread',
  7317. '0x0025': 'NtCreateTimer',
  7318. '0x0026': 'NtCreateToken',
  7319. '0x0027': 'NtDelayExecution',
  7320. '0x00cf': 'NtOpenChannel',
  7321. '0x00ce': 'NtListenChannel',
  7322. '0x00cd': 'NtCreateChannel',
  7323. '0x00cc': 'NtW32Call',
  7324. '0x00b6': 'NtSignalAndWaitForSingleObject',
  7325. '0x00ca': 'NtWriteRequestData',
  7326. '0x001e': 'NtCreatePort',
  7327. '0x001d': 'NtCreatePagingFile',
  7328. '0x001f': 'NtCreateProcess',
  7329. '0x001a': 'NtCreateMailslotFile',
  7330. '0x001c': 'NtCreateNamedPipeFile',
  7331. '0x001b': 'NtCreateMutant',
  7332. '0x004b': 'NtNotifyChangeKey',
  7333. '0x004c': 'NtOpenDirectoryObject',
  7334. '0x004a': 'NtNotifyChangeDirectoryFile',
  7335. '0x004f': 'NtOpenFile',
  7336. '0x004d': 'NtOpenEvent',
  7337. '0x004e': 'NtOpenEventPair',
  7338. '0x0037': 'NtFlushKey',
  7339. '0x0036': 'NtFlushInstructionCache',
  7340. '0x0035': 'NtFlushBuffersFile',
  7341. '0x0034': 'NtFindAtom',
  7342. '0x0033': 'NtExtendSection',
  7343. '0x0032': 'NtEnumerateValueKey',
  7344. '0x0031': 'NtEnumerateKey',
  7345. '0x0030': 'NtDuplicateToken',
  7346. '0x0039': 'NtFlushWriteBuffer',
  7347. '0x0038': 'NtFlushVirtualMemory',
  7348. 'NA': 'NtWriteErrorLogEntry',
  7349. '0x003f': 'NtImpersonateClientOfPort',
  7350. '0x003e': 'NtGetTickCount',
  7351. '0x003d': 'NtGetPlugPlayEvent',
  7352. '0x003c': 'NtGetContextThread',
  7353. '0x003b': 'NtFsControlFile',
  7354. '0x003a': 'NtFreeVirtualMemory',
  7355. '0x009d': 'NtSetEvent',
  7356. '0x0042': 'NtListenPort',
  7357. '0x0043': 'NtLoadDriver',
  7358. '0x0040': 'NtImpersonateThread',
  7359. '0x0041': 'NtInitializeRegistry',
  7360. '0x0046': 'NtLockFile',
  7361. '0x0047': 'NtLockVirtualMemory',
  7362. '0x0044': 'NtLoadKey',
  7363. '0x0045': 'NtLoadKey2',
  7364. '0x0048': 'NtMakeTemporaryObject',
  7365. '0x0049': 'NtMapViewOfSection',
  7366. '0x00a7': 'NtSetIntervalProfile',
  7367. '0x00a6': 'NtSetInformationToken',
  7368. '0x00a1': 'NtSetInformationFile',
  7369. '0x00d2': 'NtSetContextChannel',
  7370. '0x00a0': 'NtSetHighWaitLowThread',
  7371. '0x00a2': 'NtSetInformationKey',
  7372. '0x00a5': 'NtSetInformationThread',
  7373. '0x006d': 'NtQueryInformationProcess',
  7374. '0x006e': 'NtQueryInformationThread',
  7375. '0x006f': 'NtQueryInformationToken',
  7376. '0x00d3': 'NtYieldExecution',
  7377. '0x006a': 'NtQueryInformationFile',
  7378. '0x006b': 'NtQueryIoCompletion',
  7379. '0x006c': 'NtQueryInformationPort',
  7380. '0x0051': 'NtOpenKey',
  7381. '0x0050': 'NtOpenIoCompletion',
  7382. '0x0053': 'NtOpenObjectAuditAlarm',
  7383. '0x0052': 'NtOpenMutant',
  7384. '0x0055': 'NtOpenProcessToken',
  7385. '0x0054': 'NtOpenProcess',
  7386. '0x0057': 'NtOpenSemaphore',
  7387. '0x0056': 'NtOpenSection',
  7388. '0x0059': 'NtOpenThread',
  7389. '0x0058': 'NtOpenSymbolicLinkObject',
  7390. '0x00c8': 'NtWriteFile',
  7391. '0x00cb': 'NtWriteVirtualMemory',
  7392. '0x005a': 'NtOpenThreadToken',
  7393. '0x005c': 'NtPlugPlayControl',
  7394. '0x005b': 'NtOpenTimer',
  7395. '0x005e': 'NtPrivilegedServiceAuditAlarm',
  7396. '0x005d': 'NtPrivilegeCheck',
  7397. '0x005f': 'NtPrivilegeObjectAuditAlarm',
  7398. '0x0099': 'NtSetContextThread',
  7399. '0x0068': 'NtQueryEvent',
  7400. '0x0069': 'NtQueryFullAttributesFile',
  7401. '0x009f': 'NtSetHighWaitLowEventPair',
  7402. '0x0064': 'NtQueryDefaultLocale',
  7403. '0x0065': 'NtQueryDirectoryFile',
  7404. '0x0066': 'NtQueryDirectoryObject',
  7405. '0x0067': 'NtQueryEaFile',
  7406. '0x0060': 'NtProtectVirtualMemory',
  7407. '0x0061': 'NtPulseEvent',
  7408. '0x0062': 'NtQueryInformationAtom',
  7409. '0x0063': 'NtQueryAttributesFile',
  7410. '0x00b7': 'NtStartProfile',
  7411. '0x0098': 'NtSetIoCompletion',
  7412. '0x00c6': 'NtWaitHighEventPair',
  7413. '0x00c0': 'NtUnlockFile',
  7414. '0x00ad': 'NtSetSystemEnvironmentValue'},
  7415. 'XP': {
  7416. '0x0103': 'NtTestAlert',
  7417. '0x009e': 'NtQueryIntervalProfile',
  7418. '0x0079': 'NtOpenObjectAuditAlarm',
  7419. '0x0078': 'NtOpenMutant',
  7420. '0x00c9': 'NtRequestWakeupLatency',
  7421. '0x0073': 'NtOpenEventPair',
  7422. '0x0072': 'NtOpenEvent',
  7423. '0x0071': 'NtOpenDirectoryObject',
  7424. '0x0070': 'NtNotifyChangeMultipleKeys',
  7425. '0x0077': 'NtOpenKey',
  7426. '0x0076': 'NtOpenJobObject',
  7427. '0x0075': 'NtOpenIoCompletion',
  7428. '0x0074': 'NtOpenFile',
  7429. '0x008f': 'NtQueryDefaultLocale',
  7430. '0x00db': 'NtSetEvent',
  7431. '0x008d': 'NtQueryBootOptions',
  7432. '0x008e': 'NtQueryDebugFilterState',
  7433. '0x008b': 'NtQueryAttributesFile',
  7434. '0x008c': 'NtQueryBootEntryOrder',
  7435. '0x008a': 'NtPulseEvent',
  7436. '0x00ba': 'NtReadVirtualMemory',
  7437. '0x00bb': 'NtRegisterThreadTerminatePort',
  7438. '0x00bc': 'NtReleaseMutant',
  7439. '0x00bd': 'NtReleaseSemaphore',
  7440. '0x00be': 'NtRemoveIoCompletion',
  7441. '0x00bf': 'NtRemoveProcessDebug',
  7442. '0x00da': 'NtSetEaFile',
  7443. '0x00a9': 'NtQuerySemaphore',
  7444. '0x00a8': 'NtQuerySecurityObject',
  7445. '0x000f': 'NtAllocateUserPhysicalPages',
  7446. '0x00a4': 'NtQueryOpenSubKeys',
  7447. '0x000d': 'NtAlertThread',
  7448. '0x000e': 'NtAllocateLocallyUniqueId',
  7449. '0x000b': 'NtAdjustPrivilegesToken',
  7450. '0x000c': 'NtAlertResumeThread',
  7451. '0x00a3': 'NtQueryObject',
  7452. '0x000a': 'NtAdjustGroupsToken',
  7453. '0x00c0': 'NtRenameKey',
  7454. '0x00df': 'NtSetInformationDebugObject',
  7455. '0x00dd': 'NtSetHighEventPair',
  7456. '0x007c': 'NtOpenProcessTokenEx',
  7457. '0x007b': 'NtOpenProcessToken',
  7458. '0x007a': 'NtOpenProcess',
  7459. '0x00de': 'NtSetHighWaitLowEventPair',
  7460. '0x007f': 'NtOpenSymbolicLinkObject',
  7461. '0x007e': 'NtOpenSemaphore',
  7462. '0x007d': 'NtOpenSection',
  7463. '0x00c3': 'NtReplyWaitReceivePort',
  7464. '0x00f9': 'NtShutdownSystem',
  7465. '0x0008': 'NtAddAtom',
  7466. '0x0009': 'NtAddBootEntry',
  7467. '0x0006': 'NtAccessCheckByTypeResultListAndAuditAlarm',
  7468. '0x0007': 'NtAccessCheckByTypeResultListAndAuditAlarmByHandle',
  7469. '0x0004': 'NtAccessCheckByTypeAndAuditAlarm',
  7470. '0x0005': 'NtAccessCheckByTypeResultList',
  7471. '0x0002': 'NtAccessCheckAndAuditAlarm',
  7472. '0x0003': 'NtAccessCheckByType',
  7473. '0x0000': 'NtAcceptConnectPort',
  7474. '0x0001': 'NtAccessCheck',
  7475. '0x0086': 'NtPrivilegeCheck',
  7476. '0x0087': 'NtPrivilegeObjectAuditAlarm',
  7477. '0x0084': 'NtPlugPlayControl',
  7478. '0x0085': 'NtPowerInformation',
  7479. '0x0082': 'NtOpenThreadTokenEx',
  7480. '0x0083': 'NtOpenTimer',
  7481. '0x0080': 'NtOpenThread',
  7482. '0x0081': 'NtOpenThreadToken',
  7483. '0x00b0': 'NtQueryTimerResolution',
  7484. '0x00b1': 'NtQueryValueKey',
  7485. '0x00b2': 'NtQueryVirtualMemory',
  7486. '0x00b3': 'NtQueryVolumeInformationFile',
  7487. '0x00b4': 'NtQueueApcThread',
  7488. '0x00b5': 'NtRaiseException',
  7489. '0x0088': 'NtPrivilegedServiceAuditAlarm',
  7490. '0x0089': 'NtProtectVirtualMemory',
  7491. '0x00af': 'NtQueryTimer',
  7492. '0x00aa': 'NtQuerySymbolicLinkObject',
  7493. '0x010d': 'NtWaitForDebugEvent',
  7494. '0x00f1': 'NtSetSystemPowerState',
  7495. '0x00ac': 'NtQuerySystemEnvironmentValueEx',
  7496. '0x00ab': 'NtQuerySystemEnvironmentValue',
  7497. '0x00c7': 'NtRequestPort',
  7498. '0x00b8': 'NtReadFileScatter',
  7499. '0x00c5': 'NtReplyWaitReplyPort',
  7500. '0x00c4': 'NtReplyWaitReceivePortEx',
  7501. '0x0019': 'NtClose',
  7502. '0x0018': 'NtClearEvent',
  7503. '0x00c1': 'NtReplaceKey',
  7504. '0x00b9': 'NtReadRequestData',
  7505. '0x0015': 'NtCancelDeviceWakeupRequest',
  7506. '0x0014': 'NtCallbackReturn',
  7507. '0x0017': 'NtCancelTimer',
  7508. '0x0016': 'NtCancelIoFile',
  7509. '0x0011': 'NtAllocateVirtualMemory',
  7510. '0x0010': 'NtAllocateUuids',
  7511. '0x0013': 'NtAssignProcessToJobObject',
  7512. '0x0012': 'NtAreMappedFilesTheSame',
  7513. '0x0095': 'NtQueryFullAttributesFile',
  7514. '0x0094': 'NtQueryEvent',
  7515. '0x0097': 'NtQueryInformationFile',
  7516. '0x0096': 'NtQueryInformationAtom',
  7517. '0x0091': 'NtQueryDirectoryFile',
  7518. '0x0090': 'NtQueryDefaultUILanguage',
  7519. '0x0093': 'NtQueryEaFile',
  7520. '0x0092': 'NtQueryDirectoryObject',
  7521. '0x002a': 'NtCreateMailslotFile',
  7522. '0x002b': 'NtCreateMutant',
  7523. '0x002c': 'NtCreateNamedPipeFile',
  7524. '0x002d': 'NtCreatePagingFile',
  7525. '0x002e': 'NtCreatePort',
  7526. '0x002f': 'NtCreateProcess',
  7527. '0x00ae': 'NtQuerySystemTime',
  7528. '0x00c2': 'NtReplyPort',
  7529. '0x0028': 'NtCreateJobSet',
  7530. '0x0029': 'NtCreateKey',
  7531. '0x00d0': 'NtSaveKeyEx',
  7532. '0x009f': 'NtQueryIoCompletion',
  7533. '0x009a': 'NtQueryInformationProcess',
  7534. '0x00d7': 'NtSetDefaultHardErrorPort',
  7535. '0x009c': 'NtQueryInformationToken',
  7536. '0x009b': 'NtQueryInformationThread',
  7537. '0x0020': 'NtContinue',
  7538. '0x0021': 'NtCreateDebugObject',
  7539. '0x0022': 'NtCreateDirectoryObject',
  7540. '0x0023': 'NtCreateEvent',
  7541. '0x0024': 'NtCreateEventPair',
  7542. '0x0025': 'NtCreateFile',
  7543. '0x0026': 'NtCreateIoCompletion',
  7544. '0x0027': 'NtCreateJobObject',
  7545. '0x00cf': 'NtSaveKey',
  7546. '0x00ce': 'NtResumeThread',
  7547. '0x00cd': 'NtResumeProcess',
  7548. '0x00cc': 'NtRestoreKey',
  7549. '0x00b6': 'NtRaiseHardError',
  7550. '0x00ca': 'NtResetEvent',
  7551. '0x00e8': 'NtSetIoCompletion',
  7552. '0x001e': 'NtCompressKey',
  7553. '0x001d': 'NtCompleteConnectPort',
  7554. '0x001f': 'NtConnectPort',
  7555. '0x001a': 'NtCloseObjectAuditAlarm',
  7556. '0x001c': 'NtCompareTokens',
  7557. '0x001b': 'NtCompactKeys',
  7558. '0x004b': 'NtFilterToken',
  7559. '0x004c': 'NtFindAtom',
  7560. '0x004a': 'NtExtendSection',
  7561. '0x004f': 'NtFlushKey',
  7562. '0x004d': 'NtFlushBuffersFile',
  7563. '0x004e': 'NtFlushInstructionCache',
  7564. '0x0037': 'NtCreateToken',
  7565. '0x0036': 'NtCreateTimer',
  7566. '0x0035': 'NtCreateThread',
  7567. '0x0034': 'NtCreateSymbolicLinkObject',
  7568. '0x0033': 'NtCreateSemaphore',
  7569. '0x0032': 'NtCreateSection',
  7570. '0x0031': 'NtCreateProfile',
  7571. '0x0030': 'NtCreateProcessEx',
  7572. '0x0039': 'NtDebugActiveProcess',
  7573. '0x0038': 'NtCreateWaitablePort',
  7574. '0x00e1': 'NtSetInformationJobObject',
  7575. '0x00e0': 'NtSetInformationFile',
  7576. '0x00e3': 'NtSetInformationObject',
  7577. '0x00e2': 'NtSetInformationKey',
  7578. '0x00e5': 'NtSetInformationThread',
  7579. '0x00e4': 'NtSetInformationProcess',
  7580. '0x00e7': 'NtSetIntervalProfile',
  7581. '0x00e6': 'NtSetInformationToken',
  7582. '0x00e9': 'NtSetLdtEntries',
  7583. 'NA': 'NtWriteErrorLogEntry',
  7584. '0x0109': 'NtUnlockFile',
  7585. '0x00fd': 'NtSuspendProcess',
  7586. '0x00fe': 'NtSuspendThread',
  7587. '0x00ff': 'NtSystemDebugControl',
  7588. '0x0108': 'NtUnloadKeyEx',
  7589. '0x0102': 'NtTerminateThread',
  7590. '0x00fa': 'NtSignalAndWaitForSingleObject',
  7591. '0x00fb': 'NtStartProfile',
  7592. '0x00fc': 'NtStopProfile',
  7593. '0x003f': 'NtDeleteKey',
  7594. '0x003e': 'NtDeleteFile',
  7595. '0x003d': 'NtDeleteBootEntry',
  7596. '0x003c': 'NtDeleteAtom',
  7597. '0x003b': 'NtDelayExecution',
  7598. '0x003a': 'NtDebugContinue',
  7599. '0x009d': 'NtQueryInstallUILanguage',
  7600. '0x00d1': 'NtSaveMergedKeys',
  7601. '0x0042': 'NtDeviceIoControlFile',
  7602. '0x0043': 'NtDisplayString',
  7603. '0x0040': 'NtDeleteObjectAuditAlarm',
  7604. '0x0041': 'NtDeleteValueKey',
  7605. '0x0046': 'NtEnumerateBootEntries',
  7606. '0x0047': 'NtEnumerateKey',
  7607. '0x0044': 'NtDuplicateObject',
  7608. '0x0045': 'NtDuplicateToken',
  7609. '0x00d6': 'NtSetDebugFilterState',
  7610. '0x0048': 'NtEnumerateSystemEnvironmentValuesEx',
  7611. '0x0049': 'NtEnumerateValueKey',
  7612. '0x00a7': 'NtQuerySection',
  7613. '0x00a6': 'NtQueryQuotaInformationFile',
  7614. '0x00f8': 'NtSetVolumeInformationFile',
  7615. '0x00d4': 'NtSetBootOptions',
  7616. '0x00f4': 'NtSetTimer',
  7617. '0x00a1': 'NtQueryMultipleValueKey',
  7618. '0x00f6': 'NtSetUuidSeed',
  7619. '0x00d5': 'NtSetContextThread',
  7620. '0x00f0': 'NtSetSystemInformation',
  7621. '0x00d2': 'NtSecureConnectPort',
  7622. '0x00f2': 'NtSetSystemTime',
  7623. '0x00a0': 'NtQueryKey',
  7624. '0x00ea': 'NtSetLowEventPair',
  7625. '0x00ec': 'NtSetQuotaInformationFile',
  7626. '0x00eb': 'NtSetLowWaitHighEventPair',
  7627. '0x00ee': 'NtSetSystemEnvironmentValue',
  7628. '0x00ed': 'NtSetSecurityObject',
  7629. '0x00f7': 'NtSetValueKey',
  7630. '0x00ef': 'NtSetSystemEnvironmentValueEx',
  7631. '0x00a2': 'NtQueryMutant',
  7632. '0x00d8': 'NtSetDefaultLocale',
  7633. '0x010f': 'NtWaitForSingleObject',
  7634. '0x010e': 'NtWaitForMultipleObjects',
  7635. '0x00d9': 'NtSetDefaultUILanguage',
  7636. '0x010c': 'NtVdmControl',
  7637. '0x010b': 'NtUnmapViewOfSection',
  7638. '0x010a': 'NtUnlockVirtualMemory',
  7639. '0x00a5': 'NtQueryPerformanceCounter',
  7640. '0x006d': 'NtModifyBootEntry',
  7641. '0x006e': 'NtNotifyChangeDirectoryFile',
  7642. '0x006f': 'NtNotifyChangeKey',
  7643. '0x00d3': 'NtSetBootEntryOrder',
  7644. '0x006a': 'NtMapUserPhysicalPages',
  7645. '0x006b': 'NtMapUserPhysicalPagesScatter',
  7646. '0x006c': 'NtMapViewOfSection',
  7647. '0x0051': 'NtFlushWriteBuffer',
  7648. '0x0050': 'NtFlushVirtualMemory',
  7649. '0x0053': 'NtFreeVirtualMemory',
  7650. '0x0052': 'NtFreeUserPhysicalPages',
  7651. '0x0055': 'NtGetContextThread',
  7652. '0x0054': 'NtFsControlFile',
  7653. '0x0057': 'NtGetPlugPlayEvent',
  7654. '0x0056': 'NtGetDevicePowerState',
  7655. '0x0059': 'NtImpersonateAnonymousToken',
  7656. '0x0058': 'NtGetWriteWatch',
  7657. '0x00c8': 'NtRequestWaitReplyPort',
  7658. '0x00f5': 'NtSetTimerResolution',
  7659. '0x0118': 'NtOpenKeyedEvent',
  7660. '0x0119': 'NtReleaseKeyedEvent',
  7661. '0x0110': 'NtWaitHighEventPair',
  7662. '0x0111': 'NtWaitLowEventPair',
  7663. '0x00f3': 'NtSetThreadExecutionState',
  7664. '0x0113': 'NtWriteFileGather',
  7665. '0x0114': 'NtWriteRequestData',
  7666. '0x0115': 'NtWriteVirtualMemory',
  7667. '0x0116': 'NtYieldExecution',
  7668. '0x0117': 'NtCreateKeyedEvent',
  7669. '0x00cb': 'NtResetWriteWatch',
  7670. '0x005a': 'NtImpersonateClientOfPort',
  7671. '0x005c': 'NtInitializeRegistry',
  7672. '0x005b': 'NtImpersonateThread',
  7673. '0x005e': 'NtIsProcessInJob',
  7674. '0x005d': 'NtInitiatePowerAction',
  7675. '0x005f': 'NtIsSystemResumeAutomatic',
  7676. '0x011a': 'NtWaitForKeyedEvent',
  7677. '0x0107': 'NtUnloadKey',
  7678. '0x0106': 'NtUnloadDriver',
  7679. '0x0105': 'NtTranslateFilePath',
  7680. '0x0099': 'NtQueryInformationPort',
  7681. '0x0068': 'NtMakePermanentObject',
  7682. '0x0069': 'NtMakeTemporaryObject',
  7683. '0x0101': 'NtTerminateProcess',
  7684. '0x0100': 'NtTerminateJobObject',
  7685. '0x0064': 'NtLockFile',
  7686. '0x0065': 'NtLockProductActivationKeys',
  7687. '0x0066': 'NtLockRegistryKey',
  7688. '0x0067': 'NtLockVirtualMemory',
  7689. '0x0060': 'NtListenPort',
  7690. '0x0061': 'NtLoadDriver',
  7691. '0x0062': 'NtLoadKey',
  7692. '0x0063': 'NtLoadKey2',
  7693. '0x00dc': 'NtSetEventBoostPriority',
  7694. '0x00b7': 'NtReadFile',
  7695. '0x0104': 'NtTraceEvent',
  7696. '0x0098': 'NtQueryInformationJobObject',
  7697. '0x00c6': 'NtRequestDeviceWakeup',
  7698. '0x011b': 'NtQueryPortInformationProcess',
  7699. '0x0112': 'NtWriteFile',
  7700. '0x00ad': 'NtQuerySystemInformation'},
  7701. 'Vista': {'0x0172': 'NtCancelIoFileEx',
  7702. '0x0173': 'NtCancelSynchronousIoFile',
  7703. '0x0079': 'NtDeleteFile',
  7704. '0x0078': 'NtDeleteDriverEntry',
  7705. '0x0176': 'NtPullTransaction',
  7706. '0x0177': 'NtMarshallTransaction',
  7707. '0x0174': 'NtRemoveIoCompletionEx',
  7708. '0x0175': 'NtRegisterProtocolAddressInformation',
  7709. '0x0073': 'NtDebugActiveProcess',
  7710. '0x0072': 'NtCreateWaitablePort',
  7711. '0x0178': 'NtPropagationComplete',
  7712. '0x0012': 'NtAllocateVirtualMemory',
  7713. '0x0077': 'NtDeleteBootEntry',
  7714. '0x0076': 'NtDeleteAtom',
  7715. '0x0075': 'NtDelayExecution',
  7716. '0x0074': 'NtDebugContinue',
  7717. '0x00ba': 'NtOpenJobObject',
  7718. '0x00bb': 'NtOpenKey',
  7719. '0x00bc': 'NtOpenMutant',
  7720. '0x00bd': 'NtOpenPrivateNamespace',
  7721. '0x00be': 'NtOpenObjectAuditAlarm',
  7722. '0x00bf': 'NtOpenProcess',
  7723. '0x000f': 'NtAllocateLocallyUniqueId',
  7724. '0x000d': 'NtAlertResumeThread',
  7725. '0x000e': 'NtAlertThread',
  7726. '0x000b': 'NtAdjustGroupsToken',
  7727. '0x000c': 'NtAdjustPrivilegesToken',
  7728. '0x000a': 'NtAddDriverEntry',
  7729. '0x017b': 'NtReleaseWorkerFactoryWorker',
  7730. '0x017c': 'NtWaitForWorkViaWorkerFactory',
  7731. '0x017a': 'NtCreateWorkerFactory',
  7732. '0x017f': 'NtWorkerFactoryWorkerReady',
  7733. '0x017d': 'NtSetInformationWorkerFactory',
  7734. '0x017e': 'NtQueryInformationWorkerFactory',
  7735. '0x007c': 'NtDeleteObjectAuditAlarm',
  7736. '0x007b': 'NtDeletePrivateNamespace',
  7737. '0x007a': 'NtDeleteKey',
  7738. '0x007f': 'NtDisplayString',
  7739. '0x007e': 'NtDeviceIoControlFile',
  7740. '0x007d': 'NtDeleteValueKey',
  7741. '0x00f8': 'NtQueryTimerResolution',
  7742. '0x0128': 'NtSetEaFile',
  7743. '0x0008': 'NtAddAtom',
  7744. '0x0009': 'NtAddBootEntry',
  7745. '0x0006': 'NtAccessCheckByTypeResultListAndAuditAlarm',
  7746. '0x0007': 'NtAccessCheckByTypeResultListAndAuditAlarmByHandle',
  7747. '0x0004': 'NtAccessCheckByTypeAndAuditAlarm',
  7748. '0x0005': 'NtAccessCheckByTypeResultList',
  7749. '0x0002': 'NtAccessCheckAndAuditAlarm',
  7750. '0x0003': 'NtAccessCheckByType',
  7751. '0x0000': 'NtAcceptConnectPort',
  7752. '0x0001': 'NtAccessCheck',
  7753. '0x00b8': 'NtOpenFile',
  7754. '0x00b9': 'NtOpenIoCompletion',
  7755. '0x0171': 'NtGetNextThread',
  7756. '0x00f5': 'NtQuerySystemInformation',
  7757. '0x00b0': 'NtModifyBootEntry',
  7758. '0x00b1': 'NtModifyDriverEntry',
  7759. '0x00b2': 'NtNotifyChangeDirectoryFile',
  7760. '0x00b3': 'NtNotifyChangeKey',
  7761. '0x00b4': 'NtNotifyChangeMultipleKeys',
  7762. '0x00b5': 'NtOpenDirectoryObject',
  7763. '0x00b6': 'NtOpenEvent',
  7764. '0x00b7': 'NtOpenEventPair',
  7765. '0x00f7': 'NtQueryTimer',
  7766. '0x00f0': 'NtQuerySecurityObject',
  7767. '0x00f1': 'NtQuerySemaphore',
  7768. '0x00f2': 'NtQuerySymbolicLinkObject',
  7769. '0x00f3': 'NtQuerySystemEnvironmentValue',
  7770. '0x0071': 'NtStartTm',
  7771. '0x0179': 'NtPropagationFailed',
  7772. '0x0095': 'NtGetContextThread',
  7773. '0x0094': 'NtFsControlFile',
  7774. '0x0097': 'NtGetNlsSectionPtr',
  7775. '0x0096': 'NtGetDevicePowerState',
  7776. '0x0091': 'NtFreeVirtualMemory',
  7777. '0x0090': 'NtFreeUserPhysicalPages',
  7778. '0x0093': 'NtFreezeTransactions',
  7779. '0x0092': 'NtFreezeRegistry',
  7780. '0x0099': 'NtGetWriteWatch',
  7781. '0x0098': 'NtGetPlugPlayEvent',
  7782. '0x009e': 'NtInitializeRegistry',
  7783. '0x009d': 'NtInitializeNlsFiles',
  7784. '0x009f': 'NtInitiatePowerAction',
  7785. '0x009a': 'NtImpersonateAnonymousToken',
  7786. '0x009c': 'NtImpersonateThread',
  7787. '0x009b': 'NtImpersonateClientOfPort',
  7788. '0x004b': 'NtCreateSymbolicLinkObject',
  7789. '0x004c': 'NtCreateThread',
  7790. '0x004a': 'NtCreateSemaphore',
  7791. '0x004f': 'NtCreateTransaction',
  7792. '0x004d': 'NtCreateTimer',
  7793. '0x004e': 'NtCreateToken',
  7794. '0x012e': 'NtSetInformationFile',
  7795. '0x00fe': 'NtRaiseHardError',
  7796. '0x00ff': 'NtReadFile',
  7797. '0x012f': 'NtSetInformationJobObject',
  7798. '0x012a': 'NtSetEventBoostPriority',
  7799. '0x00fa': 'NtQueryVirtualMemory',
  7800. '0x012c': 'NtSetHighWaitLowEventPair',
  7801. '0x012b': 'NtSetHighEventPair',
  7802. '0x0042': 'NtCreateNamedPipeFile',
  7803. '0x0043': 'NtCreatePrivateNamespace',
  7804. '0x0040': 'NtCreateMailslotFile',
  7805. '0x0041': 'NtCreateMutant',
  7806. '0x0046': 'NtCreateProcess',
  7807. '0x0047': 'NtCreateProcessEx',
  7808. '0x0044': 'NtCreatePagingFile',
  7809. '0x0045': 'NtCreatePort',
  7810. '0x0048': 'NtCreateProfile',
  7811. '0x0049': 'NtCreateSection',
  7812. '0x0170': 'NtGetNextProcess',
  7813. '0x0129': 'NtSetEvent',
  7814. '0x00f9': 'NtQueryValueKey',
  7815. '0x0125': 'NtSetDefaultLocale',
  7816. '0x0124': 'NtSetDefaultHardErrorPort',
  7817. '0x00f6': 'NtQuerySystemTime',
  7818. '0x0126': 'NtSetDefaultUILanguage',
  7819. '0x0121': 'NtSetBootOptions',
  7820. '0x0120': 'NtSetBootEntryOrder',
  7821. '0x0123': 'NtSetDebugFilterState',
  7822. '0x0122': 'NtSetContextThread',
  7823. '0x0070': 'NtQueryInformationEnlistment',
  7824. '0x016a': 'NtOpenKeyedEvent',
  7825. '0x016c': 'NtWaitForKeyedEvent',
  7826. '0x016b': 'NtReleaseKeyedEvent',
  7827. '0x016e': 'NtGetCurrentProcessorNumber',
  7828. '0x016d': 'NtQueryPortInformationProcess',
  7829. '0x016f': 'NtWaitForMultipleObjects32',
  7830. '0x0161': 'NtWaitForSingleObject',
  7831. '0x0160': 'NtWaitForMultipleObjects',
  7832. '0x0163': 'NtWaitLowEventPair',
  7833. '0x0162': 'NtWaitHighEventPair',
  7834. '0x0165': 'NtWriteFileGather',
  7835. '0x0164': 'NtWriteFile',
  7836. '0x0167': 'NtWriteVirtualMemory',
  7837. '0x0166': 'NtWriteRequestData',
  7838. '0x0169': 'NtCreateKeyedEvent',
  7839. '0x0168': 'NtYieldExecution',
  7840. '0x00c7': 'NtOpenThreadToken',
  7841. '0x00c6': 'NtOpenThread',
  7842. '0x00c5': 'NtOpenSymbolicLinkObject',
  7843. '0x00c4': 'NtOpenSession',
  7844. '0x0019': 'NtAlpcCreateSectionView',
  7845. '0x0018': 'NtAlpcCreateResourceReserve',
  7846. '0x00c1': 'NtOpenProcessTokenEx',
  7847. '0x00c0': 'NtOpenProcessToken',
  7848. '0x0015': 'NtAlpcConnectPort',
  7849. '0x0014': 'NtAlpcCancelMessage',
  7850. '0x0017': 'NtAlpcCreatePortSection',
  7851. '0x0016': 'NtAlpcCreatePort',
  7852. '0x0011': 'NtAllocateUuids',
  7853. '0x0010': 'NtAllocateUserPhysicalPages',
  7854. '0x0013': 'NtAlpcAcceptConnectPort',
  7855. '0x00c8': 'NtOpenThreadTokenEx',
  7856. '0x00e7': 'NtQueryKey',
  7857. '0x00e6': 'NtQueryIoCompletion',
  7858. '0x00cf': 'NtProtectVirtualMemory',
  7859. '0x00ce': 'NtPrivilegedServiceAuditAlarm',
  7860. '0x00cd': 'NtPrivilegeObjectAuditAlarm',
  7861. '0x00cc': 'NtPrivilegeCheck',
  7862. '0x00cb': 'NtPowerInformation',
  7863. '0x00ca': 'NtPlugPlayControl',
  7864. 'NA': 'NtWriteErrorLogEntry',
  7865. '0x001e': 'NtAlpcDeleteSecurityContext',
  7866. '0x001d': 'NtAlpcDeleteSectionView',
  7867. '0x001f': 'NtAlpcDisconnectPort',
  7868. '0x001a': 'NtAlpcCreateSecurityContext',
  7869. '0x001c': 'NtAlpcDeleteResourceReserve',
  7870. '0x001b': 'NtAlpcDeletePortSection',
  7871. '0x0062': 'NtCreateTransactionManager',
  7872. '0x0063': 'NtOpenTransactionManager',
  7873. '0x0069': 'NtCreateResourceManager',
  7874. '0x0127': 'NtSetDriverEntryOrder',
  7875. '0x00c9': 'NtOpenTimer',
  7876. '0x00f4': 'NtQuerySystemEnvironmentValueEx',
  7877. '0x0068': 'NtRecoverTransactionManager',
  7878. '0x0051': 'NtQueryInformationTransaction',
  7879. '0x0050': 'NtOpenTransaction',
  7880. '0x0053': 'NtPrePrepareEnlistment',
  7881. '0x0052': 'NtQueryInformationTransactionManager',
  7882. '0x0055': 'NtCommitEnlistment',
  7883. '0x0054': 'NtPrepareEnlistment',
  7884. '0x0057': 'NtRollbackComplete',
  7885. '0x0056': 'NtReadOnlyEnlistment',
  7886. '0x0059': 'NtCommitTransaction',
  7887. '0x0058': 'NtRollbackEnlistment',
  7888. '0x0118': 'NtSaveKeyEx',
  7889. '0x0119': 'NtSaveMergedKeys',
  7890. '0x0110': 'NtRequestWaitReplyPort',
  7891. '0x0111': 'NtRequestWakeupLatency',
  7892. '0x0112': 'NtResetEvent',
  7893. '0x0113': 'NtResetWriteWatch',
  7894. '0x0114': 'NtRestoreKey',
  7895. '0x0115': 'NtResumeProcess',
  7896. '0x018a': 'NtGetMUIRegistryInfo',
  7897. '0x0117': 'NtSaveKey',
  7898. '0x005a': 'NtRollbackTransaction',
  7899. '0x005c': 'NtPrepareComplete',
  7900. '0x005b': 'NtPrePrepareComplete',
  7901. '0x005e': 'NtSinglePhaseReject',
  7902. '0x005d': 'NtCommitComplete',
  7903. '0x005f': 'NtSetInformationTransaction',
  7904. '0x0189': 'NtFlushInstallUILanguage',
  7905. '0x0188': 'NtIsUILanguageComitted',
  7906. '0x0187': 'NtClearMUILicenseInfo',
  7907. '0x0186': 'NtGetMUILicenseInfo',
  7908. '0x0185': 'NtListTransactions',
  7909. '0x011c': 'NtRollbackSavepointTransaction',
  7910. '0x011d': 'NtSavepointTransaction',
  7911. '0x011e': 'NtSavepointComplete',
  7912. '0x011f': 'NtSecureConnectPort',
  7913. '0x0180': 'NtShutdownWorkerFactory',
  7914. '0x0158': 'NtUnloadKey',
  7915. '0x0159': 'NtUnloadKey2',
  7916. '0x0154': 'NtTraceEvent',
  7917. '0x0155': 'NtTraceControl',
  7918. '0x0156': 'NtTranslateFilePath',
  7919. '0x0157': 'NtUnloadDriver',
  7920. '0x0150': 'NtTerminateThread',
  7921. '0x0151': 'NtTestAlert',
  7922. '0x0152': 'NtThawRegistry',
  7923. '0x0153': 'NtThawTransactions',
  7924. '0x00db': 'NtQueryEvent',
  7925. '0x00dc': 'NtQueryFullAttributesFile',
  7926. '0x00da': 'NtQueryEaFile',
  7927. '0x00df': 'NtQueryInformationJobObject',
  7928. '0x00dd': 'NtQueryInformationAtom',
  7929. '0x00de': 'NtQueryInformationFile',
  7930. '0x002a': 'NtCallbackReturn',
  7931. '0x002b': 'NtCancelDeviceWakeupRequest',
  7932. '0x002c': 'NtCancelIoFile',
  7933. '0x002d': 'NtCancelTimer',
  7934. '0x002e': 'NtClearEvent',
  7935. '0x002f': 'NtClose',
  7936. '0x00ed': 'NtQueryPerformanceCounter',
  7937. '0x015d': 'NtUnmapViewOfSection',
  7938. '0x015e': 'NtVdmControl',
  7939. '0x015f': 'NtWaitForDebugEvent',
  7940. '0x015a': 'NtUnloadKeyEx',
  7941. '0x015b': 'NtUnlockFile',
  7942. '0x015c': 'NtUnlockVirtualMemory',
  7943. '0x0028': 'NtAreMappedFilesTheSame',
  7944. '0x0029': 'NtAssignProcessToJobObject',
  7945. '0x00d0': 'NtPulseEvent',
  7946. '0x00d1': 'NtQueryAttributesFile',
  7947. '0x00d6': 'NtQueryDefaultUILanguage',
  7948. '0x00d7': 'NtQueryDirectoryFile',
  7949. '0x00d4': 'NtQueryDebugFilterState',
  7950. '0x00d5': 'NtQueryDefaultLocale',
  7951. '0x0020': 'NtAlpcImpersonateClientOfPort',
  7952. '0x0021': 'NtAlpcOpenSenderProcess',
  7953. '0x0022': 'NtAlpcOpenSenderThread',
  7954. '0x0023': 'NtAlpcQueryInformation',
  7955. '0x0024': 'NtAlpcQueryInformationMessage',
  7956. '0x0025': 'NtAlpcSendWaitReceivePort',
  7957. '0x0026': 'NtAlpcSetInformation',
  7958. '0x0027': 'NtApphelpCacheControl',
  7959. '0x00d2': 'NtQueryBootEntryOrder',
  7960. '0x00d3': 'NtQueryBootOptions',
  7961. '0x00d8': 'NtQueryDirectoryObject',
  7962. '0x010f': 'NtRequestPort',
  7963. '0x010e': 'NtRequestDeviceWakeup',
  7964. '0x010d': 'NtReplyWaitReplyPort',
  7965. '0x010c': 'NtReplyWaitReceivePortEx',
  7966. '0x010b': 'NtReplyWaitReceivePort',
  7967. '0x010a': 'NtReplyPort',
  7968. '0x006d': 'NtCreateEnlistment',
  7969. '0x006e': 'NtOpenEnlistment',
  7970. '0x006f': 'NtSetInformationEnlistment',
  7971. '0x006a': 'NtOpenResourceManager',
  7972. '0x006b': 'NtGetNotificationResourceManager',
  7973. '0x006c': 'NtQueryInformationResourceManager',
  7974. '0x0136': 'NtSetIoCompletion',
  7975. '0x0137': 'NtSetLdtEntries',
  7976. '0x0107': 'NtRemoveProcessDebug',
  7977. '0x0106': 'NtRemoveIoCompletion',
  7978. '0x0105': 'NtReleaseSemaphore',
  7979. '0x0104': 'NtReleaseMutant',
  7980. '0x0103': 'NtRegisterThreadTerminatePort',
  7981. '0x0102': 'NtReadVirtualMemory',
  7982. '0x0101': 'NtReadRequestData',
  7983. '0x0100': 'NtReadFileScatter',
  7984. '0x0064': 'NtRenameTransactionManager',
  7985. '0x0065': 'NtRollforwardTransactionManager',
  7986. '0x0066': 'NtRecoverEnlistment',
  7987. '0x0067': 'NtRecoverResourceManager',
  7988. '0x0060': 'NtSetInformationTransactionManager',
  7989. '0x0061': 'NtSetInformationResourceManager',
  7990. '0x0109': 'NtReplaceKey',
  7991. '0x0108': 'NtRenameKey',
  7992. '0x00d9': 'NtQueryDriverEntryOrder',
  7993. '0x0116': 'NtResumeThread',
  7994. '0x008f': 'NtFlushWriteBuffer',
  7995. '0x008d': 'NtFlushProcessWriteBuffers',
  7996. '0x008e': 'NtFlushVirtualMemory',
  7997. '0x008b': 'NtFlushInstructionCache',
  7998. '0x008c': 'NtFlushKey',
  7999. '0x008a': 'NtFlushBuffersFile',
  8000. '0x00a9': 'NtLockRegistryKey',
  8001. '0x00a8': 'NtLockProductActivationKeys',
  8002. '0x00a5': 'NtLoadKey2',
  8003. '0x00a4': 'NtLoadKey',
  8004. '0x00a7': 'NtLockFile',
  8005. '0x00a6': 'NtLoadKeyEx',
  8006. '0x00a1': 'NtIsSystemResumeAutomatic',
  8007. '0x00a0': 'NtIsProcessInJob',
  8008. '0x00a3': 'NtLoadDriver',
  8009. '0x00a2': 'NtListenPort',
  8010. '0x00ae': 'NtMapUserPhysicalPagesScatter',
  8011. '0x00ad': 'NtMapUserPhysicalPages',
  8012. '0x00af': 'NtMapViewOfSection',
  8013. '0x00aa': 'NtLockVirtualMemory',
  8014. '0x00ac': 'NtMakeTemporaryObject',
  8015. '0x00ab': 'NtMakePermanentObject',
  8016. '0x0086': 'NtEnumerateValueKey',
  8017. '0x0087': 'NtExtendSection',
  8018. '0x0084': 'NtEnumerateKey',
  8019. '0x0085': 'NtEnumerateSystemEnvironmentValuesEx',
  8020. '0x0082': 'NtEnumerateBootEntries',
  8021. '0x0083': 'NtEnumerateDriverEntries',
  8022. '0x0080': 'NtDuplicateObject',
  8023. '0x0081': 'NtDuplicateToken',
  8024. '0x0088': 'NtFilterToken',
  8025. '0x0089': 'NtFindAtom',
  8026. '0x014c': 'NtSuspendThread',
  8027. '0x014b': 'NtSuspendProcess',
  8028. '0x014a': 'NtStopProfile',
  8029. '0x014f': 'NtTerminateProcess',
  8030. '0x014e': 'NtTerminateJobObject',
  8031. '0x014d': 'NtSystemDebugControl',
  8032. '0x0149': 'NtStartProfile',
  8033. '0x0148': 'NtSignalAndWaitForSingleObject',
  8034. '0x0143': 'NtSetTimerResolution',
  8035. '0x0142': 'NtSetTimer',
  8036. '0x0141': 'NtSetThreadExecutionState',
  8037. '0x0140': 'NtSetSystemTime',
  8038. '0x0147': 'NtShutdownSystem',
  8039. '0x0146': 'NtSetVolumeInformationFile',
  8040. '0x0145': 'NtSetValueKey',
  8041. '0x0144': 'NtSetUuidSeed',
  8042. '0x0037': 'NtCreateDebugObject',
  8043. '0x0036': 'NtContinue',
  8044. '0x0035': 'NtConnectPort',
  8045. '0x0034': 'NtCompressKey',
  8046. '0x0033': 'NtCompleteConnectPort',
  8047. '0x0032': 'NtCompareTokens',
  8048. '0x0031': 'NtCompactKeys',
  8049. '0x0030': 'NtCloseObjectAuditAlarm',
  8050. '0x0039': 'NtCreateEvent',
  8051. '0x0038': 'NtCreateDirectoryObject',
  8052. '0x00e1': 'NtQueryInformationProcess',
  8053. '0x00e0': 'NtQueryInformationPort',
  8054. '0x00e3': 'NtQueryInformationToken',
  8055. '0x00e2': 'NtQueryInformationThread',
  8056. '0x00e5': 'NtQueryIntervalProfile',
  8057. '0x00e4': 'NtQueryInstallUILanguage',
  8058. '0x0138': 'NtSetLowEventPair',
  8059. '0x0139': 'NtSetLowWaitHighEventPair',
  8060. '0x00e9': 'NtQueryMutant',
  8061. '0x00e8': 'NtQueryMultipleValueKey',
  8062. '0x0134': 'NtSetInformationToken',
  8063. '0x0135': 'NtSetIntervalProfile',
  8064. '0x0132': 'NtSetInformationProcess',
  8065. '0x0133': 'NtSetInformationThread',
  8066. '0x0130': 'NtSetInformationKey',
  8067. '0x0131': 'NtSetInformationObject',
  8068. '0x003f': 'NtCreateKey',
  8069. '0x003e': 'NtCreateJobSet',
  8070. '0x003d': 'NtCreateJobObject',
  8071. '0x003c': 'NtCreateIoCompletion',
  8072. '0x003b': 'NtCreateFile',
  8073. '0x003a': 'NtCreateEventPair',
  8074. '0x00fd': 'NtRaiseException',
  8075. '0x012d': 'NtSetInformationDebugObject',
  8076. '0x013e': 'NtSetSystemInformation',
  8077. '0x00ea': 'NtQueryObject',
  8078. '0x00ec': 'NtQueryOpenSubKeysEx',
  8079. '0x00eb': 'NtQueryOpenSubKeys',
  8080. '0x00ee': 'NtQueryQuotaInformationFile',
  8081. '0x00fb': 'NtQueryVolumeInformationFile',
  8082. '0x00ef': 'NtQuerySection',
  8083. '0x013f': 'NtSetSystemPowerState',
  8084. '0x013d': 'NtSetSystemEnvironmentValueEx',
  8085. '0x00fc': 'NtQueueApcThread',
  8086. '0x013b': 'NtSetSecurityObject',
  8087. '0x013c': 'NtSetSystemEnvironmentValue',
  8088. '0x013a': 'NtSetQuotaInformationFile',
  8089. '0x011a': 'NtClearSavepointTransaction',
  8090. '0x00c3': 'NtOpenSemaphore',
  8091. '0x011b': 'NtClearAllSavepointsTransaction',
  8092. '0x00c2': 'NtOpenSection',
  8093. '0x0184': 'NtMapCMFModule',
  8094. '0x0183': 'NtQueryLicenseValue',
  8095. '0x0181': 'NtCreateThreadEx'}}
  8096.  
  8097.  
  8098.  
  8099.  
  8100. def usage(imm):
  8101.  
  8102. imm.log("!syscall PyCommand (c) Immunity Inc.")
  8103. imm.log("Usage: !syscall -m <modulename> [-f <filename>]")
  8104. imm.log("-m Module to be analyzed. (Required)")
  8105. imm.log("-f Specify a filename to log all information to. (Optional)")
  8106.  
  8107. def main(args):
  8108.  
  8109. imm = Debugger()
  8110.  
  8111. log_file = None
  8112. module = ""
  8113. error = False
  8114.  
  8115. try:
  8116. opts,argo = getopt.getopt(args, "m:f")
  8117. except:
  8118. usage(imm)
  8119. return "See log for usage info"
  8120.  
  8121. for o,a in opts:
  8122. if o == "-m":
  8123. module = a
  8124. if o == "-f":
  8125. log_file = a
  8126.  
  8127. # We key into the syscall_table using the OS
  8128. # getOsInformation returns ["Windows", "XP", "5.1.2600"]
  8129. global syscall_table
  8130. syscall_key = imm.getOsInformation()[1]
  8131.  
  8132. # Analyse the binary, and then grab all of the
  8133. # functions
  8134. executable = imm.getModule( module )
  8135.  
  8136. if executable is None:
  8137. imm.log("[*] Error finding module, please check the filename.")
  8138. return usage(imm)
  8139.  
  8140. exec_base = executable.getCodebase()
  8141.  
  8142. if not executable.isAnalysed():
  8143. imm.analyseCode( exec_base )
  8144.  
  8145. # In ImmLib you can use assembly instructions and wildcard
  8146. # search patterns the CONST below means match against any
  8147. # constants used as as operand
  8148. syscall_sig = "MOV EAX, CONST \n \
  8149. MOV EDX, 0x7FFE0300 \n \
  8150. CALL [EDX]"
  8151.  
  8152. address_list= imm.searchCommandsOnModule( exec_base, syscall_sig )
  8153.  
  8154. syscall_count = 0
  8155. for address in address_list:
  8156.  
  8157. # Simply decode the function that this call
  8158. # resides in
  8159. address = int(address[0])
  8160. resident_function = imm.decodeAddress( address )
  8161.  
  8162. # Attempt to map the opcode from our syscall table
  8163. #syscall_number = str(imm.disasm( function_head ).getOpData()[0])
  8164. opcode = imm.disasm( address )
  8165. instructions = opcode.getResult()
  8166.  
  8167. # This is testing whether its a false-positive, just
  8168. # means our search picked up the same binary pattern
  8169. if "MOV EAX" not in instructions:
  8170. imm.log("Werd")
  8171. continue
  8172.  
  8173. syscall_number = "0x%04x" % opcode.getOpData()[0]
  8174.  
  8175. if syscall_table[syscall_key].has_key( syscall_number ):
  8176. syscall_count += 1
  8177. syscall_name = syscall_table[syscall_key][syscall_number]
  8178. imm.setComment(address, "Syscall: %s" % syscall_name)
  8179.  
  8180. log_message = "[*] Syscall: %s (%s) from %s" % ( syscall_name, syscall_number, resident_function )
  8181. imm.log( "%s" % log_message, address = address)
  8182.  
  8183. # I do this for every iteration in case there is a failure
  8184. # we at least get the information logged as far as we could
  8185. if log_file is not None:
  8186.  
  8187. try:
  8188. fd = open(log_file,"w")
  8189. fd.write( log_message )
  8190. fd.close()
  8191. except IOError:
  8192. error = True
  8193. log_file
  8194.  
  8195. imm.log("[*] %d syscalls discovered - check log window for output." % syscall_count)
  8196.  
  8197. if error == True:
  8198. imm.log("[*] Unable to save to log file, please check pathname and permissions.")
  8199.  
  8200. return "[*] %d syscalls discovered - check log window for output." % syscall_count
  8201. #!/usr/bin/env python
  8202.  
  8203. """
  8204. (c) Immunity, Inc. 2004-2007
  8205.  
  8206.  
  8207. U{Immunity Inc.<http://www.immunityinc.com>}
  8208.  
  8209. Immunity PyCommand Template
  8210.  
  8211. """
  8212.  
  8213. __VERSION__ = '0.0'
  8214.  
  8215. import immlib
  8216. import getopt
  8217.  
  8218. DESC= "Immunity PyCommand Template" #description used by PyCommands GUI
  8219.  
  8220. def usage(imm):
  8221. """ All the options"""
  8222. imm.log("!template example command")
  8223. imm.log("!template [-a] [-b] [-c] ",focus=1) # focus the usage
  8224.  
  8225.  
  8226. def main(args):
  8227. imm = immlib.Debugger()
  8228.  
  8229. if not args:
  8230. imm.log("### Immunity's PyCommand template ###")
  8231. return "Command ok - no args"
  8232. try:
  8233. opts, argo = getopt.getopt(args, "a:bc:")
  8234. except getopt.GetoptError: #get args, if error, show usage
  8235. usage(imm)
  8236. return "Bad argument %s" % args[0]
  8237.  
  8238. #parsing args
  8239. for o,a in opts:
  8240. if o == "-a":
  8241. #processing args
  8242. ret=processA(imm,a)
  8243. elif o == "-b":
  8244. ret=processB(imm,a)
  8245. elif o == "-c":
  8246. ret=processC(imm,a)
  8247.  
  8248. #ret is the string shown at status bar
  8249. return ret
  8250.  
  8251.  
  8252.  
  8253. def processA(imm,arg):
  8254. """do whatever"""
  8255. imm.log("Argument received: %s" % str(arg))
  8256. return "Command ok with: %s" %str(arg) #string, string, string!
  8257.  
  8258. def processB(imm,arg):
  8259. imm.log("Argument received: %s" % str(arg))
  8260. return "Command ok with: %s" %str(arg)
  8261.  
  8262. def processC(imm,arg):
  8263. imm.log("Argument received: %s" % str(arg))
  8264. return "Command ok with: %s" %str(arg)
  8265. import socket
  8266. import struct
  8267.  
  8268. from immlib import *
  8269.  
  8270.  
  8271. DESC="""Creates a table that displays packets received on the network."""
  8272.  
  8273. #############################################################################
  8274. '''
  8275. Some defines for re-use.
  8276. '''
  8277. PACKET_TYPE_SEND = "Send "
  8278. PACKET_TYPE_RECV = "Recv "
  8279. PACKET_PROTOCOL_UDP = "(UDP)"
  8280. PACKET_PROTOCOL_TCP = "(TCP)"
  8281.  
  8282.  
  8283. #############################################################################
  8284. class set_hooks(LogBpHook):
  8285. def __init__(self):
  8286. LogBpHook.__init__(self)
  8287.  
  8288. #########################################################################
  8289. def run(self,regs):
  8290. '''
  8291. This routine is the first one hit, when a socket operation occurs.
  8292. '''
  8293. imm = Debugger()
  8294.  
  8295.  
  8296. # Retrieve the function name
  8297. function_name = imm.getKnowledge("%08x" % regs['EIP'])
  8298.  
  8299. self.retrieve_packet(imm,function_name,regs)
  8300.  
  8301.  
  8302. #########################################################################
  8303. def retrieve_packet(self,imm,function_name,regs):
  8304. '''
  8305. This function determines how to handle the packet data. Some socket
  8306. operations require more work (such as WSARecv), and others less (recv).
  8307.  
  8308. If necessary this function will register a hook on [ESP], where any
  8309. [out] pointers from a function will be set.
  8310. '''
  8311.  
  8312. # Determine what function we have hooked, based on this, retrieve the packet contents
  8313. if function_name == "WSARecv":
  8314. type = PACKET_TYPE_RECV+PACKET_PROTOCOL_TCP
  8315. extended_hook = True
  8316.  
  8317. if function_name == "WSASend":
  8318. type=PACKET_TYPE_SEND+PACKET_PROTOCOL_TCP
  8319. extended_hook = True
  8320.  
  8321. if function_name == "recvfrom":
  8322. type=PACKET_TYPE_RECV+PACKET_PROTOCOL_UDP
  8323. extended_hook = False
  8324.  
  8325. if function_name =="recv":
  8326. type=PACKET_TYPE_RECV+PACKET_PROTOCOL_TCP
  8327. extended_hook = False
  8328.  
  8329. # An extended hook requires a bit more work to pull out the packet info
  8330. if extended_hook == True:
  8331.  
  8332. # Get the pointer to the payload pointer :(
  8333. pbuffer_ptr = imm.readMemory( regs['ESP'] + 8, 4)
  8334. pbuffer_ptr = struct.unpack("L", pbuffer_ptr)
  8335. imm.log("Buffer Location: 0x%08x" % pbuffer_ptr[0])
  8336.  
  8337. # Get the pointer to the packet payload
  8338. payload_ptr = imm.readMemory(pbuffer_ptr[0]+4,4)
  8339. payload_ptr = struct.unpack("<L", payload_ptr)
  8340. imm.log("Payload Pointer: %08x" % payload_ptr[0])
  8341.  
  8342. # Get the [out] pointer of the received bytes
  8343. recv_ptr = imm.readMemory(regs['ESP'] + 0x10, 4)
  8344. recv_ptr = struct.unpack("L",recv_ptr)
  8345. imm.log("Receive Pointer: %08x" % recv_ptr[0])
  8346.  
  8347. # Figure out [esp]
  8348. esp_ptr = imm.readMemory(regs['ESP'],4)
  8349. esp_ptr = struct.unpack("<L", esp_ptr)
  8350. imm.log("[ESP] at 0x%08x" % esp_ptr[0])
  8351.  
  8352. # Now we hook [esp]
  8353. ret_hook = ext_hooks()
  8354. ret_hook.add("%08x" % esp_ptr[0],esp_ptr[0])
  8355.  
  8356. # Add this ret hook to the knowledgebase
  8357. imm.addKnowledge("%08x" % esp_ptr[0],(payload_ptr[0],recv_ptr[0],type,function_name))
  8358.  
  8359. else:
  8360.  
  8361. # Get the pointer to the buffer
  8362. payload_ptr = imm.readMemory(regs['ESP'] + 8, 4)
  8363. payload_ptr = struct.unpack("L", payload_ptr)
  8364.  
  8365. # Figure out where [ESP] points to
  8366. esp_ptr = imm.readMemory(regs['ESP'],4)
  8367. esp_ptr = struct.unpack("<L", esp_ptr)
  8368.  
  8369. # Add the [ESP] hook for when the function returns
  8370. simple_hook = simple_hooks()
  8371. simple_hook.add("%08x" % esp_ptr[0],esp_ptr[0])
  8372.  
  8373. # Add our pertinent information to the knowledgebase
  8374. imm.addKnowledge("%08x" % esp_ptr[0],(payload_ptr[0],type,function_name))
  8375.  
  8376.  
  8377. # The main routine that gets run when you type !packets
  8378. def main(args):
  8379.  
  8380. imm = Debugger()
  8381. imm.ignoreSingleStep("CONTINUE")
  8382. hooker = set_hooks()
  8383.  
  8384. # Find the addresses of the functions we want to hook
  8385. # Then register the hooks
  8386. ws_wsarecv = imm.getAddress("ws2_32.WSARecv")
  8387. ws_wsasend = imm.getAddress("ws2_32.WSASend")
  8388. ws_recv = imm.getAddress("ws2_32.recv")
  8389. ws_recvfrom = imm.getAddress("ws2_32.recvfrom")
  8390.  
  8391. # Set the hooks
  8392. hooker.add("WSARecv", ws_wsarecv)
  8393. hooker.add("WSASend", ws_wsasend)
  8394. hooker.add("recv", ws_recv)
  8395. hooker.add("recvfrom", ws_recvfrom)
  8396.  
  8397. # Register the hook-address pair with the knowledgebase
  8398. imm.addKnowledge("%08x" % ws_wsarecv, "WSARecv")
  8399. imm.addKnowledge("%08x" % ws_wsasend, "WSASend")
  8400. imm.addKnowledge("%08x" % ws_recv, "recv")
  8401. imm.addKnowledge("%08x" % ws_recvfrom, "recvfrom")
  8402.  
  8403.  
  8404. return "Network hooks in place."
  8405.  
  8406.  
  8407. import socket
  8408. import struct
  8409.  
  8410. from immlib import *
  8411.  
  8412.  
  8413. DESC="""Creates a table that displays packets received on the network."""
  8414.  
  8415. #############################################################################
  8416. '''
  8417. Some defines for re-use.
  8418. '''
  8419. PACKET_TYPE_SEND = "Send "
  8420. PACKET_TYPE_RECV = "Recv "
  8421. PACKET_PROTOCOL_UDP = "(UDP)"
  8422. PACKET_PROTOCOL_TCP = "(TCP)"
  8423.  
  8424.  
  8425. #############################################################################
  8426. class set_hooks(LogBpHook):
  8427. def __init__(self):
  8428. LogBpHook.__init__(self)
  8429.  
  8430. #########################################################################
  8431. def run(self,regs):
  8432. '''
  8433. This routine is the first one hit, when a socket operation occurs.
  8434. '''
  8435. imm = Debugger()
  8436.  
  8437.  
  8438. # Retrieve the function name
  8439. function_name = imm.getKnowledge("%08x" % regs['EIP'])
  8440.  
  8441. self.retrieve_packet(imm,function_name,regs)
  8442.  
  8443.  
  8444. #########################################################################
  8445. def retrieve_packet(self,imm,function_name,regs):
  8446. '''
  8447. This function determines how to handle the packet data. Some socket
  8448. operations require more work (such as WSARecv), and others less (recv).
  8449.  
  8450. If necessary this function will register a hook on [ESP], where any
  8451. [out] pointers from a function will be set.
  8452. '''
  8453.  
  8454. # Determine what function we have hooked, based on this, retrieve the packet contents
  8455. if function_name == "WSARecv":
  8456. type = PACKET_TYPE_RECV+PACKET_PROTOCOL_TCP
  8457. extended_hook = True
  8458.  
  8459. if function_name == "WSASend":
  8460. type=PACKET_TYPE_SEND+PACKET_PROTOCOL_TCP
  8461. extended_hook = True
  8462.  
  8463. if function_name == "recvfrom":
  8464. type=PACKET_TYPE_RECV+PACKET_PROTOCOL_UDP
  8465. extended_hook = False
  8466.  
  8467. if function_name =="recv":
  8468. type=PACKET_TYPE_RECV+PACKET_PROTOCOL_TCP
  8469. extended_hook = False
  8470.  
  8471. # An extended hook requires a bit more work to pull out the packet info
  8472. if extended_hook == True:
  8473.  
  8474. # Get the pointer to the payload pointer :(
  8475. pbuffer_ptr = imm.readMemory( regs['ESP'] + 8, 4)
  8476. pbuffer_ptr = struct.unpack("L", pbuffer_ptr)
  8477. imm.log("Buffer Location: 0x%08x" % pbuffer_ptr[0])
  8478.  
  8479. # Get the pointer to the packet payload
  8480. payload_ptr = imm.readMemory(pbuffer_ptr[0]+4,4)
  8481. payload_ptr = struct.unpack("<L", payload_ptr)
  8482. imm.log("Payload Pointer: %08x" % payload_ptr[0])
  8483.  
  8484. # Get the [out] pointer of the received bytes
  8485. recv_ptr = imm.readMemory(regs['ESP'] + 0x10, 4)
  8486. recv_ptr = struct.unpack("L",recv_ptr)
  8487. imm.log("Receive Pointer: %08x" % recv_ptr[0])
  8488.  
  8489. # Figure out [esp]
  8490. esp_ptr = imm.readMemory(regs['ESP'],4)
  8491. esp_ptr = struct.unpack("<L", esp_ptr)
  8492. imm.log("[ESP] at 0x%08x" % esp_ptr[0])
  8493.  
  8494. # Now we hook [esp]
  8495. #ret_hook = ext_hooks()
  8496. #ret_hook.add("%08x" % esp_ptr[0],esp_ptr[0])
  8497.  
  8498. # Add this ret hook to the knowledgebase
  8499. #imm.addKnowledge("%08x" % esp_ptr[0],(payload_ptr[0],recv_ptr[0],type,function_name))
  8500.  
  8501. else:
  8502.  
  8503. # Get the pointer to the buffer
  8504. payload_ptr = imm.readMemory(regs['ESP'] + 8, 4)
  8505. payload_ptr = struct.unpack("L", payload_ptr)
  8506.  
  8507. # Figure out where [ESP] points to
  8508. esp_ptr = imm.readMemory(regs['ESP'],4)
  8509. esp_ptr = struct.unpack("<L", esp_ptr)
  8510. imm.log("Payload Pointer: %08x" % payload_ptr[0])
  8511. imm.log("Payload Pointer: %08x" % esp_ptr[0])
  8512.  
  8513. # Add the [ESP] hook for when the function returns
  8514. #simple_hook = simple_hooks()
  8515. #simple_hook.add("%08x" % esp_ptr[0],esp_ptr[0])
  8516.  
  8517. # Add our pertinent information to the knowledgebase
  8518. #imm.addKnowledge("%08x" % esp_ptr[0],(payload_ptr[0],type,function_name))
  8519.  
  8520.  
  8521. # The main routine that gets run when you type !packets
  8522. def main(args):
  8523.  
  8524. imm = Debugger()
  8525. imm.ignoreSingleStep("CONTINUE")
  8526. hooker = set_hooks()
  8527.  
  8528. # Find the addresses of the functions we want to hook
  8529. # Then register the hooks
  8530. ws_wsarecv = imm.getAddress("ws2_32.WSARecv")
  8531. ws_wsasend = imm.getAddress("ws2_32.WSASend")
  8532. ws_recv = imm.getAddress("ws2_32.recv")
  8533. ws_recvfrom = imm.getAddress("ws2_32.recvfrom")
  8534.  
  8535. # Set the hooks
  8536. hooker.add("WSARecv", ws_wsarecv)
  8537. hooker.add("WSASend", ws_wsasend)
  8538. hooker.add("recv", ws_recv)
  8539. hooker.add("recvfrom", ws_recvfrom)
  8540.  
  8541. # Register the hook-address pair with the knowledgebase
  8542. imm.addKnowledge("%08x" % ws_wsarecv, "WSARecv")
  8543. imm.addKnowledge("%08x" % ws_wsasend, "WSASend")
  8544. imm.addKnowledge("%08x" % ws_recv, "recv")
  8545. imm.addKnowledge("%08x" % ws_recvfrom, "recvfrom")
  8546.  
  8547.  
  8548. return "Network 2 in place."
  8549.  
  8550.  
  8551. #!/usr/bin/env python
  8552.  
  8553. """
  8554. (c) Immunity, Inc. 2004-2007
  8555.  
  8556.  
  8557. U{Immunity Inc.<http://www.immunityinc.com>}
  8558.  
  8559. Traceargs example
  8560.  
  8561. """
  8562.  
  8563. __VERSION__ = '1.0'
  8564.  
  8565. DESC="""TraceArgs -> Find User supplied arguments into a given function"""
  8566.  
  8567. import immlib
  8568. import immutils
  8569. import getopt
  8570. modarg = []
  8571. visited = []
  8572. COUNT = 100 # LOOP LIMIT
  8573.  
  8574. def usage(imm):
  8575. imm.log( "!traceargs Find user-supplied arguments into a given function" )
  8576. imm.log( "!traceargs -a ADDRESS -n ARG <-s> <-b>" )
  8577. imm.log(" -a ADDRESS Address of the function")
  8578. imm.log(" -n ARG Argument number you want to look for")
  8579. imm.log(" -s Wheter or not, show all the result (including non user-supplied)")
  8580. imm.log(" -b Wheter or not, breakpoint on the calling instructions")
  8581.  
  8582. def main(args):
  8583. imm=immlib.Debugger()
  8584. if not args:
  8585. usage(imm)
  8586. return "Wrong Arguments (Check usage on the Log Window)"
  8587.  
  8588. try:
  8589. opts, argo = getopt.getopt(args, "a:n:sb")
  8590. except getopt.GetoptError:
  8591. usage(imm)
  8592. return "Wrong Arguments (Check usage on the Log Window)"
  8593.  
  8594. funcaddress = 0
  8595. tracedarg = 0
  8596. shownonusersupplied = False
  8597. breakpointoncall = False
  8598.  
  8599. for o,a in opts:
  8600. if o == '-a':
  8601. try:
  8602. funcaddress = int( a, 16 )
  8603. except ValueError:
  8604. usage(imm)
  8605. return "Wrong Address (%s) % " % a
  8606. elif o == '-n':
  8607. try:
  8608. tracedarg = int( a, 16 )
  8609. except ValueError:
  8610. usage(imm)
  8611. return "Wrong Trace Arg (%s) % " % a
  8612. elif o == '-s':
  8613. shownonusersupplied = True
  8614. elif o == '-b':
  8615. breakpointoncall = True
  8616.  
  8617. if not funcaddress:
  8618. usage(imm)
  8619. return "Wrong Arguments. Address is missing"
  8620. if not tracedarg:
  8621. usage(imm)
  8622. return "Wrong Arguments. Trace Argument is missing"
  8623. references = imm.getXrefFrom( funcaddress )
  8624. for ref in references:
  8625.  
  8626. ret = imm.getTraceArgs( ref[0], tracedarg, shownonusersupplied)
  8627. if ret:
  8628. ( op, show ) = ret
  8629. imm.log("Found user-supplied for arg_%d in %s" % ( tracedarg, imm.disasm(ref[0]).result) , address = ref[0])
  8630. if hasattr(op, 'type'): type = op.type
  8631. else: type=""
  8632.  
  8633. imm.log( "%s %s" % (op.getDisasm(), type), address = op.getAddress() )
  8634. for msg in show:
  8635. imm.log( msg.getDisasm(), address = msg.getAddress() )
  8636. imm.log("------")
  8637. if breakpointoncall:
  8638. imm.setBreakpoint( ref[0] )
  8639.  
  8640. return 0
  8641. #!/usr/bin/env python
  8642.  
  8643. """
  8644. (c) Immunity, Inc. 2004-2008
  8645.  
  8646. U{Immunity Inc.<http://www.immunityinc.com>}
  8647.  
  8648. Tree Dll
  8649.  
  8650. """
  8651.  
  8652. __VERSION__ = '1.0'
  8653.  
  8654. NAME = "treedll"
  8655. DESC="""Creates imported dll tree"""
  8656.  
  8657. import immlib
  8658. import immutils
  8659. import getopt
  8660.  
  8661. def usage(imm):
  8662. imm.log("!%s" % NAME)
  8663. imm.log("%s" % DESC)
  8664. imm.log("-p process name")
  8665. imm.log("-l max tree level")
  8666.  
  8667. class Node:
  8668. def __init__(self, name):
  8669. self.name = name
  8670. self.imports = []
  8671. def getName(self, name):
  8672. return name
  8673. def getImports(self):
  8674. return self.imports
  8675. def addImport(self, tl):
  8676. self.imports.append( tl )
  8677.  
  8678. class DLLTree:
  8679. def __init__(self, imm, entry = "", maxlevel = 3):
  8680. self.imm = imm
  8681. if not entry:
  8682. self.entry = imm.getDebuggedName()
  8683. else:
  8684. self.entry = entry
  8685. self.node = None
  8686. self.maxlevel = maxlevel
  8687. self.sym = None
  8688.  
  8689. def Initalize(self):
  8690. self.sym = self.imm.getAllSymbols()
  8691.  
  8692. def Get(self):
  8693. if not self.sym:
  8694. self.Initalize()
  8695. self.tree = {}
  8696. self.checked = {}
  8697. self.node = self.buru(self.entry)
  8698. return self.node
  8699.  
  8700. def Show(self):
  8701. if not self.node:
  8702. self.Get()
  8703.  
  8704. self.showNodeTree(self.node, 0, 0)
  8705.  
  8706. def showNodeTree(self, node, num, level):
  8707. if level >= self.maxlevel:
  8708. return
  8709. self.imm.log(" " * num + node.name)
  8710. self.checked[ node.name ] = 1
  8711. for n in node.getImports():
  8712. self.showNodeTree(n, num + 2, level+1)
  8713.  
  8714. def buru(self, name):
  8715. if name in self.checked.keys():
  8716. return None
  8717. tl = []
  8718. self.checked[name] = Node( name )
  8719. try:
  8720. tl = self.getAssociatedDLL(name)
  8721. except Exception, msg:
  8722. self.imm.log("Exception: %s" % str(msg))
  8723.  
  8724. for nn in tl:
  8725. if nn != name:
  8726. node = self.buru( nn )
  8727. if not node:
  8728. node = self.checked[nn]
  8729. self.checked[name].addImport( node )
  8730. return self.checked[name]
  8731.  
  8732. def getAssociatedDLL(self, name):
  8733. if not self.sym:
  8734. self.Initalize()
  8735.  
  8736. tl = {}
  8737. if name not in self.sym:
  8738. raise Exception, "Entry not a dll found: %s" % name
  8739. symbols = self.sym[name]
  8740. for a in symbols.keys():
  8741. s = symbols[a]
  8742. #self.imm.log("%s | %s " % (s.type, s.name))
  8743. if s.type[:6] == "Import":
  8744. sname = s.name.split(".",1)[0].lower() + ".dll"
  8745. if sname not in tl.keys():
  8746. tl[sname] = 1
  8747. return tl.keys()
  8748.  
  8749. def main(args):
  8750. imm=immlib.Debugger()
  8751. try:
  8752. opts, argo = getopt.getopt(args, "p:l:")
  8753. except getopt.GetoptError:
  8754. usage(imm)
  8755. return "Wrong Arguments (Check usage on the Log Window)"
  8756.  
  8757. processname = None
  8758. level = 3
  8759.  
  8760. for o,a in opts:
  8761. if o == '-p':
  8762. processname = a
  8763. elif o == '-l':
  8764. level = int(a, 16)
  8765.  
  8766. if processname is None:
  8767. usage(imm)
  8768. return "See log for usage info"
  8769.  
  8770. d = DLLTree(imm, processname, level)
  8771. d.Show()
  8772.  
  8773.  
  8774. return "Check log window for results."
  8775. #!/usr/bin/env python
  8776.  
  8777. """
  8778. (c) Immunity, Inc. 2004 - 2007
  8779.  
  8780.  
  8781. U{Immunity Inc.<http://www.immunityinc.com>}
  8782.  
  8783. """
  8784.  
  8785.  
  8786. __VERSION__ = '1.0'
  8787.  
  8788. import immlib
  8789.  
  8790. DESC = "Return the usage information for a python command"
  8791.  
  8792. def usage(imm):
  8793. imm.log("!usage Returns the usage information for a pytho command")
  8794.  
  8795. def main(args):
  8796. imm = immlib.Debugger()
  8797. ret_str = None
  8798.  
  8799. if args:
  8800. try:
  8801. mod = __import__(args[0])
  8802. except ImportError:
  8803. return "Error: %s is not a python command" % args[0]
  8804. try:
  8805. ret_str = mod.usage(imm)
  8806. except AttributeError:
  8807. return "Sorry, no usage available for this command"
  8808. else:
  8809. return "No arguments given"
  8810.  
  8811. if ret_str is None:
  8812. return "See log window for usage information"
  8813. import immutils
  8814. from immlib import *
  8815. import getopt
  8816.  
  8817. # Hook names, no need for an explanation
  8818. HOOK_NAME = "vct_hook"
  8819.  
  8820. # Symbol names of the functions we want to hook
  8821. HOOK_SYMS = ["VariantChangeTypeEx"]
  8822.  
  8823. # Module name, just to know where we are
  8824. HOOK_MODULE = "OLEAUT32"
  8825.  
  8826. class VCTHook(LogBpHook):
  8827. """
  8828. VariantChangeType Hook
  8829.  
  8830. This hook is used to check if the arguments of VariantChangeType are pointers
  8831. to the same object. There might be vulnerabilities in code that call this function
  8832. in such a manner.
  8833. """
  8834. def __init__(self):
  8835. LogBpHook.__init__(self)
  8836. self.dbg = Debugger()
  8837. self.count = 0
  8838.  
  8839. def run(self, regs):
  8840. pvargDest = self.dbg.readLong(regs['ESP'] + 0x4)
  8841. pvarSrc = self.dbg.readLong(regs['ESP'] + 0x8)
  8842. third = self.dbg.readLong(regs['ESP'] + 0xc)
  8843.  
  8844. if pvargDest == pvarSrc:
  8845. self.dbg.log("-"*80)
  8846. call_stack = self.dbg.callStack()
  8847. for frame in call_stack:
  8848. self.dbg.log("Address = %08x | Stack = %08x | Procedure %s | Frame %08x | Called from %08x" \
  8849. %(frame.address, frame.stack, frame.procedure, frame.frame, frame.calledfrom), address=frame.calledfrom)
  8850.  
  8851. def usage(dbg):
  8852. dbg.log("!VCTHook.py")
  8853. dbg.log("-u (to uninstall hook)")
  8854.  
  8855. def main(args):
  8856. """
  8857. """
  8858. dbg = Debugger()
  8859.  
  8860. mod = dbg.getModule(HOOK_MODULE)
  8861.  
  8862. try:
  8863. opts, argo = getopt.getopt(args, "ulc:", ["remove", "list", "count"])
  8864. except getopt.GetoptError, err:
  8865. usage(dbg)
  8866. return str(err)
  8867.  
  8868. for o,a in opts:
  8869. if o == "-u":
  8870. # TODO check if the hook exists
  8871. dbg.removeHook(HOOK_NAME)
  8872. return "Removed hook on %s." %(HOOK_NAME)
  8873. elif o == "-l":
  8874. hooks = dbg.listHooks()
  8875. for hook in hooks:
  8876. dbg.log(hook)
  8877. return "OK"
  8878. elif o == "-c":
  8879. count = int(a)
  8880.  
  8881. hooker = VCTHook()
  8882.  
  8883. # Set hooks
  8884. for sym_name in HOOK_SYMS:
  8885. full_sym_name = HOOK_MODULE + "." + sym_name
  8886. bp_address = dbg.getAddress(full_sym_name)
  8887. dbg.log("Adding hook to %s on address %08x" %(full_sym_name, bp_address))
  8888. hooker.add(HOOK_NAME, bp_address)
  8889.  
  8890. return "Hooks are in Place!"
  8891.  
  8892. if __name__ == "__main__":
  8893. main()
Add Comment
Please, Sign In to add comment