Skip to content
TheChatArchiveThe Chat Archive
gpt-4-1106-preview· openaiHugging Face Suzhen/CodeChat

#include <windows.h> // buffer for saving original bytes char originalBytes[5]; FARPROC…

  1. User

    #include <windows.h>

    // buffer for saving original bytes char originalBytes[5];

    FARPROC hookedAddress;

    // we will jump to after the hook has been installed int __stdcall myFunc(LPCSTR lpCmdLine, UINT uCmdShow) {

    // unhook the function: rewrite original bytes WriteProcessMemory(GetCurrentProcess(), (LPVOID)hookedAddress, originalBytes, 5, NULL);

    // return to the original function and modify the text return WinExec("calc", uCmdShow); }

    // hooking logic void setMySuperHook() { HINSTANCE hLib; VOID *myFuncAddress; DWORD *rOffset; DWORD src; DWORD dst; CHAR patch[5]= {0};

    // get memory address of function MessageBoxA hLib = LoadLibraryA("kernel32.dll"); hookedAddress = GetProcAddress(hLib, "WinExec");

    // save the first 5 bytes into originalBytes (buffer) ReadProcessMemory(GetCurrentProcess(), (LPCVOID) hookedAddress, originalBytes, 5, NULL);

    // overwrite the first 5 bytes with a jump to myFunc myFuncAddress = &myFunc;

    // will jump from the next instruction (after our 5 byte jmp instruction) src = (DWORD)hookedAddress + 5; dst = (DWORD)myFuncAddress; rOffset = (DWORD *)(dst-src);

    // \xE9 - jump instruction memcpy(patch, "\xE9", 1); memcpy(patch + 1, &rOffset, 4);

    WriteProcessMemory(GetCurrentProcess(), (LPVOID)hookedAddress, patch, 5, NULL);

    }

    int main() {

    // call original WinExec("notepad", SW_SHOWDEFAULT);

    // install hook setMySuperHook();

    // call after install hook WinExec("notepad", SW_SHOWDEFAULT);

    } поправь данный код для x64 компиляции

  2. Assistant

    Ваш код написан для 32-битных приложений и не будет работать для 64-битной версии Windows без изменений. В x64-архитектуре используется другая схема адресации и другие регистры.

    Прежде всего, в x64 Windows основное отличие связано с тем, что расстояние для перехода (jump) может быть больше, чем позволяет представить DWORD (32 бита), поэтому вам понадобится использовать jmp инструкции, которые могут обрабатывать 64-битные смещения.

    Кроме того, FARPROC и указатели теперь будут 64-битными, так что вам нужно обновить все типы данных для соответствия 64-битной среде.

    Вот как можно обновить ваш код для 64-битной компиляции:

    #include <windows.h>
    
    // buffer for saving original bytes
    char originalBytes[14];
    
    // remember the function address we will hook
    FARPROC hookedAddress;
    
    // our hook function
    int __stdcall myFunc(LPCSTR lpCmdLine, UINT uCmdShow) {
    
      // unhook the function: rewrite original bytes
      WriteProcessMemory(GetCurrentProcess(), (LPVOID)hookedAddress, originalBytes, sizeof(originalBytes), NULL);
    
      // you may want to call the original WinExec function here using a trampoline
      // function which you need to implement using the saved bytes and a jump
      // to the remainder of the original function
    
      // modify text or do something else here
      return WinExec("calc", uCmdShow);
    }
    
    // hook installation logic
    void setMySuperHook() {
      HMEMORYMODULE hLib;
      void *myFuncAddress;
      intptr_t src, dst;
      intptr_t relativeAddr;
      char patch[14] = {0}; // 14-byte long patch for 64-bit absolute jump
    
      // get memory address of function WinExec
      hLib = LoadLibraryA("kernel32.dll");
      hookedAddress = GetProcAddress(hLib, "WinExec");
    
      // save the first 14 bytes into originalBytes (buffer)
      ReadProcessMemory(GetCurrentProcess(), (LPCVOID)hookedAddress, originalBytes, sizeof(originalBytes), NULL);
    
      // overwrite the first bytes with a jump to myFunc
      myFuncAddress = &myFunc;
    
      src = (intptr_t)hookedAddress;
      dst = (intptr_t)myFuncAddress;
      relativeAddr = dst - (src + sizeof(patch));
    
      // Patch bytes: Jump to the relative address
      memcpy(patch, "\xFF\x25\x00\x00\x00\x00", 6); // jmp [rip+0] (RIP-relative indirect jump)
      memcpy(patch+6, &relativeAddr, sizeof(relativeAddr)); // Address after the jmp + 0
    
      WriteProcessMemory(GetCurrentProcess(), (LPVOID)hookedAddress, patch, sizeof(patch), NULL);
    }
    
    int main() {
    
      // call original
      WinExec("notepad", SW_SHOWDEFAULT);
    
      // install hook
      setMySuperHook();
    
      // call after install hook
      WinExec("notepad", SW_SHOWDEFAULT);
    
      return 0;
    }
    

    Обратите внимание, что данная версия кода не включает реализацию так называемой трамплинной функции, которая необходима для возврата в исходную (оригинальную) функцию после обработки в пользовательской функции. Она потребуется, если после выполнения вашей пользовательской функции myFunc вы все же хотите вызвать оригинальную функцию WinExec.

    Также важно помнить, что хук функций Windows не рекомендуется без веской причины, так как это может привести к нестабильности и нарушению безопасности системы. Кроме того, подход с заменой первых инструкций функции на jmp может не работать из-за технологий защиты памяти, таких как DEP (Data Execution Prevention) и ASLR (Address Space Layout Randomization).

Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.