Panoptes 1.0.0
Endpoint Detection and Response
Loading...
Searching...
No Matches
pe_features.cpp
Go to the documentation of this file.
1#include "PanoptesML.h"
2#include <algorithm>
3#include <array>
4#include <cmath>
5#include <cstdio>
6#include <cstring>
7#include <stdexcept>
8
9// The README and every trained model depend on this; changing it means a new feature version
10static_assert(FEATURE_COUNT == 278, "update README.md and PANO_ML_FEATURE_VERSION");
11
12// Names of the features after the byte histogram, in PanoMlFeature order
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",
19};
20static_assert(kNamedFeatures.size() == FEATURE_COUNT - FEATURE_ENTROPY, "name every feature in PanoMlFeature");
21
22const char* FeatureName(size_t Index)
23{
24 // byte_00 .. byte_ff for the histogram, built once
25 static const std::vector<std::string> names = [] {
26 std::vector<std::string> all;
27 all.reserve(FEATURE_COUNT);
28 char name[16];
29 for (int value = 0; value < 256; value++) {
30 snprintf(name, sizeof(name), "byte_%02x", value);
31 all.emplace_back(name);
32 }
33 all.insert(all.end(), kNamedFeatures.begin(), kNamedFeatures.end());
34 return all;
35 }();
36 return Index < names.size() ? names[Index].c_str() : nullptr;
37}
38
39// The file is untrusted: every header field is checked against the file's size before it is
40// used, and nothing in it is followed outside the file. The PE is never loaded or run.
41
42#pragma region Helpers
43
45static float Entropy(const uint8_t* Data, size_t Size)
46{
47 if (Size == 0) {
48 return 0;
49 }
50 size_t counts[256] = {};
51 for (size_t i = 0; i < Size; i++) {
52 counts[Data[i]]++;
53 }
54 double entropy = 0;
55 for (size_t count : counts) {
56 if (count != 0) {
57 double p = (double)count / (double)Size;
58 entropy -= p * std::log2(p);
59 }
60 }
61 return (float)entropy;
62}
63
65class FileView {
66public:
67 FileView(const uint8_t* Data, size_t Size) : m_data(Data), m_size(Size) {}
68
69 size_t Size() const { return m_size; }
70 const uint8_t* Data() const { return m_data; }
71
72 bool Contains(uint64_t Offset, uint64_t Length) const
73 {
74 return Offset <= m_size && Length <= m_size - Offset;
75 }
76
78 template <typename T>
79 bool Read(uint64_t Offset, T* Out) const
80 {
81 if (!Contains(Offset, sizeof(T))) {
82 return false;
83 }
84 memcpy(Out, m_data + Offset, sizeof(T)); // the file has no alignment guarantees
85 return true;
86 }
87
88private:
89 const uint8_t* m_data;
90 size_t m_size;
91};
92
94struct PeLayout {
95 bool Is64Bit = false;
96 IMAGE_FILE_HEADER FileHeader{};
98 DWORD SizeOfImage = 0;
99 WORD Subsystem = 0;
101 IMAGE_DATA_DIRECTORY DataDirectories[IMAGE_NUMBEROF_DIRECTORY_ENTRIES]{};
102 std::vector<IMAGE_SECTION_HEADER> Sections;
103};
104
106static bool ParsePe(const FileView& File, PeLayout* Pe)
107{
108 IMAGE_DOS_HEADER dos;
109 if (!File.Read(0, &dos) || dos.e_magic != IMAGE_DOS_SIGNATURE || dos.e_lfanew < 0) {
110 return false;
111 }
112 uint64_t ntOffset = (uint64_t)dos.e_lfanew;
113 DWORD signature;
114 if (!File.Read(ntOffset, &signature) || signature != IMAGE_NT_SIGNATURE ||
115 !File.Read(ntOffset + sizeof(DWORD), &Pe->FileHeader)) {
116 return false;
117 }
118
119 uint64_t optionalOffset = ntOffset + sizeof(DWORD) + sizeof(IMAGE_FILE_HEADER);
120 WORD magic;
121 if (!File.Read(optionalOffset, &magic)) {
122 return false;
123 }
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)) {
129 Pe->Is64Bit = true;
130 Pe->AddressOfEntryPoint = optional64.AddressOfEntryPoint;
131 Pe->SizeOfImage = optional64.SizeOfImage;
132 Pe->Subsystem = optional64.Subsystem;
133 directories = optional64.DataDirectory;
134 directoryCount = optional64.NumberOfRvaAndSizes;
135 }
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;
142 }
143 else {
144 return false;
145 }
146 Pe->DataDirectoryCount = std::min<DWORD>(directoryCount, IMAGE_NUMBEROF_DIRECTORY_ENTRIES);
147 memcpy(Pe->DataDirectories, directories, Pe->DataDirectoryCount * sizeof(IMAGE_DATA_DIRECTORY));
148
149 // The section table follows the optional header at the size the file header gives, which
150 // a crafted file can set to anything
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), &section)) {
155 break; // a truncated table: keep the sections that are there
156 }
157 Pe->Sections.push_back(section);
158 }
159 return true;
160}
161
162static const IMAGE_DATA_DIRECTORY* Directory(const PeLayout& Pe, DWORD Index)
163{
164 if (Index >= Pe.DataDirectoryCount || Pe.DataDirectories[Index].VirtualAddress == 0 ||
165 Pe.DataDirectories[Index].Size == 0) {
166 return nullptr;
167 }
168 return &Pe.DataDirectories[Index];
169}
170
172static bool RvaToOffset(const PeLayout& Pe, const FileView& File, DWORD Rva, uint64_t* Offset)
173{
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) {
179 return false; // in the section's zero-filled tail, not in the file
180 }
181 *Offset = (uint64_t)section.PointerToRawData + delta;
182 return File.Contains(*Offset, 1);
183 }
184 }
185 return false;
186}
187
190static void CountImports(const PeLayout& Pe, const FileView& File, uint32_t* Dlls, uint32_t* Functions)
191{
192 const uint32_t maxDlls = 4096;
193 const uint32_t maxFunctionsPerDll = 65536;
194 *Dlls = 0;
195 *Functions = 0;
196
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)) {
200 return;
201 }
202
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) {
207 break;
208 }
209 (*Dlls)++;
210
211 // The lookup table, or the address table when a linker left the lookup table out
212 DWORD thunkRva = descriptor.OriginalFirstThunk != 0 ? descriptor.OriginalFirstThunk : descriptor.FirstThunk;
213 uint64_t thunkOffset;
214 if (!RvaToOffset(Pe, File, thunkRva, &thunkOffset)) {
215 continue;
216 }
217 size_t thunkSize = Pe.Is64Bit ? sizeof(uint64_t) : sizeof(uint32_t);
218 for (uint32_t j = 0; j < maxFunctionsPerDll; j++) {
219 uint64_t thunk = 0;
220 bool read = Pe.Is64Bit
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) {
224 break;
225 }
226 (*Functions)++;
227 }
228 }
229}
230
231#pragma endregion
232
233PeFeatures ExtractPeFeatures(const uint8_t* Data, size_t Size)
234{
235 PeFeatures features;
236 std::vector<float>& f = features.Values;
237 f.assign(FEATURE_COUNT, 0.0f);
238 FileView file(Data, Size);
239
240 // Byte statistics: computed for every file, PE or not
241 if (Size > 0) {
242 size_t counts[256] = {};
243 for (size_t i = 0; i < Size; i++) {
244 counts[Data[i]]++;
245 }
246 for (size_t b = 0; b < 256; b++) {
247 f[FEATURE_BYTE_HISTOGRAM + b] = (float)((double)counts[b] / (double)Size);
248 }
249 }
250 f[FEATURE_ENTROPY] = Entropy(Data, Size) / 8.0f;
251 f[FEATURE_LOG_SIZE] = (float)(std::log2((double)Size + 1) / 32.0);
252
253 PeLayout pe;
254 if (!ParsePe(file, &pe)) {
255 return features;
256 }
257 features.IsPe = true;
258 f[FEATURE_IS_PE] = 1;
259 f[FEATURE_IS_64BIT] = pe.Is64Bit ? 1.0f : 0.0f;
260 f[FEATURE_IS_DLL] = (pe.FileHeader.Characteristics & IMAGE_FILE_DLL) ? 1.0f : 0.0f;
261 f[FEATURE_SUBSYSTEM_GUI] = pe.Subsystem == IMAGE_SUBSYSTEM_WINDOWS_GUI ? 1.0f : 0.0f;
262 f[FEATURE_ZERO_TIMESTAMP] = pe.FileHeader.TimeDateStamp == 0 ? 1.0f : 0.0f;
263 f[FEATURE_SECTION_COUNT] = std::min((float)pe.Sections.size() / 16.0f, 4.0f);
264
265 // Sections: entropy of each one's raw data, W+X sections, where the entry point is, and
266 // how much of the file lies past the last section (the overlay)
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++;
276 }
277 DWORD virtualSize = std::max(section.Misc.VirtualSize, section.SizeOfRawData);
278 if (executable && pe.AddressOfEntryPoint >= section.VirtualAddress &&
279 pe.AddressOfEntryPoint - section.VirtualAddress < virtualSize) {
280 entryInExecutable = true;
281 }
282
283 uint64_t start = section.PointerToRawData;
284 uint64_t length = section.SizeOfRawData;
285 if (length == 0 || !file.Contains(start, 1)) {
286 continue;
287 }
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;
294 withData++;
295 }
296 if (withData > 0) {
297 f[FEATURE_SECTION_ENTROPY_MAX] = entropyMax / 8.0f;
298 f[FEATURE_SECTION_ENTROPY_MIN] = entropyMin / 8.0f;
299 f[FEATURE_SECTION_ENTROPY_MEAN] = entropySum / (float)withData / 8.0f;
300 }
301 if (!pe.Sections.empty()) {
302 f[FEATURE_WRITABLE_EXECUTABLE_SECTIONS] = (float)writableExecutable / (float)pe.Sections.size();
303 }
304 // A DLL without an entry point has AddressOfEntryPoint 0, which is not suspicious
305 f[FEATURE_ENTRY_OUTSIDE_EXECUTABLE] = (pe.AddressOfEntryPoint != 0 && !entryInExecutable) ? 1.0f : 0.0f;
306 if (Size > 0 && endOfSections < Size) {
307 f[FEATURE_OVERLAY_RATIO] = (float)((double)(Size - endOfSections) / (double)Size);
308 }
309 if (Size > 0) {
310 f[FEATURE_IMAGE_TO_FILE_RATIO] = (float)(std::min((double)pe.SizeOfImage / (double)Size, 16.0) / 16.0);
311 }
312
313 uint32_t dlls = 0, functions = 0;
314 CountImports(pe, file, &dlls, &functions);
315 f[FEATURE_IMPORTED_DLLS] = (float)(std::log2((double)dlls + 1) / 8.0);
316 f[FEATURE_IMPORTED_FUNCTIONS] = (float)(std::log2((double)functions + 1) / 12.0);
317
318 f[FEATURE_HAS_SIGNATURE] = Directory(pe, IMAGE_DIRECTORY_ENTRY_SECURITY) ? 1.0f : 0.0f;
319 f[FEATURE_HAS_TLS] = Directory(pe, IMAGE_DIRECTORY_ENTRY_TLS) ? 1.0f : 0.0f;
320 f[FEATURE_HAS_DEBUG] = Directory(pe, IMAGE_DIRECTORY_ENTRY_DEBUG) ? 1.0f : 0.0f;
321 f[FEATURE_HAS_RELOCATIONS] = Directory(pe, IMAGE_DIRECTORY_ENTRY_BASERELOC) ? 1.0f : 0.0f;
322 f[FEATURE_HAS_RESOURCES] = Directory(pe, IMAGE_DIRECTORY_ENTRY_RESOURCE) ? 1.0f : 0.0f;
323 return features;
324}
325
326PeFeatures ExtractPeFeatures(const std::wstring& Path)
327{
328 // Shared for read and write, so a file still open in the program that wrote it can be read
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()) + ")");
333 }
334
335 LARGE_INTEGER size{};
336 if (!GetFileSizeEx(file, &size)) {
337 CloseHandle(file);
338 throw std::runtime_error("cannot get the file's size");
339 }
340 if ((ULONGLONG)size.QuadPart > PANO_ML_MAX_FILE_SIZE) {
341 CloseHandle(file);
342 throw std::runtime_error("the file is larger than " + std::to_string(PANO_ML_MAX_FILE_SIZE) + " bytes");
343 }
344
345 std::vector<uint8_t> data((size_t)size.QuadPart);
346 size_t read = 0;
347 while (read < data.size()) {
348 DWORD chunk = (DWORD)std::min<size_t>(data.size() - read, 1 << 24);
349 DWORD got = 0;
350 if (!ReadFile(file, data.data() + read, chunk, &got, NULL) || got == 0) {
351 break; // the file shrank; score what was read
352 }
353 read += got;
354 }
355 CloseHandle(file);
356 data.resize(read);
357 return ExtractPeFeatures(data.data(), data.size());
358}
#define PANO_ML_MAX_FILE_SIZE
Files larger than this are not scored (the features are computed over the whole file).
Definition PanoptesML.h:17
@ FEATURE_IMPORTED_FUNCTIONS
Definition PanoptesML.h:42
@ FEATURE_HAS_RELOCATIONS
Definition PanoptesML.h:46
@ FEATURE_HAS_SIGNATURE
Definition PanoptesML.h:43
@ FEATURE_IS_PE
Definition PanoptesML.h:31
@ FEATURE_LOG_SIZE
Definition PanoptesML.h:30
@ FEATURE_IMPORTED_DLLS
Definition PanoptesML.h:41
@ FEATURE_ENTRY_OUTSIDE_EXECUTABLE
Definition PanoptesML.h:40
@ FEATURE_ENTROPY
Definition PanoptesML.h:29
@ FEATURE_IS_64BIT
Definition PanoptesML.h:32
@ FEATURE_SECTION_ENTROPY_MAX
Definition PanoptesML.h:36
@ FEATURE_HAS_TLS
Definition PanoptesML.h:44
@ FEATURE_IS_DLL
Definition PanoptesML.h:33
@ FEATURE_IMAGE_TO_FILE_RATIO
Definition PanoptesML.h:49
@ FEATURE_WRITABLE_EXECUTABLE_SECTIONS
Definition PanoptesML.h:39
@ FEATURE_HAS_RESOURCES
Definition PanoptesML.h:47
@ FEATURE_OVERLAY_RATIO
Definition PanoptesML.h:48
@ FEATURE_ZERO_TIMESTAMP
Definition PanoptesML.h:50
@ FEATURE_SUBSYSTEM_GUI
Definition PanoptesML.h:34
@ FEATURE_SECTION_ENTROPY_MIN
Definition PanoptesML.h:37
@ FEATURE_HAS_DEBUG
Definition PanoptesML.h:45
@ FEATURE_COUNT
Definition PanoptesML.h:51
@ FEATURE_SECTION_COUNT
Definition PanoptesML.h:35
@ FEATURE_BYTE_HISTOGRAM
Definition PanoptesML.h:28
@ FEATURE_SECTION_ENTROPY_MEAN
Definition PanoptesML.h:38
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.
size_t Size() const
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
Definition PanoptesML.h:55
The parts of a PE the features need.
DWORD AddressOfEntryPoint
DWORD SizeOfImage
std::vector< IMAGE_SECTION_HEADER > Sections
DWORD DataDirectoryCount
WORD Subsystem
IMAGE_DATA_DIRECTORY DataDirectories[IMAGE_NUMBEROF_DIRECTORY_ENTRIES]
IMAGE_FILE_HEADER FileHeader