Advertisement
yorath

hooker

Jan 7th, 2013
66
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 2.04 KB | None | 0 0
  1. #!/usr/bin/env python
  2.  
  3. from pydbg import *
  4. from pydbg.defines import *
  5.  
  6. import ctypes
  7. import struct
  8.  
  9.  
  10. class Hooker():
  11.  
  12.     def __init__(self):
  13.         self.jump_code = bytearray('6800000000C3'.decode('hex'))
  14.         self.Jumpback_code = bytearray('6800000000C3'.decode('hex'))
  15.         self.Jump_code_ize = len(self.jump_code)
  16.         self.jumpback_code_size = len(self.Jumpback_code)
  17.         self.dbg = pydbg()
  18.  
  19.  
  20.     def hook(dll, function=None, calltype=None, restype=c_ulong, **kwargs):
  21.  
  22.         def decorator(f):
  23.  
  24.             if function is None:
  25.                 function = f.__name__
  26.  
  27.             functype = {
  28.                 None: ctypes.WINFUNCTYE,
  29.                 'C': ctypes.CFUNCTYPE,
  30.             }[calltype]
  31.  
  32.             arg_names = f.func_code.co_varnames
  33.             arg_types = [kwargs.get(arg_name, c_ulong) for arg_name in arg_names]
  34.  
  35.             prototype = functype(restype, *arg_types)
  36.             fake = prototype(f)
  37.  
  38.             address = self.dbg.func_resolve_debuggee(dll, function)
  39.             if not address:
  40.                 return False
  41.  
  42.             backup_length = 0
  43.             while backup_length < self.Jump_code_ize:
  44.                 instruction = self.dbg.get_instruction(where)
  45.                 if instruction:
  46.                     backup_length += instruction.length
  47.                 else:
  48.                     return False
  49.  
  50.             self.jump_code[1:5] = struct.pack('I', fake)
  51.             self.Jumpback_code[1:5] = struct.pack('I', address + backup_length)
  52.  
  53.             proxy_function_addr = self.dbg.virtual_alloc(
  54.                 NULL, backup_length + self.jumpback_code_size,
  55.                 MEM_COMMIT | MEM_RESERVE, PAGE_EXECUTE_READWRITE)
  56.  
  57.             proxy_function = self.dbg.read(address, backup_length)
  58.             proxy_function += self.Jumpback_code
  59.  
  60.             self.dbg.write(proxy_function_addr, proxy_function,
  61.                          len(proxy_function))
  62.  
  63.             return proxy_function_addr
  64.  
  65.         return decorator
  66.  
  67. if __main__ == '__main__':
  68.     hooker = Hooker()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement