Panoptes 1.0.0
Endpoint Detection and Response
Loading...
Searching...
No Matches
dllmain.cpp
Go to the documentation of this file.
1#include "PanoptesML.h"
2#include <algorithm>
3#include <cstring>
4#include <iostream>
5#include <mutex>
6#include <stdexcept>
7
8// The model is loaded on the first scan and kept for the container's lifetime: loading it is
9// far slower than scoring a file. A model that fails to load is not retried until the container
10// restarts
11static std::once_flag g_ModelLoad;
12static std::string g_ModelError; // why the model didn't load; set once, with g_Model
13
14// Deliberately a plain pointer, not a static unique_ptr: a static's destructor runs during
15// DLL_PROCESS_DETACH, and at process exit Windows has already ended ONNX Runtime's threads by
16// then, so tearing down its session and thread pool there reads freed memory and crashes or
17// hangs (ORT documents not destroying sessions during DLL unload). PanoUnbind frees it while the
18// threads are alive; at process exit the memory is reclaimed with the process
19static MlModel* g_Model = nullptr;
20
21static MlModel* GetModel()
22{
23 std::call_once(g_ModelLoad, [] {
24 // The model built into the DLL when there is one (encrypted, see model_seal.cpp), and
25 // otherwise model.onnx from the DLL's folder
26 std::wstring path = L"the embedded model"; // what failed, for the message below
27 std::vector<uint8_t> embedded;
28 try {
29 bool isEmbedded = LoadEmbeddedModel(embedded);
30 if (!isEmbedded) {
32 }
33 if (isEmbedded) {
34 g_Model = new MlModel(embedded.data(), embedded.size(), "embedded model.onnx");
35 }
36 else {
37 g_Model = new MlModel(path);
38 }
39 }
40 catch (const std::exception& e) {
41 g_ModelError = e.what();
42 std::wcerr << L"PanoptesML: cannot load " << path << L": ";
43 std::cerr << e.what() << std::endl;
44 }
45 if (!embedded.empty()) {
46 SecureZeroMemory(embedded.data(), embedded.size());
47 }
48 });
49 return g_Model;
50}
51
52static std::wstring Widen(const std::string& Text)
53{
54 int length = MultiByteToWideChar(CP_UTF8, 0, Text.c_str(), (int)Text.size(), NULL, 0);
55 std::wstring out(length, L'\0');
56 MultiByteToWideChar(CP_UTF8, 0, Text.c_str(), (int)Text.size(), out.data(), length);
57 return out;
58}
59
60BOOL APIENTRY DllMain(HMODULE module, DWORD reason, LPVOID reserved)
61{
62 UNREFERENCED_PARAMETER(reserved);
63 if (reason == DLL_PROCESS_ATTACH) {
64 DisableThreadLibraryCalls(module);
65 }
66 return TRUE;
67}
68
72extern "C" PANO_API int PanoBind(int ContainerPort)
73{
75 if (!client.Hello(ExtensibilityType::EXTENSIBILITY_TYPE_ML, ContainerPort)) {
76 return 0;
77 }
78 return ContainerPort;
79}
80
87extern "C" PANO_API bool PanoEntry(PeScan* data)
88{
89 MlScanResult result;
90 bool scored = false;
91 // No exception may leave this extern "C" export: it would end the container
92 try {
93 MlModel* model = GetModel();
94 if (model == nullptr) {
95 result.Error = "cannot load the model: " + g_ModelError;
96 }
97 else {
98 result.Model = model->Name();
99 PeFeatures features = ExtractPeFeatures(Widen(data->PePath));
100 result.IsPe = features.IsPe;
101 if (!features.IsPe) {
102 // The model is trained on PE files only (EMBER2024's Win32, Win64 and .NET
103 // records); its score for anything else means nothing
104 result.Error = "not a PE file; the model only scores PE files";
105 }
106 else {
107 result.Score = model->Score(features.Values);
108 result.Malicious = result.Score >= PANO_ML_THRESHOLD;
109 scored = true;
110 }
111 }
112 }
113 catch (const std::exception& e) {
114 // Ort::Exception derives from std::exception. A file deleted or locked before its scan,
115 // or one over the size limit, is common
116 result.Error = e.what();
117 std::cerr << "PanoptesML scan of " << data->PePath << " failed: " << e.what() << std::endl;
118 }
119
120 try {
122 return client.SendResults_ML(data->PePath, data->FileHash, result) && scored;
123 }
124 catch (const std::exception& e) {
125 std::cerr << "PanoptesML: reporting " << data->PePath << " failed: " << e.what() << std::endl;
126 return false;
127 }
128}
129
130#pragma region Test interface
131
132// tools/mlquery declares the same layout; no padding, so the size is the sum of the fields
133static_assert(sizeof(PanoMlTestResult) == 7 * 4 + FEATURE_COUNT * 4 + 128 + 512,
134 "PanoMlTestResult changed: update tools/mlquery/main.go");
135
136static void CopyText(char* Destination, size_t Size, const std::string& Text)
137{
138 strncpy_s(Destination, Size, Text.c_str(), _TRUNCATE);
139}
140
141extern "C" PANO_API int PanoMlScoreFile(const wchar_t* Path, PanoMlTestResult* Result)
142{
143 // A caller built against another layout gets nothing written, rather than a struct overrun
144 if (Result == nullptr || Result->StructSize != sizeof(PanoMlTestResult)) {
145 return PANO_ML_TEST_FAILED;
146 }
147 ZeroMemory(Result, sizeof(*Result));
148 Result->StructSize = sizeof(PanoMlTestResult);
150 Result->FeatureCount = FEATURE_COUNT;
152 if (Path == nullptr) {
153 CopyText(Result->Error, sizeof(Result->Error), "no path");
154 return PANO_ML_TEST_FAILED;
155 }
156
157 // No exception may leave an extern "C" export
158 try {
159 PeFeatures features = ExtractPeFeatures(std::wstring(Path));
160 std::copy(features.Values.begin(), features.Values.end(), Result->Features);
161 Result->IsPe = features.IsPe ? 1 : 0;
162
163 MlModel* model = GetModel();
164 if (model == nullptr) {
165 CopyText(Result->Error, sizeof(Result->Error), "cannot load the model: " + g_ModelError);
167 }
168 // The raw score is kept for testing, but as in PanoEntry a file that isn't a PE gets no
169 // verdict: the model is trained on PE files only
170 Result->Score = model->Score(features.Values);
171 Result->Malicious = features.IsPe && Result->Score >= PANO_ML_THRESHOLD ? 1 : 0;
172 CopyText(Result->Model, sizeof(Result->Model), model->Name());
173 return PANO_ML_TEST_OK;
174 }
175 catch (const std::exception& e) {
176 CopyText(Result->Error, sizeof(Result->Error), e.what());
177 return PANO_ML_TEST_FAILED;
178 }
179}
180
181extern "C" PANO_API int PanoMlFeatureName(int Index, char* Buffer, int BufferSize)
182{
183 const char* name = Index >= 0 ? FeatureName((size_t)Index) : nullptr;
184 if (name == nullptr || Buffer == nullptr) {
185 return -1;
186 }
187 size_t length = strlen(name);
188 if (BufferSize <= 0 || length >= (size_t)BufferSize) {
189 return -1;
190 }
191 memcpy(Buffer, name, length + 1);
192 return (int)length;
193}
194
195#pragma endregion
196
198extern "C" PANO_API bool PanoUnbind()
199{
200 // No scan runs after this: the container calls it once, when it shuts down
201 delete g_Model;
202 g_Model = nullptr;
203 return true;
204}
#define PANO_API
@ EXTENSIBILITY_TYPE_ML
#define PANO_ML_THRESHOLD
Score at or above which a file is reported as malicious.
Definition PanoptesML.h:14
#define PANO_ML_TEST_OK
PanoMlScoreFile results.
Definition PanoptesML.h:142
std::wstring ModuleDirectory()
The folder this DLL was loaded from, with a trailing backslash.
Definition ml_model.cpp:122
#define PANO_ML_FEATURE_VERSION
Version of the feature layout below. A model is trained for one layout; change this whenever a featur...
Definition PanoptesML.h:23
bool LoadEmbeddedModel(std::vector< uint8_t > &Model)
The model built into the DLL (an encrypted RCDATA resource, see tools/sealmodel), decrypted into Mode...
#define PANO_ML_TEST_FAILED
Definition PanoptesML.h:143
#define PANO_ML_MODEL_FILE
The model file, loaded from the folder PanoptesML.dll is in (ext).
Definition PanoptesML.h:11
#define PANO_ML_TEST_NO_MODEL
Definition PanoptesML.h:144
const char * FeatureName(size_t Index)
The name of feature Index, or nullptr when it is out of range.
@ FEATURE_COUNT
Definition PanoptesML.h:51
PeFeatures ExtractPeFeatures(const std::wstring &Path)
Reads a file and computes its static features. The file is only read, never run or loaded....
An ONNX model that scores a feature vector. The model must take one float tensor of shape [1,...
Definition PanoptesML.h:73
float Score(const std::vector< float > &Features)
Runs the model on one file's features. Returns the malicious probability.
Definition ml_model.cpp:99
const std::string & Name() const
Definition PanoptesML.h:87
The Panoptes Service client used to talk to the service over gRPC.
bool SendResults_ML(const std::string &PePath, const std::string &FileHash, const MlScanResult &Result)
bool Hello(ExtensibilityType extensibilityType, std::string port)
The Hello function sends a Hello message to the Panoptes main service from the container.
ExtensibilityCore::PanoBindPtr PanoBind
Definition container.cpp:11
ExtensibilityCore::PanoEntryPtr PanoEntry
Definition container.cpp:12
PANO_API int PanoMlScoreFile(const wchar_t *Path, PanoMlTestResult *Result)
Computes a file's features and scores them with the model (embedded, or model.onnx from the DLL's fol...
Definition dllmain.cpp:141
PANO_API bool PanoUnbind()
Called once when the container shuts down.
Definition dllmain.cpp:198
PANO_API int PanoMlFeatureName(int Index, char *Buffer, int BufferSize)
Copies the name of feature Index (e.g. "byte_4d", "section_entropy_max") into Buffer.
Definition dllmain.cpp:181
BOOL APIENTRY DllMain(HMODULE module, DWORD reason, LPVOID reserved)
Definition dllmain.cpp:60
One file's result, as sent to the service.
Definition PanoptesML.h:111
std::string Model
Definition PanoptesML.h:115
std::string Error
Definition PanoptesML.h:116
One file's result for a test tool. Every field has a fixed size, so a caller in any language can decl...
Definition PanoptesML.h:128
int32_t FeatureCount
Definition PanoptesML.h:131
uint32_t StructSize
Definition PanoptesML.h:129
char Model[128]
Definition PanoptesML.h:137
char Error[512]
Definition PanoptesML.h:138
float Features[FEATURE_COUNT]
Definition PanoptesML.h:136
int32_t FeatureVersion
Definition PanoptesML.h:130
std::vector< float > Values
Definition PanoptesML.h:55
The information about the file to be scanned that passed between the container, extensibility and the...
std::string FileHash
std::string PePath