示例#1
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;
}
示例#2
0
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");
	
}
示例#3
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;
}
示例#4
0
文件: dll.cpp 项目: ema29/TemplePlus
DllImpl::DllImpl(const std::wstring& installationDir) {

    auto dllPath(installationDir + L"temple.dll");

    // Does it even exist?
    if (!PathFileExists(dllPath.c_str())) {
        auto msg(fmt::format("Temple.dll does not exist: {}", ucs2_to_utf8(dllPath)));
        throw TempleException(msg);
    }

    SetCurrentDirectory(installationDir.c_str());

    // Try to load it
    mDllHandle = LoadLibrary(dllPath.c_str());
    if (!mDllHandle) {
        throw TempleException("Unable to load temple.dll from {}: {}",
                              ucs2_to_utf8(dllPath), GetLastWin32Error());
    }

    // calculate the offset from the default 0x10000000 base address
    auto baseAddr = reinterpret_cast<uint32_t>(mDllHandle);
    mDeltaFromVanilla = baseAddr - defaultBaseAddr;
    logger->info("The temple.dll base address delta is: {}", mDeltaFromVanilla);

    auto status = MH_Initialize();
    if (status != MH_OK) {
        FreeLibrary(mDllHandle);
        auto msg(fmt::format("Unable to initialize MinHook: {}", MH_StatusToString(status)));
        throw TempleException(msg);
    }
}
示例#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
文件: 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;
}
示例#7
0
BOOL APIENTRY DllMain(HINSTANCE instDLL, DWORD reason, LPVOID /* reserved */)
{
    // called when the DLL is being loaded into the
    // virtual address space of the current process (where to be injected)
    if (reason == DLL_PROCESS_ATTACH)
    {
        instanceDLL = instDLL;
        // disables thread notifications (DLL_THREAD_ATTACH, DLL_THREAD_DETACH)
        DisableThreadLibraryCalls(instDLL);
        MH_Initialize();

        // creates a thread to execute within the
        // virtual address space of the calling process (WoW)
        CreateThread(NULL, 0, (LPTHREAD_START_ROUTINE)&MainThreadControl, NULL, 0, NULL);
    }
    // the DLL is being unloaded
    else if (reason == DLL_PROCESS_DETACH)
    {
        // close the dump file
        if (fileDump)
            fclose(fileDump);

        MH_Uninitialize();
    }
    return TRUE;
}
示例#8
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;
}
示例#9
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);
}
示例#10
0
BOOL Initialize()
{
	if (MH_Initialize() != MH_OK)
		return FALSE;

	// Get the path to the games's AppData folder
	TCHAR szPath[MAX_PATH];
	if (SUCCEEDED(SHGetFolderPath(NULL, CSIDL_LOCAL_APPDATA, NULL, 0, szPath)))
	{
		// Get the path to the textures folder
		std::wstring appData(szPath);
		appData = appData.substr(0, appData.rfind(L"AC"));
		appData += L"LocalState\\games\\com.mojang\\assets\\";

		MINECRAFT_LOCAL_PATH = appData;
	}
	else
		return FALSE;

	// Attach a hook on CreateProcessW and return the status of the hook
	BOOL hook = TRUE;
	hook &= attach(L"KernelBase.dll", "CreateFileW", (LPVOID*)&HfnCreateFileW, (LPVOID*)&pfnCreateFileW);

	return hook;
}
示例#11
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;
	}
