Embed /Load a DLL as a resource in VC++ 2008? - c++

As the topic's description/title puts it, is this a possibility because I've been searching around on Google and other sources and without any luck I've come here to ask the question...
Is it at all possible to Embed a DLL as a resource into my final Executable and then call upon it/ as-if it were an external file in the current directory and/or System Directory?
I've tried a number of things without luck, a number of said solutions are not working out so well, I've seemingly embedded the DLL with my .rc file, however am struck with the problem of trying to call upon it, perhaps it's needing to be saved into a physical file on the disk, I'm not sure.
[EDIT]
Below is currently the code I've implemented, still without any success; I am still confronted with The program can't start because soandso.dll is missing from your computer.
Code below, -/
int WINAPI WinMain ( HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nShowCmd )
{
HRSRC hRes = FindResource( hInstance, MAKEINTRESOURCE("#101"), "IDR_DLLRESOURCE_101" );
HGLOBAL hData = LoadResource( hInstance, hRes );
LPVOID lpFile = LockResource( hData );
DWORD dwSize = SizeofResource( hInstance, hRes );
HANDLE hFile = CreateFile("soandso.dll", GENERIC_READ | GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, 0);
HANDLE hFilemap = CreateFileMapping(hFile, 0, PAGE_READWRITE, 0, dwSize, 0);
LPVOID lpBaseAddr = MapViewOfFile(hFilemap, FILE_MAP_WRITE, 0, 0, 0);
CopyMemory(lpBaseAddr, lpFile, dwSize);
UnmapViewOfFile(lpBaseAddr);
CloseHandle(hFilemap);
CloseHandle(hFile);
return 0;
}
Thank you in advance for any and all help provided.

It is fundamentally incompatible with the way Windows treats executable code in a PE32 file format. It must be present in a file, Windows creates a memory-mapped file to map it into memory. Trying anything like loading it into memory from a resource requires you taking over all of the duties of the Windows loader. Which includes relocating the code if it cannot be located at the expected base address, finding and loading all of the dependent DLLs and calling their DllMain() methods.
Particularly the DLL_THREAD_ATTACH and DETACH notifications are next to impossible to implement yourself since you can't control every thread that gets created. Very hard to do right and there's not a single winapi that will help you doing this. It is not worth it. And most certainly not competitive with just linking the DLL's code into your EXE image.

The only supported way to load a DLL is from a file. So, when you need to load this DLL, extract the resource, save it to a file (e.g. in the temporary directory), and call LoadLibrary and GetProcAddress to link to the library.

Related

Manual DLL injection

I am trying to learn some manual dll injection, but cant seem to get the execution of the dlls code to work. I am new to Windows C++ so any tips on improving my code is appreciated. I have also only posted the relevant code.
Injector program:
hProcess = OpenProcess(PROCESS_CREATE_THREAD | PROCESS_QUERY_INFORMATION | PROCESS_VM_OPERATION | PROCESS_VM_READ | PROCESS_VM_WRITE, FALSE, getPID(TARGET_NAME));
DWORD gotDLL = GetFullPathName(DLL_NAME, MAX_PATH, dllPath, NULL);
hFile = CreateFile(dllPath, GENERIC_READ, NULL, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
dllFileSize = GetFileSize(hFile, NULL);
memAddrForDLL = VirtualAllocEx(hProcess, NULL, dllFileSize, MEM_RESERVE | MEM_COMMIT, PAGE_EXECUTE_READWRITE);
loadedDLL = HeapAlloc(GetProcessHeap(), NULL, dllFileSize);
// Load dll into allocated memory in current process
ReadFile(hFile, loadedDLL, dllFileSize, &bytesRead, NULL))
// Find offset of dll entry point
IMAGE_NT_HEADERS* pOldNtHeader = reinterpret_cast<IMAGE_NT_HEADERS*>(reinterpret_cast<BYTE*>(loadedDLL) + reinterpret_cast<IMAGE_DOS_HEADER*>(loadedDLL)->e_lfanew);
IMAGE_OPTIONAL_HEADER* pOldOptHeader = &pOldNtHeader->OptionalHeader;
entryPointOffset = pOldOptHeader->AddressOfEntryPoint;
// Load dll into allocated memory in target process
WriteProcessMemory(hProcess, memAddrForDLL, loadedDLL, bytesRead, NULL)
LPTHREAD_START_ROUTINE entryPoint = (LPTHREAD_START_ROUTINE)((unsigned __int64)memAddrForDLL + entryPointOffset);
CreateRemoteThread(hProcess, NULL, NULL, (LPTHREAD_START_ROUTINE)LoadLibrary, entryPoint, NULL, NULL)
DLL:
DWORD WINAPI OnDllAttach(LPVOID base){
typedef void func(void);
func* f = (func*)0x00007FF605EC5835;
f();
FreeLibraryAndExitThread(static_cast<HMODULE>(base),1);
}
BOOL WINAPI OnDllDetach(){
return TRUE;
}
BOOL WINAPI DllMain(_In_ HINSTANCE hinstDll,
_In_ DWORD fdwReason,
_In_opt_ LPVOID lpvReserved){
typedef void func(void);
func* f = (func*)0x00007FF605EC5835;
f();
switch(fdwReason) {
case DLL_PROCESS_ATTACH:
DisableThreadLibraryCalls(hinstDll);
CreateThread(nullptr, 0, OnDllAttach, hinstDll, 0, nullptr);
return TRUE;
case DLL_PROCESS_DETACH:
if(lpvReserved == nullptr)
return OnDllDetach();
return TRUE;
default:
return TRUE;
}
}
Target program contains this function:
void printer(){
cout << "test" << endl;
}
My injector produces the following output
1. Attempting to attatch to process target.exe
--- Got target.exe PID: 14640
--- Got target.exe Handle: 0x0000000000000084
2. Attempting to allocate memory
--- Found dll: D:\projects\injector\hack.dll
--- Got hack.dll Handle: 0x0000000000000088
--- Allocated memory in target.exe at 0x0000017BEB690000
3. Attempting to copy dll to target.exe
--- Allocated memory at 0x00000226A060FFE0
--- Loaded hack.dll in current process at 0x00000226A060FFE0
--- hack.dll is a valid DLL
--- Loaded hack.dll into target.exe at 0x0000017BEB690000
4. Attempting to execute dll
--- Offset from start of file to entrypoint: 0x3cf6
--- Began execution of hack.dll in target.exe at 0x0000017BEB693CF6
Using Ghidra I can confirm this is the correct offset for the dll entrypoint. But when running my injector nothing happens in the target process, I've also tried using cout to print a message from the dll but I get nothing(I dont think it would even work because nothing has been relocated)
I was using
CreateRemoteThread(hProcess, NULL, NULL, entryPoint, memAddrForDLL, NULL, NULL)
before as the 4th parameter is called lpStartAddress and I thought this should want the entry point but it was causing the target process to crash and every example I saw used the way I currently have it in my code.
In my dll I am calling the function in the target process by the address.
EDIT: I am testing this on my own console application.
The most basic form of DLL injection is:
Allocating Memory in target process using VirtualAllocEx()
Writing the path of the DLL to that memory location with WriteProcessMemory
Calling LoadLibrary() via CreateRemoteThread() in the target process
Passing the memory location where the DLL path is written to that call
You already have this but, your goal is to manually map the DLL and avoid using LoadLibrary(). The code you have provided is not going to work out, there are about 5 more steps. You need to emulate everything that LoadLibrary() normally does:
Load raw binary data
Map sections into target process
Inject loader shellcode
Do relocations
Fix imports
Execute TLS callbacks
Call DllMain
Cleanup
The benefits of manually mapping are that you will be hidden from ToolHelp32Snapshot(), walking the module linked list in the PEB and NtQueryVirtualMemory.
If you want to do it right, with decent error checking, it's about 350 lines of code and it gets complicated. It's all done by parsing the PE header.
Get the process id of the target
Read the DLL file
Allocate memory in target process the same size as ImageBase from the PE header
Loop through PE sections after parsing the PE header
Write the section to memory in the correct relative address
Write shellcode into target process
Call CreateRemoteThread and set your shellcode to execute
Your shellcode fixes imports and does relocations
Your Shellcode Execute TLS callbacks
The above 2 steps are done parsing the DataDirectory in the optional header
Call DllMain(), with DLL_PROCESS_ATTACH argument
Now your DLL is loaded and the DLL_PROCESS_ATTACH switch case is executing. Obivously it's more complicated than that, but that's the idea.
I wouldn't know anything about this without my friend Broihon teaching me it, so I want credit this answer to him. Good luck
A .DLL loaded in memory is not the same thing as a .DLL file on disk. The section layout is not the same and you need to deal with relocations, the import table and the PEB loaded module list. You basically have to re-implement NTDLL!Ldr*.
Calling CreateRemoteThread on LoadLibrary is a different technique and when you do this the thread parameter needs to point to the .DLLs path in the remote process, not the entrypoint.

C++ and Windows - how to overwrite exe file of the running program?

