Panoptes 1.0.0
Endpoint Detection and Response
Loading...
Searching...
No Matches
grpc.cpp
Go to the documentation of this file.
1#include <grpcpp/grpcpp.h>
2#include "panoptes.grpc.pb.h"
3
4#include "panoptes_service.h"
5#include "grpc.hpp"
6#include "hash.h"
7#include "pano_log.h"
8#include "utils.h"
9#include "service_constants.h"
10
11#include "tray_notifications.h"
12#include "Configuration.hpp"
13#include "detector.h"
14#include "detector_stream.h"
15#include "process_images.h"
16#include <atomic>
17#include <map>
18#include <vector>
19#include <string>
20#include <algorithm>
21#include <filesystem>
22#include <regex>
23#include <mutex>
24#include <chrono>
25#include <filesystem>
26
27using grpc::Channel;
28using grpc::ClientContext;
29using grpc::Status;
30
31std::unique_ptr<PanoptesExtensibility::Stub> stub_;
32std::unique_ptr<PanoptesService::Stub> selfStub_;
34
35// The containers that have registered (Hello), one per extension type. A container that
36// restarts registers again on its new port and replaces its old entry
37static std::mutex g_containersLock;
38static std::map<ContainerType, int> g_containers;
39
40// Scans sent to a container whose result hasn't come back yet, by file hash. A scan that takes
41// longer than PANO_SCAN_TIMEOUT_SECONDS is taken to have failed (an extension can drop a file it
42// couldn't scan): the next request for the file sends it again, and a scanner waiting on it stops
43#define PANO_SCAN_TIMEOUT_SECONDS 120
44static std::mutex g_inFlightLock;
45static std::map<std::string, std::map<ContainerType, std::chrono::steady_clock::time_point>> g_inFlight;
46// The port the server listens on, set once it has started. The detector RPCs use it to find
47// the calling process
48static std::atomic<int> g_serverPort{ 0 };
49
50// How long a SubscribeEvents call waits for events before checking whether it was cancelled
51#define PANO_DETECTOR_POLL_MS 250
52
53// A Windows header defines PERMISSION_DENIED as a macro, which breaks StatusCode::PERMISSION_DENIED
54#pragma push_macro("PERMISSION_DENIED")
55#undef PERMISSION_DENIED
56static ::grpc::Status PermissionDenied(const std::string& why) {
57 return ::grpc::Status(::grpc::StatusCode::PERMISSION_DENIED, why);
58}
59#pragma pop_macro("PERMISSION_DENIED")
60
61// "DETECTION_SEVERITY_MEDIUM" without its prefix, lowercased: "medium"
62static std::string EnumWord(const std::string& name, const std::string& prefix) {
63 std::string word = name.rfind(prefix, 0) == 0 ? name.substr(prefix.size()) : name;
64 std::transform(word.begin(), word.end(), word.begin(), [](unsigned char c) { return (char)std::tolower(c); });
65 return word;
66}
67
68
69namespace fs = std::filesystem;
70
71bool MoveFileToQuarantine(std::string filePath) {
72 std::string quarantinePath = "C:\\ProgramData\\Panoptes\\Quarantine";
73
74 std::error_code error;
75 fs::create_directories(quarantinePath, error);
76 std::filesystem::path sourcePath(filePath);
77 std::filesystem::path destinationPath = fs::path(quarantinePath) / sourcePath.filename();
78 try {
79 fs::rename(sourcePath, destinationPath);
80 }
81 catch (const std::filesystem::filesystem_error& e) {
82 std::cerr << "Error moving file to quarantine: " << e.what() << std::endl;
83 return false;
84 }
85 return true;
86}
87
88bool GetRegistryPortValue(DWORD& portValue)
89{
90 HKEY hKey;
91 DWORD dwType = REG_DWORD;
92 DWORD dwSize = sizeof(DWORD);
93
94 // Open the key
95 LONG lResult = RegOpenKeyExA(
97 "SOFTWARE\\Panoptes",
98 0,
99 KEY_READ,
100 &hKey
101 );
102
103 if (lResult != ERROR_SUCCESS) {
104 std::cerr << "Error opening registry key. Error code: " << lResult << std::endl;
105 return false;
106 }
107
108 // Read the SRV_PORT value
109 lResult = RegQueryValueExA(
110 hKey,
111 "SRV_PORT",
112 NULL,
113 &dwType,
114 reinterpret_cast<LPBYTE>(&portValue),
115 &dwSize
116 );
117
118 RegCloseKey(hKey);
119
120 if (lResult != ERROR_SUCCESS) {
121 std::cerr << "Error reading registry value. Error code: " << lResult << std::endl;
122 return false;
123 }
124
125 if (dwType != REG_DWORD) {
126 std::cerr << "Unexpected value type in registry." << std::endl;
127 return false;
128 }
129
130 return true;
131}
132
133bool CheckIfMalicious(std::string jsonString) {
134 nlohmann::json jsonObject = nlohmann::json::parse(jsonString);
135 if (jsonObject.contains("yara_scan") && jsonObject["yara_scan"].contains("detected_rules"))
136 {
137 nlohmann::json yaraObject = jsonObject["yara_scan"];
138 int detected_rules = yaraObject["detected_rules"].size();
139 if (detected_rules > 0) {
140 return true;
141 }
142 }
143 // PanoptesML's verdict: its score was at or above its threshold
144 if (jsonObject.contains("ml_scan") && jsonObject["ml_scan"].value("malicious", false))
145 {
146 return true;
147 }
148
149 return false;
150}
151
152bool CreateRegistryEntryWithPort(DWORD dwPort) {
153 HKEY hKey;
154 DWORD dwDisposition;
155
156 // Create or open the key
157 LONG lResult = RegCreateKeyExA(
159 "SOFTWARE\\Panoptes",
160 0,
161 NULL,
162 REG_OPTION_NON_VOLATILE,
163 KEY_ALL_ACCESS,
164 NULL,
165 &hKey,
166 &dwDisposition
167 );
168
169 if (lResult != ERROR_SUCCESS) {
170 std::cerr << "Error creating/opening registry key. Error code: " << lResult << std::endl;
171 return false;
172 }
173
174 // Set the SRV_PORT value
175 lResult = RegSetValueExA(
176 hKey,
177 "SRV_PORT",
178 0,
179 REG_DWORD,
180 reinterpret_cast<const BYTE*>(&dwPort),
181 sizeof(dwPort)
182 );
183
184 if (lResult != ERROR_SUCCESS) {
185 std::cerr << "Error setting registry value. Error code: " << lResult << std::endl;
186 RegCloseKey(hKey);
187 return false;
188 }
189
190 RegCloseKey(hKey);
191 std::cout << "Registry entry created successfully." << std::endl;
192 return true;
193}
194
195std::string CleanUpProtobufMessage(std::string msg) {
196 size_t pos;
197 while ((pos = msg.find("\\u0000")) != std::string::npos) {
198 msg.erase(pos, 6);
199 }
200
201 nlohmann::json j = nlohmann::json::parse(msg);
202 std::time_t now = std::time(nullptr);
203 std::string formattedTime = FormatTime(now);
204 j["Time"] = std::string(formattedTime);
205 std::string dumpAgain = j.dump();
206
207 return dumpAgain;
208}
209
211 std::string server_url = "localhost:" + std::to_string(containerPort);
212 std::shared_ptr<grpc::Channel> channel = grpc::CreateChannel(server_url, grpc::InsecureChannelCredentials());
213 stub_ = PanoptesExtensibility::NewStub(channel);
214}
215
216bool PanoptesContainerClient::SendPeScanRequest(std::string pePath, std::string fileHash) {
217 AckMessage reply;
218 ClientContext context;
219
220 PeScanInfo request;
221 request.set_file_hash(fileHash);
222 request.set_portable_executable_path(pePath);
223
224 Status status = stub_->PEScan(&context, request, &reply);
225 if (!status.ok()) {
226 std::cout << status.error_code() << ": " << status.error_message() << std::endl;
227 }
228
229 return reply.ack_type();
230}
231
233static const char* ResultKey(ContainerType type) {
234 switch (type) {
235 case CONTAINER_TYPE_YARA: return "yara_scan";
236 case CONTAINER_TYPE_ML: return "ml_scan";
237 default: return nullptr;
238 }
239}
240
242static bool SendPeScan(int port, const std::string& pePath, const std::string& fileHash) {
243 // A stub per call: QueuePeScan runs on several server threads at once
244 auto channel = grpc::CreateChannel("localhost:" + std::to_string(port), grpc::InsecureChannelCredentials());
245 auto stub = PanoptesExtensibility::NewStub(channel);
246 ClientContext context;
247 context.set_deadline(std::chrono::system_clock::now() + std::chrono::seconds(5)); // it only queues the scan
248
249 PeScanInfo request;
250 request.set_file_hash(fileHash);
251 request.set_portable_executable_path(pePath);
252 AckMessage reply;
253 Status status = stub->PEScan(&context, request, &reply);
254 if (!status.ok()) {
255 std::cerr << "Scan request to the container on port " << port << " failed: " << status.error_message() << std::endl;
256 return false;
257 }
258 return reply.ack_type() == AckType::SUCCESS;
259}
260
264static std::vector<std::string> DispatchScans(const std::string& pePath, const std::string& fileHash, const std::string& entry, bool poll) {
265 nlohmann::json stored = entry.empty() ? nlohmann::json::object() : nlohmann::json::parse(entry, nullptr, false);
266 if (!stored.is_object()) {
267 stored = nlohmann::json::object();
268 }
269 std::map<ContainerType, int> containers;
270 {
271 std::lock_guard<std::mutex> lock(g_containersLock);
272 containers = g_containers;
273 }
274
275 std::vector<std::string> pending;
276 std::vector<std::pair<ContainerType, int>> toSend;
277 auto now = std::chrono::steady_clock::now();
278 auto expired = [now](std::chrono::steady_clock::time_point sent) {
279 return now - sent >= std::chrono::seconds(PANO_SCAN_TIMEOUT_SECONDS);
280 };
281 {
282 std::lock_guard<std::mutex> lock(g_inFlightLock);
283 auto& flights = g_inFlight[fileHash];
284 for (const auto& [type, port] : containers) {
285 const char* key = ResultKey(type);
286 if (key == nullptr || stored.contains(key)) {
287 continue;
288 }
289 auto flight = flights.find(type);
290 if (flight != flights.end() && !expired(flight->second)) {
291 pending.push_back(key); // sent, result not back yet
292 continue;
293 }
294 if (poll) {
295 continue; // never sent, or it gave up: nothing to wait for
296 }
297 flights[type] = now;
298 toSend.push_back({ type, port });
299 pending.push_back(key);
300 }
301 if (flights.empty()) {
302 g_inFlight.erase(fileHash);
303 }
304 // Files whose scans failed are never cleared by a result; drop them once they've expired
305 for (auto file = g_inFlight.begin(); file != g_inFlight.end();) {
306 for (auto flight = file->second.begin(); flight != file->second.end();) {
307 flight = expired(flight->second) ? file->second.erase(flight) : std::next(flight);
308 }
309 file = file->second.empty() ? g_inFlight.erase(file) : std::next(file);
310 }
311 }
312
313 for (const auto& [type, port] : toSend) {
314 if (!SendPeScan(port, pePath, fileHash)) {
315 std::lock_guard<std::mutex> lock(g_inFlightLock);
316 auto file = g_inFlight.find(fileHash);
317 if (file != g_inFlight.end()) {
318 file->second.erase(type);
319 }
320 pending.erase(std::remove(pending.begin(), pending.end(), std::string(ResultKey(type))), pending.end());
321 }
322 }
323 return pending;
324}
325
327static void ScanFinished(const std::string& fileHash, ContainerType type) {
328 std::lock_guard<std::mutex> lock(g_inFlightLock);
329 auto file = g_inFlight.find(fileHash);
330 if (file != g_inFlight.end()) {
331 file->second.erase(type);
332 if (file->second.empty()) {
333 g_inFlight.erase(file);
334 }
335 }
336}
337
338void SelfQueuePeScan(std::string pePath, std::string fileHash) {
339 auto configuration = serviceContext->config;
340 if (Configuration::IsPathInList(configuration->m_exclusions, pePath)) {
341 return;
342 }
343
344 DWORD containerPort = 0;
345 GetRegistryPortValue(containerPort);
346 std::string server_url = "localhost:" + std::to_string(containerPort);
347 std::shared_ptr<grpc::Channel> channel = grpc::CreateChannel(server_url, grpc::InsecureChannelCredentials());
348 selfStub_ = PanoptesService::NewStub(channel);
349
350 AckMessage reply;
351 ClientContext context;
352 PeScanInfo request;
353 request.set_file_hash(fileHash);
354 request.set_portable_executable_path(pePath);
355
356 Status status = selfStub_->QueuePeScan(&context, request, &reply);
357 if (!status.ok()) {
358 std::cout << status.error_code() << ": " << status.error_message() << std::endl;
359 }
360}
361
362class PanoptesImpl : public PanoptesService::Service {
363 ::grpc::Status ScanResults(::grpc::ServerContext* context, const ::ContainerReply* request, ::AckMessage* response) override {
364 google::protobuf::util::JsonPrintOptions options;
365 auto configuration = serviceContext->config;
366 options.add_whitespace = false;
367 // options.always_print_primitive_fields = true;
368 options.preserve_proto_field_names = true;
369 options.always_print_enums_as_ints = false;
370
371
372 std::string fileHash = request->file_hash();
373 std::string filePath = request->portable_executable_path();
374 std::string json_string;
375 // The log line, the database entry and the detection check below are all built from
376 // this JSON, so a scan result that cannot be converted is rejected rather than stored
377 // as an empty or partial entry
378 auto jsonStatus = google::protobuf::util::MessageToJsonString(*request, &json_string, options);
379 if (!jsonStatus.ok()) {
380 std::string message = "Failed to convert the scan result for " + filePath + " to JSON: " + jsonStatus.ToString();
381 std::cerr << message << std::endl;
382 return ::grpc::Status(::grpc::StatusCode::INTERNAL, message);
383 }
384 std::string cleanMsg = CleanUpProtobufMessage(json_string);
385 WriteToLogFile(cleanMsg + "\n");
386
387 switch (request->container_event_reply_case()) {
388 case ContainerReply::kYaraScan:
389 ScanFinished(fileHash, CONTAINER_TYPE_YARA);
390 break;
391 case ContainerReply::kMlScan:
392 ScanFinished(fileHash, CONTAINER_TYPE_ML);
393 break;
394 default:
395 break;
396 }
397
398 serviceContext->database = PanoptesDatabase();
399 auto loadedDB = serviceContext->database.load();
400 std::string entry = loadedDB.GetEntry(fileHash);
401 // Each extension's result is merged into the file's entry as it arrives. Notify (and
402 // quarantine) when a result makes the file malicious, not again for each later one
403 bool wasMalicious = !entry.empty() && CheckIfMalicious(entry);
404 if (entry.empty()) {
405 loadedDB.AddEntry(fileHash, cleanMsg);
406 entry = cleanMsg;
407 }
408 else
409 {
410 entry = loadedDB.UpdateEntry(fileHash, cleanMsg);
411 }
412
413 if (!wasMalicious && CheckIfMalicious(entry)) {
414 std::string displayMessage = "Malicious File Detected: " + GetBaseName(filePath);
415 TrayNotifications::Tray::ShowTrayIconBalloon("Panoptes EDR Detection", displayMessage.c_str());
416
417 if (configuration->m_quartine) {
418 MoveFileToQuarantine(filePath);
419 }
420 }
421
422 response->set_ack_type(SUCCESS);
423 return ::grpc::Status::OK;
424 }
425
426 ::grpc::Status QueuePeScan(::grpc::ServerContext* context, const ::PeScanInfo* request, ::AckMessage* response) override {
427 std::string fileToScan = request->portable_executable_path();
428 if (fileToScan.empty()) {
429 return ::grpc::Status(::grpc::StatusCode::INVALID_ARGUMENT, "PE path not provided");
430 }
431
432 auto configuration = serviceContext->config;
433 if (Configuration::IsPathInList(configuration->m_exclusions, fileToScan)) {
434 std::string message = "File is excluded from scan: " + fileToScan;
435 return ::grpc::Status(::grpc::StatusCode::UNKNOWN, message);
436 }
437
438 std::string fileHash = request->file_hash();
439 if (fileHash.empty()) {
440 fileHash = GenerateMD5(fileToScan);
441 if (fileHash.empty()) {
442 std::string message = "Failed to generate hash for " + fileToScan;
443 return ::grpc::Status(::grpc::StatusCode::INVALID_ARGUMENT, message);
444 }
445 }
446
447 // Every running extension scans the file: those whose result the stored entry doesn't
448 // have yet are sent it (a file scanned before PanoptesML was installed still gets its
449 // ML scan). Their results arrive through ScanResults
450 bool poll = request->poll();
451 auto loadedDB = serviceContext->database.load();
452 std::string entry = loadedDB.GetEntry(fileHash);
453 std::vector<std::string> pending = DispatchScans(fileToScan, fileHash, entry, poll);
454
455 response->set_ack_type(AckType::SUCCESS);
456 response->set_message(entry);
457 response->set_file_hash(fileHash);
458 for (const auto& key : pending) {
459 response->add_pending_scans(key);
460 }
461 // A scanner polling for the rest of the results gets them without another notification
462 if (!entry.empty() && !poll)
463 {
464 WriteToLogFile(entry + "\n");
465 if (CheckIfMalicious(entry)) {
466 std::string displayMessage = "Malicious File Detected: " + GetBaseName(fileToScan.c_str());
467 TrayNotifications::Tray::ShowTrayIconBalloon("Panoptes EDR Detection", displayMessage.c_str());
468
469 if (configuration->m_quartine) {
470 MoveFileToQuarantine(request->portable_executable_path());
471 }
472 }
473 }
474
475 return ::grpc::Status::OK;
476 }
477
478 ::grpc::Status HealthCheck(::grpc::ServerContext* context, const ::HealthCheckRequest* request, ::HealthCheckResponse* response) override {
479 response->set_pong("pong");
480 return ::grpc::Status::OK;
481 }
482
483 ::grpc::Status Hello(::grpc::ServerContext* context, const ::ContainerInfo* request, ::AckMessage* response) override {
484 if (request->container_type() == NULL) {
485 return ::grpc::Status(::grpc::StatusCode::INVALID_ARGUMENT, "No container type provided");
486 }
487
488 std::cout << "Hello: " << request->container_type() << std::endl;
489
490 {
491 std::lock_guard<std::mutex> lock(g_containersLock);
492 g_containers[request->container_type()] = request->grpc_port();
493 }
494
495 response->set_ack_type(AckType::SUCCESS);
496 return ::grpc::Status::OK;
497 }
498
499 // Streams every logged event to the detector until it disconnects or the service stops
500 ::grpc::Status SubscribeEvents(::grpc::ServerContext* context, const ::DetectorHello* request, ::grpc::ServerWriter<::DetectorEvent>* writer) override {
501 std::string why;
502 if (!IsDetectorPeer(context->peer(), g_serverPort.load(), why)) {
503 std::cerr << "SubscribeEvents refused: " << why << std::endl;
504 return PermissionDenied(why);
505 }
506
507 std::vector<std::string> eventNames(request->event_names().begin(), request->event_names().end());
508 auto subscription = DetectorSubscription::Open(eventNames);
509 if (subscription == nullptr) {
510 return ::grpc::Status(::grpc::StatusCode::RESOURCE_EXHAUSTED, "too many detectors subscribed, or the service is stopping");
511 }
512 std::cout << "Detector " << request->version() << " subscribed to events" << std::endl;
513
514 std::vector<DetectorEventRecord> batch;
515 ::DetectorEvent message;
516 while (!context->IsCancelled() && subscription->Wait(batch, PANO_DETECTOR_POLL_MS)) {
517 for (auto& record : batch) {
518 message.set_sequence(record.Sequence);
519 message.set_timestamp(record.Timestamp);
520 message.set_json(std::move(record.Json));
521 // Blocks while the detector is behind; the publisher keeps queueing (or
522 // dropping) meanwhile, so the event threads are never held up
523 if (!writer->Write(message)) {
524 std::cout << "Detector disconnected" << std::endl;
525 return ::grpc::Status::OK;
526 }
527 }
528 }
529 return ::grpc::Status::OK;
530 }
531
532 // Logs a detection to pano.log, notifies, and carries out its action
533 ::grpc::Status ReportDetection(::grpc::ServerContext* context, const ::Detection* request, ::AckMessage* response) override {
534 std::string why;
535 if (!IsDetectorPeer(context->peer(), g_serverPort.load(), why)) {
536 std::cerr << "ReportDetection refused: " << why << std::endl;
537 return PermissionDenied(why);
538 }
539
540 std::string outcome = RespondToDetection(*request, *serviceContext->config);
541
542 // Not published to the detector: it already knows, and no rule matches on it
543 nlohmann::ordered_json event;
544 event["Event"] = "Detection";
545 event["Rule"] = request->rule();
546 event["Description"] = request->description();
547 // The same words the rules and detection.log use: "medium", "kill"
548 event["Severity"] = EnumWord(DetectionSeverity_Name(request->severity()), "DETECTION_SEVERITY_");
549 event["Action"] = EnumWord(DetectionAction_Name(request->action()), "DETECTION_ACTION_");
550 event["PID"] = request->process_id();
551 // The detector takes the image from the event, which is empty for processes that started
552 // before the service; the service may still know it
553 std::string image = request->image_path();
554 if (image.empty()) {
555 FILETIME matched;
556 matched.dwLowDateTime = (DWORD)(request->timestamp() & 0xFFFFFFFF);
557 matched.dwHighDateTime = (DWORD)((UINT64)request->timestamp() >> 32);
558 image = ResolveProcessImage(request->process_id(), request->timestamp() != 0 ? matched : CurrentFileTime());
559 }
560 event["Image"] = image;
561 // UTC in the format of every other line, so the log sorts and replays consistently
562 event["Time"] = FormatSystemTime(CurrentFileTime());
563 event["Response"] = outcome;
564 event["EventSequences"] = std::vector<uint64_t>(request->event_sequences().begin(), request->event_sequences().end());
565 WriteToLogFile(event.dump() + "\n");
566
567 std::string displayMessage = request->rule() + " (PID " + std::to_string(request->process_id()) + (image.empty() ? "" : ", " + GetBaseName(image)) + "): " + outcome;
568 TrayNotifications::Tray::ShowTrayIconBalloon("Panoptes EDR Detection", displayMessage.c_str());
569
570 response->set_ack_type(AckType::SUCCESS);
571 response->set_message(outcome);
572 return ::grpc::Status::OK;
573 }
574};
575
576// The running server, so StopServiceServer can shut it down from another thread.
577// g_serverStopping covers a stop that arrives before the server has been built
578static std::mutex g_serverLock;
579static grpc::Server* g_server = nullptr;
580static bool g_serverStopping = false;
581
582// How long calls in flight get to finish before StopServiceServer cancels them
583#define PANO_SERVER_SHUTDOWN_GRACE_MS 2000
584
586{
587 // Event streams only end when the detector disconnects, so they are ended first; otherwise
588 // each would hold up shutdown until the grace period runs out
590
591 std::lock_guard<std::mutex> lock(g_serverLock);
592 g_serverStopping = true;
593 if (g_server != nullptr) {
594 g_server->Shutdown(std::chrono::system_clock::now() + std::chrono::milliseconds(PANO_SERVER_SHUTDOWN_GRACE_MS));
595 }
596}
597
598void RunServiceServer(LPVOID lpParam)
599{
600 serviceContext = reinterpret_cast<PanoptesContext*>(lpParam);
601 PanoptesImpl service;
602 grpc::ServerBuilder builder;
603 int selected_port = 0;
604 std::string server_url = "localhost:0";
605
606 //Setting the server address to localhost:0 will allow the OS to assign an available port
607 builder.AddListeningPort(server_url, grpc::InsecureServerCredentials(), &selected_port);
608 builder.RegisterService(&service);
609
610 std::unique_ptr<grpc::Server> server(builder.BuildAndStart());
611 if (server == nullptr) {
612 auto threadError = &serviceContext->threadError;
613 bool threadState = threadError->load();
614 threadError->store(true);
615 return;
616 }
617
618 g_serverPort = selected_port;
619 bool updatedReg = CreateRegistryEntryWithPort(selected_port);
620 if (!updatedReg) {
621 auto threadError = &serviceContext->threadError;
622 bool threadState = threadError->load();
623 threadError->store(true);
624 }
625
626 {
627 std::lock_guard<std::mutex> lock(g_serverLock);
628 if (g_serverStopping) {
629 server->Shutdown();
630 }
631 g_server = server.get();
632 }
633
634 // Returns once StopServiceServer has shut the server down
635 server->Wait();
636
637 std::lock_guard<std::mutex> lock(g_serverLock);
638 g_server = nullptr;
639}
static bool IsPathInList(const std::vector< std::string > &patterns, const std::string &path)
Check whether a path matches any pattern in an exclusion list. A pattern with no wildcard matches eve...
static std::unique_ptr< DetectorSubscription > Open(const std::vector< std::string > &eventNames)
Registers a subscriber. Returns nullptr when the service is stopping or too many subscribers are conn...
PanoptesContainerClient(int ContainerPort)
Definition grpc.cpp:210
bool SendPeScanRequest(std::string PePath, std::string FileHash)
Definition grpc.cpp:216
The PanoptesImpl class is a class that implements the PanoptesExtensibility::Service interface from t...
static BOOL ShowTrayIconBalloon(LPCSTR pszTitle, LPCSTR pszText)
Queues a tray icon balloon notification and returns at once. A background thread shows queued balloon...
std::unique_ptr< PanoptesService::Stub > stub
Definition container.cpp:17
#define PANOPTES_REG_ROOT
Definition container.cpp:24
void HealthCheck()
The HealthCheck function is a thread that checks the health of the Panoptes main service.
Definition container.cpp:89
bool IsDetectorPeer(const std::string &peer, int serverPort, std::string &why)
Whether a gRPC peer is PanoptesDetector.exe from the service's folder. The server listens on localhos...
Definition detector.cpp:91
std::string RespondToDetection(const Detection &detection, const Configuration &configuration)
Carries out a detection's action and describes what was done, for the log. Kill and quarantine only h...
Definition detector.cpp:193
void StopDetectorStreams()
Wakes every subscriber's Wait with false and refuses new subscribers, so the SubscribeEvents calls re...
FILETIME CurrentFileTime()
The current time as a FILETIME, for events that carry no timestamp of their own.
PanoptesContext * serviceContext
Definition grpc.cpp:33
std::string CleanUpProtobufMessage(std::string msg)
Definition grpc.cpp:195
VOID StopServiceServer()
Shuts down the server RunServiceServer started, cancelling calls still in flight after a short grace ...
Definition grpc.cpp:585
bool CheckIfMalicious(std::string jsonString)
Definition grpc.cpp:133
bool CreateRegistryEntryWithPort(DWORD dwPort)
Definition grpc.cpp:152
bool GetRegistryPortValue(DWORD &portValue)
Definition grpc.cpp:88
void SelfQueuePeScan(std::string pePath, std::string fileHash)
Definition grpc.cpp:338
std::unique_ptr< PanoptesService::Stub > selfStub_
Definition grpc.cpp:32
void RunServiceServer(LPVOID lpParam)
Definition grpc.cpp:598
#define PANO_SERVER_SHUTDOWN_GRACE_MS
Definition grpc.cpp:583
#define PANO_DETECTOR_POLL_MS
Definition grpc.cpp:51
bool MoveFileToQuarantine(std::string filePath)
Moves a file into C:\ProgramData\Panoptes\Quarantine.
Definition grpc.cpp:71
std::string GenerateMD5(std::string filePath)
Generate an MD5 hash of a file using the Windows Crypto API https://learn.microsoft....
Definition hash.cpp:8
void WriteToLogFile(const std::string &message)
Appends a line to the event log: LOG_FOLDER\pano.log, continuing in pano1.log, pano2....
Definition pano_log.cpp:72
std::string ResolveProcessImage(DWORD processId, const FILETIME &time)
LookupProcessImage, falling back to asking Windows (QueryFullProcessImageName) for processes the serv...
std::unique_ptr< PanoptesService::Stub > stub_
Configuration * config
std::atomic< PanoptesDatabase > database
std::string FormatSystemTime(const FILETIME &ft)
The log's Time format: "2026/11/15 21:05:48.123", in the FILETIME's zone (UTC).
Definition utils.cpp:109
std::string GetBaseName(const std::string &path)
Definition utils.cpp:94
std::string FormatTime(const std::time_t &time)
Definition utils.cpp:99