Log in

View Full Version : detecting or preventing patching in memory (code and data)


Paradigm
April 10th, 2013, 11:23
hi this is my first post here, nice community
I'm currently trying to make an anticheat program for a game. basically what I have done is just placing hooks in some winAPI functions.
I'm not very experienced with a lot of things, but I have no inconvenient in developing it slowly, because by the way I will be learning anyway. What I would like to know, is if anybody can tell me about what the topic's title says, and it is about how to prevent a hack program from patching my memory or the game's memory. Consider this, my anticheat program will be injected into the game as a module, for example "myanticheat.dll". from there I want to prevent any hack program from patching in the game's code and data sections.
I really don't know if this has to do with sections access permissions or if it has to do with memory read/writing permissions, I really don't have much idea, but I would like if anybody can tell me a bit about all this. I would really appreciate it, since as you see I am dedicating some time to this program.

Indy
April 10th, 2013, 11:59
nya ("http://www.woodmann.com/forum/showthread.php?14987-Defeating-Memory-Breakpoints&p=93671&highlight=#post93671")

rendari
April 10th, 2013, 15:10
Quote:
[Originally Posted by Indy;94499]nya ("http://www.woodmann.com/forum/showthread.php?14987-Defeating-Memory-Breakpoints&p=93671&highlight=#post93671")


This is good for protecting the image. But for games the game memory being patched is usually in the heap or allocated memory.

I am also writing an anticheat for a friend's game that is being hacked excessively. So far I think the only way to consistently prevent Read/WriteProcessMemory from working is to code a driver. It's a tough problem, if anyone has any suggestions I would be open to them.

Indy
April 10th, 2013, 19:28
Private memory(R|E, heap etc) can be protected ^.

You can always change memory. For example from the kernel.

Quote:
So far I think the only way to consistently prevent Read/WriteProcessMemory from working is to code a driver. It's a tough problem


Block manipulation the process handle(NtOpenProcess/NtDuplicateObject and lower).

Against scrap no way .. if no other scrap.

Discussed on rk:
Quote:
Интересует механизм защиты проекций модулей от негодных патчей. В общем для юзермода механизм такой:

1. В проекцию выполняется запись, это настройка IAT и релоков.
2. Запись должна выполняться исключительно загрузчиком.
3. В следствии этого можно поступить следующими путями:
3.1 - Перенести загрузчик в ядро.
3.2 - Разрешать запись только из лодера.
4. Сторонний код не должен получить W доступ к проекции.
4.1 - В ядре возможно получение W доступа, это можно обойти эмулируя запись в проекцию загрузчиком.
4.2 - Проекция должна иметь доступ NOACCESS, для блокирования записи из юзермода сторонним кодом.

5. Обрабатываем NtMapViewOfSection() - проецируем файловую проекцию разделяемой(SHARED) с доступом RE для кодосекций и блокируя её(VAD.SecNoChange & NoChange), отображаем образ второй раз доступом RW.
6. Обрабатываем NtProtectVirtualMemory() для проекции, возвращая STATUS_SUCCESS.
7. Отслеживаем запись в проекцию, установив ловушку.
8. При срабатывании ловушки проверяем расположение кода, который пишет в проекцию. Если это не загрузчик, то блокируем запись.
8.1 Определить загрузчик можно по колстеку - вызов должен быть из:

- LdrpWalkImportDescriptor() и LdrRelocateImage() при инициализации процесса.
- LdrpWalkImportDescriptor() из LdrpLoadDll().
- AVrfDllLoadNotification() и AVrfInitializeVerifier().

8.2 Код, вызываемый при нотификациях не является загрузчиком. В колстеке не должно быть адресов за пределами ntdll.

9. При срабатывании ловушки эмулируем запись, это можно сделать следующими способами:
9.1 - Определить адрес, куда выполняется запись, размер записываемых данных и источник данных. Для определения источника необходим дизассемблер.
9.2 - Смещаем сегмент, чтобы доступ произошёл к RW копии проекции(LDT, IDP).

