Pointer From Cheat Engine To C++ - c++

I am looking for a way to pass a pointer address from cheat engine to a line of code.
The Cheat Engine address is P-> 0C86D240.
The Line of Code is as follows:
WriteProcessMemory(handle,(LPVOID)P->0C86D240,).
In the end i would like to change the pointer address' value.
Update: i changed P-> to 0x0C86D240 and i was able to write memory for THAT session of the game. When closed then opened again the hex number was different

P->0C86D240 in Cheat Engine means that the entry is a chain of pointers which finally resolves to the address 0x0C86D240. If you double click this part in Cheat Engine, you will see a popup dialog showing you what this pointer chain consists of. For example, let's call the starting pointer P0 and a series of offsets called offset0, offset1, offset2, .... A pointer chain is to take the value at the address P0 + offset0, use that as your next pointer P1, then take the value at the address P1 + offset1, use that as your next pointer P2 ... this chain will finally give you the address 0C86D240. If you reset your game, you hope your P0 will not change but everything afterwards will change dynamically (i.e. P1, P2, P3,...) and track all the way down to the desired value.
If you know how the pointer chain works, it is then trivial to convert this to C++. You just need to take note of the base pointer and all offsets (as shown in the popup dialog by double-clicking the P->0C86D240 part.) Then, track down until you use up all offset values.

You write a function which walks the multilevel pointer, each step it de-references the pointer and adds the relative offset.
For this example I will use a simple assault cube cheat I've made
FindDMAAddy function (Find Dynamic Memory Allocation Address):
uintptr_t FindDMAAddy(HANDLE hProc, uintptr_t ptr, std::vector<unsigned int> offsets)
{
uintptr_t addr = ptr;
for (unsigned int i = 0; i < offsets.size(); ++i)
{
ReadProcessMemory(hProc, (BYTE*)addr, &addr, sizeof(addr), 0);
addr += offsets[i];
}
return addr;
}
The main code:
uintptr_t moduleBase = GetModuleBaseAddress(procId, L"ac_client.exe");
//Get Handle to Process
HANDLE hProcess = 0;
hProcess = OpenProcess(PROCESS_ALL_ACCESS, NULL, procId);
//Resolve base address of the pointer chain
uintptr_t dynamicPtrBaseAddr = moduleBase + 0x10f4f4;
std::cout << "DynamicPtrBaseAddr = " << "0x" << std::hex << dynamicPtrBaseAddr << std::endl;
//Resolve our ammo pointer chain
std::vector<unsigned int> ammoOffsets = { 0x374, 0x14, 0x0 };
uintptr_t ammoAddr = FindDMAAddy(hProcess, dynamicPtrBaseAddr, ammoOffsets);
std::cout << "ammoAddr = " << "0x" << std::hex << ammoAddr << std::endl;
You can find a more complete version of my answer here but you seemed to already know the rest.

Step 1: Search the value you want to change with cheat engine.
Step 2: If you have found the right address do right click on it and make a pointer scan for this address. Now you should get many base-addresses with some offsets.
Step 3: Close your game and repeat Step 1. Now copy the new address and click on rescan pointerscan (in the window that opened from step 2).Paste the new address in the rescan address field and rescan. Then you should only get the right base-addresses + offsets.
Step 4: To always find the right address do: readprocessmemory(baseaddress+offset)

fist of all I can't figure out what the P-> means maybe remove that and make the value a 0x for hex
When closed then opened again the hex number was different
I guess that you are talking about the game if I'm wrong then don't continue reading
so the address you get from cheat engine is probably a dynamic one meaning that every time you close or open it that value will change sense the program will be allocated another place in the memory
so what should you do.....
you could find the static address this process is a bit complicated I will advise you to watch a tutorial https://www.youtube.com/watch?v=hfWOAFsYnFA

Cheat engine tutorial built into the program covers multilevel Pointers. Do your work first. If you have the pointer already found, you have the address you are looking for: A static address that points to the address containing the value you want to modify.

Related

Is there a way to resize a module, inside a process, or extend one to be longer in memory?

