commit 0e57048caf2778fafe62dc093ae21d395161412e Author: admin Date: Mon Aug 17 02:11:20 2026 +0000 Upload files to "/" diff --git a/Includes.h b/Includes.h new file mode 100644 index 0000000..fe8956b --- /dev/null +++ b/Includes.h @@ -0,0 +1,14 @@ +#pragma once +#include +#include +#include +#include +#include + + +#include "../deps/minhook/include/MinHook.h" + +struct Il2cppString { + int Length; + wchar_t s[1024]; +}; \ No newline at end of file diff --git a/Methods.h b/Methods.h new file mode 100644 index 0000000..704c24c --- /dev/null +++ b/Methods.h @@ -0,0 +1,85 @@ +#pragma once +#include "../Utils/globals.h" + +// All RVAs below verified against the user's DUMPER-7 runtime dump (Aug 2026). Game-code offsets +// happen to be IDENTICAL to the July 19 2025 reference build the original 2025Patch targeted - +// that's why we can reuse the same numbers unchanged. If a future build shifts these, re-dump and +// update this file (or fall back to pattern-scanning). + +namespace RR::Methods::Referee { + // Referee's 4 anti-tamper check functions. Original July 19 offsets. + uintptr_t Check1 = 0x76E850; + uintptr_t Check2 = 0x2E6F680; + uintptr_t Check3 = 0x2E6F670; + uintptr_t Check4 = 0x2E6F6E0; +} + +namespace RR::Methods::LegacyTlsAuthentication { + // NOP'd -> game accepts any TLS cert (needed for the private server's self-signed cert). + uintptr_t NotifyServerCertificate = 0x77E5E30; +} + +namespace RR::Methods::HTTPManager { + // HTTPManager.SendRequest(HTTPRequest* request) - the single-arg internal SendRequest that + // carries the URI on request+0x10. Hooked to redirect ns.rec.net -> CAMPUS_NAMESERVER_HOST. + uintptr_t SendRequest = 0x77E0950; +} + +// RecNet HTTP response callback. CBACIMLIBPF.CLCAHKCJDLC(request, response, promise) fires +// once BestHTTP has a completed response for a RecNet-managed request. Signature is +// (HTTPRequest*, DPEENGNNEEB*, Promise*). The response has the HTTP status code as int32 at +// +0x10 (verified against the runtime dump). Hooking here lets us log "URI [STATUS]" in a +// single line — the URI comes off request+0x10 the same way SendRequest_H reads it. +namespace RR::Methods::RecNetHttp { + uintptr_t ResponseCallback = 0x7CC2BD0; +} + +namespace RR::Methods::System::Uri { + uintptr_t ToString = 0x935AF50; + uintptr_t ctor = 0x935C2A0; // Uri..ctor(string) - single-arg overload +} + +// Photon connect entry points. Each takes Photon.Realtime.AppSettings* as its first non-this +// argument; we Prefix them so the game's own AppSettings gets its identity fields (AppId*, +// AppVersion) overwritten to Campus values before Photon actually connects. +namespace RR::Methods::Photon { + uintptr_t OLPEILEPEAD_JBNCMFDFDLM = 0x757E8C0; // realtime connect + uintptr_t OEOMKFKDCCG_JBNCMFDFDLM = 0x759B710; // PUN wrapper + uintptr_t VoiceConnection_ConnectUsingSettings = 0x75F55D0; // Photon.Voice + uintptr_t PhotonVoiceNetwork_ConnectUsingSettings = 0x75FB2B0; // Photon.Voice.PUN +} + +// AppSettings field offsets from Photon.Realtime.AppSettings.h in the dump. Il2Cpp string fields +// are pointers to Il2CppString*; we replace them with pointers returned by il2cpp_string_new. +namespace RR::Methods::AppSettingsFields { + constexpr ptrdiff_t AppIdRealtime = 0x10; // Il2CppString* + constexpr ptrdiff_t AppIdChat = 0x18; // Il2CppString* + constexpr ptrdiff_t AppIdVoice = 0x20; // Il2CppString* + constexpr ptrdiff_t AppVersion = 0x28; // Il2CppString* +} + +// Resolved at runtime. On protected builds GameAssembly.dll's export table is STRIPPED, so +// GetProcAddress returns null for every il2cpp_* name. When that happens we fall back to a +// UnityPlayer.dll memory scan (see UnityPlayerScan in Patches.h). +namespace RR::Methods::Il2cpp { + uintptr_t il2cpp_string_new; + uintptr_t il2cpp_object_get_class; + uintptr_t il2cpp_object_new; +} + +// UnityEngine.Gradient - the managed wrapper around the native gradient. get_colorKeys returns a +// FRESH copy of the color-key array each call; modifying that array locally does not sync back +// unless we then call SetKeys to marshal to the C++ side. Values here are RVAs verified against +// the Aug 2026 DUMPER-7 runtime dump (UnityEngine.CoreModule/UnityEngine/Gradient.h). +namespace RR::Methods::UnityGradient { + uintptr_t SetKeys = 0x9987030; // void SetKeys(GradientColorKey[], GradientAlphaKey[]) + uintptr_t get_colorKeys = 0x9987110; // GradientColorKey[] get_colorKeys() + uintptr_t get_alphaKeys = 0x99870D0; // GradientAlphaKey[] get_alphaKeys() +} + +// RRUI.UIGradient - Rec Room's MonoBehaviour that wraps a Unity Gradient for rendering. Hooking +// the setter lets us swap Rec Room's orange 4-stop ramp for the Campus purple/magenta/orange/gold +// ramp on EVERY UI element that ever gets a gradient assigned. +namespace RR::Methods::UIGradient { + uintptr_t set_Gradient = 0x8BFA6A0; // void set_Gradient(UnityEngine.Gradient) +} diff --git a/MinHook.def b/MinHook.def new file mode 100644 index 0000000..c6af698 --- /dev/null +++ b/MinHook.def @@ -0,0 +1,14 @@ +EXPORTS + MH_Initialize + MH_Uninitialize + + MH_CreateHook + MH_CreateHookApi + MH_CreateHookApiEx + MH_RemoveHook + MH_EnableHook + MH_DisableHook + MH_QueueEnableHook + MH_QueueDisableHook + MH_ApplyQueued + MH_StatusToString diff --git a/MinHook.h b/MinHook.h new file mode 100644 index 0000000..15c0a87 --- /dev/null +++ b/MinHook.h @@ -0,0 +1,186 @@ +/* + * MinHook - The Minimalistic API Hooking Library for x64/x86 + * Copyright (C) 2009-2017 Tsuda Kageyu. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED + * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A + * PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER + * OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING + * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +#pragma once + +#if !(defined _M_IX86) && !(defined _M_X64) && !(defined __i386__) && !(defined __x86_64__) + #error MinHook supports only x86 and x64 systems. +#endif + +#include + +// MinHook Error Codes. +typedef enum MH_STATUS +{ + // Unknown error. Should not be returned. + MH_UNKNOWN = -1, + + // Successful. + MH_OK = 0, + + // MinHook is already initialized. + MH_ERROR_ALREADY_INITIALIZED, + + // MinHook is not initialized yet, or already uninitialized. + MH_ERROR_NOT_INITIALIZED, + + // The hook for the specified target function is already created. + MH_ERROR_ALREADY_CREATED, + + // The hook for the specified target function is not created yet. + MH_ERROR_NOT_CREATED, + + // The hook for the specified target function is already enabled. + MH_ERROR_ENABLED, + + // The hook for the specified target function is not enabled yet, or already + // disabled. + MH_ERROR_DISABLED, + + // The specified pointer is invalid. It points the address of non-allocated + // and/or non-executable region. + MH_ERROR_NOT_EXECUTABLE, + + // The specified target function cannot be hooked. + MH_ERROR_UNSUPPORTED_FUNCTION, + + // Failed to allocate memory. + MH_ERROR_MEMORY_ALLOC, + + // Failed to change the memory protection. + MH_ERROR_MEMORY_PROTECT, + + // The specified module is not loaded. + MH_ERROR_MODULE_NOT_FOUND, + + // The specified function is not found. + MH_ERROR_FUNCTION_NOT_FOUND +} +MH_STATUS; + +// Can be passed as a parameter to MH_EnableHook, MH_DisableHook, +// MH_QueueEnableHook or MH_QueueDisableHook. +#define MH_ALL_HOOKS NULL + +#ifdef __cplusplus +extern "C" { +#endif + + // Initialize the MinHook library. You must call this function EXACTLY ONCE + // at the beginning of your program. + MH_STATUS WINAPI MH_Initialize(VOID); + + // Uninitialize the MinHook library. You must call this function EXACTLY + // ONCE at the end of your program. + MH_STATUS WINAPI MH_Uninitialize(VOID); + + // Creates a Hook for the specified target function, in disabled state. + // Parameters: + // pTarget [in] A pointer to the target function, which will be + // overridden by the detour function. + // pDetour [in] A pointer to the detour function, which will override + // the target function. + // ppOriginal [out] A pointer to the trampoline function, which will be + // used to call the original target function. + // This parameter can be NULL. + MH_STATUS WINAPI MH_CreateHook(LPVOID pTarget, LPVOID pDetour, LPVOID *ppOriginal); + + // Creates a Hook for the specified API function, in disabled state. + // Parameters: + // pszModule [in] A pointer to the loaded module name which contains the + // target function. + // pszTarget [in] A pointer to the target function name, which will be + // overridden by the detour function. + // pDetour [in] A pointer to the detour function, which will override + // the target function. + // ppOriginal [out] A pointer to the trampoline function, which will be + // used to call the original target function. + // This parameter can be NULL. + MH_STATUS WINAPI MH_CreateHookApi( + LPCWSTR pszModule, LPCSTR pszProcName, LPVOID pDetour, LPVOID *ppOriginal); + + // Creates a Hook for the specified API function, in disabled state. + // Parameters: + // pszModule [in] A pointer to the loaded module name which contains the + // target function. + // pszTarget [in] A pointer to the target function name, which will be + // overridden by the detour function. + // pDetour [in] A pointer to the detour function, which will override + // the target function. + // ppOriginal [out] A pointer to the trampoline function, which will be + // used to call the original target function. + // This parameter can be NULL. + // ppTarget [out] A pointer to the target function, which will be used + // with other functions. + // This parameter can be NULL. + MH_STATUS WINAPI MH_CreateHookApiEx( + LPCWSTR pszModule, LPCSTR pszProcName, LPVOID pDetour, LPVOID *ppOriginal, LPVOID *ppTarget); + + // Removes an already created hook. + // Parameters: + // pTarget [in] A pointer to the target function. + MH_STATUS WINAPI MH_RemoveHook(LPVOID pTarget); + + // Enables an already created hook. + // Parameters: + // pTarget [in] A pointer to the target function. + // If this parameter is MH_ALL_HOOKS, all created hooks are + // enabled in one go. + MH_STATUS WINAPI MH_EnableHook(LPVOID pTarget); + + // Disables an already created hook. + // Parameters: + // pTarget [in] A pointer to the target function. + // If this parameter is MH_ALL_HOOKS, all created hooks are + // disabled in one go. + MH_STATUS WINAPI MH_DisableHook(LPVOID pTarget); + + // Queues to enable an already created hook. + // Parameters: + // pTarget [in] A pointer to the target function. + // If this parameter is MH_ALL_HOOKS, all created hooks are + // queued to be enabled. + MH_STATUS WINAPI MH_QueueEnableHook(LPVOID pTarget); + + // Queues to disable an already created hook. + // Parameters: + // pTarget [in] A pointer to the target function. + // If this parameter is MH_ALL_HOOKS, all created hooks are + // queued to be disabled. + MH_STATUS WINAPI MH_QueueDisableHook(LPVOID pTarget); + + // Applies all queued changes in one go. + MH_STATUS WINAPI MH_ApplyQueued(VOID); + + // Translates the MH_STATUS to its name as a string. + const char * WINAPI MH_StatusToString(MH_STATUS status); + +#ifdef __cplusplus +} +#endif + diff --git a/MinHook.rc b/MinHook.rc new file mode 100644 index 0000000..7cbacb7 --- /dev/null +++ b/MinHook.rc @@ -0,0 +1,32 @@ +1 VERSIONINFO + FILEVERSION 1,3,3,0 + PRODUCTVERSION 1,3,3,0 + FILEFLAGSMASK 0x17L +#ifdef _DEBUG + FILEFLAGS 0x1L +#else + FILEFLAGS 0x0L +#endif + FILEOS 0x4L + FILETYPE 0x2L + FILESUBTYPE 0x0L +BEGIN + BLOCK "StringFileInfo" + BEGIN + BLOCK "040904b0" + BEGIN + VALUE "CompanyName", "Tsuda Kageyu" + VALUE "FileDescription", "MinHook - The Minimalistic API Hook Library for x64/x86" + VALUE "FileVersion", "1.3.3.0" + VALUE "InternalName", "MinHookD" + VALUE "LegalCopyright", "Copyright (C) 2009-2017 Tsuda Kageyu. All rights reserved." + VALUE "LegalTrademarks", "Tsuda Kageyu" + VALUE "ProductName", "MinHook DLL" + VALUE "ProductVersion", "1.3.3.0" + END + END + BLOCK "VarFileInfo" + BEGIN + VALUE "Translation", 0x409, 1200 + END +END diff --git a/Patches.h b/Patches.h new file mode 100644 index 0000000..7ecaa3a --- /dev/null +++ b/Patches.h @@ -0,0 +1,450 @@ +#pragma once +#include "../Methods.h" +#include "../../Utils/scan.h" +#include "../../Utils/deps/spoofcall/RetSpoof.hpp" + +// Campus server target +// Change these constants if you move to a different server / Photon apps. +static const char* CAMPUS_NAMESERVER_HOST = "gameauth.ddns.net"; +static const char* CAMPUS_APP_ID_REALTIME = "3034d59c-49d5-4441-b627-a90683970217"; +static const char* CAMPUS_APP_ID_VOICE = "2f0fac1b-e91a-4271-8e95-8aee7fd67360"; +static const char* CAMPUS_APP_ID_CHAT = "e75ba377-2f03-46a4-a87d-f4fc151913b8"; +static const char* CAMPUS_APP_VERSION = "20250719_prod"; + +// Referee bypass: NOP the 4 anti-tamper checks so they return immediately. Same technique the +// reference 2025 patch uses. Also reused for TLS NotifyServerCertificate (a bool method - "return" +// with an empty body coerces to false but the caller path doesn't care about the value; what +// matters is that the real check body never runs, so self-signed certs are accepted). +void (*nop_O)(); +void nop_H() { return; } + +// il2cpp API resolution +// On protected (Referee) builds GameAssembly.dll's export table is stripped, so the reference +// patch's plain GetProcAddress path returns null and every downstream il2cpp_* call blows up. +// We fall back to scanning UnityPlayer.dll's decrypted code for the standard +// `lea reg, "il2cpp_name"; ... mov [rip+slot], rax` pattern - same technique the Puck Dumper +// uses to resolve il2cpp APIs on this exact build. Runs off already-decrypted memory; no exports +// required. +namespace UnityPlayerScan { + static void* find_il2cpp_api(const char* name) { + HMODULE up = GetModuleHandleA("UnityPlayer.dll"); + HMODULE ga = GetModuleHandleA("GameAssembly.dll"); + if (!up || !ga) return nullptr; + auto upBase = (uint8_t*)up; + auto dos = (PIMAGE_DOS_HEADER)upBase; + if (dos->e_magic != IMAGE_DOS_SIGNATURE) return nullptr; + auto nt = (PIMAGE_NT_HEADERS64)(upBase + dos->e_lfanew); + if (nt->Signature != IMAGE_NT_SIGNATURE) return nullptr; + const uint8_t* modEnd = upBase + nt->OptionalHeader.SizeOfImage; + + auto gaDos = (PIMAGE_DOS_HEADER)ga; + auto gaNt = (PIMAGE_NT_HEADERS64)((uint8_t*)ga + gaDos->e_lfanew); + const uint8_t* gaBase = (uint8_t*)ga; + const uint8_t* gaEnd = gaBase + gaNt->OptionalHeader.SizeOfImage; + + size_t nameLen = strlen(name); + auto sec = IMAGE_FIRST_SECTION(nt); + for (WORD s = 0; s < nt->FileHeader.NumberOfSections; s++) { + if (!(sec[s].Characteristics & IMAGE_SCN_CNT_CODE)) continue; + uint8_t* code = upBase + sec[s].VirtualAddress; + size_t codeSize = sec[s].Misc.VirtualSize; + if (code + codeSize > modEnd) codeSize = (size_t)(modEnd - code); + + for (size_t off = 0; off + 7 < codeSize; off++) { + uint8_t* p = code + off; + // lea r64, [rip+disp32] (REX.W/REX.WR + 8D + modrm mod=00 rm=101) + if (!((p[0] == 0x48 || p[0] == 0x4C) && p[1] == 0x8D && (p[2] & 0xC7) == 0x05)) continue; + int32_t disp = *(int32_t*)(p + 3); + uint8_t* target = p + 7 + disp; + if (target < upBase || target + nameLen + 1 >= modEnd) continue; + if (memcmp(target, name, nameLen) != 0 || target[nameLen] != 0) continue; + + // Next store-to-global (mov [rip+d], rax) within a short window is the slot. + for (size_t k = 7; k < 128 && off + k + 7 < codeSize; k++) { + uint8_t* q = p + k; + if (q[0] == 0x48 && q[1] == 0x89 && (q[2] & 0xC7) == 0x05) { + int32_t d2 = *(int32_t*)(q + 3); + uint8_t* slot = q + 7 + d2; + if (slot >= upBase && slot + 8 <= modEnd) { + void* fn = *(void**)slot; + // Sanity: resolved pointer must land INSIDE GameAssembly.dll. + if (fn && (uint8_t*)fn >= gaBase && (uint8_t*)fn < gaEnd) + return fn; + } + break; + } + } + } + } + return nullptr; + } +} + +// SendRequest hook: rewrite ns.rec.net -> CAMPUS_NAMESERVER_HOST +// Direct port of the reference 2025 patch's URL redirect, just retargeted at our host instead of +// the reference's ns.cgb.net. HTTPRequest carries the URI on the object at +0x10; we read it, +// stringify it, and if it references ns.rec.net we build a new Uri object with the swapped host +// and swap it into the request before the real SendRequest runs. +void (*SendRequest_O)(void*); +void SendRequest_H(void* request) { + void* uri = read(request, 16); + if (uri) { + using ToStringFn = Il2cppString * (*)(void*); + auto toStringFn = reinterpret_cast(GA + RR::Methods::System::Uri::ToString); + + // ONE toString per request. The previous version called this twice (once to inspect, + // once for the debug print), doubling IL2CPP string allocations on every HTTP request. + Il2cppString* Uri = spoof_call(RetAddr, toStringFn, uri); + std::string url = ReadIl2CppStringOwned(Uri); + + const std::string find = "ns.rec.net"; + bool rewritten = false; + auto findPos = url.find(find); + if (findPos != std::string::npos) { + url.replace(findPos, find.length(), CAMPUS_NAMESERVER_HOST); + + using Il2cppStringNewFn = Il2cppString * (*)(const char*); + auto strNew = reinterpret_cast(GA + RR::Methods::Il2cpp::il2cpp_string_new); + Il2cppString* NewStr = spoof_call(RetAddr, strNew, url.c_str()); + + using ObjectGetClassFn = void * (*)(void*); + auto getClass = reinterpret_cast(GA + RR::Methods::Il2cpp::il2cpp_object_get_class); + void* UriClass = spoof_call(RetAddr, getClass, uri); + + using ObjectNewFn = void* (*)(void*); + auto objNew = reinterpret_cast(GA + RR::Methods::Il2cpp::il2cpp_object_new); + void* NewUri = spoof_call(RetAddr, objNew, UriClass); + + if (NewUri && NewStr) { + using UriCtor = void (*)(void*, Il2cppString*); + auto uriCtor = reinterpret_cast(GA + RR::Methods::System::Uri::ctor); + spoof_call(RetAddr, uriCtor, NewUri, NewStr); + set(request, 16, NewUri); + rewritten = true; + } + } + // Log the URL here. Status is logged separately by RecNetResponse_H — the console will + // show `Uri: ` followed by ` <- HTTP ` for the same request. Pairing them + // in one line would need a request-pointer -> URL side map, which is more surface than + // it's worth. + std::cout << "Uri: " << url << (rewritten ? " (rewritten)" : "") << std::endl; + } + return SendRequest_O(request); +} + +// RecNet HTTP response hook: log HTTP status per completed request +// Signature confirmed against DUMPER-7 (CBACIMLIBPF.h line 1361): +// static void CLCAHKCJDLC(CDHPGPJPLII* request, DPEENGNNEEB* response, JFNOOGODOOA* promise) +// It IS a static method (no `this` arg) — the 3-arg raw signature matches perfectly. +// +// IMPORTANT: `CDHPGPJPLII` is RecNet's own request wrapper, NOT BestHTTP's `HTTPRequest`. +// Its offset 16 is a `bool`, NOT a `Uri*`. The previous version of this hook tried to read +// `request+16` as a Uri pointer, got garbage, called Uri.ToString on it, and black-screened +// the client on the first RecNet response. We now touch ONLY the response object, whose +// layout IS confirmed (DPEENGNNEEB.h: `int32_t backingField__IKBENAMGBFE` at offset 16 = +// the HTTP status code the ctor stores). +void (*RecNetResponse_O)(void*, void*, void*); +void RecNetResponse_H(void* request, void* response, void* promise) { + if (response) { + int status = read(response, 16); + // Force decimal — Resolve() sets `std::hex` when printing RVAs, and it sticks on the + // shared cout stream, so status codes were printing as "c8" instead of "200". + std::cout << " <- HTTP " << std::dec << status << std::endl; + } + return RecNetResponse_O(request, response, promise); +} + +// Gradient recolor: Rec Room orange -> Campus purple/magenta/orange/gold ramp +// Direct native port of CampusPatch (2023)'s RRUIGradientPatch: intercept UIGradient.set_Gradient, +// walk the incoming Unity Gradient's color keys, and if ANY key looks like Rec Room orange, +// replace ALL keys with the Campus 4-stop ramp (times preserved so the gradient's shape stays). +// +// UnityEngine.Gradient stores its actual key data on the C++ side behind m_Ptr; managed +// get_colorKeys hands back a fresh copy each call, so mutating that copy is invisible until we +// push it back via SetKeys. +namespace CampusGradient { + struct Color { float r, g, b, a; }; + + // 4 stops sampled from the admin panel's Background.png so recolored UI reads as the same + // visual palette Puck / the dashboard uses. + static constexpr Color Purple { 0.475f, 0.106f, 0.553f, 1.0f }; // #791B8D + static constexpr Color Magenta { 0.749f, 0.161f, 0.400f, 1.0f }; // #BF2966 + static constexpr Color Orange { 0.976f, 0.365f, 0.141f, 1.0f }; // #F95D24 + static constexpr Color Gold { 0.980f, 0.600f, 0.071f, 1.0f }; // #FA9912 + + static Color rampAt(float t) { + const Color stops[4] = { Purple, Magenta, Orange, Gold }; + if (t <= 0.0f) return stops[0]; + if (t >= 1.0f) return stops[3]; + float f = t * 3.0f; + int i = (int)f; + float u = f - (float)i; + return Color{ + stops[i].r * (1.0f - u) + stops[i+1].r * u, + stops[i].g * (1.0f - u) + stops[i+1].g * u, + stops[i].b * (1.0f - u) + stops[i+1].b * u, + 1.0f, + }; + } + + static void rgbToHsv(float r, float g, float b, float& h, float& s, float& v) { + float mx = r; if (g > mx) mx = g; if (b > mx) mx = b; + float mn = r; if (g < mn) mn = g; if (b < mn) mn = b; + v = mx; + float d = mx - mn; + s = (mx == 0.0f) ? 0.0f : d / mx; + if (d == 0.0f) { h = 0.0f; return; } + if (mx == r) h = fmodf((g - b) / d, 6.0f); + else if (mx == g) h = (b - r) / d + 2.0f; + else h = (r - g) / d + 4.0f; + h /= 6.0f; + if (h < 0.0f) h += 1.0f; + } + + // Two-branch HSV window matching bright Rec Room orange and the lighter yellow-orange used + // in secondary UI sweeps. + static bool isRecRoomOrange(float r, float g, float b) { + float h, s, v; + rgbToHsv(r, g, b, h, s, v); + return + (h >= 0.02f && h <= 0.07f && s >= 0.70f && v >= 0.60f) || + (h >= 0.05f && h <= 0.10f && s >= 0.45f && s <= 0.80f && v >= 0.85f); + } +} + +void (*UIGradient_set_Gradient_O)(void*, void*); +void UIGradient_set_Gradient_H(void* self, void* gradient) { + if (gradient) { + using GetKeysFn = void*(*)(void*); + using SetKeysFn = void (*)(void*, void*, void*); + auto getColorKeys = (GetKeysFn)(GA + RR::Methods::UnityGradient::get_colorKeys); + auto getAlphaKeys = (GetKeysFn)(GA + RR::Methods::UnityGradient::get_alphaKeys); + auto setKeys = (SetKeysFn)(GA + RR::Methods::UnityGradient::SetKeys); + + void* colorKeys = spoof_call(RetAddr, getColorKeys, gradient); + if (colorKeys) { + // Il2Cpp single-dim value-type array: length at +24, packed data at +32. + // GradientColorKey = { Color color(16B), float time(4B) } = 20 bytes. + uint64_t len = read(colorKeys, 24); + if (len > 0 && len <= 32) { + uint8_t* keyData = (uint8_t*)colorKeys + 32; + constexpr size_t STRIDE = 20; + + bool looksOrange = false; + for (uint64_t i = 0; i < len; i++) { + float r = *(float*)(keyData + i * STRIDE + 0); + float g = *(float*)(keyData + i * STRIDE + 4); + float b = *(float*)(keyData + i * STRIDE + 8); + if (CampusGradient::isRecRoomOrange(r, g, b)) { looksOrange = true; break; } + } + + if (looksOrange) { + void* alphaKeys = spoof_call(RetAddr, getAlphaKeys, gradient); + for (uint64_t i = 0; i < len; i++) { + float t = (len > 1) ? (float)i / (float)(len - 1) : 0.5f; + auto c = CampusGradient::rampAt(t); + *(float*)(keyData + i * STRIDE + 0) = c.r; + *(float*)(keyData + i * STRIDE + 4) = c.g; + *(float*)(keyData + i * STRIDE + 8) = c.b; + *(float*)(keyData + i * STRIDE + 12) = c.a; + } + spoof_call(RetAddr, setKeys, gradient, colorKeys, alphaKeys); + } + } + } + } + UIGradient_set_Gradient_O(self, gradient); +} + +// Photon connect hooks: rewrite AppSettings identity to Campus values on the way through +// Each connect entry point takes (this, AppSettings*, [maybe extra args]). We mutate AppSettings' +// string fields BEFORE the real method runs (Prefix-style behaviour), so the game connects to +// OUR Photon apps and version. This is the native equivalent of CampusPatch (2023)'s +// PhotonAppSettingsPatch Postfix that overwrote AppIdRealtime / AppIdVoice / AppVersion. +// The previous implementation allocated a fresh IL2CPP string for realtime/voice/version on +// EVERY Photon connect (matchmaking, room join, voice channel switch, reconnects). The GC does +// clean these up eventually, but under a busy session they piled up and showed as a memory +// climb. Allocate once, cache forever, and short-circuit if AppSettings already points at our +// cached strings. +static Il2cppString* g_campusAppIdRealtime = nullptr; +static Il2cppString* g_campusAppIdVoice = nullptr; +static Il2cppString* g_campusAppIdChat = nullptr; +static Il2cppString* g_campusAppVersion = nullptr; + +// The four Photon connect hooks (Realtime / PUN / Voice / VoicePUN) can fire on independent +// threads simultaneously. Without a guard, two threads could each see all four globals as null, +// each call il2cpp_string_new four times, and orphan the four losers of the race. +static std::once_flag g_campusPhotonStringsOnce; + +static void EnsureCampusPhotonStrings() +{ + std::call_once(g_campusPhotonStringsOnce, []{ + if (!RR::Methods::Il2cpp::il2cpp_string_new) return; + + using Il2cppStringNewFn = Il2cppString * (*)(const char*); + auto strNew = reinterpret_cast(GA + RR::Methods::Il2cpp::il2cpp_string_new); + + g_campusAppIdRealtime = spoof_call(RetAddr, strNew, CAMPUS_APP_ID_REALTIME); + g_campusAppIdVoice = spoof_call(RetAddr, strNew, CAMPUS_APP_ID_VOICE); + g_campusAppIdChat = spoof_call(RetAddr, strNew, CAMPUS_APP_ID_CHAT); + g_campusAppVersion = spoof_call(RetAddr, strNew, CAMPUS_APP_VERSION); + }); +} + +static void RewriteAppSettings(void* appSettings) +{ + if (!appSettings) return; + EnsureCampusPhotonStrings(); + if (!g_campusAppIdRealtime) { + std::cout << "[Campus/Photon] AppSettings NOT rewritten - il2cpp_string_new not resolved\n"; + return; + } + + // Skip the write when AppSettings already points at our cached strings — cuts out a bunch + // of __TypeStore / write-barrier work on hot Photon reconnect paths. + void* curRt = read(appSettings, RR::Methods::AppSettingsFields::AppIdRealtime); + void* curVc = read(appSettings, RR::Methods::AppSettingsFields::AppIdVoice); + void* curChat = read(appSettings, RR::Methods::AppSettingsFields::AppIdChat); + void* curVer = read(appSettings, RR::Methods::AppSettingsFields::AppVersion); + if (curRt == g_campusAppIdRealtime && + curVc == g_campusAppIdVoice && + curChat == g_campusAppIdChat && + curVer == g_campusAppVersion) { + return; // already redirected — nothing to do + } + + if (g_campusAppIdRealtime) set(appSettings, RR::Methods::AppSettingsFields::AppIdRealtime, g_campusAppIdRealtime); + if (g_campusAppIdVoice) set(appSettings, RR::Methods::AppSettingsFields::AppIdVoice, g_campusAppIdVoice); + if (g_campusAppIdChat) set(appSettings, RR::Methods::AppSettingsFields::AppIdChat, g_campusAppIdChat); + if (g_campusAppVersion) set(appSettings, RR::Methods::AppSettingsFields::AppVersion, g_campusAppVersion); + + std::cout << "[Campus/Photon] AppSettings redirected -> " << CAMPUS_APP_ID_REALTIME + << " ver " << CAMPUS_APP_VERSION << "\n"; +} + +// Image signature patch (DISABLED) +// Placeholder for a future image-sig bypass. Two prior attempts hard-crashed the client +// (see project-image-sig-crash memory), so this stays fully commented out until we have a +// safer hook target. Uncomment + wire the RVA in Methods.h + add the hook() call below when +// the sig verify function is confirmed. +// +// void (*ImageSig_O)(void*, void*); +// void ImageSig_H(void* self, void* payload) { +// // e.g. bypass RSA/HMAC check on inbound image manifests: return early so the caller +// // treats the payload as valid without actually verifying the signature. +// return; +// } +// +// Register in Patch() when re-enabling: +// hook(GA + RR::Methods::ImageSig::VerifyFn, +// (void*)ImageSig_H, (void**)&ImageSig_O, "Image signature verify"); + +bool (*RealtimeConnect_O)(void*, void*); +bool RealtimeConnect_H(void* self, void* appSettings) { + RewriteAppSettings(appSettings); + return RealtimeConnect_O(self, appSettings); +} + +bool (*PunConnect_O)(void*, void*, bool); +bool PunConnect_H(void* self, void* appSettings, bool arg) { + RewriteAppSettings(appSettings); + return PunConnect_O(self, appSettings, arg); +} + +bool (*VoiceConnect_O)(void*, void*); +bool VoiceConnect_H(void* self, void* appSettings) { + RewriteAppSettings(appSettings); + return VoiceConnect_O(self, appSettings); +} + +bool (*VoicePUNConnect_O)(void*, void*); +bool VoicePUNConnect_H(void* self, void* appSettings) { + RewriteAppSettings(appSettings); + return VoicePUNConnect_O(self, appSettings); +} + +//Patch installer +namespace RR::Patches { + void Resolve() { + RetAddr = PatternScan("FF 23", GA, NtHeaders->OptionalHeader.SizeOfImage); + std::cout << "[Campus] RetSpoof gadget (FF 23): 0x" << std::hex << (uintptr_t)RetAddr << "\n"; + auto assm = GetModuleHandle("GameAssembly.dll"); + + // 1) Try GetProcAddress first (works on unpacked builds). + auto tryExport = [&](const char* name) -> uintptr_t { + void* p = spoof_call(RetAddr, GetProcAddress, assm, name); + return p ? (uintptr_t)p - GA : 0; + }; + RR::Methods::Il2cpp::il2cpp_string_new = tryExport("il2cpp_string_new"); + RR::Methods::Il2cpp::il2cpp_object_get_class = tryExport("il2cpp_object_get_class"); + RR::Methods::Il2cpp::il2cpp_object_new = tryExport("il2cpp_object_new"); + + // 2) Fall back to UnityPlayer scan when exports are stripped (Referee'd builds). + auto fallback = [&](const char* name, uintptr_t& slot) { + if (slot) return; + void* p = UnityPlayerScan::find_il2cpp_api(name); + if (p) slot = (uintptr_t)p - GA; + }; + fallback("il2cpp_string_new", RR::Methods::Il2cpp::il2cpp_string_new); + fallback("il2cpp_object_get_class", RR::Methods::Il2cpp::il2cpp_object_get_class); + fallback("il2cpp_object_new", RR::Methods::Il2cpp::il2cpp_object_new); + + auto label = [](uintptr_t v) { return v ? "OK " : "FAIL"; }; + std::cout << "[Campus] " << label(RR::Methods::Il2cpp::il2cpp_string_new) + << " il2cpp_string_new -> 0x" << std::hex << RR::Methods::Il2cpp::il2cpp_string_new << "\n"; + std::cout << "[Campus] " << label(RR::Methods::Il2cpp::il2cpp_object_get_class) + << " il2cpp_object_get_class -> 0x" << std::hex << RR::Methods::Il2cpp::il2cpp_object_get_class << "\n"; + std::cout << "[Campus] " << label(RR::Methods::Il2cpp::il2cpp_object_new) + << " il2cpp_object_new -> 0x" << std::hex << RR::Methods::Il2cpp::il2cpp_object_new << "\n"; + } + + static void hook(uintptr_t abs, void* detour, void** orig, const char* label) { + MH_STATUS s = MH_CreateHook((void*)abs, detour, (LPVOID*)orig); + if (s == MH_OK) s = MH_EnableHook((void*)abs); + std::cout << "[Campus] hook " << label << " @ 0x" << std::hex << abs + << " -> " << (s == MH_OK ? "OK" : "FAIL") << "\n"; + } + + void Patch() { + if (MH_Initialize() != MH_OK) { + std::cout << "[Campus] MH_Initialize FAILED\n"; + return; + } + + // Referee bypass (must run before anything else calls into libil2cpp under Referee's watch). + hook(Referee + RR::Methods::Referee::Check1, (void*)nop_H, (void**)&nop_O, "Referee Check1"); + hook(Referee + RR::Methods::Referee::Check2, (void*)nop_H, (void**)&nop_O, "Referee Check2"); + hook(Referee + RR::Methods::Referee::Check3, (void*)nop_H, (void**)&nop_O, "Referee Check3"); + hook(Referee + RR::Methods::Referee::Check4, (void*)nop_H, (void**)&nop_O, "Referee Check4"); + + // Accept any TLS cert (private server uses self-signed). + hook(GA + RR::Methods::LegacyTlsAuthentication::NotifyServerCertificate, + (void*)nop_H, (void**)&nop_O, "TLS NotifyServerCertificate"); + + // URI rewrite (ns.rec.net -> CAMPUS_NAMESERVER_HOST). + hook(GA + RR::Methods::HTTPManager::SendRequest, + (void*)SendRequest_H, (void**)&SendRequest_O, "HTTPManager.SendRequest"); + + // RecNet response callback — logs " <- HTTP " per completed request. Pairs + // visually with the SendRequest URL log line above. + hook(GA + RR::Methods::RecNetHttp::ResponseCallback, + (void*)RecNetResponse_H, (void**)&RecNetResponse_O, "RecNet response callback (status)"); + + // Gradient recolor: Rec Room orange -> Campus purple/magenta/orange/gold ramp. + hook(GA + RR::Methods::UIGradient::set_Gradient, + (void*)UIGradient_set_Gradient_H, (void**)&UIGradient_set_Gradient_O, + "UIGradient.set_Gradient (gradient recolor)"); + + // Photon redirect (all four connect-with-AppSettings entry points). + hook(GA + RR::Methods::Photon::OLPEILEPEAD_JBNCMFDFDLM, + (void*)RealtimeConnect_H, (void**)&RealtimeConnect_O, "Photon Realtime connect"); + hook(GA + RR::Methods::Photon::OEOMKFKDCCG_JBNCMFDFDLM, + (void*)PunConnect_H, (void**)&PunConnect_O, "Photon PUN connect"); + hook(GA + RR::Methods::Photon::VoiceConnection_ConnectUsingSettings, + (void*)VoiceConnect_H, (void**)&VoiceConnect_O, "Photon Voice connect"); + hook(GA + RR::Methods::Photon::PhotonVoiceNetwork_ConnectUsingSettings, + (void*)VoicePUNConnect_H, (void**)&VoicePUNConnect_O, "Photon Voice PUN connect"); + + std::cout << "[Campus] all hooks installed. target = " << CAMPUS_NAMESERVER_HOST << "\n"; + } +} diff --git a/RetSpoof.asm b/RetSpoof.asm new file mode 100644 index 0000000..f3347fe --- /dev/null +++ b/RetSpoof.asm @@ -0,0 +1,42 @@ + PUBLIC _spoofer_stub + + .code + + _spoofer_stub PROC + pop r11 + pop r10 + mov rax, [rsp + 24] + + mov r10, [rax] + mov [rsp], r10 + + mov r10, [rax + 8] + mov [rax + 8], r11 + + mov [rax + 16], rbx + lea rbx, fixup + mov [rax], rbx + mov rbx, rax + + jmp r10 + + fixup: + sub rsp, 16 + mov rcx, rbx + mov rbx, [rcx + 16] + jmp QWORD PTR [rcx + 8] + _spoofer_stub ENDP + + NtProtectVirtualMemory PROC + mov r10, rcx ; Move first parameter from rcx to r10 (syscall convention) + mov eax, 50h ; Set syscall number for NtProtectVirtualMemory (Windows 10 x64) + test byte ptr [7FFE0308h], 1 ; Check KUSER_SHARED_DATA flag + jnz use_int2e ; If flag is set, use int 2Eh + syscall ; Execute 64-bit system call + ret ; Return with NTSTATUS in eax + use_int2e: + int 2Eh ; Execute 32-bit system call (compatibility) + ret ; Return with NTSTATUS in eax + NtProtectVirtualMemory ENDP + + END \ No newline at end of file diff --git a/RetSpoof.hpp b/RetSpoof.hpp new file mode 100644 index 0000000..0a6e08e --- /dev/null +++ b/RetSpoof.hpp @@ -0,0 +1,146 @@ +#pragma once + +#include +#include +#include + +#ifdef __cplusplus +extern "C" { +#endif + + ULONG32 NTAPI MyZwProtectVirtualMemory( + HANDLE ProcessHandle, + PVOID* BaseAddress, + PULONG RegionSize, + ULONG NewProtect, + PULONG OldProtect + ); + +#ifdef __cplusplus +} +#endif + +namespace detail +{ + extern "C" void* _spoofer_stub(); + + template + static inline auto shellcode_stub_helper( + const void* shell, + Args... args + ) -> Ret + { + auto fn = (Ret(*)(Args...))(shell); + return fn(args...); + } + + template + struct argument_remapper + { + template< + typename Ret, + typename First, + typename Second, + typename Third, + typename Fourth, + typename... Pack + > + static auto do_call( + const void* shell, + void* shell_param, + First first, + Second second, + Third third, + Fourth fourth, + Pack... pack + ) -> Ret + { + return shellcode_stub_helper< + Ret, + First, + Second, + Third, + Fourth, + void*, + void*, + Pack... + >( + shell, + first, + second, + third, + fourth, + shell_param, + nullptr, + pack... + ); + } + }; + + template + struct argument_remapper> + { + template< + typename Ret, + typename First = void*, + typename Second = void*, + typename Third = void*, + typename Fourth = void* + > + static auto do_call( + const void* shell, + void* shell_param, + First first = First{}, + Second second = Second{}, + Third third = Third{}, + Fourth fourth = Fourth{} + ) -> Ret + { + return shellcode_stub_helper< + Ret, + First, + Second, + Third, + Fourth, + void*, + void* + >( + shell, + first, + second, + third, + fourth, + shell_param, + nullptr + ); + } + }; +} + + +template +static inline auto spoof_call( + const void* trampoline, + Ret(*fn)(Args...), + Args... args +) -> Ret +{ + struct shell_params + { + const void* trampoline; + void* function; + void* rbx; + }; + + shell_params p{ trampoline, reinterpret_cast(fn) }; + using mapper = detail::argument_remapper; + return mapper::template do_call((const void*)&detail::_spoofer_stub, &p, args...); +} + +extern "C" LONG NtProtectVirtualMemory( + HANDLE ProcessHandle, + PVOID* BaseAddress, + PULONG NumberOfBytesToProtect, + ULONG NewAccessProtection, + PULONG OldAccessProtection +); diff --git a/buffer.c b/buffer.c new file mode 100644 index 0000000..8f9fbce --- /dev/null +++ b/buffer.c @@ -0,0 +1,312 @@ +/* + * MinHook - The Minimalistic API Hooking Library for x64/x86 + * Copyright (C) 2009-2017 Tsuda Kageyu. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED + * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A + * PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER + * OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING + * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +#include +#include "buffer.h" + +// Size of each memory block. (= page size of VirtualAlloc) +#define MEMORY_BLOCK_SIZE 0x1000 + +// Max range for seeking a memory block. (= 1024MB) +#define MAX_MEMORY_RANGE 0x40000000 + +// Memory protection flags to check the executable address. +#define PAGE_EXECUTE_FLAGS \ + (PAGE_EXECUTE | PAGE_EXECUTE_READ | PAGE_EXECUTE_READWRITE | PAGE_EXECUTE_WRITECOPY) + +// Memory slot. +typedef struct _MEMORY_SLOT +{ + union + { + struct _MEMORY_SLOT *pNext; + UINT8 buffer[MEMORY_SLOT_SIZE]; + }; +} MEMORY_SLOT, *PMEMORY_SLOT; + +// Memory block info. Placed at the head of each block. +typedef struct _MEMORY_BLOCK +{ + struct _MEMORY_BLOCK *pNext; + PMEMORY_SLOT pFree; // First element of the free slot list. + UINT usedCount; +} MEMORY_BLOCK, *PMEMORY_BLOCK; + +//------------------------------------------------------------------------- +// Global Variables: +//------------------------------------------------------------------------- + +// First element of the memory block list. +PMEMORY_BLOCK g_pMemoryBlocks; + +//------------------------------------------------------------------------- +VOID InitializeBuffer(VOID) +{ + // Nothing to do for now. +} + +//------------------------------------------------------------------------- +VOID UninitializeBuffer(VOID) +{ + PMEMORY_BLOCK pBlock = g_pMemoryBlocks; + g_pMemoryBlocks = NULL; + + while (pBlock) + { + PMEMORY_BLOCK pNext = pBlock->pNext; + VirtualFree(pBlock, 0, MEM_RELEASE); + pBlock = pNext; + } +} + +//------------------------------------------------------------------------- +#if defined(_M_X64) || defined(__x86_64__) +static LPVOID FindPrevFreeRegion(LPVOID pAddress, LPVOID pMinAddr, DWORD dwAllocationGranularity) +{ + ULONG_PTR tryAddr = (ULONG_PTR)pAddress; + + // Round down to the allocation granularity. + tryAddr -= tryAddr % dwAllocationGranularity; + + // Start from the previous allocation granularity multiply. + tryAddr -= dwAllocationGranularity; + + while (tryAddr >= (ULONG_PTR)pMinAddr) + { + MEMORY_BASIC_INFORMATION mbi; + if (VirtualQuery((LPVOID)tryAddr, &mbi, sizeof(mbi)) == 0) + break; + + if (mbi.State == MEM_FREE) + return (LPVOID)tryAddr; + + if ((ULONG_PTR)mbi.AllocationBase < dwAllocationGranularity) + break; + + tryAddr = (ULONG_PTR)mbi.AllocationBase - dwAllocationGranularity; + } + + return NULL; +} +#endif + +//------------------------------------------------------------------------- +#if defined(_M_X64) || defined(__x86_64__) +static LPVOID FindNextFreeRegion(LPVOID pAddress, LPVOID pMaxAddr, DWORD dwAllocationGranularity) +{ + ULONG_PTR tryAddr = (ULONG_PTR)pAddress; + + // Round down to the allocation granularity. + tryAddr -= tryAddr % dwAllocationGranularity; + + // Start from the next allocation granularity multiply. + tryAddr += dwAllocationGranularity; + + while (tryAddr <= (ULONG_PTR)pMaxAddr) + { + MEMORY_BASIC_INFORMATION mbi; + if (VirtualQuery((LPVOID)tryAddr, &mbi, sizeof(mbi)) == 0) + break; + + if (mbi.State == MEM_FREE) + return (LPVOID)tryAddr; + + tryAddr = (ULONG_PTR)mbi.BaseAddress + mbi.RegionSize; + + // Round up to the next allocation granularity. + tryAddr += dwAllocationGranularity - 1; + tryAddr -= tryAddr % dwAllocationGranularity; + } + + return NULL; +} +#endif + +//------------------------------------------------------------------------- +static PMEMORY_BLOCK GetMemoryBlock(LPVOID pOrigin) +{ + PMEMORY_BLOCK pBlock; +#if defined(_M_X64) || defined(__x86_64__) + ULONG_PTR minAddr; + ULONG_PTR maxAddr; + + SYSTEM_INFO si; + GetSystemInfo(&si); + minAddr = (ULONG_PTR)si.lpMinimumApplicationAddress; + maxAddr = (ULONG_PTR)si.lpMaximumApplicationAddress; + + // pOrigin ± 512MB + if ((ULONG_PTR)pOrigin > MAX_MEMORY_RANGE && minAddr < (ULONG_PTR)pOrigin - MAX_MEMORY_RANGE) + minAddr = (ULONG_PTR)pOrigin - MAX_MEMORY_RANGE; + + if (maxAddr > (ULONG_PTR)pOrigin + MAX_MEMORY_RANGE) + maxAddr = (ULONG_PTR)pOrigin + MAX_MEMORY_RANGE; + + // Make room for MEMORY_BLOCK_SIZE bytes. + maxAddr -= MEMORY_BLOCK_SIZE - 1; +#endif + + // Look the registered blocks for a reachable one. + for (pBlock = g_pMemoryBlocks; pBlock != NULL; pBlock = pBlock->pNext) + { +#if defined(_M_X64) || defined(__x86_64__) + // Ignore the blocks too far. + if ((ULONG_PTR)pBlock < minAddr || (ULONG_PTR)pBlock >= maxAddr) + continue; +#endif + // The block has at least one unused slot. + if (pBlock->pFree != NULL) + return pBlock; + } + +#if defined(_M_X64) || defined(__x86_64__) + // Alloc a new block above if not found. + { + LPVOID pAlloc = pOrigin; + while ((ULONG_PTR)pAlloc >= minAddr) + { + pAlloc = FindPrevFreeRegion(pAlloc, (LPVOID)minAddr, si.dwAllocationGranularity); + if (pAlloc == NULL) + break; + + pBlock = (PMEMORY_BLOCK)VirtualAlloc( + pAlloc, MEMORY_BLOCK_SIZE, MEM_COMMIT | MEM_RESERVE, PAGE_EXECUTE_READWRITE); + if (pBlock != NULL) + break; + } + } + + // Alloc a new block below if not found. + if (pBlock == NULL) + { + LPVOID pAlloc = pOrigin; + while ((ULONG_PTR)pAlloc <= maxAddr) + { + pAlloc = FindNextFreeRegion(pAlloc, (LPVOID)maxAddr, si.dwAllocationGranularity); + if (pAlloc == NULL) + break; + + pBlock = (PMEMORY_BLOCK)VirtualAlloc( + pAlloc, MEMORY_BLOCK_SIZE, MEM_COMMIT | MEM_RESERVE, PAGE_EXECUTE_READWRITE); + if (pBlock != NULL) + break; + } + } +#else + // In x86 mode, a memory block can be placed anywhere. + pBlock = (PMEMORY_BLOCK)VirtualAlloc( + NULL, MEMORY_BLOCK_SIZE, MEM_COMMIT | MEM_RESERVE, PAGE_EXECUTE_READWRITE); +#endif + + if (pBlock != NULL) + { + // Build a linked list of all the slots. + PMEMORY_SLOT pSlot = (PMEMORY_SLOT)pBlock + 1; + pBlock->pFree = NULL; + pBlock->usedCount = 0; + do + { + pSlot->pNext = pBlock->pFree; + pBlock->pFree = pSlot; + pSlot++; + } while ((ULONG_PTR)pSlot - (ULONG_PTR)pBlock <= MEMORY_BLOCK_SIZE - MEMORY_SLOT_SIZE); + + pBlock->pNext = g_pMemoryBlocks; + g_pMemoryBlocks = pBlock; + } + + return pBlock; +} + +//------------------------------------------------------------------------- +LPVOID AllocateBuffer(LPVOID pOrigin) +{ + PMEMORY_SLOT pSlot; + PMEMORY_BLOCK pBlock = GetMemoryBlock(pOrigin); + if (pBlock == NULL) + return NULL; + + // Remove an unused slot from the list. + pSlot = pBlock->pFree; + pBlock->pFree = pSlot->pNext; + pBlock->usedCount++; +#ifdef _DEBUG + // Fill the slot with INT3 for debugging. + memset(pSlot, 0xCC, sizeof(MEMORY_SLOT)); +#endif + return pSlot; +} + +//------------------------------------------------------------------------- +VOID FreeBuffer(LPVOID pBuffer) +{ + PMEMORY_BLOCK pBlock = g_pMemoryBlocks; + PMEMORY_BLOCK pPrev = NULL; + ULONG_PTR pTargetBlock = ((ULONG_PTR)pBuffer / MEMORY_BLOCK_SIZE) * MEMORY_BLOCK_SIZE; + + while (pBlock != NULL) + { + if ((ULONG_PTR)pBlock == pTargetBlock) + { + PMEMORY_SLOT pSlot = (PMEMORY_SLOT)pBuffer; +#ifdef _DEBUG + // Clear the released slot for debugging. + memset(pSlot, 0x00, sizeof(*pSlot)); +#endif + // Restore the released slot to the list. + pSlot->pNext = pBlock->pFree; + pBlock->pFree = pSlot; + pBlock->usedCount--; + + // Free if unused. + if (pBlock->usedCount == 0) + { + if (pPrev) + pPrev->pNext = pBlock->pNext; + else + g_pMemoryBlocks = pBlock->pNext; + + VirtualFree(pBlock, 0, MEM_RELEASE); + } + + break; + } + + pPrev = pBlock; + pBlock = pBlock->pNext; + } +} + +//------------------------------------------------------------------------- +BOOL IsExecutableAddress(LPVOID pAddress) +{ + MEMORY_BASIC_INFORMATION mi; + VirtualQuery(pAddress, &mi, sizeof(mi)); + + return (mi.State == MEM_COMMIT && (mi.Protect & PAGE_EXECUTE_FLAGS)); +} diff --git a/buffer.h b/buffer.h new file mode 100644 index 0000000..204d551 --- /dev/null +++ b/buffer.h @@ -0,0 +1,42 @@ +/* + * MinHook - The Minimalistic API Hooking Library for x64/x86 + * Copyright (C) 2009-2017 Tsuda Kageyu. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED + * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A + * PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER + * OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING + * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +#pragma once + +// Size of each memory slot. +#if defined(_M_X64) || defined(__x86_64__) + #define MEMORY_SLOT_SIZE 64 +#else + #define MEMORY_SLOT_SIZE 32 +#endif + +VOID InitializeBuffer(VOID); +VOID UninitializeBuffer(VOID); +LPVOID AllocateBuffer(LPVOID pOrigin); +VOID FreeBuffer(LPVOID pBuffer); +BOOL IsExecutableAddress(LPVOID pAddress); diff --git a/globals.h b/globals.h new file mode 100644 index 0000000..e4fa1b6 --- /dev/null +++ b/globals.h @@ -0,0 +1,76 @@ +#pragma once +#include "Inc/Includes.h" + +// Defined at namespace scope but NOT initialized from GetModuleHandle at DLL-load time. +// Suspended-start injection would run those calls when the game hasn't loaded its modules yet, +// dereferencing NULL for NtHeaders and hard-faulting inside DllMain. Instead we set these in +// InitGlobals(), called from InitThread() after the launcher has confirmed the modules are loaded. +uintptr_t GA = 0; +const IMAGE_NT_HEADERS* NtHeaders = nullptr; +uintptr_t Referee = 0; + +uint64_t* RetAddr = nullptr; + +// Called from the DLL's init thread once the game has loaded GameAssembly and Referee. +// Returns true only if both modules are present AND GameAssembly has a readable PE header. +static bool InitGlobals() { + GA = (uintptr_t)GetModuleHandleA("GameAssembly.dll"); + Referee = (uintptr_t)GetModuleHandleA("Referee.dll"); + if (!GA) { printf("[Campus] init: GameAssembly.dll not loaded\n"); return false; } + if (!Referee) { printf("[Campus] init: Referee.dll not loaded\n"); return false; } + auto dos = reinterpret_cast(GA); + if (dos->e_magic != IMAGE_DOS_SIGNATURE) { printf("[Campus] init: GameAssembly has bad DOS header\n"); return false; } + NtHeaders = reinterpret_cast(GA + dos->e_lfanew); + if (NtHeaders->Signature != IMAGE_NT_SIGNATURE) { printf("[Campus] init: GameAssembly has bad NT header\n"); NtHeaders = nullptr; return false; } + printf("[Campus] init: GameAssembly=%p Referee=%p SizeOfImage=0x%X\n", + (void*)GA, (void*)Referee, NtHeaders->OptionalHeader.SizeOfImage); + return true; +} + +template +T read(void* obj, std::ptrdiff_t offset) { + return *(T*)((std::uint8_t*)obj + offset); +} + +template +void set(void* obj, std::ptrdiff_t offset, T val) { + *(T*)((std::uint8_t*)obj + offset) = val; +} + +// Byte-for-byte identical to the pre-refactor version — same offsets, same wcstombs_s call, +// same success/failure branches. Only difference: caller is REQUIRED to delete[] the returned +// buffer (see the ReadIl2CppStringOwned helper below which does that for you). The earlier +// std::string return-by-value refactor was reading empty strings on this build for reasons +// I couldn't pin down without a live debugger, so we revert to the known-working shape. +char* ReadIl2CppString(Il2cppString* il2cppString) { + + if (il2cppString == nullptr) { + return nullptr; + } + + size_t length = static_cast(il2cppString->Length); + const size_t bufferSize = (length + 1) * sizeof(wchar_t); + char* internalString = new char[bufferSize]; + size_t convertedChars = 0; + + errno_t result = wcstombs_s(&convertedChars, internalString, bufferSize, reinterpret_cast(il2cppString) + 0xA, length); + + if (result != 0) { + delete[] internalString; + return nullptr; + } + + return internalString; +} + +// Owning wrapper: reads the IL2CPP string, copies into std::string, frees the intermediate +// buffer. Use this from hot paths (SendRequest_H, log lines) — the raw ReadIl2CppString +// leaks (length+1)*2 bytes per call if the caller doesn't delete[] the return. +#include +inline std::string ReadIl2CppStringOwned(Il2cppString* il2cppString) { + char* raw = ReadIl2CppString(il2cppString); + if (!raw) return {}; + std::string out(raw); + delete[] raw; + return out; +} \ No newline at end of file diff --git a/hde32.c b/hde32.c new file mode 100644 index 0000000..08fa25b --- /dev/null +++ b/hde32.c @@ -0,0 +1,326 @@ +/* + * Hacker Disassembler Engine 32 C + * Copyright (c) 2008-2009, Vyacheslav Patkov. + * All rights reserved. + * + */ + +#if defined(_M_IX86) || defined(__i386__) + +#include "hde32.h" +#include "table32.h" + +unsigned int hde32_disasm(const void *code, hde32s *hs) +{ + uint8_t x, c, *p = (uint8_t *)code, cflags, opcode, pref = 0; + uint8_t *ht = hde32_table, m_mod, m_reg, m_rm, disp_size = 0; + + // Avoid using memset to reduce the footprint. +#ifndef _MSC_VER + memset((LPBYTE)hs, 0, sizeof(hde32s)); +#else + __stosb((LPBYTE)hs, 0, sizeof(hde32s)); +#endif + + for (x = 16; x; x--) + switch (c = *p++) { + case 0xf3: + hs->p_rep = c; + pref |= PRE_F3; + break; + case 0xf2: + hs->p_rep = c; + pref |= PRE_F2; + break; + case 0xf0: + hs->p_lock = c; + pref |= PRE_LOCK; + break; + case 0x26: case 0x2e: case 0x36: + case 0x3e: case 0x64: case 0x65: + hs->p_seg = c; + pref |= PRE_SEG; + break; + case 0x66: + hs->p_66 = c; + pref |= PRE_66; + break; + case 0x67: + hs->p_67 = c; + pref |= PRE_67; + break; + default: + goto pref_done; + } + pref_done: + + hs->flags = (uint32_t)pref << 23; + + if (!pref) + pref |= PRE_NONE; + + if ((hs->opcode = c) == 0x0f) { + hs->opcode2 = c = *p++; + ht += DELTA_OPCODES; + } else if (c >= 0xa0 && c <= 0xa3) { + if (pref & PRE_67) + pref |= PRE_66; + else + pref &= ~PRE_66; + } + + opcode = c; + cflags = ht[ht[opcode / 4] + (opcode % 4)]; + + if (cflags == C_ERROR) { + hs->flags |= F_ERROR | F_ERROR_OPCODE; + cflags = 0; + if ((opcode & -3) == 0x24) + cflags++; + } + + x = 0; + if (cflags & C_GROUP) { + uint16_t t; + t = *(uint16_t *)(ht + (cflags & 0x7f)); + cflags = (uint8_t)t; + x = (uint8_t)(t >> 8); + } + + if (hs->opcode2) { + ht = hde32_table + DELTA_PREFIXES; + if (ht[ht[opcode / 4] + (opcode % 4)] & pref) + hs->flags |= F_ERROR | F_ERROR_OPCODE; + } + + if (cflags & C_MODRM) { + hs->flags |= F_MODRM; + hs->modrm = c = *p++; + hs->modrm_mod = m_mod = c >> 6; + hs->modrm_rm = m_rm = c & 7; + hs->modrm_reg = m_reg = (c & 0x3f) >> 3; + + if (x && ((x << m_reg) & 0x80)) + hs->flags |= F_ERROR | F_ERROR_OPCODE; + + if (!hs->opcode2 && opcode >= 0xd9 && opcode <= 0xdf) { + uint8_t t = opcode - 0xd9; + if (m_mod == 3) { + ht = hde32_table + DELTA_FPU_MODRM + t*8; + t = ht[m_reg] << m_rm; + } else { + ht = hde32_table + DELTA_FPU_REG; + t = ht[t] << m_reg; + } + if (t & 0x80) + hs->flags |= F_ERROR | F_ERROR_OPCODE; + } + + if (pref & PRE_LOCK) { + if (m_mod == 3) { + hs->flags |= F_ERROR | F_ERROR_LOCK; + } else { + uint8_t *table_end, op = opcode; + if (hs->opcode2) { + ht = hde32_table + DELTA_OP2_LOCK_OK; + table_end = ht + DELTA_OP_ONLY_MEM - DELTA_OP2_LOCK_OK; + } else { + ht = hde32_table + DELTA_OP_LOCK_OK; + table_end = ht + DELTA_OP2_LOCK_OK - DELTA_OP_LOCK_OK; + op &= -2; + } + for (; ht != table_end; ht++) + if (*ht++ == op) { + if (!((*ht << m_reg) & 0x80)) + goto no_lock_error; + else + break; + } + hs->flags |= F_ERROR | F_ERROR_LOCK; + no_lock_error: + ; + } + } + + if (hs->opcode2) { + switch (opcode) { + case 0x20: case 0x22: + m_mod = 3; + if (m_reg > 4 || m_reg == 1) + goto error_operand; + else + goto no_error_operand; + case 0x21: case 0x23: + m_mod = 3; + if (m_reg == 4 || m_reg == 5) + goto error_operand; + else + goto no_error_operand; + } + } else { + switch (opcode) { + case 0x8c: + if (m_reg > 5) + goto error_operand; + else + goto no_error_operand; + case 0x8e: + if (m_reg == 1 || m_reg > 5) + goto error_operand; + else + goto no_error_operand; + } + } + + if (m_mod == 3) { + uint8_t *table_end; + if (hs->opcode2) { + ht = hde32_table + DELTA_OP2_ONLY_MEM; + table_end = ht + sizeof(hde32_table) - DELTA_OP2_ONLY_MEM; + } else { + ht = hde32_table + DELTA_OP_ONLY_MEM; + table_end = ht + DELTA_OP2_ONLY_MEM - DELTA_OP_ONLY_MEM; + } + for (; ht != table_end; ht += 2) + if (*ht++ == opcode) { + if (*ht++ & pref && !((*ht << m_reg) & 0x80)) + goto error_operand; + else + break; + } + goto no_error_operand; + } else if (hs->opcode2) { + switch (opcode) { + case 0x50: case 0xd7: case 0xf7: + if (pref & (PRE_NONE | PRE_66)) + goto error_operand; + break; + case 0xd6: + if (pref & (PRE_F2 | PRE_F3)) + goto error_operand; + break; + case 0xc5: + goto error_operand; + } + goto no_error_operand; + } else + goto no_error_operand; + + error_operand: + hs->flags |= F_ERROR | F_ERROR_OPERAND; + no_error_operand: + + c = *p++; + if (m_reg <= 1) { + if (opcode == 0xf6) + cflags |= C_IMM8; + else if (opcode == 0xf7) + cflags |= C_IMM_P66; + } + + switch (m_mod) { + case 0: + if (pref & PRE_67) { + if (m_rm == 6) + disp_size = 2; + } else + if (m_rm == 5) + disp_size = 4; + break; + case 1: + disp_size = 1; + break; + case 2: + disp_size = 2; + if (!(pref & PRE_67)) + disp_size <<= 1; + } + + if (m_mod != 3 && m_rm == 4 && !(pref & PRE_67)) { + hs->flags |= F_SIB; + p++; + hs->sib = c; + hs->sib_scale = c >> 6; + hs->sib_index = (c & 0x3f) >> 3; + if ((hs->sib_base = c & 7) == 5 && !(m_mod & 1)) + disp_size = 4; + } + + p--; + switch (disp_size) { + case 1: + hs->flags |= F_DISP8; + hs->disp.disp8 = *p; + break; + case 2: + hs->flags |= F_DISP16; + hs->disp.disp16 = *(uint16_t *)p; + break; + case 4: + hs->flags |= F_DISP32; + hs->disp.disp32 = *(uint32_t *)p; + } + p += disp_size; + } else if (pref & PRE_LOCK) + hs->flags |= F_ERROR | F_ERROR_LOCK; + + if (cflags & C_IMM_P66) { + if (cflags & C_REL32) { + if (pref & PRE_66) { + hs->flags |= F_IMM16 | F_RELATIVE; + hs->imm.imm16 = *(uint16_t *)p; + p += 2; + goto disasm_done; + } + goto rel32_ok; + } + if (pref & PRE_66) { + hs->flags |= F_IMM16; + hs->imm.imm16 = *(uint16_t *)p; + p += 2; + } else { + hs->flags |= F_IMM32; + hs->imm.imm32 = *(uint32_t *)p; + p += 4; + } + } + + if (cflags & C_IMM16) { + if (hs->flags & F_IMM32) { + hs->flags |= F_IMM16; + hs->disp.disp16 = *(uint16_t *)p; + } else if (hs->flags & F_IMM16) { + hs->flags |= F_2IMM16; + hs->disp.disp16 = *(uint16_t *)p; + } else { + hs->flags |= F_IMM16; + hs->imm.imm16 = *(uint16_t *)p; + } + p += 2; + } + if (cflags & C_IMM8) { + hs->flags |= F_IMM8; + hs->imm.imm8 = *p++; + } + + if (cflags & C_REL32) { + rel32_ok: + hs->flags |= F_IMM32 | F_RELATIVE; + hs->imm.imm32 = *(uint32_t *)p; + p += 4; + } else if (cflags & C_REL8) { + hs->flags |= F_IMM8 | F_RELATIVE; + hs->imm.imm8 = *p++; + } + + disasm_done: + + if ((hs->len = (uint8_t)(p-(uint8_t *)code)) > 15) { + hs->flags |= F_ERROR | F_ERROR_LENGTH; + hs->len = 15; + } + + return (unsigned int)hs->len; +} + +#endif // defined(_M_IX86) || defined(__i386__) diff --git a/hde32.h b/hde32.h new file mode 100644 index 0000000..1112450 --- /dev/null +++ b/hde32.h @@ -0,0 +1,105 @@ +/* + * Hacker Disassembler Engine 32 + * Copyright (c) 2006-2009, Vyacheslav Patkov. + * All rights reserved. + * + * hde32.h: C/C++ header file + * + */ + +#ifndef _HDE32_H_ +#define _HDE32_H_ + +/* stdint.h - C99 standard header + * http://en.wikipedia.org/wiki/stdint.h + * + * if your compiler doesn't contain "stdint.h" header (for + * example, Microsoft Visual C++), you can download file: + * http://www.azillionmonkeys.com/qed/pstdint.h + * and change next line to: + * #include "pstdint.h" + */ +#include "pstdint.h" + +#define F_MODRM 0x00000001 +#define F_SIB 0x00000002 +#define F_IMM8 0x00000004 +#define F_IMM16 0x00000008 +#define F_IMM32 0x00000010 +#define F_DISP8 0x00000020 +#define F_DISP16 0x00000040 +#define F_DISP32 0x00000080 +#define F_RELATIVE 0x00000100 +#define F_2IMM16 0x00000800 +#define F_ERROR 0x00001000 +#define F_ERROR_OPCODE 0x00002000 +#define F_ERROR_LENGTH 0x00004000 +#define F_ERROR_LOCK 0x00008000 +#define F_ERROR_OPERAND 0x00010000 +#define F_PREFIX_REPNZ 0x01000000 +#define F_PREFIX_REPX 0x02000000 +#define F_PREFIX_REP 0x03000000 +#define F_PREFIX_66 0x04000000 +#define F_PREFIX_67 0x08000000 +#define F_PREFIX_LOCK 0x10000000 +#define F_PREFIX_SEG 0x20000000 +#define F_PREFIX_ANY 0x3f000000 + +#define PREFIX_SEGMENT_CS 0x2e +#define PREFIX_SEGMENT_SS 0x36 +#define PREFIX_SEGMENT_DS 0x3e +#define PREFIX_SEGMENT_ES 0x26 +#define PREFIX_SEGMENT_FS 0x64 +#define PREFIX_SEGMENT_GS 0x65 +#define PREFIX_LOCK 0xf0 +#define PREFIX_REPNZ 0xf2 +#define PREFIX_REPX 0xf3 +#define PREFIX_OPERAND_SIZE 0x66 +#define PREFIX_ADDRESS_SIZE 0x67 + +#pragma pack(push,1) + +typedef struct { + uint8_t len; + uint8_t p_rep; + uint8_t p_lock; + uint8_t p_seg; + uint8_t p_66; + uint8_t p_67; + uint8_t opcode; + uint8_t opcode2; + uint8_t modrm; + uint8_t modrm_mod; + uint8_t modrm_reg; + uint8_t modrm_rm; + uint8_t sib; + uint8_t sib_scale; + uint8_t sib_index; + uint8_t sib_base; + union { + uint8_t imm8; + uint16_t imm16; + uint32_t imm32; + } imm; + union { + uint8_t disp8; + uint16_t disp16; + uint32_t disp32; + } disp; + uint32_t flags; +} hde32s; + +#pragma pack(pop) + +#ifdef __cplusplus +extern "C" { +#endif + +/* __cdecl */ +unsigned int hde32_disasm(const void *code, hde32s *hs); + +#ifdef __cplusplus +} +#endif + +#endif /* _HDE32_H_ */ diff --git a/hde64.c b/hde64.c new file mode 100644 index 0000000..c23e2fc --- /dev/null +++ b/hde64.c @@ -0,0 +1,337 @@ +/* + * Hacker Disassembler Engine 64 C + * Copyright (c) 2008-2009, Vyacheslav Patkov. + * All rights reserved. + * + */ + +#if defined(_M_X64) || defined(__x86_64__) + +#include "hde64.h" +#include "table64.h" + +unsigned int hde64_disasm(const void *code, hde64s *hs) +{ + uint8_t x, c, *p = (uint8_t *)code, cflags, opcode, pref = 0; + uint8_t *ht = hde64_table, m_mod, m_reg, m_rm, disp_size = 0; + uint8_t op64 = 0; + + // Avoid using memset to reduce the footprint. +#ifndef _MSC_VER + memset((LPBYTE)hs, 0, sizeof(hde64s)); +#else + __stosb((LPBYTE)hs, 0, sizeof(hde64s)); +#endif + + for (x = 16; x; x--) + switch (c = *p++) { + case 0xf3: + hs->p_rep = c; + pref |= PRE_F3; + break; + case 0xf2: + hs->p_rep = c; + pref |= PRE_F2; + break; + case 0xf0: + hs->p_lock = c; + pref |= PRE_LOCK; + break; + case 0x26: case 0x2e: case 0x36: + case 0x3e: case 0x64: case 0x65: + hs->p_seg = c; + pref |= PRE_SEG; + break; + case 0x66: + hs->p_66 = c; + pref |= PRE_66; + break; + case 0x67: + hs->p_67 = c; + pref |= PRE_67; + break; + default: + goto pref_done; + } + pref_done: + + hs->flags = (uint32_t)pref << 23; + + if (!pref) + pref |= PRE_NONE; + + if ((c & 0xf0) == 0x40) { + hs->flags |= F_PREFIX_REX; + if ((hs->rex_w = (c & 0xf) >> 3) && (*p & 0xf8) == 0xb8) + op64++; + hs->rex_r = (c & 7) >> 2; + hs->rex_x = (c & 3) >> 1; + hs->rex_b = c & 1; + if (((c = *p++) & 0xf0) == 0x40) { + opcode = c; + goto error_opcode; + } + } + + if ((hs->opcode = c) == 0x0f) { + hs->opcode2 = c = *p++; + ht += DELTA_OPCODES; + } else if (c >= 0xa0 && c <= 0xa3) { + op64++; + if (pref & PRE_67) + pref |= PRE_66; + else + pref &= ~PRE_66; + } + + opcode = c; + cflags = ht[ht[opcode / 4] + (opcode % 4)]; + + if (cflags == C_ERROR) { + error_opcode: + hs->flags |= F_ERROR | F_ERROR_OPCODE; + cflags = 0; + if ((opcode & -3) == 0x24) + cflags++; + } + + x = 0; + if (cflags & C_GROUP) { + uint16_t t; + t = *(uint16_t *)(ht + (cflags & 0x7f)); + cflags = (uint8_t)t; + x = (uint8_t)(t >> 8); + } + + if (hs->opcode2) { + ht = hde64_table + DELTA_PREFIXES; + if (ht[ht[opcode / 4] + (opcode % 4)] & pref) + hs->flags |= F_ERROR | F_ERROR_OPCODE; + } + + if (cflags & C_MODRM) { + hs->flags |= F_MODRM; + hs->modrm = c = *p++; + hs->modrm_mod = m_mod = c >> 6; + hs->modrm_rm = m_rm = c & 7; + hs->modrm_reg = m_reg = (c & 0x3f) >> 3; + + if (x && ((x << m_reg) & 0x80)) + hs->flags |= F_ERROR | F_ERROR_OPCODE; + + if (!hs->opcode2 && opcode >= 0xd9 && opcode <= 0xdf) { + uint8_t t = opcode - 0xd9; + if (m_mod == 3) { + ht = hde64_table + DELTA_FPU_MODRM + t*8; + t = ht[m_reg] << m_rm; + } else { + ht = hde64_table + DELTA_FPU_REG; + t = ht[t] << m_reg; + } + if (t & 0x80) + hs->flags |= F_ERROR | F_ERROR_OPCODE; + } + + if (pref & PRE_LOCK) { + if (m_mod == 3) { + hs->flags |= F_ERROR | F_ERROR_LOCK; + } else { + uint8_t *table_end, op = opcode; + if (hs->opcode2) { + ht = hde64_table + DELTA_OP2_LOCK_OK; + table_end = ht + DELTA_OP_ONLY_MEM - DELTA_OP2_LOCK_OK; + } else { + ht = hde64_table + DELTA_OP_LOCK_OK; + table_end = ht + DELTA_OP2_LOCK_OK - DELTA_OP_LOCK_OK; + op &= -2; + } + for (; ht != table_end; ht++) + if (*ht++ == op) { + if (!((*ht << m_reg) & 0x80)) + goto no_lock_error; + else + break; + } + hs->flags |= F_ERROR | F_ERROR_LOCK; + no_lock_error: + ; + } + } + + if (hs->opcode2) { + switch (opcode) { + case 0x20: case 0x22: + m_mod = 3; + if (m_reg > 4 || m_reg == 1) + goto error_operand; + else + goto no_error_operand; + case 0x21: case 0x23: + m_mod = 3; + if (m_reg == 4 || m_reg == 5) + goto error_operand; + else + goto no_error_operand; + } + } else { + switch (opcode) { + case 0x8c: + if (m_reg > 5) + goto error_operand; + else + goto no_error_operand; + case 0x8e: + if (m_reg == 1 || m_reg > 5) + goto error_operand; + else + goto no_error_operand; + } + } + + if (m_mod == 3) { + uint8_t *table_end; + if (hs->opcode2) { + ht = hde64_table + DELTA_OP2_ONLY_MEM; + table_end = ht + sizeof(hde64_table) - DELTA_OP2_ONLY_MEM; + } else { + ht = hde64_table + DELTA_OP_ONLY_MEM; + table_end = ht + DELTA_OP2_ONLY_MEM - DELTA_OP_ONLY_MEM; + } + for (; ht != table_end; ht += 2) + if (*ht++ == opcode) { + if (*ht++ & pref && !((*ht << m_reg) & 0x80)) + goto error_operand; + else + break; + } + goto no_error_operand; + } else if (hs->opcode2) { + switch (opcode) { + case 0x50: case 0xd7: case 0xf7: + if (pref & (PRE_NONE | PRE_66)) + goto error_operand; + break; + case 0xd6: + if (pref & (PRE_F2 | PRE_F3)) + goto error_operand; + break; + case 0xc5: + goto error_operand; + } + goto no_error_operand; + } else + goto no_error_operand; + + error_operand: + hs->flags |= F_ERROR | F_ERROR_OPERAND; + no_error_operand: + + c = *p++; + if (m_reg <= 1) { + if (opcode == 0xf6) + cflags |= C_IMM8; + else if (opcode == 0xf7) + cflags |= C_IMM_P66; + } + + switch (m_mod) { + case 0: + if (pref & PRE_67) { + if (m_rm == 6) + disp_size = 2; + } else + if (m_rm == 5) + disp_size = 4; + break; + case 1: + disp_size = 1; + break; + case 2: + disp_size = 2; + if (!(pref & PRE_67)) + disp_size <<= 1; + } + + if (m_mod != 3 && m_rm == 4) { + hs->flags |= F_SIB; + p++; + hs->sib = c; + hs->sib_scale = c >> 6; + hs->sib_index = (c & 0x3f) >> 3; + if ((hs->sib_base = c & 7) == 5 && !(m_mod & 1)) + disp_size = 4; + } + + p--; + switch (disp_size) { + case 1: + hs->flags |= F_DISP8; + hs->disp.disp8 = *p; + break; + case 2: + hs->flags |= F_DISP16; + hs->disp.disp16 = *(uint16_t *)p; + break; + case 4: + hs->flags |= F_DISP32; + hs->disp.disp32 = *(uint32_t *)p; + } + p += disp_size; + } else if (pref & PRE_LOCK) + hs->flags |= F_ERROR | F_ERROR_LOCK; + + if (cflags & C_IMM_P66) { + if (cflags & C_REL32) { + if (pref & PRE_66) { + hs->flags |= F_IMM16 | F_RELATIVE; + hs->imm.imm16 = *(uint16_t *)p; + p += 2; + goto disasm_done; + } + goto rel32_ok; + } + if (op64) { + hs->flags |= F_IMM64; + hs->imm.imm64 = *(uint64_t *)p; + p += 8; + } else if (!(pref & PRE_66)) { + hs->flags |= F_IMM32; + hs->imm.imm32 = *(uint32_t *)p; + p += 4; + } else + goto imm16_ok; + } + + + if (cflags & C_IMM16) { + imm16_ok: + hs->flags |= F_IMM16; + hs->imm.imm16 = *(uint16_t *)p; + p += 2; + } + if (cflags & C_IMM8) { + hs->flags |= F_IMM8; + hs->imm.imm8 = *p++; + } + + if (cflags & C_REL32) { + rel32_ok: + hs->flags |= F_IMM32 | F_RELATIVE; + hs->imm.imm32 = *(uint32_t *)p; + p += 4; + } else if (cflags & C_REL8) { + hs->flags |= F_IMM8 | F_RELATIVE; + hs->imm.imm8 = *p++; + } + + disasm_done: + + if ((hs->len = (uint8_t)(p-(uint8_t *)code)) > 15) { + hs->flags |= F_ERROR | F_ERROR_LENGTH; + hs->len = 15; + } + + return (unsigned int)hs->len; +} + +#endif // defined(_M_X64) || defined(__x86_64__) diff --git a/hde64.h b/hde64.h new file mode 100644 index 0000000..ecbf4df --- /dev/null +++ b/hde64.h @@ -0,0 +1,112 @@ +/* + * Hacker Disassembler Engine 64 + * Copyright (c) 2008-2009, Vyacheslav Patkov. + * All rights reserved. + * + * hde64.h: C/C++ header file + * + */ + +#ifndef _HDE64_H_ +#define _HDE64_H_ + +/* stdint.h - C99 standard header + * http://en.wikipedia.org/wiki/stdint.h + * + * if your compiler doesn't contain "stdint.h" header (for + * example, Microsoft Visual C++), you can download file: + * http://www.azillionmonkeys.com/qed/pstdint.h + * and change next line to: + * #include "pstdint.h" + */ +#include "pstdint.h" + +#define F_MODRM 0x00000001 +#define F_SIB 0x00000002 +#define F_IMM8 0x00000004 +#define F_IMM16 0x00000008 +#define F_IMM32 0x00000010 +#define F_IMM64 0x00000020 +#define F_DISP8 0x00000040 +#define F_DISP16 0x00000080 +#define F_DISP32 0x00000100 +#define F_RELATIVE 0x00000200 +#define F_ERROR 0x00001000 +#define F_ERROR_OPCODE 0x00002000 +#define F_ERROR_LENGTH 0x00004000 +#define F_ERROR_LOCK 0x00008000 +#define F_ERROR_OPERAND 0x00010000 +#define F_PREFIX_REPNZ 0x01000000 +#define F_PREFIX_REPX 0x02000000 +#define F_PREFIX_REP 0x03000000 +#define F_PREFIX_66 0x04000000 +#define F_PREFIX_67 0x08000000 +#define F_PREFIX_LOCK 0x10000000 +#define F_PREFIX_SEG 0x20000000 +#define F_PREFIX_REX 0x40000000 +#define F_PREFIX_ANY 0x7f000000 + +#define PREFIX_SEGMENT_CS 0x2e +#define PREFIX_SEGMENT_SS 0x36 +#define PREFIX_SEGMENT_DS 0x3e +#define PREFIX_SEGMENT_ES 0x26 +#define PREFIX_SEGMENT_FS 0x64 +#define PREFIX_SEGMENT_GS 0x65 +#define PREFIX_LOCK 0xf0 +#define PREFIX_REPNZ 0xf2 +#define PREFIX_REPX 0xf3 +#define PREFIX_OPERAND_SIZE 0x66 +#define PREFIX_ADDRESS_SIZE 0x67 + +#pragma pack(push,1) + +typedef struct { + uint8_t len; + uint8_t p_rep; + uint8_t p_lock; + uint8_t p_seg; + uint8_t p_66; + uint8_t p_67; + uint8_t rex; + uint8_t rex_w; + uint8_t rex_r; + uint8_t rex_x; + uint8_t rex_b; + uint8_t opcode; + uint8_t opcode2; + uint8_t modrm; + uint8_t modrm_mod; + uint8_t modrm_reg; + uint8_t modrm_rm; + uint8_t sib; + uint8_t sib_scale; + uint8_t sib_index; + uint8_t sib_base; + union { + uint8_t imm8; + uint16_t imm16; + uint32_t imm32; + uint64_t imm64; + } imm; + union { + uint8_t disp8; + uint16_t disp16; + uint32_t disp32; + } disp; + uint32_t flags; +} hde64s; + +#pragma pack(pop) + +#ifdef __cplusplus +extern "C" { +#endif + +/* __cdecl */ +unsigned int hde64_disasm(const void *code, hde64s *hs); + +#ifdef __cplusplus +} +#endif + +#endif /* _HDE64_H_ */ diff --git a/hook.c b/hook.c new file mode 100644 index 0000000..ce65e57 --- /dev/null +++ b/hook.c @@ -0,0 +1,889 @@ +/* + * MinHook - The Minimalistic API Hooking Library for x64/x86 + * Copyright (C) 2009-2017 Tsuda Kageyu. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED + * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A + * PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER + * OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING + * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +#include +#include +#include + +#include "../include/MinHook.h" +#include "buffer.h" +#include "trampoline.h" + +#ifndef ARRAYSIZE + #define ARRAYSIZE(A) (sizeof(A)/sizeof((A)[0])) +#endif + +// Initial capacity of the HOOK_ENTRY buffer. +#define INITIAL_HOOK_CAPACITY 32 + +// Initial capacity of the thread IDs buffer. +#define INITIAL_THREAD_CAPACITY 128 + +// Special hook position values. +#define INVALID_HOOK_POS UINT_MAX +#define ALL_HOOKS_POS UINT_MAX + +// Freeze() action argument defines. +#define ACTION_DISABLE 0 +#define ACTION_ENABLE 1 +#define ACTION_APPLY_QUEUED 2 + +// Thread access rights for suspending/resuming threads. +#define THREAD_ACCESS \ + (THREAD_SUSPEND_RESUME | THREAD_GET_CONTEXT | THREAD_QUERY_INFORMATION | THREAD_SET_CONTEXT) + +// Hook information. +typedef struct _HOOK_ENTRY +{ + LPVOID pTarget; // Address of the target function. + LPVOID pDetour; // Address of the detour or relay function. + LPVOID pTrampoline; // Address of the trampoline function. + UINT8 backup[8]; // Original prologue of the target function. + + UINT8 patchAbove : 1; // Uses the hot patch area. + UINT8 isEnabled : 1; // Enabled. + UINT8 queueEnable : 1; // Queued for enabling/disabling when != isEnabled. + + UINT nIP : 4; // Count of the instruction boundaries. + UINT8 oldIPs[8]; // Instruction boundaries of the target function. + UINT8 newIPs[8]; // Instruction boundaries of the trampoline function. +} HOOK_ENTRY, *PHOOK_ENTRY; + +// Suspended threads for Freeze()/Unfreeze(). +typedef struct _FROZEN_THREADS +{ + LPDWORD pItems; // Data heap + UINT capacity; // Size of allocated data heap, items + UINT size; // Actual number of data items +} FROZEN_THREADS, *PFROZEN_THREADS; + +//------------------------------------------------------------------------- +// Global Variables: +//------------------------------------------------------------------------- + +// Spin lock flag for EnterSpinLock()/LeaveSpinLock(). +volatile LONG g_isLocked = FALSE; + +// Private heap handle. If not NULL, this library is initialized. +HANDLE g_hHeap = NULL; + +// Hook entries. +struct +{ + PHOOK_ENTRY pItems; // Data heap + UINT capacity; // Size of allocated data heap, items + UINT size; // Actual number of data items +} g_hooks; + +//------------------------------------------------------------------------- +// Returns INVALID_HOOK_POS if not found. +static UINT FindHookEntry(LPVOID pTarget) +{ + UINT i; + for (i = 0; i < g_hooks.size; ++i) + { + if ((ULONG_PTR)pTarget == (ULONG_PTR)g_hooks.pItems[i].pTarget) + return i; + } + + return INVALID_HOOK_POS; +} + +//------------------------------------------------------------------------- +static PHOOK_ENTRY AddHookEntry() +{ + if (g_hooks.pItems == NULL) + { + g_hooks.capacity = INITIAL_HOOK_CAPACITY; + g_hooks.pItems = (PHOOK_ENTRY)HeapAlloc( + g_hHeap, 0, g_hooks.capacity * sizeof(HOOK_ENTRY)); + if (g_hooks.pItems == NULL) + return NULL; + } + else if (g_hooks.size >= g_hooks.capacity) + { + PHOOK_ENTRY p = (PHOOK_ENTRY)HeapReAlloc( + g_hHeap, 0, g_hooks.pItems, (g_hooks.capacity * 2) * sizeof(HOOK_ENTRY)); + if (p == NULL) + return NULL; + + g_hooks.capacity *= 2; + g_hooks.pItems = p; + } + + return &g_hooks.pItems[g_hooks.size++]; +} + +//------------------------------------------------------------------------- +static void DeleteHookEntry(UINT pos) +{ + if (pos < g_hooks.size - 1) + g_hooks.pItems[pos] = g_hooks.pItems[g_hooks.size - 1]; + + g_hooks.size--; + + if (g_hooks.capacity / 2 >= INITIAL_HOOK_CAPACITY && g_hooks.capacity / 2 >= g_hooks.size) + { + PHOOK_ENTRY p = (PHOOK_ENTRY)HeapReAlloc( + g_hHeap, 0, g_hooks.pItems, (g_hooks.capacity / 2) * sizeof(HOOK_ENTRY)); + if (p == NULL) + return; + + g_hooks.capacity /= 2; + g_hooks.pItems = p; + } +} + +//------------------------------------------------------------------------- +static DWORD_PTR FindOldIP(PHOOK_ENTRY pHook, DWORD_PTR ip) +{ + UINT i; + + if (pHook->patchAbove && ip == ((DWORD_PTR)pHook->pTarget - sizeof(JMP_REL))) + return (DWORD_PTR)pHook->pTarget; + + for (i = 0; i < pHook->nIP; ++i) + { + if (ip == ((DWORD_PTR)pHook->pTrampoline + pHook->newIPs[i])) + return (DWORD_PTR)pHook->pTarget + pHook->oldIPs[i]; + } + +#if defined(_M_X64) || defined(__x86_64__) + // Check relay function. + if (ip == (DWORD_PTR)pHook->pDetour) + return (DWORD_PTR)pHook->pTarget; +#endif + + return 0; +} + +//------------------------------------------------------------------------- +static DWORD_PTR FindNewIP(PHOOK_ENTRY pHook, DWORD_PTR ip) +{ + UINT i; + for (i = 0; i < pHook->nIP; ++i) + { + if (ip == ((DWORD_PTR)pHook->pTarget + pHook->oldIPs[i])) + return (DWORD_PTR)pHook->pTrampoline + pHook->newIPs[i]; + } + + return 0; +} + +//------------------------------------------------------------------------- +static void ProcessThreadIPs(HANDLE hThread, UINT pos, UINT action) +{ + // If the thread suspended in the overwritten area, + // move IP to the proper address. + + CONTEXT c; +#if defined(_M_X64) || defined(__x86_64__) + DWORD64 *pIP = &c.Rip; +#else + DWORD *pIP = &c.Eip; +#endif + UINT count; + + c.ContextFlags = CONTEXT_CONTROL; + if (!GetThreadContext(hThread, &c)) + return; + + if (pos == ALL_HOOKS_POS) + { + pos = 0; + count = g_hooks.size; + } + else + { + count = pos + 1; + } + + for (; pos < count; ++pos) + { + PHOOK_ENTRY pHook = &g_hooks.pItems[pos]; + BOOL enable; + DWORD_PTR ip; + + switch (action) + { + case ACTION_DISABLE: + enable = FALSE; + break; + + case ACTION_ENABLE: + enable = TRUE; + break; + + default: // ACTION_APPLY_QUEUED + enable = pHook->queueEnable; + break; + } + if (pHook->isEnabled == enable) + continue; + + if (enable) + ip = FindNewIP(pHook, *pIP); + else + ip = FindOldIP(pHook, *pIP); + + if (ip != 0) + { + *pIP = ip; + SetThreadContext(hThread, &c); + } + } +} + +//------------------------------------------------------------------------- +static VOID EnumerateThreads(PFROZEN_THREADS pThreads) +{ + HANDLE hSnapshot = CreateToolhelp32Snapshot(TH32CS_SNAPTHREAD, 0); + if (hSnapshot != INVALID_HANDLE_VALUE) + { + THREADENTRY32 te; + te.dwSize = sizeof(THREADENTRY32); + if (Thread32First(hSnapshot, &te)) + { + do + { + if (te.dwSize >= (FIELD_OFFSET(THREADENTRY32, th32OwnerProcessID) + sizeof(DWORD)) + && te.th32OwnerProcessID == GetCurrentProcessId() + && te.th32ThreadID != GetCurrentThreadId()) + { + if (pThreads->pItems == NULL) + { + pThreads->capacity = INITIAL_THREAD_CAPACITY; + pThreads->pItems + = (LPDWORD)HeapAlloc(g_hHeap, 0, pThreads->capacity * sizeof(DWORD)); + if (pThreads->pItems == NULL) + break; + } + else if (pThreads->size >= pThreads->capacity) + { + LPDWORD p = (LPDWORD)HeapReAlloc( + g_hHeap, 0, pThreads->pItems, (pThreads->capacity * 2) * sizeof(DWORD)); + if (p == NULL) + break; + + pThreads->capacity *= 2; + pThreads->pItems = p; + } + pThreads->pItems[pThreads->size++] = te.th32ThreadID; + } + + te.dwSize = sizeof(THREADENTRY32); + } while (Thread32Next(hSnapshot, &te)); + } + CloseHandle(hSnapshot); + } +} + +//------------------------------------------------------------------------- +static VOID Freeze(PFROZEN_THREADS pThreads, UINT pos, UINT action) +{ + pThreads->pItems = NULL; + pThreads->capacity = 0; + pThreads->size = 0; + EnumerateThreads(pThreads); + + if (pThreads->pItems != NULL) + { + UINT i; + for (i = 0; i < pThreads->size; ++i) + { + HANDLE hThread = OpenThread(THREAD_ACCESS, FALSE, pThreads->pItems[i]); + if (hThread != NULL) + { + SuspendThread(hThread); + ProcessThreadIPs(hThread, pos, action); + CloseHandle(hThread); + } + } + } +} + +//------------------------------------------------------------------------- +static VOID Unfreeze(PFROZEN_THREADS pThreads) +{ + if (pThreads->pItems != NULL) + { + UINT i; + for (i = 0; i < pThreads->size; ++i) + { + HANDLE hThread = OpenThread(THREAD_ACCESS, FALSE, pThreads->pItems[i]); + if (hThread != NULL) + { + ResumeThread(hThread); + CloseHandle(hThread); + } + } + + HeapFree(g_hHeap, 0, pThreads->pItems); + } +} + +//------------------------------------------------------------------------- +static MH_STATUS EnableHookLL(UINT pos, BOOL enable) +{ + PHOOK_ENTRY pHook = &g_hooks.pItems[pos]; + DWORD oldProtect; + SIZE_T patchSize = sizeof(JMP_REL); + LPBYTE pPatchTarget = (LPBYTE)pHook->pTarget; + + if (pHook->patchAbove) + { + pPatchTarget -= sizeof(JMP_REL); + patchSize += sizeof(JMP_REL_SHORT); + } + + if (!VirtualProtect(pPatchTarget, patchSize, PAGE_EXECUTE_READWRITE, &oldProtect)) + return MH_ERROR_MEMORY_PROTECT; + + if (enable) + { + PJMP_REL pJmp = (PJMP_REL)pPatchTarget; + pJmp->opcode = 0xE9; + pJmp->operand = (UINT32)((LPBYTE)pHook->pDetour - (pPatchTarget + sizeof(JMP_REL))); + + if (pHook->patchAbove) + { + PJMP_REL_SHORT pShortJmp = (PJMP_REL_SHORT)pHook->pTarget; + pShortJmp->opcode = 0xEB; + pShortJmp->operand = (UINT8)(0 - (sizeof(JMP_REL_SHORT) + sizeof(JMP_REL))); + } + } + else + { + if (pHook->patchAbove) + memcpy(pPatchTarget, pHook->backup, sizeof(JMP_REL) + sizeof(JMP_REL_SHORT)); + else + memcpy(pPatchTarget, pHook->backup, sizeof(JMP_REL)); + } + + VirtualProtect(pPatchTarget, patchSize, oldProtect, &oldProtect); + + // Just-in-case measure. + FlushInstructionCache(GetCurrentProcess(), pPatchTarget, patchSize); + + pHook->isEnabled = enable; + pHook->queueEnable = enable; + + return MH_OK; +} + +//------------------------------------------------------------------------- +static MH_STATUS EnableAllHooksLL(BOOL enable) +{ + MH_STATUS status = MH_OK; + UINT i, first = INVALID_HOOK_POS; + + for (i = 0; i < g_hooks.size; ++i) + { + if (g_hooks.pItems[i].isEnabled != enable) + { + first = i; + break; + } + } + + if (first != INVALID_HOOK_POS) + { + FROZEN_THREADS threads; + Freeze(&threads, ALL_HOOKS_POS, enable ? ACTION_ENABLE : ACTION_DISABLE); + + for (i = first; i < g_hooks.size; ++i) + { + if (g_hooks.pItems[i].isEnabled != enable) + { + status = EnableHookLL(i, enable); + if (status != MH_OK) + break; + } + } + + Unfreeze(&threads); + } + + return status; +} + +//------------------------------------------------------------------------- +static VOID EnterSpinLock(VOID) +{ + SIZE_T spinCount = 0; + + // Wait until the flag is FALSE. + while (InterlockedCompareExchange(&g_isLocked, TRUE, FALSE) != FALSE) + { + // No need to generate a memory barrier here, since InterlockedCompareExchange() + // generates a full memory barrier itself. + + // Prevent the loop from being too busy. + if (spinCount < 32) + Sleep(0); + else + Sleep(1); + + spinCount++; + } +} + +//------------------------------------------------------------------------- +static VOID LeaveSpinLock(VOID) +{ + // No need to generate a memory barrier here, since InterlockedExchange() + // generates a full memory barrier itself. + + InterlockedExchange(&g_isLocked, FALSE); +} + +//------------------------------------------------------------------------- +MH_STATUS WINAPI MH_Initialize(VOID) +{ + MH_STATUS status = MH_OK; + + EnterSpinLock(); + + if (g_hHeap == NULL) + { + g_hHeap = HeapCreate(0, 0, 0); + if (g_hHeap != NULL) + { + // Initialize the internal function buffer. + InitializeBuffer(); + } + else + { + status = MH_ERROR_MEMORY_ALLOC; + } + } + else + { + status = MH_ERROR_ALREADY_INITIALIZED; + } + + LeaveSpinLock(); + + return status; +} + +//------------------------------------------------------------------------- +MH_STATUS WINAPI MH_Uninitialize(VOID) +{ + MH_STATUS status = MH_OK; + + EnterSpinLock(); + + if (g_hHeap != NULL) + { + status = EnableAllHooksLL(FALSE); + if (status == MH_OK) + { + // Free the internal function buffer. + + // HeapFree is actually not required, but some tools detect a false + // memory leak without HeapFree. + + UninitializeBuffer(); + + HeapFree(g_hHeap, 0, g_hooks.pItems); + HeapDestroy(g_hHeap); + + g_hHeap = NULL; + + g_hooks.pItems = NULL; + g_hooks.capacity = 0; + g_hooks.size = 0; + } + } + else + { + status = MH_ERROR_NOT_INITIALIZED; + } + + LeaveSpinLock(); + + return status; +} + +//------------------------------------------------------------------------- +MH_STATUS WINAPI MH_CreateHook(LPVOID pTarget, LPVOID pDetour, LPVOID *ppOriginal) +{ + MH_STATUS status = MH_OK; + + EnterSpinLock(); + + if (g_hHeap != NULL) + { + if (IsExecutableAddress(pTarget) && IsExecutableAddress(pDetour)) + { + UINT pos = FindHookEntry(pTarget); + if (pos == INVALID_HOOK_POS) + { + LPVOID pBuffer = AllocateBuffer(pTarget); + if (pBuffer != NULL) + { + TRAMPOLINE ct; + + ct.pTarget = pTarget; + ct.pDetour = pDetour; + ct.pTrampoline = pBuffer; + if (CreateTrampolineFunction(&ct)) + { + PHOOK_ENTRY pHook = AddHookEntry(); + if (pHook != NULL) + { + pHook->pTarget = ct.pTarget; +#if defined(_M_X64) || defined(__x86_64__) + pHook->pDetour = ct.pRelay; +#else + pHook->pDetour = ct.pDetour; +#endif + pHook->pTrampoline = ct.pTrampoline; + pHook->patchAbove = ct.patchAbove; + pHook->isEnabled = FALSE; + pHook->queueEnable = FALSE; + pHook->nIP = ct.nIP; + memcpy(pHook->oldIPs, ct.oldIPs, ARRAYSIZE(ct.oldIPs)); + memcpy(pHook->newIPs, ct.newIPs, ARRAYSIZE(ct.newIPs)); + + // Back up the target function. + + if (ct.patchAbove) + { + memcpy( + pHook->backup, + (LPBYTE)pTarget - sizeof(JMP_REL), + sizeof(JMP_REL) + sizeof(JMP_REL_SHORT)); + } + else + { + memcpy(pHook->backup, pTarget, sizeof(JMP_REL)); + } + + if (ppOriginal != NULL) + *ppOriginal = pHook->pTrampoline; + } + else + { + status = MH_ERROR_MEMORY_ALLOC; + } + } + else + { + status = MH_ERROR_UNSUPPORTED_FUNCTION; + } + + if (status != MH_OK) + { + FreeBuffer(pBuffer); + } + } + else + { + status = MH_ERROR_MEMORY_ALLOC; + } + } + else + { + status = MH_ERROR_ALREADY_CREATED; + } + } + else + { + status = MH_ERROR_NOT_EXECUTABLE; + } + } + else + { + status = MH_ERROR_NOT_INITIALIZED; + } + + LeaveSpinLock(); + + return status; +} + +//------------------------------------------------------------------------- +MH_STATUS WINAPI MH_RemoveHook(LPVOID pTarget) +{ + MH_STATUS status = MH_OK; + + EnterSpinLock(); + + if (g_hHeap != NULL) + { + UINT pos = FindHookEntry(pTarget); + if (pos != INVALID_HOOK_POS) + { + if (g_hooks.pItems[pos].isEnabled) + { + FROZEN_THREADS threads; + Freeze(&threads, pos, ACTION_DISABLE); + + status = EnableHookLL(pos, FALSE); + + Unfreeze(&threads); + } + + if (status == MH_OK) + { + FreeBuffer(g_hooks.pItems[pos].pTrampoline); + DeleteHookEntry(pos); + } + } + else + { + status = MH_ERROR_NOT_CREATED; + } + } + else + { + status = MH_ERROR_NOT_INITIALIZED; + } + + LeaveSpinLock(); + + return status; +} + +//------------------------------------------------------------------------- +static MH_STATUS EnableHook(LPVOID pTarget, BOOL enable) +{ + MH_STATUS status = MH_OK; + + EnterSpinLock(); + + if (g_hHeap != NULL) + { + if (pTarget == MH_ALL_HOOKS) + { + status = EnableAllHooksLL(enable); + } + else + { + FROZEN_THREADS threads; + UINT pos = FindHookEntry(pTarget); + if (pos != INVALID_HOOK_POS) + { + if (g_hooks.pItems[pos].isEnabled != enable) + { + Freeze(&threads, pos, ACTION_ENABLE); + + status = EnableHookLL(pos, enable); + + Unfreeze(&threads); + } + else + { + status = enable ? MH_ERROR_ENABLED : MH_ERROR_DISABLED; + } + } + else + { + status = MH_ERROR_NOT_CREATED; + } + } + } + else + { + status = MH_ERROR_NOT_INITIALIZED; + } + + LeaveSpinLock(); + + return status; +} + +//------------------------------------------------------------------------- +MH_STATUS WINAPI MH_EnableHook(LPVOID pTarget) +{ + return EnableHook(pTarget, TRUE); +} + +//------------------------------------------------------------------------- +MH_STATUS WINAPI MH_DisableHook(LPVOID pTarget) +{ + return EnableHook(pTarget, FALSE); +} + +//------------------------------------------------------------------------- +static MH_STATUS QueueHook(LPVOID pTarget, BOOL queueEnable) +{ + MH_STATUS status = MH_OK; + + EnterSpinLock(); + + if (g_hHeap != NULL) + { + if (pTarget == MH_ALL_HOOKS) + { + UINT i; + for (i = 0; i < g_hooks.size; ++i) + g_hooks.pItems[i].queueEnable = queueEnable; + } + else + { + UINT pos = FindHookEntry(pTarget); + if (pos != INVALID_HOOK_POS) + { + g_hooks.pItems[pos].queueEnable = queueEnable; + } + else + { + status = MH_ERROR_NOT_CREATED; + } + } + } + else + { + status = MH_ERROR_NOT_INITIALIZED; + } + + LeaveSpinLock(); + + return status; +} + +//------------------------------------------------------------------------- +MH_STATUS WINAPI MH_QueueEnableHook(LPVOID pTarget) +{ + return QueueHook(pTarget, TRUE); +} + +//------------------------------------------------------------------------- +MH_STATUS WINAPI MH_QueueDisableHook(LPVOID pTarget) +{ + return QueueHook(pTarget, FALSE); +} + +//------------------------------------------------------------------------- +MH_STATUS WINAPI MH_ApplyQueued(VOID) +{ + MH_STATUS status = MH_OK; + UINT i, first = INVALID_HOOK_POS; + + EnterSpinLock(); + + if (g_hHeap != NULL) + { + for (i = 0; i < g_hooks.size; ++i) + { + if (g_hooks.pItems[i].isEnabled != g_hooks.pItems[i].queueEnable) + { + first = i; + break; + } + } + + if (first != INVALID_HOOK_POS) + { + FROZEN_THREADS threads; + Freeze(&threads, ALL_HOOKS_POS, ACTION_APPLY_QUEUED); + + for (i = first; i < g_hooks.size; ++i) + { + PHOOK_ENTRY pHook = &g_hooks.pItems[i]; + if (pHook->isEnabled != pHook->queueEnable) + { + status = EnableHookLL(i, pHook->queueEnable); + if (status != MH_OK) + break; + } + } + + Unfreeze(&threads); + } + } + else + { + status = MH_ERROR_NOT_INITIALIZED; + } + + LeaveSpinLock(); + + return status; +} + +//------------------------------------------------------------------------- +MH_STATUS WINAPI MH_CreateHookApiEx( + LPCWSTR pszModule, LPCSTR pszProcName, LPVOID pDetour, + LPVOID *ppOriginal, LPVOID *ppTarget) +{ + HMODULE hModule; + LPVOID pTarget; + + hModule = GetModuleHandleW(pszModule); + if (hModule == NULL) + return MH_ERROR_MODULE_NOT_FOUND; + + pTarget = (LPVOID)GetProcAddress(hModule, pszProcName); + if (pTarget == NULL) + return MH_ERROR_FUNCTION_NOT_FOUND; + + if(ppTarget != NULL) + *ppTarget = pTarget; + + return MH_CreateHook(pTarget, pDetour, ppOriginal); +} + +//------------------------------------------------------------------------- +MH_STATUS WINAPI MH_CreateHookApi( + LPCWSTR pszModule, LPCSTR pszProcName, LPVOID pDetour, LPVOID *ppOriginal) +{ + return MH_CreateHookApiEx(pszModule, pszProcName, pDetour, ppOriginal, NULL); +} + +//------------------------------------------------------------------------- +const char * WINAPI MH_StatusToString(MH_STATUS status) +{ +#define MH_ST2STR(x) \ + case x: \ + return #x; + + switch (status) { + MH_ST2STR(MH_UNKNOWN) + MH_ST2STR(MH_OK) + MH_ST2STR(MH_ERROR_ALREADY_INITIALIZED) + MH_ST2STR(MH_ERROR_NOT_INITIALIZED) + MH_ST2STR(MH_ERROR_ALREADY_CREATED) + MH_ST2STR(MH_ERROR_NOT_CREATED) + MH_ST2STR(MH_ERROR_ENABLED) + MH_ST2STR(MH_ERROR_DISABLED) + MH_ST2STR(MH_ERROR_NOT_EXECUTABLE) + MH_ST2STR(MH_ERROR_UNSUPPORTED_FUNCTION) + MH_ST2STR(MH_ERROR_MEMORY_ALLOC) + MH_ST2STR(MH_ERROR_MEMORY_PROTECT) + MH_ST2STR(MH_ERROR_MODULE_NOT_FOUND) + MH_ST2STR(MH_ERROR_FUNCTION_NOT_FOUND) + } + +#undef MH_ST2STR + + return "(unknown)"; +} diff --git a/logging.h b/logging.h new file mode 100644 index 0000000..e0f0c00 --- /dev/null +++ b/logging.h @@ -0,0 +1,176 @@ +#pragma once +// CampusPatch console tee: mirrors every std::cout write into a per-session log file next to +// the DLL. Existing call sites (`std::cout << ...`) don't need to change - the redirect is +// transparent once Init() runs. +// +// File path: \Logs\logsession.txt (BST timestamp) +// Header: date/time in BST + full log path, so opening the file cold identifies the session. +// +// Implementation note: an earlier revision used std::ofstream + std::cout.rdbuf() and swapped +// buffers. That interacted badly with the game's CRT (crash on first write). This version uses +// only raw Win32 HANDLEs and WriteFile, so nothing about std::cout's original rdbuf, the game's +// C++ runtime state, or std::sync_with_stdio matters. If Init fails for any reason we simply +// leave logging in console-only mode - the game keeps running. + +#include +#include +#include +#include +#include +#include + +namespace CampusLogging { + +// A streambuf whose overflow/xsputn write bytes to two Win32 handles: the process's console +// (CONOUT$) and a session log file. We deliberately don't chain to a "parent" streambuf - by +// writing to CONOUT$ ourselves we avoid ever touching the original std::cout rdbuf and its +// unclear ownership/lifetime relationship with the CRT. +// +// Concurrency: multiple hook threads write concurrently (heartbeat + SendRequest + Steam +// callbacks + SteamHookThread's install log all race). A CRITICAL_SECTION guards each write so +// individual `std::cout << ...` chains land as atomic byte groups instead of interleaving. +class TeeBuf : public std::streambuf { + HANDLE hConsole_ = INVALID_HANDLE_VALUE; + HANDLE hFile_ = INVALID_HANDLE_VALUE; + CRITICAL_SECTION cs_{}; +public: + TeeBuf() { InitializeCriticalSection(&cs_); } + + // Open both destinations. Returns true iff the FILE handle is valid; console failure is + // tolerated (we'll silently drop the console mirror if CONOUT$ can't be opened, which + // shouldn't happen since CreateConsole() already AllocConsole'd it). + bool Open(const std::string& path) { + hConsole_ = CreateFileA("CONOUT$", + GENERIC_WRITE, + FILE_SHARE_WRITE | FILE_SHARE_READ, + nullptr, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, nullptr); + hFile_ = CreateFileA(path.c_str(), + GENERIC_WRITE, + FILE_SHARE_READ, + nullptr, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, nullptr); + return hFile_ != INVALID_HANDLE_VALUE; + } + + HANDLE FileHandle() const { return hFile_; } + +protected: + int overflow(int ch) override { + if (ch == traits_type::eof()) { sync(); return 0; } + char c = static_cast(ch); + writeBoth(&c, 1); + // Flush the file on newline so a crash leaves the last line on disk. + if (c == '\n' && hFile_ != INVALID_HANDLE_VALUE) FlushFileBuffers(hFile_); + return ch; + } + std::streamsize xsputn(const char* s, std::streamsize n) override { + if (n <= 0) return n; + writeBoth(s, static_cast(n)); + // Flush on any newline in the batch. + for (std::streamsize i = 0; i < n; i++) { + if (s[i] == '\n' && hFile_ != INVALID_HANDLE_VALUE) { + FlushFileBuffers(hFile_); + break; + } + } + return n; + } + int sync() override { + if (hFile_ != INVALID_HANDLE_VALUE) FlushFileBuffers(hFile_); + return 0; + } + +private: + // Serialise writes across threads so a `std::cout << "a"` chain from one thread doesn't + // interleave mid-word with another thread's chain. NOT full line-based - streambuf gets + // called per fragment, so bytes from different `<<` chains can still interleave between + // fragments; but individual fragments are now atomic, and the batch flush on newline keeps + // sub-word tearing rare in practice. + void writeBoth(const char* p, DWORD n) { + EnterCriticalSection(&cs_); + DWORD w = 0; + if (hConsole_ != INVALID_HANDLE_VALUE) WriteFile(hConsole_, p, n, &w, nullptr); + if (hFile_ != INVALID_HANDLE_VALUE) WriteFile(hFile_, p, n, &w, nullptr); + LeaveCriticalSection(&cs_); + } +}; + +// Kept as a raw pointer for the process lifetime - never deleted, so no destruction race with +// hook threads still logging during shutdown. +static TeeBuf* g_tee = nullptr; + +// UTC + 1 hour = BST. Hard-coded rather than reading the OS timezone so the label is stable +// across machines. In UK winter (GMT) this would be an hour ahead - accepted trade-off, port +// work is happening in summer. +static void UtcNowAsBst(SYSTEMTIME& out) { + SYSTEMTIME utc; + GetSystemTime(&utc); + FILETIME ft; + SystemTimeToFileTime(&utc, &ft); + ULARGE_INTEGER u; + u.LowPart = ft.dwLowDateTime; + u.HighPart = ft.dwHighDateTime; + u.QuadPart += 3600ULL * 10000000ULL; // +1h in 100-ns units + ft.dwLowDateTime = u.LowPart; + ft.dwHighDateTime = u.HighPart; + FileTimeToSystemTime(&ft, &out); +} + +// Call once from InitThread. selfModule is the DLL's own HMODULE (from DllMain) - used to +// resolve \Logs. All status/failure messages use printf so they're visible in the +// console even if the tee itself never comes up. +static void Init(HMODULE selfModule) { + // Resolve \Logs. If selfModule is null (unexpected), fall back to the process + // exe's folder rather than crashing. + char dllPath[MAX_PATH] = {}; + if (GetModuleFileNameA(selfModule, dllPath, MAX_PATH) == 0) { + printf("[Campus/Log] GetModuleFileNameA failed err=%lu - console only\n", GetLastError()); + return; + } + char* slash = strrchr(dllPath, '\\'); + if (slash) *slash = 0; + std::string dir = std::string(dllPath) + "\\Logs"; + // CreateDirectoryA on an existing dir returns FALSE with ERROR_ALREADY_EXISTS - fine. + CreateDirectoryA(dir.c_str(), nullptr); + + SYSTEMTIME bst; + UtcNowAsBst(bst); + char id[32]; + _snprintf_s(id, sizeof(id), _TRUNCATE, "%04d%02d%02d_%02d%02d%02d", + bst.wYear, bst.wMonth, bst.wDay, + bst.wHour, bst.wMinute, bst.wSecond); + std::string path = dir + "\\logsession" + id + ".txt"; + + // Print the target path FIRST via printf so even if the tee itself fails, the user can see + // where we tried to write. + printf("[Campus/Log] session log -> %s\n", path.c_str()); + + TeeBuf* tee = new TeeBuf(); + if (!tee->Open(path)) { + printf("[Campus/Log] failed to open '%s' err=%lu - console only\n", + path.c_str(), GetLastError()); + delete tee; + return; + } + + // Write the session header directly to both destinations via the TeeBuf, WITHOUT swapping + // std::cout's rdbuf first. Reason: writing via std::cout hits the game's shared C++ + // streambuf machinery, which is what crashed the earlier version. sputn() below only touches + // our own HANDLEs. + char header[512]; + int hn = _snprintf_s(header, sizeof(header), _TRUNCATE, + "=== CampusPatch session log ===\n" + "Started (BST): %04d-%02d-%02d %02d:%02d:%02d BST\n" + "Log path: %s\n" + "===============================\n", + bst.wYear, bst.wMonth, bst.wDay, + bst.wHour, bst.wMinute, bst.wSecond, + path.c_str()); + if (hn > 0) tee->sputn(header, hn); + + // Publish the tee AFTER a known-good write proved it works. Any std::cout << ... call after + // this point routes through our overflow/xsputn -> WriteFile to both handles. + g_tee = tee; + std::cout.rdbuf(g_tee); +} + +} // namespace CampusLogging diff --git a/main.cpp b/main.cpp new file mode 100644 index 0000000..41f7fb5 --- /dev/null +++ b/main.cpp @@ -0,0 +1,62 @@ +#include "RR/Patching/Patches.h" +#include "Utils/logging.h" + +// CampusPatch2025 — adapted from the public "Rec Room 2025 Patch" reference for the July 19 2025 +// build, retargeted at the private Campus server (gameauth.ddns.net) instead of the reference's +// ns.cgb.net. Native x64 DLL (not BepInEx): BepInEx cannot bootstrap on builds behind Referee +// because Referee's guard rejects il2cpp_domain_get calls originating from BepInEx's DLL, so a +// bare native DLL that neutralises Referee FIRST is the working approach on this build. +// +// Do NOT do heavy work inside DllMain (loader-lock). We only allocate a console and spawn a worker +// thread that runs the actual init once the module is fully loaded. + +// Captured in DllMain and read by InitThread. HMODULE is used to resolve \Logs for +// the tee log file (see logging.h). +static HMODULE g_selfModule = nullptr; + +static DWORD WINAPI InitThread(LPVOID) +{ + // Wait a bit for the game to load its native modules. The launcher already polls for + // GameAssembly + Referee before injecting, but this is defense-in-depth: if the DLL gets + // injected via any other mechanism at a different point in startup, we still wait rather + // than dereference NULL. + for (int i = 0; i < 200; i++) { // up to ~20s + if (GetModuleHandleA("GameAssembly.dll") && GetModuleHandleA("Referee.dll")) break; + Sleep(100); + } + if (!InitGlobals()) { + printf("[Campus] init failed - aborting (no hooks installed)\n"); + return 1; + } + // Install the console -> file tee BEFORE Resolve()/Patch() so every line the rest of + // startup emits (il2cpp resolutions, hook install results, URI rewrites) is captured to + // disk. The header written by Init() ends up as the first bytes of the file. + CampusLogging::Init(g_selfModule); + RR::Patches::Resolve(); + RR::Patches::Patch(); + return 0; +} + +static void CreateConsole() +{ + AllocConsole(); + FILE* f; + freopen_s(&f, "CONOUT$", "w", stdout); + SetConsoleTitleA("Campus"); + printf("[CampusPatch] loaded - target: gameauth.ddns.net\n"); +} + +BOOL APIENTRY DllMain(HMODULE hModule, DWORD ul_reason_for_call, LPVOID lpReserved) +{ + if (ul_reason_for_call == DLL_PROCESS_ATTACH) { + DisableThreadLibraryCalls(hModule); + g_selfModule = hModule; // stash for InitThread -> CampusLogging::Init + CreateConsole(); + // Run Resolve()/Patch() OUTSIDE DllMain to avoid loader-lock deadlocks - MinHook takes + // locks and touches other modules, which is unsafe from DLL_PROCESS_ATTACH. + HANDLE h = CreateThread(nullptr, 0, InitThread, nullptr, 0, nullptr); + if (h) CloseHandle(h); + } + return TRUE; +} + diff --git a/pstdint.h b/pstdint.h new file mode 100644 index 0000000..84d82a0 --- /dev/null +++ b/pstdint.h @@ -0,0 +1,39 @@ +/* + * MinHook - The Minimalistic API Hooking Library for x64/x86 + * Copyright (C) 2009-2017 Tsuda Kageyu. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY THE AUTHOR "AS IS" AND ANY EXPRESS OR + * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES + * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. + * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT + * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY + * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF + * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +#pragma once + +#include + +// Integer types for HDE. +typedef INT8 int8_t; +typedef INT16 int16_t; +typedef INT32 int32_t; +typedef INT64 int64_t; +typedef UINT8 uint8_t; +typedef UINT16 uint16_t; +typedef UINT32 uint32_t; +typedef UINT64 uint64_t; diff --git a/scan.h b/scan.h new file mode 100644 index 0000000..9a542f7 --- /dev/null +++ b/scan.h @@ -0,0 +1,75 @@ +#pragma once +#include +#include +#include + +static std::vector PatternToIntVector(const char* Pattern) +{ + std::vector PatternVector = std::vector{}; + + char* Start = const_cast(Pattern); + + char* End = const_cast(Pattern) + strlen(Pattern); + + for (char* Current = Start; Current < End; ++Current) + { + if (*Current == '?') + { + ++Current; + + PatternVector.push_back(-69); + } + else { + PatternVector.push_back(strtoul(Current, &Current, 16)); + } + } + + return PatternVector; +} + +static inline void* FindPointer(std::vector Pattern, uint8_t* Address, int Addition = 0) { + + int i = 0; + while (Pattern[i] != -69) i++; + + int Offset = *reinterpret_cast(Address + i); + + return reinterpret_cast(Address + i + 0x4 + Offset + Addition); +} + +template +static T PatternScan(const char* Pattern, uint64_t Start, size_t Size, bool bFindPointer = false, int Addition = 0) +{ + std::vector PatternVector = PatternToIntVector(Pattern); + + uint8_t* Search = reinterpret_cast(Start); + + const size_t SizeOfPattern = PatternVector.size(); + const int* PatternData = PatternVector.data(); + + for (int i = 0; i < Size - SizeOfPattern; ++i) + { + bool FoundSignature = true; + + for (int j = 0; j < SizeOfPattern; ++j) + { + if (Search[i + j] != PatternData[j] && PatternData[j] != -69) + { + FoundSignature = false; + break; + } + } + + if (FoundSignature) { + + if (bFindPointer) { + return reinterpret_cast(FindPointer(PatternVector, &Search[i], Addition)); + } + + return reinterpret_cast(&Search[i]); + + } + } + + return reinterpret_cast(nullptr); +} \ No newline at end of file diff --git a/table32.h b/table32.h new file mode 100644 index 0000000..7b3e12e --- /dev/null +++ b/table32.h @@ -0,0 +1,73 @@ +/* + * Hacker Disassembler Engine 32 C + * Copyright (c) 2008-2009, Vyacheslav Patkov. + * All rights reserved. + * + */ + +#define C_NONE 0x00 +#define C_MODRM 0x01 +#define C_IMM8 0x02 +#define C_IMM16 0x04 +#define C_IMM_P66 0x10 +#define C_REL8 0x20 +#define C_REL32 0x40 +#define C_GROUP 0x80 +#define C_ERROR 0xff + +#define PRE_ANY 0x00 +#define PRE_NONE 0x01 +#define PRE_F2 0x02 +#define PRE_F3 0x04 +#define PRE_66 0x08 +#define PRE_67 0x10 +#define PRE_LOCK 0x20 +#define PRE_SEG 0x40 +#define PRE_ALL 0xff + +#define DELTA_OPCODES 0x4a +#define DELTA_FPU_REG 0xf1 +#define DELTA_FPU_MODRM 0xf8 +#define DELTA_PREFIXES 0x130 +#define DELTA_OP_LOCK_OK 0x1a1 +#define DELTA_OP2_LOCK_OK 0x1b9 +#define DELTA_OP_ONLY_MEM 0x1cb +#define DELTA_OP2_ONLY_MEM 0x1da + +unsigned char hde32_table[] = { + 0xa3,0xa8,0xa3,0xa8,0xa3,0xa8,0xa3,0xa8,0xa3,0xa8,0xa3,0xa8,0xa3,0xa8,0xa3, + 0xa8,0xaa,0xaa,0xaa,0xaa,0xaa,0xaa,0xaa,0xaa,0xac,0xaa,0xb2,0xaa,0x9f,0x9f, + 0x9f,0x9f,0xb5,0xa3,0xa3,0xa4,0xaa,0xaa,0xba,0xaa,0x96,0xaa,0xa8,0xaa,0xc3, + 0xc3,0x96,0x96,0xb7,0xae,0xd6,0xbd,0xa3,0xc5,0xa3,0xa3,0x9f,0xc3,0x9c,0xaa, + 0xaa,0xac,0xaa,0xbf,0x03,0x7f,0x11,0x7f,0x01,0x7f,0x01,0x3f,0x01,0x01,0x90, + 0x82,0x7d,0x97,0x59,0x59,0x59,0x59,0x59,0x7f,0x59,0x59,0x60,0x7d,0x7f,0x7f, + 0x59,0x59,0x59,0x59,0x59,0x59,0x59,0x59,0x59,0x59,0x59,0x59,0x9a,0x88,0x7d, + 0x59,0x50,0x50,0x50,0x50,0x59,0x59,0x59,0x59,0x61,0x94,0x61,0x9e,0x59,0x59, + 0x85,0x59,0x92,0xa3,0x60,0x60,0x59,0x59,0x59,0x59,0x59,0x59,0x59,0x59,0x59, + 0x59,0x59,0x9f,0x01,0x03,0x01,0x04,0x03,0xd5,0x03,0xcc,0x01,0xbc,0x03,0xf0, + 0x10,0x10,0x10,0x10,0x50,0x50,0x50,0x50,0x14,0x20,0x20,0x20,0x20,0x01,0x01, + 0x01,0x01,0xc4,0x02,0x10,0x00,0x00,0x00,0x00,0x01,0x01,0xc0,0xc2,0x10,0x11, + 0x02,0x03,0x11,0x03,0x03,0x04,0x00,0x00,0x14,0x00,0x02,0x00,0x00,0xc6,0xc8, + 0x02,0x02,0x02,0x02,0x00,0x00,0xff,0xff,0xff,0xff,0x00,0x00,0x00,0xff,0xca, + 0x01,0x01,0x01,0x00,0x06,0x00,0x04,0x00,0xc0,0xc2,0x01,0x01,0x03,0x01,0xff, + 0xff,0x01,0x00,0x03,0xc4,0xc4,0xc6,0x03,0x01,0x01,0x01,0xff,0x03,0x03,0x03, + 0xc8,0x40,0x00,0x0a,0x00,0x04,0x00,0x00,0x00,0x00,0x7f,0x00,0x33,0x01,0x00, + 0x00,0x00,0x00,0x00,0x00,0xff,0xbf,0xff,0xff,0x00,0x00,0x00,0x00,0x07,0x00, + 0x00,0xff,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, + 0x00,0xff,0xff,0x00,0x00,0x00,0xbf,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, + 0x7f,0x00,0x00,0xff,0x4a,0x4a,0x4a,0x4a,0x4b,0x52,0x4a,0x4a,0x4a,0x4a,0x4f, + 0x4c,0x4a,0x4a,0x4a,0x4a,0x4a,0x4a,0x4a,0x4a,0x55,0x45,0x40,0x4a,0x4a,0x4a, + 0x45,0x59,0x4d,0x46,0x4a,0x5d,0x4a,0x4a,0x4a,0x4a,0x4a,0x4a,0x4a,0x4a,0x4a, + 0x4a,0x4a,0x4a,0x4a,0x4a,0x61,0x63,0x67,0x4e,0x4a,0x4a,0x6b,0x6d,0x4a,0x4a, + 0x45,0x6d,0x4a,0x4a,0x44,0x45,0x4a,0x4a,0x00,0x00,0x00,0x02,0x0d,0x06,0x06, + 0x06,0x06,0x0e,0x00,0x00,0x00,0x00,0x06,0x06,0x06,0x00,0x06,0x06,0x02,0x06, + 0x00,0x0a,0x0a,0x07,0x07,0x06,0x02,0x05,0x05,0x02,0x02,0x00,0x00,0x04,0x04, + 0x04,0x04,0x00,0x00,0x00,0x0e,0x05,0x06,0x06,0x06,0x01,0x06,0x00,0x00,0x08, + 0x00,0x10,0x00,0x18,0x00,0x20,0x00,0x28,0x00,0x30,0x00,0x80,0x01,0x82,0x01, + 0x86,0x00,0xf6,0xcf,0xfe,0x3f,0xab,0x00,0xb0,0x00,0xb1,0x00,0xb3,0x00,0xba, + 0xf8,0xbb,0x00,0xc0,0x00,0xc1,0x00,0xc7,0xbf,0x62,0xff,0x00,0x8d,0xff,0x00, + 0xc4,0xff,0x00,0xc5,0xff,0x00,0xff,0xff,0xeb,0x01,0xff,0x0e,0x12,0x08,0x00, + 0x13,0x09,0x00,0x16,0x08,0x00,0x17,0x09,0x00,0x2b,0x09,0x00,0xae,0xff,0x07, + 0xb2,0xff,0x00,0xb4,0xff,0x00,0xb5,0xff,0x00,0xc3,0x01,0x00,0xc7,0xff,0xbf, + 0xe7,0x08,0x00,0xf0,0x02,0x00 +}; diff --git a/table64.h b/table64.h new file mode 100644 index 0000000..01d4541 --- /dev/null +++ b/table64.h @@ -0,0 +1,74 @@ +/* + * Hacker Disassembler Engine 64 C + * Copyright (c) 2008-2009, Vyacheslav Patkov. + * All rights reserved. + * + */ + +#define C_NONE 0x00 +#define C_MODRM 0x01 +#define C_IMM8 0x02 +#define C_IMM16 0x04 +#define C_IMM_P66 0x10 +#define C_REL8 0x20 +#define C_REL32 0x40 +#define C_GROUP 0x80 +#define C_ERROR 0xff + +#define PRE_ANY 0x00 +#define PRE_NONE 0x01 +#define PRE_F2 0x02 +#define PRE_F3 0x04 +#define PRE_66 0x08 +#define PRE_67 0x10 +#define PRE_LOCK 0x20 +#define PRE_SEG 0x40 +#define PRE_ALL 0xff + +#define DELTA_OPCODES 0x4a +#define DELTA_FPU_REG 0xfd +#define DELTA_FPU_MODRM 0x104 +#define DELTA_PREFIXES 0x13c +#define DELTA_OP_LOCK_OK 0x1ae +#define DELTA_OP2_LOCK_OK 0x1c6 +#define DELTA_OP_ONLY_MEM 0x1d8 +#define DELTA_OP2_ONLY_MEM 0x1e7 + +unsigned char hde64_table[] = { + 0xa5,0xaa,0xa5,0xb8,0xa5,0xaa,0xa5,0xaa,0xa5,0xb8,0xa5,0xb8,0xa5,0xb8,0xa5, + 0xb8,0xc0,0xc0,0xc0,0xc0,0xc0,0xc0,0xc0,0xc0,0xac,0xc0,0xcc,0xc0,0xa1,0xa1, + 0xa1,0xa1,0xb1,0xa5,0xa5,0xa6,0xc0,0xc0,0xd7,0xda,0xe0,0xc0,0xe4,0xc0,0xea, + 0xea,0xe0,0xe0,0x98,0xc8,0xee,0xf1,0xa5,0xd3,0xa5,0xa5,0xa1,0xea,0x9e,0xc0, + 0xc0,0xc2,0xc0,0xe6,0x03,0x7f,0x11,0x7f,0x01,0x7f,0x01,0x3f,0x01,0x01,0xab, + 0x8b,0x90,0x64,0x5b,0x5b,0x5b,0x5b,0x5b,0x92,0x5b,0x5b,0x76,0x90,0x92,0x92, + 0x5b,0x5b,0x5b,0x5b,0x5b,0x5b,0x5b,0x5b,0x5b,0x5b,0x5b,0x5b,0x6a,0x73,0x90, + 0x5b,0x52,0x52,0x52,0x52,0x5b,0x5b,0x5b,0x5b,0x77,0x7c,0x77,0x85,0x5b,0x5b, + 0x70,0x5b,0x7a,0xaf,0x76,0x76,0x5b,0x5b,0x5b,0x5b,0x5b,0x5b,0x5b,0x5b,0x5b, + 0x5b,0x5b,0x86,0x01,0x03,0x01,0x04,0x03,0xd5,0x03,0xd5,0x03,0xcc,0x01,0xbc, + 0x03,0xf0,0x03,0x03,0x04,0x00,0x50,0x50,0x50,0x50,0xff,0x20,0x20,0x20,0x20, + 0x01,0x01,0x01,0x01,0xc4,0x02,0x10,0xff,0xff,0xff,0x01,0x00,0x03,0x11,0xff, + 0x03,0xc4,0xc6,0xc8,0x02,0x10,0x00,0xff,0xcc,0x01,0x01,0x01,0x00,0x00,0x00, + 0x00,0x01,0x01,0x03,0x01,0xff,0xff,0xc0,0xc2,0x10,0x11,0x02,0x03,0x01,0x01, + 0x01,0xff,0xff,0xff,0x00,0x00,0x00,0xff,0x00,0x00,0xff,0xff,0xff,0xff,0x10, + 0x10,0x10,0x10,0x02,0x10,0x00,0x00,0xc6,0xc8,0x02,0x02,0x02,0x02,0x06,0x00, + 0x04,0x00,0x02,0xff,0x00,0xc0,0xc2,0x01,0x01,0x03,0x03,0x03,0xca,0x40,0x00, + 0x0a,0x00,0x04,0x00,0x00,0x00,0x00,0x7f,0x00,0x33,0x01,0x00,0x00,0x00,0x00, + 0x00,0x00,0xff,0xbf,0xff,0xff,0x00,0x00,0x00,0x00,0x07,0x00,0x00,0xff,0x00, + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0xff,0xff, + 0x00,0x00,0x00,0xbf,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x7f,0x00,0x00, + 0xff,0x40,0x40,0x40,0x40,0x41,0x49,0x40,0x40,0x40,0x40,0x4c,0x42,0x40,0x40, + 0x40,0x40,0x40,0x40,0x40,0x40,0x4f,0x44,0x53,0x40,0x40,0x40,0x44,0x57,0x43, + 0x5c,0x40,0x60,0x40,0x40,0x40,0x40,0x40,0x40,0x40,0x40,0x40,0x40,0x40,0x40, + 0x40,0x40,0x64,0x66,0x6e,0x6b,0x40,0x40,0x6a,0x46,0x40,0x40,0x44,0x46,0x40, + 0x40,0x5b,0x44,0x40,0x40,0x00,0x00,0x00,0x00,0x06,0x06,0x06,0x06,0x01,0x06, + 0x06,0x02,0x06,0x06,0x00,0x06,0x00,0x0a,0x0a,0x00,0x00,0x00,0x02,0x07,0x07, + 0x06,0x02,0x0d,0x06,0x06,0x06,0x0e,0x05,0x05,0x02,0x02,0x00,0x00,0x04,0x04, + 0x04,0x04,0x05,0x06,0x06,0x06,0x00,0x00,0x00,0x0e,0x00,0x00,0x08,0x00,0x10, + 0x00,0x18,0x00,0x20,0x00,0x28,0x00,0x30,0x00,0x80,0x01,0x82,0x01,0x86,0x00, + 0xf6,0xcf,0xfe,0x3f,0xab,0x00,0xb0,0x00,0xb1,0x00,0xb3,0x00,0xba,0xf8,0xbb, + 0x00,0xc0,0x00,0xc1,0x00,0xc7,0xbf,0x62,0xff,0x00,0x8d,0xff,0x00,0xc4,0xff, + 0x00,0xc5,0xff,0x00,0xff,0xff,0xeb,0x01,0xff,0x0e,0x12,0x08,0x00,0x13,0x09, + 0x00,0x16,0x08,0x00,0x17,0x09,0x00,0x2b,0x09,0x00,0xae,0xff,0x07,0xb2,0xff, + 0x00,0xb4,0xff,0x00,0xb5,0xff,0x00,0xc3,0x01,0x00,0xc7,0xff,0xbf,0xe7,0x08, + 0x00,0xf0,0x02,0x00 +}; diff --git a/trampoline.c b/trampoline.c new file mode 100644 index 0000000..ac37f0f --- /dev/null +++ b/trampoline.c @@ -0,0 +1,316 @@ +/* + * MinHook - The Minimalistic API Hooking Library for x64/x86 + * Copyright (C) 2009-2017 Tsuda Kageyu. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED + * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A + * PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER + * OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING + * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +#include + +#ifndef ARRAYSIZE + #define ARRAYSIZE(A) (sizeof(A)/sizeof((A)[0])) +#endif + +#if defined(_M_X64) || defined(__x86_64__) + #include "./hde/hde64.h" + typedef hde64s HDE; + #define HDE_DISASM(code, hs) hde64_disasm(code, hs) +#else + #include "./hde/hde32.h" + typedef hde32s HDE; + #define HDE_DISASM(code, hs) hde32_disasm(code, hs) +#endif + +#include "trampoline.h" +#include "buffer.h" + +// Maximum size of a trampoline function. +#if defined(_M_X64) || defined(__x86_64__) + #define TRAMPOLINE_MAX_SIZE (MEMORY_SLOT_SIZE - sizeof(JMP_ABS)) +#else + #define TRAMPOLINE_MAX_SIZE MEMORY_SLOT_SIZE +#endif + +//------------------------------------------------------------------------- +static BOOL IsCodePadding(LPBYTE pInst, UINT size) +{ + UINT i; + + if (pInst[0] != 0x00 && pInst[0] != 0x90 && pInst[0] != 0xCC) + return FALSE; + + for (i = 1; i < size; ++i) + { + if (pInst[i] != pInst[0]) + return FALSE; + } + return TRUE; +} + +//------------------------------------------------------------------------- +BOOL CreateTrampolineFunction(PTRAMPOLINE ct) +{ +#if defined(_M_X64) || defined(__x86_64__) + CALL_ABS call = { + 0xFF, 0x15, 0x00000002, // FF15 00000002: CALL [RIP+8] + 0xEB, 0x08, // EB 08: JMP +10 + 0x0000000000000000ULL // Absolute destination address + }; + JMP_ABS jmp = { + 0xFF, 0x25, 0x00000000, // FF25 00000000: JMP [RIP+6] + 0x0000000000000000ULL // Absolute destination address + }; + JCC_ABS jcc = { + 0x70, 0x0E, // 7* 0E: J** +16 + 0xFF, 0x25, 0x00000000, // FF25 00000000: JMP [RIP+6] + 0x0000000000000000ULL // Absolute destination address + }; +#else + CALL_REL call = { + 0xE8, // E8 xxxxxxxx: CALL +5+xxxxxxxx + 0x00000000 // Relative destination address + }; + JMP_REL jmp = { + 0xE9, // E9 xxxxxxxx: JMP +5+xxxxxxxx + 0x00000000 // Relative destination address + }; + JCC_REL jcc = { + 0x0F, 0x80, // 0F8* xxxxxxxx: J** +6+xxxxxxxx + 0x00000000 // Relative destination address + }; +#endif + + UINT8 oldPos = 0; + UINT8 newPos = 0; + ULONG_PTR jmpDest = 0; // Destination address of an internal jump. + BOOL finished = FALSE; // Is the function completed? +#if defined(_M_X64) || defined(__x86_64__) + UINT8 instBuf[16]; +#endif + + ct->patchAbove = FALSE; + ct->nIP = 0; + + do + { + HDE hs; + UINT copySize; + LPVOID pCopySrc; + ULONG_PTR pOldInst = (ULONG_PTR)ct->pTarget + oldPos; + ULONG_PTR pNewInst = (ULONG_PTR)ct->pTrampoline + newPos; + + copySize = HDE_DISASM((LPVOID)pOldInst, &hs); + if (hs.flags & F_ERROR) + return FALSE; + + pCopySrc = (LPVOID)pOldInst; + if (oldPos >= sizeof(JMP_REL)) + { + // The trampoline function is long enough. + // Complete the function with the jump to the target function. +#if defined(_M_X64) || defined(__x86_64__) + jmp.address = pOldInst; +#else + jmp.operand = (UINT32)(pOldInst - (pNewInst + sizeof(jmp))); +#endif + pCopySrc = &jmp; + copySize = sizeof(jmp); + + finished = TRUE; + } +#if defined(_M_X64) || defined(__x86_64__) + else if ((hs.modrm & 0xC7) == 0x05) + { + // Instructions using RIP relative addressing. (ModR/M = 00???101B) + + // Modify the RIP relative address. + PUINT32 pRelAddr; + + // Avoid using memcpy to reduce the footprint. +#ifndef _MSC_VER + memcpy(instBuf, (LPBYTE)pOldInst, copySize); +#else + __movsb(instBuf, (LPBYTE)pOldInst, copySize); +#endif + pCopySrc = instBuf; + + // Relative address is stored at (instruction length - immediate value length - 4). + pRelAddr = (PUINT32)(instBuf + hs.len - ((hs.flags & 0x3C) >> 2) - 4); + *pRelAddr + = (UINT32)((pOldInst + hs.len + (INT32)hs.disp.disp32) - (pNewInst + hs.len)); + + // Complete the function if JMP (FF /4). + if (hs.opcode == 0xFF && hs.modrm_reg == 4) + finished = TRUE; + } +#endif + else if (hs.opcode == 0xE8) + { + // Direct relative CALL + ULONG_PTR dest = pOldInst + hs.len + (INT32)hs.imm.imm32; +#if defined(_M_X64) || defined(__x86_64__) + call.address = dest; +#else + call.operand = (UINT32)(dest - (pNewInst + sizeof(call))); +#endif + pCopySrc = &call; + copySize = sizeof(call); + } + else if ((hs.opcode & 0xFD) == 0xE9) + { + // Direct relative JMP (EB or E9) + ULONG_PTR dest = pOldInst + hs.len; + + if (hs.opcode == 0xEB) // isShort jmp + dest += (INT8)hs.imm.imm8; + else + dest += (INT32)hs.imm.imm32; + + // Simply copy an internal jump. + if ((ULONG_PTR)ct->pTarget <= dest + && dest < ((ULONG_PTR)ct->pTarget + sizeof(JMP_REL))) + { + if (jmpDest < dest) + jmpDest = dest; + } + else + { +#if defined(_M_X64) || defined(__x86_64__) + jmp.address = dest; +#else + jmp.operand = (UINT32)(dest - (pNewInst + sizeof(jmp))); +#endif + pCopySrc = &jmp; + copySize = sizeof(jmp); + + // Exit the function If it is not in the branch + finished = (pOldInst >= jmpDest); + } + } + else if ((hs.opcode & 0xF0) == 0x70 + || (hs.opcode & 0xFC) == 0xE0 + || (hs.opcode2 & 0xF0) == 0x80) + { + // Direct relative Jcc + ULONG_PTR dest = pOldInst + hs.len; + + if ((hs.opcode & 0xF0) == 0x70 // Jcc + || (hs.opcode & 0xFC) == 0xE0) // LOOPNZ/LOOPZ/LOOP/JECXZ + dest += (INT8)hs.imm.imm8; + else + dest += (INT32)hs.imm.imm32; + + // Simply copy an internal jump. + if ((ULONG_PTR)ct->pTarget <= dest + && dest < ((ULONG_PTR)ct->pTarget + sizeof(JMP_REL))) + { + if (jmpDest < dest) + jmpDest = dest; + } + else if ((hs.opcode & 0xFC) == 0xE0) + { + // LOOPNZ/LOOPZ/LOOP/JCXZ/JECXZ to the outside are not supported. + return FALSE; + } + else + { + UINT8 cond = ((hs.opcode != 0x0F ? hs.opcode : hs.opcode2) & 0x0F); +#if defined(_M_X64) || defined(__x86_64__) + // Invert the condition in x64 mode to simplify the conditional jump logic. + jcc.opcode = 0x71 ^ cond; + jcc.address = dest; +#else + jcc.opcode1 = 0x80 | cond; + jcc.operand = (UINT32)(dest - (pNewInst + sizeof(jcc))); +#endif + pCopySrc = &jcc; + copySize = sizeof(jcc); + } + } + else if ((hs.opcode & 0xFE) == 0xC2) + { + // RET (C2 or C3) + + // Complete the function if not in a branch. + finished = (pOldInst >= jmpDest); + } + + // Can't alter the instruction length in a branch. + if (pOldInst < jmpDest && copySize != hs.len) + return FALSE; + + // Trampoline function is too large. + if ((newPos + copySize) > TRAMPOLINE_MAX_SIZE) + return FALSE; + + // Trampoline function has too many instructions. + if (ct->nIP >= ARRAYSIZE(ct->oldIPs)) + return FALSE; + + ct->oldIPs[ct->nIP] = oldPos; + ct->newIPs[ct->nIP] = newPos; + ct->nIP++; + + // Avoid using memcpy to reduce the footprint. +#ifndef _MSC_VER + memcpy((LPBYTE)ct->pTrampoline + newPos, pCopySrc, copySize); +#else + __movsb((LPBYTE)ct->pTrampoline + newPos, pCopySrc, copySize); +#endif + newPos += copySize; + oldPos += hs.len; + } + while (!finished); + + // Is there enough place for a long jump? + if (oldPos < sizeof(JMP_REL) + && !IsCodePadding((LPBYTE)ct->pTarget + oldPos, sizeof(JMP_REL) - oldPos)) + { + // Is there enough place for a short jump? + if (oldPos < sizeof(JMP_REL_SHORT) + && !IsCodePadding((LPBYTE)ct->pTarget + oldPos, sizeof(JMP_REL_SHORT) - oldPos)) + { + return FALSE; + } + + // Can we place the long jump above the function? + if (!IsExecutableAddress((LPBYTE)ct->pTarget - sizeof(JMP_REL))) + return FALSE; + + if (!IsCodePadding((LPBYTE)ct->pTarget - sizeof(JMP_REL), sizeof(JMP_REL))) + return FALSE; + + ct->patchAbove = TRUE; + } + +#if defined(_M_X64) || defined(__x86_64__) + // Create a relay function. + jmp.address = (ULONG_PTR)ct->pDetour; + + ct->pRelay = (LPBYTE)ct->pTrampoline + newPos; + memcpy(ct->pRelay, &jmp, sizeof(jmp)); +#endif + + return TRUE; +} diff --git a/trampoline.h b/trampoline.h new file mode 100644 index 0000000..bdffdac --- /dev/null +++ b/trampoline.h @@ -0,0 +1,105 @@ +/* + * MinHook - The Minimalistic API Hooking Library for x64/x86 + * Copyright (C) 2009-2017 Tsuda Kageyu. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED + * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A + * PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER + * OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING + * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +#pragma once + +#pragma pack(push, 1) + +// Structs for writing x86/x64 instructions. + +// 8-bit relative jump. +typedef struct _JMP_REL_SHORT +{ + UINT8 opcode; // EB xx: JMP +2+xx + UINT8 operand; +} JMP_REL_SHORT, *PJMP_REL_SHORT; + +// 32-bit direct relative jump/call. +typedef struct _JMP_REL +{ + UINT8 opcode; // E9/E8 xxxxxxxx: JMP/CALL +5+xxxxxxxx + UINT32 operand; // Relative destination address +} JMP_REL, *PJMP_REL, CALL_REL; + +// 64-bit indirect absolute jump. +typedef struct _JMP_ABS +{ + UINT8 opcode0; // FF25 00000000: JMP [+6] + UINT8 opcode1; + UINT32 dummy; + UINT64 address; // Absolute destination address +} JMP_ABS, *PJMP_ABS; + +// 64-bit indirect absolute call. +typedef struct _CALL_ABS +{ + UINT8 opcode0; // FF15 00000002: CALL [+6] + UINT8 opcode1; + UINT32 dummy0; + UINT8 dummy1; // EB 08: JMP +10 + UINT8 dummy2; + UINT64 address; // Absolute destination address +} CALL_ABS; + +// 32-bit direct relative conditional jumps. +typedef struct _JCC_REL +{ + UINT8 opcode0; // 0F8* xxxxxxxx: J** +6+xxxxxxxx + UINT8 opcode1; + UINT32 operand; // Relative destination address +} JCC_REL; + +// 64bit indirect absolute conditional jumps that x64 lacks. +typedef struct _JCC_ABS +{ + UINT8 opcode; // 7* 0E: J** +16 + UINT8 dummy0; + UINT8 dummy1; // FF25 00000000: JMP [+6] + UINT8 dummy2; + UINT32 dummy3; + UINT64 address; // Absolute destination address +} JCC_ABS; + +#pragma pack(pop) + +typedef struct _TRAMPOLINE +{ + LPVOID pTarget; // [In] Address of the target function. + LPVOID pDetour; // [In] Address of the detour function. + LPVOID pTrampoline; // [In] Buffer address for the trampoline and relay function. + +#if defined(_M_X64) || defined(__x86_64__) + LPVOID pRelay; // [Out] Address of the relay function. +#endif + BOOL patchAbove; // [Out] Should use the hot patch area? + UINT nIP; // [Out] Number of the instruction boundaries. + UINT8 oldIPs[8]; // [Out] Instruction boundaries of the target function. + UINT8 newIPs[8]; // [Out] Instruction boundaries of the trampoline function. +} TRAMPOLINE, *PTRAMPOLINE; + +BOOL CreateTrampolineFunction(PTRAMPOLINE ct);