示例#12
0
// =================================================================================
// Init
// =================================================================================
void Memory::Init()
{
	// Init MinHook
	if (MH_Initialize() != MH_OK)
	{
		printf("[Memory::Init] MH_Initialize failed!\n");
		return;
	}
}
示例#13
0
// EnsureMinHookInitialized ensures that the MinHook
// library is initialized. If MinHook is already
// initialized, calling this function is a no-op.
static void EnsureMinHookInitialized() {
	// Ensure MH_Initialize is only called once.
	if (InterlockedCompareExchange(&minhook_init_once, 1, 0) == 0) {
		MH_STATUS status = MH_Initialize();
		if (status != MH_OK && status != MH_ERROR_ALREADY_INITIALIZED) {
			fods("HardHook: Failed to initialize minhook; MH_Initialize returned %s", MH_StatusToString(status));
		}
	}
}
示例#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;
}
vr::EVRInitError ServerDriver::Init(vr::IVRDriverContext *pDriverContext) {
	LOG(TRACE) << "CServerDriver::Init()";

	// Initialize Hooking
	InterfaceHooks::setServerDriver(this);
	auto mhError = MH_Initialize();
	if (mhError == MH_OK) {
		_driverContextHooks = InterfaceHooks::hookInterface(pDriverContext, "IVRDriverContext");
	} else {
		LOG(ERROR) << "Error while initialising minHook: " << MH_StatusToString(mhError);
	}

	LOG(DEBUG) << "Initialize driver context.";
	VR_INIT_SERVER_DRIVER_CONTEXT(pDriverContext);

	// Read installation directory
	vr::ETrackedPropertyError tpeError;
	installDir = vr::VRProperties()->GetStringProperty(pDriverContext->GetDriverHandle(), vr::Prop_InstallPath_String, &tpeError);
	if (tpeError == vr::TrackedProp_Success) {
		LOG(INFO) << "Install Dir:" << installDir;
	} else {
		LOG(INFO) << "Could not get Install Dir: " << vr::VRPropertiesRaw()->GetPropErrorNameFromEnum(tpeError);
	}

	// Read vrsettings
	char buffer[vr::k_unMaxPropertyStringSize];
	vr::EVRSettingsError peError;
	vr::VRSettings()->GetString(vrsettings_SectionName, vrsettings_overrideHmdManufacturer_string, buffer, vr::k_unMaxPropertyStringSize, &peError);
	if (peError == vr::VRSettingsError_None) {
		_propertiesOverrideHmdManufacturer = buffer;
		LOG(INFO) << vrsettings_SectionName << "::" << vrsettings_overrideHmdManufacturer_string << " = " << _propertiesOverrideHmdManufacturer;
	}
	vr::VRSettings()->GetString(vrsettings_SectionName, vrsettings_overrideHmdModel_string, buffer, vr::k_unMaxPropertyStringSize, &peError);
	if (peError == vr::VRSettingsError_None) {
		_propertiesOverrideHmdModel = buffer;
		LOG(INFO) << vrsettings_SectionName << "::" << vrsettings_overrideHmdModel_string << " = " << _propertiesOverrideHmdModel;
	}
	vr::VRSettings()->GetString(vrsettings_SectionName, vrsettings_overrideHmdTrackingSystem_string, buffer, vr::k_unMaxPropertyStringSize, &peError);
	if (peError == vr::VRSettingsError_None) {
		_propertiesOverrideHmdTrackingSystem = buffer;
		LOG(INFO) << vrsettings_SectionName << "::" << vrsettings_overrideHmdTrackingSystem_string << " = " << _propertiesOverrideHmdTrackingSystem;
	}
	auto boolVal = vr::VRSettings()->GetBool(vrsettings_SectionName, vrsettings_genericTrackerFakeController_bool, &peError);
	if (peError == vr::VRSettingsError_None) {
		_propertiesOverrideGenericTrackerFakeController = boolVal;
		LOG(INFO) << vrsettings_SectionName << "::" << vrsettings_genericTrackerFakeController_bool << " = " << boolVal;
	}

	// Start IPC thread
	shmCommunicator.init(this);
	return vr::VRInitError_None;
}
示例#16
0
int init()
{
	BOOST_LOG_TRIVIAL(info) << "Initializing hook engine...";

	if (MH_Initialize() != MH_OK)
	{
		BOOST_LOG_TRIVIAL(fatal) << "Couldn't initialize hook engine";
		return -1;
	}

	BOOST_LOG_TRIVIAL(info) << "Hook engine initialized";

	HookDefWindowProc();

	return WaitForSingleObject(INVALID_HANDLE_VALUE, INFINITE);
}
示例#17
0
void HookSSL()
{
	if (MH_Initialize() != MH_OK)
		printf("Init failed!\n");
	else
		printf("Init succeded!\n");
	if (MH_CreateHookApiEx(L"secur32.dll", "DecryptMessage", DetouredDecrypt, (LPVOID*)&orgDecrypt, true) != MH_OK)
        printf("Decrypthook failed!\n");
	else
		printf("Decrypthook succeded!\n");
	if (MH_CreateHookApiEx(L"secur32.dll", "EncryptMessage", DetouredEncrypt, (LPVOID*)&orgEncrypt, true) != MH_OK)
        printf("Encrypthook failed!\n");
	else
		printf("Encrypthook succeded!\n");
	MH_ApplyQueued();
}
示例#18
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;
		}

	}