I tried to make self-updatable program, but I can't understand, how to over-write exe file of the running program (of the current process). When Exe file is running, it's locked by process and can't be writable.
How to update program - I need to update file, close current process and re-run updated file...
Maybe my question is silly, but I haven't this problem, until I used Linux...
Cheers! ❤
I solved this question by packing needed file into the another one wrapper via Resources in MS VS.
Here is code to extract resource into the file:
#include "stdafx.h"
#include "resource.h"
#include "windows.h"
int main()
{
HRSRC hrsrc = FindResource(NULL, MAKEINTRESOURCE(IDR_BINARYTYPE1), _T("BINARYTYPE"));
//FindResource(NULL, MAKEINTRESOURCE(IDR_BINARYTYPE1), RT_BITMAP);
HGLOBAL hLoaded = LoadResource(NULL, hrsrc);
LPVOID lpLock = LockResource(hLoaded);
DWORD dwSize = SizeofResource(NULL, hrsrc);
HANDLE hFile = CreateFile(TEXT("c:/temp/zxcv.exe"), GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
DWORD dwByteWritten;
WriteFile(hFile, lpLock, dwSize, &dwByteWritten, NULL);
CloseHandle(hFile);
FreeResource(hLoaded);
return 0;
}
I am not realized it by 100%, but I have plan to pack my exe into the wrapper, that will unpack my exe into the %Temp% directory and will start unpacked exe file. Unpacked file will be deleted with DELETE_ON_CLOSE.
It's just plan, but I see possible solution :).
Thanks to all!

C++ WinAPI - How to get the installation path of an executable from its name

Is there a way to get the installation path of an executable ( not self ) by using its name.
Say i want to find the path where a running process (eg : "notepad.exe") is installed on the hard drive from process list snapshot.
Best,
The process list gives you the full path and filename of every running process. Simply enumerate the list looking at just the filename portion of each path, and when you find the filename you are interested in, simply truncate the filename off of the path and use the remaining folder path as needed.
Either the process list snapshot contains that information, or not.
It is impossible to reconstruct that information after the fact. Even if you also had a snapshot of the exact disk state matching the process list snapshot, there can be more than one file on disk with the same filename.
Get the executable path when listing processes, and store it in the snapshot. Once the process exits, it is too late.
You can probably use the SearchPath() function.
these functions should help
HMODULE WINAPI GetModuleHandle(
_In_opt_ LPCTSTR lpModuleName
);
then
DWORD WINAPI GetModuleFileName(
_In_opt_ HMODULE hModule,
_Out_ LPTSTR lpFilename,
_In_ DWORD nSize
);

ShellExecuteW not working well on Windows 8.1?

I call standard ShellExecuteW call on Windows8.1 to open PPS (powerpoint slide) file.
This works just fine on Windows 7. On Windows 8.1. it reports "There is no program associated to open the file". Of course, the file association is set and if file is saved and run from Explorer (double clicked) it opens just fine. I also tried to change association and to associate another program and then associate back to PPS viewer, no improvement. It just doesn't work for W8.1 but the same call works on earlier Windows.
Can anyone give me a clue what might be wrong here?
The code used to open file is very simple and I see no errors with it:
HINSTANCE hinst = ShellExecuteW(NULL, L"open", L"C:\\path\\to\\file.pps", NULL, NULL, SW_SHOWNORMAL);
// Check if result is error
if ((int)hinst <= 32)
{
wchar_t buf[512] = { 0 };
FormatMessageW(FORMAT_MESSAGE_FROM_SYSTEM, NULL, GetLastError(), MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), buf, 512, NULL);
MSGBOX(buf);
}
I use free PPS viewer as found here:
http://www.microsoft.com/en-us/download/details.aspx?id=13
I found something similar which points to that this could be a bug in Win8.1. Can anyone confirm this? Or reveal a workaround?
I found the solution myself.
The problem on W8.1 was that the verb open was not registered to the application so it used different default verb. So if the ShellExecute call is replaced with:
HINSTANCE hinst = ShellExecuteW(NULL, NULL, L"C:\\path\\to\\file.pps", NULL, NULL, SW_SHOWNORMAL);
Then the system looks for a default verb which may or may not be open (usually is), so by not using this verb explicitly it leaves this decision to the system.

win32 Api programming

I want to get a running application text e.g if i am running notepad then i want to get the text written inside it .For this first i have to get the handle of notepad but i don't know how to get the notepad handle so please tell me .Then through which functions i can get its inside text ? which header files to include ? what are necessary declarations?
Please help me i am new to windows API programming.i have gone through basic tutorials of windows programming but that doesn't help me a lot.
Use FindWindowEx. Though you must have been able to find this yourself, if you were looking/googling for a way to "find notepad handle in C++" ;)
You can even find complete examples on "Sending text to notepad in C++"
To expand on GolezTrol's answer, you could do this:
#include <windows.h>
#include <tchar.h>
int CALLBACK _tWinMain( HINSTANCE hInstance, HINSTANCE hPrevInstance, LPTSTR lpCmdLine, int nCmdShow ) {
HWND hwnd = FindWindow( _T("Notepad"), NULL);
hwnd = FindWindowEx( hwnd, NULL, _T("edit"), NULL );
TCHAR lpText[256];
SendMessage( hwnd, WM_GETTEXT, _countof(lpText), (LPARAM)lpText);
MessageBox(0, lpText, lpText, 0);
return ERROR_SUCCESS;
}
In reality, you would probably use a more reliable method of window identification (eg. enumerating all windows and verifying what process it belongs to)