Nelze vybrat více než 25 témat Téma musí začínat písmenem nebo číslem, může obsahovat pomlčky („-“) a může být dlouhé až 35 znaků.

SNFMulti.hpp 25KB

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