C++ Unable to Read Memory Address - c++

I'm creating a simple HACK for educational purpose only. A simple Triggerbot that reads from memory the value of player aiming to enemy YES = 1 or NO = 0. I have made some other similar HACKS however I never found this problem .. in Rainbow Six Siege I have the memory address both static or dynamic however cheat engine read it well but when I try to read it from my C++ Program it does't work. Not sure why if it had work with other games. I'm new to this and maybe I did something wrong.
#include "stdafx.h"
#include <iostream>
#include <windows.h>
#define F6Key 0x75
using namespace std ;
int value ;
int main()
{
cout << "Open Game .." << endl ;
system("Pause") ;
LPCWSTR gameone = L"Rainbow Six";
HWND hwnd = FindWindow(0, gameone);
if (gameone == 0)
{
cout << "Not Found." << endl ;
system("Pause") ;
}
else
{
cout << "Success finding game." << endl;
DWORD processid ;
GetWindowThreadProcessId(hwnd, &processid) ;
HANDLE process = OpenProcess(PROCESS_ALL_ACCESS, FALSE, processid) ;
cout << processid ;
if (!ReadProcessMemory(process, (void *)0x25421AD9D6C, (void *)&value, sizeof(value), NULL)) {
cout << "Unable to read memory proccess";
}
else {
cout << "\n Read: " << value;
}
system("Pause");
}
return 0 ;
}
Here is the code simple Find the Window by name, gets its PID fine no problem. OpenProcess then when I call the method ReadProcessMemory with the process, address pointer value by parameter is unable to read it print the if condition and never the else of value read.
If I remove the function from the If condition just for testing if at least points to something it gives some random values... is weird that I'm unable to read memory It always work ::(
Can someone help me out? It is some king of security software or something?

First of all, you have to check OpenProcess return value. If your process does not have sufficient rights, it will return NULL and any attempts to use this handle will fail. Use GetLastError function to determine error reason.
Most likely it will be ERROR_ACCESS_DENIED.
Secondary, to successfully access external process memory space, you should open its handle with PROCESS_VM_READ right or enable seDebugPrivilege for you process token. Example how to do that you could see in the MSDN.
And lastly. If memory address (0x25421AD9D6C in your case) is invalid, ReadProcessMemory will fail. In that case value variable would not be initialized and any attempts to use it is an undefined behavior.
Also, if you managed to get process handle, it should be closed using CloseHandle function when you finish using it.
Upd: If ReadProcessMemory returns FALSE and GetLastError - ERROR_PARTIAL_COPY that means that a page fault has occured, you are trying to read from a buffer and at least part of it is not assigned to the physical memory. If you know your value offset, get module load address using PSAPI GetModuleInformation function and add offset to the lpBaseOfDll field of the MODULEINFO structure.

Related

How can i get pointer's address from other application without Cheat Engine?

I want to change or read the pointer's value which is in other program.But i need to know pointer's address.Can i get the address without Cheat Engine and how can i do that ? In the youtube/google/facebook they are using Cheat Engine to know the address.
#include <iostream>
#include <windows.h>
int main() {
DWORD pointer = 0x006DFEF8; // I learned this address from Cheat Engine.
DWORD pid;
int deger;
char program_isim[100];
std::cin >> program_isim;
HWND program = FindWindow(0, program_isim);
if (program == 0) {
std::cout << program_isim << ",bulunamadi." << std::endl;
}
else {
GetWindowThreadProcessId(program, &pid);
HANDLE hand = OpenProcess(PROCESS_ALL_ACCESS, 0, pid);
while (1) {
ReadProcessMemory(hand, (void*)pointer, &deger, sizeof(deger), 0);
std::cout << deger << std::endl;
}
}
return 0;
}
Cheat Engine is a disassembler and debugger. You can find pointers using both of these features, but everything is easiest when using a debugger at runtime. It allows you to set "break on read" and "break on write" breakpoints. The "find what accesses" function of Cheat Engine is just using read breakpoints and logging the addresses where the breakpoint is hit.
Cheat Engine will always be the best way to find pointers. Can you find a pointer via static analysis? Yes you can but it will be more difficult.
You can replicate Cheat Engine's behavior by writing your own program which registers itself as a debugger with the Windows API and set breakpoints on the target process.
But the reason you can't use Cheat Engine is because the game has anticheat that detects your debugger, it will also detect your debugger you write so this is not the solution.
The solution is to bypass the anticheat and then just use Cheat Engine as normal.

