Solved Python CreateRemoteThread crashing process

Hexui Undetected CSGO Cheats Sinkicheat PUBG Cheat

rubberduccky

Newbie
Full Member
Jan 25, 2014
7
144
0
Hello GuidedHacking! I am new to this website and to hacking in general. I hope to learn a lot about the windows API/OS programming in general. If I am doing something wrong in posting this thread I apologize. I retrieved the following code from C source code found around the internet and attempted to translate it into a python script.

C++:
from ctypes import *

def dllinjector(processID, DLL_NAME):
    PROCESS_CREATE_THREAD = 0x0002
    PROCESS_QUERY_INFORMATION = 0x0400
    PROCESS_VM_OPERATION = 0x0008
    PROCESS_VM_WRITE = 0x0020
    PROCESS_VM_READ = 0x0010
    openHandle = windll.kernel32.OpenProcess(PROCESS_CREATE_THREAD|
                                             PROCESS_QUERY_INFORMATION|
                                             PROCESS_VM_OPERATION|
                                             PROCESS_VM_WRITE|
                                             PROCESS_VM_READ, False, processID)
    MEM_RESERVE = 0x00002000
    MEM_COMMIT = 0x00001000
    PAGE_READWRITE = 0x04
    
    if not openHandle:
        print("OpenProcess failed.")
        print("GetLastError: ", windll.kernel32.GetLastError())
        return False

    print("Successfully opened process.")

    LoadLibAddy = windll.kernel32.GetProcAddress(windll.kernel32.GetModuleHandleW("kernel32.dll"), "LoadLibraryA");

    # Allocate space in the process for the dll
    RemoteString = windll.kernel32.VirtualAllocEx(openHandle, None, len(DLL_NAME), MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE)
    if not RemoteString:
        print("VirtualAllocEx failed.")
        return False

    # Write the string name of the dll in the memory allocated
    if not windll.kernel32.WriteProcessMemory(openHandle, RemoteString, DLL_NAME, len(DLL_NAME), None):
        print("WriteProcessMemory failed.")
        return False

    #Load the dll
    if not windll.kernel32.CreateRemoteThread(openHandle, None, None, LoadLibAddy, RemoteString, None, None):
        print("CreateRemoteThread failed.")
        return False

    windll.kernel32.CloseHandle(openHandle)

    return True

def main():
    processID = 33480
    DLL_NAME = "mydll32.dll"
    
    dllinjector(processID, DLL_NAME)
    
    print("program completed.")

main()
The problem that I am facing is CreateRemoteThread crashes the process that I am attempting to inject the dll into. When I comment out CreateRemoteThread the script seems to run fine. No errors are raised and I think everything works fine. If I call GetLastError after calling CreateRemoteThread only a 0 is returned. From reading the docs on CreateRemoteThread and GetLastError a 0 indicates that no errors were raised so I have very little information to go on. I would greatly appreciate any help that anyone could give me.

Other errors that I encountered are:
  • This script will only inject into 32-bit processes
  • Only certain processes can be injected into. For example: when I select assault cube the script will work fine but if I choose heroes 3 the script will raise an error immediately and can't attempt to inject
I have not researched much into these extra errors as I am just trying to get a basic dll injector to work. These are just bonus errors where it would be nice to know a solution to them.
 

mambda

headass
Escobar Tier VIP
Trump Tier Donator
Jun 25, 2014
2,294
37,938
269
Check the memory out of the process you want to inject to to ensure that things are properly written. Call and print the get last error after each winapi call
 

NTvalk

Hacker
Meme Tier VIP
Jul 6, 2013
499
3,108
8
maybe try this code, i found it somewhere and cant test it because im on linux:
C++:
#!/usr/bin/python
# Win32 DLL injector from Grey Hat Python
# Minor formatting cleanups done...
import sys
from ctypes import *

print "DLL Injector implementation in Python"
print "Taken from Grey Hat Python"

