#
# 2015 Collin Mulliner <collin AT mulliner.org> http://www.mulliner.org/security/windows
#
# use QueueUserAPC to inject a DLL into a process on load time, injection
# takes place before main thread is run, injected DLL therefore can take 
# control of the process (e.g. hijacking its entrypoint)
#
# based on inject.c from cuckoo sandbox by Jurriaan Bremer
#

import sys
import os
from pydbg           import *
from pydbg.defines   import *
from pydbg.my_ctypes import *

def injectdll_apc( dbg, dll_path):
    h_kernel32 = kernel32.GetModuleHandleA("kernel32.dll")
    h_loadlib  = kernel32.GetProcAddress(h_kernel32, "LoadLibraryA")

    h_process = kernel32.OpenProcess(PROCESS_ALL_ACCESS, False, dbg.pid)

    dll_len = len(dll_path)
    arg_address = kernel32.VirtualAllocEx(h_process, 0, dll_len, VIRTUAL_MEM, PAGE_READWRITE)

    written = c_int(0)
    kernel32.WriteProcessMemory(h_process, arg_address, dll_path, dll_len, byref(written))

    res = 0
    # only one thread at this point
    for thread_id in dbg.enumerate_threads():
        h_thread = dbg.open_thread(thread_id)
        res = kernel32.QueueUserAPC(h_loadlib, h_thread, arg_address)
        break
   
    kernel32.CloseHandle(h_process)
    kernel32.CloseHandle(h_kernel32)
    dbg.close_handle(h_thread)

    # return status of QueueUserAPC
    return res


if __name__ == "__main__":
    dbg = pydbg()
    self.dbg = dbg
    dbg.load(sys.argv[2], command_line = sys.argv[3])
	injectdll_apc(dbg, sys.argv[1])
	dbg.run()