示例#19
0
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";
	}
}
示例#20
0
//-------------------------------------------------------------------------
MH_STATUS WINAPI MH_InitializeEx(MH_INITIALIZE* pInit)
{
    MH_STATUS status = MH_Initialize();

    if ((status == MH_OK) && pInit && (pInit->cbSize >= sizeof(MH_INITIALIZE)))
    {
        // CreateToolhelp32Snapshot(TH32CS_SNAPTHREAD) has large overhead
        // In some cases, caller application may provide thread list itself
        // Caller is responsible to pass valid pointers or NULLs
        ThreadListCreate = pInit->ThreadListCreate;
        ThreadListFirst = pInit->ThreadListFirst;
        ThreadListNext = pInit->ThreadListNext;
        ThreadListClose = pInit->ThreadListClose;

        // Minhook working modes
        g_Flags = pInit->Flags;
    }

    return status;
}
示例#21
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);
}
示例#22
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;
}
示例#23
0
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;
}
示例#24
0
EXTERNC BOOL WINAPI DllMain(HINSTANCE hModule, DWORD dwReason, LPVOID pv)
{
    if (dwReason == DLL_PROCESS_ATTACH)
    {
        hInstance = hModule;

        // 保持系统dll原有功能
        LoadSysDll(hModule);

        // 初始化HOOK库成功以后安装加载器
        MH_STATUS status = MH_Initialize();
        if (status == MH_OK)
        {
            InstallLoader();
        }
        else
        {
            DebugLog(L"MH_Initialize failed:%d", status);
        }
    }
    return TRUE;
}
示例#25
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);
}
示例#26
0
static void AdjustLimits()
{
	g_drawableStore = hook::get_address<char*>(hook::get_pattern("74 16 8B 17 48 8D 0D ? ? ? ? 41 B8 02 00 00 00", 7));
	g_dwdStore = hook::get_address<char*>(hook::get_pattern("EB 7B 48 8D 54 24 40 48 8D 0D", 10));

	MH_Initialize();
	MH_CreateHook(hook::get_pattern("41 8B 18 44 0F B7 81 80 00 00 00", -5), GetIndexByKeyStub, (void**)&g_origGetIndexByKey);
	MH_CreateHook(hook::get_pattern("48 89 7C 24 10 44 0F B7 49 10", -5)/*(void*)0x1414F9E68*/, StoreInsert, (void**)&g_origStoreInsert);
	MH_CreateHook((void*)hook::get_pattern("44 0F B7 41 10 44 8B DA 33 D2")/*0x1414F4A34*/, StoreRemove, (void**)&g_origStoreRemove);
	MH_CreateHook((void*)hook::get_pattern("48 63 DA 48 8B F9 8B C3", -20)/*0x1414F9790*/, StoreInit, (void**)&g_origStoreInit);
	MH_CreateHook((void*)hook::get_pattern("BE FF FF 00 00 C6 41 60 00", -16)/*0x141588FE4*/, ArchetypeSetDrawable, (void**)&g_origSetDrawable);
	MH_CreateHook((void*)hook::get_pattern("41 8B F8 48 8B D9 75 12", -16)/*0x141588FE4*/, ArchetypeSetDrawableDict, nullptr);
	MH_CreateHook((void*)hook::get_pattern("F6 41 50 01 4C 8B D1 75 03")/*0x141586390*/, ArchetypeGetDrawable, (void**)&g_origGetDrawable);
	MH_CreateHook((void*)hook::get_pattern("0F B6 51 60 41 83 C9 FF")/*0x14158615C*/, ArchetypeGetDrawableF18, (void**)&g_origGetDrawableF18);
	MH_EnableHook(MH_ALL_HOOKS);

	static struct : jitasm::Frontend
	{
		static int GetArchetype(char* archetype)
		{
			if (*(uint8_t*)(archetype + 96) != 2 && *(uint8_t*)(archetype + 96) != 3)
			{
				return *(uint16_t*)(archetype + 98);
			}

			uint16_t archetypeIdx = *(uint16_t*)(archetype + 102);			
			return g_drawableIndices[archetypeIdx];
		}

		virtual void InternalMain() override
		{
			push(rcx);
			push(r8);
			push(r9);
			sub(rsp, 0x20);

			mov(rcx, rdx);
			mov(rax, (uintptr_t)GetArchetype);
			call(rax);

			add(rsp, 0x20);
			pop(r9);
			pop(r8);
			pop(rcx);

			add(ecx, eax);

			ret();
		}
	} getArchetypeStub;

	{
		auto location = hook::get_pattern("0F B7 42 62 03 C8");
		hook::nop(location/*0x141586371*/, 6);
		hook::call(location, getArchetypeStub.GetCode());
	}

	// in setting of drawable dict index
	static struct : jitasm::Frontend
	{
		static int GetArchetype(char* archetype)
		{
			uint16_t archetypeIdx = *(uint16_t*)(archetype + 102);
			return g_drawableIndices[archetypeIdx];
		}

		virtual void InternalMain() override
		{
			push(rcx);
			push(r8);
			push(r9);
			sub(rsp, 0x20);

			mov(rcx, r10);
			mov(rax, (uintptr_t)GetArchetype);
			call(rax);

			add(rsp, 0x20);
			pop(r9);
			pop(r8);
			pop(rcx);

			mov(r8d, eax);

			ret();
		}
	} getArchetypeStub2;

	{
		auto location = hook::get_pattern("E9 84 00 00 00 45 0F B7 42 62", 5);
		hook::nop(location, 5);
		hook::call(location, getArchetypeStub2.GetCode());
	}
}
示例#27
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;
}
示例#28
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);
	}
}
示例#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
文件: main.c 项目: TETYYS/ph-malhide
LOGICAL DllMain(
	__in HINSTANCE Instance,
	__in ULONG Reason,
	__reserved PVOID Reserved
	)
{
	switch (Reason)
	{
	case DLL_PROCESS_ATTACH:
		{
			PPH_PLUGIN_INFORMATION info;

			PluginInstance = PhRegisterPlugin(L"TT.MalHide", Instance, &info);

			if (!PluginInstance)
				return FALSE;

			info->DisplayName = L"MalHide";
			info->Author = L"TETYYS";
			info->Description = L"Changes window properties to prevent malware killing ProcessHacker, however you will not able to see user running PH.";
			info->HasOptions = FALSE;
			info->Url = L"http://wj32.org/processhacker/forums/viewtopic.php?f=18&t=1301&p=5731";

			PhRegisterCallback(
				PhGetPluginCallback(PluginInstance, PluginCallbackUnload),
				UnloadCallback,
				NULL,
				&PluginUnloadCallbackRegistration
				);

			RANGE range;
			RangesSize = 27;
			Ranges = malloc(sizeof(RANGE) * RangesSize);
			Ranges[0] =	 (RANGE) { .From = 0x0021, .To = 0x007E };
			Ranges[1] =  (RANGE) { .From = 0x00A1, .To = 0x024F };
			Ranges[2] =  (RANGE) { .From = 0x1F00, .To = 0x2049 };
			Ranges[3] =  (RANGE) { .From = 0x2070, .To = 0x2094 };
			Ranges[4] =  (RANGE) { .From = 0x20A0, .To = 0x20B5 };
			Ranges[5] =  (RANGE) { .From = 0x20B8, .To = 0x20B9 };
			Ranges[6] =  (RANGE) { .From = 0x20D0, .To = 0x20E1 };
			Ranges[7] =  (RANGE) { .From = 0x2100, .To = 0x2138 };
			Ranges[8] =  (RANGE) { .From = 0x214D, .To = 0x214E };
			Ranges[9] =  (RANGE) { .From = 0x2153, .To = 0x2182 };
			Ranges[10] = (RANGE) { .From = 0x2184, .To = 0x2184 };
			Ranges[11] = (RANGE) { .From = 0x2190, .To = 0x21EA };
			Ranges[12] = (RANGE) { .From = 0x2200, .To = 0x22F1 };
			Ranges[14] = (RANGE) { .From = 0x23BE, .To = 0x23CC };
			Ranges[15] = (RANGE) { .From = 0x23CE, .To = 0x23CE };
			Ranges[16] = (RANGE) { .From = 0x23DA, .To = 0x23DB };
			Ranges[18] = (RANGE) { .From = 0x2460, .To = 0x24FE };
			Ranges[19] = (RANGE) { .From = 0x2500, .To = 0x2595 };
			Ranges[20] = (RANGE) { .From = 0x25A0, .To = 0x25EF };
			Ranges[22] = (RANGE) { .From = 0x3000, .To = 0x303F };
			Ranges[23] = (RANGE) { .From = 0xFE30, .To = 0xFE4F };
			Ranges[24] = (RANGE) { .From = 0xFE50, .To = 0xFE6B };
			Ranges[25] = (RANGE) { .From = 0xFF01, .To = 0xFF65 };
			Ranges[26] = (RANGE) { .From = 0xFFE0, .To = 0xFFEE };
			
			srand((UINT)time(NULL));

			ClassName = RandomString();

			if (MH_Initialize() != MH_OK)
				return 1;

			if (MH_CreateHook(&CreateWindowExW, &H_CreateWindowExW, (LPVOID*)(&O_CreateWindow)) != MH_OK || MH_EnableHook(&CreateWindowExW) != MH_OK)
				return 1;

			if (MH_CreateHook(&RegisterClassExW, &H_RegisterClassExW, (LPVOID*)(&O_RegisterClass)) != MH_OK || MH_EnableHook(&RegisterClassExW) != MH_OK)
				return 1;

			if (MH_CreateHook(&FindWindowExW, &H_FindWindowExW, (LPVOID*)(&O_FindWindow)) != MH_OK || MH_EnableHook(&FindWindowExW) != MH_OK)
				return 1;
		}
		break;
	}
	return TRUE;
}

