0

I used this code which I found somewhere on internet:

    void InjectDLL()
{
    char *dllName = "C:\\Project2.dll";

    HANDLE proc = OpenProcess(PROCESS_VM_READ | PROCESS_VM_WRITE | PROCESS_SET_INFORMATION | PROCESS_QUERY_INFORMATION | PROCESS_VM_OPERATION | PROCESS_CREATE_THREAD, FALSE, PID);

    LPVOID LoadLibAddr = (LPVOID)GetProcAddress(GetModuleHandleA("kernel32.dll"), "LoadLibraryA");
    LPVOID dereercomp = VirtualAllocEx(proc, NULL, strlen(dllName) + 1, MEM_COMMIT | MEM_RESERVE, PAGE_READWRITE);
    WriteProcessMemory(proc, dereercomp, dllName, strlen(dllName) + 1, NULL);
    HANDLE asdc = CreateRemoteThread(proc, NULL, NULL, (LPTHREAD_START_ROUTINE)LoadLibAddr, dereercomp, 0, NULL);

    WaitForSingleObject(asdc, INFINITE);
    VirtualFreeEx(proc, dereercomp, strlen(dllName) + 1, MEM_RELEASE);
    CloseHandle(asdc);
    CloseHandle(proc);
}

Everything work perfectly fine, but after I finished things I had to do I'd like to remove injected dll, either from program which injects dll or dll itself.

Gonmator
  • 760
  • 6
  • 15
user3213103
  • 133
  • 3
  • 14
  • First Solution: the DLL creates a thread, doesn't run other code, wait for some signal and then use `FreeLibraryAndExitThread`. Second Solution: inject with `SetWindowsHookEx` ; `UnhookWindowsHookEx` will unload the DLL (be sure to be prepared for that, that's mean: no living windows, no private threads) – manuell Jun 26 '14 at 12:55
  • Thank You very much for your answer! I have succeded to do it via SetWindowsHookEx, and unhook so DLL detaches... I have one more question. Is it possible to unlock DLL file on HDD after its been loaded by hooked program. I tried using FreeLibrary, but that seems to detach DLL also, while I'd like to have it loaded in process, but not on HDD. – user3213103 Jun 27 '14 at 14:45
  • When a DLL is loaded in a process, you may be able to rename it, but you can't delete it or update it (from another process). Loading from memory is tricky. You won't find help here if you don't explain clearly what's your goal, that is: "not writing malware". – manuell Jun 27 '14 at 14:52

0 Answers0