Showing posts with label mmorpg. Show all posts
Showing posts with label mmorpg. Show all posts

Sunday, September 1, 2013

Memory Patching with OllyDbg + Source

Hello fellow programmers,

Today, I'll be showing you a rather interesting technique known as memory patching; this method is also used in game hacking to patch the anti-hack and to modify instructions. You will understand what I mean as we proceed through the tutorial.

In this tutorial, we will be hacking minesweeper. I know you'll be thinking hacking minesweeper is really low and useless but you see, minesweeper is just an example but you can use this technique to patch anti-hack on online games and hack online games. Useful technique, isn't it? Now, I want to open minesweeper in cheat engine and get the time address. I'll show you how to get the time address with screenshots; if you already know how to use cheat engine, then you can skip it.

1. Open minesweeper in cheatengine.
2. Enter '0' in the textbox and click 'New Scan'
3. Click on any of the boxes. You'll see the time incrementing by 1.
4. Change the cheat engine's scan type to 'Increased value' and click 'Next Scan'. What this does is that it will check which address' value has been increasing.
5. Keep clicking 'Next Scan', until you have isolated to one address, which, if you followed the instructions correctly, should be the time address. The value of the address should update real time.
6. Double click on the address. It will add it to the listbox at bottom. Now, right click and click 'Find out what writes to this address'. It should give you one assembly instruction. This is the instruction inside minesweeper that updates the time value by 1.

[Image: 6234421.bmp]

This is the instruction I recieved from cheat engine:
Code:
01002FF5 - FF 05 9C570001  - inc [0100579C]

Explanation: The instruction is located in memory address(01002FF5) and it is INC(assembly instruction for increment) the value inside the 100579C(time address).

The C/C++ equivalent:
Code:
(*timeAddress)++;

Now, open up OllyDbg and open Minesweeper in it. Winmine.exe is located in system32 folder inside Windows.

After Minesweeper is loaded onto ollydbg, press control + G. This will ask us where in the ollydbg do you want to go to. We want to go to this: 01002FF5, where our instruction is located.

[Image: 6234428.bmp]

Now, the dark bracket line that covers 9 lines, including our incrememnt instruction is a function minesweeper calls. That functions' purpose is to update the time. Now, I want the game to not execute the function. So, lets write a DLL that will NOP(Assembly instruction for no operation) the function. Lets see what's actually calling time update function. You can do that by clicking the first instruction of the function which is
Code:
01002FE0  /$ 833D 64510001 >CMP DWORD PTR DS:[1005164],0

If you click on it, olly will tell us what's calling this instruction. Here is an image to help you out:
[Image: 6234425.bmp]

It's a local call from 01001d6c. Lets press control + G and go there or you can right click on that string and click 'Go to CALL from 01001d6c'. Once you go there, you will notice something interesting, if you know Win32 programming. You'll see WM_TIMER. WM_TIMER is a message.

This is the instruction:
Code:
01001D6C  |. E8 6F120000    CALL winmine.01002FE0    ;  Case 113 (WM_TIMER) of switch 01001D5B

That instruction uses CALL(assembly instruction to call a funtion or address in the program) to call the time update function. Now, lets write the DLL to NOP the function. It's very simple. You'll need two functions: VirtualProtect and memcpy

The instruction is protected. It's only for us to read and understand the code and not to edit it as we wish. So we will use VirtualProtect function to edit the privilages to PAGE_EXECUTE_READWRITE which will let us not only read the memory but also write to it.

VirtualProtect asks for:
Code:
VirtualProtect(WhichAddress, Size, WhatTypeOfProtection, ActualProtection);

We will pass in 01001D6C for WhichAddress, and 5 bytes for the size, and PAGE_EXECUTE_READWRITE for WhatTypeOfProtection so that we can use memcpy to write to the address. For the last parameter, we will pass the address of a DWORD to store the actual protection so we can bring the address back to the way it was after we use it. With me so far?

This is what the code will look like:
Code:
    DWORD dwOld;
    VirtualProtect((LPVOID)WM_TIMER_ADDRESS, 5, PAGE_EXECUTE_READWRITE, &dwOld);

WM_TIMER_ADDRESS is a definition for our 01001D6C.

Now, we want to memcpy the NOP bytes to the address. Now how will we do that? Simple. Let's create a BYTE array.

Code:
BYTE nops[] = {0x90, 0x90, 0x90, 0x90, 0x90};

0x90 is the hex exquivalent of the NOP instruction.

Now, let's copy the nops and patch the memory!

Code:
memcpy((void *)WM_TIMER_ADDRESS, nops, 5);

Now, we have to set the original protection type back to the way it was.

Code:
    VirtualProtect((LPVOID)WM_TIMER_ADDRESS, 5, dwOld, &dwOld);

I made a function called patch() to make it easier to understand.

Here is the full code:
Code:
#include <windows.h>

#define WM_TIMER_ADDRESS 0x01001D6C

BYTE nop[5] = {0x90, 0x90, 0x90, 0x90, 0x90};

