-1

Today I got an LoadLibraryA injector that works perfectly but it doesn't let delete the dll after injection (loadlibrary things) and I tried doing FreeLibraryAndExitThread but it didnt work.

The code I tried: FreeLibraryAndExitThread(hThread, 0);

The injection code:

            const char* procName = "notepad.exe";
            DWORD procID = 0;

            while (!procID)
            {
                procID = GetProcID(procName);
                Sleep(30);
            }

            HANDLE hProc = OpenProcess(PROCESS_ALL_ACCESS, 0, procID);

            if (hProc && hProc != INVALID_HANDLE_VALUE)
            {
                void* loc = VirtualAllocEx(hProc, 0, MAX_PATH, MEM_COMMIT | MEM_RESERVE, PAGE_READWRITE);

                if (loc)
                {
                    WriteProcessMemory(hProc, loc, dllPath, strlen(dllPath) + 1, 0);
                }

                HANDLE hThread = CreateRemoteThread(hProc, 0, 0, (LPTHREAD_START_ROUTINE)LoadLibraryA, loc, 0, 0);

                if (hThread)
                {
                    CloseHandle(hThread);
                }

                if (hProc)
                {
                    CloseHandle(hProc);
                }
                
                FreeLibraryAndExitThread(hThread, 0);

                return 0;
            }

btw sorry for stupid questions, I'm new to cpp and didn't find an solution in internet that does work.

Ted Lyngmo
  • 93,841
  • 5
  • 60
  • 108
Daniel TG
  • 29
  • 1
  • 3

2 Answers2

1

You are not unloading the DLL correctly.

You are misusing FreeLibraryAndExitThread(). It expects an HMODULE of a loaded DLL to unload, but you are giving it the HANDLE of the remote thread instead - which you have already closed via CloseHandle() beforehand. And in any case, FreeLibraryAndExitThread() terminates the calling thread, which is not what you want to do in this situation.

You need to wait for LoadLibrary() to fully complete. After creating the remote thread, wait on the thread HANDLE using WaitForSingleObject() or related function.

After that, you can then inject a call to FreeLibrary() into the context of the remote process, passing it the HMODULE that LoadLibrary() returned - which you currently do not have. When using LoadLibrary() as a thread procedure, the thread's exit code will contain the returned HMODULE. If your target is a 32-bit process, you can use GetExitCodeThread() to retrieve that HMODULE. But things get more complicated if your target is a 64-bit process, since the thread's exit code will truncate the HMODULE value.

See CreateRemoteThread on LoadLibrary and get the HMODULE back.

Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770
0

I am not really sure what do you want but you can't do it because you closed the handle:

if (hThread)
{
     CloseHandle(hThread);
} 
...

FreeLibraryAndExitThread(hThread, 0);