Ви не можете вибрати більше 25 тем Теми мають розпочинатися з літери або цифри, можуть містити дефіси (-) і не повинні перевищувати 35 символів.

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