WriteProcessMemory not working for some reason - c++

This is all the source code for a program i'm trying to make, and I can't get WriteProcessMemory to work at all. It returns the correct messages, saying that everything went successfully, but nothing actually changes in the game. Does anyone know of a fix?
#include <iostream>
#include <Windows.h>
using namespace std;
// variables
int plcHold = 1;
string hlthLoop = "OFF";
string ammoLoop = "OFF";
DWORD pid;
DWORD playerAddr;
DWORD hlthOffs = 0xF8;
// main function
int main()
{
// finding pid, opening proc, finding player address
HWND hwnd = FindWindowA(NULL, "AssaultCube");
if(hwnd == NULL)
{
cout << "Error; Couldn't find window" << endl;
} else{
GetWindowThreadProcessId(hwnd, &pid);
HANDLE pHandle = OpenProcess(PROCESS_ALL_ACCESS, FALSE, pid);
if(pHandle == NULL)
{
cout << "Error; Couldn't open process" << endl;
} else{
ReadProcessMemory(pHandle, (LPCVOID)0x50F4F4, &playerAddr, sizeof(playerAddr), 0);
if(ReadProcessMemory != FALSE)
{
cout << "Health successfully read!" << endl;
} else{
cout << "Error code " << GetLastError << endl;
}
}
while(plcHold == 1){
cout << "========== *****'s Assault Cube Trainer ==========\n" << endl;
cout << "=============== Health Loop - " << hlthLoop << " ================" << endl;
Sleep(1500);
system("cls");
if(GetAsyncKeyState(0x5A))
{
cout << "Health successfully edited!" << endl;
WriteProcessMemory(pHandle, LPVOID(playerAddr + hlthOffs), 0, sizeof(999), 0);
CloseHandle(pHandle);
}
}
}
return 0;
}

You're passing a null pointer to WriteProcessMemory for the third (lpBuffer) parameter. You have to pass the address of the actual value, not the value itself. If you want to write an integer value, try this:
DWORD val = 0; // or 999?
WriteProcessMemory(
pHandle, static_cast<LPVOID>(playerAddr + hlthOffs),
&val, sizeof(val), 0);

Related

C++ dll dont inject correctly

I decided to create my own dll injector but the problem is that almost when I finished my code a problem occurs, in the following code my dll does not inject correctly, I tried everything like checking if my dll was good or even my code in general but nothing works. (I want to specify that for my processId if I use GetCurrentProcessId() my dll is injected correctly but not where I want so it is imperative for me to use GetProcessIdByName.) Thank you to all those who will help me!
#include <Windows.h>
#include <TlHelp32.h>
#include <tchar.h>
#include <string>
#include <iostream>
using namespace std;
DWORD GetProcessIdByName(const char* processName)
{
DWORD processId = 0;
HANDLE snap = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
if (snap != INVALID_HANDLE_VALUE)
{
PROCESSENTRY32 pe;
pe.dwSize = sizeof(pe);
if (Process32First(snap, &pe))
{
do
{
if (!_stricmp(pe.szExeFile, processName))
{
processId = pe.th32ProcessID;
break;
}
} while (Process32Next(snap, &pe));
}
CloseHandle(snap);
}
return processId;
}
int main()
{
const char* processName = "OLLYDBG.exe";
DWORD processId = GetProcessIdByName(processName);
LPCSTR dllPath = "C:\\Users\\Alban\\source\\repos\\Cheat\\Cheat\\testdll.dll";
HANDLE hProcess = OpenProcess(PROCESS_ALL_ACCESS, FALSE, processId);
if (hProcess == NULL)
{
cout << "Error with 'OpenProcess', error code : " << GetLastError() << endl;
return 1;
}
cout << "process id : " << processId << endl;
LPVOID pdllPath = VirtualAllocEx(hProcess, NULL, strlen(dllPath) + 1, MEM_COMMIT | MEM_RESERVE, PAGE_READWRITE);
if (pdllPath == NULL)
{
cout << "failed to allocate dll path, error code : " << GetLastError() << endl;
return 1;
}
cout << "path to memory : " << hex << pdllPath << endl;
BOOL writedMemory = WriteProcessMemory(hProcess, pdllPath, LPVOID(dllPath), strlen(dllPath) + 1, NULL);
if (writedMemory == 0)
{
cout << "failed to write memory, error code : " << GetLastError() << endl;
return 1;
}
HANDLE hloadThread = CreateRemoteThread(hProcess, NULL, 0, (LPTHREAD_START_ROUTINE)GetProcAddress(GetModuleHandle("KERNEL32.DLL"), "LoadLibraryA"), pdllPath, 0, NULL);
if (hloadThread == NULL)
{
cout << "Can not create remote thread, error code : " << GetLastError() << endl;
return 1;
}
WaitForSingleObject(hloadThread, INFINITE);
BOOL virtualFree = VirtualFreeEx(hProcess, pdllPath, 0, MEM_RELEASE);
if (virtualFree == 0)
{
cout << "Can not release memory, error code : " << GetLastError() << endl;
}
CloseHandle(hProcess);
}