if (len(sys.argv) != 3):
    print "Usage: %s <PID> <Path To DLL>" %(sys.argv[0])
    print "Eg: %s 1111 C:\\test\messagebox.dll" %(sys.argv[0])
    sys.exit(0)

PAGE_READWRITE = 0x04
PROCESS_ALL_ACCESS = ( 0x00F0000 | 0x00100000 | 0xFFF )
VIRTUAL_MEM = ( 0x1000 | 0x2000 )

kernel32 = windll.kernel32
pid = sys.argv[1]
dll_path = sys.argv[2]

dll_len = len(dll_path)

# Get handle to process being injected...
h_process = kernel32.OpenProcess( PROCESS_ALL_ACCESS, False, int(pid) )

if not h_process:
    print "[!] Couldn't get handle to PID: %s" %(pid)
    print "[!] Are you sure %s is a valid PID?" %(pid)
    sys.exit(0)

# Allocate space for DLL path
arg_address = kernel32.VirtualAllocEx(h_process, 0, dll_len, VIRTUAL_MEM, PAGE_READWRITE)

# Write DLL path to allocated space
written = c_int(0)
kernel32.WriteProcessMemory(h_process, arg_address, dll_path, dll_len, byref(written))

# Resolve LoadLibraryA Address
h_kernel32 = kernel32.GetModuleHandleA("kernel32.dll")
h_loadlib = kernel32.GetProcAddress(h_kernel32, "LoadLibraryA")

# Now we createRemoteThread with entrypoiny set to LoadLibraryA and pointer to DLL path as param
thread_id = c_ulong(0)

if not kernel32.CreateRemoteThread(h_process, None, 0, h_loadlib, arg_address, 0, byref(thread_id)):
    print "[!] Failed to inject DLL, exit..."
    sys.exit(0)

print "[+] Remote Thread with ID 0x%08x created." %(thread_id.value)
 
Last edited:

rubberduccky

Newbie
Full Member
Jan 25, 2014
7
144
0
Thank you for the reply! I tried using this program (after converting it from older python to python 3) and I get the same problem.
 

rubberduccky

Newbie
Full Member
Jan 25, 2014
7
144
0
Hello and thank you for the reply. I tried calling GetLastError after each winapi call as you mentioned and I found this: "LoadLibAddy GetLastError: 126". I tried replacing GetModuleHandleW with GetModuleHandleA and I get the following: "LoadLibAddy GetLastError: 127". From what I can tell Python can't find kernel32.dll but in IDLE when I use windll.LoadLibrary("kernel32.dll") everything seems to work fine. I am currently using google to try and solve this problem but I will post here just in case someone knows more about this.
 

rubberduccky

Newbie
Full Member
Jan 25, 2014
7
144
0
I also tried the following: windll.kernel32.GetProcAddress(windll.LoadLibrary("kernel32.dll"), "LoadLibraryA").
The error that I get is ctypes.ArgumentError: argument 1: <class 'TypeError'>: Don't know how to convert parameter 1. I am going to bed and will continue to debug this tomorrow.
 

rubberduccky

Newbie
Full Member
Jan 25, 2014
7
144
0
The problem I am now facing is when I call windll.GetModuleHandleW("C:\\Windows\\System32\\kernel32.dll") I get the following error: OSError: [WinError 126] The specified module could not be found. However if I use windll.LoadLibrary("C:\\Windows\\System32\\kernel32.dll") kernel32.dll is found but I get the following error: ctypes.ArgumentError: argument 1: <class 'TypeError'>: Don't know how to convert parameter 1.
 

mambda

headass
Escobar Tier VIP
Trump Tier Donator
Jun 25, 2014
2,294
37,938
269
Well, then use LoadLibrary, the TypeError is simply it not knowing what type to make the return value i guess, i've never used any python winapi wrappers so you're just going to have to google that one mate, can you explicitly tell it that the return value is a long/hmodule/void*?
 

