我正在寻找一种方法来扫描程序的内存以寻找特定的模式。该程序将我们的代码加载为库(.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
开始,它不会返回我们加载的程序的正确基址。我还尝试了解释here的link_map。
我知道IDA和gdb的地址,这就是我知道dlopen
返回错误值的原因。
在CentOS 6.5 64bit上使用gcc-4.4.7。该程序是32位可执行二进制文件。
答案 0 :(得分:1)
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;
}