pythonnumpyctypesmalware-detectionreadprocessmemory

How to read a buffer content after you call ReadProcessMemory() ? (python)


I'm building a Memory Scanner with ctypes and after I create a buffer with VirtualAlloc(), then I use ReadProcessMemory() to write the memory contents in the buffer, but how can I see the contents to search for malware strings ? VirtualAlloc() returns me the Address of the buffer, so do create_buffer_string if I use it instead of VirtualAlloc(), but what functions/libs can I use to actually know the strings that are in the buffer and finally compare with my malware strings database?

part of the main code (the full code is too big and for some reason I cant insert the pastebin link, tell me if you want)

 while VQEResult != 0:


    VQEResult = VirtualQueryEx(         # If VirtualQueryEx == Verifica se é possível retornar info sobre a page do Adress
            process,            # HANDLE para o Processo
            Adress,             # Pointer pro Adress a ser lido
            byref(mbi),         # Pointer pra variável com output da MEMORY_BASIC_INFORMATION
            sizeof(mbi),        # Tamanho da variável com output da MEMORY_BASIC_INFORMATION
            )

    print(mbi.BaseAddress,mbi.RegionSize,Adress)
    

    if mbi.State == MEM_COMMIT or 65536 and mbi.RegionSize > 41000:    # Se haver memória alocada:

            
            ContentsBuffer = VirtualAlloc (        # Alocando conteúdo do processo num buffer
           
                            None,           # Sem adress específico
                            mbi.RegionSize, # Tamanho do buffer alocado é igual o do app
                            0x1000,         # 0x1000 = MEMORY_COMMIT
                            0x04,           # 0x04   = PAGE_READWRITE   
                            
                            )

            if not ReadProcessMemory (

                    process,                    # handle pro processo
                    Adress,                     # ponteiro pro adress do buffer
                    ContentsBuffer,             # ponteiro pro output
                    mbi.RegionSize,             # tanto de bytes a serem lidos
                    byref(BytesRead),           # output de quantos bytes foram lidos

                    ):
              
               continue
               # print("Erro:",GetLastError)
              
            
    if VQEResult:
            Adress += mbi.RegionSize

Basically I want to see the contents inside the Address pointed by ContentsBuffer variable.


Solution

  • You can use ContentsBuffer = ctypes.create_string_buffer(), then ContentsBuffer.raw is the entire buffer as a bytes object. Using VirtualAlloc isn't a requirement of the buffer address for ReadProcessMemory.

    You malware signatures, if kept as bytes strings, can then just be:

    for s in malware:
        if s in ContentsBuffer:
            ...