Process Injection --Part 2--

1. Finding the Target Process ID

The function FindProcessID(const char *processName) is used to retrieve the Process ID (PID) of a running process by its name.

How it works:

  • It takes a snapshot of all running processes using CreateToolhelp32Snapshot().

  • It loops through the process list using Process32First() and Process32Next().

  • If it finds a process with a matching name (strcmp(pe32.szExeFile, processName) == 0), it returns the Process ID.

// Function to find process ID by name
DWORD FindProcessID(const char *processName) {
    PROCESSENTRY32 pe32;
    pe32.dwSize = sizeof(PROCESSENTRY32);

    HANDLE snapshot = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
    if (snapshot == INVALID_HANDLE_VALUE) {
        printf("Failed to take snapshot of processes. Error: %lu\n", GetLastError());
        return 0;
    }

    if (!Process32First(snapshot, &pe32)) {
        printf("Failed to get first process. Error: %lu\n", GetLastError());
        CloseHandle(snapshot);
        return 0;
    }

    do {
        if (strcmp(pe32.szExeFile, processName) == 0) {
            CloseHandle(snapshot);
            return pe32.th32ProcessID;
        }
    } while (Process32Next(snapshot, &pe32));

    CloseHandle(snapshot);
    return 0;
}

2. Defining the Shellcode

The unsigned char shellcode[] contains raw machine code (in hexadecimal format). This shellcode is executed inside the target process after being injected.

3. Allocating Memory in the Target Process

  • VirtualAllocEx() is called to allocate memory inside the target process.

  • The allocated memory has PAGE_READWRITE permissions for now.

  • If memory allocation fails, the program cleans up and exits.


3. Writing the Shellcode to the Allocated Memory

  • WriteProcessMemory() writes the shellcode to the allocated memory.

  • If writing fails, it frees the allocated memory and exits.


4. Changing Memory Permissions

  • VirtualProtectEx() changes the memory protection from PAGE_READWRITE to PAGE_EXECUTE_READ.

  • This allows the shellcode to be executed.


5. Creating a Remote Thread

  • CreateRemoteThread() is used to create a new thread inside the target process.

  • The entry point for this thread is the allocated memory containing the shellcode.

  • If the function fails, the program cleans up and exits.


8. Waiting for the Shellcode Execution

  • WaitForSingleObject(hThread, INFINITE) waits for the shellcode execution to complete.

  • VirtualFreeEx() releases the allocated memory.

  • CloseHandle(hThread) and CloseHandle(hProcess) close the handles to prevent resource leaks.

  • A final message [+] We Are Do it <3 Happy Hack is printed.


Last updated