Cheat Engine Forum Index Cheat Engine
The Official Site of Cheat Engine
 
 FAQFAQ   SearchSearch   MemberlistMemberlist   UsergroupsUsergroups   RegisterRegister 
 ProfileProfile   Log in to check your private messagesLog in to check your private messages   Log inLog in 


(C++) I need help with WriteProcessMemory!

 
Post new topic   Reply to topic    Cheat Engine Forum Index -> General programming
View previous topic :: View next topic  
Author Message
DaviFN
Cheater
Reputation: 0

Joined: 23 Oct 2016
Posts: 32

PostPosted: Sun Oct 23, 2016 5:13 pm    Post subject: (C++) I need help with WriteProcessMemory! Reply with quote

Hello everyone!

I have a huge problem. When I use WriteProcessMemory on Windows XP, everything goes fine; all processes are affected by this WPM function.

However, while trying to use WPM in Windows 7, it turns out that some processes won't be affected by it. I mean, even executing my C++ program as admin the function fails. GetLastError() says "5", which stands for "Access Denied".

Here is my problem: I don't understand much of programming. I code for hobby. The only thing I want to do is to use WPM and RPM (yes, RPM doesn't work too) in Windows 7. Here is the thing: I used Cheat Engine in order to verify if it could write/read to/from memory, and it couldn't. Memory Editor just had ?? in it. But then, after googling a little bit, I was able to make it work: I went to Settings>Extra and enabled some Kernel mode, for OpenProcess and WPM/RPM.

I wonder if I can do my C++ code to use the same strategy CE does. I need some code example of using the same Kernel WPM and RPM that CE does, but in C++.



More details:

English is not my 1st language, but I think I can be understood well enough.

Googling a little bit, it seems like CE uses a DLL or a SYS file (I don't understand anything about it) which contains the Kernel WPM/RPM, so maybe my solution can be associated with using this DLL/SYS in my C++ code, though I don't know how.

I've tried to enable a lot of privilege things, without success.


My code so far: (You can laugh if you want to, as I said, this is a hobby. And the code is all mixed, I will organize it later, when RPM and WPM work)

Code:
#include <cstdio>
#include <windows.h>
#include <tlhelp32.h>
int newdata;
DWORD newdatasize;


void enableDebugPrivileges() { 
    HANDLE hcurrent=GetCurrentProcess(); 
    HANDLE hToken; 
    BOOL bret=OpenProcessToken(hcurrent,40,&hToken); 
    LUID luid; 
    bret=LookupPrivilegeValue(NULL,"SeDebugPrivilege",&luid); 
    TOKEN_PRIVILEGES NewState,PreviousState; 
    DWORD ReturnLength; 
    NewState.PrivilegeCount =1; 
    NewState.Privileges[0].Luid =luid; 
    NewState.Privileges[0].Attributes=2; 
    AdjustTokenPrivileges(hToken,FALSE,&NewState,28,&PreviousState,&ReturnLength); 
}


BOOL SetProcessEditPriv(LPCSTR Priv, HANDLE pHandle)
{
   HANDLE hToken;
   LUID luid;
   TOKEN_PRIVILEGES Privs;
   ZeroMemory (&Privs, sizeof(Privs));
   if (!OpenProcessToken (pHandle, (TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY),
      &hToken))
   {
      printf("No se pudieron modificar los privilegios");
      return FALSE;
   }
   if (!LookupPrivilegeValue (NULL, Priv, &luid))
   {
      CloseHandle (hToken);
      return FALSE;
   }

   Privs.PrivilegeCount = 1;
   Privs.Privileges[0].Luid = luid;
   Privs.Privileges[0].Attributes = SE_PRIVILEGE_ENABLED;

   BOOL retValue = AdjustTokenPrivileges(hToken, FALSE,
      &Privs, sizeof(Privs),NULL,NULL);
   CloseHandle(hToken);
   return retValue;

}




void EnableDebugPriv()
{
    HANDLE hToken;
    LUID luid;
    TOKEN_PRIVILEGES tkp;

    OpenProcessToken(GetCurrentProcess(), TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, &hToken);

    LookupPrivilegeValue(NULL, SE_DEBUG_NAME, &luid);

    tkp.PrivilegeCount = 1;
    tkp.Privileges[0].Luid = luid;
    tkp.Privileges[0].Attributes = SE_PRIVILEGE_ENABLED;

    AdjustTokenPrivileges(hToken, false, &tkp, sizeof(tkp), NULL, NULL);

    CloseHandle(hToken);
}

int main( int, char *[] )
{
    //EnableDebugPriv();
enableDebugPrivileges();

    PROCESSENTRY32 entry;
    entry.dwSize = sizeof(PROCESSENTRY32);

    HANDLE snapshot = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, NULL);

    if (Process32First(snapshot, &entry) == TRUE)
    {
        while (Process32Next(snapshot, &entry) == TRUE)
        {
            if (stricmp(entry.szExeFile, "notepad.exe") == 0)
            { 
                HANDLE hProcess = OpenProcess(PROCESS_VM_WRITE|PROCESS_VM_READ , FALSE, entry.th32ProcessID);

               if(hProcess)
               { printf("Process was found succesfully");
               
               
               //SetProcessEditPriv(SE_DEBUG_NAME,hProcess);
               
               
               
               BYTE BufferOut = 0x00;
   int BufferSize = sizeof(BufferOut);
   int BufferIn;
   SIZE_T bWritten;
   DWORD OldProtection = -1;
   MEMORY_BASIC_INFORMATION mbi;
             // if (!VirtualProtectEx (hProcess, (LPVOID)0x0001000C, BufferSize, PAGE_EXECUTE_READWRITE, &OldProtection))
    //  printf("\n\nNo se han podido modificar los permisos de memoria. Error %d\n\n",GetLastError());
               BYTE bP = 0x00;
               if (ReadProcessMemory(hProcess, (LPVOID)0x0001000C, &bP, sizeof(BYTE), NULL))
{printf("\n\nLeitura feita. Resposta: %d",BufferOut);}else{printf("\n\nLeitura falhou. LastError:%d",GetLastError());}
               
               
               newdata = 30;
               newdatasize = sizeof(newdata);
               
               
               
               
               if(WriteProcessMemory(hProcess, (LPVOID)0x0001000C, &bP, sizeof(BYTE), NULL))
         {
                    printf("\n\nMemory written succesfully.\n\n");
               }
               else{printf("Erro ao manipular memoria! Codigo do erro: %d",GetLastError());}
               }





                CloseHandle(hProcess);
            }
        }
    }

    CloseHandle(snapshot);


system("pause>nul");


    return 0;
}


