So recently I made my own dll injector to be able to debug my other app by injecting a debug dll in it; Using c++/cli for the interface and c++ for the code.
I tested the same code I used on this project on a C++ console app project and it worked without any problems.
The injection occurs inside the Init.cpp file, which essentially gets the provided dll path under the form of C:\\user\\documents\\debug.dll and checks if it exists. After that it gets the process id by passing the name, in this case myotherapp.exe, as a parameter. If successful it then get's the Handle to the process and store's it in g.h_process, it continues by allocating readable/writable memory in the process and then writing to this memory the path of the dll and finally use's LoadLibraryA to load the dll inside the process.
Init.cpp:
void Injector::Init(void)
{
Inject::Checks((char*)g.dll_path, g.procName);//checking for dll validity
}
bool Injector::Inject::Checks(char* dll_path, PCSTR procName)
{
if (!Utils::file_exists(dll_path))
return Utils::error("File does not exist.");
Utils::successInput("Prepared DLL for injection");
Utils::getProcId(procName, g.proc_id);
if (!g.proc_id) {
return Utils::error("Could not find specified process.");
}
g.h_process = OpenProcess(PROCESS_ALL_ACCESS, NULL, g.proc_id);
if (!g.h_process) {
return Utils::error("Failed to open a handle to process");
}
g.allocatedMemory = VirtualAllocEx(g.h_process, nullptr, MAX_PATH, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE);//mem_reserver reserve memory then commit memory to be able to write to that memory
Allocate(g.allocatedMemory, dll_path);
Llib();
Release(dll_path, g.allocatedMemory);
return 0;
}
bool Injector::Inject::Allocate(void* allocatedMemory, char* dll_path)
{
if (!allocatedMemory)
return Utils::error("Failed to allocate memory");
if (!WriteProcessMemory(g.h_process, g.allocatedMemory, g.dll_path, MAX_PATH, nullptr))
return Utils::error("Failed to write process");
return true;
}
bool Injector::Inject::Llib() {
HANDLE h_thread = CreateRemoteThread(g.h_process, nullptr, NULL, LPTHREAD_START_ROUTINE(LoadLibraryA), g.allocatedMemory, NULL, nullptr);
if (!h_thread)
return Utils::error("Failed to create remote thread");
return true;
}
bool Injector::Inject::Release(PCSTR dll_path, void* allocatedMemory)
{
CloseHandle(g.h_process);
VirtualFreeEx(g.h_process, allocatedMemory, NULL, MEM_RELEASE);
return true;
}
The g.debug is just a flag which tells us if the console is enabled or not. found in the globals.hpp which just contains global variables.
You can also check the Utils namespace here.
The error:
The problem I'm experiencing here is whenever I inject my DLL into the process, my injector works fine with no errors but when I attach vs to the process I want to inject to I get an Access Violation error with the process exiting with an error code.
I don't understand, I can't see where I am accessing invalid memory.
Thanks in advance.
Related
I'm trying to create a mod loader for an 18 year old game to help me get better at c++. Right now I'm just trying to inject a dll into the same process of the mod loader. The sample dll just prints some text to the command window but doesn't. I think that the code that I have loading the entry point of the dll is not working because everything works up until I call the entry point function of my sample dll within my ModLoader.exe, and Visual Studio just throws an Access Violation. I poked through the memory viewer in debug mode within visual studio to try and see where my ModLoader program thinks the dll entry point is located within the dll but the address just points to a bunch of zeros. I recently learned the PE file format and tried to understand all the code that I wrote when I was following a tutorial on Youtube on how to do this, so forgive me for my inexperience I'm just trying to learn. The other code that I do not show is me locating and finding the target process, reading the dll binary, getting the headers from the dll, me allocating space on the target process for the dll, and finally me writing all of the section header data into the target process. I can provide any other code that y'all would like to see!
Injector.h
using ModLoader_LoadLibrary = HINSTANCE(WINAPI*)(const char* filename);
using ModLoader_GetProcAddress = UINT_PTR(WINAPI*)(HINSTANCE module, const char* procName);
using ModLoader_DllEntry = BOOL(WINAPI*)(HINSTANCE dll, DWORD reason, LPVOID reserved);
struct ModLoader_ManualMapping_Data
{
ModLoader_LoadLibrary ML_LoadLibrary; //Function pointer to the windows load library function
ModLoader_GetProcAddress ML_ProcAddress; //Function pointer to a function to be called
HINSTANCE ML_Module; //dll instance
};
Injector.cpp : Shellcode function that'll run alongside the target executable
void __stdcall Shellcode(ModLoader_ManualMapping_Data* data)
{
if (!data)
return;
BYTE* pData = reinterpret_cast<BYTE*>(data);
IMAGE_OPTIONAL_HEADER& optHeader = reinterpret_cast<IMAGE_NT_HEADERS*>(pData + reinterpret_cast<IMAGE_DOS_HEADER*>(pData)->e_lfanew)->OptionalHeader;
auto loadLibrary = data->ML_LoadLibrary;
auto procAddress = data->ML_ProcAddress;
auto dllLoad = reinterpret_cast<ModLoader_DllEntry>(pData + optHeader.AddressOfEntryPoint); //Loads entry point func from dll
BYTE* locationDelta = pData - optHeader.ImageBase; //pData = the new address | ImageBase = preferred address -> Get the difference between the two to add to every address in the relocation table
if (locationDelta) //THIS DOES NOT GET RAN
{
//Adds the delta value to all addresses within the base relocation table
}
//Import table
if (optHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_IMPORT].Size)
{
IMAGE_IMPORT_DESCRIPTOR* imgImport = reinterpret_cast<IMAGE_IMPORT_DESCRIPTOR*>(pData
+ optHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_IMPORT].VirtualAddress);
while (imgImport->Name) //THIS DOES NOT GET RAN B\C imgImport is all zeros.
{
//Loops through import table
}
}
if (optHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_TLS].Size) //THIS DOES NOT GET RAN
{
//Calls the callback functions within dll
}
dllLoad(reinterpret_cast<HINSTANCE>(pData), DLL_PROCESS_ATTACH, nullptr); //PROBLEM: ACCESS VIOLATION
}
Injector.cpp : bool ManualMapping(HANDLE process, const char* dllFilepath)
-- This function is called in main.cpp.
The srcData variable is just the binary contents of the dll
ModLoader_ManualMapping_Data loadData = { 0 };
loadData.ML_LoadLibrary = LoadLibraryA;
loadData.ML_ProcAddress = reinterpret_cast<ModLoader_GetProcAddress>(GetProcAddress);
memcpy(srcData, &loadData, sizeof(loadData));
WriteProcessMemory(process, locOfDll, srcData, 0x1000, nullptr);
void* shellCodeBase = VirtualAllocEx(process, nullptr, 0x1000, MEM_COMMIT | MEM_RESERVE, PAGE_EXECUTE_READWRITE); //Allocates 0x1000 bytes in the process memory for the shellcode
WriteProcessMemory(process, shellCodeBase, Shellcode, 0x1000, nullptr); //Injects the Shellcode function into the process
HANDLE thread = nullptr;
thread = CreateRemoteThread(process, nullptr, 0, reinterpret_cast<PTHREAD_START_ROUTINE>(shellCodeBase), locOfDll, 0, nullptr); //Runs
Finally the sample dll code
#include <Windows.h>
BOOL WINAPI DllMain(HINSTANCE hModule, DWORD reason_for_call, LPVOID lpReserved)
{
switch (reason_for_call)
{
case DLL_PROCESS_ATTACH:
OutputDebugStringA("Injected!");
break;
}
return TRUE;
}
EDIT
After rewriting all the code and looking at it all day I finally figured it out. I just had to make sure that the parameters were right when I called dllLoad!
I'm trying to share memory between two processes C# (EXE) and C++ (DLL).
The C++ DLL is dynamically loaded by a Citrix receiver process.
Below is my C# and C++ code:
private void Test()
{
string data = "Hello";
_memoryMap = MemoryMappedFile.CreateOrOpen("14614C87-8D7F-45FC-8D59-DCBF1715A715", data.Length, MemoryMappedFileAccess.ReadWrite);
var stream = _memoryMap.CreateViewStream();
using (BinaryWriter binReader = new BinaryWriter(stream))
{
binReader.Write(data);
}
}
void readFromMemoryMap()
{
HANDLE hMapObject = OpenFileMapping(FILE_MAP_ALL_ACCESS, FALSE, L"14614C87-8D7F-45FC-8D59-DCBF1715A715");
char buffer[2000];
if (hMapObject == NULL)
{
sprintf(buffer, "OpenFileMapping: GetLastError=%d", GetLastError());
}
char *fileBuffer = (char *)MapViewOfFile(hMapObject, FILE_MAP_ALL_ACCESS, 0, 0, 6);
UnmapViewOfFile(fileBuffer);
CloseHandle(hMapObject);
}
I took care of writing and reading an object sequence. My C# application's memory map handle didn't crash. I have run this code using an administrator account which has rights.
I am facing the below error. Can anyone help me with the case of this error?
I followed below link for fix this issue.
OpenFileMapping ERROR_FILE_NOT_FOUND
Try prefixing the object name with Global\ like it says here: https://learn.microsoft.com/en-us/windows/win32/memory/creating-named-shared-memory
i am currently trying out PE injection and noticed that as soon as i use stuff like std::cout or std::string my target process which i injected in crashes.
Messageboxes or even printf() works fine. The code compiles without an error and i read about the import table not being at the same location in the injected process could cause it to crash but i have no idea what to do in order to fix it (re load the import table). Thanks in advance and here is the injection example:
#include <iostream>
#include <stdio.h>
#include <Windows.h>
void ThreadProc(PVOID p)
{
MessageBox(NULL,"Message from injected code!","Message",MB_ICONINFORMATION); //funktioniert einwandfrei
RedirectOutput();
std::cout << "hi"; //crashed
}
int main(int argc,char* argv[])
{
PIMAGE_DOS_HEADER pIDH;
PIMAGE_NT_HEADERS pINH;
PIMAGE_BASE_RELOCATION pIBR;
HANDLE hProcess,hThread;
PUSHORT TypeOffset;
PVOID ImageBase,Buffer,mem;
ULONG i,Count,Delta,*p;
printf("\nOpening target process\n");
hProcess=OpenProcess(
PROCESS_CREATE_THREAD|PROCESS_QUERY_INFORMATION|PROCESS_VM_OPERATION|PROCESS_VM_READ|PROCESS_VM_WRITE,
FALSE,
13371337);
if(!hProcess)
{
printf("\nError: Unable to open target process (%u)\n",GetLastError());
return -1;
}
ImageBase=GetModuleHandle(NULL);
printf("\nImage base in current process: %#x\n",ImageBase);
pIDH=(PIMAGE_DOS_HEADER)ImageBase;
pINH=(PIMAGE_NT_HEADERS)((PUCHAR)ImageBase+pIDH->e_lfanew);
printf("\nAllocating memory in target process\n");
mem=VirtualAllocEx(hProcess,NULL,pINH->OptionalHeader.SizeOfImage,MEM_COMMIT|MEM_RESERVE,PAGE_EXECUTE_READWRITE);
if(!mem)
{
printf("\nError: Unable to allocate memory in target process (%u)\n",GetLastError());
CloseHandle(hProcess);
return 0;
}
printf("\nMemory allocated at %#x\n",mem);
Buffer=VirtualAlloc(NULL,pINH->OptionalHeader.SizeOfImage,MEM_COMMIT|MEM_RESERVE,PAGE_READWRITE);
memcpy(Buffer,ImageBase,pINH->OptionalHeader.SizeOfImage);
printf("\nRelocating image\n");
pIBR=(PIMAGE_BASE_RELOCATION)((PUCHAR)Buffer+pINH->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_BASERELOC].VirtualAddress);
Delta=(ULONG)mem-(ULONG)ImageBase;
printf("\nDelta: %#x\n",Delta);
while(pIBR->VirtualAddress)
{
if(pIBR->SizeOfBlock>=sizeof(IMAGE_BASE_RELOCATION))
{
Count=(pIBR->SizeOfBlock-sizeof(IMAGE_BASE_RELOCATION))/sizeof(USHORT);
TypeOffset=(PUSHORT)(pIBR+1);
for(i=0;i<Count;i++)
{
if(TypeOffset[i])
{
p=(PULONG)((PUCHAR)Buffer+pIBR->VirtualAddress+(TypeOffset[i] & 0xFFF));
*p+=Delta;
}
}
}
pIBR=(PIMAGE_BASE_RELOCATION)((PUCHAR)pIBR+pIBR->SizeOfBlock);
}
printf("\nWriting relocated image into target process\n");
if(!WriteProcessMemory(hProcess,mem,Buffer,pINH->OptionalHeader.SizeOfImage,NULL))
{
printf("\nError: Unable to write process memory (%u)\n",GetLastError());
VirtualFreeEx(hProcess,mem,0,MEM_RELEASE);
CloseHandle(hProcess);
return -1;
}
VirtualFree(Buffer,0,MEM_RELEASE);
printf("\nCreating thread in target process\n");
hThread=CreateRemoteThread(hProcess,NULL,0,(LPTHREAD_START_ROUTINE)((PUCHAR)ThreadProc+Delta),NULL,0,NULL);
if(!hThread)
{
printf("\nError: Unable to create thread in target process (%u)\n",GetLastError());
VirtualFreeEx(hProcess,mem,0,MEM_RELEASE);
CloseHandle(hProcess);
return -1;
}
printf("\nWaiting for the thread to terminate\n");
WaitForSingleObject(hThread,INFINITE);
printf("\nThread terminated\n\nFreeing allocated memory\n");
VirtualFreeEx(hProcess,mem,0,MEM_RELEASE);
CloseHandle(hProcess);
return 0;
}
I think that answer simple - STL library request some initializations of global data. Via constructors of global objects, for example. But you just copy your code to target process. It don't invoke any initializations, that normally performed before call main function. Just try DLL injection instead.
You don't seem to be loading the CRT dll in the target process, so what I'm assuming is that when you try to call the cout function, you are jumping to unallocated memory.
If the DLL is in fact loaded in the target process, make sure it's loaded at the same address as it is in your own process. Otherwise you'll have to patch your import table to match that of the target process.
I'm creating a Windows Add/Remove Programs application in Qt 5.4 and I'm becaming crazy to solve a little "puzzle":
My application (APP_0) runs another application (APP_1) and waits for this APP_1 until it terminates.
APP_1 is an uninstaller (i.e. uninstall.exe) and I've not the source code of the APP_1, just of my Qt APP_0.
APP_1, instead of doing the uninstall job, it simply copies itself somewhere in the filesystem (I saw as Au_.exe but other apps could use different names and locations), runs this copy of itself (APP_2) and terminates.
The APP_2 has a GUI and the job I'm waiting for (uninstall) is demanded to the final user of the running APP_2.
In this situation my application (APP_0) stops waiting for APP_1 pratically immediately (because it launches APP_1 and waits for APP_1). But to work properly, obviously, I need to know instead when APP_2 is terminated...
So the question is:
is there a way (using some techniques (hooking?)) to know if and when APP_2 terminates?
Note: Consider that the standard Windows Add/Remove Programs utility does the job successfully (it seems it waits for APP_2). You can test this, for example, installing Adobe Digital Edition. Its uninstaller (uninstall.exe) copies itself into a new folder in the User_Local_Temp folder as Au_.exe, runs it and terminates. But the OS utility successfully waits for Au_.exe and only after it terminates refreshes the list of installed programs.
If this kind of technique (uninstall.exe copies itself somewhere ALWAYS with THE SAME name (Au_.exe) ) the problem could be resolved, obviously, very simply. But I don't think that the name of the copied uninstaller is always the same and also I don't like to assume things I'm not sure are real.
Many thanks in advance
Thanks to IInspectable's suggestion (see his comment... and many thanks guy!) I created a function which solves my problems! I'll share here this function which could be useful to other people with the same (or similar) problem.
For my needs, the function receives as parameter the index of the item to be uninstalled (from a QList) and gets the uninstall string (for example: C:\ProgramFiles\MyApp\uninstall.exe).
Then with this uninstall string, I'll create a process (CreateProcess) and put its handle into a Job Object, so that my function will wait for all the processes ran by this process.
The function itself is pretty simple and can be improved.
Notice that the process MUST be created with the CREATE_BREAKAWAY_FROM_JOB option, otherwise the AssignProcessToJobObject will fail with a "Access Denied" error.
void MainWindow::uniButtonClick(int idx)
{
QMessageBox::StandardButton reply;
QMessageBox::StandardButton err;
reply = QMessageBox::question(this, "Uninstall/Change", "Uninstall " +
ip[idx].displayName +"?\r\n\r\n" + ip[idx].uninstallString,
QMessageBox::Yes|QMessageBox::No);
if (reply == QMessageBox::Yes)
{
//QString s = "C:\\windows\\notepad.exe"; // Just to test Job assignment and createprocess
QString s = ip[idx].uninstallString; // the real uninstaller string
QString jobName = "MyJobObject";
try
{
PROCESS_INFORMATION ProcessInfo; //This is what we get as an [out] parameter
STARTUPINFO StartupInfo; //This is an [in] parameter
PJOBOBJECT_BASIC_PROCESS_ID_LIST pList;
HANDLE hProcess;
BOOL bJobAllEnd;
ZeroMemory(&StartupInfo, sizeof(StartupInfo));
StartupInfo.cb = sizeof StartupInfo ; //Only compulsory field
wchar_t* path;
path = (wchar_t*) malloc (sizeof(wchar_t)*s.length()+1);
s.toWCharArray(path);
path[s.length()]=0; // Null terminate the string
// Create the process with CREATE_BREAKAWAY_FROM_JOB to overcome the AccessDenied issue on AssignProcessToJobObject.
if(CreateProcess(NULL, path, NULL, NULL, FALSE, CREATE_BREAKAWAY_FROM_JOB|CREATE_SUSPENDED, NULL, NULL,&StartupInfo, &ProcessInfo))
{
pList = (PJOBOBJECT_BASIC_PROCESS_ID_LIST)GlobalAlloc(GMEM_FIXED, 10000);
HANDLE jobObj = CreateJobObject(NULL, (const wchar_t*)jobName.utf16());
if (AssignProcessToJobObject(jobObj, ProcessInfo.hProcess) != 0)
{
ResumeThread(ProcessInfo.hThread); // Process assigned to JobObjext, resume it now
do
{
QueryInformationJobObject(jobObj, JobObjectBasicProcessIdList, pList, 10000, NULL);
bJobAllEnd = TRUE;
for(DWORD i=0; i<pList->NumberOfProcessIdsInList; i++)
{
hProcess = OpenProcess(SYNCHRONIZE, FALSE, pList->ProcessIdList[i]);
if(hProcess != NULL)
{
CloseHandle(hProcess);
bJobAllEnd = FALSE;
}
}
Sleep(500);
} while(!bJobAllEnd);
}
else
qDebug() << "AssignProcess to Job failed: error = " << QString::number(GetLastError());
GlobalFree(pList);
CloseHandle(jobObj);
CloseHandle(ProcessInfo.hThread);
CloseHandle(ProcessInfo.hProcess);
}
}
catch(QString error)
{
QMessageBox::critical(this, "File not found!", "The requested uninstaller doesn't exists", QMessageBox::Ok);
}
// refresh list
handleButton();
}
}
I want to close a handle to a mutex located in another process, so I can run more than one instance of the application.
I already know this can be done, see Process Explorer. Example: Windows Minesweeper (Windows 7) uses a mutex to only allow one game, so I thought I would use it as an example since it's pre-installed with Windows and therefore easier for you guys to guide me.
The mutex that I need to close is \Sessions\1\BaseNamedObjects\Oberon_Minesweeper_Singleton, which I found using Process Explorer.
After closing this mutex I was able to launch two games of Minesweeper, but I want to do this in my program using C++.
After some searching I have found that I might need the API DuplicateHandle. So far I haven't been able to close the handle on this mutex.
Here is my code so far:
#include <Windows.h>
#include <iostream>
using namespace std;
void printerror(LPSTR location){
printf("Error: %s_%d", location, GetLastError());
cin.get();
}
int main(){
DWORD pid = 0;
HWND hMineWnd = FindWindow("Minesweeper", "Minesveiper");
GetWindowThreadProcessId(hMineWnd, &pid);
HANDLE hProc =OpenProcess(PROCESS_DUP_HANDLE, 0, pid);
if(hProc == NULL){
printerror("1");
return 1;
}
HANDLE hMutex = OpenMutex(MUTEX_ALL_ACCESS, TRUE, "Oberon_Minesweeper_Singleton");
if(hMutex == NULL){
printerror("2");
return 2;
}
if(DuplicateHandle(hProc, hMutex, NULL, 0, 0, FALSE, DUPLICATE_CLOSE_SOURCE) == 0){
printerror("3");
return 3;
}
if(CloseHandle(hMutex) == 0){
printerror("4");
return 4;
}
return 0;
}
This code returns 0, but the mutex is still there, and I am not able to launch more games of Minesweeper. I think some of my parameters to DuplicateHandle are wrong.
The second argument to DuplicateHandle expects "an open object handle that is valid in the context of the source process", however I believe the handle you're passing in would only be valid within the current process (OpenMutex creates a new handle to an existing mutex object). You'll likely need to determine what the mutex's handle is in the remote process, and use that value when calling DuplicateHandle.