Skip to content

Instantly share code, notes, and snippets.

@axodox
Created June 6, 2017 13:26
Show Gist options
  • Save axodox/2820cf1138d55489fd23fcdc1fc1ae79 to your computer and use it in GitHub Desktop.
Save axodox/2820cf1138d55489fd23fcdc1fc1ae79 to your computer and use it in GitHub Desktop.
typedef HANDLE(WINAPI *CreateFileWCallback)(
LPCWSTR lpFileName,
DWORD dwDesiredAccess,
DWORD dwShareMode,
LPSECURITY_ATTRIBUTES lpSecurityAttributes,
DWORD dwCreationDisposition,
DWORD dwFlagsAndAttributes,
HANDLE hTemplateFile
);
CreateFileWCallback OriginalCreateFileW;
HANDLE WINAPI OnCreateFileW(
LPCWSTR lpFileName,
DWORD dwDesiredAccess,
DWORD dwShareMode,
LPSECURITY_ATTRIBUTES lpSecurityAttributes,
DWORD dwCreationDisposition,
DWORD dwFlagsAndAttributes,
HANDLE hTemplateFile)
{
return OriginalCreateFileW(
lpFileName,
dwDesiredAccess,
dwShareMode,
lpSecurityAttributes,
dwCreationDisposition,
dwFlagsAndAttributes,
hTemplateFile);
}
#pragma managed
using namespace System;
namespace AxoCoverRunnerNative {
public ref class FileRemapper
{
static FileRemapper()
{
//Locate function address to redirect
auto moduleHandle = GetModuleHandle(L"Kernel32.dll");
auto procAddress = GetProcAddress(moduleHandle, "CreateFileW");
std::cout << procAddress;
//Prepare unconditional jump opcodes
const int jmpLength = 6;
BYTE jmpOpcodes[jmpLength] = { 0xE9, 0x90, 0x90, 0x90, 0x90, 0xC3 };
auto jmpDistance = (DWORD)OnCreateFileW - (DWORD)procAddress - jmpLength + 1;
//Unlock original method for reading and writing
DWORD procProtectionMode, tempProtectionMode;
VirtualProtect((LPVOID)procAddress, jmpLength, PAGE_EXECUTE_READWRITE, &procProtectionMode);
//Back-up original opcodes
const int backupLength = jmpLength;
BYTE* backupOpcodes = new BYTE[backupLength + jmpLength];
CopyMemory(backupOpcodes, procAddress, backupLength);
CopyMemory(backupOpcodes + backupLength, jmpOpcodes, jmpLength);
auto backDistance = (DWORD)procAddress - (DWORD)backupOpcodes - jmpLength + 1;
CopyMemory(backupOpcodes + backupLength + 1, &backDistance, sizeof(backDistance));
VirtualProtect((LPVOID)backupOpcodes, backupLength + jmpLength, PAGE_EXECUTE_READWRITE, &tempProtectionMode);
OriginalCreateFileW = (CreateFileWCallback)backupOpcodes;
//Override original opcodes with unconditional jump to callback
CopyMemory(&jmpOpcodes[1], &jmpDistance, sizeof(jmpDistance));
CopyMemory(procAddress, jmpOpcodes, jmpLength);
//Restore memory protection
VirtualProtect((LPVOID)procAddress, jmpLength, procProtectionMode, &tempProtectionMode);
}
};
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment