本文介绍了在二进制文件中搜索模式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要在二进制文件中搜索二进制模式,我该怎么办?

I need to search for a binary pattern in binary file,how can i do it?

我尝试使用"strstr()"函数,将文件和模式转换为字符串,但是不起作用.

I tried with "strstr()" function and convert the file and the pattern to a string but its not working.

(该模式也是二进制文件)这是它尝试过的:

(the pattern is also a binary file)this is what it tried:

void isinfected(FILE *file, FILE *sign, char filename[], char filepath[])
{
char* fil,* vir;
int filelen, signlen;
fseek(file, 0, SEEK_END);
fseek(sign, 0, SEEK_END);
filelen = ftell(file);
signlen = ftell(sign);

fil = (char *)malloc(sizeof(char) * filelen);
if (!fil)
{
    printf("unseccesful malloc!\n");
}

vir = (char *)malloc(sizeof(char) * signlen);

if (!vir)
{
    printf("unseccesful malloc!\n");
}

fseek(file, 0, SEEK_CUR);
fseek(sign, 0, SEEK_CUR);

fread(fil, 1, filelen, file);
fread(vir, 1, signlen, sign);
if (strstr(vir, fil) != NULL)
    log(filename, "infected",filepath );
else
    log(filename, "not infected", filepath);
free(vir);
free(fil);
}

推荐答案

对于任何二进制处理,您应该从不使用 strXX 之一函数,因为这些仅(且排他地)适用于C样式的零终止字符串.您的代码失败,因为 strXX 函数的外观不能超过遇到的第一个二进制0.

For any binary handling you should never use one of the strXX functions, because these only (and exclusively) work on C-style zero terminated strings. Your code is failing because the strXX functions cannot look beyond the first binary 0 they encounter.

由于您使用 strstr 的基本想法是正确的(并且 only 失败,因为它仅适用于零终止字符串),因此可以将其替换为 memmem ,它对任意数据都执行相同的操作.由于 memmem 是GNU C扩展(另请参见),它可能在您的系统上不可用,并且您需要编写执行相同操作的代码.

As your basic idea with strstr appears correct (and only fails because it works on zero terminated strings only), you can replace it with memmem, which does the same on arbitrary data. Since memmem is a GNU C extension (see also Is there a particular reason for memmem being a GNU extension?), it may not be available on your system and you need to write code that does the same thing.

对于 memmem 的非常基本的实现,您可以使用 memchr 扫描第一个二进制字符,如果发现了某些内容,则使用 memcmp 进行扫描:

For a very basic implementation of memmem you can use memchr to scan for the first binary character, followed by memcmp if it found something:

void * my_memmem(const void *big, size_t big_len, const void *little, size_t little_len)
{
    void *iterator;
    if (big_len < little_len)
        return NULL;

    iterator = (void *)big;
    while (1)
    {
        iterator = memchr (iterator, ((unsigned char *)little)[0], big_len - (iterator-big));
        if (iterator == NULL)
            return NULL;
        if (iterator && !memcmp (iterator, little, little_len))
            return iterator;
        iterator++;
    }
}

可能有更好的实现,但是除非 memmem 是程序中的重要功能,否则它会做的很好.

There are better implementations possible, but unless memmem is an important function in your program, it'll do the job just fine.

这篇关于在二进制文件中搜索模式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

06-24 08:05