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

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