Results 1 to 13 of 13

Thread: detecting or preventing patching in memory (code and data)

  1. #1

    detecting or preventing patching in memory (code and data)

    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.
    I promise that I have read the FAQ and tried to use the Search to answer my question.

  2. #2

  3. #3
    Registered User
    Join Date
    Dec 2005
    Posts
    216
    Blog Entries
    5
    Quote Originally Posted by Indy View Post
    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.

  4. #4
    Private memory(R|E, heap etc) can be protected ^.

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

    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:
    Интересует механизм защиты проекций модулей от негодных патчей. В общем для юзермода механизм такой:

    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() ?)
    Last edited by Indy; April 10th, 2013 at 19:53.

  5. #5
    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):
    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?
    Last edited by Paradigm; April 11th, 2013 at 12:04.
    I promise that I have read the FAQ and tried to use the Search to answer my question.

  6. #6
    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.

    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 ?

    anti-patch detections
    The patch is not necessary.

    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.

  7. #7
    Registered User
    Join Date
    Dec 2005
    Posts
    216
    Blog Entries
    5
    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".

  8. #8
    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
    I promise that I have read the FAQ and tried to use the Search to answer my question.

  9. #9
    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
    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).

    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.

  10. #10
    Registered User
    Join Date
    Dec 2005
    Posts
    216
    Blog Entries
    5
    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:

    See IDP eg. Intercept control is based on the data
    Could you please clarify?

    -rendari

  11. #11
    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
    I promise that I have read the FAQ and tried to use the Search to answer my question.

  12. #12
    because virtualization and morphing, I'm not thinking of that right now
    So all is useless. Any other protection is primitive

  13. #13
    Indy you lack answer to rendari
    I promise that I have read the FAQ and tried to use the Search to answer my question.

Similar Threads

  1. using filestreams to store data..or code as data?
    By BanMe in forum The Newbie Forum
    Replies: 7
    Last Post: August 8th, 2009, 21:58
  2. From code to data???
    By homunculus in forum OllyDbg Support Forums
    Replies: 6
    Last Post: February 5th, 2003, 00:56
  3. In-memory patching question
    By Czaj-nick in forum Advanced Reversing and Programming
    Replies: 6
    Last Post: August 29th, 2001, 02:23
  4. Inline memory patching Asprotect
    By Instructor in forum Advanced Reversing and Programming
    Replies: 1
    Last Post: July 15th, 2001, 08:28
  5. CommView 2.3 and Asprotect memory patching
    By TOTEU in forum Advanced Reversing and Programming
    Replies: 12
    Last Post: October 31st, 2000, 00:50

Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •