Loading DLL to user defined address

556 Views Asked by At

How to load the DLL into user define memory address or is it possible to change the DLL address after loading the DLL using loadlibrary() function.

I have tried using VirtualAllocEx() to allocate the memory address and load DLL to the remote process. DLL is loading into the remote process but the address is not same.

//virtually allocating the memory address
DWORD *arg = (PDWORD)VirtualAllocEx(process, /*(LPVOID)0x81200000*/0, strlen(buffer), MEM_RESERVE|MEM_COMMIT, PAGE_READWRITE);
if(arg == NULL) {
    return 1;
}

//Write the argument to LoadLibraryA to the process's newly allocated memory region.
int n = WriteProcessMemory(process, arg, buffer, strlen(buffer), NULL);
if(n == 0) {
    return 1;
}

//Inject our DLL into the process's address space.
HANDLE threadID = CreateRemoteThread(process, NULL, 0, (LPTHREAD_START_ROUTINE)address, arg, NULL, NULL);

I have also tried using rebaseimage() function but memory address changing after loading the DLL.

//rebaseimage function to change the base address of the DLL
ret = ReBaseImage("WinMemoryDLL.dll","",TRUE,TRUE,FALSE,0,&OldImage,&OldImageBase,&NewImageSize,&NewImageBase,0);

hinstLib = LoadLibrary(TEXT("WinMemoryDLL.dll"));
1

There are 1 best solutions below

0
On

There is no reason that I can think of to require your DLL to load into a user defined address. According to standard Windows programming practices, you should never rely on a DLL being loaded into a specific address.

If you need to access something from the DLL at runtime, use relative offsets. You can use CreateToolhelp32Snapshot() at runtime to get the address of the module, and then add your relative offset to get the dynamic address of whatever you need. You can also export a function and use GetProcAddress() to get the address of the function. Both these methods work with ASLR enabled and is the proper way to do it.