kubo / injector

Library for injecting a shared library into a Linux or Windows process
GNU General Public License v2.0
504 stars 97 forks source link

How can I uninject the injected lib #1

Closed huhuang03 closed 4 years ago

huhuang03 commented 5 years ago

Thanks for your great job! It work prefect.

However I'm new to windows api, and I now want to uninject the injected success lib. Can I do this, and how, thanks.

kubo commented 5 years ago

Here is a sample. It may not work because I have not tested it. It doesn't work when the bitness (64-bit or 32-bit) of the injector process is different from that of the target process.

    DWORD pid = ...process id of the target process...;

    // find the base address of the library in the target process.
    HANDLE hSnapshot = CreateToolhelp32Snapshot(TH32CS_SNAPMODULE, pid);
    if (hSnapshot == INVALID_HANDLE_VALUE) {
        ...error handling...
    }
    MODULEENTRY32 me;
    me.dwSize = sizeof(me);
    BOOL ok;
    for (ok = Module32FirstW(hSnapshot, &me); ok; ok = Module32NextW(hSnapshot, &me)) {
        if (...check `me.szModule` or `me.szExePath`...) {
            break;
        }
    }
    if (!ok) {
        ...error handling...
    }
    CloseHandle(hSnapshot);
    // `me.modBaseAddr` is the base address of the library to be uninjected.

    // Call FreeLibarry in the target process.
    HANDLE hProcess = OpenProcess(PROCESS_CREATE_THREAD, FALSE, pid);
    if (hProcess == NULL) {
        ...error handling...
    }
    HMODULE kernel32 = GetModuleHandleA("kernel32");
    LPTHREAD_START_ROUTINE func_addr = (LPTHREAD_START_ROUTINE)GetProcAddress(kernel32, "FreeLibrary");
    HANDLE hThread = CreateRemoteThead(hProcess, NULL, 0,  func_addr, me.modBaseAddr, 0, NULL);
    if (hThread == NULL) {
        ...error handling...
    }
    WaitForSingleObject(hThread, INFINITE);
    DWORD exit_code;
    GetExitCodeThread(hThread, &exit_code);
    if (exit_code == 0) {
        // FreeLibrary in the target process failed.
        ...error handling...
    }
    CloseHandle(hThread);
    CloseHandle(hProcess);
huhuang03 commented 4 years ago

Sorry for so late replay, After test, it works.

But in one situation, it does not work: the injected dll start new thread and the thread is running. In this situation, seem like did nothing.