How to "translate" this code, more specifically the WPM and RPM parts of it, to the strategy Cheat Engine uses in its Kernel (Settings>Extra)?

Any tips are welcome. Thanks.
Back to top
View user's profile Send private message
ParkourPenguin
I post too much
Reputation: 140

Joined: 06 Jul 2014
Posts: 4300

PostPosted: Sun Oct 23, 2016 5:41 pm    Post subject: Reply with quote

Do you have any antivirus programs installed or anything similar that could be interfering? What sort of programs are you targeting?
_________________
I don't know where I'm going, but I'll figure it out when I get there.
Back to top
View user's profile Send private message
DaviFN
Cheater
Reputation: 0

Joined: 23 Oct 2016
Posts: 32

PostPosted: Sun Oct 23, 2016 5:53 pm    Post subject: Reply with quote

I have Avast in both Win XP and 7, but I disabled them while executing my C++ program.

I'm attempting to target a game. It can be targeted in WinXP, but not in 7.

The game doesn't have any kind of anticheat. The problem persists even with other processes, such as Chrome.
Back to top
View user's profile Send private message
Astaroth4256
Advanced Cheater
Reputation: 0

Joined: 25 May 2014
Posts: 59

PostPosted: Sun Oct 23, 2016 7:05 pm    Post subject: Reply with quote

Code:
pHandle = OpenProcess(PROCESS_ALL_ACCESS, FALSE, PID);

I'm not sure if this will work, but worth trying, works for me on win7
Back to top
View user's profile Send private message
DaviFN
Cheater
Reputation: 0

Joined: 23 Oct 2016
Posts: 32

PostPosted: Sun Oct 23, 2016 7:32 pm    Post subject: Reply with quote