I am curious to know if it is possible to extend a process module, like a dll, to be larger.
As an example, I inject test.dll into test.exe, I make test.dll + 0x1000 bytes larger, these new bytes now have PAGE_EXECUTE privileges and I can modify them however I like.
I want to be able to do this only after injecting the dll, not by adding fake code to the dll to overwrite, as I will likely have no control over the execution of the actual test subject.
I have already tried to use VirtualAlloc on the end of the dll's sections to increase its size, but it hasn't worked, I usually get ERROR_BAD_ADDRESS, I made sure to verify the process had enough space after the dll to allocate to and commit to.
uint64_t module_contents = (uint64_t)GetModuleHandleA(NULL);
IMAGE_DOS_HEADER* dos_header = (IMAGE_DOS_HEADER*)module_contents;
IMAGE_NT_HEADERS64* nt_header = (IMAGE_NT_HEADERS*)(module_contents + dos_header->e_lfanew);
IMAGE_SECTION_HEADER* section = (IMAGE_SECTION_HEADER*)(nt_header + 1);
for (unsigned short i = 0; i < nt_header->FileHeader.NumberOfSections; i++) {
if (!section->SizeOfRawData && section->Characteristics & IMAGE_SCN_MEM_EXECUTE) {
char name[8];
memcpy(name, section->Name, sizeof(name));
if (std::string(name).find("text") == std::string::npos) {
//std::cout << name << std::endl;
break;
}
}
section++;
}
std::cout << VirtualAlloc((void*)(module_contents + section->VirtualAddress + section->Misc.PhysicalAddress), 0x1000, MEM_COMMIT | MEM_RESERVE, PAGE_EXECUTE) << std::endl;
The expected result of this is to fill in and commit to the empty space after the module's sections, which I verify has not been committed to both by the cout & with Cheat Engine to look at the memory region. The result I get is an error message of 0x1E7, or ERROR_INVALID_ADDRESS. I have gotten other error messages like ERROR_INVALID_PARAMETER, when using a smaller size like 0x1.
Any help with this is appreciated!

C++ DLL Memory Reading Crashes

I've been trying all day how to read properly the memory of a game with my injected DLL, it works correctly but if the DLL reach other type of variable which is not "float" then it crashes. My question is, how can I detect if is float and avoid crashes. Here is my code:
for (DWORD i = 0x1000000; i < 0x2FFFFFF; i += 0x4)
{
DWORD Base = *(DWORD*)(base + i);
DWORD lvl_2 = *(DWORD*)(Base + 0x8);
float* posx = static_cast<float*>((float*)(lvl_2 + 0x90));
Position_x = static_cast<float>(*posx);
if (Position_x > 7.05f && Position_x < 7.20f) //test > 7.05f && test < 7.20f || i == 0x2217710
{
fprintf(file, "Pointer: 0x%x Position x: %.2f \n", i, Position_x);
}
}
This is a scanner I made to update pointer of a game knowing the structs offsets. This code works correctly if I use as condition i == 0x2217710, it returns the correct position x of the player. If I remove the condition it crashes due to the line Position_x = static_cast... is converting other type of variable in float which is illegal for some variables. How could I do this? Thanks in advance.
First, I'm pretty sure the problem isn't that it crashes when you have a pointer that isn't to a float. All binary values 0 - 0xFFFFFFFF are generally valid as float values, but some are "special", such as "not a number" - but as long as you only compare the value, etc, it will work just fine to use such values too - will just come out as false in the comparison.
Your actual problem is that you are making a pointer from base+i, and then using the content at that location as another pointer - but if base+i does not hold a valid pointer {which is pretty much most 32- or 64-bit values in most systems}, then your next fetch will go wrong. Unfortunately, there is no trivial way to check if a memory address is valid or not. In Windows, you could possibly use __try, __except to catch when you are trying to read an invalid memory address and "do something else".

How can a memory space allocated by mmap() protected from getting allocated by 'new' calls?

I'm allocating space at a specific address using
mmap(...,PROT_WRITE | PROT_READ, MAP_PRIVATE | MAP_ANONYMOUS | MAP_FIXED,...)
But if I call something like new char[large_number] that array is created overlapping the previously allocated memory segment. So my question is what should I do to protect the memory segment I've tried to allocate earlier.
EDIT:
For the following code,
char* base_address = (char*)malloc(sizeof(long));
int page_size = getpagesize();
size_t length = page_size;
char* selected_address = (char*)base_address + (page_size - ((long)base_address % page_size));
char* allocated_address = (char*) mmap(selected_address, page_size * 4, PROT_WRITE | PROT_READ
, MAP_SHARED | MAP_ANONYMOUS | MAP_FIXED, -1, 0);
int* a = new int[page_size / 4];
// mprotect(allocated_address, page_size * 4, PROT_READ | PROT_WRITE);
int* b = new (allocated_address) int[page_size / 2];
int* c = new (allocated_address + page_size / 2 ) int[page_size/2];
int* d = (int*)malloc(page_size);
cout << "base_address:" << (int*)base_address << " selected_address:" << (int*)selected_address << " allocated_address:" << (int*)allocated_address << endl;
cout << "a=" << a << " end=" << &a[page_size/4 - 1] << endl;
cout << "b=" << b << " end=" << &b[page_size/2 - 1] << endl;
cout << "c=" << c << " end=" << &c[page_size/2 - 1] << endl;
cout << "d=" << d << " end=" << &d[page_size - 1] << endl;
I'm getting
base_address:0x603010 selected_address:0x604000 allocated_address:0x604000
a=0x603030 end=0x60402c
b=0x604000 end=0x605ffc
c=0x604800 end=0x6067fc
d=0x604040 end=0x60803c
Shouldn't the a and d segments allocated outside of the mmap allocated space?
From the man page of mmap on my system (OS X)
If MAP_FIXED is specified in flags, the system will try to place the mapping at the specified address, possibly removing a mapping that already exists at that location.
you are forcing mmap() to map at the first page above an address handed to you by malloc(). It is likely that new calls malloc() to get memory blocks and it is likely that the memory allocator thinks it owns the page that you are trying to map to. You don't tell the allocator that it can't use that page, so it goes ahead and does it.
Do not specify MAP_FIXED. Just use the address it gives back to you without MAP_FIXED specified.
mmap(...,PROT_WRITE | PROT_READ, MAP_SHARED | MAP_ANONYMOUS | MAP_FIXED,...)
A memory mapping can only be either MAP_SHARED or MAP_ANONYMOUS, but not both.
But if I call something like new char[large_number] that array is created overlapping the previously allocated memory segment.
This is not possible. You ignore the return value of mmap call, the call most likely fails.
Your implementation platform likely grows the heap implicitly, by keeping track of the highest page address used by the heap, then simply increasing it when needed. The first access to a previously unused page generates a page fault, and the O/S then automatically increases the process's virtual memory address space, starting at the faulted address.
On Linux, see the sbrk(2) man page for a more complete description of this process.
So what happened here, is that you explicitly requested something mmap()ed to an address exactly where the C library will be using next, for allocated memory. And the C library happily proceeded to increase the data segment, intruding on your mmap-ed space.
This is a simple case of "Doctor, it hurts when I wave my arm like this."; "Well, don't do wave your arm like that."
The mmap() man page on Linux offers this caution about the first parameter to mmap():
If addr is NULL, then the kernel chooses the address at which to create
the mapping; this is the most portable method of creating a new mapā€ping.
An NULL address results in the kernel mapping your new memory segment at an address that's nowhere near anything else, and nowhere near the process's data segment, and the two won't interfere with each other.
If, as in your case, you're explicitly mmap()ing a specific address in your virtual address space, the onus is on you to avoid running into trouble, and knowing exactly what's going on within your process, including what the C library is doing.
And I should also note that in order to calculate the new mmaped address, you're calculating a pointer address that's past the end of a currently allocated array.
This is, strictly, undefined behavior. All bets are off, at this point, as far as strict C/C++ compliance goes, as well.
Your code is undefined behavior. You are mmap-ing an address given by new or malloc. You should not do that (and it often should fail with MAP_FIXED since an address returned by new or malloc is rarely page-aligned).
I guess that you are using Linux. So code:
char* allocated_address
= (char*) mmap(NULL, page_size * 4,
PROT_WRITE | PROT_READ,
MAP_ANONYMOUS | MAP_PRIVATE, -1, 0);
if (allocated_address == MMAP_FAILED)
{ perror("mmap"); exit(EXIT_FAILURE); };
int* b = new ((void*)allocated_address) int[page_size / 2];
int* c = new ((void*)(allocated_address + (page_size / 2)*sizeof(int)))
int[page_size/2];
Notice that the byte size of an array int[page_size/2] is sizeof(int)*(page_size/2). On my system (Linux/x86-64/Debian/Sid) sizeof(int) is 4, and page_size is 4096.
Read carefully mmap(2). Because of ASLR the result of mmap (without MAP_FIXED, which you should almost never use, except when mapping again a previously mmaped address segment) is often non-reproducible from one run to the next.
BTW, when your program is running as pid 1234, run cat /proc/1234/maps in a separate terminal (from inside your program you could even read sequentially line by line and parse /proc/self/maps); it will show you the address space of process 1234. Read proc(5) and Advanced Linux Programming

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.
}