Unload dll from process

Hello I want to unload this dll from the process it is injected to, how can I do this? this is how I inject the dll to process:
this is just me showing how i inject my dll into a process, but how do i UNLOAD / UNINJECT this dll from the process if my inject method is this
HANDLE h = OpenProcess(PROCESS_ALL_ACCESS, false, GetProcessIdByName("csgo.exe"));
if (h)
{
LPVOID LoadLibAddr = (LPVOID)GetProcAddress(GetModuleHandleA("kernel32.dll"), "LoadLibraryA");
//cout << "[!] Initialized Library\n";
LPVOID dereercomp = VirtualAllocEx(h, NULL, strlen(dllName), MEM_COMMIT | MEM_RESERVE, PAGE_READWRITE);
//cout << "[!] Initialized memory allocation\n";
WriteProcessMemory(h, dereercomp, dllName, strlen(dllName), NULL);
//cout << "[!] Wrote dll name to memory: " << strlen(dllName) << " byte(s)\n";
HANDLE asdc = CreateRemoteThread(h, NULL, NULL, (LPTHREAD_START_ROUTINE)LoadLibAddr, dereercomp, 0, NULL);
//cout << "[!] Created remote thread: " << asdc << endl;
//cout << "[!] Waiting for Dll exit...\n";
WaitForSingleObject(asdc, INFINITE);
VirtualFreeEx(h, dereercomp, strlen(dllName), MEM_RELEASE);
//cout << "[!] Freeing memory\n";
CloseHandle(asdc);
CloseHandle(h);
//cout << "[!] Closed all handles\n";
//cout << "[!] Complete!\n";
}
You’re using CreateRemoteThread to launch a thread in your target process that runs “LoadLibraryA”.
I have no idea why commenters didn't like your injection code. Looks OK to me. I think you’re correctly closing that thread, however I recommend adding GetExitCodeThread call after WaitForSingleObject, this will give you the return code from LoadLibrary so you can check for errors. You can't call FreeLibrary on that handle because different processes. GetLastError won't work either. But at least you can compare with nullptr to detect a fail.
The reason why DLL stays loaded is no one has called FreeLibrary.
One pattern here, in DllMain of your DLL, under DLL_PROCESS_ATTACH case, create one more remote thread. This time no need to use CreateRemoteThread, just call normal CreateThread because that code already runs in the target process. Call CloseHandle at once on the returned handle (this won't kill the new thread just release the handle). Now in that second remote thread, do whatever you want to do in the target process, and when finished, call FreeLibraryAndExitThread API. This will exit the second remote thread, at the same time unloading your DLL from your target process.
More info: DllMain entry point For DLLs, HINSTANCE is same as HMODULE, just cast the first argument to HMODULE and keep that argument in some variable to pass into FreeLibraryAndExitThread.
Update: As said by the commenter, ideally you need to allocate, and copy, one extra character. Just replace strlen(dllName) with strlen(dllName)+1 in both cases.
Update 2: BTW it's often a good idea to call DisableThreadLibraryCalls first thing in DLL_PROCESS_ATTACH handler. Especially if you then launch new threads from your DllMain.

How to send a struct over a pipe C++

I am very new to writing in c++ and am working on using pipes to communicate between processes. I have written a very simple program that works when I am sending strings or integers but when I try to send a struct (message in this case) I get null when I try to read it on the other side. Does anyone have some insight into this that they would share? Thanks for your time.
#include <unistd.h>
#include <iostream>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#define BUFFER_LEN sizeof(message)
using namespace std;
struct message{
int from;
string msg;
};
void childCode(int *pipeOUT, int *pipeIN, message buffer){
// Local Buffer for input from pipeIN
cout << "Child: Sending Message"<< endl;
buffer.msg = "Child:I am the child!!";
write(pipeOUT[1],(char*) &buffer, BUFFER_LEN); // Test Child -> Parent comms
cout << "Child: Message Sent"<<endl;
read(pipeIN[0],(char*) &buffer,BUFFER_LEN); // Test Child <- Parent comms
cout << "Child: Recieved: "<< buffer.msg << endl;
cout << "Child Exiting..."<< endl;
exit(0); // Child process End
}
int main(int argCount, char** argVector){
pid_t pid;
int childPipeIN[2];
int childPipeOUT[2];
message buffer; // Buffer for reading from pipe
// Make Parent <- Child pipe
int ret = pipe(childPipeIN);
if (ret == -1){
perror("There was an error creating the childPipeIN. Exiting...");
exit(1);
}
// Make Parent -> Child pipe
ret = pipe(childPipeOUT);
if (ret == -1){
perror("There was an error creating the childPipeOUT. Exiting...");
exit(1);
}
// Fork off Child
pid = fork();
if (pid == -1){
perror("There has been an issue forking off the child. Exiting...");
exit(1);
}
if (pid == 0){ // Child code
cout << "Child PID = " << getpid() << endl;
childCode(childPipeIN,childPipeOUT,buffer);
}
else{ // Parent Code
cout << "Parent PID = " << getpid() << endl;
// Test Parent <- Child comms
read(childPipeIN[0], (char*) &buffer, BUFFER_LEN);
cout << "Parent: I recieved this from the child...\n" << buffer.msg << endl;
buffer.msg = "Parent: Got you message!";
// Test Parent -> Child comms
write(childPipeOUT[1], (char*) &buffer, BUFFER_LEN);
wait(null);
cout << "Parent: Children are done. Exiting..." << endl;
}
exit(0);
}
Yeah. I voted to close. Then I read Dupe more closely and realized it didn't explain the problem or the solution very well, and the solution didn't really fit with OP's intent.
The problem:
One does not simply write a std::string into a pipe. std::string is not a trivial piece of data. There are pointers there that do not sleep.
Come to think of it, it's bloody dangerous to write a std::string into anything. Including another std::string. I would not, could not with a file. This smurf is hard to rhyme, so I'll go no further with Dr. Seuss.
To another process, the pointer that references the storage containing the string's data, the magic that allows strings to be resizable, likely means absolutely nothing, and if it does mean something, you can bet it's not something you want to mess with because it certainly isn't the string's data.
Even in the same process in another std::string the two strings cannot peacefully co-exist pointing to the same memory. When one goes out of scope, resizes, or does practically anything else that mutates the string badness will ensue.
Don't believe me? Check BUFFER_LEN. No matter how big your message gets, BUFFER_LEN never changes.
This applies to everything you want to write that isn't a simple hunk of data. Integer, write away. Structure of integers and an array of characters of fixed size, write away. std::vector? No such luck. You can write std::vector::data if and only if whatever it contains is trivial.
std::is_pod may help you decide what you can and cannot read and write the easy way.
Solution:
Serialize the data. Establish a communications protocol that defines the format of the data, then use that protocol as the basis of your reading and writing code.
Typical solutions for moving a string are null terminating the buffer just like in the good ol' days of C and prepending the size of the string to the characters in the string like the good old days of Pascal.
I like the Pascal approach because it allows you to size the receiver's buffer ahead of time. With null termination you have to play a few dozen rounds of Getta-byte looking for the null terminator and hope your buffer's big enough or compound the ugliness with the dynamic allocation and copying that comes with buffer resizes.
Writing is pretty much what you are doing now, but structure member by structure member. In the above case
Write message.from to pipe.
Write length of message.msg to pipe.
Write message.msg.data() to pipe.
Two caveats:
Watch your endian! Firmly establish the byte order used by your protocol. If the native endian does not match the protocol endian, some bit shifting may be required to re-orient the message.
One man's int may be the size of another man's long so use fixed width integers.
Reading is a bit more complicated because a single call to read will return up to the requested length. It may take more than one read to get all the data you need, so you'll want a function that loops until all of the data arrives or cannot arrive because the pipe, file, socket, whatever is closed.
Loop on read until all of message.from has arrived.
Loop on read until all of the length of message.msg has arrived.
Use message.msg.resize(length) to size message.msg to hold the message.
Loop on read until all of message.msg has arrived. You can read the message directly into message.msg.data().

ReadProcessMemory() returns 0 for static addresses

What I try to do is to read a static address that's pointing to a dynamic adress that holds some value. But if I try to read the static address it always returns 0. The only way for it to be read is if I attach a debugger to the dynamic address in cheat engine. However I have no problem reading it with only reading from the dynamic address.
DWORD address = 0x74EA46D8;
int value = 0;
int new_address = 0;
DWORD pid;
HWND hwnd;
hwnd = FindWindow(NULL,L"HackMe.exe");
if(!hwnd) {
cout <<"Window not found!\n";
cin.get();
} else {
GetWindowThreadProcessId(hwnd,&pid);
HANDLE phandle = OpenProcess(PROCESS_VM_READ,0,pid);
if(!phandle) {
cout <<"Could not get handle!\n";
cin.get();
} else {
while(1) {
ReadProcessMemory(phandle,(void*)address,&new_address,sizeof(new_address),0);
cout << new_address << "\n"; //Always print 0
//int new_address = 0x2ECA40B0; //This works if I uncomment this
ReadProcessMemory(phandle,(void*)new_address,&value,sizeof(value),0);
I even tried getting debug privelege, but that didn't do anything. I have no clue on what the problem is since I'm very new to C++. Any help is appreciated.
Thank you.
Edit
GetLastError() returns 0 at first, then it returns 299
Edit 2
BOOL x = ReadProcessMemory(phandle,(void*)address,&new_address,sizeof(new_address),0);
cout << x << " " << GetLastError() << "\n";
returns
1 0
1 299
1 299
1 299
and so on
Edit 3
Bytes read is 4.
Edit 4
Just to clarify.
Reading directly from 0x74EA46D8 with ReadProcessMemory() returns 0.
If I open up cheat engine and add the address 0x74EA46D8 points to to the address list. Then right click on it and press "Find out what access this address" it can be read all of a sudden. Enabling SeDebugPrivelege does nothing.
The dynamic address can be read as normal, without having debug privelege(as long as I manually type the address for it or cheat engine debugs the address so the static address can be read)
It's structured in this way:
static address pointing to the address I try to read, this return 0 as the "new address" unless see above.
dynamic address, containing the value I'm trying to read. This reads just fine if I define the dynamic address manually. But if I don't it fails since new_address is 0, unless see above.
Edit 5
Finally I found out the problem, the previous address was wrong. That address was part of cheat engine and the real address was 0x013CD878 with an offset of 0x4B0. That was the reason why it didn't work unless I debugged it.
But I hope others will learn from my mistake :P
Aren't you reading from different addresses? address != new_address. (void*)address - is the address where you start reading from.

Distinguish if program runs by clicking on the icon, typing its name in the console, or from a batch file

The program I am writing is a simple console application that gets params, computes, and then returns data.
I am asking this because I am trying to implement a smart "press enter to exit" message that would run only if a console program is called by clicking on its icon in explorer. Without it, the result is that program only flashes for a split of second, but if a program is run from a context of already opened console then the same thing becomes an annoyance. Similar thing arises when program is run inside bat or cmd file, then pausing at the end is also unwelcome since bat files have 'pause' command that is supposed to do it.
So, we have 2 modes:
program says "press enter to exit" when is started by:
direct clicking in explorer
clicking on a shortcut
Simply exit when:
its name is typed in console
it is run from a bat/cmd file
it is run from another console application
Using Windows APIs:
You can use the GetConsoleProcessList API function (available on Windows XP/2003 and higher only). It returns a list of processes that are attached to the current console. When your program is launched in the "no console" mode, your program is the only process attached to the current console. When your program is launched from another process which already has a console, there will be more than one process attached to the current console.
In this case, we don't care about the list of process IDs returned by the function, we only care about the count that is returned.
Example program (I used Visual C++ with a Console Application template):
#include "stdafx.h"
#include <iostream>
#include <Windows.h>
using namespace std;
int _tmain(int argc, _TCHAR* argv[])
{
DWORD procIDs[2];
DWORD maxCount = 2;
DWORD result = GetConsoleProcessList((LPDWORD)procIDs, maxCount);
cout << "Number of processes listed: " << result << endl;
if (result == 1)
{
system("pause");
}
return 0;
}
We only need to list up to 2 processes, because we only care whether there is 1 or more than 1.
Using Windows APIs present in Windows 2000:
GetConsoleWindow returns the window handle of the console associated with the current process (if any). GetWindowThreadProcessId can tell you which process created a window. And finally, GetCurrentProcessId tells you the id of current process. You can make some useful deductions based on this information:
#include "stdafx.h"
#include <iostream>
#include <Windows.h>
using namespace std;
int _tmain(int argc, _TCHAR* argv[])
{
HWND consoleWindow = GetConsoleWindow();
if (consoleWindow != NULL)
{
DWORD windowCreatorProcessId;
GetWindowThreadProcessId(consoleWindow, &windowCreatorProcessId);
if (windowCreatorProcessId == GetCurrentProcessId())
{
cout << "Console window was created by this process." << endl;
system("pause");
}
else
cout << "Console window was not created by this process." << endl;
}
else
cout << "No console window is associated with this process." << endl;
return 0;
}
This technique seems slightly less precise than the first one, but I think in practice it should perform equally well.
The simplest solution I can think of is require the first parameter to be a flag whether or not the program should pause at the end. If the parameter is not there, i.e. it was started via explorer and the user did not have the ability to pass it in, then it should pause.
//Pseudo-code!!
int main(int argc, char** argv) {
//...
if(argv[1] == SHOULD_PAUSE) system("pause");
return 0;
}
There's a simple way to do this, and of course a more complicated way. The more complicated way may be more fun in the end, but probably more trouble than it's worth.
For the simple way, add a command line argument to the program, --pause-on-exit or something similar. Pass the extra arg whan calling it from a batch-file or the launcher icon. You could of course rather check for an environment variable for a similar effect.
For a more complicated (and automatic) way, you could probably try to find out who is the parent process of your application. You may have to go further up the chain than your immediate parent, and it may not work in all cases. I'd go for the command line argument.
Elaborating on my comment, rather than trying to tell how the program was executed (which I don't know is even possible, I'd assume there's no difference/distinction at all), I would implement a similar functionality in either one of two ways:
Add an extra argument to the program that will either make it "pause" at the end before terminating or not. ie. You could have something like -w to make it wait, or -W to make it not wait, and default with not waiting (or vice versa). You can add arguments through shortcuts.
Add a timer at the end of the program so that you wait for a few seconds, long enough for the user to read the input, so that the program doesn't wait infinitely when used in a batch.
Visual Studio introduces a wrinkle to #tcovo's otherwise valid answer when you are debugging. In this situation, it creates a second process and attaches it to the same console as the process you're running in:
So, it's necessary to detect the debugger using the Windows API function IsDebuggerPresent in order to get a definitive answer:
#include <iostream>
#include <Windows.h>
#include "debugapi.h"
int main()
{
DWORD pl[2];
auto np = GetConsoleProcessList(pl, 2);
std::cout << np << " processes\n";
bool shared;
if (IsDebuggerPresent())
shared = np > 2;
else
shared = np > 1;
std::cout << "Shared: ";
std::boolalpha(std::cout);
std::cout << shared << "\n";
std::cin.ignore(1);
return 0;
}
This only matters if you're using the local debugger; when run in a remote debugger there is still only one process attached.