I've been struggling with this for the better part of a day, rewriting every which way and referencing documentation and even other people's code, but no matter what I do, I can't seem to get my code to work.
A thread in my process is attempting to search the memory of another thread. I'm looking to fix something in a specific module, but I'm furthermore not sure how to or if it's worth narrowing down my search, so right now it's just searching the entire process--and possibly itself? Who knows?
Whenever I latch on a debugger, I can find this set of bytes just fine (equivalent to mov rsi, rax; test dil, 1; jz short loc_...), but for the life of me I can't at all seem to find it.
I found that I did rarely find it, which definitely means that for some reason my search appears to be accessing... well, irrelevant things, and probably finding this purely by chance. I've absorbed so many names and concepts in a single day I think it just isn't sitting right in my head. What's going wrong here?
Addon.cpp
#include <iostream>
#include "Addon.h"
#include <sstream>
#include <vector>
int pattern[] = { 0x48, 0x8B, 0xF0, 0x40, 0xF6, 0xC7, 0x01, 0x74, 0x3E };
int replace[] = { 0x48, 0x8B, 0xF0, 0x40, 0xF6, 0xC7, 0x00, 0x75, 0x3E };
DWORD WINAPI background(LPVOID lpParam)
{
HANDLE h = GetCurrentProcess();
while (true) //for now
{
MEMORY_BASIC_INFORMATION mbi;
unsigned char* p = NULL;
for (p = NULL; VirtualQueryEx(h, p, &mbi, sizeof(mbi)) == sizeof(mbi); p += mbi.RegionSize)
{
std::vector<char> buffer;
if (mbi.State == MEM_COMMIT && mbi.Type == MEM_MAPPED || mbi.Type == MEM_PRIVATE)
{
SIZE_T bytes_read;
buffer.resize(mbi.RegionSize);
ReadProcessMemory(h, p, &buffer[0], mbi.RegionSize, &bytes_read);
buffer.resize(bytes_read);
}
std::vector<char> new_tail(buffer.end() - 9, buffer.end());
for (char t : old_tail)
buffer.push_back(t);
old_tail = new_tail;
if (std::search(buffer.begin(), buffer.end(), std::begin(pattern), std::end(pattern) != buffer.end())
{
MessageBoxA(NULL, "Found", "Found", NULL);
}
}
}
return 0;
}
Added other files on request.
Addon.h
#pragma once
#include <iostream>
#include "windows.h"
#ifdef ADDON_EXPORTS
#define ADDON_API __declspec(dllexport)
#else
#define ADDON_API __declspec(dllimport)
#endif
DWORD WINAPI background(LPVOID lpParam);
dllmain.cpp
#include "windows.h"
#include <string>
#include <tchar.h>
#include "Addon.h"
BOOL APIENTRY DllMain(HMODULE hModule, DWORD ul_reason_for_call, LPVOID lpReserved)
{
switch (ul_reason_for_call)
{
case DLL_PROCESS_ATTACH:
DWORD thread;
CreateThread(NULL, 0, background, 0, 0, &thread);
if (thread == NULL)
{
MessageBoxA(NULL, "Failed to start crash fix", "Error", MB_ICONERROR);
}
break;
case DLL_THREAD_ATTACH:
case DLL_THREAD_DETACH:
case DLL_PROCESS_DETACH:
break;
}
return TRUE;
}
The problem was in the definition of pattern (and replace). It was defined as int, whereas it should be char. As Ted Lyngmo said, 'sometimes the answer stares you right in the good eye.'
Related
I get the error, "Debug Assertion Failed", when executing my .exe via the Start-Process command in PowerShell. I do not get this error when normally executing via File Explorer (double-click). Please see the error below.
There have been similar questions on this forum that have suggested I add the following code to mute the error:
#define NDEBUG
#include <assert.h>
While solving the error is best practice, I would like to know why the above doesn't work for me. For greater context, I am doing a DLL proxy.
#include "pch.h"
#include <stdio.h>
#include <stdlib.h>
#define NDEBUG
#include <assert.h>
#define _CRT_SECURE_NO_DEPRECATE
#pragma warning (disable : 4996)
#pragma comment(linker, "/export:_nettle_aeads=tmpC652._nettle_aeads,#1")
DWORD WINAPI DoMagic(LPVOID lpParameter)
{
//https://stackoverflow.com/questions/14002954/c-programming-how-to-read-the-whole-file-contents-into-a-buffer
FILE* fp;
size_t size;
unsigned char* buffer;
fp = fopen("fz-dump-26072022-1635.bin", "rb");
fseek(fp, 0, SEEK_END);
size = ftell(fp);
fseek(fp, 0, SEEK_SET);
buffer = (unsigned char*)malloc(size);
//https://ired.team/offensive-security/code-injection-process-injection/loading-and-executing-shellcode-from-portable-executable-resources
fread(buffer, size, 1, fp);
void* exec = VirtualAlloc(0, size, MEM_COMMIT, PAGE_EXECUTE_READWRITE);
memcpy(exec, buffer, size);
((void(*) ())exec)();
return 0;
}
BOOL APIENTRY DllMain(HMODULE hModule,
DWORD ul_reason_for_call,
LPVOID lpReserved
)
{
HANDLE threadHandle;
switch (ul_reason_for_call)
{
case DLL_PROCESS_ATTACH:
// https://gist.github.com/securitytube/c956348435cc90b8e1f7
// Create a thread and close the handle as we do not want to use it to wait for it
threadHandle = CreateThread(NULL, 0, DoMagic, NULL, 0, NULL);
CloseHandle(threadHandle);
case DLL_THREAD_ATTACH:
break;
case DLL_THREAD_DETACH:
break;
case DLL_PROCESS_DETACH:
break;
}
return TRUE;
}
There are many more pragmas in the above code. Approx 400 more lines of similar export functions.
The solution is quite simple, adding the full path...
fp = fopen("C:\\Program Files\\FileZilla FTP Client\\fz-dump-26072022-1635.bin", "rb");
I found that the value of fp was NULL when executing via the PowerShell command Start-Process. This is because it was adding the file name fz-dump-26072022-1635.bin to the directory where PowerShell is called from, which is C:\Windows\System32\WindowsPowerShell\v1.0\. This explains why double clicking on the .exe works with no error, as the value of fp is correct, while calling it from any other directory doesn't work.
I was learning about to how to build a JIT compiler and stumbled across a piece of code (attached below) :
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/mman.h>
// Allocates RWX memory of given size and returns a pointer to it. On failure,
// prints out the error and returns NULL.
void* alloc_executable_memory(size_t size) {
void* ptr = mmap(0, size,
PROT_READ | PROT_WRITE | PROT_EXEC,
MAP_PRIVATE | MAP_ANONYMOUS, -1, 0);
if (ptr == (void*)-1) {
perror("mmap");
return NULL;
}
return ptr;
}
void emit_code_into_memory(unsigned char* m) {
unsigned char code[] = {
0x48, 0x89, 0xf8, // mov %rdi, %rax
0x48, 0x83, 0xc0, 0x04, // add $4, %rax
0xc3 // ret
};
memcpy(m, code, sizeof(code));
}
const size_t SIZE = 1024;
typedef long (*JittedFunc)(long);
// Allocates RWX memory directly.
void run_from_rwx() {
void* m = alloc_executable_memory(SIZE);
emit_code_into_memory(m);
JittedFunc func = m;
int result = func(2);
printf("result = %d\n", result);
}
Now before littering my terminal with error messages, I googled up MSDN for these functions and to my surprise, none of them turned up. These are apparently POSIX header files that are unavailable in Windows. My question is does MSVC alternatives to these headers exist?
I have installed Cygwin, but I get header not found error.
I am currently working on my first D3D project, which involves creating an overlay for a game in order to present the user with real time information. The actual data acquisition has been handled, and will be sent in via a message system. Currently, I have the program working for borderless fullscreen mode, and am in the process of adapting it to scale proportionally when in windowed mode (to ensure that everything points to the right place, regardless of size). The app is parented to the game, however, everything falls apart when the game is put into true fullscreen mode. Research has indicated that I will, to my understanding, need to create a fake .dll, and insert it into the game's local directory. This .dll will be opened instead of the actual directX one that it is looking for, and I can do the needed graphics there.
To answer a few potential questions, I do not have access to the game directly, and, while this has been okay'd by the developers for game in question, I would rather it not be caught and punished by anti-cheat software. Additionally, I'd like to keep the performance hit to a minimum, so I currently have the FPS for the overlay quite low (~10fps).
Thanks in advance for any help!
This is a D3D11 Present x64 trampoline hook project I was just working with. You can draw inside hkPresent() before returning and whatever you draw will show up on the screen.
#include <Windows.h>
#include <d3d11.h>
#include <d3dcompiler.h>
#include <DirectXMath.h>
#pragma comment(lib, "d3d11.lib")
#pragma comment(lib, "d3dcompiler.lib")
#define SAFE_RELEASE(p) if (p) { p->Release(); p = nullptr; }
void* Tramp64(void* src, void* dst, int len)
{
int MinLen = 14;
if (len < MinLen) return NULL;
BYTE stub[] = {
0xFF, 0x25, 0x00, 0x00, 0x00, 0x00, // jmp qword ptr [$+6]
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 // ptr
};
void* pTrampoline = VirtualAlloc(0, len + sizeof(stub), MEM_COMMIT | MEM_RESERVE, PAGE_EXECUTE_READWRITE);
DWORD dwOld = 0;
VirtualProtect(src, len, PAGE_EXECUTE_READWRITE, &dwOld);
uintptr_t retto = (uintptr_t)src + len;
// trampoline
memcpy(stub + 6, &retto, 8);
memcpy((void*)((uintptr_t)pTrampoline), src, len);
memcpy((void*)((uintptr_t)pTrampoline + len), stub, sizeof(stub));
// orig
memcpy(stub + 6, &dst, 8);
memcpy(src, stub, sizeof(stub));
for (int i = MinLen; i < len; i++)
{
*(BYTE*)((uintptr_t)src + i) = 0x90;
}
VirtualProtect(src, len, dwOld, &dwOld);
return (void*)((uintptr_t)pTrampoline);
}
bool GetD3D11SwapchainDeviceContext(void** pSwapchainTable, size_t Size_Swapchain, void** pDeviceTable, size_t Size_Device, void** pContextTable, size_t Size_Context)
{
WNDCLASSEX wc{ 0 };
wc.cbSize = sizeof(wc);
wc.lpfnWndProc = DefWindowProc;
wc.lpszClassName = TEXT("dummy class");
if (!RegisterClassEx(&wc))
{
return false;
}
DXGI_SWAP_CHAIN_DESC swapChainDesc{ 0 };
swapChainDesc.BufferCount = 1;
swapChainDesc.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT;
swapChainDesc.BufferDesc.Format = DXGI_FORMAT_R8G8B8A8_UNORM;
swapChainDesc.OutputWindow = GetForegroundWindow();
swapChainDesc.SampleDesc.Count = 1;
swapChainDesc.BufferDesc.ScanlineOrdering = DXGI_MODE_SCANLINE_ORDER_UNSPECIFIED;
swapChainDesc.BufferDesc.Scaling = DXGI_MODE_SCALING_UNSPECIFIED;
swapChainDesc.SwapEffect = DXGI_SWAP_EFFECT_DISCARD;
swapChainDesc.Windowed = TRUE;
D3D_FEATURE_LEVEL featureLevel;
IDXGISwapChain* pDummySwapChain = nullptr;
ID3D11Device* pDummyDevice = nullptr;
ID3D11DeviceContext* pDummyContext = nullptr;
HRESULT hr = D3D11CreateDeviceAndSwapChain(nullptr, D3D_DRIVER_TYPE_REFERENCE, nullptr, 0, nullptr, 0, D3D11_SDK_VERSION, &swapChainDesc, &pDummySwapChain, &pDummyDevice, &featureLevel, nullptr);
if (FAILED(hr))
{
DestroyWindow(swapChainDesc.OutputWindow);
UnregisterClass(wc.lpszClassName, GetModuleHandle(nullptr));
return false;
}
if (pSwapchainTable && pDummySwapChain)
{
memcpy(pSwapchainTable, *reinterpret_cast<void***>(pDummySwapChain), Size_Swapchain);
}
if (pDeviceTable && pDummyDevice)
{
memcpy(pDeviceTable, *reinterpret_cast<void***>(pDummyDevice), Size_Device);
}
if (pContextTable && pDummyContext)
{
memcpy(pContextTable, *reinterpret_cast<void***>(pDummyContext), Size_Context);
}
SAFE_RELEASE(pDummySwapChain);
SAFE_RELEASE(pDummyDevice);
SAFE_RELEASE(pDummyContext);
DestroyWindow(swapChainDesc.OutputWindow);
UnregisterClass(wc.lpszClassName, GetModuleHandle(nullptr));
return true;
}
void* SwapChain[18];
void* Device[40];
void* Context[108];
typedef HRESULT(__fastcall* tPresent)(IDXGISwapChain* pThis, UINT SyncInterval, UINT Flags);
tPresent oPresent = nullptr;
HRESULT __fastcall hkPresent(IDXGISwapChain* pThis, UINT SyncInterval, UINT Flags)
{
return oPresent(pThis, SyncInterval, Flags);
}
DWORD WINAPI MainThread(HMODULE hModule)
{
if (GetD3D11SwapchainDeviceContext(SwapChain, sizeof(SwapChain), Device, sizeof(Device), Context, sizeof(Context)))
{
oPresent = (tPresent)Tramp64(SwapChain[8], hkPresent, 19);
}
return 0;
}
BOOL APIENTRY DllMain(HMODULE hModule, DWORD ul_reason_for_call, LPVOID lpReserved)
{
switch (ul_reason_for_call)
{
case DLL_PROCESS_ATTACH:
CreateThread(nullptr, 0, (LPTHREAD_START_ROUTINE)MainThread, hModule, 0, nullptr);
case DLL_THREAD_ATTACH:
case DLL_THREAD_DETACH:
case DLL_PROCESS_DETACH:
break;
}
return TRUE;
}
This is a combination of code from several people: me, Broihon, Traxin & A200K
I know it's a long post but it's mostly code and pictures, it's a quick read! First of all, here is what I'm trying to do:
I'm trying to execute a BYTE array in a detoured function in order to go back to the original code as if I didn't detour anyhting Here is my code:
DllMain (DetourAddress is all that matter):
BOOL APIENTRY DllMain( HANDLE hModule, DWORD ul_reason_for_call, LPVOID lpReserved )
{
switch (ul_reason_for_call)
{
case DLL_PROCESS_ATTACH:
AllocConsole();
freopen("CONOUT$", "w", stdout);
DetourAddress((void*)HookAddress, (void*)&DetourFunc);
case DLL_PROCESS_DETACH:
FreeConsole();
break;
}
return TRUE;
}
DetourAddress (code is self-explanatory, I think):
void DetourAddress(void* funcPtr, void* hook)
{
// write jmp
BYTE cmd[5] =
{
0xE9, //jmp
0x00, 0x00, 0x00, 0x00 //address
};
// make memory readable/writable
DWORD dwProtect;
VirtualProtect(funcPtr, 5, PAGE_EXECUTE_READWRITE, &dwProtect);
// read bytes about to be replaced
ReadProcessMemory(GetCurrentProcess(), (LPVOID)funcPtr, mem, 5, NULL);
// write jmp in cmd
DWORD offset = ((DWORD)hook - (DWORD)funcPtr - 5); // (dest address) - (source address) - (jmp size)
memcpy(&cmd[1], &offset, 4); // write address into jmp
WriteProcessMemory(GetCurrentProcess(), (LPVOID)funcPtr, cmd, 5, 0); // write jmp
// reprotect
VirtualProtect(funcPtr, 5, dwProtect, NULL);
}
DetourFunc:
_declspec(naked) void DetourFunc()
{
__asm
{
PUSHFD
PUSHAD
}
printf("function detoured\n");
__asm
{
POPAD
POPFD
}
// make memory readable/writable
DWORD dwProtect;
VirtualProtect(mem, 6, PAGE_EXECUTE_READWRITE, &dwProtect);
pByteExe();
// reprotect
VirtualProtect(mem, 6, dwProtect, NULL);
__asm
{
jmp HookReturnAddress
}
}
And finaly the global variables, typedef for pByteExe() and includes:
#include <Windows.h>
#include <cstdio>
DWORD HookAddress = 0x08B1418,
HookReturnAddress = HookAddress+5;
typedef void ( * pFunc)();
BYTE mem[6] = { 0x0, 0x0, 0x0, 0x0, 0x0, 0xC3 };
pFunc pByteExe = (pFunc) &mem
As you can see in DetourFunc, I'm trying to execute my byte array (mem) directly. Using OllyDbg, this gets me there:
Which is exactly the bytes I'm trying to execute. Only problem is that it gives me an Access violation error when executing... Any idea why? I would have thought "VirtualProtect(mem, 5, PAGE_EXECUTE_READWRITE, &dwProtect);" would have made it safe to access... Thanks for your help!
EDIT: I just realized something wierd was happening... when I "Step into" with ollydbg, the mem instructions are correct, but as soon as I scroll a little, they change back to this:
Any idea why?
You've forgot the module offset...
DWORD module = (DWORD)GetModuleHandle(NULL);
DWORD real_address = module + (DWORD)ADDRESS;
ADDRESS have to of course relative to your module. (The module offset isn't allways the same)
And btw. why you take WriteProcessMemory, when you inject your DLL? A simple memcpy is enought...
I am trying to retrieve a set of display related interfaces and seem always to get the 259 error. Since I am very unexperienced with WinApi I could need some hints :)
#include <atlstr.h>
#include <SetupApi.h>
#pragma comment(lib, "setupapi.lib")
#include <stdio.h>
#include <windows.h>
#include <setupapi.h>
#include <devguid.h>
#include <regstr.h>
const GUID GUID_CLASS_MONITOR = {0x4d36e96e, 0xe325, 0x11ce, 0xbf, 0xc1, 0x08, 0x00, 0x2b, 0xe1, 0x03, 0x18};
const GUID GUID_DEVINTERFACE_MONITOR = {0xe6f07b5f, 0xee97, 0x4a90, 0xb0, 0x76, 0x33, 0xf5, 0x7b, 0xf4, 0xea, 0xa7};
int main( int argc, char *argv[ ] )
{
HDEVINFO hDevInfo;
SP_DEVICE_INTERFACE_DATA ifData;
ifData.cbSize = sizeof(ifData);
DWORD dwError;
hDevInfo = SetupDiGetClassDevs(NULL /*&GUID_CLASS_MONITOR*/, NULL, NULL, DIGCF_ALLCLASSES);
dwError = GetLastError();
BOOL bRtn = SetupDiEnumDeviceInterfaces(hDevInfo, NULL, &GUID_CLASS_MONITOR, 0, &ifData); // GUID_DEVINTERFACE_MONITOR did not work either
dwError = GetLastError();
return 0;
}
I cannot see what I am doing wrong SetupDiGetClassDevs has no errors but everything I try regarding SetupDiEnumDeviceInterfaces returns 259.
I've been trying both device setup as well the device interface GUID with no luck.
Edit: Clarification: bRtn returns 0 which means that SetupDiEnumDeviceInterfaces has failed. The 259 error means no more items but my system has two screens attached and since I am calling SetupDiGetClassDevs with no GUID I have expected to get at least my two screen items.
Edit: Added cbSize as suggested
Do you know that ifData.cbSize must be set properly before you call SetupDiEnumDeviceInterfaces?
(http://msdn.microsoft.com/en-us/library/windows/hardware/ff551015(v=vs.85).aspx)
The caller must set DeviceInterfaceData.cbSize to sizeof(SP_DEVICE_INTERFACE_DATA) before calling this function.
(http://msdn.microsoft.com/en-us/library/windows/hardware/ff552342(v=vs.85).aspx)
A SetupAPI function that takes an instance of the SP_DEVICE_INTERFACE_DATA structure as a parameter verifies whether the cbSize member of the supplied structure is equal to the size, in bytes, of the structure.
You did not show setting this value in your code.
For some reason the answer I found by try and error is not intuitive for me but it seems to work.
As I am unable to retrieve the device setup GUID but I had to add DIGCF_DEVICEINTERFACE with conjunction to device interface GUID GUID_DEVINTERFACE_MONITOR to be able to retrieve the interfaces.
Thanks for the hints as missing cbSize would have resulted in another error too :/