Reading and writing with a DLL injection C++

I've run into a bit of a problem and I'm not sure how to do what I am trying to do.
I am using C++ to inject a DLL into an application and I want to alter an address. The problem is that I'm not quite sure how to target it - let me explain...
I know how to use pointers:
int x;
int *myPointer;
myPointer = &x;
*myPointer = 5;
std::cout << x << endl; // 5
And I know that you can point to pointers:
int x;
int *myPointer;
int **myPointer2;
myPointer = &x;
myPointer2 = &myPointer;
**myPointer = 5;
std::cout << x << endl; // 5
I am trying to make a basic game hack by injecting a DLL into a game, and then setting the ammo to a fixed value on a keypress. The injection is working, the keypress is working, but I get a crash whenever I try and access the memory.
I have used Cheat Engine to get the static address for the variable I want to change, along with 3 offsets.
The address info in Cheat Engine looks like this:
Address: 0288A520 = 19
Type: 4 bytes
0 [0288A520 + 0] -> 0288A520
14 [0288A520 + 14] -> 0288A520
384 [0288A3D0 + 384] -> 02881A30
ac_client.exe+109B74 -> 0288A3D0
The value 19 is the one I want to modify in my DLL.
If I close the game and re-open it, I get the correct values coming through using these pointers, but now my issue is I'm not sure how to implement this in C++. How do I represent this static address in C++?
My main thread currently looks like this...
DWORD WINAPI Main_Thread(LPVOID lpParam)
{
while(1)
{
if(GetAsyncKeyState(VK_HOME)) {
// Output value here???
}
Sleep(100);
}
}
Any help is greatly appreciated.
I've got it working. The things I had been trying before were happening because I had an incorrect base address.
My solution can be seen below.
Defining addresses
#define BASE_ADDR 0x00400000
#define AMMO_ADDR 0x00109B74
#define AMMO_OFS1 0x00000384
#define AMMO_OFS2 0x00000014
Get address function
DWORD getAddress(DWORD baseAddress, DWORD offsets[], int offsetCount)
{
DWORD address; // Where the final address will be stored
address = *(DWORD*)(BASE_ADDR + baseAddress); // Add the base address to the modules base address.
// Loop through each offset
for(int i = 0; i < offsetCount; i++) {
address = *(DWORD*)(address + offsets[i]);
}
return address;
}
Changing the value
DWORD ammoOffsets[] = {AMMO_OFS1, AMMO_OFS2};
DWORD ammoAddress = getAddress(AMMO_ADDR, ammoOffsets, 2);
int* ammoPointer = (int*) ammoAddress;
*ammoPointer = 20;