예제 #1
1
파일: HookDI.cpp 프로젝트: jeppeter/x360ce
HRESULT STDMETHODCALLTYPE HookCreateDeviceW (LPDIRECTINPUT8W This, REFGUID rguid, LPDIRECTINPUTDEVICE8W * lplpDirectInputDevice, LPUNKNOWN pUnkOuter)
{
    HRESULT hr = oCreateDeviceW(This, rguid, lplpDirectInputDevice, pUnkOuter);

    if(!iHookThis->GetState(iHook::HOOK_DI)) return hr;
    PrintLog(LOG_HOOKDI,"*CreateDeviceW*");

    if(hr != NO_ERROR) return hr;

    if(*lplpDirectInputDevice)
    {
        LPDIRECTINPUTDEVICE8W &ref = *lplpDirectInputDevice;
        if(ref->lpVtbl->GetDeviceInfo)
        {
            hGetDeviceInfoW = ref->lpVtbl->GetDeviceInfo;
            MH_CreateHook(hGetDeviceInfoW,HookGetDeviceInfoW,reinterpret_cast<void**>(&oGetDeviceInfoW));
            if(MH_EnableHook(hGetDeviceInfoW) == MH_OK) PrintLog(LOG_HOOKDI,"Hooking GetDeviceInfoW");
        }

        if(ref->lpVtbl->GetProperty)
        {
            hGetPropertyW = ref->lpVtbl->GetProperty;
            MH_CreateHook(hGetPropertyW,HookGetPropertyW,reinterpret_cast<void**>(&oGetPropertyW));
            if(MH_EnableHook(hGetPropertyW) == MH_OK) PrintLog(LOG_HOOKDI,"Hooking GetPropertyW");
        }
    }

    return hr;
}
예제 #2
1
BOOL WINAPI DllMain( HINSTANCE hinstDLL, DWORD fdwReason, LPVOID lpReserved )  
{
    if( fdwReason == DLL_PROCESS_ATTACH )
    {
        if( MH_Initialize() != MH_OK )
        {
            return FALSE;
        }

        if( MH_CreateHook(&CreateProcessA, &HookedCreateProcessA, reinterpret_cast<void**>(&OrigCreateProcessA)) != MH_OK )
        {
            return FALSE;
        }

        if( MH_EnableHook(&CreateProcessA) != MH_OK )
        {
            return FALSE;
        }

        if( MH_CreateHook(&CreateProcessW, &HookedCreateProcessW, reinterpret_cast<void**>(&OrigCreateProcessW)) != MH_OK )
        {
            return FALSE;
        }

        if( MH_EnableHook(&CreateProcessW) != MH_OK )
        {
            return FALSE;
        }

        if( MH_CreateHook(&ResumeThread, &HookedResumeThread, reinterpret_cast<void**>(&OrigResumeThread)) != MH_OK )
        {
            return FALSE;
        }

        if( MH_EnableHook(&ResumeThread) != MH_OK )
        {
            return FALSE;
        }

        if( MH_CreateHook(&LoadLibraryW, &HookedLoadLibraryW, reinterpret_cast<void**>(&OrigLoadLibraryW)) != MH_OK )
        {
            return FALSE;
        }

        if( MH_EnableHook(&LoadLibraryW) != MH_OK )
        {
            return FALSE;
        }

        HookD3D9(::GetModuleHandleW(L"d3d9.dll"));

        std::wstring moduleFilename = GetModulePath(hinstDLL);
        WstrToUtf8(moduleFilename, &g_moduleFilenameUtf8);
    }
    return TRUE;
}
예제 #3
1
// Hooks a function at a given address given the hook function and trampoline function
BOOL setHook(LPVOID* origAddress, LPVOID* hookFunction, LPVOID* trampFunction)
{
	if (MH_CreateHook(origAddress, hookFunction, reinterpret_cast<LPVOID*>(trampFunction)) != MH_OK)
		return FALSE;

	if (MH_EnableHook(origAddress) != MH_OK)
		return FALSE;

	return TRUE;
}
예제 #4
0
파일: main.cpp 프로젝트: DavidLanz/Revive
BOOL APIENTRY DllMain(HANDLE hModule, DWORD ul_reason_for_call, LPVOID lpReserved)
{
#if defined(_WIN64)
	const char* pBitDepth = "64";
#else
	const char* pBitDepth = "32";
#endif
	switch (ul_reason_for_call)
	{
		case DLL_PROCESS_ATTACH:
			ReviveModule = (HMODULE)hModule;
			swprintf(ovrModuleName, MAX_PATH, L"LibOVRRT%hs_%d.dll", pBitDepth, OVR_MAJOR_VERSION);
			MH_Initialize();
			MH_CreateHook(LoadLibraryW, HookLoadLibrary, (PVOID*)&TrueLoadLibrary);
			MH_CreateHook(OpenEventW, HookOpenEvent, (PVOID*)&TrueOpenEvent);
			MH_CreateHook(GetProcAddress, HookGetProcAddress, (PVOID*)&TrueGetProcAddress);
			MH_EnableHook(LoadLibraryW);
			MH_EnableHook(OpenEventW);
			break;
		case DLL_PROCESS_DETACH:
			MH_RemoveHook(LoadLibraryW);
			MH_RemoveHook(OpenEventW);
			MH_RemoveHook(GetProcAddress);
			MH_Uninitialize();
			break;
		default:
			break;
	}
	return TRUE;
}
예제 #5
0
BOOL APIENTRY DllMain(HANDLE hModule, DWORD ul_reason_for_call, LPVOID lpReserved)
{
#if defined(_WIN64)
	const char* pBitDepth = "64";
#else
	const char* pBitDepth = "32";
#endif
	switch (ul_reason_for_call)
	{
		case DLL_PROCESS_ATTACH:
			ReviveModule = (HMODULE)hModule;
			swprintf(ovrModuleName, MAX_PATH, L"LibOVRRT%hs_%d.dll", pBitDepth, OVR_MAJOR_VERSION);
			swprintf(revModuleName, MAX_PATH, L"LibRevive%hs_%d.dll", pBitDepth, OVR_MAJOR_VERSION);
			swprintf(ovrPlatformName, MAX_PATH, L"LibOVRPlatform%hs_%d", pBitDepth, OVR_MAJOR_VERSION);
			TrueIsError = (_IsError)DetourIATptr("ovr_Message_IsError", ovr_Message_IsError, GetModuleHandle(NULL));
			DetourIATptr("ovr_IsEntitled", ovr_IsEntitled, GetModuleHandle(NULL));
			MH_Initialize();
			MH_CreateHook(LoadLibraryW, HookLoadLibrary, (PVOID*)&TrueLoadLibrary);
			MH_CreateHook(OpenEventW, HookOpenEvent, (PVOID*)&TrueOpenEvent);
			MH_EnableHook(LoadLibraryW);
			MH_EnableHook(OpenEventW);
			break;
		case DLL_PROCESS_DETACH:
			MH_RemoveHook(LoadLibraryW);
			MH_RemoveHook(OpenEventW);
			MH_Uninitialize();
			break;
		default:
			break;
	}
	return TRUE;
}
예제 #6
0
파일: HookDI.cpp 프로젝트: jeppeter/x360ce
HRESULT WINAPI HookDirectInput8Create(HINSTANCE hinst, DWORD dwVersion, REFIID riidltf, LPVOID *ppvOut, LPUNKNOWN punkOuter)
{
    HRESULT hr = oDirectInput8Create(hinst,dwVersion,riidltf,ppvOut,punkOuter);

    if(!iHookThis->GetState(iHook::HOOK_DI)) return hr;
    PrintLog(LOG_HOOKDI,"*DirectInput8Create*");

    if(IsEqualIID(riidltf,IID_IDirectInput8A))
    {
        LPDIRECTINPUT8A pDIA = static_cast<LPDIRECTINPUT8A>(*ppvOut);

        if(pDIA)
        {
            PrintLog(LOG_HOOKDI,"DirectInput8Create - ANSI interface");
            if(pDIA->lpVtbl->CreateDevice)
            {
                hCreateDeviceA = pDIA->lpVtbl->CreateDevice;
                MH_CreateHook(hCreateDeviceA,HookCreateDeviceA,reinterpret_cast<void**>(&oCreateDeviceA));
                if(MH_EnableHook(hCreateDeviceA) == MH_OK) PrintLog(LOG_HOOKDI,"Hooking CreateDeviceA");
            }
            if(pDIA->lpVtbl->EnumDevices)
            {
                hEnumDevicesA = pDIA->lpVtbl->EnumDevices;
                MH_CreateHook(hEnumDevicesA,HookEnumDevicesA,reinterpret_cast<void**>(&oEnumDevicesA));
                if(MH_EnableHook(hEnumDevicesA) == MH_OK) PrintLog(LOG_HOOKDI,"Hooking EnumDevicesA");
            }
        }
    }

    if (IsEqualIID(riidltf,IID_IDirectInput8W))
    {
        LPDIRECTINPUT8W pDIW = static_cast<LPDIRECTINPUT8W>(*ppvOut);

        if(pDIW)
        {
            PrintLog(LOG_HOOKDI,"DirectInput8Create - UNICODE interface");
            if(pDIW->lpVtbl->CreateDevice)
            {
                hCreateDeviceW = pDIW->lpVtbl->CreateDevice;
                MH_CreateHook(hCreateDeviceW,HookCreateDeviceW,reinterpret_cast<void**>(&oCreateDeviceW));
                if(MH_EnableHook(hCreateDeviceW) == MH_OK) PrintLog(LOG_HOOKDI,"Hooking CreateDeviceW");
            }
            if(pDIW->lpVtbl->EnumDevices)
            {
                hEnumDevicesW = pDIW->lpVtbl->EnumDevices;
                MH_CreateHook(hEnumDevicesW,HookEnumDevicesW,reinterpret_cast<void**>(&oEnumDevicesW));
                if(MH_EnableHook(hEnumDevicesW) == MH_OK) PrintLog(LOG_HOOKDI,"Hooking EnumDevicesW");
            }
        }
    }

    return hr;
}
예제 #7
0
파일: HookDI.cpp 프로젝트: jeppeter/x360ce
void iHook::HookDICOM(REFIID riidltf, LPVOID *ppv)
{
    PrintLog(LOG_IHOOK,"Hooking HookDICOM");
    iHookThis = this;

    if(IsEqualIID(riidltf,IID_IDirectInput8A))
    {
        LPDIRECTINPUT8A pDIA = static_cast<LPDIRECTINPUT8A>(*ppv);

        if(pDIA)
        {
            PrintLog(LOG_HOOKDI,"DirectInput8Create - ANSI interface");
            if(pDIA->lpVtbl->CreateDevice)
            {
                hCreateDeviceA = pDIA->lpVtbl->CreateDevice;
                MH_CreateHook(hCreateDeviceA,HookCreateDeviceA,reinterpret_cast<void**>(&oCreateDeviceA));
                if(MH_EnableHook(hCreateDeviceA) == MH_OK) PrintLog(LOG_HOOKDI,"Hooking CreateDeviceA");
            }
            if(pDIA->lpVtbl->EnumDevices)
            {

                hEnumDevicesA = pDIA->lpVtbl->EnumDevices;
                MH_CreateHook(hEnumDevicesA,HookEnumDevicesA,reinterpret_cast<void**>(&oEnumDevicesA));
                if(MH_EnableHook(hEnumDevicesA) == MH_OK) PrintLog(LOG_HOOKDI,"Hooking EnumDevicesA");
            }
        }
    }

    if (IsEqualIID(riidltf,IID_IDirectInput8W))
    {
        LPDIRECTINPUT8W pDIW = static_cast<LPDIRECTINPUT8W>(*ppv);

        if(pDIW)
        {
            PrintLog(LOG_HOOKDI,"DirectInput8Create - UNICODE interface");
            if(pDIW->lpVtbl->CreateDevice)
            {
                hCreateDeviceW = pDIW->lpVtbl->CreateDevice;
                MH_CreateHook(hCreateDeviceW,HookCreateDeviceW,reinterpret_cast<void**>(&oCreateDeviceW));
                if(MH_EnableHook(hCreateDeviceW) == MH_OK) PrintLog(LOG_HOOKDI,"Hooking CreateDeviceW");
            }
            if(pDIW->lpVtbl->EnumDevices)
            {
                hEnumDevicesW = pDIW->lpVtbl->EnumDevices;
                MH_CreateHook(hEnumDevicesW,HookEnumDevicesW,reinterpret_cast<void**>(&oEnumDevicesW));
                if(MH_EnableHook(hEnumDevicesW) == MH_OK) PrintLog(LOG_HOOKDI,"Hooking EnumDevicesW");
            }
        }
    }
}
예제 #8
0
파일: main.cpp 프로젝트: Stal1tm/Revive
BOOL APIENTRY DllMain(HANDLE hModule, DWORD ul_reason_for_call, LPVOID lpReserved)
{
#if defined(_WIN64)
	const char* pBitDepth = "64";
#else
	const char* pBitDepth = "32";
#endif
	switch (ul_reason_for_call)
	{
		case DLL_PROCESS_ATTACH:
			GetModuleFileName((HMODULE)hModule, revModuleName, MAX_PATH);
			swprintf(ovrModuleName, MAX_PATH, L"LibOVRRT%hs_%d.dll", pBitDepth, OVR_MAJOR_VERSION);
			MH_Initialize();
			MH_CreateHook(LoadLibraryW, HookLoadLibrary, (PVOID*)&TrueLoadLibrary);
			MH_CreateHook(OpenEventW, HookOpenEvent, (PVOID*)&TrueOpenEvent);
			MH_CreateHookApi(L"dxgi.dll", "CreateDXGIFactory", HookDXGIFactory, (PVOID*)&DXGIFactory);
			MH_EnableHook(MH_ALL_HOOKS);
			break;
		case DLL_PROCESS_DETACH:
			MH_Uninitialize();
			break;
		default:
			break;
	}
	return TRUE;
}
예제 #9
0
파일: main.cpp 프로젝트: leftas/hookNative
void mainFunction()
{

	MODULEINFO moduleInfo;
	bool bSuccess;
	MH_STATUS status;

	Log::Init();
	
	GetModuleInformation(GetCurrentProcess(), GetModuleHandle(NULL), &moduleInfo, sizeof(MODULEINFO));
	Log::Write(Log::Type::Debug, "Base address is at: %I64X", moduleInfo.lpBaseOfDll);

	funcToHookOn = Pattern::Scan(moduleInfo, "48 89 5C 24 ? 57 48 83 EC 20 44 0F B7 05 ? ? ? ? 33 D2");
	Log::Write(Log::Type::Debug, "The code is found at: %I64X", funcToHookOn);
	
	status = MH_Initialize();

	Log::Write(Log::Type::Debug, "MinHook intialization was: ", status != MH_STATUS::MH_OK ? "Not successful" : "Successful");

	status = MH_CreateHook((void*)funcToHookOn, hkRETURN_NUMBER_OF_RUNNING_SCRIPT, (void**)&oRETURN_NUMBER_OF_RUNNING_SCRIPT);

	Log::Write(Log::Type::Debug, "MinHook hook creation was: ", status != MH_STATUS::MH_OK ? "Not successful" : "Successful");
	
	status = MH_EnableHook((void*)funcToHookOn);

	Log::Write(Log::Type::Debug, "MinHook enable was: ", status != MH_STATUS::MH_OK ? "Not successful" : "Successful");
	
}
예제 #10
0
void HookDefWindowProc()
{
	BOOST_LOG_TRIVIAL(info) << "Hooking USER32!DefWindowProcA (ANSI)";

	if (MH_CreateHookApiEx(L"user32", "DefWindowProcA", &DetourDefWindowProc, &OriginalDefWindowProc) != MH_OK)
	{
		BOOST_LOG_TRIVIAL(error) << "Couldn't hook USER32!DefWindowProcA (ANSI)";
		return;
	}

	BOOST_LOG_TRIVIAL(info) << "Hooking USER32!DefWindowProcW (Unicode)";

	if (MH_CreateHookApiEx(L"user32", "DefWindowProcW", &DetourDefWindowProc, &OriginalDefWindowProc) != MH_OK)
	{
		BOOST_LOG_TRIVIAL(error) << "Couldn't hook USER32!DefWindowProcW (Unicode)";
		return;
	}

	if (MH_EnableHook(MH_ALL_HOOKS) != MH_OK)
	{
		BOOST_LOG_TRIVIAL(error) << "Couldn't enable DefWindowProc hooks";
		return;
	}

	BOOST_LOG_TRIVIAL(info) << "DefWindowProc hooked";
}
예제 #11
0
BOOL APIENTRY DllMain(HANDLE hModule, DWORD fdwReason, LPVOID lpReserved)
{
	switch (fdwReason)
	{
	case DLL_PROCESS_ATTACH:
	{
		MH_Initialize();

		if (GetModuleHandle("dinput8.dll") == NULL)
			LoadLibrary("dinput8.dll");

		MH_CreateHook(GetProcAddress(GetModuleHandle("dinput8.dll"), "DirectInput8Create"), &DirectInput8Create_Hook, reinterpret_cast<void**>(&DirectInput8Create_fn));

		MH_EnableHook(MH_ALL_HOOKS);
	}
		break;

	case DLL_PROCESS_DETACH:
		ExitInstance();

		MH_Uninitialize();

		break;
	}
	return TRUE;
}
예제 #12
0
// main logic
int init()
{
	// initialize hook engine
	if (MH_Initialize() != MH_OK)
	{
		return -1;
	}

	// create kernel32!CreateFileW hook (unicode)
	if (MH_CreateHookApiEx(L"kernel32", "CreateFileW", &DetourCreateFileW, &OriginalCreateFileW) != MH_OK)
	{
		return -2;
	}

	// create kernel32!CreateFileA hook (ANSI)
	if (MH_CreateHookApiEx(L"kernel32", "CreateFileA", &DetourCreateFileA, &OriginalCreateFileA) != MH_OK)
	{
		return -3;
	}

	// enable all hooks
	if (MH_EnableHook(MH_ALL_HOOKS) != MH_OK)
	{
		return -5;
	}

	// block this thread infinitely to keep hooks active
	return WaitForSingleObject(INVALID_HANDLE_VALUE, INFINITE);
}
예제 #13
0
	bool Utility::InstallHook(void *target, void *function, void *original_function) {
		if (MH_CreateHook(target, function, reinterpret_cast<void**>(original_function)) == MH_ERROR_NOT_INITIALIZED) {
			MH_Initialize();
			MH_CreateHook(target, function, reinterpret_cast<void**>(original_function));
		}

		return MH_EnableHook(target) == MH_OK;
	}
