View Full Version : Running Code in a Remote Process

02-18-2011, 07:12 PM
I'm going to attempt to describe a simple but effective method for running code in an external process. This isn't as detectable as injecting a .dll, although not quite as easy or fun to work with. The best use for this method is making small deployable hacks.

I am assuming you have some basic assembly and low level skills. This is all psuedo code, and not intended to be compiled directly in anything. If you need help, add your comments to this thread.

First, you need to open a handle to the target process.

hwnd = FindWindow("Notepad", NULL) ;
GetWindowThreadProcessId(hwnd, pid);
handle = OpenProcess(PROCESS_READ_WRITE_QUERY, False, pid);

From here, we are going to need a code cave/compartment. Basically some memory space in the target app that isn't used. I usually allocate it myself like so.

CAVE_MAX_SIZE = 1024; //1kb
RemoteMem = VirtualAllocEx(handle, 0, CAVE_MAX_SIZE, MEM_COMMIT, PAGE_READWRITE);

We have our open handle and our own 1kb chunk of memory in the target. Now we need a way to call our injected code. The method I use most; create a suspended remote thread in our target process. To call my code, I simply resume the remote thread.

First, create our suspended thread.

thread = CreateRemoteThread(handle, 0, 0, RemoteMem, 0, CREATE_SUSPENDED, threadId);

This gives us our own suspended thread. Once this thread is resumed, it enters the code located at RemoteMem.

We can now use WriteProcessMemory to write our code. Then resume our thread to execute the code.

WriteProcessMemory(handle, RemoteMem, BYTES, BYTES_LENGTH, byteswritten);

Using this method, we are now executing code in a remote process in a relatively painless and stable way. Couple things to note; if you want to keep your thread alive you must suspend it after your code is executed. If you don't suspend it, it will attempt to execute beyond your code and crash. This is really easy to accomplish by appending a call to suspendthread in kernel32.dll to the code you are writing to the remote process. Also, if you want to kill the thread, simply execute 0xC3 [ret]. And finally, don't forget to clean up and close those handles when done!

02-25-2013, 06:24 AM
is this really work?

08-31-2013, 04:08 AM
Thanks for this guide!