tthtlc

pycommand

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