C++ memory address and offset writing / read - c++

Hello sorry for my bad English.
I want to calculate an address with offset.
The example I have got a base address: 0x00D2038 with offset 0x1c
I have tried this.
DWORD address = 0x004D2038;
DWORD offset = 0x1c;
DWORD base = (DWORD)(address + offset);
int old_value = 0;
int value = 3000;
//Obtain new address form the address whit offset.
DWORD addr2 = ReadProcessMemory(phandle,(void*)base,&old_value,sizeof(old_value),0);
//Write Memory
WriteProcessMemory(phandle,(void*)addr2,&value,(DWORD)sizeof(value),NULL);
But it does not work.
Memory is not changed. what is my error?

According to msdn, ReadProcessMemory returns a BOOL and you use that as addr2 to WriteProcessMemory. How can the memory be changed?
Suggest search from msdn on ReadProcessMemory and WriteProcessMemory and their example and learn how to use these 2 functions.

Think you have a simple typo -- Try;
//Write Memory
WriteProcessMemory(phandle,(void*)base,&value,(DWORD)sizeof(value),NULL);

Related

C++ How to take value from EXE + Pointer + Offset + Offset?

I'm learning to modifying game values using C++ but now I'm stuck.
I know how to edit for example FLOAT value of Player speed:
uintptr_t _EntitiesBase = (uintptr_t)GetModuleHandle(L"EntitiesMP.dll");
uintptr_t EntityBase = _EntitiesBase + 0x3153D0;
DWORD Run = 0xDE4;
*(FLOAT*)(*(DWORD*)EntityBase + Run) = Value;
But I don't know, how to edit values, that have much offsets (Engine.dll + 0xD52AB0 + 0x48 + 0x228), because in the end it return wrong value, not that I wanted to change
For example, in Cheat Engine, the same thing looks like this:
I added Engine.dll + 0xD52AB0 as a pointer, and next add offset 0x48 and offset 0x220 and it gives me address 2DC7E488, that contains FLOAT value, that I need to change
Do you have any ideas?
You can use ReadProcessMemory to read process memory and WriteProcessMemory to write process memory. to do this you just need to use ReadProcessMemory for every offset then write the pointer value with WriteProcessMemory:-
uintptr_t entitybase;
uintptr_t value1;
float newValue = 100000;
ReadProcessMemory(ProcessHandle, (uintptr_t)EngineDllHandle + 0xD52AB0, &entitybase, sizeof(entitybase), 0);
ReadProcessMemory(ProcessHandle, entitybase + 0x48, &value1, sizeof(value1), 0);
WriteProcessMemory(ProcessHandle, value1 + 0x220, &newValue, sizeof(entitybase), 0);

WriteProcessMemory with multiple Offsets C++

I have struggled with a very annoying problem lately with writing to Process memory in c++... I can not write to process memory with multiple offsets! Even though there are thousands of pages explaining how you fix this problem, it still seems to not work for me. I have been searching around on google all day long, and found many examples of how to fix this problem, but it still seems to not work for me.
So, let me first explain how I am writing to process memory myself, and you could possibly correct it afterwards.
Let us say I have a base address of: 0x04AF3C94
First offsets as: 0x1C
Second offsets as: 0x20
Third as: 0x568
And fourth as: 0x134
How I am doing this myself:
DWORD offset1 = 0x1C;
DWORD offset2 = 0x20;
DWORD offset3 = 0x568;
DWORD offset4 = 0x134;
DWORD base = 0x04AF3C94;
DWORD pointer;
DWORD pointer2;
DWORD pointer3;
DWORD pointer4;
DWORD pointer5;
ReadProcessMemory(handle, LPVOID(base), &pointer, sizeof(pointer), 0);
ReadProcessMemory(handle, LPVOID(pointer + offset1), &pointer2, sizeof(pointer2), 0);
ReadProcessMemory(handle, LPVOID(pointer2 + offset2), &pointer3, sizeof(pointer3), 0);
ReadProcessMemory(handle, LPVOID(pointer3 + offset3), &pointer4, sizeof(pointer4), 0);
ReadProcessMemory(handle, LPVOID(pointer4 + offset4), &pointer5, sizeof(pointer4), 0);
int value = 500;
WriteProcessMemory(handle, LPVOID(pointer5), &value, sizeof(value), 0);
As you can see, if I have 4 offsets such as in this example, I am adding every offset one at a time to the base address, until I got one value that stores every offset added to the baseaddress.
This apparently don't work, what should I do!?
I can't reply to all with your description, but in the MSDN they say that ReadProcessMemory read memory from where it is asked to the given buffer. It means when you call...
ReadProcessMemory(handle, LPVOID(base), &pointer, sizeof(pointer), 0);
...your "pointer" will be filled with what is at the "base" address. So it will contain an address that is numericaly the value of the four bytes at address "base". This is probably not what you want, because if you didn't stored something there before, it's indeterminate. And if so, it will probably crash when you use "pointer".
If you want to read the memory at adresse "base + offset1" with that function, what you have to do is:
ReadProcessMemory(handle, LPVOID(base + offset1), some_buffer, some_buffer_size, 0);
Where some_buffer is a valid buffer you have to declare somewhere.

Problems with pointers and memory adresses

I wonder why this code doesn't work:
#include <iostream>
using namespace std;
int main()
{
int *pointer = (int*)0x02F70BCC;
cout<<*pointer;
return 0;
}
In my opinion it should write on the screen value of 0x02F70BCC,
instead of this my programm crashes.
I know that memory with adress 0x02F70BCC stores value of 20.
But like I said no matter what it just doesn't want to show correct number.
Please help me guys, detailed explanation would be very nice of you.
It doesn't work, because you won't get access to every location in memory you want. Not every location in memory is valid, you may want to read about Virtual Address Space.
Some addresses are reserved for device drivers and kernel mode operations. Another range of addresses (for example 0xCCCCCCCC and higher) may be reserved for uninitialized pointers.
Even if some location is valid, operating system may still deny access to write to/read from certain location, if that would cause undefined behaviour or violate system safety.
EDIT
I think you might be interested in creating some kind of "GameHack", that allows you to modify amount of resources, number of units, experience level, attributes or anything.
Memory access is not a simple topic. Different OSes use different strategies to prevent security violations. But many thing can be done here, after all there is a lot software for doing such things.
First of all, do you really need to write your own tool? If you just want some cheating, use ArtMoney - it is a great memory editor, that I have been using for years.
But if you really have to write it manually, you need to do some research first.
On Windows, for example, I would start from these:
ReadProcessMemory
WriteProcessMemory
Also, I am quite certain, that one of possible techniques is to pretend, that you are a debugger:
DebugActiveProcess.
EDIT 2
I have done some research and it looks, that on Windows (I assume this is your platform, since you mentioned gaming; can't imagine playing anything on crappy Linux), steps required to write another process' memory are:
1. Enumerate processes: (EnumProcesses)
const size_t MAX_PROC_NUM = 512;
DWORD procIDs[MAX_PROC_NUM] = { 0 };
DWORD idsNum = 0;
if(!EnumProcesses(procIDs, sizeof(DWORD) * MAX_PROC_NUM, &idsNum))
//handle error here
idsNum /= sizeof(DWORD); //After EnumProcesses(), idsNum contains number of BYTES!
2. Open required process. (OpenProcess,GetModuleFileNameEx)
const char* game_exe_path = "E:\\Games\\Spellforce\\Spellforce.exe"; //Example
HANDLE game_proc_handle = nullptr;
DWORD proc_access = PROCESS_QUERY_INFORMATION | PROCESS_VM_READ | PROCESS_VM_WRITE; //read & write memory, query info needed to get .exe name
const DWORD MAX_EXE_PATH_LEN = 1024;
for(DWORD n = 0 ; n < idsNum ; ++idsNum)
{
DWORD current_id = procIDs[n];
HANDLE current_handle = OpenProcess(proc_access, false, current_id);
if(!current_handle)
{
//handle error here
continue;
}
char current_path[MAX_EXE_PATH_LEN];
DWORD length = GetModuleFileNameEx(current_handle, nullptr, current_path, MAX_EXE_PATH_LEN);
if(length > 0)
{
if(strcmp(current_path, game_exe_path) == 0) //that's our game!
{
game_proc_handle = current_handle;
break;
}
}
CloseHandle(current_handle); //don't forget this!
}
if(!game_proc_handle)
//sorry, game not found
3. Write memory (WriteProcessMemory)
void* pointer = reinterpret_cast<void*>(0x02F70BCC);
int new_value = 5000; //value to be written
BOOL success = WriteProcessMemory(game_proc_handle, pointer, &new_value, sizeof(int), nullptr);
if(success)
//data successfully written!
else
//well, that's... em...
This code is written just 'as is', but I see no errors, so you can use it as your starting point. I also provided links for all functions I used, so with some additional research (if necessary), you can achieve what you are trying to.
Cheers.
When you use,
cout<<*pointer;
the program tries to dereference the value of the pointer and writes the value at the address.
If you want to print just the pointer, use:
cout << pointer;
Example:
int main()
{
int i = 20;
int* p = &i;
std::cout << *p << std::endl; // print the value stored at the address
// pointed to by p. In this case, it will
// print the value of i, which is 20
std::cout << p << std::endl; // print the address that p points to
// It will print the address of i.
}

Access a spawned process's TIB through FS register?

I'd like to access a spawned process's TIB (I created the process with CreateProcessW successfully).
I have obtained a pointer to the spawned process's TIB through:
GetThreadContext (with permissions set of course)
Accessing pContext.SegFs
Formatting this value like so: (ldtSel.HighWord.Bits.BaseHi << 24 ) | ( ldtSel.HighWord.Bits.BaseMid << 16 ) | ( ldtSel.BaseLow ); (I don't think this is necessary).
The value I am left with after the format is a 10 digit pointer.
How am I to use this variable in place of the fs register to access the threads information block?
The conventional way I would access it generally would be as so:
__asm
{
mov eax, fs:[0x30] // PEB
mov dwPebBase, eax
}
However, replacing the "fs" with the pointer variable of course wouldn't work, and removing the semi-colon had unexpected results.
So how can I access the members of the TIB through this pointer value, I feel as if I am accessing memory that isn't supposed to be accessed (or attempting to anyway :P).
Thank you for the help.
You are taking the wrong approach for this. Use NtQueryInformationProcess() instead of GetThreadContext() to access the spawned process's PEB, eg:
PROCESS_INFORMATION pi = {0};
...
PROCESS_BASIC_INFORMATION pbi = {0};
ULONG pbi_len = 0;
if (NtQueryInformationProcess(pi.hProcess, ProcessBasicInformation, &pbi, sizeof(pbi), &pbi_len) >= 0)
{
if (pbi.PebBaseAddress)
{
PEB peb = {0};
SIZE_T peb_len = 0;
if (ReadProcessMemory(pi.hProcess, pbi.PebBaseAddress, &peb, sizeof(peb), &peb_len))
{
// use peb as needed...
}
}
}
Refer to the following article for more info:
Get Process Info with NtQueryInformationProcess
a simple trick is call ntdll!RtlGetCurrentPeb() in your local process, this routine return a pointer to PEB, this pointer is in fact valid, and also point to PEB in remote process, then you can use ReadProcessMemory() to read what you need.

memcpy() crashes randomly

I am using memcpy in my application. memcpy crashes randomely and below is the logs i got in Dr.Watson files.
100181b5 8bd1 mov edx,ecx
100181b7 c1e902 shr ecx,0x2
100181ba 8d7c030c lea edi,[ebx+eax+0xc]
100181be f3a5 rep movsd
100181c0 8bca mov ecx,edx
100181c2 83e103 and ecx,0x3
FAULT ->100181c5 f3a4 rep movsb ds:02a3b000=?? es:01b14e64=00
100181c7 ff1508450210 call dword ptr [Debug (10024508)]
100181cd 83c424 add esp,0x24
100181d0 6854580210 push 0x10025854
100181d5 ff1508450210 call dword ptr [Debug (10024508)]
100181db 83c404 add esp,0x4
Below is the code
memcpy((char *)dep + (int)sizeof(EntryRec) + (int)adp->fileHdr.keySize, data, dataSize );
Where:
dep is a structure
EntryRec is a charecter pointer
adp is a structure
data is not NULL in this case
Has anyone faced this issue and can help me?
I have tried to debug the prog,
then i got the following error
Unhandled exception in Prog.exe(MSVCRTD.DLL):0xC0000005: Access voilation
Data is passed argument for this program and this is void*
Further Info:
I have tried to Debug the code adapter is crashing in the following area this function is present in OUTPUT.c (I think this is a library function)
#else /* _UNICODE */
if (flags & (FL_LONG|FL_WIDECHAR)) {
if (text.wz == NULL) /* NULL passed, use special string */
text.wz = __wnullstring;
bufferiswide = 1;
pwch = text.wz;
while ( i-- && *pwch )
++pwch;
textlen = pwch - text.wz;
/* textlen now contains length in wide chars */
} else {
if (text.sz == NULL) /* NULL passed, use special string */
text.sz = __nullstring;
p = text.sz;
while (i-- && *p) //Crash points here
++p;
textlen = p - text.sz; /* length of the string */
}
Value for variables:
p= ""(not initialised)
i= 2147483598
There are two very likely explanations:
You are using memcpy across overlapping addresses -- the behavior of this situation is undefined. If you require the ability to handle overlapping addresses, std::memmove is the "equivalent" tool.
You are using memcpy to copy to/from memory that is inaccessible to your program.
From the code you've shown, it looks like (2) is the more likely scenario. Since you are able to debug the source, try setting a breakpoint before the memcpy occurs, and verify that the arguments to memcpy all match up (i.e. source + num < dest or source > dest + num).
From the disassembled code it appears that the source pointer is not in your address space.
rep movsb copies from ds:si to es:di. The ?? indicates that the memory at ds:si could not be read.
Is the data pointed to by (char *)dep + (int)sizeof(EntryRec) + (int)adp->fileHdr.keySize always at least dataSize long?
I have come across similar crashes where variable length strings are later treated like fixed with strings.
eg
char * ptr = strdup("some string");
// ...
memcpy(ptr, dest, fixedLength);
Where fixedLength is greater than 10. Obviously these were in different functions so the length issue was not noticed. Most of the time this will work, dest will contain "some string" and after the null will be random garbage. In this case if you treat dest as a null terminated string you will never notice, as you don't see the garbage after the null.
However if ptr is allocated at the end of a page of memory, you can only read to the end of the allocated memory and no further. As soon as you read past the end of the page the operating system will rightly crash your program.
It looks like you've run over the end of a buffer and generated an access violation.
Edit: There still is not enough information. We cannot spot a bug without knowing much more about how the buffer you are trying to copy to is allocated whether it has enough space (I suspect it does not) and whether dataSize is valid.
If memcpy crashes the usual reason is, that you passed illegal arguments.
Note that with memcpy source and destination may not overlap.
In such a case use memmove.
from your code "memcpy((char *)dep + (int)sizeof(EntryRec) + (int)adp->fileHdr.keySize, data, dataSize)" and the debug infomation, the "data" looks like a local variable (on-stack variable), you'd do "data = malloc(DATA_SIZE)" instead of "char data[DATA_SIZE]" etc; otherwise, at your current code line, the "data" was popped already, so may cause memory accessing fault randomly.
I'd suggest using memmove as this handles overlapping strings, when using memcpy in this situation the result is unpredictable.