Panoptes 1.0.0
Endpoint Detection and Response
Loading...
Searching...
No Matches
grpc.cpp File Reference
#include <grpcpp/grpcpp.h>
#include "panoptes.grpc.pb.h"
#include "panoptes_service.h"
#include "grpc.hpp"
#include "hash.h"
#include "pano_log.h"
#include "utils.h"
#include "service_constants.h"
#include "tray_notifications.h"
#include "Configuration.hpp"
#include "detector.h"
#include "detector_stream.h"
#include "process_images.h"
#include <atomic>
#include <map>
#include <vector>
#include <string>
#include <algorithm>
#include <filesystem>
#include <regex>
#include <mutex>
#include <chrono>

Go to the source code of this file.

Classes

class  PanoptesImpl
 The PanoptesImpl class is a class that implements the PanoptesExtensibility::Service interface from the gRPC class. More...

Macros

#define PANO_SCAN_TIMEOUT_SECONDS   120
#define PANO_DETECTOR_POLL_MS   250
#define PANO_SERVER_SHUTDOWN_GRACE_MS   2000

Functions

bool MoveFileToQuarantine (std::string filePath)
 Moves a file into C:\ProgramData\Panoptes\Quarantine.
bool GetRegistryPortValue (DWORD &portValue)
bool CheckIfMalicious (std::string jsonString)
bool CreateRegistryEntryWithPort (DWORD dwPort)
std::string CleanUpProtobufMessage (std::string msg)
void SelfQueuePeScan (std::string pePath, std::string fileHash)
VOID StopServiceServer ()
 Shuts down the server RunServiceServer started, cancelling calls still in flight after a short grace period, so RunServiceServer returns. Safe to call if it never started.
void RunServiceServer (LPVOID lpParam)

Variables

std::unique_ptr< PanoptesExtensibility::Stub > stub_
std::unique_ptr< PanoptesService::Stub > selfStub_
PanoptesContext * serviceContext

Macro Definition Documentation

◆ PANO_DETECTOR_POLL_MS

#define PANO_DETECTOR_POLL_MS   250

Definition at line 51 of file grpc.cpp.

◆ PANO_SCAN_TIMEOUT_SECONDS

#define PANO_SCAN_TIMEOUT_SECONDS   120

Definition at line 43 of file grpc.cpp.

◆ PANO_SERVER_SHUTDOWN_GRACE_MS

#define PANO_SERVER_SHUTDOWN_GRACE_MS   2000

Definition at line 583 of file grpc.cpp.

Referenced by StopServiceServer().

Function Documentation

◆ CheckIfMalicious()

bool CheckIfMalicious ( std::string jsonString)

Definition at line 133 of file grpc.cpp.

133 {
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}

◆ CleanUpProtobufMessage()

std::string CleanUpProtobufMessage ( std::string msg)

Definition at line 195 of file grpc.cpp.

195 {
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}
std::string FormatTime(const std::time_t &time)
Definition utils.cpp:99

References FormatTime().

◆ CreateRegistryEntryWithPort()

bool CreateRegistryEntryWithPort ( DWORD dwPort)

Definition at line 152 of file grpc.cpp.

152 {
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}
#define PANOPTES_REG_ROOT
Definition container.cpp:24

References PANOPTES_REG_ROOT.

Referenced by RunServiceServer().

◆ GetRegistryPortValue()

bool GetRegistryPortValue ( DWORD & portValue)

Definition at line 88 of file grpc.cpp.

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}

References PANOPTES_REG_ROOT.

Referenced by SelfQueuePeScan().

◆ MoveFileToQuarantine()

bool MoveFileToQuarantine ( std::string filePath)

Moves a file into C:\ProgramData\Panoptes\Quarantine.

Returns
Whether the file was moved

Definition at line 71 of file grpc.cpp.

71 {
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}

Referenced by RespondToDetection().

◆ RunServiceServer()

void RunServiceServer ( LPVOID lpParam)

Definition at line 598 of file grpc.cpp.

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}
The PanoptesImpl class is a class that implements the PanoptesExtensibility::Service interface from t...
PanoptesContext * serviceContext
Definition grpc.cpp:33
bool CreateRegistryEntryWithPort(DWORD dwPort)
Definition grpc.cpp:152

References CreateRegistryEntryWithPort(), and serviceContext.

Referenced by WinMain().

◆ SelfQueuePeScan()

void SelfQueuePeScan ( std::string pePath,
std::string fileHash )

Definition at line 338 of file grpc.cpp.

338 {
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}
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...
bool GetRegistryPortValue(DWORD &portValue)
Definition grpc.cpp:88
std::unique_ptr< PanoptesService::Stub > selfStub_
Definition grpc.cpp:32

References GetRegistryPortValue(), Configuration::IsPathInList(), selfStub_, and serviceContext.

◆ StopServiceServer()

VOID StopServiceServer ( )

Shuts down the server RunServiceServer started, cancelling calls still in flight after a short grace period, so RunServiceServer returns. Safe to call if it never started.

Definition at line 585 of file grpc.cpp.

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}
void StopDetectorStreams()
Wakes every subscriber's Wait with false and refuses new subscribers, so the SubscribeEvents calls re...
#define PANO_SERVER_SHUTDOWN_GRACE_MS
Definition grpc.cpp:583

References PANO_SERVER_SHUTDOWN_GRACE_MS, and StopDetectorStreams().

Variable Documentation

◆ selfStub_

std::unique_ptr<PanoptesService::Stub> selfStub_

Definition at line 32 of file grpc.cpp.

Referenced by SelfQueuePeScan().

◆ serviceContext

PanoptesContext* serviceContext

Definition at line 33 of file grpc.cpp.

Referenced by RunServiceServer(), SelfQueuePeScan(), and WinMain().

◆ stub_

std::unique_ptr<PanoptesExtensibility::Stub> stub_

Definition at line 31 of file grpc.cpp.