Had already tried the PROCESS_ALL_ACCESS. Changes nothing.

I am currently trying to use the WPM function inside the dbk32.dll of the Cheat Engine, but my program fails in the "if(func(hProcess, (LPVOID)0x0001000C, &bP, sizeof(BYTE), NULL))" part. I feel I'm close, just need a little bit of help. How can I use the WPM properly? Is it the way? Thanks (BTW, I'm using the dbk32.dll and dbk32.sys from CE 5.6.1)

Current code:

Code:
#include <cstdio>
#include <windows.h>
#include <tlhelp32.h>
#include <stdio.h>
#include <objidl.h>
#pragma comment(lib, "user32.lib")
int newdata;
DWORD newdatasize;

typedef unsigned int(WINAPI* AvVersion)(HANDLE  hProcess,LPVOID  lpBaseAddress,LPCVOID lpBuffer,SIZE_T  nSize,SIZE_T  *lpNumberOfBytesWritten);

void enableDebugPrivileges() { 
    HANDLE hcurrent=GetCurrentProcess(); 
    HANDLE hToken; 
    BOOL bret=OpenProcessToken(hcurrent,40,&hToken); 
    LUID luid; 
    bret=LookupPrivilegeValue(NULL,"SeDebugPrivilege",&luid); 
    TOKEN_PRIVILEGES NewState,PreviousState; 
    DWORD ReturnLength; 
    NewState.PrivilegeCount =1; 
    NewState.Privileges[0].Luid =luid; 
    NewState.Privileges[0].Attributes=2; 
    AdjustTokenPrivileges(hToken,FALSE,&NewState,28,&PreviousState,&ReturnLength); 
}


BOOL SetProcessEditPriv(LPCSTR Priv, HANDLE pHandle)
{
   HANDLE hToken;
   LUID luid;
   TOKEN_PRIVILEGES Privs;
   ZeroMemory (&Privs, sizeof(Privs));
   if (!OpenProcessToken (pHandle, (TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY),
      &hToken))
   {
      printf("No se pudieron modificar los privilegios");
      return FALSE;
   }
   if (!LookupPrivilegeValue (NULL, Priv, &luid))
   {
      CloseHandle (hToken);
      return FALSE;
   }

   Privs.PrivilegeCount = 1;
   Privs.Privileges[0].Luid = luid;
   Privs.Privileges[0].Attributes = SE_PRIVILEGE_ENABLED;

   BOOL retValue = AdjustTokenPrivileges(hToken, FALSE,
      &Privs, sizeof(Privs),NULL,NULL);
   CloseHandle(hToken);
   return retValue;

}




void EnableDebugPriv()
{
    HANDLE hToken;
    LUID luid;
    TOKEN_PRIVILEGES tkp;

    OpenProcessToken(GetCurrentProcess(), TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, &hToken);

    LookupPrivilegeValue(NULL, SE_DEBUG_NAME, &luid);

    tkp.PrivilegeCount = 1;
    tkp.Privileges[0].Luid = luid;
    tkp.Privileges[0].Attributes = SE_PRIVILEGE_ENABLED;

    AdjustTokenPrivileges(hToken, false, &tkp, sizeof(tkp), NULL, NULL);

    CloseHandle(hToken);
}

