在C对Linux内存图案扫描(Memory pattern scanning on Linux in

2019-10-20 07:57发布

我正在寻找一种方式来扫描程序的特定模式记忆。 在程序加载我们的代码库( .so )。

这里是我的尝试:

unsigned long FindPattern(char *pattern, char *mask)
{
    void *address;
    unsigned long size, i;      

    // NULL = We want the base address of the process we are loaded in
    address = dlopen(NULL, 0); // Would be GetModuleHandle(NULL) on Windows

    // The size of the program, would be GetModuleInformation.SizeOfImage on Windows
    size = 0x128000; // Didn't find a way for Linux

    for(i = 0; i < size; i++)
    {
         if(_compare((unsigned char *)(address + i), (unsigned char *)pattern, mask))
               return (unsigned long)(address + i);
    }
    return 0;         
}

int _compare(unsigned char *data, unsigned char *pattern, char *mask)
{
    for(; *mask; ++mask, ++data, ++pattern)
    {
        if(*mask == 'x' && *data != *pattern) // Crashes here according to gdb
            return 0;
    }
    return (*mask) == 0;
}

但是,所有的这不起作用。 在开始dlopen ,它不返回我们在加载程序的正确的基址。我也曾尝试link_map作为解释在这里 。 我知道从IDA地址和GDB这就是为什么我知道dlopen返回错误的值。

使用在CentOS 6.5 64位GCC-4.4.7。 该计划是一个32位二进制可执行文件。

Answer 1:

dlopen返回HANDLE为库,而不是一个指针,指向包含该库的存储器。

您需要使用dlsym得到一个函数的地址。

handle = dlopen(NULL, RTLD_LAZY);

address = dlsym(handle, "main");

现在你要在偷看的地址。

“主”未必是最好的地方开始,但它的工作原理如下示范。 一定要及早发现位于程序中的符号,让全搜索。

作为奖励,加快您的搜索/比较循环:

// The size of the program, would be GetModuleInformation.SizeOfImage on Windows
size = 0x128000; // Didn't find a way for Linux

unsigned char* ptr = address;

while (1)
{

  /* hmmm, gets complicated if we need to mask src char then compare pattern, I punted
   * and just compared for first char of pattern. It's just an idea... */

  ptr = memcmp(ptr, pattern[0], (size - ptr + address));

  if (ptr==NULL)
    break;

  if (_compare(ptr, (unsigned char *)pattern, mask))
           return ptr;
}


文章来源: Memory pattern scanning on Linux in C
标签: c linux gcc memory