/** * main */ int _tmain(int argc, TCHAR* argv[]) { // get path wchar_t buf[MAX_PATH] = { 0 }; ::GetModuleFileName(NULL, buf, MAX_PATH); boost::filesystem::wpath modulePath = boost::filesystem::wpath(buf).parent_path(); // initialize logger logger->initialize(modulePath); logger->debug(L"forge.exe _tmain -> " + modulePath.wstring()); DWORD exitCode = 1; if (argc > 0) { #ifdef _WIN64 bool ret = InjectDLL((DWORD)_wtoi(argv[0]), L"frame64.dll"); #else bool ret = InjectDLL((DWORD)_wtoi(argv[0]), L"frame32.dll"); #endif exitCode = ret ? 0 : 2; } logger->debug(L"forge.exe _tmain exiting -> " + boost::lexical_cast<wstring>(exitCode)); /** * Possible exit codes: * 0 - success * 1 - invalid/missing command line arguments * 2 - DLL injection failed */ return exitCode; }
bool InjectLibRevive(HANDLE hProcess) { #if _WIN64 return InjectDLL(hProcess, "LibRevive64_1.dll"); #else return InjectDLL(hProcess, "LibRevive32_1.dll"); #endif }
// injects dll whose path is given in dllName into proces with PID pid int GuardExistingProcess(int pid, char *dllName) { HANDLE proc = OpenProcess( PROCESS_CREATE_THREAD | PROCESS_VM_READ | PROCESS_VM_WRITE | PROCESS_VM_OPERATION | PROCESS_QUERY_INFORMATION, FALSE, pid); if(proc == NULL){ char buf[1024]; wsprintf(buf, "Error: opening process %d, error code %d\n", pid, GetLastError()); WriteLog(buf); return 0; } BOOL parent64, child64; IsWow64Process(GetCurrentProcess(), &parent64); IsWow64Process(proc, &child64); if(parent64 != child64){ WriteLog("Error: Current version of ROPGuard cannot protect 64-bit processes"); }else{ InjectDLL(proc, dllName); } CloseHandle(proc); return 1; }
bool Injector::Inject(DWORD processID) { HANDLE process = ::OpenProcess(PROCESS_ALL_ACCESS, FALSE, processID); if(!process) { return false; } std::vector<HANDLE> threads; EnumerateThreads(process, [&](DWORD tid){ if(HANDLE thread=::OpenThread(THREAD_ALL_ACCESS, FALSE, tid)) { ::SuspendThread(thread); threads.push_back(thread); } }); { HMODULE kernel32 = ::GetModuleHandleA(KernelDLLFileName); HMODULE tkernel32 = FindModule(process, KernelDLLFileName); void *base = ::GetProcAddress(kernel32, "SetUnhandledExceptionFilter"); void *tbase = (void*) ((size_t)tkernel32+((size_t)base-(size_t)kernel32)); SetThreadTrap(process, tbase); } std::for_each(threads.begin(), threads.end(), [](HANDLE thread){ ::ResumeThread(thread); }); std::string dll_path = std::getenv("USERPROFILE"); dll_path += AddInDir; dll_path += MLBDllFileName; bool result = InjectDLL(process, dll_path.c_str()); ::CloseHandle(process); return result; }
//-------------------------------------------------------------------------- // injects dll whose path is given in dllName into process with PID pid int GuardExistingProcess(int pid, char *dllName) { HANDLE proc; proc = OpenProcess(PROCESS_CREATE_THREAD | PROCESS_VM_READ |PROCESS_VM_WRITE | PROCESS_VM_OPERATION | PROCESS_QUERY_INFORMATION , FALSE, pid); if (!proc) { printf("Error opening process %d, error code %d\n", pid, GetLastError()); return 0; } BOOL parent64,child64; IsWow64Process(GetCurrentProcess(),&parent64); IsWow64Process(proc, &child64); if(parent64 != child64) { MessageBoxA(NULL, "Current version of ROPGuard cannot protect 64-bit processes.\nThe process will NOT be protected.", "ROPGuard", MB_OK); } else { InjectDLL(proc, dllName); } CloseHandle(proc); return 1; }
static bool LoadOldblivion(PROCESS_INFORMATION * info) { bool result = false; HANDLE syncEvent = CreateEvent(NULL, 0, 0, "OldblivionInjectionCompleted"); if(syncEvent) { if(InjectDLL(info, "oldblivion.dll", false)) { switch(WaitForSingleObject(syncEvent, g_options.m_threadTimeout)) { case WAIT_OBJECT_0: _MESSAGE("oldblivion loaded"); result = true; break; case WAIT_ABANDONED: _ERROR("LoadOldblivion: waiting for oldblivion = WAIT_ABANDONED"); break; case WAIT_TIMEOUT: _ERROR("LoadOldblivion: waiting for oldblivion = WAIT_TIMEOUT"); break; } } else _ERROR("couldn't inject oldblivion dll"); CloseHandle(syncEvent); } else _ERROR("couldn't create oldblivion sync event (%d)", GetLastError()); return result; }
int InjectDLLtoNewProcess(TCHAR *szCommandLine, TCHAR *szDllPath) { STARTUPINFO si; PROCESS_INFORMATION pi; ZeroMemory(&si, sizeof(STARTUPINFO)); si.cb = sizeof(STARTUPINFO); BOOL bResult = CreateProcess(NULL, szCommandLine, NULL, NULL, FALSE, CREATE_SUSPENDED, NULL, NULL, &si, &pi); if(bResult == FALSE) return -1; int nRet = -1; /* BOOL bJudgeWow64; IsWow64Process(pi.hProcess, &bJudgeWow64); if(bJudgeWow64 == FALSE) goto _Exit; */ if(InjectDLL(pi.hProcess, szDllPath)) goto _Exit; nRet = 0; _Exit: ResumeThread(pi.hThread); CloseHandle(pi.hThread); CloseHandle(pi.hProcess); return nRet; }
int main(int argc, char* argv[]) { char dllPath[MAXLINE] = ""; unsigned int pid = 0; unsigned int injResult; unsigned char attackType = 0; unsigned char numargs = 4; char *usageString = "Syringe v1.2\nA General Purpose DLL & Code Injection Utility\n\nUsage:\n\nInject DLL:\n\tsyringe.exe -1 [ dll ] [ pid ]\n\nInject Shellcode:\n\tsyringe.exe -2 [ shellcode ] [ pid ]\n\nExecute Shellcode:\n\tsyringe.exe -3 [ shellcode ]\n"; if (argc < 2) { printf("%s", usageString); return 0; } if (strncmp(argv[1], "-1", 2) == 0) { attackType = ATTACK_TYPE_DLL_INJECTION; } else if (strncmp(argv[1], "-2", 2) == 0) { attackType = ATTACK_TYPE_SHELL_CODE_INJECTION; } else if (strncmp(argv[1], "-3", 2) == 0) { attackType = ATTACK_TYPE_EXECUTE_SHELL_CODE; numargs = 3; } else { printf("%s", usageString); return 0; } if (argc != numargs) { printf("%s", usageString); return 0; } if ((attackType == ATTACK_TYPE_DLL_INJECTION) || (attackType == ATTACK_TYPE_SHELL_CODE_INJECTION)) { pid = atoi(argv[3]); if (!pid) { printf("Invalid Process ID.\n"); return 0; } if (attackType == ATTACK_TYPE_DLL_INJECTION) { GetFullPathNameA(argv[2], MAXLINE, dllPath, NULL); injResult = InjectDLL(dllPath, pid); } else if (attackType == ATTACK_TYPE_SHELL_CODE_INJECTION) { injResult = InjectShellcode(argv[2], pid); } if (injResult == 0) { printf("Successfully Injected.\n"); } else { printf("Failed To Inject. \nError: "); switch (injResult) { case 1: { printf("Invalid Process ID.\n"); break; } case 2: { printf("Could Not Open A Handle To The Process.\n"); break; } case 3: { printf("Could Not Get The Address Of LoadLibraryA.\n"); break; } case 4: { printf("Could Not Allocate Memory In Remote Process.\n"); break; } case 5: { printf("Could Not Write To Remote Process.\n"); break; } case 6: { printf("Could Not Start The Remote Thread.\n"); break; } } } } else if (attackType == ATTACK_TYPE_EXECUTE_SHELL_CODE) { ExecuteShellcode(argv[2]); } return 0; }
int main(int argc, char* argv[]) { // nice title :) SetConsoleTitle("SzimatSzatyor, WoW injector sniffer"); // some info printf("Welcome to SzimatSzatyor2, a WoW injector sniffer.\n"); printf("SzimatSzatyor2 is distributed under the GNU GPLv3 license.\n"); printf("Source code is available at: "); printf("https://github.com/ChipLeo/SzimatSzatyor\n\n"); if (argc > 2) { printf("ERROR: Invalid parameters. "); printf("\"szatyor.exe [wow_exe_name]\" should be used.\n\n"); system("pause"); return 0; } // custom process' name else if (argc == 2) lookingProcessName[0] = std::string(argv[1]); // this process will be injected DWORD processID = SelectProcess(); if (!processID) return 0; // stores where the injector is, so location/path of the current process char injectorPath[MAX_PATH] = { 0 }; // gets where the injector is DWORD injectorPathSize = GetModuleFileName(NULL, injectorPath, MAX_PATH); if (!injectorPathSize) { printf("ERROR: Can't get the injector's path, "); printf("ErrorCode: %u\n\n", GetLastError()); system("pause"); return 0; } // full path of the DLL char* dllPath = new char[MAX_PATH]; // copies injector's full path to dllPath strncpy_s(dllPath, MAX_PATH, injectorPath, injectorPathSize); // some magic to replace path/szatyor.exe to path/szimat.dll // removes injector's name PathRemoveFileSpec(dllPath); // appends DLL's name PathAppend(dllPath, injectDLLName); printf("DLL: %s\n", dllPath); if (InjectDLL(processID, dllPath)) printf("\nInjection of '%s' is successful.\n\n", injectDLLName); else printf("\nInjection of '%s' is NOT successful.\n\n", injectDLLName); delete[] dllPath; //system("pause"); return 0; }
int _tmain(int argc, _TCHAR* argv[]) { if( argc != 4 ) { printf( "Format command:\n\tInjectDLL.exe 'Name process' 'Path Dll' 'Name func dll'"); return 0; } if( InjectDLL( argv[1], argv[2], argv[3] ) ) return 0; return 1; }
// Find the name of the DLL and inject it. void Inject( LPPROCESS_INFORMATION ppi ) { DWORD len; WCHAR dll[MAX_PATH]; len = GetModuleFileName( NULL, dll, lenof(dll) ); while (dll[len-1] != '\\') --len; lstrcpy( dll + len, L"ANSI" BITS L".dll" ); InjectDLL( ppi, dll ); }
//This function is used for SetWindowsHookEx injections //The function is the required callback function LRESULT __stdcall hookProc(int code, WPARAM wParam, LPARAM lParam) { //Just display some MessageBoxes, to show that the call was successful. MessageBoxW(nullptr, L"Test", L"Test", MB_OK); //Start the async thread if (hRemoteThread == nullptr) { InjectDLL(); } //Pass on the hook, so other registered hooks continue working return CallNextHookEx(nullptr, code, wParam, lParam); }
bool InjectDLL(HANDLE hProcess, const char *dllName) { char dllPath[MAX_PATH]; char *cwd; if ((cwd = _getcwd(NULL, 0)) == NULL) { printf("Failed to get cwd\n"); return false; } #if _WIN64 snprintf(dllPath, sizeof(dllPath), "%s\\x64\\%s", cwd, dllName); #else snprintf(dllPath, sizeof(dllPath), "%s\\x86\\%s", cwd, dllName); #endif int dllPathLength = sizeof(dllPath); return InjectDLL(hProcess, dllPath, dllPathLength); }
//-------------------------------------------------------------------------- // creates a new process with command given in commandLine and injects dll whose path is dllName into it int CreateProcessWithDll( char *commandLine, char *dllName, bool patchEntryPoint) { STARTUPINFO startupinfo; PROCESS_INFORMATION processinfo; ZeroMemory(&startupinfo, sizeof(startupinfo)); startupinfo.cb = sizeof(startupinfo); ZeroMemory(&processinfo, sizeof(processinfo)); if (!CreateProcess(NULL, commandLine, NULL, NULL, FALSE, CREATE_SUSPENDED, NULL, NULL, &startupinfo, &processinfo)) { printf("Error creating process (%d)\n", GetLastError()); return 0; } BOOL parent64,child64; IsWow64Process(GetCurrentProcess(), &parent64); IsWow64Process(processinfo.hProcess, &child64); if (parent64 != child64) { MessageBoxA(NULL, "Current version of ROPGuard cannot protect 64-bit processes.\n" "The process will NOT be protected.", "ROPGuard", MB_OK); } else { if (patchEntryPoint) PatchEntryPoint(processinfo.hProcess, processinfo.hThread, dllName); else InjectDLL(processinfo.hProcess, dllName); } // resume normal execution ResumeThread(processinfo.hThread); // cleanup CloseHandle(processinfo.hThread); CloseHandle(processinfo.hProcess); return 1; }
FrameProxy::FrameProxy(const wstring& uuid, HINSTANCE instance, HWND toolbar, HWND target, const wstring& title, const wstring& icon) : uuid(uuid), isOnline(false), m_commandChannel(NULL), m_messageChannel(NULL), m_toolbar(toolbar) { logger->debug(L"FrameProxy::FrameProxy" L" -> " + uuid + L" -> " + title + L" -> " + icon + L" -> " + boost::lexical_cast<wstring>(instance)+ L" -> " + boost::lexical_cast<wstring>(toolbar)+ L" -> " + boost::lexical_cast<wstring>(target)); DWORD processId = 0; ::GetWindowThreadProcessId(toolbar, &processId); if (processId == ::GetCurrentProcessId()) { logger->debug(L"FrameProxy::FrameProxy invoking FrameServer::load directly" L" -> " + uuid + L" -> " + title + L" -> " + icon); FrameServer::AddRef(); m_frameServer = FrameServer::GetInstance(); m_frameServer->load(toolbar, target, uuid, title, icon, ::GetCurrentProcessId(), (INT_PTRX)this); isOnline = true; return; } m_frameServer = nullptr; m_commandChannel = new Channel(L"IeBarListner", processId); m_messageChannel = new Channel(L"IeBarMsgPoint", ::GetCurrentProcessId()); if (m_messageChannel->IsFirst()) { HANDLE thread = ::CreateThread(NULL, 0, MessageHandlerListener, m_messageChannel, 0, NULL); ::CloseHandle(thread); } isOnline = m_commandChannel->IsFirst() ? InjectDLL(instance, processId) : true; // already conencted if (isOnline && uuid != L"NativeControls") { // @ugly logger->debug(L"FrameProxy::FrameProxy sending LoadCommand message"); LoadCommand command(reinterpret_cast<HWNDX>(toolbar), reinterpret_cast<HWNDX>(target), uuid, title, icon, ::GetCurrentProcessId(), (INT_PTRX)this); m_commandChannel->Write(&command, sizeof(command)); } }
int WINAPI mWinMain (HINSTANCE hInstance, HINSTANCE hPrevInstance, PSTR szCmdParam, int iCmdShow) { //if (!stricmp(szCmdParam, "-n")) //phc //editnpc = 1; //if (!stricmp(szCmdParam, "-r")) //phc random = 1; //phc // First check to see if the file exists. // while (GetFileAttributesA("cityofheroes.exe") == INVALID_FILE_ATTRIBUTES) { PromptUserForCohLocation(); } STARTUPINFO startup; memset(&startup, 0, sizeof(startup)); startup.cb = sizeof(STARTUPINFO); memset(&pinfo, 0, sizeof(pinfo)); if(!CreateProcessA("cityofheroes.exe", "cityofheroes.exe -project coh -noverify", NULL, NULL, FALSE, CREATE_NEW_PROCESS_GROUP | CREATE_SUSPENDED | DETACHED_PROCESS, NULL, NULL, (LPSTARTUPINFOA)&startup, &pinfo)) { MessageBoxA(NULL, "Failed to launch process!", "Error", MB_OK | MB_ICONEXCLAMATION); return 0; } // delete old crap previous version used BOOL blAtr = GetFileAttributesA("data\\charcreate.txt"); if (blAtr) DeleteFileA("data\\charcreate.txt"); RunPatch(); //Inject my Dll DWORD dwPID = pinfo.dwProcessId ; m_hTargetProcess = OpenProcess(PROCESS_ALL_ACCESS, FALSE, dwPID); InjectDLL(_T("HookCostume.dll")); CloseHandle(m_hTargetProcess); ResumeThread(pinfo.hThread); return 0; }
// creates a new process with command given in commandLine and injects dll whose path is dllName into it int CreateNewGuardedProcess(char *commandLine, char *dllName, bool patchEntryPoint) { STARTUPINFO startupinfo; PROCESS_INFORMATION processinfo; ZeroMemory(&startupinfo, sizeof(startupinfo)); startupinfo.cb = sizeof(startupinfo); ZeroMemory(&processinfo, sizeof(processinfo)); BOOL result = CreateProcess( NULL, commandLine, NULL, NULL, FALSE, CREATE_SUSPENDED, NULL, NULL, &startupinfo, &processinfo); if(!result){ char buf[1024]; wsprintf(buf, "Error: creating process (%d)", GetLastError()); WriteLog(buf); return 0; } BOOL parent64, child64; IsWow64Process(GetCurrentProcess(), &parent64); IsWow64Process(processinfo.hProcess, &child64); if(parent64 != child64){ WriteLog("Error: Current version of ROPGuard cannot protect 64-bit processes"); }else{ if(patchEntryPoint){ PatchEntryPoint(processinfo.hProcess, processinfo.hThread, dllName); }else{ InjectDLL(processinfo.hProcess, dllName); } } // resume normal execution ResumeThread(processinfo.hThread); // cleanup CloseHandle(processinfo.hThread); CloseHandle(processinfo.hProcess); return 1; }
int InjectDLLtoExistedProcess(DWORD dwPid, TCHAR *szDllPath) { HANDLE hProcess = OpenProcess( PROCESS_CREATE_THREAD | PROCESS_VM_READ | PROCESS_VM_WRITE | PROCESS_VM_OPERATION | PROCESS_QUERY_INFORMATION , FALSE, dwPid); if(hProcess == NULL) return -1; /* BOOL bJudgeWow64; IsWow64Process(hProcess, &bJudgeWow64); if(bJudgeWow64 == FALSE){ CloseHandle(hProcess); return -1; } */ if(InjectDLL(hProcess, szDllPath)) return -1; CloseHandle(hProcess); return 0; }
//Entry point function, called after DLL was mapped to memory BOOL APIENTRY DllMain(HMODULE hModule, DWORD fdwReason, LPVOID lpReserved) { //Detect if the DLL was loaded into chrome.exe WCHAR applicationPath[MAX_PATH + 1]; auto len = GetModuleFileNameW(nullptr, applicationPath, MAX_PATH); if (len > 0) { std::wstring applicationString(applicationPath); auto found = applicationString.find_last_of(L"/\\"); if (applicationString.substr(found + 1) != L"chrome.exe") { //It wasn't -> do nothing return TRUE; } } else { //Couldn't get process name - exit! return TRUE; } //This is a chrome.exe process, start "hijack" / malware activity switch (fdwReason) { case DLL_PROCESS_ATTACH: //Only start a new thread if there's no existing one if (hThisDll == nullptr && lpReserved == nullptr) { hThisDll = hModule; InjectDLL(); } break; case DLL_PROCESS_DETACH: break; } return TRUE; }
int main(int argc, char* argv[]) { CHAR pDllPath[MAXLINE] = ""; DWORD dwPid = 0; DWORD dwResult = 0; DWORD dwAttackType = 0; DWORD dwNumArgs = 4; PBYTE pShellcode = NULL; DWORD dwShellcodeLength = 0; printf("%s\n", APPLICATION_NAME); if (argc < 2) { printf(USAGE_STRING); return 0; } if (strncmp(argv[1], "-1", 2) == 0) { dwAttackType = ATTACK_TYPE_DLL_INJECTION; } else if (strncmp(argv[1], "-2", 2) == 0) { dwAttackType = ATTACK_TYPE_SHELL_CODE_INJECTION; } else if (strncmp(argv[1], "-3", 2) == 0) { dwAttackType = ATTACK_TYPE_EXECUTE_SHELL_CODE; dwNumArgs = 3; } else { printf(USAGE_STRING); return 0; } if (argc != dwNumArgs) { printf(USAGE_STRING); return 0; } if ((dwAttackType == ATTACK_TYPE_SHELL_CODE_INJECTION) || (dwAttackType == ATTACK_TYPE_EXECUTE_SHELL_CODE)) { if (!CryptStringToBinaryA(argv[2], 0, CRYPT_STRING_BASE64, pShellcode, &dwShellcodeLength, 0, NULL)) { printf("Failed to decode the provided shellcode\n"); return 0; } pShellcode = (PBYTE)HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, dwShellcodeLength); if (pShellcode == NULL) { printf("Failed to allocate space for the shellcode\n"); return 0; } if (!CryptStringToBinaryA(argv[2], 0, CRYPT_STRING_BASE64, pShellcode, &dwShellcodeLength, 0, NULL)) { printf("Failed to decode the provided shellcode\n"); return 0; } } if ((dwAttackType == ATTACK_TYPE_DLL_INJECTION) || (dwAttackType == ATTACK_TYPE_SHELL_CODE_INJECTION)) { dwPid = atoi(argv[3]); if (!dwPid) { printf("Invalid Process ID.\n"); return 0; } if (dwAttackType == ATTACK_TYPE_DLL_INJECTION) { GetFullPathNameA(argv[2], MAXLINE, pDllPath, NULL); dwResult = InjectDLL(pDllPath, dwPid); } else if (dwAttackType == ATTACK_TYPE_SHELL_CODE_INJECTION) { dwResult = InjectShellcode(pShellcode, (SIZE_T)dwShellcodeLength, dwPid); } if (dwResult == 0) { printf("Successfully Injected.\n"); } else { printf("Failed To Inject.\nError: "); switch (dwResult) { case 1: { printf("Invalid Process ID.\n"); break; } case 2: { printf("Could Not Open A Handle To The Process.\n"); break; } case 3: { printf("Could Not Get The Address Of LoadLibraryA.\n"); break; } case 4: { printf("Could Not Allocate Memory In Remote Process.\n"); break; } case 5: { printf("Could Not Write To Remote Process.\n"); break; } case 6: { printf("Could Not Start The Remote Thread.\n"); break; } } } } else if (dwAttackType == ATTACK_TYPE_EXECUTE_SHELL_CODE) { ExecuteShellcode(pShellcode, (SIZE_T)dwShellcodeLength, FALSE); } if (pShellcode) { HeapFree(GetProcessHeap(), 0, pShellcode); } return 0; }
int main() { std::string dll_name = "sniffer.dll"; std::string exe_name = "process.exe"; if(!CheckWindowsVersion()) { THROW_ERROR("The system does not meet the requirements (should be XP or later)!"); ps::Error::Print(); system("PAUSE"); return EXIT_FAILURE; } DWORD process_id = GetProcessIdFromExe(exe_name); if(process_id == 0) { THROW_ERROR("Could not find process if by the name of the executable!"); ps::Error::Print(); system("PAUSE"); return EXIT_FAILURE; } printf("Process id: %u\n", process_id); HMODULE module = NULL; if(!InjectDLL(process_id, dll_name, &module)) { THROW_ERROR("DLL injection failed!\n"); ps::Error::Print(); system("PAUSE"); return EXIT_FAILURE; } printf("DLL successfully injected!\n"); ps::Pipe client; bool rv = client.InitializeClient("packet_sniffer_pipe_42"); CHECK(rv == true); rv = client.Connect(); CHECK(rv == true); printf("Connected to server via pipe!\n"); std::vector<char> message; rv = client.ReadMessage(&message); if(rv == false) { ps::Error::Print(); system("PAUSE"); return EXIT_FAILURE; } //printf("%u\n", message.size()); CHECK(message.size() == 1); CHECK(message[0] == 0); /*client.ReadMessage(&message); std::string packet(message.begin(), message.end()); printf("Received: '%s'\n", packet.c_str());*/ rv = client.FinalizeClient(); CHECK(rv == true); system("PAUSE"); if(!EjectDLL(process_id, module)) { THROW_ERROR("DLL ejection failed!\n"); ps::Error::Print(); system("PAUSE"); return EXIT_FAILURE; } printf("DLL successfully ejected!\n"); system("PAUSE"); return EXIT_SUCCESS; }
int main(int argc, char* argv[]) { // nice title :) SetConsoleTitle("SzimatSzatyor, WoW injector sniffer"); // some info printf("Welcome to SzimatSzatyor, a WoW injector sniffer.\n"); printf("SzimatSzatyor is distributed under the GNU GPLv3 license.\n"); printf("Source code is available at: "); printf("http://github.com/Konctantin/SzimatSzatyor\n\n"); if (argc > 3) { printf("ERROR: Invalid parameters. "); printf("\"szatyor.exe [wow_exe_name] [dll_name]\" should be used.\n\n"); system("pause"); return 0; } // custom process' name else if (argc > 1) lookingProcessName = argv[1]; else if (argc > 2) injectDLLName = argv[2]; // this process will be injected DWORD processID = 0; // tries to get the PIDs PIDList& pids = GetProcessIDsByName(lookingProcessName); if (pids.empty()) { printf("'%s' process NOT found.\n", lookingProcessName); printf("Note: be sure the process which you looking for "); printf("is must be a 32 bit process.\n\n"); system("pause"); return 0; } // just one PID found else if (pids.size() == 1) { processID = pids.front(); printf("'%s' process found, PID: %u\n", lookingProcessName, processID); // checks this process is already injected or not if (IsProcessAlreadyInjected(processID, injectDLLName)) { printf("Process is already injected.\n\n"); system("pause"); return 0; } } // size > 1, multiple possible processes else { printf("Multiple '%s' processes found.\n", lookingProcessName); printf("Please select one which will be injected.\n\n"); // stores the PIDs which are already injected // so these are "invalid" PIDList injectedPIDs; unsigned int idx = 1; for (PIDList_ConstItr itr = pids.begin(); itr != pids.end(); ++itr) { DWORD pid = *itr; printf("[%u] PID: %u\n", idx++, pid); if (IsProcessAlreadyInjected(pid, injectDLLName)) { printf("Already injected!\n\n"); injectedPIDs.push_back(pid); } } // same size: there is no non-injected PID if (pids.size() == injectedPIDs.size()) { printf("All the processes are already injected.\n\n"); system("pause"); return 0; } unsigned int selectedIndex = 0; // loops until has correct PID while (1) { processID = 0; selectedIndex = 0; printf("Please select a process, use [index]: "); scanf("%u", &selectedIndex); // bigger than max index if (selectedIndex > idx - 1) { printf("Your index is too big, max index is %u.\n", idx - 1); continue; } // 0 or non int used else if (selectedIndex == 0) { printf("Your index is invalid, 1-%u should be used.\n", idx - 1); continue; } // gets PID via index PIDList_ConstItr itr = pids.begin(); std::advance(itr, selectedIndex - 1); processID = *itr; // if already injected if (std::find(injectedPIDs.begin(), injectedPIDs.end(), processID) != injectedPIDs.end()) { printf("This process is already injected. "); printf("Please choose a different one.\n"); continue; } // looks like all good break; } printf("\n"); } // stores where the injector is, so location/path of the current process char injectorPath[MAX_PATH] = { 0 }; // gets where the injector is DWORD injectorPathSize = GetModuleFileName(NULL, injectorPath, MAX_PATH); if (!injectorPathSize) { printf("ERROR: Can't get the injector's path, "); printf("ErrorCode: %u\n\n", GetLastError()); system("pause"); return 0; } // full path of the DLL char* dllPath = new char[MAX_PATH]; // copies injector's full path to dllPath strncpy_s(dllPath, MAX_PATH, injectorPath, injectorPathSize); // some magic to replace path/szatyor.exe to path/szimat.dll // removes injector's name PathRemoveFileSpec(dllPath); // appends DLL's name PathAppend(dllPath, injectDLLName); printf("DLL: %s\n", dllPath); if (InjectDLL(processID, dllPath)) { printf("\nInjection of '%s' is successful.\n\n", injectDLLName); } else { printf("\nInjection of '%s' is NOT successful.\n\n", injectDLLName); system("pause"); } delete[] dllPath; //system("pause"); return 0; }
//-------------------------------------------------------------------------- // a function that will replace CreateProcessInternalW // gets called whenever a process creates a child process DWORD WINAPI CreateProcessInternalGuarded( __in DWORD unknown1, // always (?) NULL __in_opt LPCTSTR lpApplicationName, __inout_opt LPTSTR lpCommandLine, __in_opt LPSECURITY_ATTRIBUTES lpProcessAttributes, __in_opt LPSECURITY_ATTRIBUTES lpThreadAttributes, __in BOOL bInheritHandles, __in DWORD dwCreationFlags, __in_opt LPVOID lpEnvironment, __in_opt LPCTSTR lpCurrentDirectory, __in LPSTARTUPINFO lpStartupInfo, __out LPPROCESS_INFORMATION lpProcessInformation, __in DWORD unknown2 // always (?) NULL ) { DWORD ret; DWORD newCreationFlags; //MessageBoxA(NULL, "Creating new process", "ROPGuard", MB_OK); //start new process in suspended state to inject dll into it newCreationFlags = dwCreationFlags | CREATE_SUSPENDED; ret = (*CreateProcessInternalOriginal)(unknown1, lpApplicationName, lpCommandLine, lpProcessAttributes, lpThreadAttributes, bInheritHandles, newCreationFlags, lpEnvironment, lpCurrentDirectory, lpStartupInfo, lpProcessInformation, unknown2); if(!ret) return ret; BOOL parent64,child64; IsWow64Process(GetCurrentProcess(),&parent64); IsWow64Process(lpProcessInformation->hProcess,&child64); if (parent64 != child64) { //MessageBoxA(NULL, "Current version of ROPGuard cannot protect 64-bit processes.\nThe process will NOT be protected.", "ROPGuard", MB_OK); if((dwCreationFlags&CREATE_SUSPENDED)==0) ResumeThread(lpProcessInformation->hThread); return ret; } //get the path of the ropguard dll char dllpath[1000]; HMODULE dllhandle; dllhandle = GetModuleHandle("ropguarddll.dll"); if((!dllhandle) || (!GetModuleFileName(dllhandle, dllpath, _countof(dllpath)-1))) { MessageBoxA(NULL, "Warning: could not obtain ropguarddll path", "ROPGuard", MB_OK); if((dwCreationFlags&CREATE_SUSPENDED)==0) ResumeThread(lpProcessInformation->hThread); return ret; } //MessageBoxA(NULL, dllpath, "ROPGuard", MB_OK); // inject ropguard dll into the newly created process if (((dwCreationFlags&CREATE_SUSPENDED)==0)&&(GetROPSettings()->waitEntryPoint)) { PatchEntryPoint(lpProcessInformation->hProcess, lpProcessInformation->hThread, dllpath); } else { InjectDLL(lpProcessInformation->hProcess, dllpath); } //resume process if necessary if((dwCreationFlags&CREATE_SUSPENDED)==0) ResumeThread(lpProcessInformation->hThread); return ret; }
//-------------------------------------------------------------------------- // patches the entry point of the main thread to go into infinite loop // dll is injected when this loop is reached, // after which the old entry point data is restored int PatchEntryPoint(HANDLE proc, HANDLE thread, char *dllName) { DWORD entryPoint; DWORD oldProtect1,oldProtect2; unsigned char oldHeader[2]; unsigned char newHeader[2]; CONTEXT context; entryPoint = GetEntryPoint(proc); if (!entryPoint) { printf("Error getting entry point\n"); return 0; } // make entry point writeable VirtualProtectEx(proc, (LPVOID)entryPoint, 2, PAGE_EXECUTE_READWRITE, &oldProtect1); //store 2 bytes from entry point if (!ReadProcessMemory(proc, (LPCVOID)(entryPoint),oldHeader, 2, NULL)) { printf("Error reading data from entry point"); return 0; } // JMP -2 newHeader[0] = 0xEB; newHeader[1] = 0xFE; // patch entry point to go into infinite loop if (!WriteProcessMemory(proc, (LPVOID)(entryPoint),newHeader, 2, NULL)) { printf("Error writing to entry point"); return 0; } ResumeThread(thread); // wait until entry point is reached while (true) { Sleep(100); context.ContextFlags = CONTEXT_CONTROL; GetThreadContext(thread, &context); if (context.Eip == entryPoint) break; } InjectDLL(proc, dllName); SuspendThread(thread); // return original code to entry point if (!WriteProcessMemory(proc, (LPVOID)(entryPoint),oldHeader, 2, NULL)) { printf("Error writing to entry point"); return 0; } // restore protection VirtualProtectEx(proc, (LPVOID)entryPoint, 2, oldProtect1, &oldProtect2); return 1; }
bool InjectOpenVR(HANDLE hProcess) { return InjectDLL(hProcess, "openvr_api.dll"); }
// a function that will replace CreateProcessInternalW // gets called whenever a process creates a child process DWORD WINAPI CreateProcessInternalGuarded( __in DWORD unknown1, // always (?) NULL __in_opt LPCTSTR lpApplicationName, __inout_opt LPTSTR lpCommandLine, __in_opt LPSECURITY_ATTRIBUTES lpProcessAttributes, __in_opt LPSECURITY_ATTRIBUTES lpThreadAttributes, __in BOOL bInheritHandles, __in DWORD dwCreationFlags, __in_opt LPVOID lpEnvironment, __in_opt LPCTSTR lpCurrentDirectory, __in LPSTARTUPINFO lpStartupInfo, __out LPPROCESS_INFORMATION lpProcessInformation, __in DWORD unknown2 // always (?) NULL ) { DWORD ret; DWORD newCreationFlags; // start new process in suspended state to inject dll into it newCreationFlags = dwCreationFlags | CREATE_SUSPENDED; ret = (*CreateProcessInternalOriginal)( unknown1, lpApplicationName, lpCommandLine, lpProcessAttributes, lpThreadAttributes, bInheritHandles, newCreationFlags, lpEnvironment, lpCurrentDirectory, lpStartupInfo, lpProcessInformation, unknown2); if(!ret) return ret; BOOL parent64, child64; IsWow64Process(GetCurrentProcess(), &parent64); IsWow64Process(lpProcessInformation->hProcess, &child64); if(parent64 != child64){ WriteLog("Error: Current version of ROPGuard cannot protect 64-bit processes"); if((dwCreationFlags & CREATE_SUSPENDED) == 0) ResumeThread(lpProcessInformation->hThread); return ret; } // get the path of the ropguard dll char dllpath[2048]; HMODULE dllhandle = GetModuleHandle("ropguard.dll"); if((!dllhandle) || (!GetModuleFileName(dllhandle, dllpath, sizeof(dllpath) - 256))){ WriteLog("Error: could not obtain ropguard.dll path"); if((dwCreationFlags & CREATE_SUSPENDED) == 0) ResumeThread(lpProcessInformation->hThread); return ret; } // inject ropguard dll into the newly created process char buf[1024]; if((dwCreationFlags & CREATE_SUSPENDED) == 0){ wsprintf(buf, "Log: create process PID: %d", lpProcessInformation->dwProcessId); WriteLog(buf); PatchEntryPoint(lpProcessInformation->hProcess, lpProcessInformation->hThread, dllpath); }else{ wsprintf(buf, "Log: create process PID: %d", lpProcessInformation->dwProcessId); WriteLog(buf); InjectDLL(lpProcessInformation->hProcess, dllpath); } // resume process if necessary if((dwCreationFlags & CREATE_SUSPENDED) == 0) ResumeThread(lpProcessInformation->hThread); return ret; }
int WinMain(HINSTANCE hInstance,HINSTANCE hPrevInstance,LPSTR lpCmdLine,int nCmdShow) { //ini = new Ini("Option.INI"); //char* buf = new char[strlen(lpCmdLine)](); //MessageBox (NULL, lpCmdLine, "CmdLine Is", 0) ; // The paramaters depends on what method we wish to use // /K0000USERID/PHPSessionID/0/0/ScreenMode/ResX/ResY // These should be in a class or static. // get username and password set //sprintf(UserID,"%.*s",UserID_Length,"Administrator"); //sprintf(Password,"%.*s",Password_Length,"Password"); //sprintf(ResX,"%.*s",5,ini->GetString("x",ResX_Default).c_str()); //sprintf(ResY,"%.*s",5,ini->GetString("y",ResY_Default).c_str()); // Screen Mode should be 1 for full screen and 2 for window mode 0 could be testing debug stuff //if (ini->GetString("fullscreen","TRUE")=="TRUE") //{ //ScreenMode=1; //} //else //{ //ScreenMode=2; //} // Load screen res and mode from options.ini // Allow setting paramaters // Yeah I know its slightly big but should be big enough //char* LaunchString=new char[strlen(EXEPath)+1+strlen(ClientConnectString)+1+UserID_Length+1+Password_Length+30](); char* LaunchString=new char[255]; //sprintf(LaunchString,"%s %s/%s/%s/0/18/0/%i/%s/%s",EXEPath,ClientConnectString,UserID,Password,ScreenMode,ResX,ResY); if (strlen(lpCmdLine)>0) { sprintf(LaunchString,"%s %s",EXEPath,lpCmdLine); } //sprintf(LaunchString,"TwelveSky.exe alt1games.twelvesky1:/Username/Password/0/0/0/2/1024/768"); HWND hDlg=0; // This would be set to the dialog eventually when we create one STARTUPINFO info={sizeof(info)}; PROCESS_INFORMATION processInfo; //MessageBoxA(0,LaunchString,"Launching with this string",0); if(CreateProcessA(NULL,LaunchString, NULL, NULL, FALSE, CREATE_SUSPENDED, NULL, NULL, &info, &processInfo)) { //ACTCTX actctx = {sizeof(actctx)}; //ZeroMemory(&actctx, sizeof(actctx)); //actctx.cbSize = sizeof(actctx); // //actctx.lpSource = static_cast<LPCSTR>(DLLManifestPath); //HANDLE hActCtx = CreateActCtx( &actctx ); //ULONG_PTR cookie = 0; // Disabled manifest shit //if ( ActivateActCtx( hActCtx, &cookie ) ) //{ // //if (MapRemoteModule(processInfo.dwProcessId,DLLPath)) if (InjectDLL(processInfo.dwProcessId,DLLPath)) { ResumeThread((HANDLE)processInfo.hThread); } else { MessageBox(hDlg,"Cannot inject into TwelveSky.exe\r\nYou may have to run this launcher as Administrator\r\nRight click the shortcut and go Run As Administrator\r\n If this works you can change the preference in the properties.","Error injecting TSX Client!",MB_OK | MB_ICONERROR); // Kill the process if its running TerminateProcess(processInfo.hProcess,1); } // Disabled manifest shit //// Need to do everything in this function here //DeactivateActCtx( 0, cookie ); //ReleaseActCtx( hActCtx ); //} //else //{ // MessageBox(hDlg,"Cannot inject into TwelveSky.exe Unable to find the dll manifest\r\nYou may have to reinstall our files.","Error injecting TSX Client!",MB_OK | MB_ICONERROR); // // Kill the process if its running // TerminateProcess(processInfo.hProcess,1); //} } else { MessageBox(hDlg,"Failed to launch game","Error",MB_OK | MB_ICONERROR); } delete[] LaunchString; // We would call this to exit launcher //PostQuitMessage( 0 ); //delete ini; return 0 ; }
int main(int argc, char ** argv) { gLog.SetPrintLevel(IDebugLog::kLevel_Error); gLog.SetLogLevel(IDebugLog::kLevel_DebugMessage); if(!g_options.Read(argc, argv)) { PrintError("Couldn't read arguments."); g_options.PrintUsage(); return -1; } if(g_options.m_optionsOnly) { g_options.PrintUsage(); return 0; } if(g_options.m_launchCS) _MESSAGE("launching editor"); if(g_options.m_loadOldblivion) _MESSAGE("loading oldblivion"); // create the process STARTUPINFO startupInfo = { 0 }; PROCESS_INFORMATION procInfo = { 0 }; bool dllHasFullPath = false; startupInfo.cb = sizeof(startupInfo); const char * procName = g_options.m_launchCS ? "TESConstructionSet.exe" : "Oblivion.exe"; const char * baseDllName = g_options.m_launchCS ? "obse_editor" : "obse"; if(g_options.m_altEXE.size()) { procName = g_options.m_altEXE.c_str(); _MESSAGE("launching alternate exe (%s)", procName); } if(g_options.m_altDLL.size()) { baseDllName = g_options.m_altDLL.c_str(); _MESSAGE("launching alternate dll (%s)", baseDllName); dllHasFullPath = true; } std::string dllSuffix; ProcHookInfo procHookInfo; if(!TestChecksum(procName, &dllSuffix, &procHookInfo)) { _ERROR("checksum not found"); return -1; } if(procHookInfo.steamVersion) { // ### maybe check for the loader DLL and just CreateProcess("oblivion.exe") if we can? PrintError("You are trying to use a Steam version of Oblivion. Steam users should launch the game through Steam, not by running obse_loader.exe. If OBSE fails to load, go to Steam > Settings > In Game and check the box marked \"Enable Steam community in game\". Please see the instructions in obse_readme.txt for more information."); return 0; } if(g_options.m_crcOnly) return 0; // build dll path std::string dllPath; if(dllHasFullPath) { dllPath = baseDllName; } else { dllPath = GetCWD() + "\\" + baseDllName + "_" + dllSuffix + ".dll"; } _MESSAGE("dll = %s", dllPath.c_str()); // check to make sure the dll exists { IFileStream tempFile; if(!tempFile.Open(dllPath.c_str())) { PrintError("Couldn't find OBSE DLL (%s). Please make sure you have installed OBSE correctly and are running it from your Oblivion folder.", dllPath.c_str()); return -1; } } bool result = CreateProcess( procName, NULL, // no args NULL, // default process security NULL, // default thread security TRUE, // don't inherit handles CREATE_SUSPENDED, NULL, // no new environment NULL, // no new cwd &startupInfo, &procInfo) != 0; // check for Vista failing to create the process due to elevation requirements if(!result && (GetLastError() == ERROR_ELEVATION_REQUIRED)) { // in theory we could figure out how to UAC-prompt for this process and then run CreateProcess again, but I have no way to test code for that PrintError("Vista has decided that launching Oblivion requires UAC privilege elevation. There is no good reason for this to happen, but to fix it, right-click on obse_loader.exe, go to Properties, pick the Compatibility tab, then turn on \"Run this program as an administrator\"."); return -1; } ASSERT_STR_CODE(result, "Launching Oblivion failed", GetLastError()); if(g_options.m_setPriority) { if(!SetPriorityClass(procInfo.hProcess, g_options.m_priority)) _WARNING("couldn't set process priority"); } result = false; if(g_options.m_launchCS) { if(g_options.m_oldInject) { _MESSAGE("using old editor injection method"); // start the process ResumeThread(procInfo.hThread); // CS needs to run its crt0 code before the DLL is attached, this delays until the message pump is running // note that this method makes it impossible to patch the startup code // this is better than Sleep(1000) but still ugly WaitForInputIdle(procInfo.hProcess, 1000 * 10); // too late if this fails result = InjectDLL(&procInfo, dllPath.c_str(), !g_options.m_noSync); if(!result) PrintError("Couldn't inject dll."); } else { _MESSAGE("using new editor injection method"); result = DoInjectDLL_New(&procInfo, dllPath.c_str(), &procHookInfo); if(!result) PrintError("Couldn't inject dll."); // start the process either way ResumeThread(procInfo.hThread); } } else { result = InjectDLL(&procInfo, dllPath.c_str(), !g_options.m_noSync); if(result) { // try to load oldblivion if requested if(g_options.m_loadOldblivion) { result = LoadOldblivion(&procInfo); if(!result) PrintError("Couldn't load oldblivion."); } } else PrintError("Couldn't inject dll."); if(result) { _MESSAGE("launching oblivion"); // start the process ResumeThread(procInfo.hThread); } else { _ERROR("terminating oblivion process"); // kill the partially-created process TerminateProcess(procInfo.hProcess, 0); g_options.m_waitForClose = false; } } // wait for the process to close if requested if(g_options.m_waitForClose) { WaitForSingleObject(procInfo.hProcess, INFINITE); } // clean up CloseHandle(procInfo.hProcess); CloseHandle(procInfo.hThread); return 0; }