10static_assert(
FEATURE_COUNT == 278,
"update README.md and PANO_ML_FEATURE_VERSION");
13static constexpr std::array kNamedFeatures = {
14 "entropy",
"log_size",
"is_pe",
"is_64bit",
"is_dll",
"subsystem_gui",
"section_count",
15 "section_entropy_max",
"section_entropy_min",
"section_entropy_mean",
16 "writable_executable_sections",
"entry_outside_executable",
"imported_dlls",
17 "imported_functions",
"has_signature",
"has_tls",
"has_debug",
"has_relocations",
18 "has_resources",
"overlay_ratio",
"image_to_file_ratio",
"zero_timestamp",
25 static const std::vector<std::string> names = [] {
26 std::vector<std::string> all;
29 for (
int value = 0; value < 256; value++) {
30 snprintf(name,
sizeof(name),
"byte_%02x", value);
31 all.emplace_back(name);
33 all.insert(all.end(), kNamedFeatures.begin(), kNamedFeatures.end());
36 return Index < names.size() ? names[Index].c_str() :
nullptr;
45static float Entropy(
const uint8_t* Data,
size_t Size)
50 size_t counts[256] = {};
51 for (
size_t i = 0; i < Size; i++) {
55 for (
size_t count : counts) {
57 double p = (double)count / (
double)Size;
58 entropy -= p * std::log2(p);
61 return (
float)entropy;
69 size_t Size()
const {
return m_size; }
70 const uint8_t*
Data()
const {
return m_data; }
72 bool Contains(uint64_t Offset, uint64_t Length)
const
74 return Offset <= m_size && Length <= m_size - Offset;
79 bool Read(uint64_t Offset, T* Out)
const
84 memcpy(Out, m_data + Offset,
sizeof(T));
89 const uint8_t* m_data;
108 IMAGE_DOS_HEADER dos;
109 if (!File.
Read(0, &dos) || dos.e_magic != IMAGE_DOS_SIGNATURE || dos.e_lfanew < 0) {
112 uint64_t ntOffset = (uint64_t)dos.e_lfanew;
114 if (!File.Read(ntOffset, &signature) || signature != IMAGE_NT_SIGNATURE ||
115 !File.Read(ntOffset +
sizeof(DWORD), &Pe->FileHeader)) {
119 uint64_t optionalOffset = ntOffset +
sizeof(DWORD) +
sizeof(IMAGE_FILE_HEADER);
121 if (!File.Read(optionalOffset, &magic)) {
124 const IMAGE_DATA_DIRECTORY* directories =
nullptr;
125 DWORD directoryCount = 0;
126 IMAGE_OPTIONAL_HEADER64 optional64;
127 IMAGE_OPTIONAL_HEADER32 optional32;
128 if (magic == IMAGE_NT_OPTIONAL_HDR64_MAGIC && File.Read(optionalOffset, &optional64)) {
130 Pe->AddressOfEntryPoint = optional64.AddressOfEntryPoint;
131 Pe->SizeOfImage = optional64.SizeOfImage;
132 Pe->Subsystem = optional64.Subsystem;
133 directories = optional64.DataDirectory;
134 directoryCount = optional64.NumberOfRvaAndSizes;
136 else if (magic == IMAGE_NT_OPTIONAL_HDR32_MAGIC && File.Read(optionalOffset, &optional32)) {
137 Pe->AddressOfEntryPoint = optional32.AddressOfEntryPoint;
138 Pe->SizeOfImage = optional32.SizeOfImage;
139 Pe->Subsystem = optional32.Subsystem;
140 directories = optional32.DataDirectory;
141 directoryCount = optional32.NumberOfRvaAndSizes;
146 Pe->DataDirectoryCount = std::min<DWORD>(directoryCount, IMAGE_NUMBEROF_DIRECTORY_ENTRIES);
147 memcpy(Pe->DataDirectories, directories, Pe->DataDirectoryCount *
sizeof(IMAGE_DATA_DIRECTORY));
151 uint64_t sectionOffset = optionalOffset + Pe->FileHeader.SizeOfOptionalHeader;
152 for (WORD i = 0; i < Pe->FileHeader.NumberOfSections; i++) {
153 IMAGE_SECTION_HEADER section;
154 if (!File.Read(sectionOffset + (uint64_t)i *
sizeof(section), §ion)) {
157 Pe->Sections.push_back(section);
162static const IMAGE_DATA_DIRECTORY* Directory(
const PeLayout& Pe, DWORD Index)
172static bool RvaToOffset(
const PeLayout& Pe,
const FileView& File, DWORD Rva, uint64_t* Offset)
174 for (
const auto& section : Pe.
Sections) {
175 DWORD size = std::max(section.Misc.VirtualSize, section.SizeOfRawData);
176 if (Rva >= section.VirtualAddress && Rva - section.VirtualAddress < size) {
177 uint64_t delta = Rva - section.VirtualAddress;
178 if (delta >= section.SizeOfRawData) {
181 *Offset = (uint64_t)section.PointerToRawData + delta;
190static void CountImports(
const PeLayout& Pe,
const FileView& File, uint32_t* Dlls, uint32_t* Functions)
192 const uint32_t maxDlls = 4096;
193 const uint32_t maxFunctionsPerDll = 65536;
197 const IMAGE_DATA_DIRECTORY* imports = Directory(Pe, IMAGE_DIRECTORY_ENTRY_IMPORT);
198 uint64_t descriptorOffset;
199 if (imports ==
nullptr || !RvaToOffset(Pe, File, imports->VirtualAddress, &descriptorOffset)) {
203 for (uint32_t i = 0; i < maxDlls; i++) {
204 IMAGE_IMPORT_DESCRIPTOR descriptor;
205 if (!File.
Read(descriptorOffset + (uint64_t)i *
sizeof(descriptor), &descriptor) ||
206 descriptor.Name == 0) {
212 DWORD thunkRva = descriptor.OriginalFirstThunk != 0 ? descriptor.OriginalFirstThunk : descriptor.FirstThunk;
213 uint64_t thunkOffset;
214 if (!RvaToOffset(Pe, File, thunkRva, &thunkOffset)) {
217 size_t thunkSize = Pe.
Is64Bit ?
sizeof(uint64_t) : sizeof(uint32_t);
218 for (uint32_t j = 0; j < maxFunctionsPerDll; j++) {
221 ? File.
Read(thunkOffset + (uint64_t)j * thunkSize, &thunk)
222 : File.
Read(thunkOffset + (uint64_t)j * thunkSize, (uint32_t*)&thunk);
223 if (!read || thunk == 0) {
236 std::vector<float>& f = features.
Values;
242 size_t counts[256] = {};
243 for (
size_t i = 0; i < Size; i++) {
246 for (
size_t b = 0; b < 256; b++) {
254 if (!ParsePe(file, &pe)) {
257 features.
IsPe =
true;
267 float entropyMax = 0, entropyMin = 8, entropySum = 0;
268 size_t withData = 0, writableExecutable = 0;
269 bool entryInExecutable =
false;
270 uint64_t endOfSections = 0;
271 for (
const auto& section : pe.
Sections) {
272 DWORD flags = section.Characteristics;
273 bool executable = (flags & IMAGE_SCN_MEM_EXECUTE) != 0;
274 if (executable && (flags & IMAGE_SCN_MEM_WRITE)) {
275 writableExecutable++;
277 DWORD virtualSize = std::max(section.Misc.VirtualSize, section.SizeOfRawData);
280 entryInExecutable =
true;
283 uint64_t start = section.PointerToRawData;
284 uint64_t length = section.SizeOfRawData;
285 if (length == 0 || !file.
Contains(start, 1)) {
288 length = std::min<uint64_t>(length, Size - start);
289 endOfSections = std::max(endOfSections, start + length);
290 float entropy = Entropy(Data + start, (
size_t)length);
291 entropyMax = std::max(entropyMax, entropy);
292 entropyMin = std::min(entropyMin, entropy);
293 entropySum += entropy;
306 if (Size > 0 && endOfSections < Size) {
313 uint32_t dlls = 0, functions = 0;
314 CountImports(pe, file, &dlls, &functions);
319 f[
FEATURE_HAS_TLS] = Directory(pe, IMAGE_DIRECTORY_ENTRY_TLS) ? 1.0f : 0.0f;
329 HANDLE file = CreateFileW(Path.c_str(), GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE,
330 NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL | FILE_FLAG_SEQUENTIAL_SCAN, NULL);
331 if (file == INVALID_HANDLE_VALUE) {
332 throw std::runtime_error(
"cannot open the file (error " + std::to_string(GetLastError()) +
")");
335 LARGE_INTEGER size{};
336 if (!GetFileSizeEx(file, &size)) {
338 throw std::runtime_error(
"cannot get the file's size");
342 throw std::runtime_error(
"the file is larger than " + std::to_string(
PANO_ML_MAX_FILE_SIZE) +
" bytes");
345 std::vector<uint8_t> data((
size_t)size.QuadPart);
347 while (read < data.size()) {
348 DWORD chunk = (DWORD)std::min<size_t>(data.size() - read, 1 << 24);
350 if (!ReadFile(file, data.data() + read, chunk, &got, NULL) || got == 0) {
#define PANO_ML_MAX_FILE_SIZE
Files larger than this are not scored (the features are computed over the whole file).
@ FEATURE_IMPORTED_FUNCTIONS
@ FEATURE_HAS_RELOCATIONS
@ FEATURE_ENTRY_OUTSIDE_EXECUTABLE
@ FEATURE_SECTION_ENTROPY_MAX
@ FEATURE_IMAGE_TO_FILE_RATIO
@ FEATURE_WRITABLE_EXECUTABLE_SECTIONS
@ FEATURE_SECTION_ENTROPY_MIN
@ FEATURE_SECTION_ENTROPY_MEAN
A read-only view of the file that refuses reads outside it.
const uint8_t * Data() const
bool Read(uint64_t Offset, T *Out) const
Copies a T from Offset. False when it doesn't fit in the file.
FileView(const uint8_t *Data, size_t Size)
bool Contains(uint64_t Offset, uint64_t Length) const
PeFeatures ExtractPeFeatures(const uint8_t *Data, size_t Size)
The same, from a file's bytes (used by ExtractPeFeatures and the tests).
const char * FeatureName(size_t Index)
The name of feature Index, or nullptr when it is out of range.
std::vector< float > Values
The parts of a PE the features need.
DWORD AddressOfEntryPoint
std::vector< IMAGE_SECTION_HEADER > Sections
IMAGE_DATA_DIRECTORY DataDirectories[IMAGE_NUMBEROF_DIRECTORY_ENTRIES]
IMAGE_FILE_HEADER FileHeader