예제 #14
0
파일: main.cpp 프로젝트: korha/Portablize
//-------------------------------------------------------------------------------------------------
extern "C" BOOL WINAPI DllEntryPoint(HINSTANCE hInstDll, DWORD fdwReason, LPVOID)
{
    if (fdwReason == DLL_PROCESS_ATTACH)
    {
        DWORD dwTemp = GetModuleFileNameW(nullptr, g_wBuf, MAX_PATH+1);
        if (dwTemp >= 6 && dwTemp < MAX_PATH)
        {
            wchar_t *pDelim = g_wBuf+dwTemp;
            do
            {
                if (*--pDelim == L'\\')
                    break;
            } while (pDelim > g_wBuf);
            if (pDelim >= g_wBuf+4 && pDelim <= g_wBuf+MAX_PATH-g_dwPathMargin)
            {
#ifdef _WIN64
                if (MH_Initialize() == MH_OK &&
                        FCreateHook(RegCreateKeyExW, RegCreateKeyExWStub) &&
                        MH_EnableHook(reinterpret_cast<LPVOID>(RegCreateKeyExW)) == MH_OK &&
                        DisableThreadLibraryCalls(hInstDll))
                {
                    *pDelim = L'\0';
                    return TRUE;
                }
#else
                constexpr const DWORD dwPatchSize = 1+sizeof(size_t);
                BYTE *const pAddress = reinterpret_cast<BYTE*>(RegCreateKeyExW);
                DWORD dwOldProtect;
                if (VirtualProtect(pAddress, dwPatchSize, PAGE_EXECUTE_READWRITE, &dwOldProtect))
                {
                    const size_t szOffset = reinterpret_cast<size_t>(RegCreateKeyExWStub) - (reinterpret_cast<size_t>(pAddress) + dwPatchSize);
                    const BYTE *const pByte = static_cast<const BYTE*>(static_cast<const void*>(&szOffset));
                    pAddress[0] = 0xE9;        //jump near
                    pAddress[1] = pByte[0];
                    pAddress[2] = pByte[1];
                    pAddress[3] = pByte[2];
                    pAddress[4] = pByte[3];
                    if (VirtualProtect(pAddress, dwPatchSize, dwOldProtect, &dwTemp) && DisableThreadLibraryCalls(hInstDll))
                    {
                        *pDelim = L'\0';
                        return TRUE;
                    }
                }
#endif
            }
        }
    }
#ifdef _WIN64
    else if (fdwReason == DLL_PROCESS_DETACH)
        MH_Uninitialize();
#endif
    return FALSE;
}
예제 #15
0
/**
 * @brief Injects redirection code into the target function.
 *
 * @param force No-op in the MinHook-based HardHook implementation.
 */