void patch()
{
    DWORD dwOld;
    VirtualProtect((LPVOID)WM_TIMER_ADDRESS, 5, PAGE_EXECUTE_READWRITE, &dwOld);
    memcpy((void *)WM_TIMER_ADDRESS, nop, 5);
    VirtualProtect((LPVOID)WM_TIMER_ADDRESS, 5, dwOld, &dwOld);
}

BOOL WINAPI DllMain(HINSTANCE hinstDLL, DWORD dwReason, LPVOID lpReserved)
{
    if(dwReason == DLL_PROCESS_ATTACH)
    {
        MessageBox(NULL, "Injected to Process!", "Injected!", MB_OK);
        patch();
    }
    return true;
}

Now, let's inject the DLL into Minesweeper and attach OllyDbg to it. After doing so, go the WM_TIMER call.

Before injection:
[Image: 6234420.bmp]

After injection:
[Image: 6234419.bmp]

W00t! w00t! Notice how the 5 nops were copied on to the address, essentially, cancelling the call to the timer update. Of course, there are different methods of stopping time. You can create a while loop which will always set the time address(0x0100579c) to zero.

Here is the source for it:
Code:
#include <windows.h>

void timezero()
{
    while(1)
    {
        __asm
        {
            mov eax, 0x0100579c
            mov [eax], 0
        }
    }
}

BOOL WINAPI DllMain(HINSTANCE hinstDLL, DWORD dwReason, LPVOID lpReserved)
{
    if(dwReason == DLL_PROCESS_ATTACH)
    {
        MessageBox(NULL, "Injected to Process!", "Injected!", MB_OK);
        timezero();
    }
    return true;
}

This is a basic hack for a basic game but this technique can be used for other complex games. For example, I'm using this technique to patch XTrap(an anti-cheat program). Basically, step through the code and check for traces of XTrap activity and NOP it or use unconditional jumps. Online games load XTrap through a DLL using LoadLibrary by CALL'ing it from kernel32.dll. You can, of course, NOP the entire LoadLibrary call which, basically, prevents Xtrap.dll from loading.

If you have any questions or suggestions, don't hesitate to reply. You can private message for questions or add my MSN(PM for it).

Hope you learned something.

Saturday, August 31, 2013

-DLL Injection Source + Tutorial

Hello,

Full source present below. I am Sri Krishna. I have already posted this tutorial long back in Hackforums. I thought it would be nice to share it here.

Here is a quick explanation of how DLL injection works. The concept is very simple. This encompasses a lot of very useful functions. Very good knowledge.

DLL injection is not really injecting the DLL but to load the DLL inside the targeted process. The function that is used to load a DLL is [a href="http://msdn.microsoft.com/en-us/library/ms684175(v=vs.85).aspx"]LoadLibrary[/a]. LoadLibrary takes one argument which is the path of the DLL. We pretty much know how to load a DLL. Now, we need to understand how to make the targeted process load our DLL.

Let's look at it in this perspective: If you want to load a DLL in general, you would call LoadLibrary(DLL_PATH);, however, if you want to LoadLibrary(DLL_NAME); inside a process, you would have to execute that function inside the targeted process, correct? Well, Windows has provided us with useful functions that can help us perform this task. The functions we will be using are OpenProcess, VirtualAllocEx, WriteProcessMemory, and CreateRemoteThread.

We'll be using OpenProcess to open the target process. The information required to open the process is the Process ID(or PID). I suggest you look at the MSDN documentation for more information.

Here is what OpenProcess is asking:
OpenProcess(HowToOpen, InheritEverything(BOOL), Process ID);

Here is the actual code:
int ProcessID;

std::cin >> ProcessID;

HANDLE hProcess; //This will contain the handle to the process.

hProcess = OpenProcess(PROCESS_ALL_ACCESS, false, ProcessID);



Now, hProcess contains the handle to the process, if OpenProcess doesn't return NULL. If OpenProcess returned NULL, then it failed. You can use [url=http://msdn.microsoft.com/en-us/library/ms679360(v=VS.85).aspx]GetLastError()[/url] function to get details of the failure.

if(hProcess == NULL)

 std::cout << "OpenProcess: " << GetLastError();

else

 //continue



Now, we need to allocate some memory in the targeted process for DLL path so we can pass it to LoadLibrary. We can do this by using VirtualAllocEx.

VirtualAllocEx might sound complicated but the arguments it takes are easy to understand and is perfect for this task. It's similar to malloc or new in C and C++, respectively. malloc/new only works in the process you are working with but with VirtualAllocEx you can "malloc" inside a target process!

What VirtualAllocEx is asking for:

VirtualAllocEx(HandleToTheProcess, WhereDoYouWantToAllocate, HowMuchDoYouWantToAllocate, AllocationType, ProtectionType);



That's essentially what it is asking us for. Now, lets follow along and legitimately fill in the arguments. Please, look up the MSDN Documention for MEM_RESERVE, MEM_COMMIT and PAGE_READWRITE for more information.

