Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- from __future__ import print_function
- from win32con import *
- from tempfile import NamedTemporaryFile, mkstemp
- import logging
- import os, subprocess, sys
- from binascii import hexlify
- logfile = mkstemp(suffix='.log')[1]
- logging.basicConfig(level=logging.DEBUG,
- format='%(asctime)s %(name)-12s %(levelname)-8s %(message)s',
- datefmt='%m-%d %H:%M',
- filename=logfile,
- filemode='w')
- print('Logging to file %s' % (logfile,))
- # define a Handler which writes DEBUG messages or higher to the sys.stderr
- console = logging.StreamHandler()
- console.setLevel(logging.DEBUG)
- # set a format which is simpler for console use
- formatter = logging.Formatter('%(name)-12s: %(levelname)-8s %(message)s')
- # tell the handler to use this format
- console.setFormatter(formatter)
- # add the handler to the root logger
- log = logging.getLogger('asmgen')
- log.setLevel(logging.DEBUG)
- if len(log.handlers) == 0:
- log.addHandler(console)
- def GenAsm(asm):
- tf = NamedTemporaryFile(mode='w+', suffix='.asm', delete=False)
- filename = tf.name
- log.info('Creating temporary asm file %s' % (filename,))
- tf.write(asm)
- tf.close()
- return filename
- GenAsm("""
- SECTION .data
- _str:
- dd 'Testing'
- SECTION .text
- extern _printf
- GLOBAL _entrypoint_asm ; DLL entry point
- _entrypoint_asm:
- mov eax, 1
- push _str
- call _printf
- pop eax
- ret
- """
- )
- tf = open('asm.c.tmp', 'w+')
- tf.write("""
- #include <windows.h>
- extern "C" BOOL WINAPI DllMain(
- __in HINSTANCE hinstDLL,
- __in DWORD fdwReason,
- __in LPVOID lpvReserved
- );
- """)
- tf.close()
- tf = open('make.bat', 'w+')
- tf.write("""
- cmd /C "vcvarsall.bat && cl asm.obj stub.cpp /LD /MD -Feinject.dll"
- """)
- tf.close()
- outfile = os.getcwd() + '\\asm.obj'
- infile = os.getcwd() + '\\asm.tmp'
- incfile = os.getcwd() + '\\stub.cpp'
- outdll = os.getcwd() + '\\inject.dll'
- make = os.getcwd() + '\\make.bat'
- print(infile, outfile)
- def Call(cmdline, silent=False):
- result = subprocess.call(cmdline, stdout=sys.stdout, stderr=sys.stderr)
- if result:
- raise Exception, "%s failed with error code %d" % (cmdline, result)
- return result
- Call(['C:\\bin\\yasm.exe', '-f', 'win32', '-o', outfile, infile])
- Call([make])
- import ctypes
- dll = os.getcwd() + '\\inject.dll'
- class FunctionPointer(object):
- def __init__(self, fn):
- self.fn = fn
- def __call__(self, *args):
- new_args = []
- for arg in args:
- if isinstance(arg, str):
- arg = ctypes.create_string_buffer(arg)
- new_args.append(arg)
- print new_args
- return self.fn(*new_args)
- class Kernel32(object):
- def __init__(self):
- import ctypes
- self.lib = ctypes.windll['kernel32.dll']
- def __getattr__(self, attr):
- val = getattr(self.lib, attr)
- if isinstance(val, self.lib._FuncPtr):
- return FunctionPointer(val)
- return val
- def GPA(mod, fn):
- import win32api
- mod = win32api.GetModuleHandle(mod)
- return win32api.GetProcAddress(mod, fn)
- k = Kernel32()
- pid = 2564
- ph = k.OpenProcess(PROCESS_ALL_ACCESS, 1, pid)
- print GPA('kernel32.dll', 'GetStartupInfoA')
- remote_buf = k.VirtualAllocEx(ph, 0, len(dll)+1,MEM_COMMIT, PAGE_READWRITE)
- if remote_buf == 0:
- raise Exception, "Unable to allocate remote memory"
- bytes_written = ctypes.c_uint64(0)
- if k.WriteProcessMemory(ph, remote_buf, dll, len(dll), ctypes.byref(bytes_written)) == 0:
- raise Exception, "Failed to write remote memory"
- print "Wrote %d bytes to remote memory" % bytes_written.value
- remote_thread = k.CreateRemoteThread(ph, 0, 0,
- GPA('kernel32.dll', 'LoadLibraryA'),
- remote_buf, 0, 0)
- print "Started remote thread %d" % remote_thread
- if not remote_thread:
- raise Exception, "Failed to create remote thread"
- WaitForSingleObject(remote_thread, 100000)
Advertisement
Add Comment
Please, Sign In to add comment