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 26KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476
  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/faults.hpp"
  31. #include "../CodeDweller/threading.hpp"
  32. #include "GBUdb.hpp"
  33. #include "FilterChain.hpp"
  34. #include "snf_engine.hpp"
  35. #include "snf_match.h"
  36. #include "snfCFGmgr.hpp"
  37. #include "snfLOGmgr.hpp"
  38. #include "snfNETmgr.hpp"
  39. #include "snfGBUdbmgr.hpp"
  40. #include "snfXCImgr.hpp"
  41. #include <cassert>
  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. 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 Thread { // Calls system() in separate thread.
  82. private:
  83. Mutex MyMutex; // Protects internal data.
  84. string SystemCallText; // Text to send to system().
  85. 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. 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(string Name); // Constructor.
  94. ~ScriptCaller(); // Destructor.
  95. void SystemCall(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 ThreadType Type; // The thread's type.
  100. const static ThreadState CallingSystem; // State when in system() call.
  101. const static ThreadState PendingGuardTime; // State when waiting for guard time.
  102. const static ThreadState StandingBy; // State when waiting around.
  103. const static ThreadState Disabled; // State when unable to run.
  104. };
  105. class snf_Reloader : private 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. string RulebaseFileCheckName; // We keep track of these files.
  110. string ConfigFileCheckName;
  111. 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 ThreadType Type; // The thread's type.
  125. };
  126. class snf_RulebaseHandler { // Engine Core Manager.
  127. friend class snfCFGPacket;
  128. private:
  129. 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. 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 runtime_error { // When the configuration won't load.
  146. public: ConfigurationError(const string& w):runtime_error(w) {}
  147. };
  148. class FileError : public runtime_error { // Exception: rulebase file won't load.
  149. public: FileError(const string& w):runtime_error(w) {}
  150. };
  151. class AuthenticationError : public runtime_error { // Exception when authentication fails.
  152. public: AuthenticationError(const string& w):runtime_error(w) {}
  153. };
  154. class IgnoreListError : public runtime_error { // When the ignore list won't load.
  155. public: IgnoreListError(const string& w):runtime_error(w) {}
  156. };
  157. class AllocationError : public runtime_error { // Exception when we can't allocate something.
  158. public: AllocationError(const string& w):runtime_error(w) {}
  159. };
  160. class Busy : public runtime_error { // Exception when there is a collision.
  161. public: Busy(const string& w):runtime_error(w) {}
  162. };
  163. class Panic : public runtime_error { // Exception when something else happens.
  164. public: Panic(const 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, string Action); // Log an IP test result & action.
  212. void logThisError(string ContextName, int Code, string Text); // Log an error message.
  213. void logThisInfo(string ContextName, int Code, string Text); // Log an informational message.
  214. string PlatformVersion(string NewPlatformVersion); // Set platform version info.
  215. string PlatformVersion(); // Get platform version info.
  216. string PlatformConfiguration(); // Get platform configuration.
  217. string EngineVersion(); // Get engine version info.
  218. void XCIServerCommandHandler(snfXCIServerCommandHandler& XCH); // Registers a new XCI Srvr Cmd handler.
  219. 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. string& test(string& input, string& output); // Our obligatory test function.
  236. };
  237. // Here's where we pull it all together.
  238. class snf_EngineHandler {
  239. private:
  240. Mutex MyMutex; // This handler's mutex.
  241. Mutex FileScan; // File scan entry mutex.
  242. EvaluationMatrix* volatile CurrentMatrix; // Matrix for the latest scan.
  243. snf_RulebaseHandler* volatile MyRulebase; // My RulebaseHandler.
  244. snfScanData MyScanData; // Local snfScanData record.
  245. snf_IPTestEngine MyIPTestEngine; // Local IP Test Engine.
  246. int ResultsCount; // Count of Match Records for getResults
  247. int ResultsRemaining; // Count of Match Records ahead of cursor.
  248. MatchRecord* FinalResult; // Final (winning) result of the scan.
  249. MatchRecord* ResultCursor; // Current Match Record for getResults.
  250. string extractMessageID(const unsigned char* Msg, const int Len); // Get log safe Message-ID or substitute.
  251. public:
  252. class FileError : public runtime_error { // Exception when a file won't open.
  253. public: FileError(const string& w):runtime_error(w) {}
  254. };
  255. class XHDRError : public runtime_error { // Exception when XHDR Inject/File fails.
  256. public: XHDRError(const string& w):runtime_error(w) {}
  257. };
  258. class BadMatrix : public runtime_error { // Exception out of bounds of matrix.
  259. public: BadMatrix(const string& w):runtime_error(w) {}
  260. };
  261. class MaxEvals : public runtime_error { // Exception too many evaluators.
  262. public: MaxEvals(const string& w):runtime_error(w) {}
  263. };
  264. class AllocationError : public runtime_error { // Exception when we can't allocate something.
  265. public: AllocationError(const string& w):runtime_error(w) {}
  266. };
  267. class Busy : public runtime_error { // Exception when there is a collision.
  268. public: Busy(const string& w):runtime_error(w) {}
  269. };
  270. class Panic : public runtime_error { // Exception when something else happens.
  271. public: Panic(const string& w):runtime_error(w) {}
  272. };
  273. snf_EngineHandler(): // Initialization is simple.
  274. CurrentMatrix(NULL),
  275. MyRulebase(NULL),
  276. MyScanData(snf_ScanHorizon),
  277. ResultsCount(0),
  278. ResultsRemaining(0),
  279. ResultCursor(NULL) {}
  280. ~snf_EngineHandler(); // Shutdown clenas up and checks for safety.
  281. void open(snf_RulebaseHandler* Handler); // Light up the engine.
  282. bool isReady(); // Is the Engine good to go? (doubles as busy)
  283. void close(); // Close down the engine.
  284. int scanMessageFile( // Scan this message file.
  285. const string MessageFilePath, // -- this is the file (and id)
  286. const int MessageSetupTime = 0, // -- setup time already used.
  287. const IP4Address MessageSource = 0UL // -- message source IP (for injection).
  288. );
  289. int scanMessage( // Scan this message.
  290. const unsigned char* MessageBuffer, // -- this is the message buffer.
  291. const int MessageLength, // -- this is the length of the buffer.
  292. const string MessageName = "", // -- this is the message identifier.
  293. const int MessageSetupTime = 0, // -- setup time used (for logging).
  294. const IP4Address MessageSource = 0UL // -- message source IP (for injection).
  295. );
  296. int getResults(snf_match* MatchBuffer); // Get the next match buffer.
  297. int getDepth(); // Get the scan depth.
  298. const string getClassicLog(); // Get classic log entries for last scan.
  299. const string getXMLLog(); // Get XML log entries or last scan.
  300. const string getXHDRs(); // Get XHDRs for last scan.
  301. };
  302. // Here's the class that pulls it all together.
  303. class snf_MultiEngineHandler {
  304. private:
  305. Mutex RulebaseScan; // This handler's mutex.
  306. int RulebaseCursor; // Next Rulebase to search.
  307. snf_RulebaseHandler RulebaseHandlers[snf_MAX_RULEBASES]; // Array of Rulebase Handlers
  308. int RoundRulebaseCursor(); // Gets round robin Rulebase handle candidates.
  309. Mutex EngineScan; // Serializes searching the Engine list.
  310. int EngineCursor; // Next Engine to search.
  311. snf_EngineHandler EngineHandlers[snf_MAX_SCANNERS]; // Array of Engine Handlers
  312. int RoundEngineCursor(); // Gets round robin Engine handle candidates.
  313. public:
  314. class TooMany : public runtime_error { // Exception when no more handle slots.
  315. public: TooMany(const string& w):runtime_error(w) {}
  316. };
  317. class FileError : public runtime_error { // Exception when a file won't open.
  318. public: FileError(const string& w):runtime_error(w) {}
  319. };
  320. class AuthenticationError : public runtime_error { // Exception when authentication fails.
  321. public: AuthenticationError(const string& w):runtime_error(w) {}
  322. };
  323. class AllocationError : public runtime_error { // Exception when we can't allocate something.
  324. public: AllocationError(const string& w):runtime_error(w) {}
  325. };
  326. class Busy : public runtime_error { // Exception when there is a collision.
  327. public: Busy(const string& w):runtime_error(w) {}
  328. };
  329. class Panic : public runtime_error { // Exception when something else happens.
  330. public: Panic(const string& w):runtime_error(w) {}
  331. };
  332. snf_MultiEngineHandler():
  333. RulebaseCursor(0),
  334. EngineCursor(0) {}
  335. ~snf_MultiEngineHandler(); // Clean up, safety check, shut down.
  336. // snf_OpenRulebase()
  337. // Grab the first available rulebse handler and light it up.
  338. int OpenRulebase(const char* path, const char* licenseid, const char* authentication);
  339. // snf_RefreshRulebase()
  340. // Reload the rulebase associated with the handler.
  341. void RefreshRulebase(int RulebaseHandle);
  342. // snf_CloseRulebase()
  343. // Shut down this Rulebase handler.
  344. void CloseRulebase(int RulebaseHandle);
  345. // snf_OpenEngine()
  346. // Grab the first available Engine handler and light it up
  347. int OpenEngine(int RulebaseHandle);
  348. // snf_CloseEngine()
  349. // Shut down this Engine handler.
  350. void CloseEngine(int EngineHandle);
  351. // snf_Scan()
  352. // Scan the MessageBuffer with this Engine.
  353. int Scan(int EngineHandle, const unsigned char* MessageBuffer, int MessageLength);
  354. // The Engine prvides detailed match results through this function.
  355. int getResults(int EngineHandle, snf_match* matchbfr);
  356. // The Engine provies the scan depth through this function.
  357. int getDepth(int EngineHandle);
  358. };
  359. #endif