1#include <grpcpp/grpcpp.h>
2#include "panoptes.grpc.pb.h"
28using grpc::ClientContext;
31std::unique_ptr<PanoptesExtensibility::Stub>
stub_;
37static std::mutex g_containersLock;
38static std::map<ContainerType, int> g_containers;
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;
48static std::atomic<int> g_serverPort{ 0 };
51#define PANO_DETECTOR_POLL_MS 250
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);
59#pragma pop_macro("PERMISSION_DENIED")
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); });
69namespace fs = std::filesystem;
72 std::string quarantinePath =
"C:\\ProgramData\\Panoptes\\Quarantine";
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();
79 fs::rename(sourcePath, destinationPath);
81 catch (
const std::filesystem::filesystem_error& e) {
82 std::cerr <<
"Error moving file to quarantine: " << e.what() << std::endl;
91 DWORD dwType = REG_DWORD;
92 DWORD dwSize =
sizeof(DWORD);
95 LONG lResult = RegOpenKeyExA(
103 if (lResult != ERROR_SUCCESS) {
104 std::cerr <<
"Error opening registry key. Error code: " << lResult << std::endl;
109 lResult = RegQueryValueExA(
114 reinterpret_cast<LPBYTE
>(&portValue),
120 if (lResult != ERROR_SUCCESS) {
121 std::cerr <<
"Error reading registry value. Error code: " << lResult << std::endl;
125 if (dwType != REG_DWORD) {
126 std::cerr <<
"Unexpected value type in registry." << std::endl;
134 nlohmann::json jsonObject = nlohmann::json::parse(jsonString);
135 if (jsonObject.contains(
"yara_scan") && jsonObject[
"yara_scan"].contains(
"detected_rules"))
137 nlohmann::json yaraObject = jsonObject[
"yara_scan"];
138 int detected_rules = yaraObject[
"detected_rules"].size();
139 if (detected_rules > 0) {
144 if (jsonObject.contains(
"ml_scan") && jsonObject[
"ml_scan"].value(
"malicious",
false))
157 LONG lResult = RegCreateKeyExA(
159 "SOFTWARE\\Panoptes",
162 REG_OPTION_NON_VOLATILE,
169 if (lResult != ERROR_SUCCESS) {
170 std::cerr <<
"Error creating/opening registry key. Error code: " << lResult << std::endl;
175 lResult = RegSetValueExA(
180 reinterpret_cast<const BYTE*
>(&dwPort),
184 if (lResult != ERROR_SUCCESS) {
185 std::cerr <<
"Error setting registry value. Error code: " << lResult << std::endl;
191 std::cout <<
"Registry entry created successfully." << std::endl;
197 while ((pos = msg.find(
"\\u0000")) != std::string::npos) {
201 nlohmann::json j = nlohmann::json::parse(msg);
202 std::time_t now = std::time(
nullptr);
204 j[
"Time"] = std::string(formattedTime);
205 std::string dumpAgain = j.dump();
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);
218 ClientContext context;
221 request.set_file_hash(fileHash);
222 request.set_portable_executable_path(pePath);
224 Status status =
stub_->PEScan(&context, request, &reply);
226 std::cout << status.error_code() <<
": " << status.error_message() << std::endl;
229 return reply.ack_type();
233static const char* ResultKey(ContainerType type) {
235 case CONTAINER_TYPE_YARA:
return "yara_scan";
236 case CONTAINER_TYPE_ML:
return "ml_scan";
237 default:
return nullptr;
242static bool SendPeScan(
int port,
const std::string& pePath,
const std::string& fileHash) {
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));
250 request.set_file_hash(fileHash);
251 request.set_portable_executable_path(pePath);
253 Status status =
stub->PEScan(&context, request, &reply);
255 std::cerr <<
"Scan request to the container on port " << port <<
" failed: " << status.error_message() << std::endl;
258 return reply.ack_type() == AckType::SUCCESS;
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();
269 std::map<ContainerType, int> containers;
271 std::lock_guard<std::mutex> lock(g_containersLock);
272 containers = g_containers;
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);
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)) {
289 auto flight = flights.find(type);
290 if (flight != flights.end() && !expired(flight->second)) {
291 pending.push_back(key);
298 toSend.push_back({ type, port });
299 pending.push_back(key);
301 if (flights.empty()) {
302 g_inFlight.erase(fileHash);
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);
309 file = file->second.empty() ? g_inFlight.erase(file) : std::next(file);
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);
320 pending.erase(std::remove(pending.begin(), pending.end(), std::string(ResultKey(type))), pending.end());
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);
344 DWORD containerPort = 0;
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);
351 ClientContext context;
353 request.set_file_hash(fileHash);
354 request.set_portable_executable_path(pePath);
356 Status status =
selfStub_->QueuePeScan(&context, request, &reply);
358 std::cout << status.error_code() <<
": " << status.error_message() << std::endl;
363 ::grpc::Status ScanResults(::grpc::ServerContext* context, const ::ContainerReply* request, ::AckMessage* response)
override {
364 google::protobuf::util::JsonPrintOptions options;
366 options.add_whitespace =
false;
368 options.preserve_proto_field_names =
true;
369 options.always_print_enums_as_ints =
false;
372 std::string fileHash = request->file_hash();
373 std::string filePath = request->portable_executable_path();
374 std::string json_string;
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);
387 switch (request->container_event_reply_case()) {
388 case ContainerReply::kYaraScan:
389 ScanFinished(fileHash, CONTAINER_TYPE_YARA);
391 case ContainerReply::kMlScan:
392 ScanFinished(fileHash, CONTAINER_TYPE_ML);
400 std::string entry = loadedDB.GetEntry(fileHash);
405 loadedDB.AddEntry(fileHash, cleanMsg);
410 entry = loadedDB.UpdateEntry(fileHash, cleanMsg);
414 std::string displayMessage =
"Malicious File Detected: " +
GetBaseName(filePath);
417 if (configuration->m_quartine) {
422 response->set_ack_type(SUCCESS);
423 return ::grpc::Status::OK;
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");
434 std::string message =
"File is excluded from scan: " + fileToScan;
435 return ::grpc::Status(::grpc::StatusCode::UNKNOWN, message);
438 std::string fileHash = request->file_hash();
439 if (fileHash.empty()) {
441 if (fileHash.empty()) {
442 std::string message =
"Failed to generate hash for " + fileToScan;
443 return ::grpc::Status(::grpc::StatusCode::INVALID_ARGUMENT, message);
450 bool poll = request->poll();
452 std::string entry = loadedDB.GetEntry(fileHash);
453 std::vector<std::string> pending = DispatchScans(fileToScan, fileHash, entry, poll);
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);
462 if (!entry.empty() && !poll)
466 std::string displayMessage =
"Malicious File Detected: " +
GetBaseName(fileToScan.c_str());
469 if (configuration->m_quartine) {
475 return ::grpc::Status::OK;
478 ::grpc::Status
HealthCheck(::grpc::ServerContext* context, const ::HealthCheckRequest* request, ::HealthCheckResponse* response)
override {
479 response->set_pong(
"pong");
480 return ::grpc::Status::OK;
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");
488 std::cout <<
"Hello: " << request->container_type() << std::endl;
491 std::lock_guard<std::mutex> lock(g_containersLock);
492 g_containers[request->container_type()] = request->grpc_port();
495 response->set_ack_type(AckType::SUCCESS);
496 return ::grpc::Status::OK;
500 ::grpc::Status SubscribeEvents(::grpc::ServerContext* context, const ::DetectorHello* request, ::grpc::ServerWriter<::DetectorEvent>* writer)
override {
503 std::cerr <<
"SubscribeEvents refused: " << why << std::endl;
504 return PermissionDenied(why);
507 std::vector<std::string> eventNames(request->event_names().begin(), request->event_names().end());
509 if (subscription ==
nullptr) {
510 return ::grpc::Status(::grpc::StatusCode::RESOURCE_EXHAUSTED,
"too many detectors subscribed, or the service is stopping");
512 std::cout <<
"Detector " << request->version() <<
" subscribed to events" << std::endl;
514 std::vector<DetectorEventRecord> batch;
515 ::DetectorEvent message;
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));
523 if (!writer->Write(message)) {
524 std::cout <<
"Detector disconnected" << std::endl;
525 return ::grpc::Status::OK;
529 return ::grpc::Status::OK;
533 ::grpc::Status ReportDetection(::grpc::ServerContext* context, const ::Detection* request, ::AckMessage* response)
override {
536 std::cerr <<
"ReportDetection refused: " << why << std::endl;
537 return PermissionDenied(why);
543 nlohmann::ordered_json event;
544 event[
"Event"] =
"Detection";
545 event[
"Rule"] = request->rule();
546 event[
"Description"] = request->description();
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();
553 std::string image = request->image_path();
556 matched.dwLowDateTime = (DWORD)(request->timestamp() & 0xFFFFFFFF);
557 matched.dwHighDateTime = (DWORD)((UINT64)request->timestamp() >> 32);
560 event[
"Image"] = image;
563 event[
"Response"] = outcome;
564 event[
"EventSequences"] = std::vector<uint64_t>(request->event_sequences().begin(), request->event_sequences().end());
567 std::string displayMessage = request->rule() +
" (PID " + std::to_string(request->process_id()) + (image.empty() ?
"" :
", " +
GetBaseName(image)) +
"): " + outcome;
570 response->set_ack_type(AckType::SUCCESS);
571 response->set_message(outcome);
572 return ::grpc::Status::OK;
578static std::mutex g_serverLock;
579static grpc::Server* g_server =
nullptr;
580static bool g_serverStopping =
false;
583#define PANO_SERVER_SHUTDOWN_GRACE_MS 2000
591 std::lock_guard<std::mutex> lock(g_serverLock);
592 g_serverStopping =
true;
593 if (g_server !=
nullptr) {
602 grpc::ServerBuilder builder;
603 int selected_port = 0;
604 std::string server_url =
"localhost:0";
607 builder.AddListeningPort(server_url, grpc::InsecureServerCredentials(), &selected_port);
608 builder.RegisterService(&service);
610 std::unique_ptr<grpc::Server> server(builder.BuildAndStart());
611 if (server ==
nullptr) {
613 bool threadState = threadError->load();
614 threadError->store(
true);
618 g_serverPort = selected_port;
622 bool threadState = threadError->load();
623 threadError->store(
true);
627 std::lock_guard<std::mutex> lock(g_serverLock);
628 if (g_serverStopping) {
631 g_server = server.get();
637 std::lock_guard<std::mutex> lock(g_serverLock);
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)
bool SendPeScanRequest(std::string PePath, std::string FileHash)
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
#define PANOPTES_REG_ROOT
void HealthCheck()
The HealthCheck function is a thread that checks the health of the Panoptes main service.
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...
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...
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
std::string CleanUpProtobufMessage(std::string msg)
VOID StopServiceServer()
Shuts down the server RunServiceServer started, cancelling calls still in flight after a short grace ...
bool CheckIfMalicious(std::string jsonString)
bool CreateRegistryEntryWithPort(DWORD dwPort)
bool GetRegistryPortValue(DWORD &portValue)
void SelfQueuePeScan(std::string pePath, std::string fileHash)
std::unique_ptr< PanoptesService::Stub > selfStub_
void RunServiceServer(LPVOID lpParam)
#define PANO_SERVER_SHUTDOWN_GRACE_MS
#define PANO_DETECTOR_POLL_MS
bool MoveFileToQuarantine(std::string filePath)
Moves a file into C:\ProgramData\Panoptes\Quarantine.
std::string GenerateMD5(std::string filePath)
Generate an MD5 hash of a file using the Windows Crypto API https://learn.microsoft....
void WriteToLogFile(const std::string &message)
Appends a line to the event log: LOG_FOLDER\pano.log, continuing in pano1.log, pano2....
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_
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).
std::string GetBaseName(const std::string &path)
std::string FormatTime(const std::time_t &time)