Good morning stackoverflow !
I'm trying to extract from a binary file a hexadecimal string. I can't find this string directly, but I know that the string is 0x30 long and begins 0x10 after a known hex string.
So here is my code
FILE *f = NULL;
unsigned char *buffer = NULL;
unsigned long fileLen;
unsigned char known_string[] = {0x45, 0x45, 0x45, 0x45};
printf("Opening file...\n");
f = fopen(argv[1], "rb");
if (!f) {
fprintf(stderr, "Unable to open %s\n", argv[1]);
return -1;
}
// Get the length
fseek(f, 0, SEEK_END);
fileLen=ftell(f);
fseek(f, 0, SEEK_SET);
// Allocate memory
buffer=malloc(fileLen);
if (!buffer)
{
fprintf(stderr, "Memory error!\n");
fclose(f);
return开发者_开发技巧 -1;
}
// File to buffer
fread(buffer, fileLen, 1, f);
fclose(f);
printf("Buffer starts: %p\n", &buffer[0]);
printf("Buffer ends: %p\n", &buffer[fileLen]);
// Determines offset of known_string
char *p = memmem(buffer, fileLen, bytes, 4);
if (!p) {
return -1;
} else {
printf(" General offset: %x\n", p);
}
free(buffer);
So I get the general offset of the known string but I need to get the one relative to the file. I'm a bit stuck at this step. I think I must do something like p - &buffer[0], but p and &buffer[0] are not of the same type, and p is not even the real offset (678987 instead of 10678987 e.g). Then in the case I got the relative offset, how could I find the unknown string ?
As you're only interested in the pointer address, not the data it points to, you may just as well use void *, and you don't have to do &buffer[0], it's not an array.
unsigned long off_to_string = 0x10 + 4 + ((void *)p) - ((void *)buffer);
I add 0x10 + 4 to skip the found hex byte sequence and the bytes up to the searched for string.
All you need to do is use unsigned char *
for the type of p
- then you can just subtract:
unsigned char *p = memmem(buffer, fileLen, bytes, 4);
if (!p) {
return -1;
} else {
printf(" General offset: %p\n", p);
printf(" Offset within file: %llx\n", (unsigned long long)(p - buffer));
}
精彩评论