10 Вторую проекцию анмапим при возврате из LdrpSetProtection(), также возможна дополнительная обработка протекций.
(11 Обрабатываем NtUnmapViewOfSection() ?)

Paradigm
April 11th, 2013, 11:27
looks like you are trying to prevent some external programs from having access to the game's process. In that case you can try to hook LdrLoadDll, or if you already have a driver you can block other processes from using some low level functions over your game (kernelmode hook?).
http://undocumented.ntinternals.net/UserMode/Undocumented%20Functions/Executable%20Images/LdrLoadDll.html
I don't have a driver, I don't want to use that atm. I would prefer to make this in usermode for now.
As I saw that always hackers manage to load a dll and make it invisible, I would like to establish a detection that will tell me if anything has modified the memory, code section, for example game.exe.

EDIT (google translation):
Quote:

Interested in the protection mechanism of projection modules from unfit patches. In general, for yuzermoda mechanism is as follows:

1. In the projection is being recorded, it is setting IAT and relocations.
2. The recording must be done exclusively by the loader.
3. In consequence we can proceed in the following ways:
3.1 - Move the loader to the kernel.
3.2 - Allow only record of Loder.
4. Third-party code should not get access to the W projection.
4.1 - In the nucleus may receive W access, it is possible to bypass emulating record projection loader.
4.2 - The projection should have access NOACCESS, to block the entry of yuzermoda party code.

5. Process NtMapViewOfSection () - projecting projection file shared (SHARED) with access to RE kodosektsy and blocking it (VAD.SecNoChange & NoChange), display the image a second time access RW.
6. Process NtProtectVirtualMemory () for the projection, returning STATUS_SUCCESS.
7. Track record in the projection, by setting a trap.
8. When triggered, check the location of the trap code that writes to the projection. If it does not boot, then lock the record.
8.1 Identify the loader can be kolsteku - call must be from:

- LdrpWalkImportDescriptor () and LdrRelocateImage () to initialize the process.
- LdrpWalkImportDescriptor () of LdrpLoadDll ().
- AVrfDllLoadNotification () and AVrfInitializeVerifier ().

8.2 The code is called when the notifications is not the loader. In kolsteke should not address outside ntdll.

9. When triggered traps emulate record, you can do the following ways:
9.1 - Define the address where you are recording, the size of the data being written and the data source. Needed to determine the source disassembler.


I was taking a look to a lot of information but I just want to implement some idea very direct to deal with this problem.
http://en.wikipedia.org/wiki/Memory_protection
http://en.wikipedia.org/wiki/Critical_section
http://en.wikipedia.org/wiki/Memory_segmentation
http://en.wikipedia.org/wiki/Self-modifying_code
http://technet.microsoft.com/en-us/library/cc700810.aspx
http://stackoverflow.com/questions/3444052/can-i-write-protect-every-page-in-the-address-space-of-a-linux-process
http://msdn.microsoft.com/en-us/library/windows/desktop/aa366785(v=vs.85).aspx
http://msdn.microsoft.com/en-us/library/windows/hardware/gg487353.aspx
http://computervirus.uw.hu/ch12lev1sec6.html
http://www.cs.gmu.edu/~xjiang/pubs/DSN07.pdf
http://static.usenix.org/event/sec09/tech/full_papers/hund.pdf

if cheaters/hackers can load a dll to your game, they will attempt to patch game's memory from that DLL. most of the cases, they try to patch the anticheats' anti-patch detections, so they will be never detected by the anticheat program.
Said anticheat is injected in the game's process, it is now a module in that process (anticheat.dll).

at the moment, I don't care if they can use a dll loader or whatever, I assume they have just loaded the dll and will attempt to patch in the process.

from ring3, you know a way to detect this or prevent this?

for example using virtualprotect, I can hook virtualprotect to prevent them from using it, what else?

