我正在寻找一种扫描程序内存以获得特定模式的方法。程序正在将代码作为库加载(.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,如here所述。
我知道来自ida和gdb的地址,这就是我知道dlopen返回错误值的原因。
在CentOS 6.5 64位上使用GCC-4.4.7。程序是一个32位的可执行二进制文件。

最佳答案

dlopen返回库的HANDLE,而不是指向包含库的内存的指针。
您需要使用dlsym来获取函数的地址。

handle = dlopen(NULL, RTLD_LAZY);

address = dlsym(handle, "main");

现在你有一个地址可以偷看了。
“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;
}

09-10 05:26
查看更多