Hooking WinHttpReadData to intercept Data

106 Views Asked by At

I coded a simple script that sends a request and waits for the response using WinHttp. Now I'm trying to learn hooking and for testing purposes, I want to hook my own script using C++ detour.

I tried to hook the script by reading the data and modifying it within the original hook. However, instead of modifying the original response data, it creates a copy of the data and modifies that instead. As a result, I end up with two responses - the original one that the program uses to react on and a copied modified one that I want to use but which ends up not being used.

I am looking for guidance on how to hook it correctly in order to modify the original response strings code from 2000 to 3000. Any suggestions or solutions would be greatly appreciated.

typedef BOOL(WINAPI* PWinHttpReadData)(HINTERNET hRequest, LPVOID lpBuffer, DWORD dwNumberOfBytesToRead, LPDWORD lpdwNumberOfBytesRead);

PWinHttpReadData OriginalWinHttpReadData = NULL;

BOOL WINAPI MyWinHttpReadData(HINTERNET hRequest, LPVOID lpBuffer, DWORD dwNumberOfBytesToRead, LPDWORD lpdwNumberOfBytesRead) {

    // Call the original WinHttpReadData function
    BOOL result = OriginalWinHttpReadData(hRequest, lpBuffer, dwNumberOfBytesToRead, lpdwNumberOfBytesRead);

    if (result && lpBuffer && dwNumberOfBytesToRead > 0) {


        //Replacing a string in the response data
        std::string responseData(static_cast<char*>(lpBuffer), dwNumberOfBytesToRead); //Responsedata then looks like this: {"test", "code": 2000}
        std::string searchString = "2000";
        std::string replaceString = "3000";
        size_t pos = responseData.find(searchString);
        while (pos != std::string::npos) {
            responseData.replace(pos, searchString.length(), replaceString);
            pos = responseData.find(searchString, pos + replaceString.length());
        }

        // Copy the modified data back to lpBuffer
        if (responseData.length() <= dwNumberOfBytesToRead) {
            memcpy(lpBuffer, responseData.c_str(), responseData.length());
            dwNumberOfBytesToRead = static_cast<DWORD>(responseData.length());
        }
    }

    return result;
}
0

There are 0 best solutions below