rubberduccky

Newbie
Full Member
Jan 25, 2014
7
144
0
I have encountered a new problem with my dll injector. Whenever I try to inject my 32-bit dll into a 32-bit process the process will crash immediately and I will get error 193. However, if I inject my 64-bit version of the dll into the 32-bit process the dll will execute its function but will crash the process immediately after doing so. My dll opens a cmd.exe process. It won't open one when the 32-bit dll is injected but will when my 64-bit dll is injected. I tried to debug this error by attaching Ollydbg.exe to the process. What happens now though is that whenever I inject the 64-bit dll into the process with Ollydbg attached to it, it simply works. The cmd process will run and the process being injected into won't crash. Does anyone know how I can successfully inject the dll without having to attach a debugger to the process? Here is my improved code:

C++:
from ctypes import *
from ctypes import wintypes

def dllinjector(processID, DLL_PATH):
    KERNEL32 = WinDLL('kernel32.dll', use_last_error=True)
    PROCESS_CREATE_THREAD = 0x0002
    PROCESS_QUERY_INFORMATION = 0x0400
    PROCESS_VM_OPERATION = 0x0008
    PROCESS_VM_WRITE = 0x0020
    PROCESS_VM_READ = 0x0010
    MEM_RESERVE = 0x00002000
    MEM_COMMIT = 0x00001000
    PAGE_READWRITE = 0x04
    SIZE_T = c_size_t
    LPSIZE_T = POINTER(SIZE_T)
    WCHAR_SIZE = sizeof(wintypes.WCHAR)
    SIZE = (len(DLL_PATH) + 1) * WCHAR_SIZE

    openHandle = KERNEL32.OpenProcess(PROCESS_CREATE_THREAD|
                                         PROCESS_QUERY_INFORMATION|
                                         PROCESS_VM_OPERATION|
                                         PROCESS_VM_WRITE|
                                         PROCESS_VM_READ, False, processID)
    if not openHandle:
        print("OpenProcess failed.")
        print("GetLastError: ", KERNEL32.GetLastError())
        return False
    print("Successfully opened process.")

    # Allocate space in the process for the dll
    ADDRESS = KERNEL32.VirtualAllocEx(openHandle, None, SIZE, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE)
    if not ADDRESS:
        print("VirtualAllocEx failed.")
        print("GetLastError: ", KERNEL32.GetLastError())
        return False

    # Write the string name of the dll in the memory allocated
    if not KERNEL32.WriteProcessMemory(openHandle, ADDRESS, DLL_PATH, SIZE, None):
        print("WriteProcessMemory failed.")
        return False

    #Load the dll
    print("LoadLibraryW: ", KERNEL32.LoadLibraryW(DLL_PATH))
    print(KERNEL32.GetLastError())
    if not KERNEL32.CreateRemoteThread(openHandle, None, 0, KERNEL32.LoadLibraryW(DLL_PATH), ADDRESS, 0, None):
        print(KERNEL32.GetLastError())
        print("CreateRemoteThread failed.")
        return False
    
    KERNEL32.CloseHandle(openHandle)

    return True

def main():
    processID = 72756
    DLL_PATH = "mydll64.dll"
    
    dllinjector(processID, DLL_PATH)
    
    print("program completed.")

main()
 
Attention! Before you post:

Read the How to Ask Questions Guide
99% of questions are answered in the Beginner's Guide, do it before asking a question.

No Hack Requests. Post in the correct section.  Search the forum first. Read the rules.

How to make a good post:

  • Fill out the form correctly
  • Tell us the game name & coding language
  • Post everything we need to know to help you
  • Ask specific questions, be descriptive
  • Post errors, line numbers & screenshots
  • Post code snippets using code tags
  • If it's a large project, zip it up and attach it

If you do not comply, your post may be deleted.  We want to help, please make a good post and we will do our best to help you.

Community Mods