int main( int, char *[] )
{
   
   



unsigned long PID; // We need this now to store the PID.
HANDLE hProcess; //We will use this for OpenProcess
HINSTANCE hDllTrainer;
BOOL fFreeResult, fRunTimeLinkSuccess = FALSE;
HWND hWindow = FindWindow(NULL, "Minesweeper");
GetWindowThreadProcessId(hWindow, &PID);
DWORD ToBeWritten[]={0x90};
DWORD Newdatasize = sizeof(ToBeWritten);

hDllTrainer = LoadLibrary("dbk32.dll");
if(hDllTrainer != NULL) {
 
   }
   else if(!hDllTrainer) {
   MessageBoxA(0, "Error! Couldnt Load TrainerCalls.dll! Quiting.", "ERROR!", MB_ICONINFORMATION);
}
   
AvVersion func=(AvVersion)GetProcAddress(hDllTrainer,"WPM");
    if(func==NULL){MessageBox(NULL,"func=null","",MB_OK);}
   
   
    //EnableDebugPriv();
enableDebugPrivileges();

    PROCESSENTRY32 entry;
    entry.dwSize = sizeof(PROCESSENTRY32);

    HANDLE snapshot = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, NULL);

    if (Process32First(snapshot, &entry) == TRUE)
    {
        while (Process32Next(snapshot, &entry) == TRUE)
        {
            if (stricmp(entry.szExeFile, "notepad.exe") == 0)
            { 
                HANDLE hProcess = OpenProcess(PROCESS_VM_READ | PROCESS_VM_WRITE | PROCESS_VM_OPERATION | PROCESS_QUERY_INFORMATION, FALSE, entry.th32ProcessID);

               if(hProcess)
               { printf("Process was found succesfully");
               
                SetProcessEditPriv(SE_DEBUG_NAME,hProcess);
               
               VirtualProtectEx(hProcess,(LPVOID)0x0001000C,256,PAGE_EXECUTE_READWRITE, NULL);
             
               
               
               
               BYTE BufferOut = 0x00;
   int BufferSize = sizeof(BufferOut);
   int BufferIn;
   SIZE_T bWritten;
   DWORD OldProtection = -1;
   MEMORY_BASIC_INFORMATION mbi;
             // if (!VirtualProtectEx (hProcess, (LPVOID)0x0001000C, BufferSize, PAGE_EXECUTE_READWRITE, &OldProtection))
    //  printf("\n\nNo se han podido modificar los permisos de memoria. Error %d\n\n",GetLastError());
               BYTE bP = 0x00;
               if (ReadProcessMemory(hProcess, (LPVOID)0x0001000C, &bP, sizeof(BYTE), NULL))
{printf("\n\nLeitura feita. Resposta: %d",BufferOut);}else{printf("\n\nLeitura falhou. LastError:%d",GetLastError());}
               
               
               newdata = 30;
               newdatasize = sizeof(newdata);
               
               
               
               
               
               if(func(hProcess, (LPVOID)0x0001000C, &bP, sizeof(BYTE), NULL))
         {
                    printf("\n\nMemory written succesfully.\n\n");
               }
               else{printf("Erro ao manipular memoria! Codigo do erro: %d",GetLastError());}
               }





                CloseHandle(hProcess);
            }
        }
    }

    CloseHandle(snapshot);


system("pause>nul");


    return 0;
}
Back to top
View user's profile Send private message
DaviFN
Cheater
Reputation: 0

Joined: 23 Oct 2016
Posts: 32

PostPosted: Mon Oct 24, 2016 8:41 am    Post subject: Reply with quote