How to read MBR data on windows system

I'm using a file that has MBR code at an offset of 54 bytes.
In the main() function, I'm calling OpenMBbrFile(), then ReadMbrData().
However, I'm not able to read MBR in my Buffer Properly. Please Help Me with the Issue..................................................................................................................................................................................................................................................................................................................................................................................................................
BOOL OpenMbrFile(LPWSTR sPath)
{
cout << "OpenMBR: Create Handle" << endl;
m_hMbrFile = CreateFile(sPath
, GENERIC_READ
, FILE_SHARE_READ
, NULL
, OPEN_EXISTING
, FILE_ATTRIBUTE_NORMAL
, NULL);
if (m_hMbrFile == INVALID_HANDLE_VALUE) return FALSE;
return TRUE;
}
BOOL CloseMbrFile()
{
cout << "CloseMBR: Closing Handle" << endl;
BOOL bReturn = TRUE;
if (m_hMbrFile != INVALID_HANDLE_VALUE)
bReturn = CloseHandle(m_hMbrFile);
m_hMbrFile = NULL;
cout << "Returning from CloseMBR" << endl;
return bReturn;
}
BOOL ReadMbrData()
{
cout << "ReadMBR: Initialization" << endl;
BOOL bReturn = FALSE;
DWORD dwByteRead = 0;
LARGE_INTEGER filepointer;
filepointer.QuadPart = 54; //MBR data in File at offset 54
BYTE* pBuff = NULL;
pBuff = new BYTE[512];
if (!pBuff)
{
cout << "ReadMBR: Cleaning Stuff up" << endl;
if (pBuff) delete[] pBuff;
CloseMbrFile();
ClosePhysicalDrive();
return bReturn;
}
if (m_hMbrFile == INVALID_HANDLE_VALUE) return FALSE;
cout << "ReadMBR: Setting fp" << endl;
if(!SetFilePointerEx(m_hMbrFile, filepointer, NULL, FILE_BEGIN))
{
cout << "Failed to SetFilePointer ( " << m_hMbrFile << ", " << filepointer.QuadPart << ", 0, FILE_BEGIN)" << endl;
cout << "ReadMBR: Cleaning Stuff up" << endl;
if (pBuff) delete[] pBuff;
CloseMbrFile();
ClosePhysicalDrive();
return bReturn;
}
cout << "ReadMBR: Starting to read File" << endl;
bReturn = ReadFile(m_hMbrFile, pBuff, sizeof(*pBuff), &dwByteRead, 0);
if (bReturn)
bReturn = (sizeof(*pBuff) == dwByteRead); //Need to check this condition? shd it be 512 or size of wud do??
cout << "ReadMBR: Cleaning Stuff up" << endl;
if (pBuff) delete[] pBuff;
CloseMbrFile();
ClosePhysicalDrive();
return bReturn;
}

