falaina

Untitled

Aug 3rd, 2012
52
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 3.93 KB | None | 0 0
  1. from __future__ import print_function
  2. from win32con import *
  3. from tempfile import NamedTemporaryFile, mkstemp
  4. import logging
  5. import os, subprocess, sys
  6. from binascii import hexlify
  7.  
  8. logfile = mkstemp(suffix='.log')[1]
  9. logging.basicConfig(level=logging.DEBUG,
  10. format='%(asctime)s %(name)-12s %(levelname)-8s %(message)s',
  11. datefmt='%m-%d %H:%M',
  12. filename=logfile,
  13. filemode='w')
  14. print('Logging to file %s' % (logfile,))
  15.  
  16. # define a Handler which writes DEBUG messages or higher to the sys.stderr
  17. console = logging.StreamHandler()
  18. console.setLevel(logging.DEBUG)
  19.  
  20. # set a format which is simpler for console use
  21. formatter = logging.Formatter('%(name)-12s: %(levelname)-8s %(message)s')
  22. # tell the handler to use this format
  23. console.setFormatter(formatter)
  24. # add the handler to the root logger
  25. log = logging.getLogger('asmgen')
  26. log.setLevel(logging.DEBUG)
  27. if len(log.handlers) == 0:
  28. log.addHandler(console)
  29.  
  30. def GenAsm(asm):
  31. tf = NamedTemporaryFile(mode='w+', suffix='.asm', delete=False)
  32. filename = tf.name
  33. log.info('Creating temporary asm file %s' % (filename,))
  34. tf.write(asm)
  35. tf.close()
  36. return filename
  37.  
  38.  
  39. GenAsm("""
  40. SECTION .data
  41. _str:
  42. dd 'Testing'
  43.  
  44. SECTION .text
  45. extern _printf
  46. GLOBAL _entrypoint_asm ; DLL entry point
  47. _entrypoint_asm:
  48. mov eax, 1
  49. push _str
  50. call _printf
  51. pop eax
  52. ret
  53. """
  54. )
  55.  
  56. tf = open('asm.c.tmp', 'w+')
  57. tf.write("""
  58. #include <windows.h>
  59. extern "C" BOOL WINAPI DllMain(
  60. __in HINSTANCE hinstDLL,
  61. __in DWORD fdwReason,
  62. __in LPVOID lpvReserved
  63. );
  64. """)
  65. tf.close()
  66.  
  67. tf = open('make.bat', 'w+')
  68. tf.write("""
  69. cmd /C "vcvarsall.bat && cl asm.obj stub.cpp /LD /MD -Feinject.dll"
  70. """)
  71. tf.close()
  72.  
  73. outfile = os.getcwd() + '\\asm.obj'
  74. infile = os.getcwd() + '\\asm.tmp'
  75. incfile = os.getcwd() + '\\stub.cpp'
  76. outdll = os.getcwd() + '\\inject.dll'
  77. make = os.getcwd() + '\\make.bat'
  78.  
  79. print(infile, outfile)
  80. def Call(cmdline, silent=False):
  81. result = subprocess.call(cmdline, stdout=sys.stdout, stderr=sys.stderr)
  82. if result:
  83. raise Exception, "%s failed with error code %d" % (cmdline, result)
  84. return result
  85.  
  86. Call(['C:\\bin\\yasm.exe', '-f', 'win32', '-o', outfile, infile])
  87. Call([make])
  88.  
  89. import ctypes
  90. dll = os.getcwd() + '\\inject.dll'
  91. class FunctionPointer(object):
  92. def __init__(self, fn):
  93. self.fn = fn
  94.  
  95. def __call__(self, *args):
  96. new_args = []
  97. for arg in args:
  98. if isinstance(arg, str):
  99. arg = ctypes.create_string_buffer(arg)
  100. new_args.append(arg)
  101. print new_args
  102. return self.fn(*new_args)
  103.  
  104. class Kernel32(object):
  105. def __init__(self):
  106. import ctypes
  107. self.lib = ctypes.windll['kernel32.dll']
  108.  
  109. def __getattr__(self, attr):
  110. val = getattr(self.lib, attr)
  111. if isinstance(val, self.lib._FuncPtr):
  112. return FunctionPointer(val)
  113. return val
  114.  
  115. def GPA(mod, fn):
  116. import win32api
  117. mod = win32api.GetModuleHandle(mod)
  118. return win32api.GetProcAddress(mod, fn)
  119.  
  120.  
  121. k = Kernel32()
  122. pid = 2564
  123. ph = k.OpenProcess(PROCESS_ALL_ACCESS, 1, pid)
  124. print GPA('kernel32.dll', 'GetStartupInfoA')
  125. remote_buf = k.VirtualAllocEx(ph, 0, len(dll)+1,MEM_COMMIT, PAGE_READWRITE)
  126. if remote_buf == 0:
  127. raise Exception, "Unable to allocate remote memory"
  128.  
  129. bytes_written = ctypes.c_uint64(0)
  130. if k.WriteProcessMemory(ph, remote_buf, dll, len(dll), ctypes.byref(bytes_written)) == 0:
  131. raise Exception, "Failed to write remote memory"
  132.  
  133. print "Wrote %d bytes to remote memory" % bytes_written.value
  134. remote_thread = k.CreateRemoteThread(ph, 0, 0,
  135. GPA('kernel32.dll', 'LoadLibraryA'),
  136. remote_buf, 0, 0)
  137.  
  138. print "Started remote thread %d" % remote_thread
  139. if not remote_thread:
  140. raise Exception, "Failed to create remote thread"
  141.  
  142. WaitForSingleObject(remote_thread, 100000)
Advertisement
Add Comment
Please, Sign In to add comment