I'm trying to hook a function using its address, and so far it is overall working great!
The only problem is when using std::cout in combination with having MessageBoxA from the WinAPI hooked, then it crashes! The weird thing is, it only crashes in that specific case, not if it is called in combination with printf or simply int i = MessageBoxA(...);
For testing, I made so that the instructions at the function address directly returns 32. Not much of a hook I know, but this is just for testing.
// mov eax, 32
// ret
const DWORD instructionCount = 6;
BYTE instructions[instructionCount] = { 0xB8, 0x20, 0x00, 0x00, 0x00, 0xC3 };
Besides having to change protection on a region with VirtualProtect(), then
now I basically just do
memcpy(MessageBoxA, instructions, instructionCount);
Now testing it using this:
int i = MessageBoxA(NULL, "Hello World", "Injector", MB_OK);
printf("Works: %d\n", i);
printf("Works: %d\n", MessageBoxA(NULL, "Hello World", "Injector", MB_OK));
std::cout << "Works: " << i << std::endl;
std::cout << "Doesn't: " << MessageBoxA(NULL, "Hello World", "Injector", MB_OK) << std::endl;
printf("Hello World\n");
Then it crashes just after std::cout << MessageBoxA(...). Removing that line, and everything works!
Note that it successfully prints 32, it crashes when reaching the next statement.
Again it is only in that case where it doesn't work, so using this:
__declspec(noinline) int testFunction(int i)
{
return i;
}
Then reusing the above code and changing MessageBoxA to testFunction (as well as the arguments), and now all 4 statements work!
Bottom line, does anybody have any ideas for why and what is causing the crash in that specific case? When the other cases work perfectly fine.
I think the issue is that you're corrupting the stack pointer. Try using the following:
const DWORD instructionCount = 8;
BYTE instructions[instructionCount] = { 0xB8, 0x20, 0x00, 0x00, 0x00, 0xC2, 0x10, 0x0 };
That will pop the args off the stack as Peter Cordes mentioned. Hope that helps.
Related
Here is my code:
inline DWORD RestoreZwQueryInformationProcess() {
HMODULE ntdll = GetModuleHandleA("ntdll.dll");
DWORD ZwQueryInformationProcessAddr = reinterpret_cast<DWORD>(
GetProcAddress(ntdll, "ZwQueryInformationProcess"));
BYTE ZwQIP[] = {
0xB8, 0x19, 0x00, 0x00, 0x00
};
BYTE* originalBytes = (BYTE*)ZwQueryInformationProcessAddr;
int i = 0;
for (BYTE _byte : ZwQIP) {
*(BYTE*)(ZwQueryInformationProcessAddr + i) = _byte;
i++;
}
return ZwQueryInformationProcessAddr;
}
In dllmain.cpp
RestoreZwQueryInformationProcess();
When calling that function, injected application is crashing.
Is it something about ntdll.dll permissions? I couldn't get it work.
Edit: My friend is using the same dll and the same injection method, and his application isn't crashing.
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.'
I am trying to create my own JIT and so far managed to run very simple assembly code (in machine-code), but having trouble figuring out how to call functions this way. In Visual Studio I can see functions in disassembly window.
Another related question is how do I call Win32 MessageBox() in machine-code?
Next question is how do I call external DLL/LIB functions in this manner?
Also is there any books or tutorials which could teach me further in this subject? I have tried to search for it but get results like .NET, JVM and LLVM which I think is not really what I am looking for.
Here is a simplified version of the code that I am working on:
#include <iostream>
#include <Windows.h>
int main(int argc, char* argv[])
{
// b8 03 00 00 00 83 c0 02 c3
unsigned char code[] = {
0xb8, // mov eax, 3
0x03, 0x00, 0x00, 0x00, // 3 (32 bit)
0x83, // add eax, 2 // 0x83 = add,
0xc0, // ModR/M with immediate 8 bit value
0x02, // 2 (8 bit)
0xc3 // ret
};
void* mem = VirtualAlloc(0, sizeof(code), MEM_COMMIT, PAGE_EXECUTE_READWRITE);
memcpy(mem, code, sizeof(code));
DWORD old;
VirtualProtect(mem, sizeof(mem), PAGE_EXECUTE_READ, &old);
int(*func)() = reinterpret_cast<int(*)()>(mem);
printf("Number is %d\n", func());
VirtualFree(mem, 0, MEM_RELEASE);
return 0;
}
Is it possible to have the JIT assembly code to call a C++ function?
Before this project I made a byte-code interpreter in C++, but I wasn't really happy with the speed when comparing it to equivalent test program in C#. C# was roughly 25x times faster. So I stumbled on something called JIT to make it faster. So I hope you all can see where I am taking this JIT project. And maybe if possible make it handle GUI.
You can probably find some tutorials about writing a compiler/linker. It may help with implementing/calling dynamic libraries.
I'm not sure what you exactly mean by calling C++ functions. Anyway I wrote the following demo program that you can take a look and see if it helps at all.
#include <Windows.h>
#include <iostream>
using namespace std;
__int64 sub(__int64 a, __int64 b)
{
return a - b;
}
int main(int argc, char **argv)
{
char code[] =
{
0x48, 0x89, 0xC8, // mov rax, rcx
0xC3, // ret
0x48, 0x83, 0xEC, 0x20, // sub rsp, 0x20
0xFF, 0xD0, // call rax
0x48, 0x83, 0xC4, 0x20, // add rsp, 0x20
0xC3 // ret
};
char *mem = static_cast<char *>(VirtualAlloc(0, sizeof(code), MEM_COMMIT, PAGE_EXECUTE_READWRITE));
MoveMemory(mem, code, sizeof(code));
auto setFunc = reinterpret_cast<void *(*)(void *)>(mem);
auto callFunc = reinterpret_cast<__int64 (*)(__int64, __int64)>(mem + 4);
setFunc(sub);
__int64 r = callFunc(0, 1);
cout << "r = " << r << endl;
VirtualFree(mem, 0, MEM_RELEASE);
cin.ignore();
return 0;
}
I'm trying to add additional packet in MyRecv function, but I don't know why it doesn't working. I tried to parse incoming packets and function works fine.
So probably my way to sending custom packet to application isn't properly.
In general assumption I just want send prepared packet to application.
This packet i took from WPE PRO.
Code with MyRecv function:
INT WINAPI MyRecv(SOCKET sock, CHAR* buf, INT len, INT flags) {
CHAR buffer[256];
char msg2[] = { 0x1B, 0, 0x04, 0x06, 0, 0x5A, 0x65, 0x6E, 0x74, 0x61,
0x78, 0x06, 0, 0x5A, 0x65, 0x6E, 0x74, 0x61, 0x78, 0x05, 0x07, 0,
0x66, 0x61, 0x6A, 0x6E, 0x69, 0x65, 0x65 };
int ret = precv(sock, buf, len, flags);
if (ret <= 0) {
return ret;
}
if (fake_recv) {
char tmp[256];
fake_recv = false;
printf("Fake1-> Lenght:%d Size:%d", len, strlen(buf));
strcat(buf, msg2);
printf("Fake2-> Lenght:%d Size:%d", len, strlen(buf));
return ret;
}
return ret;
}
msg2 isn't a null-terminated string. In fact it has an interior null. So using strlen() and strcat() with it is never going to work.
Similarly you neither know nor care what's already in buf, so calling strcat() and strlen() on that is both pointless and dangerous: if it contains no nulls at all you will over-run it, and at best over-report the length, and at worst crash.
And you're not adjusting ret for the extra data added into the buffer.
And no useful purpose is accomplished by declaring the unused tmp[] variable.
Try this:
if (fake_recv) {
fake_recv = false;
printf("Fake1-> Length:%d Received:%d", len, ret);
int len2 = min(len-ret, sizeof msg2);
memcpy(&buf[ret], msg2, len2);
ret += len2;
printf("Fake2-> Length:%d Received:%d", len, ret);
return ret;
}
I have a problem with ReadFile function in a virtual serial port:
char tmp[128];
int multiplo=0;
DWORD err;
COMSTAT stt;
ClearCommError(hcom, &err, &stt);
do{
if(ReadFile(hcom, tmp, stt.cbInQue, &err, NULL)){
tmp[err] = '\0';
memcpy(bfIn+multiplo, tmp, err);
multiplo = multiplo + err;
}else
return 0;
}while(err > 0);
this code works when ReadFile get valid character like 0x01, 0x02, 0x03... but there is a problem with 0x00, the code doesn't read like I expected, I try with hyperterminal and that works perfect.
I've defined in dcb structure:
dcb.fNull = false;
but still I have the same problem, any help?
The problem seems to be not in ReadFile() but rather in your use of tmp[] as the terminating '\0' happens to be 0x00, too.
What do you mean by "doesn't read like I expected"? Can you describe the symptoms in more detail?