LPVOID vAlloc; //Stores our base address where the allocation occured.

vAlloc = VirtualAllocEx(hProcess, NULL, strlen(DLL_PATH) + 1, MEM_COMMIT | MEM_RESERVE, PAGE_READWRITE);

/*NULL in the second parameter lets the function choose where to allocate memory. We want to allocate

the string length of DLL path, so we can write to it. It's strlen(DLL_PATH) +1 because of the null-terminator. Thanks to PoZHx for reminding me! :)*/



If the function suceeded, vAlloc will contain the base address where the allocation occured. If it failed, it will return NULL. Of course, you can use GetLastError to get more information about why the function failed.

Now, we will write the DLL path in the allocated memory. Now, where in memory region was the memory allocated? Well, vAlloc contains the base address of our memory, so we'll just use that to write our DLL path to. We can do this by using WriteProcessMemory.

This is what WriteProcessMemory is asking:

WriteProcessMemory(WhichProcess, WhereInMemory, WhatToWrite, HowLongIsTheData, HowMuchDidIWrite); //the last parameter is not really needed



Now, lets write the actual code for the task:

WriteProcessMemory(hProcess, vAlloc, DLL_PATH, strlen(DLL_PATH), NULL); //this will pretty much write the DLL path to the process.



If the function suceeded, it will return a non-zero integer. Of course, you can use GetLastError if it returned NULL.

Now, that we have everything up and ready for us to execute our LoadLibrary function inside the process, lets execute it!

We'll need CreateRemoteThread function to create a seperate thread for our LoadLibrary while not pausing the main process thread. CreateRemoteThread is similar to CreateThread except CreateRemoteThread takes one extra parameter which is the handle to the process(I'm sure you guessed it!). We'll pass in our hProcess for that parameter.

What CreateRemoteThread is asking:

CreateRemoteThread(HandleToProcess, ThreadAttributes, StackSize, FunctionToExecute, ParametersToFunction, Flags, ThreadID);

/*For this task, we'll only worry about HandleToProcess, FunctionToExecute, and ParametersToFunction because that's all we need

to execute our thread in the targeted process*/



Now, lets write the actual code for this task:

CreateRemoteThread(hProcess, NULL, NULL, (LPTHREAD_START_ROUTINE)LoadLibraryA, vAlloc, NULL, NULL);



If the function failed, it will return NULL. Of course, you can check GetLastError() ;).

However, there are times, rarely, when this function will fail. It's probably because the kernel32.dll is not loaded in the process. This is a problem because kernel32.dll is DLL that provides us the function LoadLibrary. There is a way to fix this problem. You can use [url=http://msdn.microsoft.com/en-us/library/ms683212%28v=VS.85%29.aspx]GetProcAddress[/url] to get the address of LoadLibrary inside kernel32.dll and we can just call the address.

Here is what GetProcAddress is asking for:

GetProcAddress(HandleToTheModuleWhereTheFunctionIsLocated, FunctionName);



Now, lets write the actual code:

LPVOID pAddr; //This will contain the address of LoadLibrary, if suceeded.

pAddr = GetProcAddress(GetModuleHandle("kernel32.dll"), "LoadLibraryA");



If suceeded, pAddr will contain the address to LoadLibraryA. If it didn't suceed, it will return NULL and we can use GetLastError ;) Now, lets use this address and pass it to CreateRemoteThread.


CreateRemoteThread(hProcess, NULL, NULL, (LPTHREAD_START_ROUTINE)pAddr, vAlloc, NULL, NULL);



After you finish creating the remote thread. Make sure to free the memory we have allocated using [url=http://msdn.microsoft.com/en-us/library/aa366894(v=vs.85).aspx]VirtualFreeEx[/url] and make sure to close the handle we have opened using OpenProcess using [url=http://msdn.microsoft.com/en-us/library/ms724211(v=VS.85).aspx]CloseHandle[/url].

Please check the MSDN documentation for more information. VirtualFreeEx is similar to free and delete in C and C++, respectively.

VirtualFreeEx(hProcess, vAlloc, NULL, MEM_RELEASE); //Must call this before closing handle.

CloseHandle(hProcess);



That's basically it! Now, you should, unless you don't speak English, understand how DLL injection works.

Here is the entire source of what we discussed; I added some error checking to help us out:
[url=http://pastebin.com/7AgCZAfx]DLL Injecton[/url]

Here is a source of a DLL to test if the Injector is working:

#include <windows.h>



BOOL WINAPI DllMain(HINSTANCE hinstDLL, DWORD dwReason, LPVOID lpReserved)

{

 if(dwReason == DLL_PROCESS_ATTACH)

  MessageBox(NULL, "Injected to process!", "Injected!", MB_OK);

 return true;

}



Here is an advanced version of DLL Injector. It opens up a file dialog box and it also lists the process with process IDs: http://pastebin.com/pC8JDVvV

Hope you learned something... Sri Krishna. Please, give me some feedback.