void HardHook::inject(bool force) {
	if (!force) {
		// MinHook guarantees the presence of a trampoline, so
		// inject() and restore() are no-ops unless force is
		// set to true.
		return;
	}

	MH_STATUS status = MH_EnableHook((LPVOID)m_func);
	if (status != MH_OK) {
		fods("HardHook: inject() failed: MH_EnableHook returned %s", MH_StatusToString(status));
	}
}
예제 #16
0
파일: main.cpp 프로젝트: DavidLanz/Revive
HMODULE WINAPI HookLoadLibrary(LPCWSTR lpFileName)
{
	HMODULE hModule = TrueLoadLibrary(lpFileName);

	// Only enable the GetProcAddress hook when the Oculus Runtime was loaded.
	WCHAR modulePath[MAX_PATH];
	GetModuleFileName(hModule, modulePath, sizeof(modulePath));
	LPCWSTR moduleName = PathFindFileNameW(modulePath);
	if (wcscmp(moduleName, ovrModuleName) == 0)
		MH_EnableHook(GetProcAddress);

	return hModule;
}
예제 #17
0
파일: main.cpp 프로젝트: ema29/TemplePlus
int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int showCmd) {


	// We reserve space for temple.dll as early as possible to avoid rebasing of temple.dll
	auto& dll = temple::Dll::GetInstance();
	dll.ReserveMemoryRange();

	Breakpad breakpad;

	config.Load();
	config.Save();

	InitLogging();

	logger->info("Starting Temple Plus");
	logger->info("Version: {}", GetTemplePlusVersion());
	logger->info("Commit: {}", GetTemplePlusCommitId());

	try {
		bool userCancelled;
		auto toeeDir = GetInstallationDir(&userCancelled);

		if (userCancelled) {
			return 0; // Not an error, the user cancelled
		}

		dll.Load(toeeDir.GetDirectory());

		if (dll.HasBeenRebased()) {
			auto moduleName = dll.FindConflictingModule();
			auto msg = format(L"Module '{}' caused temple.dll to be loaded at a different address than usual.\n"
			                  L"This will most likely lead to crashes.", moduleName);
			MessageBox(nullptr, msg.c_str(), L"Module Conflict", MB_OK | MB_ICONWARNING);
		}

		TempleFixes::apply();

		MH_EnableHook(MH_ALL_HOOKS);

		auto result = TempleMain(hInstance, lpCmdLine);

		config.Save();

		return result;
	} catch (const std::exception& e) {
		logger->error("Uncaught exception: {}", e.what());
		auto msg = format("Uncaught exception: {}", e.what());
		MessageBoxA(nullptr, msg.c_str(), "Fatal Error", MB_OK | MB_ICONERROR);
		return 1;
	}
}
예제 #18
0
MainContext::MainContext()
{
	LogFile("OneTweakNG.log");

	if(config.GetAutoFix()) EnableAutoFix();

	MH_Initialize();

	MH_CreateHook(D3D9DLL::Get().Direct3DCreate9, HookDirect3DCreate9, reinterpret_cast<void**>(&TrueDirect3DCreate9));
	MH_EnableHook(D3D9DLL::Get().Direct3DCreate9);

	MH_CreateHook(CreateWindowExA, HookCreateWindowExA, reinterpret_cast<void**>(&TrueCreateWindowExA));
	MH_EnableHook(CreateWindowExA);

	MH_CreateHook(CreateWindowExW, HookCreateWindowExW, reinterpret_cast<void**>(&TrueCreateWindowExW));
	MH_EnableHook(CreateWindowExW);

	MH_CreateHook(SetWindowLongA, HookSetWindowLongA, reinterpret_cast<void**>(&TrueSetWindowLongA));
	MH_EnableHook(SetWindowLongA);

	MH_CreateHook(SetWindowLongW, HookSetWindowLongW, reinterpret_cast<void**>(&TrueSetWindowLongW));
	MH_EnableHook(SetWindowLongW);
}
예제 #19
0
	AasAnimatedModelFactory::AasAnimatedModelFactory(const AasConfig& config) : mConfig(config) {
		Expects(!sInstance);
		sInstance = this;

		LegacyAasConfig legacyConfig;
		legacyConfig.scaleX = config.scaleX;
		legacyConfig.scaleY = config.scaleY;
		legacyConfig.getSkaFilename = [](int meshId, char* filenameOut) -> AasStatus {
			if (sInstance->mConfig.resolveSkaFile) {
				auto filename(sInstance->mConfig.resolveSkaFile(meshId));
				if (!filename.empty()) {
					Expects(filename.size() < MAX_PATH);
					strncpy(filenameOut, filename.c_str(), MAX_PATH);
					return AAS_OK;
				}
			}
			return AAS_ERROR;
		};
		legacyConfig.getSkmFilename = [](int meshId, char* filenameOut) -> AasStatus {
			if (sInstance->mConfig.resolveSkmFile) {
				auto filename(sInstance->mConfig.resolveSkmFile(meshId));
				if (!filename.empty()) {
					Expects(filename.size() < MAX_PATH);
					strncpy(filenameOut, filename.c_str(), MAX_PATH);
					return AAS_OK;
				}
			}
			return AAS_ERROR;
		};
		legacyConfig.runScript = [](const char* script) {
			if (sInstance->mConfig.runScript) {
				sInstance->mConfig.runScript(script);
			}
		};

		if (functions.Init(&legacyConfig)) {
			throw TempleException("Unable to initialize the animation system.");
		}

		// The MDF resolver is not configurable, so we have to set it here manually
		MH_CreateHook(temple::GetPointer<void*>(0x10269430), &AasResolveMaterial, nullptr);
		MH_CreateHook(functions.Free, &AasFreeModel, (void**)&mOrgModelFree);
		MH_EnableHook(nullptr);

		auto meshesMapping = MesFile::ParseFile("art/meshes/meshes.mes");
		mMapping.insert(meshesMapping.begin(), meshesMapping.end());
		logger->debug("Loaded mapping for {} meshes from art/meshes/meshes.mes", 
			meshesMapping.size());

	}
