您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520
  1. // SNFMulti.hpp
  2. //
  3. // (C) Copyright 2006 - 2020 ARM Research Labs, LLC.
  4. // See www.armresearch.com for the copyright terms.
  5. //
  6. // 20060121_M
  7. // This file creates an API for multi-threaded systems to use the SNF engine.
  8. //
  9. // This API is C++ oriented, meaning it throws exceptions and so forth.
  10. // For use in shared objects and DLLs, the functions in here will be wrapped
  11. // in a C style interface appropriate to that platform.
  12. //
  13. // The interface is based on the following structure.
  14. //
  15. // The application "Opens" one or more rulebases.
  16. // The application "Opens" some number of scanners referencing opened rulebases.
  17. // Each scanner handles one thread's worth of scanning, so it is presumed that
  18. // each processing thread in the calling application will have one scanner to itself.
  19. //
  20. // Rulebases can be reloaded asynchronously. The scanner's grab a reference to the
  21. // rulebase each time they restart. The grabbing and swapping in of new rulebases is
  22. // a very short critical section.
  23. #pragma once
  24. #include <stdexcept>
  25. #include <sys/types.h>
  26. #include <sys/stat.h>
  27. #include <ctime>
  28. #include <string>
  29. #include "../CodeDweller/faults.hpp"
  30. #include "../CodeDweller/threading.hpp"
  31. #include "GBUdb.hpp"
  32. #include "FilterChain.hpp"
  33. #include "snf_engine.hpp"
  34. #include "snf_match.h"
  35. #include "snfCFGmgr.hpp"
  36. #include "snfLOGmgr.hpp"
  37. #include "snfNETmgr.hpp"
  38. #include "snfGBUdbmgr.hpp"
  39. #include "snfXCImgr.hpp"
  40. #include <cassert>
  41. namespace cd = codedweller;
  42. extern const char* SNF_ENGINE_VERSION;
  43. // snf Result Code Constants
  44. const int snf_SUCCESS = 0;
  45. const int snf_ERROR_CMD_LINE = 65;
  46. const int snf_ERROR_LOG_FILE = 66;
  47. const int snf_ERROR_RULE_FILE = 67;
  48. const int snf_ERROR_RULE_DATA = 68;
  49. const int snf_ERROR_RULE_AUTH = 73;
  50. const int snf_ERROR_MSG_FILE = 69;
  51. const int snf_ERROR_ALLOCATION = 70;
  52. const int snf_ERROR_BAD_MATRIX = 71;
  53. const int snf_ERROR_MAX_EVALS = 72;
  54. const int snf_ERROR_UNKNOWN = 99;
  55. // Settings & Other Constants
  56. const int snf_ScanHorizon = 32768; // Maximum length of message to check.
  57. const int snf_MAX_RULEBASES = 10; // 10 Rulebases is plenty. Most use just 1
  58. const int snf_MAX_SCANNERS = 500; // 500 Scanners at once should be plenty
  59. const int SHUTDOWN = -999; // Shutdown Cursor Value.
  60. // snfCFGPacket encapsulates configuration and rulebase data.
  61. // The rulebase handler can write to it.
  62. // Others can only read from it.
  63. // The engine handler creates and owns one of these. It uses it to
  64. // grab() and drop() cfg and rulebase data from the rulebase handler.
  65. class snf_RulebaseHandler; // We need to know this exists.
  66. class snfCFGPacket { // Our little bundle of, er, cfg stuff.
  67. friend class snf_RulebaseHandler; // RulebaseHandler has write access.
  68. private:
  69. snf_RulebaseHandler* MyRulebase; // Where to grab() and drop()
  70. TokenMatrix* MyTokenMatrix; // We combine the current token matrix
  71. snfCFGData* MyCFGData; // and the current cfg data for each scan.
  72. std::set<int> RulePanics; // Set of known rule panic IDs.
  73. public:
  74. snfCFGPacket(snf_RulebaseHandler* R); // Constructor grab()s the Rulebase.
  75. ~snfCFGPacket(); // Destructor drop()s the Rulebase.
  76. TokenMatrix* Tokens(); // Consumers read the Token Matrix and
  77. snfCFGData* Config(); // the snfCFGData.
  78. bool bad(); // If anything is missing it's not good.
  79. bool isRulePanic(int R); // Test for a rule panic.
  80. };
  81. class ScriptCaller : private cd::Thread { // Calls system() in separate thread.
  82. private:
  83. cd::Mutex MyMutex; // Protects internal data.
  84. std::string SystemCallText; // Text to send to system().
  85. cd::Timeout GuardTimer; // Guard time between triggers.
  86. volatile bool GoFlag; // Go flag true when triggered.
  87. volatile bool DieFlag; // Die flag when it's time to leave.
  88. std::string ScriptToRun(); // Safely grab the script.
  89. bool hasGuardExpired(); // True if guard time has expired.
  90. void myTask(); // Thread task overload.
  91. volatile int myLastResult; // Last result of system() call.
  92. public:
  93. ScriptCaller(std::string Name); // Constructor.
  94. ~ScriptCaller(); // Destructor.
  95. void SystemCall(std::string S); // Set system call text.
  96. void GuardTime(int T); // Change guard time.
  97. void trigger(); // Trigger if possible.
  98. int LastResult(); // Return myLastResult.
  99. const static cd::ThreadType Type; // The thread's type.
  100. const static cd::ThreadState CallingSystem; // State when in system() call.
  101. const static cd::ThreadState PendingGuardTime; // State when waiting for guard time.
  102. const static cd::ThreadState StandingBy; // State when waiting around.
  103. const static cd::ThreadState Disabled; // State when unable to run.
  104. };
  105. class snf_Reloader : private cd::Thread { // Rulebase maintenance thread.
  106. private:
  107. snf_RulebaseHandler& MyRulebase; // We know our rulebase.
  108. bool TimeToStop; // We know if it's time to stop.
  109. std::string RulebaseFileCheckName; // We keep track of these files.
  110. std::string ConfigFileCheckName;
  111. std::string IgnoreListCheckFileName;
  112. time_t RulebaseFileTimestamp; // We watch their timestamps.
  113. time_t ConfigurationTimestamp;
  114. time_t IgnoreListTimestamp;
  115. void captureFileStats(); // Get stats for later comparison.
  116. bool StatsAreDifferent(); // Check file stats for changes.
  117. void myTask(); // How do we do this refresh thing?
  118. ScriptCaller RulebaseGetter; // Reloader owns a RulebaseGetter.
  119. bool RulebaseGetterIsTurnedOn; // True if we should run the getter.
  120. void captureGetterConfig(); // Get RulebaseGetter config.
  121. public:
  122. snf_Reloader(snf_RulebaseHandler& R); // Setup takes some work.
  123. ~snf_Reloader(); // Tear down takes some work.
  124. const static cd::ThreadType Type; // The thread's type.
  125. };
  126. class snf_RulebaseHandler { // Engine Core Manager.
  127. friend class snfCFGPacket;
  128. private:
  129. cd::Mutex MyMutex; // This handler's mutex.
  130. snf_Reloader* MyReloader; // Reloader engine (when in use).
  131. int volatile ReferenceCount; // Associated scanners count.
  132. snfCFGData* volatile Configuration; // Configuration for this handler.
  133. TokenMatrix* volatile Rulebase; // Rulebase for this handler.
  134. int volatile CurrentCount; // Active current scanners count.
  135. TokenMatrix* volatile OldRulebase; // Retiring rulebase holder.
  136. int volatile RetiringCount; // Active retiring scanners count.
  137. bool volatile RefreshInProgress; // Flag for locking the refresh process.
  138. int volatile MyGeneration; // Generation (reload) number.
  139. void _snf_LoadNewRulebase(); // Internal function to load new rulebase.
  140. cd::Mutex XCIServerCommandMutex; // XCI Server Command Serializer.
  141. snfXCIServerCommandHandler* myXCIServerCommandHandler; // ptr to Installed Srv Cmd Handler.
  142. void grab(snfCFGPacket& CP); // Activate this Rulebase for a scan.
  143. void drop(snfCFGPacket& CP); // Deactiveate this Rulebase after it.
  144. public:
  145. class ConfigurationError : public std::runtime_error { // When the configuration won't load.
  146. public: ConfigurationError(const std::string& w):runtime_error(w) {}
  147. };
  148. class FileError : public std::runtime_error { // Exception: rulebase file won't load.
  149. public: FileError(const std::string& w):runtime_error(w) {}
  150. };
  151. class AuthenticationError : public std::runtime_error { // Exception when authentication fails.
  152. public: AuthenticationError(const std::string& w):runtime_error(w) {}
  153. };
  154. class IgnoreListError : public std::runtime_error { // When the ignore list won't load.
  155. public: IgnoreListError(const std::string& w):runtime_error(w) {}
  156. };
  157. class AllocationError : public std::runtime_error { // Exception when we can't allocate something.
  158. public: AllocationError(const std::string& w):runtime_error(w) {}
  159. };
  160. class Busy : public std::runtime_error { // Exception when there is a collision.
  161. public: Busy(const std::string& w):runtime_error(w) {}
  162. };
  163. class Panic : public std::runtime_error { // Exception when something else happens.
  164. public: Panic(const std::string& w):runtime_error(w) {}
  165. };
  166. //// Plugin Components.
  167. snfCFGmgr MyCFGmgr; // Configuration manager.
  168. snfLOGmgr MyLOGmgr; // Logging manager.
  169. snfNETmgr MyNETmgr; // Communications manager.
  170. snfGBUdbmgr MyGBUdbmgr; // GBUdb manager.
  171. GBUdb MyGBUdb; // GBUdb for this rulebase.
  172. snfXCImgr MyXCImgr; // XCI manager.
  173. //// Methods.
  174. snf_RulebaseHandler(): // Initialization is straight forward.
  175. MyReloader(0),
  176. ReferenceCount(0),
  177. Rulebase(NULL),
  178. CurrentCount(0),
  179. OldRulebase(NULL),
  180. RetiringCount(0),
  181. RefreshInProgress(false),
  182. MyGeneration(0),
  183. myXCIServerCommandHandler(0){
  184. MyNETmgr.linkLOGmgr(MyLOGmgr); // Link the NET manager to the LOGmgr.
  185. MyNETmgr.linkGBUdbmgr(MyGBUdbmgr); // Link the NET manager to the GBUdbmgr.
  186. MyGBUdbmgr.linkGBUdb(MyGBUdb); // Link the GBUdb manager to it's db.
  187. MyGBUdbmgr.linkLOGmgr(MyLOGmgr); // Link the GBUdb manager to the LOGmgr.
  188. MyLOGmgr.linkNETmgr(MyNETmgr); // Link the LOG manager to the NETmgr.
  189. MyLOGmgr.linkGBUdb(MyGBUdb); // Link the LOG manager to the GBUdb.
  190. MyXCImgr.linkHome(this); // Link the XCI manager to this.
  191. }
  192. ~snf_RulebaseHandler(); // Shutdown checks for safety.
  193. bool isReady(); // Is the object is active.
  194. bool isBusy(); // Is a refresh/open in progress.
  195. int getReferenceCount(); // How many Engines using this handler.
  196. int getCurrentCount(); // How many Engines active in the current rb.
  197. int getRetiringCount(); // How many Engines active in the old rb.
  198. void open(const char* path, // Lights up this hanlder.
  199. const char* licenseid,
  200. const char* authentication);
  201. bool AutoRefresh(bool On); // Turn on/off auto refresh.
  202. bool AutoRefresh(); // True if AutoRefresh is on.
  203. void refresh(); // Reloads the rulebase and config.
  204. void close(); // Closes this handler.
  205. void use(); // Make use of this Rulebase Handler.
  206. void unuse(); // Finish with this Rulebase Handler.
  207. int Generation(); // Returns the generation number.
  208. void addRulePanic(int RuleID); // Synchronously add a RulePanic.
  209. bool testXHDRInjectOn(); // Safely look ahead at XHDRInjectOn.
  210. IPTestRecord& performIPTest(IPTestRecord& I); // Perform an IP test.
  211. void logThisIPTest(IPTestRecord& I, std::string Action); // Log an IP test result & action.
  212. void logThisError(std::string ContextName, int Code, std::string Text); // Log an error message.
  213. void logThisInfo(std::string ContextName, int Code, std::string Text); // Log an informational message.
  214. std::string PlatformVersion(std::string NewPlatformVersion); // Set platform version info.
  215. std::string PlatformVersion(); // Get platform version info.
  216. std::string PlatformConfiguration(); // Get platform configuration.
  217. std::string EngineVersion(); // Get engine version info.
  218. void XCIServerCommandHandler(snfXCIServerCommandHandler& XCH); // Registers a new XCI Srvr Cmd handler.
  219. std::string processXCIServerCommandRequest(snf_xci& X); // Handle a parsed XCI Srvr Cmd request.
  220. };
  221. // IPTestEngine w/ GBUdb interface.
  222. // This will plug into the FilterChain to evaluate IPs on the fly.
  223. class snf_IPTestEngine : public FilterChainIPTester {
  224. private:
  225. GBUdb* Lookup; // Where we find our GBUdb.
  226. snfScanData* ScanData; // Where we find our ScanData.
  227. snfCFGData* CFGData; // Where we find our CFG data.
  228. snfLOGmgr* LOGmgr; // Where we find our LOG manager.
  229. public:
  230. snf_IPTestEngine(); // Initialize internal pointers to NULL.
  231. void setGBUdb(GBUdb& G); // Setup the GBUdb lookup.
  232. void setScanData(snfScanData& D); // Setup the ScanData object.
  233. void setCFGData(snfCFGData& C); // (Re)Set the config data to use.
  234. void setLOGmgr(snfLOGmgr& L); // Setup the LOGmgr to use.
  235. std::string& test(std::string& input, std::string& output); // Our obligatory test function.
  236. };
  237. // How to spot strangers in the IP reputations.
  238. class snf_IPStrangerList {
  239. private:
  240. cd::Mutex myMutex;
  241. std::set<cd::IP4Address> listA;
  242. std::set<cd::IP4Address> listB;
  243. bool usingANotB;
  244. cd::Timeout listExpiration;
  245. std::set<cd::IP4Address>& myActiveList() {
  246. if(usingANotB) return listA;
  247. else return listB;
  248. }
  249. void swapOutOldLists() {
  250. if(listExpiration.isExpired()) {
  251. usingANotB = !usingANotB;
  252. myActiveList().clear();
  253. listExpiration.restart();
  254. }
  255. }
  256. std::set<cd::IP4Address>& myCurrentList() {
  257. swapOutOldLists();
  258. return myActiveList();
  259. }
  260. public:
  261. static const int TwoHours = (2 * (60 * (60 * 1000)));
  262. snf_IPStrangerList() : usingANotB(true), listExpiration(TwoHours) {}
  263. bool isStranger(cd::IP4Address a) {
  264. cd::ScopeMutex JustMe(myMutex);
  265. swapOutOldLists();
  266. bool foundStranger = (0 < listA.count(a)) || (0 < listB.count(a));
  267. return foundStranger;
  268. }
  269. void addStranger(cd::IP4Address a) {
  270. cd::ScopeMutex JustMe(myMutex);
  271. myCurrentList().insert(a);
  272. }
  273. };
  274. // Here's where we pull it all together.
  275. class snf_EngineHandler {
  276. private:
  277. cd::Mutex MyMutex; // This handler's mutex.
  278. cd::Mutex FileScan; // File scan entry mutex.
  279. EvaluationMatrix* volatile CurrentMatrix; // Matrix for the latest scan.
  280. snf_RulebaseHandler* volatile MyRulebase; // My RulebaseHandler.
  281. snfScanData MyScanData; // Local snfScanData record.
  282. snf_IPTestEngine MyIPTestEngine; // Local IP Test Engine.
  283. int ResultsCount; // Count of Match Records for getResults
  284. int ResultsRemaining; // Count of Match Records ahead of cursor.
  285. MatchRecord* FinalResult; // Final (winning) result of the scan.
  286. MatchRecord* ResultCursor; // Current Match Record for getResults.
  287. std::string extractMessageID(const unsigned char* Msg, const int Len); // Get log safe Message-ID or substitute.
  288. public:
  289. class FileError : public std::runtime_error { // Exception when a file won't open.
  290. public: FileError(const std::string& w):runtime_error(w) {}
  291. };
  292. class XHDRError : public std::runtime_error { // Exception when XHDR Inject/File fails.
  293. public: XHDRError(const std::string& w):runtime_error(w) {}
  294. };
  295. class BadMatrix : public std::runtime_error { // Exception out of bounds of matrix.
  296. public: BadMatrix(const std::string& w):runtime_error(w) {}
  297. };
  298. class MaxEvals : public std::runtime_error { // Exception too many evaluators.
  299. public: MaxEvals(const std::string& w):runtime_error(w) {}
  300. };
  301. class AllocationError : public std::runtime_error { // Exception when we can't allocate something.
  302. public: AllocationError(const std::string& w):runtime_error(w) {}
  303. };
  304. class Busy : public std::runtime_error { // Exception when there is a collision.
  305. public: Busy(const std::string& w):runtime_error(w) {}
  306. };
  307. class Panic : public std::runtime_error { // Exception when something else happens.
  308. public: Panic(const std::string& w):runtime_error(w) {}
  309. };
  310. snf_EngineHandler(): // Initialization is simple.
  311. CurrentMatrix(NULL),
  312. MyRulebase(NULL),
  313. MyScanData(snf_ScanHorizon),
  314. ResultsCount(0),
  315. ResultsRemaining(0),
  316. ResultCursor(NULL) {}
  317. ~snf_EngineHandler(); // Shutdown clenas up and checks for safety.
  318. void open(snf_RulebaseHandler* Handler); // Light up the engine.
  319. bool isReady(); // Is the Engine good to go? (doubles as busy)
  320. void close(); // Close down the engine.
  321. int scanMessageFile( // Scan this message file.
  322. const std::string MessageFilePath, // -- this is the file (and id)
  323. const int MessageSetupTime = 0, // -- setup time already used.
  324. const cd::IP4Address MessageSource = 0UL // -- message source IP (for injection).
  325. );
  326. int scanMessage( // Scan this message.
  327. const unsigned char* MessageBuffer, // -- this is the message buffer.
  328. const int MessageLength, // -- this is the length of the buffer.
  329. const std::string MessageName = "", // -- this is the message identifier.
  330. const int MessageSetupTime = 0, // -- setup time used (for logging).
  331. const cd::IP4Address MessageSource = 0UL // -- message source IP (for injection).
  332. );
  333. int getResults(snf_match* MatchBuffer); // Get the next match buffer.
  334. int getDepth(); // Get the scan depth.
  335. const std::string getClassicLog(); // Get classic log entries for last scan.
  336. const std::string getXMLLog(); // Get XML log entries or last scan.
  337. const std::string getXHDRs(); // Get XHDRs for last scan.
  338. };
  339. // Here's the class that pulls it all together.
  340. class snf_MultiEngineHandler {
  341. private:
  342. cd::Mutex RulebaseScan; // This handler's mutex.
  343. int RulebaseCursor; // Next Rulebase to search.
  344. snf_RulebaseHandler RulebaseHandlers[snf_MAX_RULEBASES]; // Array of Rulebase Handlers
  345. int RoundRulebaseCursor(); // Gets round robin Rulebase handle candidates.
  346. cd::Mutex EngineScan; // Serializes searching the Engine list.
  347. int EngineCursor; // Next Engine to search.
  348. snf_EngineHandler EngineHandlers[snf_MAX_SCANNERS]; // Array of Engine Handlers
  349. int RoundEngineCursor(); // Gets round robin Engine handle candidates.
  350. public:
  351. class TooMany : public std::runtime_error { // Exception when no more handle slots.
  352. public: TooMany(const std::string& w):runtime_error(w) {}
  353. };
  354. class FileError : public std::runtime_error { // Exception when a file won't open.
  355. public: FileError(const std::string& w):runtime_error(w) {}
  356. };
  357. class AuthenticationError : public std::runtime_error { // Exception when authentication fails.
  358. public: AuthenticationError(const std::string& w):runtime_error(w) {}
  359. };
  360. class AllocationError : public std::runtime_error { // Exception when we can't allocate something.
  361. public: AllocationError(const std::string& w):runtime_error(w) {}
  362. };
  363. class Busy : public std::runtime_error { // Exception when there is a collision.
  364. public: Busy(const std::string& w):runtime_error(w) {}
  365. };
  366. class Panic : public std::runtime_error { // Exception when something else happens.
  367. public: Panic(const std::string& w):runtime_error(w) {}
  368. };
  369. snf_MultiEngineHandler():
  370. RulebaseCursor(0),
  371. EngineCursor(0) {}
  372. ~snf_MultiEngineHandler(); // Clean up, safety check, shut down.
  373. // snf_OpenRulebase()
  374. // Grab the first available rulebse handler and light it up.
  375. int OpenRulebase(const char* path, const char* licenseid, const char* authentication);
  376. // snf_RefreshRulebase()
  377. // Reload the rulebase associated with the handler.
  378. void RefreshRulebase(int RulebaseHandle);
  379. // snf_CloseRulebase()
  380. // Shut down this Rulebase handler.
  381. void CloseRulebase(int RulebaseHandle);
  382. // snf_OpenEngine()
  383. // Grab the first available Engine handler and light it up
  384. int OpenEngine(int RulebaseHandle);
  385. // snf_CloseEngine()
  386. // Shut down this Engine handler.
  387. void CloseEngine(int EngineHandle);
  388. // snf_Scan()
  389. // Scan the MessageBuffer with this Engine.
  390. int Scan(int EngineHandle, const unsigned char* MessageBuffer, int MessageLength);
  391. // The Engine prvides detailed match results through this function.
  392. int getResults(int EngineHandle, snf_match* matchbfr);
  393. // The Engine provies the scan depth through this function.
  394. int getDepth(int EngineHandle);
  395. };