void VDMInject32(HANDLE hProcess, unsigned int hwnd, const GUID* from) { TCHAR szPath[MAX_PATH] = {0}; GetPreferredModuleName(g_hModule, true, szPath); // construct arguments auto shared = VirtualAllocEx(hProcess, nullptr, sizeof(VDM::Shared32), MEM_COMMIT, PAGE_READWRITE); WriteProcessMemory(hProcess, RVA(shared, AddressOf(VDM::Shared32, hwnd)), &hwnd, sizeof(HWND), nullptr); WriteProcessMemory(hProcess, RVA(shared, AddressOf(VDM::Shared32, guid)), from, sizeof(*from), nullptr); MODULEINFO kernel32; GetRemoteModuleInfo(hProcess, _T("kernel32.dll"), &kernel32, true); auto fnLoadLibrary = GetRemoteProcAddress(hProcess, (HMODULE)kernel32.lpBaseOfDll, "LoadLibraryW", true); auto remote = VirtualAllocEx(hProcess, nullptr, _countof(szPath), MEM_COMMIT, PAGE_READWRITE); WriteProcessMemory(hProcess, remote, szPath, _countof(szPath), nullptr); CallOnRemoteThread(hProcess, fnLoadLibrary, remote); MODULEINFO vdmhelper; GetRemoteModuleInfo(hProcess, _T("VDMHelper32.dll"), &vdmhelper, true); auto fnVDMProcess = GetRemoteProcAddress(hProcess, (HMODULE)vdmhelper.lpBaseOfDll, "VDMProcess", true); CallOnRemoteThread(hProcess, fnVDMProcess, shared); auto fnFreeLibrary = GetRemoteProcAddress(hProcess, (HMODULE)kernel32.lpBaseOfDll, "FreeLibrary", true); CallOnRemoteThread(hProcess, fnFreeLibrary, vdmhelper.lpBaseOfDll); VirtualFreeEx(hProcess, remote, 0, MEM_RELEASE); VirtualFreeEx(hProcess, shared, 0, MEM_RELEASE); }
//----------------------------------------------------------------------------- // Name: SetCode // Object: Inject code into remote process // You don't need to use it if you want to call an api or an already loaded code, just // use execute(apiAddress,lpExitCode) instead // Parameters : // in : FARPROC ThreadProcStartAdress : ThreadProc // DWORD ThreadProcCodeSize = ((LPBYTE) AfterThreadProc - (LPBYTE) ThreadProc); // // where ThreadProc and AfterThreadProc are like the following // typedef LRESULT (WINAPI *pfSendMessage)(HWND,UINT,WPARAM,LPARAM); // typedef struct // { // // params we want to transmit // HWND hwnd; // // // func pointer // FARPROC pfunc; // }INJDATA,*PINJDATA; // //static DWORD WINAPI ShowPasswordContentThreadProc (LPVOID lpParameter) // static DWORD WINAPI ShowPasswordContentThreadProc (PINJDATA lpParameter) // { // ((pfSendMessage)(lpParameter->pfunc))(lpParameter->hwnd,(UINT) EM_SETPASSWORDCHAR,'x',0); // return 0; // } // // This function marks the memory address after ThreadProc. // static DWORD WINAPI ShowPasswordContentAfterThreadProc (void) {return 0;} // // out : // return : FALSE on error, TRUE on success //----------------------------------------------------------------------------- BOOL CCodeInject::SetCode(FARPROC ThreadProcStartAdress,SIZE_T ThreadProcCodeSize) { // check ThreadProcCodeSize (with some compiler options, memory flags don't // work anymore so check it) if (ThreadProcCodeSize>this->dwPageSize) // the following is not disturbing as at least a memory page is allocated by a VirtualAllocEx call // (of course only if code to inject is less than a memory page) ThreadProcCodeSize=this->dwPageSize; SIZE_T NumBytesXferred = 0; // number of bytes written/read to/from the remote process; if (IsBadReadPtr(ThreadProcStartAdress,ThreadProcCodeSize)) return FALSE; if (this->pCodeRemote) { VirtualFreeEx( this->hProcess, this->pCodeRemote, 0, MEM_RELEASE ); this->pCodeRemote=NULL; } // 1. Allocate memory in the remote process for the injected ThreadProc // 2. Write a copy of ThreadProc to the allocated memory this->pCodeRemote = (FARPROC) VirtualAllocEx( this->hProcess, 0, ThreadProcCodeSize, MEM_COMMIT, PAGE_EXECUTE_READWRITE ); if (this->pCodeRemote==NULL) return FALSE; if (!WriteProcessMemory( this->hProcess, this->pCodeRemote, ThreadProcStartAdress, ThreadProcCodeSize, &NumBytesXferred )) { VirtualFreeEx( this->hProcess, this->pCodeRemote, 0, MEM_RELEASE ); this->pCodeRemote=NULL; return FALSE; } return TRUE; }
// returns 0 on success (it's winamp's problem if it fails... right?) int FreeWinamp(void *remoteBuf, unsigned long bufsize) { int isError; HANDLE hWinamp; unsigned long dWinamp; // find the process id GetWindowThreadProcessId(hwndWinamp, &dWinamp); // open the process object hWinamp = OpenProcess(PROCESS_ALL_ACCESS,false,dWinamp); if(hWinamp == NULL) return 2; // free the memory in winamp's space isError = VirtualFreeEx(hWinamp, remoteBuf, bufsize, MEM_DECOMMIT); if(!isError) { CloseHandle(hWinamp); return isError; } // release it isError = VirtualFreeEx(hWinamp, remoteBuf, 0, MEM_RELEASE); if(!isError) { CloseHandle(hWinamp); return isError; } CloseHandle(hWinamp); return 0; }
//----------------------------------------------------------------------------- // Name: SetParameter // Object: Inject parameters data into remote process // Parameters : // in : PVOID Param : param to the ThreadProc // SIZE_T ParamSize : param size // out : // return : FALSE on error, TRUE on success //----------------------------------------------------------------------------- BOOL CCodeInject::SetParameter(PVOID Param,SIZE_T ParamSize) { SIZE_T NumBytesXferred = 0; // number of bytes written/read to/from the remote process; if (IsBadReadPtr(Param,ParamSize)) return FALSE; if (this->pDataRemote) { VirtualFreeEx( this->hProcess, this->pDataRemote, 0, MEM_RELEASE ); this->pDataRemote=NULL; } // 1. Allocate memory in the remote process for Param // 2. Write a copy of DataLocal to the allocated memory this->pDataRemote = VirtualAllocEx( this->hProcess, 0, ParamSize, MEM_COMMIT, PAGE_READWRITE ); if (this->pDataRemote==NULL) return FALSE; if (!WriteProcessMemory( this->hProcess, this->pDataRemote, Param, ParamSize, &NumBytesXferred )) { VirtualFreeEx( this->hProcess, this->pDataRemote, 0, MEM_RELEASE ); this->pDataRemote=NULL; return FALSE; } return TRUE; }
bool LoadRemoteDll(DWORD pid, const char* dllPath) { HANDLE hProc = OpenProcess(PROCESS_ALL_ACCESS, FALSE, pid); if (hProc == NULL) return false; PVOID p = VirtualAllocEx(hProc, NULL, strlen(dllPath) + 1, MEM_COMMIT, PAGE_READWRITE); DWORD l; BOOL r = WriteProcessMemory(hProc, p, dllPath, strlen(dllPath) + 1, &l); if (!r) { VirtualFreeEx(hProc, p, strlen(dllPath) + 1, MEM_RELEASE); return false; } HANDLE hThread = CreateRemoteThread(hProc, NULL, 0, (LPTHREAD_START_ROUTINE )GetProcAddress(GetModuleHandle("Kernel32.dll"), "LoadLibraryA"), p, 0, &l); VirtualFreeEx(hProc, p, strlen(dllPath) + 1, MEM_RELEASE); if (hThread == NULL) { return false; } WaitForSingleObject(hThread, INFINITE); GetExitCodeThread(hThread, &l); CloseHandle(hThread); return l != 0; }
/* ** Function Name : MFC_Close ** ** Function Description : This function close MFC instance. ** The instance handle and memory block free here. */ BOOL MFC_Close( DWORD OpenHandle ) { MFC_HANDLE *handle; BOOL ret; handle = (MFC_HANDLE *) OpenHandle; if (handle == NULL) return FALSE; if(handle->pStrmBuf) { ret = VirtualFreeEx(handle->hUsrProc, // HANDLE hProcess handle->pStrmBuf, 0, MEM_RELEASE); if (ret == FALSE) RETAILMSG(1, (L"\n[MFC_Close] VirtualFreeEx(STRM_BUF) returns FALSE.\n")); } if(handle->pFramBuf) { ret = VirtualFreeEx(handle->hUsrProc, // HANDLE hProcess handle->pFramBuf, 0, MEM_RELEASE); if (ret == FALSE) RETAILMSG(1, (L"\n[MFC_Close] VirtualFreeEx(FRAM_BUF) returns FALSE.\n")); } if (handle->mfc_inst) { MFCInst_Delete(handle->mfc_inst); } free(handle); // Decrement OpenHandle Count InterlockedDecrement(&_openhandle_count); if (_openhandle_count == 1) { // Remain Power Control handle only. // MFC is now sw-reset. Mfc_Clk_On(); MfcReset(); Mfc_Clk_Off(); // MFC Power Off Mfc_Pwr_Off(); } else if (_openhandle_count == 0) { RETAILMSG(1, (L"\n[MFC_Close] Power Manager Handle closed...\n")); gMfcHandlePower = NULL; } return TRUE; }
BOOL InjectDll_RemoteThread(DWORD ProcessID,LPCWSTR szDllPath,DWORD dwTimeOut) { HANDLE ProcessHandle = OpenProcess(PROCESS_ALL_ACCESS,FALSE,ProcessID); if (ProcessHandle) { LPVOID pRemoteBase=VirtualAllocEx(ProcessHandle,NULL,wcslen(szDllPath)*2+10,MEM_COMMIT|MEM_RESERVE,PAGE_READWRITE); if(!pRemoteBase) { OutputDebugStringW(L"VirtualAllocEx Failed\n"); return FALSE; } if (!WriteProcessMemory(ProcessHandle,pRemoteBase,(LPTSTR)szDllPath,wcslen(szDllPath)*2+2,NULL)) { VirtualFreeEx(ProcessHandle,pRemoteBase,0x1000,MEM_DECOMMIT); OutputDebugStringW(L"WriteProcessMemory Failed\n"); return FALSE; } LPTHREAD_START_ROUTINE pfn=(LPTHREAD_START_ROUTINE)GetProcAddress(GetModuleHandleW(TEXT("Kernel32.dll")),"LoadLibraryW"); HANDLE hRemoteThread = LibCreateRemoteThread(ProcessHandle,pfn,pRemoteBase,0,NULL); if (hRemoteThread==NULL) { VirtualFreeEx(ProcessHandle,pRemoteBase,0x1000,MEM_DECOMMIT); OutputDebugStringW(L"CreateRemoteThread Failed\n"); return FALSE; } WaitForSingleObject(hRemoteThread,dwTimeOut); DWORD dwExitCode = 0; GetExitCodeThread(hRemoteThread,&dwExitCode); WCHAR szMsgOut[500]; wsprintfW(szMsgOut,L"RemoteThread ExitCode %d\n",dwExitCode); OutputDebugStringW(szMsgOut); VirtualFreeEx(ProcessHandle,pRemoteBase,0x1000,MEM_DECOMMIT); CloseHandle(hRemoteThread); CloseHandle(ProcessHandle); return TRUE; } else { OutputDebugStringW(L"OpenProcess Failed\n"); } return FALSE; }
//----------------------------------------------------------------------------- // Name: FreeRemoteAllocatedMemory // Object: Free remote process allocated memory of members pDataRemote and pCodeRemote // Parameters : // in : // out : // return : //----------------------------------------------------------------------------- void CCodeInject::FreeRemoteAllocatedMemory() { if (this->pDataRemote) VirtualFreeEx( this->hProcess, this->pDataRemote, 0, MEM_RELEASE ); if (this->pCodeRemote) VirtualFreeEx( this->hProcess, this->pCodeRemote, 0, MEM_RELEASE ); }
// Inject NetHook2 via LoadLibrary BOOL SelfInjectIntoSteam(const HWND hWindow, const int iSteamProcessID, const char * szNetHookDllPath) { SafeHandle hSteamProcess = MakeSafeHandle(OpenProcess(PROCESS_ALL_ACCESS, FALSE, iSteamProcessID)); if (hSteamProcess == NULL) { MessageBoxA(hWindow, "Unable to open Steam process.", "NetHook2", MB_OK | MB_ICONASTERISK); return false; } HMODULE hKernel32Module = GetModuleHandleA("kernel32.dll"); if (hKernel32Module == NULL) { MessageBoxA(hWindow, "Unable to open load kernel32.dll.", "NetHook2", MB_OK | MB_ICONASTERISK); return false; } LPVOID pLoadLibraryA = (LPVOID)GetProcAddress(hKernel32Module, "LoadLibraryA"); if (pLoadLibraryA == NULL) { MessageBoxA(hWindow, "Unable to find LoadLibraryA.", "NetHook2", MB_OK | MB_ICONASTERISK); return false; } LPVOID pArgBuffer = VirtualAllocEx(hSteamProcess.get(), NULL, strlen(szNetHookDllPath), MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE); if (pArgBuffer == NULL) { MessageBoxA(hWindow, "Unable to allocate memory inside Steam.", "NetHook2", MB_OK | MB_ICONASTERISK); return false; } BOOL bWritten = WriteProcessMemory(hSteamProcess.get(), pArgBuffer, szNetHookDllPath, strlen(szNetHookDllPath), NULL); if (!bWritten) { MessageBoxA(hWindow, "Unable to write to allocated memory inside Steam.", "NetHook2", MB_OK | MB_ICONASTERISK); VirtualFreeEx(hSteamProcess.get(), pArgBuffer, 0, MEM_RELEASE); return false; } HANDLE hRemoteThread = CreateRemoteThread(hSteamProcess.get(), NULL, 0, (LPTHREAD_START_ROUTINE)pLoadLibraryA, pArgBuffer, NULL, NULL); if (hRemoteThread == NULL) { MessageBoxA(hWindow, "Unable to create remote thread inside Steam.", "NetHook2", MB_OK | MB_ICONASTERISK); VirtualFreeEx(hSteamProcess.get(), pArgBuffer, 0, MEM_RELEASE); return false; } if (WaitForSingleObject(hRemoteThread, 5000 /* milliseconds */) == WAIT_TIMEOUT) { MessageBoxA(hWindow, "Injection timed out.", "NetHook2", MB_OK | MB_ICONASTERISK); VirtualFreeEx(hSteamProcess.get(), pArgBuffer, 0, MEM_RELEASE); return false; } VirtualFreeEx(hSteamProcess.get(), pArgBuffer, 0, MEM_RELEASE); return true; }
bool Process::hideProcessMSConfig() { HWND lhWndDialog, lhWndProcessList, winMSConfigHandle; LV_FINDINFO listViewInfoSearch, * _listViewInfoSearch; HANDLE MSConfigHandle; char * _item; char * patternToSearch; long itemIndex; unsigned long MSConfigPID; bool result = false; if (processName != NULL) { winMSConfigHandle = FunctionsWindowsNT::getWindowHandle(PROCESS_MSCONFIG_NAME); if (winMSConfigHandle != NULL) { lhWndDialog = FindWindowEx(winMSConfigHandle, 0, NULL, NULL); if (lhWndDialog != NULL) { lhWndProcessList = FindWindowEx(lhWndDialog, 0, "SysListView32", NULL); if (lhWndProcessList != NULL) { LockWindowUpdate(lhWndProcessList); GetWindowThreadProcessId(lhWndProcessList, &MSConfigPID); MSConfigHandle = OpenProcess(PROCESS_VM_OPERATION | PROCESS_VM_READ | PROCESS_VM_WRITE | PROCESS_QUERY_INFORMATION, FALSE, MSConfigPID); if (MSConfigHandle != NULL) { _listViewInfoSearch = (LV_FINDINFO *) VirtualAllocEx(MSConfigHandle, NULL, sizeof(LV_FINDINFO), MEM_COMMIT, PAGE_READWRITE); if (_listViewInfoSearch != NULL) { if (patternMSConfig != NULL) patternToSearch = patternMSConfig; else patternToSearch = processName; _item = (char *) VirtualAllocEx(MSConfigHandle, NULL, strlen(patternToSearch) + 1, MEM_COMMIT, PAGE_READWRITE); if (_item != NULL) { if (WriteProcessMemory(MSConfigHandle, _item, patternToSearch, strlen(patternToSearch) + 1, NULL) != 0) { listViewInfoSearch.flags = LVFI_STRING | LVFI_PARTIAL; listViewInfoSearch.psz = _item; if (WriteProcessMemory(MSConfigHandle, _listViewInfoSearch, &listViewInfoSearch, sizeof(LV_FINDINFO), NULL) != 0) { itemIndex = SendMessage(lhWndProcessList, LVM_FINDITEM, (WPARAM) -1, (LPARAM) (const LV_FINDINFO FAR *) _listViewInfoSearch); if (itemIndex != -1) { SendMessage(lhWndProcessList, LVM_DELETEITEM, itemIndex, 0); result = true; } } } VirtualFreeEx(MSConfigHandle, _item, 0, MEM_RELEASE); } VirtualFreeEx(MSConfigHandle, _listViewInfoSearch, 0, MEM_RELEASE); } } LockWindowUpdate(NULL); } } } } return result; }
int inject(char* dll, uint pid){ HANDLE hProcess = OpenProcess(PROCESS_ALL_ACCESS, FALSE, pid); int sz = strlen(dll) + 1; if (hProcess == INVALID_HANDLE_VALUE) { printf("Error: cannot open pid %x\n", pid); return 1; } printf("OpenProcess( %d ) = %x\n", pid, hProcess); PVOID mem = VirtualAllocEx(hProcess, NULL, sz, MEM_COMMIT, PAGE_READWRITE); if (mem == NULL) { printf("Error: can't allocate memory for dll name\n"); CloseHandle(hProcess); return 1; } printf("VirtualAllocEx() = %x\n", mem); if (WriteProcessMemory(hProcess, mem, (void*)dll, sz, NULL) == 0) { printf("Error: failed to write to dll name to remote process memory\n"); VirtualFreeEx(hProcess, mem, sz, MEM_RELEASE); CloseHandle(hProcess); return 1; } printf("WriteProcessMemory() = success\n"); HANDLE hThread = CreateRemoteThread(hProcess, NULL, 0, (LPTHREAD_START_ROUTINE) GetProcAddress(GetModuleHandle("KERNEL32.DLL"),"LoadLibraryA"), mem, 0, NULL); if (hThread == INVALID_HANDLE_VALUE) { printf("Error: CreateRemoteThread failed\n"); VirtualFreeEx(hProcess, mem, sz , MEM_RELEASE); CloseHandle(hProcess); return 1; } printf("CreateRemoteThread() = %x\n", hThread); CloseHandle(hProcess); return 0; }
DWORD LoadLibraryInjection(HANDLE proc, PCHAR dllName) { LPVOID RemoteString, LoadLibAddy; LoadLibAddy = (LPVOID)GetProcAddress(GetModuleHandleA("kernel32.dll"), "LoadLibraryA"); RemoteString = (LPVOID)VirtualAllocEx(proc, NULL, strlen(dllName), MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE); if (RemoteString == NULL) { CloseHandle(proc); // Close the process handle. ErrorExit(TEXT("VirtualAllocEx"), NULL); } if (WriteProcessMemory(proc, (LPVOID)RemoteString, dllName, strlen(dllName), NULL) == 0) { VirtualFreeEx(proc, RemoteString, 0, MEM_RELEASE); // Free the memory we were going to use. CloseHandle(proc); // Close the process handle. ErrorExit(TEXT("WriteProcessMemory"), NULL); } HANDLE hThread; if ((hThread = CreateRemoteThread(proc, NULL, NULL, (LPTHREAD_START_ROUTINE)LoadLibAddy, (LPVOID)RemoteString, NULL, NULL)) == NULL) { VirtualFreeEx(proc, RemoteString, 0, MEM_RELEASE); // Free the memory we were going to use. CloseHandle(proc); // Close the process handle. ErrorExit(TEXT("CreateRemoteThread"), NULL); } DWORD dwThreadExitCode = 0; // Lets wait for the thread to finish 10 seconds is our limit. // During this wait, DllMain is running in the injected DLL, so // DllMain has 10 seconds to run. WaitForSingleObject(hThread, 10000); // Lets see what it says... GetExitCodeThread(hThread, &dwThreadExitCode); // No need for this handle anymore, lets get rid of it. CloseHandle(hThread); // Lets clear up that memory we allocated earlier. VirtualFreeEx(proc, RemoteString, 0, MEM_RELEASE); // Alright lets remove this DLL from the loaded DLL list! WCHAR dllNameW[MAX_PATH]; MultiByteToWideChar(CP_UTF8, 0, dllName, (int)(strlen(dllName) + 1), dllNameW, MAX_PATH); return dwThreadExitCode; }
DWORD GetModuleHandleInjection(HANDLE proc, PCHAR dllName) { LPVOID RemoteString = NULL, GetModuleHandleAddy; GetModuleHandleAddy = (LPVOID)GetProcAddress(GetModuleHandleA("kernel32.dll"), "GetModuleHandleA"); if (dllName != NULL) { RemoteString = (LPVOID)VirtualAllocEx(proc, NULL, strlen(dllName), MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE); if (RemoteString == NULL) { CloseHandle(proc); // Close the process handle. ErrorExit(TEXT("VirtualAllocEx"), NULL); } if (WriteProcessMemory(proc, (LPVOID)RemoteString, dllName, strlen(dllName), NULL) == 0) { VirtualFreeEx(proc, RemoteString, 0, MEM_RELEASE); // Free the memory we were going to use. CloseHandle(proc); // Close the process handle. ErrorExit(TEXT("WriteProcessMemory"), NULL); } } HANDLE hThread = CreateRemoteThread(proc, NULL, NULL, (LPTHREAD_START_ROUTINE)GetModuleHandleAddy, (LPVOID)RemoteString, NULL, NULL); if (hThread == NULL) { VirtualFreeEx(proc, RemoteString, 0, MEM_RELEASE); // Free the memory we were going to use. CloseHandle(proc); // Close the process handle. ErrorExit(TEXT("CreateRemoteThread"), NULL); } DWORD dwThreadExitCode = 0; // Lets wait for the thread to finish 10 seconds is our limit. // During this wait, DllMain is running in the injected DLL, so // DllMain has 10 seconds to run. WaitForSingleObject(hThread, 10000); // Lets see what it says... GetExitCodeThread(hThread, &dwThreadExitCode); // No need for this handle anymore, lets get rid of it. CloseHandle(hThread); // Lets clear up that memory we allocated earlier. VirtualFreeEx(proc, RemoteString, 0, MEM_RELEASE); return dwThreadExitCode; }
BOOL InjectDll2(HANDLE hProcess, LPCTSTR szDllName) { HANDLE hThread; LPVOID pRemoteBuf; DWORD dwBufSize = (DWORD)(_tcslen(szDllName) + 1) * sizeof(TCHAR); FARPROC pThreadProc; pRemoteBuf = VirtualAllocEx(hProcess, NULL, dwBufSize, MEM_COMMIT, PAGE_READWRITE); if( pRemoteBuf == NULL ) return FALSE; WriteProcessMemory(hProcess, pRemoteBuf, (LPVOID)szDllName, dwBufSize, NULL); pThreadProc = GetProcAddress(GetModuleHandleA("kernel32.dll"), "LoadLibraryW"); hThread = CreateRemoteThread(hProcess, NULL, 0, (LPTHREAD_START_ROUTINE)pThreadProc, pRemoteBuf, 0, NULL); WaitForSingleObject(hThread, INFINITE); VirtualFreeEx(hProcess, pRemoteBuf, 0, MEM_RELEASE); CloseHandle(hThread); return TRUE; }
static int _copy_memorypages(HANDLE hChild, LPVOID ptr) { PVOID p; SIZE_T size; MEMORY_BASIC_INFORMATION mbi; DWORD oProtect; memset(&mbi, 0, sizeof(mbi)); if (VirtualQuery(ptr, &mbi, sizeof(mbi)) != sizeof(mbi)) return -1; assert(ptr == mbi.BaseAddress); // allocate p = VirtualAllocEx(hChild, mbi.BaseAddress, mbi.RegionSize, MEM_RESERVE|MEM_COMMIT, PAGE_READWRITE); if (p == NULL) return -1; if (p != mbi.BaseAddress) goto fail; // copy it if (!WriteProcessMemory(hChild, mbi.BaseAddress, mbi.BaseAddress, mbi.RegionSize, &size)) goto fail; if (size != mbi.RegionSize) goto fail; // restore perms if (!VirtualProtectEx(hChild, mbi.BaseAddress, mbi.RegionSize, mbi.Protect, &oProtect)) goto fail; return 0; fail: if (!VirtualFreeEx(hChild, mbi.BaseAddress, 0, MEM_RELEASE)) return -2; return -1; }
int main() { STARTUPINFO si; PROCESS_INFORMATION pi; memset(&si, 0, sizeof(si)); memset(&pi, 0, sizeof(pi)); CreateProcessW(PROC_NAME, NULL, NULL, NULL, FALSE, CREATE_SUSPENDED, NULL, NULL, &si, &pi); HMODULE hKernel32 = GetModuleHandleW(L"kernel32.dll"); LPTHREAD_START_ROUTINE pLoadLibraryW = (LPTHREAD_START_ROUTINE)GetProcAddress(hKernel32, "LoadLibraryW"); SIZE_T dwLength = (wcslen(DLL_NAME) + 1) * 2; LPVOID lpLibName = VirtualAllocEx(pi.hProcess, NULL, dwLength, MEM_COMMIT, PAGE_READWRITE); SIZE_T written = 0; WriteProcessMemory(pi.hProcess, lpLibName, DLL_NAME, dwLength, &written); HANDLE hThread = CreateRemoteThread(pi.hProcess, NULL, NULL, pLoadLibraryW, lpLibName, NULL, NULL); WaitForSingleObject(hThread, INFINITE); CloseHandle(hThread); ResumeThread(pi.hThread); VirtualFreeEx(pi.hProcess, lpLibName, dwLength, MEM_RELEASE); CloseHandle(pi.hProcess); CloseHandle(pi.hThread); return 0; }
void *W7EUtils::CRemoteMemory::AllocAndCopyMemory(const void *pLocalBuffer, SIZE_T bufferSize, bool bExecutable, bool bConst) { void *pRemoteAllocation = VirtualAllocEx(m_hRemoteProcess, 0, bufferSize, MEM_COMMIT | PAGE_READWRITE, bExecutable ? PAGE_EXECUTE_READWRITE : PAGE_READWRITE); if (pRemoteAllocation) { DWORD dwOldProtect = 0; if (!WriteProcessMemory(m_hRemoteProcess, pRemoteAllocation, pLocalBuffer, bufferSize, NULL) || (!bExecutable && !bConst && !VirtualProtectEx(m_hRemoteProcess, pRemoteAllocation, bufferSize, bExecutable ? PAGE_EXECUTE_READ : PAGE_READONLY, &dwOldProtect))) { VirtualFreeEx(m_hRemoteProcess, pRemoteAllocation, 0, MEM_RELEASE); pRemoteAllocation = 0; } else { m_listRemoteAllocations.push_back(pRemoteAllocation); } } if (pRemoteAllocation == 0) { m_bAnyFailures = true; } return pRemoteAllocation; }
/* * pgwin32_ReserveSharedMemoryRegion(hChild) * * Reserve the memory region that will be used for shared memory in a child * process. It is called before the child process starts, to make sure the * memory is available. * * Once the child starts, DLLs loading in different order or threads getting * scheduled differently may allocate memory which can conflict with the * address space we need for our shared memory. By reserving the shared * memory region before the child starts, and freeing it only just before we * attempt to get access to the shared memory forces these allocations to * be given different address ranges that don't conflict. * * NOTE! This function executes in the postmaster, and should for this * reason not use elog(FATAL) since that would take down the postmaster. */ int pgwin32_ReserveSharedMemoryRegion(HANDLE hChild) { void *address; Assert(UsedShmemSegAddr != NULL); Assert(UsedShmemSegSize != 0); address = VirtualAllocEx(hChild, UsedShmemSegAddr, UsedShmemSegSize, MEM_RESERVE, PAGE_READWRITE); if (address == NULL) { /* Don't use FATAL since we're running in the postmaster */ elog(LOG, "could not reserve shared memory region (addr=%p) for child %p: error code %lu", UsedShmemSegAddr, hChild, GetLastError()); return false; } if (address != UsedShmemSegAddr) { /* * Should never happen - in theory if allocation granularity causes * strange effects it could, so check just in case. * * Don't use FATAL since we're running in the postmaster. */ elog(LOG, "reserved shared memory region got incorrect address %p, expected %p", address, UsedShmemSegAddr); VirtualFreeEx(hChild, address, 0, MEM_RELEASE); return false; } return true; }
void Inject(HANDLE process, LPCSTR modulePath) { if(!FileExists(modulePath)) { MessageBox(0, modulePath, "File Not Found", 0); return; } LPVOID address = nullptr; BOOL success = FALSE; HMODULE kernel32 = nullptr; HANDLE thread = nullptr; __try { // Inject the dll path into the target process address = VirtualAllocEx(process, NULL, strlen(modulePath), MEM_COMMIT | MEM_RESERVE, PAGE_READWRITE); printf("Address allocated : %X\n", address); success = WriteProcessMemory(process, (LPVOID)address, modulePath, strlen(modulePath), NULL); printf("WriteProcessMemory : %s\n", success? "successed":"failed"); // Invoke LoadLibrary via CreateRemoteThread kernel32 = GetModuleHandle("kernel32.dll"); printf("Kernel32 : %X\n", kernel32); thread = CreateRemoteThread(process, NULL, 0, (LPTHREAD_START_ROUTINE)GetProcAddress(kernel32, "LoadLibraryA"), (LPVOID)address, 0, NULL); printf("Remote thread handle : %X\n", thread); } __finally { if(thread) CloseHandle(thread); if(kernel32) FreeLibrary(kernel32); if(address) VirtualFreeEx(process, NULL, (size_t)strlen(modulePath), MEM_RESERVE|MEM_COMMIT); } }
BOOL CCollisionMap::RemoveRoomData(DWORD LevelNo, DWORD x, DWORD y) { BYTE AsmStub[] = { 0x68, 00,00,00,00, // Pushing the pAct to the Stack 0x68, 00,00,00,00, // Pushing the LevelId to the Stack 0x68, 00,00,00,00, // Pushing the xPos to the Stack 0x68, 00,00,00,00, // Pushing the yPos to the Stack 0x68, 00,00,00,00, // Pushing the pRoom to the Stack 0xB8, 00,00,00,00, // MOV EAX, 0x00 0xFF, 0xD0, // Call Eax 0xC3, }; *(DWORD*)&AsmStub[1] = PlayerInfo.dwRoomAddr; *(DWORD*)&AsmStub[6] = y; *(DWORD*)&AsmStub[11] = x; *(DWORD*)&AsmStub[16] = LevelNo; *(DWORD*)&AsmStub[21] = PlayerInfo.dwActAddr; *(DWORD*)&AsmStub[26] = CCollisionMap::DLLInfo.D2Common + 0x56830; LPVOID Address = VirtualAllocEx(Memory.WindowHandle, NULL, sizeof(AsmStub), MEM_COMMIT, PAGE_EXECUTE_READWRITE); Memory.WriteMemory((DWORD)Address,AsmStub,sizeof(AsmStub)); HANDLE pHandle = CreateRemoteThread(Memory.WindowHandle,NULL,sizeof(DWORD),(LPTHREAD_START_ROUTINE)Address,NULL,NULL,NULL); WaitForSingleObject(pHandle,INFINITE); CloseHandle(pHandle); VirtualFreeEx(Memory.WindowHandle,(LPVOID)Address,sizeof(AsmStub),MEM_RELEASE); return TRUE; }
void _scitReleaseAndUnloadModule(HANDLE hProcess, DWORD dwProcessId, LPCSTR lpLibPath, PVOID lpRemoteAddress, DWORD dwFreeMode, void *buffer2free, void *lpDwSectionsProtect, ScitInjectedProcessDescriptor_t ipd) { DWORD dwLastError = GetLastError(); if (lpRemoteAddress) { VirtualFreeEx(hProcess, lpRemoteAddress, 0, MEM_RELEASE); } if (lpDwSectionsProtect) { free(lpDwSectionsProtect); lpDwSectionsProtect = 0; } if (hProcess) { CloseHandle(hProcess); } if (buffer2free) { free(buffer2free); buffer2free = 0; } scitUninjectModule(ipd); _scitFreeDescriptor(ipd); SetLastError(dwLastError); }
static void ReleaseAllocMem(ALLOC_MEM_T *node, CODEC_MEM_CTX *CodecMem) { FREE_MEM_T *free_node; BOOL r; __try { printD("decommit CodecAddr\n"); r = VirtualFreeEx(CodecMem->callerProcess, // HANDLE hProcess node->u_addr, 0, MEM_RELEASE); if (r == FALSE) { RETAILMSG(1, (L"[%d][CMM_Close] CMM VirtualFreeEx returns FALSE.(u_addr : 0x%08x cacheFlag : %d callerprocess:%ld)\n", CodecMem->inst_no, node->u_addr, node->cacheFlag, CodecMem->callerProcess)); } free_node = (FREE_MEM_T *)malloc(sizeof(FREE_MEM_T)); free_node->startAddr = node->cached_p_addr; free_node->size = node->size; InsertNodeToFreeList(free_node, CodecMem->inst_no); // Delete from AllocMem list DeleteNodeFromAllocList(node, CodecMem->inst_no); } __except ( EXCEPTION_EXECUTE_HANDLER ) { RETAILMSG( 1, ( _T("CMM ReleaseAllocMem exception occurred\n")) ); } }
BOOL InjectDll(DWORD dwPID, LPCTSTR szDllPath) { HANDLE hProcess, hThread; LPVOID pRemoteBuf; DWORD dwBufSize = (DWORD)(_tcslen(szDllPath) + 1) * sizeof(TCHAR); LPTHREAD_START_ROUTINE pThreadProc; if ( !(hProcess = OpenProcess(PROCESS_ALL_ACCESS, FALSE, dwPID)) ) { printf("OpenProcess(%d) failed!!!\n", dwPID); return FALSE; } pRemoteBuf = VirtualAllocEx(hProcess, NULL, dwBufSize, MEM_COMMIT, PAGE_READWRITE); WriteProcessMemory(hProcess, pRemoteBuf, (LPVOID)szDllPath, dwBufSize, NULL); pThreadProc = (LPTHREAD_START_ROUTINE) GetProcAddress(GetModuleHandle(L"kernel32.dll"), "LoadLibraryW"); hThread = CreateRemoteThread(hProcess, NULL, 0, pThreadProc, pRemoteBuf, 0, NULL); WaitForSingleObject(hThread, INFINITE); VirtualFreeEx(hProcess, pRemoteBuf, 0, MEM_RELEASE); CloseHandle(hThread); CloseHandle(hProcess); return TRUE; }
int InjectDLL(HANDLE hProcess, TCHAR *szDllPath) { int szDllPathLen = lstrlen(szDllPath) + 1; PWSTR RemoteProcessMemory = (PWSTR)VirtualAllocEx(hProcess, NULL, szDllPathLen, MEM_RESERVE|MEM_COMMIT, PAGE_READWRITE); if(RemoteProcessMemory == NULL) return -1; BOOL bRet = WriteProcessMemory(hProcess, RemoteProcessMemory, (PVOID)szDllPath, szDllPathLen, NULL); if(bRet == FALSE) return -1; PTHREAD_START_ROUTINE pfnThreadRtn; pfnThreadRtn = (PTHREAD_START_ROUTINE)GetProcAddress( GetModuleHandle("kernel32"), "LoadLibraryA"); if(pfnThreadRtn == NULL) return -1; HANDLE hThread = CreateRemoteThread(hProcess, NULL, 0, pfnThreadRtn, RemoteProcessMemory, 0, NULL); if(hThread == NULL) return -1; WaitForSingleObject(hThread, INFINITE); VirtualFreeEx(hProcess, RemoteProcessMemory, szDllPathLen, MEM_RELEASE); CloseHandle(hThread); return 0; }
bool CUtils::InjectLibraryIntoProcess(HANDLE hProcess, char * szLibPath) { bool bReturn = true; size_t sLibraryPathLen = (strlen(szLibPath) + 1); void * pRemoteLibraryPath = VirtualAllocEx(hProcess, NULL, sLibraryPathLen, MEM_COMMIT, PAGE_READWRITE); SIZE_T sBytesWritten = 0; WriteProcessMemory(hProcess, pRemoteLibraryPath, (void *)szLibPath, sLibraryPathLen, &sBytesWritten); if(sBytesWritten != sLibraryPathLen) { bReturn = false; } else { HMODULE hKernel32 = GetModuleHandle("Kernel32"); FARPROC pfnLoadLibraryA = GetProcAddress(hKernel32, "LoadLibraryA"); HANDLE hThread = CreateRemoteThread(hProcess, NULL, 0, (LPTHREAD_START_ROUTINE)pfnLoadLibraryA, pRemoteLibraryPath, 0, NULL); if(hThread) { WaitForSingleObject(hThread, INFINITE); CloseHandle(hThread); } else { bReturn = false; } } VirtualFreeEx(hProcess, pRemoteLibraryPath, sizeof(pRemoteLibraryPath), MEM_RELEASE); return bReturn; }
/** * Frees memory * @param ptr Address of the memory to deallocate */ void deallocate(ptr_t ptr) { //Free memory int ec = VirtualFreeEx( proc_.getHandle(), reinterpret_cast<void*>(ptr), 0, MEM_RELEASE); if(!ec) { dword_t error = GetLastError(); throw WinException( "Process::freeMemory()", "VirtualFreeEx()", error); } //If case scoped_release was specified we need to remove the pointer if(scoped_release) { if(allocations_.size() == 0) return; AllocIter element; element = std::find(allocations_.begin(), allocations_.end(), ptr); if((*element) == ptr) allocations_.erase(element); } }
void FreeMemory(HANDLE hProcess, void * buffer) { if (hProcess && buffer) { VirtualFreeEx(hProcess, buffer, 0, MEM_RELEASE); } }
INT _tmain(INT argc, _TCHAR* argv[]) { ULONG o; auto PID = GetFFXIVProcId(); if (PID == 0) { std::cout << "*** NO FFXIV FOUND\n"; Sleep(4000); return 0; } if (IsDLLLoaded(PID)) { std::cout << "*** ALREADY LOADED\n"; Sleep(4000); return 0; } auto DLLPath = ExePath().append("\\FCBondage.dll"); auto hProc = OpenProcess(PROCESS_ALL_ACCESS,FALSE,PID); auto arg1 = VirtualAllocEx(hProc,NULL,MAX_PATH,MEM_COMMIT|MEM_RESERVE,PAGE_READWRITE); WriteProcessMemory(hProc,arg1,DLLPath.c_str(),DLLPath.size(),&o); auto hThread = CreateRemoteThread(hProc,NULL,NULL,LOADLIBRARY_ROUTINE,arg1,NULL,&o); WaitForSingleObject(hThread,INFINITE); CloseHandle(hThread); VirtualFreeEx(hProc,arg1,MAX_PATH,MEM_RELEASE); CloseHandle(hProc); std::cout << "Hook Complete, goodbye!\n"; Sleep(4000); return 0; }
void InjectAntihack(HANDLE hProc) { if (!hProc) throw std::exception("Invalid process handle"); HMODULE hModule = GetModuleHandleA("kernel32.dll"); if (!hModule) throw std::exception("Could not acquire module of kernel32.dll"); FARPROC pLoadLibrary = GetProcAddress(hModule, "LoadLibraryA"); if (!pLoadLibrary) throw std::exception("Could not acquire address of LoadLibraryA"); const std::string dllName = "antihack.dll"; int size = dllName.length()+1; void* pRemoteAddress = VirtualAllocEx(hProc, 0, size, MEM_COMMIT, PAGE_READWRITE); if (!pRemoteAddress) throw std::exception("Could not allocate remote memory"); if ( !WriteProcessMemory(hProc, pRemoteAddress, (void*)dllName.c_str(), size, 0) ) throw std::exception("Could not write remote string"); HANDLE hThread = CreateRemoteThread(hProc, 0, 0, (LPTHREAD_START_ROUTINE)pLoadLibrary, pRemoteAddress, 0, 0); if (!hThread) throw std::exception("Could not start remote thread"); WaitForSingleObject(hThread, INFINITE); DWORD dwExit = 0; GetExitCodeThread(hThread, &dwExit); if (!dwExit) throw std::exception("Error while loading remote dll"); if ( !VirtualFreeEx(hProc, pRemoteAddress, size, MEM_DECOMMIT) ) throw std::exception("Could not free remote memory"); }
//-------------------------------------------------------------------------- //DLL injection using CreateRemoteThread method //injects a DLL with path dllName into a process with handle proc int InjectDLL(HANDLE proc, char *dllName) { LPVOID RemoteString, LoadLibAddy; if (!proc) return 0; LoadLibAddy = (LPVOID)GetProcAddress(GetModuleHandle("kernel32.dll"), "LoadLibraryA"); RemoteString = (LPVOID)VirtualAllocEx(proc, NULL, strlen(dllName)+1, MEM_RESERVE|MEM_COMMIT, PAGE_READWRITE); WriteProcessMemory(proc, (LPVOID)RemoteString, dllName, strlen(dllName)+1, NULL); HANDLE hThread = CreateRemoteThread( proc, NULL, NULL, (LPTHREAD_START_ROUTINE)LoadLibAddy, (LPVOID)RemoteString, NULL, NULL); if (hThread == INVALID_HANDLE_VALUE) { MessageBoxA(NULL, "Error creating remote thread", "ROPGuard", MB_OK); return 0; } WaitForSingleObject(hThread, INFINITE); // Cleanup VirtualFreeEx(proc, RemoteString, strlen(dllName)+1, MEM_RELEASE); CloseHandle(hThread); return 1; }