예제 #20
0
void LSP_InitializeHooks()
{
	HWND shellWindow = GetShellWindow();
	GetWindowThreadProcessId(shellWindow, &explorerPid);

	MH_CreateHookApi(L"kernelbase.dll", "RegOpenKeyExA", ProcessLSPRegOpenKeyExA, (void**)&g_origRegOpenKeyExA);

	if (CoreIsDebuggerPresent())
	{
		MH_CreateHookApi(L"ntdll.dll", "NtQueryInformationProcess", NtQueryInformationProcessHook, (void**)&origQIP);
		MH_CreateHookApi(L"ntdll.dll", "NtClose", NtCloseHook, (void**)&origClose);
	}

	MH_EnableHook(MH_ALL_HOOKS);
}
예제 #21
0
	void AtlDepHook::Install(void)
	{
		if (MH_Initialize() != MH_OK)
		{
			return;
		}

		for(int i = 0; i < s_FunctionsCount; ++i)
		{
			FunctionInfo& info = s_Functions[i];

			if (info.bSucceeded) 
			{
				continue;
			}

			HMODULE hModule = ::LoadLibraryA(info.szFunctionModule);
			if (!hModule)
			{
				DWORD dwErrorCode = ::GetLastError();
				TRACE("[coba] Cannot LoadLibraryA(%s)! GetLastError: %d",info.szFunctionModule, dwErrorCode);
				continue;
			}

			info.pTargetFunction = GetProcAddress(hModule, info.szFunctionName);
			if (info.pTargetFunction == NULL)
			{
				TRACE("[coba] Cannot GetProcAddress of %s", info.szFunctionName);
				continue;
			}
			if (MH_CreateHook(info.pTargetFunction, info.pHookFunction, info.ppOriginalFunction) != MH_OK)
			{
				TRACE("[coba] MH_CreateHook failed! Module: %s  Function: %s", info.szFunctionModule, info.szFunctionName);
				continue;
			}
			// Enable the hook
			if (MH_EnableHook(info.pTargetFunction) != MH_OK)
			{
				TRACE("[coba] MH_EnableHook failed! Module: %s  Function: %s", info.szFunctionModule, info.szFunctionName);
				continue;
			}
			info.bSucceeded = TRUE;
		}

	}