I have a subproblem now: How to make that WPM function (which I think I'm calling from the dbk32.dll from CE 5.6.1) work within the C++ code?

The above code crashes in the WPM function (which, in code, is called by "func"). I'm a total newbie, I know I should study the basics but the only thing I need is to call that WPM properly. (Actually I need to use the same WriteProcessMemory() Cheat Engine does in that Kernel option)

I'm almost sure I'm calling the function wrongly. I'm googling everywhere trying to find a way to make it work, but no success.

Need your help.
Back to top
View user's profile Send private message
ParkourPenguin
I post too much
Reputation: 140

Joined: 06 Jul 2014
Posts: 4300

PostPosted: Mon Oct 24, 2016 8:52 am    Post subject: Reply with quote

You should be able to use the standard WPM function on its own just fine. If you can't, something else on your computer is interfering. I doubt "disabling" Avast will disable everything.

If you want to ignore that, however, CE's source code is available here. And use the latest version of software unless you have a reason not to.

_________________
I don't know where I'm going, but I'll figure it out when I get there.
Back to top
View user's profile Send private message
DaviFN
Cheater
Reputation: 0

Joined: 23 Oct 2016
Posts: 32

PostPosted: Mon Oct 24, 2016 9:46 am    Post subject: Reply with quote

I can't understand the Cheat Engine's source code...

And the only thing that can edit the process I'm attempting to target is Kernel mode of Cheat Engine. I want my C++ program to edit the memory of the process I'm attempting to use WriteProcessMemory.

Can someone gimme a code example of how to properly call the WPM function from the dbk32.dll, like Cheat Engine 5.6.1 does?

Thank you.


(By the way, the reason by which I'm not using the latest version of CE is that it doesn't have the dbk32.dll. I don't care about what version to use, the only thing I care is how to edit the memory of the process like Cheat Engine's Kernel mode does)
Back to top
View user's profile Send private message
Entelodon
How do I cheat?
Reputation: 0

Joined: 28 Oct 2016
Posts: 2

PostPosted: Fri Oct 28, 2016 10:05 pm    Post subject: Reply with quote

Hey man, I am making something similar to your code. So.. Look at mine.. Maybe it will help you.. Rolling Eyes Rolling Eyes
Code:
#include "stdafx.h"
#include <Windows.h>
#include <iostream>
using namespace std;
//#define _WIN32_WINNT 0x050
boolean keya = false;
float value = 0;
float nvalue = 9000;
DWORD address = 0x00000000;
LRESULT CALLBACK LowLevelKeyboardProc(int nCode, WPARAM wParam, LPARAM lParam)
{
   BOOL fEatKeystroke = FALSE;

   if (nCode == HC_ACTION)
   {
      switch (wParam)
      {
      case WM_KEYDOWN:
      case WM_SYSKEYDOWN:
      case WM_KEYUP:
      case WM_SYSKEYUP:
         PKBDLLHOOKSTRUCT p = (PKBDLLHOOKSTRUCT)lParam;
         if (fEatKeystroke = (p->vkCode == 0x14)) {
            DWORD pid;
            HWND hwnd;
            hwnd = FindWindow(NULL, L"League of Legends (TM) Client");
            if (!hwnd)
            {
               cout << "Window not found!\n";
               cin.get();
               break;
            }
            else
            {
               GetWindowThreadProcessId(hwnd, &pid);
               HANDLE phandle = OpenProcess(PROCESS_ALL_ACCESS, 0, pid);
               if (!phandle)
               {
                  cout << "Could not get handle!\n";
                  cin.get();
                  break;
               }
               else
               {
                  if ((wParam == WM_KEYDOWN && !keya) || (wParam == WM_SYSKEYDOWN && !keya)) // Keydown
                  {
                     ReadProcessMemory(phandle, (LPVOID)address, &value, (DWORD)sizeof(value), 0);
                     int ifs = WriteProcessMemory(phandle, (LPVOID)address, &nvalue, (DWORD)sizeof(nvalue), 0);
                     if (ifs > 0) {
                        cout << "[ZOOM OUT]\n";
                     }
                     keya = true;
                  }
                  else if ((wParam == WM_KEYUP) || (wParam == WM_SYSKEYUP)) // Keyup
                  {
                     int ifs = WriteProcessMemory(phandle, (LPVOID)address, &value, (DWORD)sizeof(value), 0);
                     cout << "[ZOOM IN]\n";
                     keya = false;
                  }
                  break;
               }
            }
         }
         break;
      }
   }
   return(fEatKeystroke ? 1 : CallNextHookEx(NULL, nCode, wParam, lParam));
}

int main()
{
   cin >> hex >> address;
   // Install the low-level keyboard & mouse hooks
   HHOOK hhkLowLevelKybd = SetWindowsHookEx(WH_KEYBOARD_LL, LowLevelKeyboardProc, 0, 0);

   // Keep this app running until we're told to stop
   MSG msg;
   while (!GetMessage(&msg, NULL, NULL, NULL)) {    //this while loop keeps the hook
      TranslateMessage(&msg);
      DispatchMessage(&msg);
   }

   UnhookWindowsHookEx(hhkLowLevelKybd);

   return 0;
}
Back to top
View user's profile Send private message
Display posts from previous:   
Post new topic   Reply to topic    Cheat Engine Forum Index -> General programming All times are GMT - 6 Hours
Page 1 of 1

 
Jump to:  
You cannot post new topics in this forum
You cannot reply to topics in this forum
You cannot edit your posts in this forum
You cannot delete your posts in this forum
You cannot vote in polls in this forum
You cannot attach files in this forum
You can download files in this forum


Powered by phpBB © 2001, 2005 phpBB Group

CE Wiki   IRC (#CEF)   Twitter
Third party websites