2026-01-06 09:48:38 +08:00
|
|
|
#include "common/binary.h"
|
|
|
|
|
#include "common/io.h"
|
|
|
|
|
#include "common/stringUtils.h"
|
|
|
|
|
#include "common/mallocHelper.h"
|
2024-08-22 16:41:06 +08:00
|
|
|
|
|
|
|
|
#include <windows.h>
|
|
|
|
|
#include <imagehlp.h>
|
|
|
|
|
#include <stdlib.h>
|
|
|
|
|
#include <string.h>
|
|
|
|
|
|
2025-04-02 10:27:25 +08:00
|
|
|
/**
|
|
|
|
|
* Extracts string literals from a PE (Windows) executable
|
|
|
|
|
*
|
|
|
|
|
* This function maps the PE file into memory, locates the .rdata section
|
|
|
|
|
* (which typically contains string literals), and scans it for valid strings.
|
|
|
|
|
* Each string found is passed to the callback function for processing.
|
|
|
|
|
*/
|
2024-08-27 16:19:05 +08:00
|
|
|
const char* ffBinaryExtractStrings(const char *peFile, bool (*cb)(const char *str, uint32_t len, void *userdata), void *userdata, uint32_t minLength)
|
2024-08-22 16:41:06 +08:00
|
|
|
{
|
2025-04-02 10:27:25 +08:00
|
|
|
// Use MapAndLoad with cleanup attribute to ensure proper unloading
|
2024-08-22 16:41:06 +08:00
|
|
|
__attribute__((__cleanup__(UnMapAndLoad))) LOADED_IMAGE loadedImage = {};
|
|
|
|
|
if (!MapAndLoad(peFile, NULL, &loadedImage, FALSE, TRUE))
|
|
|
|
|
return "File could not be loaded";
|
|
|
|
|
|
2025-04-02 10:27:25 +08:00
|
|
|
// Iterate through all sections in the PE file
|
2024-08-22 16:41:06 +08:00
|
|
|
for (ULONG i = 0; i < loadedImage.NumberOfSections; ++i)
|
|
|
|
|
{
|
|
|
|
|
PIMAGE_SECTION_HEADER section = &loadedImage.Sections[i];
|
2025-04-02 10:27:25 +08:00
|
|
|
// Look for initialized data sections with the name ".rdata" which typically contains string literals
|
2024-08-22 16:41:06 +08:00
|
|
|
if ((section->Characteristics & IMAGE_SCN_CNT_INITIALIZED_DATA) && ffStrEquals((const char*) section->Name, ".rdata"))
|
|
|
|
|
{
|
|
|
|
|
uint8_t *data = (uint8_t *) loadedImage.MappedAddress + section->PointerToRawData;
|
|
|
|
|
|
2025-04-02 10:27:25 +08:00
|
|
|
// Scan the section for string literals
|
2024-08-22 16:41:06 +08:00
|
|
|
for (size_t off = 0; off < section->SizeOfRawData; ++off)
|
|
|
|
|
{
|
|
|
|
|
const char* p = (const char*) data + off;
|
|
|
|
|
if (*p == '\0') continue;
|
|
|
|
|
uint32_t len = (uint32_t) strlen(p);
|
2024-08-27 16:19:05 +08:00
|
|
|
if (len < minLength) continue;
|
2025-04-02 10:27:25 +08:00
|
|
|
// Only process printable ASCII characters
|
2024-08-22 16:41:06 +08:00
|
|
|
if (*p >= ' ' && *p <= '~') // Ignore control characters
|
|
|
|
|
{
|
|
|
|
|
if (!cb(p, len, userdata)) break;
|
|
|
|
|
}
|
|
|
|
|
off += len;
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
return NULL;
|
|
|
|
|
}
|