VOID NTAPI UnloadCallback(
	__in_opt PVOID Parameter,
	__in_opt PVOID Context
	)
{
	MH_Uninitialize();
}

HWND WINAPI	H_FindWindowExW(
	_In_opt_ HWND hWndParent,
	_In_opt_ HWND hWndChildAfter,
	_In_opt_ LPCWSTR lpszClass,
	_In_opt_ LPCWSTR lpszWindow
	)
{
	if (lpszClass && wcscmp(lpszClass, ORIGINAL_CLASS_NAME) == 0) {
		lpszClass = ClassName;
		MH_DisableHook(&FindWindowExW);
	}
	return O_FindWindow(hWndParent, hWndChildAfter, lpszClass, lpszWindow);
}

ATOM
WINAPI
H_RegisterClassExW(
	_In_ /* CONST */ WNDCLASSEXW *lpwcx
	)
{
	if (wcscmp(lpwcx->lpszClassName, ORIGINAL_CLASS_NAME) == 0) {
		lpwcx->lpszClassName = ClassName;
		MH_DisableHook(&RegisterClassExW);
	}
	return O_RegisterClass(lpwcx);
}

HWND WINAPI H_CreateWindowExW(
	_In_     DWORD     dwExStyle,
	_In_opt_ LPCTSTR   lpClassName,
	_In_opt_ LPCTSTR   lpWindowName,
	_In_     DWORD     dwStyle,
	_In_     int       x,
	_In_     int       y,
	_In_     int       nWidth,
	_In_     int       nHeight,
	_In_opt_ HWND      hWndParent,
	_In_opt_ HMENU     hMenu,
	_In_opt_ HINSTANCE hInstance,
	_In_opt_ LPVOID    lpParam
	)
{
	BOOL found = FALSE;
	if (wcscmp(lpClassName, ORIGINAL_CLASS_NAME) == 0) {
		found = TRUE;
		lpClassName = ClassName;
		lpWindowName = RandomString();
	}
	HWND ret = O_CreateWindow(dwExStyle, lpClassName, lpWindowName, dwStyle, x, y, nWidth, nHeight, hWndParent, hMenu, hInstance, lpParam);
	if (found) {
		MainWindowHandle = ret;
		MH_DisableHook(&CreateWindowExW);
	}
	return ret;
}

WCHAR* RandomString() {
	ULONG range = rand() % RangesSize;
	ULONG len;
	do {
		len = rand() % 100;
	} while (len == 0);
	WCHAR* ustr = calloc(sizeof(WCHAR), len + 1);
	for (ULONG i = 0; i < len; i++) {
		ustr[i] = (rand() % (Ranges[range].To - Ranges[range].From + 1)) + Ranges[range].From;
		range = rand() % RangesSize;
	}
	ustr[len] = L'\0';
	return ustr;
}