예제 #22
0
파일: Main.cpp 프로젝트: ezhangle/PVZ-Hack
void HookSetCursor()
{
	if (MH_Initialize() == MH_OK)
	{
		if (MH_CreateHook(&SetCursorPos, &hkSetCursor, (void**)&origSetCursor) == MH_OK)
		{
			if (MH_EnableHook(&SetCursorPos) == MH_OK)
			{
				std::cout << "Hook Success \n";
			}else{
				std::cout << "Failed to Enable hook \n";
			}
		}else{
			std::cout << "Failed to Hook \n";
		}
	}else{
		std::cout << "Failed to initialize hook \n";
	}
}
예제 #23
0
void Start()
{
	MH_Initialize();

	hFile = CreateFile
	(
		"Dump.dll",       
		GENERIC_WRITE,       
		0,                   
		NULL,                 
		CREATE_NEW,            
		FILE_ATTRIBUTE_NORMAL,
		NULL
	);

	auto NtWow64WriteVirtualMemory64 = GetProcAddress(LoadLibrary("ntdll.dll"), "NtWow64WriteVirtualMemory64");

	MH_CreateHook(NtWow64WriteVirtualMemory64, &NtWow64WriteVirtualMemory64_h, reinterpret_cast<LPVOID*>(&oNtWow64WriteVirtualMemory64));

	MH_EnableHook(NtWow64WriteVirtualMemory64);
}
예제 #24
0
IPYTHONEMBED_STATUS ipython_embed_start(PyObject* cmdline)
{
    commandline_args = cmdline;

    if (MH_Initialize() != MH_OK) {
        return IPYTHONEMBED_MINHOOK_INIT_FAILED;
    }

    void* qt_eventloop = (void*)eventloop_address();
    if (MH_CreateHook(qt_eventloop,
                     &DetourQEventDispatcherWin32,
                     (LPVOID*)&pQEventDispatcherWin32) != MH_OK) {
        return IPYTHONEMBED_CREATE_HOOK_FAILED;
    }

    if (MH_EnableHook(qt_eventloop) != MH_OK) {
        return IPYTHONEMBED_ENABLE_HOOK_FAILED;
    }

    return IPYTHONEMBED_OK;
}
예제 #25
0
파일: Sample.cpp 프로젝트: FARCACHE/Fire-IE
int main()
{
	// Initialize MinHook.
	if (MH_Initialize() != MH_OK)
	{
		return 1;
	}

	// Create a hook for MessageBoxW, in disabled state.
	if (MH_CreateHook(&MessageBoxW, &DetourMessageBoxW, reinterpret_cast<void**>(&fpMessageBoxW)) != MH_OK)
	{
		return 1;
	}

	// Enable the hook for MessageBoxW.
	if (MH_EnableHook(&MessageBoxW) != MH_OK)
	{
		return 1;
	}

	// Expected to tell "Hooked!".
	MessageBoxW(NULL, L"Not hooked...", L"MinHook Sample", MB_OK);

	// Disable the hook for MessageBoxW.
	if (MH_DisableHook(&MessageBoxW) != MH_OK)
	{
		return 1;
	}

	// Expected to tell "Not hooked...".
	MessageBoxW(NULL, L"Not hooked...", L"MinHook Sample", MB_OK);

	// Uninitialize MinHook.
	if (MH_Uninitialize() != MH_OK)
	{
		return 1;
	}

	return 0;
}
예제 #26
0
// =================================================================================
// Hook Function
// =================================================================================
bool Memory::HookFunction(DWORD64 pAddress, void* pDetour, void** ppOriginal)
{
	// Create Hook
	int iResult = MH_CreateHook((void*)pAddress, pDetour, ppOriginal);
	if (iResult != MH_OK)
	{
		printf("[Memory::HookFunction] MH_CreateHook failed: %p [Error %i]\n", pAddress, iResult);
		MessageBox(0, "CreateHook fail", "Fail", 0);
		return false;
	}

	// Enable Hook
	iResult = MH_EnableHook((void*)pAddress);
	if (iResult != MH_OK)
	{
		printf("[Memory::HookFunction] MH_EnableHook failed: %p [Error %i]\n", pAddress, iResult);
		MessageBox(0, "EnableHook fail", "Fail", 0);
		return false;
	}

	// Success
	return true;
}
예제 #27
0
DWORD MainThreadControl(LPVOID /* param */)
{
    // creates the console
    if (!ConsoleManager::Create())
        FreeLibraryAndExitThread((HMODULE)instanceDLL, 0);

    // 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");

    printf("Press CTRL-C (CTRL then c) to stop sniffing ");
    printf("(and exit from the sniffer).\n");
    printf("Note: you can simply re-attach the sniffer without ");
    printf("restarting the WoW.\n\n");

    // gets the build number
    if (!GetWowInfo(NULL, instanceDLL, &wowInfo))
    {
        printf("Can't determine build number.\n\n");
        system("pause");
        FreeLibraryAndExitThread((HMODULE)instanceDLL, 0);
    }

    // error occured
    if (!wowInfo.build)
    {
        printf("Can't determine build number.\n\n");
        system("pause");
        FreeLibraryAndExitThread((HMODULE)instanceDLL, 0);
    }

    if (wowInfo.expansion >= _countof(ProtoTable))
    {
        printf("\nERROR: Unsupported expansion (%u) ", wowInfo.expansion);
        system("pause");
        FreeLibraryAndExitThread((HMODULE)instanceDLL, 0);
    }

    printf("Detected build number: %hu expansion: %hu\n", wowInfo.build, wowInfo.expansion);

    // checks this build is supported or not
    if (wowInfo.IsEmpty())
    {
        printf("ERROR: This build %u expansion %u is not supported.\n\n", wowInfo.build, wowInfo.expansion);
        system("pause");
        FreeLibraryAndExitThread((HMODULE)instanceDLL, 0);
    }

    // get the base address of the current process
    DWORD_PTR baseAddress = (DWORD_PTR)GetModuleHandle(NULL);

    // locale stored in reversed string (enGB as BGne...)
    if (wowInfo.lang)
    {
        *(DWORD*)hookInfo.locale = _byteswap_ulong(*(DWORD*)(baseAddress + wowInfo.lang));
        printf("Detected client locale: %s\n", hookInfo.locale);
    }

    // gets where is the DLL which injected into the client
    DWORD dllPathSize = GetModuleFileName((HMODULE)instanceDLL, dllPath, MAX_PATH);
    if (!dllPathSize)
    {
        printf("\nERROR: Can't get the injected DLL's location, ");
        printf("ErrorCode: %u\n\n", GetLastError());
        system("pause");
        FreeLibraryAndExitThread((HMODULE)instanceDLL, 0);
    }
    printf("\nDLL path: %s\n", dllPath);

    auto proto = ProtoTable[wowInfo.expansion];
    if (!proto.send || !proto.recv)
    {
        printf("\nERROR: Unsupported expansion (%u) ", wowInfo.expansion);
        system("pause");
        FreeLibraryAndExitThread((HMODULE)instanceDLL, 0);
    }

    printf("Found '%s' hooks!\n", proto.name);

    if (MH_CreateHook((LPVOID)(baseAddress + wowInfo.send), proto.send, &hookInfo.sendDetour) != MH_OK ||
        MH_CreateHook((LPVOID)(baseAddress + wowInfo.recv), proto.recv, &hookInfo.recvDetour) != MH_OK ||
        MH_EnableHook(MH_ALL_HOOKS) != MH_OK)
    {
        printf("\nERROR installing hooks (%u)\n", GetLastError());
        system("pause");
        FreeLibraryAndExitThread((HMODULE)instanceDLL, 0);
    }

    printf(">> All '%s' hooks is installed.\n", proto.name);

    while (ConsoleManager::IsRuning())
        Sleep(50);

    MH_DisableHook(MH_ALL_HOOKS);
    printf("All hook disabled.\n");
    ConsoleManager::Destroy();
    // shutdowns the sniffer
    // note: after that DLL's entry point will be called with
    // reason DLL_PROCESS_DETACH
    FreeLibraryAndExitThread((HMODULE)instanceDLL, 0);

    return 0;
}
예제 #28
0
BOOL APIENTRY DllMain(HMODULE hModule, DWORD ul_reason_for_call, LPVOID lpReserved)
{
    switch (ul_reason_for_call)
    {
    case DLL_PROCESS_ATTACH:
        if (initialized) {
            break;
        }

        initialized = true;

        //MessageBoxW(NULL, L"Hooking", L"DPIMangler", MB_OK);

        // Initialize MinHook.
        if (MH_Initialize() != MH_OK)
        {
            MessageBoxW(NULL, L"Initialization error", L"DPIMangler", MB_OK);
            return 1;
        }

        // Create a hook for the DPI awareness functions, in disabled state.
        if (MH_CreateHook(&SetProcessDPIAware, &NukeSetProcessDPIAware,
            reinterpret_cast<void**>(&fpSetProcessDPIAware)) != MH_OK ||
            MH_CreateHook(&SetProcessDpiAwareness, &NukeSetProcessDpiAwareness,
            reinterpret_cast<void**>(&fpSetProcessDpiAwareness)) != MH_OK)
        {
            MessageBoxW(NULL, L"Error creating hook", L"DPIMangler", MB_OK);
            return 1;
        }

        // Enable the hook for the DPI awareness functions.
        if (MH_EnableHook(&SetProcessDPIAware) != MH_OK ||
            MH_EnableHook(&SetProcessDpiAwareness) != MH_OK)
        {
            MessageBoxW(NULL, L"Error enabling hook", L"DPIMangler", MB_OK);
            return 1;
        }

        //MessageBoxW(NULL, L"Hooked...", L"DPIManger", MB_OK);

        break;
    case DLL_PROCESS_DETACH:
        // Disable the hook for the DPI awareness functions.
        if (MH_DisableHook(&SetProcessDPIAware) != MH_OK ||
            MH_DisableHook(&SetProcessDpiAwareness) != MH_OK)
        {
            MessageBoxW(NULL, L"Error disabling hook", L"DPIMangler", MB_OK);
            return 1;
        }

        // Uninitialize MinHook.
        if (MH_Uninitialize() != MH_OK)
        {
            MessageBoxW(NULL, L"Error uninitializing minhook", L"DPIMangler", MB_OK);
            return 1;
        }
        break;
    }

	return TRUE;
}
예제 #29
0
		}

		if (g_objectIds.size() < 16)
		{
			if (!g_requestedIds)
			{
				net::Buffer outBuffer;
				outBuffer.Write<uint16_t>(32);

				g_netLibrary->SendReliableCommand("msgRequestObjectIds", (const char*)outBuffer.GetData().data(), outBuffer.GetCurOffset());

				g_requestedIds = true;
			}
		}
	});

	OnKillNetworkDone.Connect([]()
	{
		g_objectIds.clear();
		g_usedObjectIds.clear();

		g_requestedIds = false;
	});

	MH_Initialize();
	MH_CreateHook(hook::get_pattern("FF 89 C4 3E 00 00 33 D2", -12), AssignObjectId, (void**)&g_origAssignObjectId);
	MH_CreateHook(hook::get_pattern("44 8B 91 C4 3E 00 00", -0x14), ReturnObjectId, (void**)&g_origReturnObjectId);
	MH_CreateHook(hook::get_pattern("48 83 EC 20 8B B1 C4 3E 00 00", -0xB), HasSpaceForObjectId, (void**)&g_origHasSpaceForObjectId);
	MH_EnableHook(MH_ALL_HOOKS);
});
예제 #30
0
InputHook::InputHook() :
m_hookmask(HOOK_COM),
m_fakepidvid(MAKELONG(0x045E, 0x028E)),
m_timeout(0),
m_timeout_thread(INVALID_HANDLE_VALUE)
{
	IniFile ini;
	std::string inipath("x360ce.ini");
	if (!ini.Load(inipath))
		CheckCommonDirectory(&inipath, "x360ce");
	if (!ini.Load(inipath)) return;

	bool read_from_database = ReadGameDatabase();

	if (!read_from_database)
	{
		if (!ini.Get("InputHook", "HookMask", &m_hookmask, HOOK_COM))
		{
			bool check = false;
			ini.Get("InputHook", "HookLL", &check);
			if (check) m_hookmask |= HOOK_LL;

			ini.Get("InputHook", "HookCOM", &check);
			if (check) m_hookmask |= HOOK_COM;

			ini.Get("InputHook", "HookDI", &check);
			if (check) m_hookmask |= HOOK_DI;

			ini.Get("InputHook", "HookPIDVID", &check);
			if (check) m_hookmask |= HOOK_PIDVID;

			ini.Get("InputHook", "HookSA", &check);
			if (check) m_hookmask |= HOOK_SA;

			ini.Get("InputHook", "HookNAME", &check);
			if (check) m_hookmask |= HOOK_NAME;

			ini.Get("InputHook", "HookSTOP", &check);
			if (check) m_hookmask |= HOOK_STOP;

			ini.Get("InputHook", "HookWT", &check);
			if (check) m_hookmask |= HOOK_WT;
		}

		if (GetState(HOOK_PIDVID))
		{
			u32 vid;
			u32 pid;
			ini.Get<u32>("InputHook", "FakeVID", &vid, 0x045E);
			ini.Get<u32>("InputHook", "FakePID", &pid, 0x028E);

			if (vid != 0x045E || pid != 0x28E)
				m_fakepidvid = MAKELONG(vid, pid);
		}
	}

	if (m_hookmask)
	{
		PrintLog("InputHook starting...");

		// Initalize InputHook Devices
		for (u32 i = 0; i < XUSER_MAX_COUNT; ++i)
		{
			std::string section;
			std::string key = StringFormat("PAD%u", i + 1);
			if (!ini.Get("Mappings", key, &section))
				continue;

			u32 index = 0;
			if (!ini.Get(section, "UserIndex", &index))
				index = i;

			std::string buffer;
			GUID productid = GUID_NULL;
			GUID instanceid = GUID_NULL;

			if (ini.Get(section, "ProductGUID", &buffer))
				StringToGUID(&productid, buffer);

			if (ini.Get(section, "InstanceGUID", &buffer))
				StringToGUID(&instanceid, buffer);

			if (!IsEqualGUID(productid, GUID_NULL) && !IsEqualGUID(instanceid, GUID_NULL))
			{
				m_devices.push_back(InputHookDevice(index, productid, instanceid));
			}
		}
	}

	if (!m_devices.empty())
	{
		if (!read_from_database)
			ini.Get<u32>("InputHook", "Timeout", &m_timeout, 45);

		std::string maskname;
		if (MaskToName(&maskname, m_hookmask))
			PrintLog("HookMask 0x%08X: %s", m_hookmask, maskname.c_str());

		MH_Initialize();

		if (GetState(HOOK_LL))
			HookLL();

		if (GetState(HOOK_COM))
			HookCOM();

		if (GetState(HOOK_DI))
			HookDI();

		if (GetState(HOOK_SA))
			HookSA();

		if (GetState(HOOK_WT))
			HookWT();

		MH_EnableHook(MH_ALL_HOOKS);
	}
}