Win API ReadProcessMemory at base address of DLL returning unexpected data

I'm trying to read the contents of a DLL from memory for some academic research. Specifically, the NTDSA.DLL library for the purpose of mutating specific instructions to simulate programming errors to force the system to fail. The failure will then be recorded to train machine learning algorithms to predict future failures (this is an attempt to generalize previously published research seen here).
I'm getting what I believe to be the base address in virtual memory of the lsass.exe process (which loads the target DLL) through the process outlined here. I'm then calling ReadProcessMemory with an allocated buffer and the handle to lsass obtained by calling OpenProcess with 'PROCESS_ALL_ACCESS' set. The ReadProcessMemory returns with error code 299 80% of the time (partial read) with zero bytes read. My assumption is that the area I'm trying to access is in use when the call is made. Fortunately, it will occasionally return the number of bytes I'm requesting. Unfortunately, the data returned does not match what is on disk when compared to the static DLL in the System32 directory.
So the question is, is ReadProcessMemory doing something funny with the address that I give it, or is my virtual address wrong? Is there another way to figure out where that DLL gets loaded into memory? Any thoughts? Any help or suggestions would be greatly appreciated.
Adding Code:
// FaultInjection.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include <windows.h>
#include <psapi.h>
#include <string>
#include <iostream>
#include <fstream>
#include <stdio.h>
#include <io.h>
#include <tchar.h>
using namespace std;
int _tmain(int argc, _TCHAR* argv[]) {
// Declarations
int pid = 0;
__int64* start_addr;
DWORD size_of_ntdsa;
DWORD aProcesses[1024], cbNeeded, cProcesses;
TCHAR szProcessName[MAX_PATH] = TEXT("<unknown>");
HMODULE hmods[1024];
unsigned int i;
// Get All pids
if (!EnumProcesses(aProcesses, sizeof(aProcesses), &cbNeeded)){
cout << "Failed to get all PIDs: " << GetLastError() << endl;
return -1;
}
// Find pid for lsass.exe
cProcesses = cbNeeded / sizeof(DWORD);
for (i = 0; i < cProcesses; i++) {
if (aProcesses[i] != 0) {
HANDLE hProc = OpenProcess(PROCESS_QUERY_INFORMATION | PROCESS_VM_READ, FALSE, aProcesses[i]);
if (hProc != NULL) {
HMODULE hMod;
DWORD cbNeededMod;
if (EnumProcessModules(hProc, &hMod, sizeof(hMod), &cbNeededMod)) {
GetModuleBaseName(hProc, hMod, szProcessName, sizeof(szProcessName) / sizeof(TCHAR));
}
if (wstring(szProcessName).find(L"lsass.exe") != string::npos) {
pid = aProcesses[i];
}
CloseHandle(hProc);
}
}
}
cout << "lsass pid: " << pid << endl;
HANDLE h_lsass = OpenProcess(PROCESS_ALL_ACCESS, FALSE, pid);
if (!h_lsass) {
cout << "Failed to open process (are you root?): " << GetLastError() << endl;
return -1;
}
// Get Process Image File Name
char filename[MAX_PATH];
if (GetProcessImageFileName(h_lsass, (LPTSTR)&filename, MAX_PATH) == 0) {
cout << "Failed to get image file name: " << GetLastError() << endl;
CloseHandle(h_lsass);
return -1;
}
// Enumerate modules within process
if (EnumProcessModules(h_lsass, hmods, sizeof(hmods), &cbNeeded)) {
for (i = 0; i < (cbNeeded / sizeof(HMODULE)); i++) {
TCHAR szModName[MAX_PATH];
if (GetModuleFileNameEx(h_lsass, hmods[i], szModName, sizeof(szModName) / sizeof(TCHAR))) {
if (wstring(szModName).find(L"NTDSA.dll") != string::npos) {
_tprintf(TEXT("%s\n"), szModName);
MODULEINFO lModInfo = { 0 };
if (GetModuleInformation(h_lsass, hmods[i], &lModInfo, sizeof(lModInfo))){
cout << "\t Base Addr: " << lModInfo.lpBaseOfDll << endl;
cout << "\t Entry Point: " << lModInfo.EntryPoint << endl;
cout << "\t Size of image: " << lModInfo.SizeOfImage << endl;
start_addr = (__int64*)lModInfo.lpBaseOfDll;
size_of_ntdsa = lModInfo.SizeOfImage;
}
else {
cout << "Failed to Print enumerated list of modules: " << GetLastError() << endl;
}
}
} else {
cout << "Failed to Print enumerated list of modules: " << GetLastError() << endl;
}
}
}
else {
cout << "Failed to enum the modules: " << GetLastError() << endl;
}
// Ready to continue?
string cont = "";
cout << "Continue? [Y|n]: ";
getline(cin, cont);
if (cont.find("n") != string::npos || cont.find("N") != string::npos) {
CloseHandle(h_lsass);
return 0;
}
void* buf = malloc(size_of_ntdsa);
if (!buf) {
cout << "Failed to allocate space for memory contents: " << GetLastError() << endl;
CloseHandle(h_lsass);
return -1;
}
SIZE_T num_bytes_read = 0;
int count = 0;
if (ReadProcessMemory(h_lsass, &start_addr, buf, size_of_ntdsa, &num_bytes_read) != 0) {
cout << "Read success. Got " << num_bytes_read << " bytes: " << endl;
} else {
int error_code = GetLastError();
if (error_code == 299) {
cout << "Partial read. Got " << num_bytes_read << " bytes: " << endl;
} else {
cout << "Failed to read memory: " << GetLastError() << endl;
CloseHandle(h_lsass);
free(buf);
return -1;
}
}
if (num_bytes_read > 0) {
FILE *fp;
fopen_s(&fp, "C:\\ntdsa_new.dll", "w");
SIZE_T bytes_written = 0;
while (bytes_written < num_bytes_read) {
bytes_written += fwrite(buf, 1, num_bytes_read, fp);
}
fclose(fp);
cout << "Wrote " << bytes_written << " bytes." << endl;
}
CloseHandle(h_lsass);
free(buf);
return 0;
}
Code works as described minus my amateur mistake of sending the address of the variable I was using to store the address of the location in virtual memory of the target application. In above code, changed:
if (ReadProcessMemory(h_lsass, &start_addr, buf, size_of_ntdsa, &num_bytes_read) != 0) {
to
if (ReadProcessMemory(h_lsass, start_addr, buf, size_of_ntdsa, &num_bytes_read) != 0) {
Works like a charm. Thank you ssbssa for pointing out mistake, sorry for wasting anyone's time.

WriteProcessMemory returns 0 in C++

I am developing a small cash hack for GTA V and I found that when I use
WriteProcessMemory(hp, (LPVOID)0x1417C4C18, &cashVal, (DWORD)sizeof(cashVal), 0)
that the WriteProcessMemory returns 0. Here is the full source code of my small hack.
#include <Windows.h>
#include <iostream>
#include <cstdlib>
using namespace std;
int main()
{
int cashVal = 0;
cout << "Enter the amount of cash you want: " << endl;
cin >> cashVal;
HWND hwnd = FindWindow(0, "Grand Theft Auto V");
if (hwnd == 0) {
cout << "Cannot find the GTAV window. Make sure its running in Windowed mode!" << endl;
}
else {
DWORD pid;
GetWindowThreadProcessId(hwnd, &pid);
HANDLE hp = OpenProcess(PROCESS_ALL_ACCESS, FALSE, pid);
if (!hp) {
cout << "Could not get a handle to GTAV. Try again :(" << endl;
}
else {
int success = WriteProcessMemory(hp, (LPVOID)0x1417C4C18, &cashVal, (DWORD)sizeof
(cashVal), 0);
if (success > 0) {
cout << "You now have " << cashVal << " money!" << endl;
}
else {
cout << "Writing the memory failed!" << endl;
cout << "Error code: " << success << endl;
}
CloseHandle(hp);
}
}
cin.get();
return 0;
}
I basically ask the user to input the cash they want, and it's meant to set it in the game, but it returns a code of 0 and fails. It doesn't fail trying to find the game window because it doesn't print that message to the standard output. Please help me!
NOTE: The hack will be used on single player
First, don't use PROCESS_ALL_ACCESS. Only request what you actually need. WriteProcessMemory() only needs PROCESS_VM_WRITE and PROCESS_VM_OPERATION access, so request only that.
Like many other API functions, when WriteProcessMemory() fails, GetLastError() will tell you why. Your code is assuming that WriteProcessMemory() itself returns an error code directly, but it does not. It returns a BOOL (not an int) to indicate success or failure, and then GetLastError() returns the error code if failure. This is documented behavior:
Return value
If the function succeeds, the return value is nonzero.
If the function fails, the return value is 0 (zero). To get extended error information, call GetLastError. The function fails if the requested write operation crosses into an area of the process that is inaccessible.
Try this:
#include <windows.h>
#include <iostream>
#include <cstdlib>
using namespace std;
int main()
{
int cashVal = 0;
cout << "Enter the amount of cash you want: " << endl;
cin >> cashVal;
HWND hwnd = FindWindow(0, "Grand Theft Auto V");
if (hwnd == 0) {
cout << "Cannot find the GTAV window. Make sure its running in Windowed mode!" << endl;
}
else {
DWORD pid;
GetWindowThreadProcessId(hwnd, &pid);
HANDLE hp = OpenProcess(PROCESS_VM_WRITE | PROCESS_VM_OPERATION, FALSE, pid);
if (!hp) {
cout << "Could not get a handle to GTAV. Try again :(" << endl;
}
else {
BOOL success = WriteProcessMemory(hp, (LPVOID)0x1417C4C18, &cashVal, sizeof(cashVal), 0);
if (success) {
cout << "You now have " << cashVal << " money!" << endl;
}
else {
DWORD errCode = GetLastError();
cout << "Writing the memory failed!" << endl;
cout << "Error code: " << errCode << endl;
}
CloseHandle(hp);
}
}
cin.get();
return 0;
}
You are most likely trying to write to a memory path where you don't have access to... probably you are using a 32-bit program to write to a 64-bit memory address(that's if u use a 64-bit computer), I think I had this problem a few years back porting solved my problem then forgive me if I am wrong atleast that was what I thought.
Try the code on a 32-bit address and if it works... that solves your problem.
And for the Getting_Last_Error you can add this lil' bit of functionality I use.
void PrintLastErrorMsg(){
LPTSTR pTmp = NULL;
DWORD errnum = GetLastError();
FormatMessage(
FORMAT_MESSAGE_ALLOCATE_BUFFER|FORMAT_MESSAGE_FROM_SYSTEM|FORMAT_MESSAGE_ARGUMENT_ARRAY,
NULL,
errnum,
LANG_NEUTRAL,
(LPTSTR)&pTmp,
0,
NULL
);
cout << "Error(" << errnum << "): " << pTmp << endl;
}
Be free to make changes.

GetProcessId failed with error 6: The handle is invalid

I posted a little earlier with a sendmessage issue and we came to the conclusion that it would be extremely hard to get the chat window from Xchat. I have now moved to ThrashIRC and using spy++ was able to find the chat window(highlighted):
As you can see it does have a caption which means that it does see the text. Here is the code that I am using to get the HWND's and the text:
#define WIN32_LEAN_AND_MEAN
#include <windows.h>
#include <iostream>
#include <strsafe.h>
using namespace std;
void FindThrash()
{
cout << "[ThrashIRC]" << endl;
cout << "| find ThrashIRC window" << endl;
HWND hwndThrashIRC = FindWindow(L"ThrashIRC", NULL);
if (NULL != hwndThrashIRC)
{
cout << " + found ThrashIRC window" << endl;
cout << "| find MDIClient window" << endl;
HWND hwndMDIClient = FindWindowEx(hwndThrashIRC, NULL, L"MDIClient", NULL);
if (NULL != hwndMDIClient)
{
cout << " + found MDIClient window" << endl;
cout << "| find DefChannel window" << endl;
HWND hwndDefChannel = FindWindowEx(hwndMDIClient, NULL, L"DefChannel", NULL);
if (NULL != hwndDefChannel)
{
cout << " + found MDIClient window" << endl;
cout << "| find RichEdit20W window" << endl;
HWND hwndRichEdit20W = FindWindowEx(hwndDefChannel, NULL, L"RichEdit20W", NULL);
if (NULL != hwndRichEdit20W)
{
cout << " + found RichEdit20W window" << endl << endl;
cout << "- get text " << endl;
const int bufferSize = 32768;
char textBuffer[bufferSize] = "";
SendMessage(hwndRichEdit20W, WM_GETTEXT, (WPARAM)bufferSize, (LPARAM)textBuffer);
cout << "[begin text]" << endl;
cout << textBuffer << endl;
cout << "[end text]" << endl;
}
else
{
cerr << "RichEdit20W not found." << endl;
}
}
else
{
cerr << "DefChannel not found." << endl;
}
}
else
{
cerr << "MDIClient not found." << endl;
}
}
else
{
cerr << "ThrashIRC not open." << endl;
}
}
void ErrorExit(LPTSTR lpszFunction)
{
// Retrieve the system error message for the last-error code
LPVOID lpMsgBuf;
LPVOID lpDisplayBuf;
DWORD dw = GetLastError();
FormatMessage(
FORMAT_MESSAGE_ALLOCATE_BUFFER |
FORMAT_MESSAGE_FROM_SYSTEM |
FORMAT_MESSAGE_IGNORE_INSERTS,
NULL,
dw,
MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
(LPTSTR)&lpMsgBuf,
0, NULL);
// Display the error message and exit the process
lpDisplayBuf = (LPVOID)LocalAlloc(LMEM_ZEROINIT,
(lstrlen((LPCTSTR)lpMsgBuf) + lstrlen((LPCTSTR)lpszFunction) + 40)*sizeof(TCHAR));
StringCchPrintf((LPTSTR)lpDisplayBuf,
LocalSize(lpDisplayBuf) / sizeof(TCHAR),
TEXT("%s failed with error %d: %s"),
lpszFunction, dw, lpMsgBuf);
MessageBox(NULL, (LPCTSTR)lpDisplayBuf, TEXT("Error"), MB_OK);
LocalFree(lpMsgBuf);
LocalFree(lpDisplayBuf);
ExitProcess(dw);
}
int main()
{
FindThrash();
if (!GetProcessId(NULL))
ErrorExit(TEXT("GetProcessId"));
return 0;
}
The buffer is only that large because 1: I thought it might have been an error where the buffer was to small, and 2: the buffer is going to have to be large because of the amount of text. Any suggestions / code would be greatly appreciated! Thanks!
GetProcessID expects to be passed a valid process handle, as is clearly stated in the MSDN documentation. You're calling it with NULL as the argument:
if (!GetProcessId(NULL))
Why would you expect it to return anything but an invalid handle error when you're clearly providing it an invalid process handle?
Just to make sure you're aware, an HWND is a window handle, not a process handle. FindWindow and FindWindowEx return a window handle.