Indy
April 11th, 2013, 13:13
Quote:
if you already have a driver you can block other processes from using some low level functions over your game (kernelmode hook?).

Driver is useless. Kernel manipulates pointers, not handles for eg.

Quote:
I would like to establish a detection that will tell me if anything has modified the memory, code section, for example game.exe.

Verify the checksum ?

Quote:
anti-patch detections

The patch is not necessary.

Quote:
for example using virtualprotect, I can hook virtualprotect to prevent them from using it, what else?

You can prevent modify the attributes(UM only). As was said in the beginning.

rendari
April 11th, 2013, 16:34
You can prevent patching of the game executable with excessive amounts of checksums. This I already have. The problem is the game memory being modified with programs that use WriteProcessMemory/ReadProcessMemory. So far, the only way to prevent this (that I can see) is to use a driver. So I wouldn't say driver is "useless".

Paradigm
April 11th, 2013, 18:03
checksums of what? functions? blocks of code? can you show me an example of what you have? I mean not your entire project, just tell me how can I do that.
http://en.wikipedia.org/wiki/Checksum
I saw something like this before, applied for files on disk. For example, using crc32 algo to get a hash out of a file on disk, then you check if the file is the correct before opening the program (a .txt file,, whatever).
you think I can apply crc in functions code in memory? or perhaps blocks of code in memory?

And getting to memory modification again, if the hack program uses read/write process memory, but if you prevent them from using VirtualProtect by hooking it?.

And regarding your previous answer, you mean to use VP to set page protection level?
http://msdn.microsoft.com/en-us/library/windows/desktop/aa366786(v=vs.85).aspx

http://msdn.microsoft.com/en-us/library/sf9b18xk.aspx
http://infocenter.arm.com/help/index.jsp?topic=/com.arm.doc.dui0491c/Caccache.html
http://stackoverflow.com/questions/6252812/what-does-the-aw-flag-in-the-section-attribute-mean
http://en.wikipedia.org/wiki/Page_attribute_table
http://www.delorie.com/djgpp/doc/dpmi/api/310507.html

Indy
April 11th, 2013, 22:26
rendari
The checksum is only possible for the code. The data can not be protected. See IDP eg. Intercept control is based on the data. The code remains unchanged.

Paradigm
Quote:
checksums of what? functions? blocks of code? can you show me an example of what you have? I mean not your entire project, just tell me how can I do that.

Sections of code(also relocs & IAT).

Quote:
And getting to memory modification again, if the hack program uses read/write process memory, but if you prevent them from using VirtualProtect by hooking it?.

No. Syscall(Int 0x2e eg) can call directly. R|E map is protected from being overwritten.

The best method of protection - virtualization and morphing.

rendari
April 12th, 2013, 14:15
Hello Paradigm,

Ideally you want to do checksums of the code at runtime. You can do this by getting a pointer to a function at runtime, and checksumming the memory at runtime, and then comparing it to an embedded 'correct' checksum. You will need to compensate for relocations if your application was compiled with 'Randomized Base Address' option in Visual Studio.

@Indy: I realize that the data cannot be protected with checksums. This is why I am looking for suggestions on how to protect it otherwise. Like I said before, all I have come up with is using a driver to block access to the process. I do not understand what you mean with this:

Quote:
See IDP eg. Intercept control is based on the data


Could you please clarify?

-rendari

Paradigm
April 12th, 2013, 16:06
Rendari what kind of checksum can it be? crc?

virtualization of code is easily patched in the 'jmp to vm' place?, someone told me.

Indy, so my best chance is this (R|E map)?
http://www.woodmann.com/forum/showthread.php?14987-Defeating-Memory-Breakpoints&p=93671&highlight=#post93671

because virtualization and morphing, I'm not thinking of that right now

Indy
April 12th, 2013, 16:30
Quote:
because virtualization and morphing, I'm not thinking of that right now

So all is useless. Any other protection is primitive

Paradigm
April 13th, 2013, 12:36
Indy you lack answer to rendari