使用C在Linux上进行内存模式扫描 [英] Memory pattern scanning on Linux in C
问题描述
我正在寻找一种扫描程序内存中特定模式的方法.该程序正在将我们的代码作为库(.so
)加载.
I am looking for a way to scan a program's memory for specific pattern. The program is loading our code as a library (.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
返回错误值的原因.
But all of this doesn't work. Starting at dlopen
, it does not return the correct base address of the program we are loaded in. I have also tried link_map as explained here.
I do know the addresses from IDA and gdb that's why I know dlopen
returns wrong values.
在CentOS 6.5 64位上使用gcc-4.4.7.该程序是32位可执行二进制文件.
Using gcc-4.4.7 on CentOS 6.5 64bit. The program is a 32bit executable binary.
推荐答案
dlopen
返回该库的HANDLE
,而不是指向包含该库的内存的指针.
dlopen
returns a HANDLE
for the library, not a pointer to the memory containing the library.
您需要使用dlsym
来获取函数的地址.
You need to use dlsym
to get an address of a function.
handle = dlopen(NULL, RTLD_LAZY);
address = dlsym(handle, "main");
现在您将有一个地址可以浏览.
NOW you'll have an address to peek at.
主要"可能不是最好的起点,但此处仅作为示例.请确保在程序的开头找到一个符号,以便进行全面搜索.
"main" may not be the best place to start, but it works as a demonstration here. Be sure to find a symbol located early in the program to allow full searching.
作为奖励,加快您的搜索/比较循环:
And as a bonus, speed up your search/compare loop:
// 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;
}
这篇关于使用C在Linux上进行内存模式扫描的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!