Você não pode selecionar mais de 25 tópicos Os tópicos devem começar com uma letra ou um número, podem incluir traços ('-') e podem ter até 35 caracteres.

SNFMulti.cpp 136KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187
  1. // SNFMulti.cpp
  2. //
  3. // (C) Copyright 2006 - 2009 ARM Research Labs, LLC
  4. // See www.armresearch.com for the copyright terms.
  5. //
  6. // 20060121_M
  7. //
  8. // See SNFMulti.hpp for history and detailed notes.
  9. #include <sys/types.h>
  10. #include <sys/stat.h>
  11. #include <ctime>
  12. #include <cstring>
  13. #include <cstdlib>
  14. #include <sstream>
  15. #include "SNFMulti.hpp"
  16. #include "../CodeDweller/timing.hpp"
  17. //#include "../nvwa-0.6/nvwa/debug_new.h"
  18. using namespace std;
  19. //// Version Info
  20. const char* SNF_ENGINE_VERSION = "SNFMulti Engine Version 3.0.19 Build: " __DATE__ " " __TIME__;
  21. //// Script Caller Methods
  22. const ThreadType ScriptCaller::Type("Script Caller"); // Script caller thread type mnemonic.
  23. const ThreadState ScriptCaller::CallingSystem("In system()"); // Script caller "CallingSystem" state.
  24. const ThreadState ScriptCaller::PendingGuardTime("Guard Time"); // Script caller "GuardTime" state.
  25. const ThreadState ScriptCaller::StandingBy("Standby"); // Script caller "Standby" state.
  26. const ThreadState ScriptCaller::Disabled("Disabled"); // State when unable to run.
  27. const int ScriptGuardDefault = 180000; // 3 Minute Default Guard Time.
  28. ScriptCaller::ScriptCaller(string S) : // Script caller constructor (with name).
  29. Thread(ScriptCaller::Type, S), // Set up the thread type and name.
  30. GuardTimer(ScriptGuardDefault), // Initialize the guard time.
  31. GoFlag(false), // Not ready to go yet.
  32. DieFlag(false), // Not ready to die yet.
  33. myLastResult(0) { // No last result yet.
  34. run(); // Launch the thread.
  35. }
  36. ScriptCaller::~ScriptCaller() { // Destructor.
  37. DieFlag = true; // Set the die flag.
  38. Sleeper WaitATic(1000); // One second sleeper.
  39. for(int x = 10; x > 0; x--) { // We don't join, we might get stuck.
  40. if(false == isRunning()) break; // If we're still running then wait
  41. WaitATic(); // up to 10 seconds, then just exit.
  42. } // If the thread is stuck it will
  43. } // just get closed.
  44. string ScriptCaller::ScriptToRun() { // Safely grab the SystemCallText.
  45. ScopeMutex Freeze(MyMutex); // Protect the string.
  46. return SystemCallText; // Grab a copy of the text.
  47. }
  48. bool ScriptCaller::hasGuardExpired() { // True if guard time has expired.
  49. ScopeMutex Freeze(MyMutex); // Protect the timer.
  50. return GuardTimer.isExpired(); // If it has expired we're true.
  51. }
  52. void ScriptCaller::SystemCall(string S) { // Set the SystemCall text.
  53. ScopeMutex Freeze(MyMutex); // Protect the string object.
  54. SystemCallText = S; // Set it's data.
  55. }
  56. const int MinimumGuardTime = 60000; // Minimum Guard Time 1 minute.
  57. void ScriptCaller::GuardTime(int T) { // Set the Guard Time.
  58. if(MinimumGuardTime > T) T = MinimumGuardTime; // Enforce our lower limit.
  59. ScopeMutex Freeze(MyMutex); // Protect the Guard Timer.
  60. GuardTimer.setDuration(T); // Set the duration.
  61. GuardTimer.restart(); // Restart the timer.
  62. }
  63. void ScriptCaller::trigger() { // Trigger the system() call.
  64. GoFlag = true; // Set the flag.
  65. }
  66. int ScriptCaller::LastResult() { // Return the result code from
  67. return myLastResult; // the last system() call.
  68. }
  69. void ScriptCaller::myTask() { // Safely call system() when triggered.
  70. Sleeper WaitATic(1000); // One second sleeper.
  71. while(false == DieFlag) { // While it's not time to die:
  72. WaitATic(); // Pause for 1 sec each round.
  73. string ScriptThisRound = ScriptToRun(); // Grab the current script.
  74. if(0 < ScriptToRun().length()) { // If script text is defined and
  75. if(true == GoFlag) { // If GoFlag is triggered and
  76. if(hasGuardExpired()) { // Guard time is expired:
  77. CurrentThreadState(CallingSystem); // Publish our state.
  78. myLastResult = system(ScriptThisRound.c_str()); // Make the system call.
  79. GoFlag = false; // Done with that trigger.
  80. GuardTimer.restart(); // Restart our Guard Time.
  81. } else { // If we're waiting for Guard Time:
  82. CurrentThreadState(PendingGuardTime); // publish that state and hold down
  83. GoFlag = false; // the trigger signal (no stale go).
  84. }
  85. } else { // If nothing is triggered yet then
  86. CurrentThreadState(StandingBy); // we are standing by.
  87. }
  88. } else { // If we have no script to run then
  89. CurrentThreadState(Disabled); // we are disabled.
  90. }
  91. }
  92. }
  93. //// Rulebase Reloader Methods
  94. // How to get timestamps on critical files.
  95. time_t getFileTimestamp(string FileName) {
  96. struct stat FileNameStat; // First we need a stat buffer.
  97. if(0 != stat(FileName.c_str(), &FileNameStat)) { // If we can't get the stat we
  98. return 0; // will return 0;
  99. } // If all goes well we return
  100. return FileNameStat.st_mtime; // the last modified time_t.
  101. }
  102. void snf_Reloader::captureFileStats() { // Get stats for later comparison.
  103. snfCFGData& C = *(MyRulebase.MyCFGmgr.ActiveConfiguration()); // Reference the active config.
  104. RulebaseFileCheckName = C.RuleFilePath; // Build/Get Rulebase File Name.
  105. ConfigFileCheckName = C.ConfigFilePath; // Build/Get Configuration File Name.
  106. IgnoreListCheckFileName = C.paths_workspace_path; // Build/Get Ignore File Name.
  107. IgnoreListCheckFileName.append("GBUdbIgnoreList.txt");
  108. RulebaseFileTimestamp = getFileTimestamp(RulebaseFileCheckName); // Timestamps to check for
  109. ConfigurationTimestamp = getFileTimestamp(ConfigFileCheckName); // changes in configuration data
  110. IgnoreListTimestamp = getFileTimestamp(IgnoreListCheckFileName); // or rulebase files.
  111. }
  112. bool snf_Reloader::StatsAreDifferent() { // Check file stats for changes.
  113. return ( // Return true if any of the
  114. RulebaseFileTimestamp != getFileTimestamp(RulebaseFileCheckName) || // Rulebase File, or the
  115. ConfigurationTimestamp != getFileTimestamp(ConfigFileCheckName) || // Configuration File, or the
  116. IgnoreListTimestamp != getFileTimestamp(IgnoreListCheckFileName) // Ignore List File have changed.
  117. );
  118. }
  119. const int MSPerSec = 1000; // 1000 milliseconds per second.
  120. void snf_Reloader::captureGetterConfig() { // Update RulebaseGetter config.
  121. snfCFGData& C = *(MyRulebase.MyCFGmgr.ActiveConfiguration()); // Reference the active config.
  122. RulebaseGetterIsTurnedOn = ( // Is the script caller on or off?
  123. true == C.update_script_on_off && // We're on if the bit is set and
  124. 0 < C.update_script_call.length() // we have a non-empty script to call.
  125. );
  126. if(RulebaseGetterIsTurnedOn) { // If it is turned on:
  127. RulebaseGetter.SystemCall(C.update_script_call); // Set the script call and
  128. RulebaseGetter.GuardTime(C.update_script_guard_time * MSPerSec); // the cycle guard time.
  129. }
  130. else { // If the scripter is turned off:
  131. RulebaseGetter.SystemCall(""); // Set the script to nothing.
  132. }
  133. }
  134. const string snfReloadContext = "--RELOADING--"; // Context for info and error logs.
  135. void snf_Reloader::myTask() { // How do we do this refresh thing?
  136. Sleeper WaitATic(1000); // Wait a second between checks.
  137. while(!TimeToStop) { // While it's not time to stop:
  138. if(
  139. RulebaseGetterIsTurnedOn && // If our rulebase getter is enabled
  140. MyRulebase.MyLOGmgr.isUpdateAvailable() // and a new rulebase is availalbe:
  141. ) {
  142. RulebaseGetter.trigger(); // Trigger the update script (if any).
  143. }
  144. if(StatsAreDifferent()) { // Check the stats. If different:
  145. try { // safely attempt a reload.
  146. WaitATic(); // Wait a tic to let things stabilize
  147. MyRulebase.refresh(); // then call refresh on the handler.
  148. captureFileStats(); // If it works, capture the new stats.
  149. captureGetterConfig(); // Also update the RulebaseGetter.
  150. MyRulebase.logThisInfo( // Log our success.
  151. snfReloadContext, snf_SUCCESS, "Success");
  152. }
  153. catch(snf_RulebaseHandler::IgnoreListError) { // If we get an IgnoreListError - say so.
  154. MyRulebase.logThisError(
  155. snfReloadContext, snf_ERROR_RULE_FILE, "IgnoreListError");
  156. }
  157. catch(snf_RulebaseHandler::ConfigurationError) { // If we get a ConfigurationError - say so.
  158. MyRulebase.logThisError(
  159. snfReloadContext, snf_ERROR_RULE_FILE, "ConfigurationError");
  160. }
  161. catch(snf_RulebaseHandler::FileError x) { // If we get a FileError - say so.
  162. MyRulebase.logThisError(
  163. snfReloadContext, snf_ERROR_RULE_FILE, "FileError");
  164. }
  165. catch(snf_RulebaseHandler::AuthenticationError x) { // If we get a Auth Error - say so.
  166. MyRulebase.logThisError(
  167. snfReloadContext, snf_ERROR_RULE_AUTH, "AuthError");
  168. }
  169. catch(snf_RulebaseHandler::Busy x) { // If we get a Busy Exception - say so.
  170. MyRulebase.logThisError(
  171. snfReloadContext, snf_ERROR_UNKNOWN, "BusyError");
  172. }
  173. catch(snf_RulebaseHandler::Panic x) { // If we get a Panic - say so.
  174. MyRulebase.logThisError(
  175. snfReloadContext, snf_ERROR_UNKNOWN, "PanicError");
  176. }
  177. catch(...) { // If we get some other error - shout!
  178. MyRulebase.logThisError(
  179. snfReloadContext, snf_ERROR_UNKNOWN, "UnhandledError");
  180. }
  181. }
  182. WaitATic(); // Wait before the next loop.
  183. }
  184. }
  185. const ThreadType snf_Reloader::Type("snf_Reloader"); // The thread's type.
  186. snf_Reloader::snf_Reloader(snf_RulebaseHandler& R) : // When we are created, we
  187. Thread(snf_Reloader::Type, "Reloader"), // brand and name our thread.
  188. MyRulebase(R), // Capture the rulebase handler.
  189. TimeToStop(false), // It's not time to stop yet.
  190. RulebaseGetter("RulebaseGetter"), // Setup our ScriptCaller thread.
  191. RulebaseGetterIsTurnedOn(false) { // Rulebase getter is off at first.
  192. captureFileStats(); // Set up the initial stats.
  193. captureGetterConfig(); // Set up RulebaseGetter config.
  194. run(); // Run our maintenenace thread.
  195. }
  196. snf_Reloader::~snf_Reloader() { // When we are destroyed we
  197. TimeToStop = true; // set our time to stop bit
  198. join(); // and wait for the thread.
  199. }
  200. //// snfCFGPacket Methods
  201. snfCFGPacket::snfCFGPacket(snf_RulebaseHandler* R) : // When we are created:
  202. MyRulebase(R), // Capture our rulebase handler and
  203. MyTokenMatrix(NULL), // ready our token matrix and
  204. MyCFGData(NULL) { // cfg pointers.
  205. if(MyRulebase) { MyRulebase->grab(*this); } // Safely grab our rulebase.
  206. }
  207. snfCFGPacket::~snfCFGPacket() { if(MyRulebase) MyRulebase->drop(*this); } // Safely drop our rulebase when we die.
  208. TokenMatrix* snfCFGPacket::Tokens() { return MyTokenMatrix; } // Consumers read the Token Matrix and
  209. snfCFGData* snfCFGPacket::Config() { return MyCFGData; } // the snfCFGData.
  210. bool snfCFGPacket::bad() { // If anything is missing it's not good.
  211. return (NULL == MyTokenMatrix || NULL == MyCFGData); // True if any of these aren NULL.
  212. }
  213. bool snfCFGPacket::isRulePanic(int R) { // Test for a rule panic.
  214. return(RulePanics.end() != RulePanics.find(R)); // Find it in the list, it's a panic.
  215. }
  216. //// Rulebase Handler Methods
  217. snf_RulebaseHandler::~snf_RulebaseHandler(){ // Destruct the handler.
  218. close(); // Close before we go.
  219. }
  220. bool snf_RulebaseHandler::isReady(){ // Is the object ready?
  221. return (NULL!=Rulebase); // Have Rulebase? We're ready.
  222. }
  223. bool snf_RulebaseHandler::isBusy(){ // Is a refresh/open in progress or
  224. return (RefreshInProgress || 0<RetiringCount); // an older rulebase is not yet retired.
  225. }
  226. int snf_RulebaseHandler::getReferenceCount(){ // How many Engines using this handler.
  227. return ReferenceCount; // Tell them the count bob.
  228. }
  229. int snf_RulebaseHandler::getCurrentCount(){ // How many Engines active in the current rb.
  230. return CurrentCount; // Tell them what it is bob.
  231. }
  232. int snf_RulebaseHandler::getRetiringCount(){ // How many Engines active in the old rb.
  233. return RetiringCount; // Tell them what it is bob.
  234. }
  235. // FileUTC(FileName) - utility function for tagging the active rulebase
  236. string FileUTC(string FileName) { // Gets a files UTC.
  237. struct stat FileNameStat; // First we need a stat buffer.
  238. string t; // We also need a Timestamp holder.
  239. if(0 != stat(FileName.c_str(), &FileNameStat)) { // If we can't get the stat we
  240. t.append("000000000000"); return t; // will return 000000000000 to
  241. } // make sure we should get the file.
  242. struct tm FileNameTime; // Allocate a time structure.
  243. FileNameTime = *(gmtime(&FileNameStat.st_mtime)); // Copy the file time to it as UTC.
  244. char TimestampBfr[20]; // Timestamp buffer.
  245. sprintf(TimestampBfr,"%04d%02d%02d%02d%02d%02d", // Format yyyymmddhhmmss
  246. FileNameTime.tm_year+1900,
  247. FileNameTime.tm_mon+1,
  248. FileNameTime.tm_mday,
  249. FileNameTime.tm_hour,
  250. FileNameTime.tm_min,
  251. FileNameTime.tm_sec
  252. );
  253. t.append(TimestampBfr); // Append the timestamp to t
  254. return t; // and return it to the caller.
  255. }
  256. // Auto Reload Controls
  257. bool snf_RulebaseHandler::AutoRefresh(bool On) { // Turn on/off auto refresh.
  258. if(On) { // If they want Reload On:
  259. if(!AutoRefresh()) { // and it isn't already on:
  260. try { MyReloader = new snf_Reloader(*this); } // try to set up a Reloader.
  261. catch(...) { MyReloader = 0; } // If that fails we don't
  262. } // have one. If it's already
  263. } // on do nothing.
  264. else { // If they want Reload Off:
  265. if(AutoRefresh()) { // and it is turned on:
  266. delete MyReloader; // destroy the reloader and
  267. MyReloader = 0; // zero it's pointer.
  268. }
  269. }
  270. return AutoRefresh(); // Return the truth (on/off)
  271. }
  272. bool snf_RulebaseHandler::AutoRefresh() { // True if AutoRefresh is on.
  273. return (0 != MyReloader); // If we have one, it's on.
  274. }
  275. // _snf_LoadNewRulebase()
  276. // This is actually a common sub-funtion. It expects that the object is in the "RefreshInProgress" state,
  277. // and that everything is in place and safe for a new rulebase to be loaded into the object. Once it's
  278. // done it will reset from the "RefreshInProgress" state and along the way will throw any errors that
  279. // are appropriate. The other functions can count on this one to polish off the various forms of rulebase
  280. // load activity.
  281. const LogicCheck SaneRefreshProcessCheck("snf_RulebaseHandler::_snf_LoadNewRulebase():SaneRefreshProcessCheck(RefreshInProgress)");
  282. void snf_RulebaseHandler::_snf_LoadNewRulebase(){ // Common internal load/check routine.
  283. SaneRefreshProcessCheck(RefreshInProgress); // We only get called when this flag is set.
  284. try { MyCFGmgr.load(); } // Load a fresh copy of the configuration.
  285. catch(...) { // If something goes wrong:
  286. RefreshInProgress = false; // we are no longer "in refresh"
  287. throw ConfigurationError("_snf_LoadNewRulebase() MyCFGmgr.load() failed"); // throw the Configuration exception.
  288. }
  289. string RuleFilePath = MyCFGmgr.RuleFilePath(); // Get our rulebase file path and our
  290. string SecurityKey = MyCFGmgr.SecurityKey(); // security key from the CFG manager.
  291. if(0>=RuleFilePath.length()) { // If we don't have a path, we're hosed.
  292. RefreshInProgress = false; // We are no longer "in refresh"
  293. throw FileError("_snf_LoadNewRulebase() Zero length RuleFilePath"); // Can't load a RB file with no path!
  294. }
  295. if(0>=SecurityKey.length()) { // No security string? toast!
  296. RefreshInProgress = false; // We are no longer "in refresh"
  297. throw AuthenticationError("snf_LoadNewRulebase() Zero length SecurityKey"); // Can't authenticate without a key!
  298. }
  299. // Notify sub modules of the new configuration data.
  300. MyGeneration++; // Increment the generation number.
  301. snfCFGData& CFGData = (*(MyCFGmgr.ActiveConfiguration())); // Capture the active config...
  302. CFGData.Generation = MyGeneration; // Tag the configuration data.
  303. MyLOGmgr.configure(CFGData); // Update the LOGmgr's configuration.
  304. MyNETmgr.configure(CFGData); // Update the NETmgr's configuration.
  305. MyGBUdbmgr.configure(CFGData); // Update the GBUdbmgr's configuration.
  306. // Load the new rulebase locally (on stack) and see if it authenticates.
  307. TokenMatrix* TryThis = NULL; // We need our candidate to remain in scope.
  308. try { // This try block decodes the problem.
  309. try { // This try block does cleanup work.
  310. TryThis = new TokenMatrix(); // Grab a new Token Matrix
  311. TryThis->Load(RuleFilePath); // Load it from the provided file path
  312. TryThis->Validate(SecurityKey); // Validate it with the provided security key
  313. TryThis->Verify(SecurityKey); // Verify that it is not corrupt.
  314. }
  315. catch(...) { // Clean up after any exceptions.
  316. RefreshInProgress = false; // We're not refreshing now.
  317. if(TryThis) { // If we allocated a TokenMatrix then
  318. delete TryThis; // we need to reclaim the memory
  319. TryThis = 0; // and erase the pointer.
  320. } // With everything nice and clean we can
  321. throw; // rethrow he exception for decoding.
  322. }
  323. } // If nothing threw, we're golden!
  324. catch (TokenMatrix::BadFile) { // BadFile translates to FileError
  325. throw FileError("_snf_LoadNewRulebase() TokenMatrix::BadFile");
  326. }
  327. catch (TokenMatrix::BadMatrix) { // BadMatrix translates to AuthenticationError
  328. throw AuthenticationError("_snf_LoadNewRulebase() TokenMatrix::BadMatrix");
  329. }
  330. catch (TokenMatrix::BadAllocation) { // BadAllocation translates to AllocationError
  331. throw AllocationError("_snf_LoadNewRulebase() TokenMatrix::BadAllocation");
  332. }
  333. catch (TokenMatrix::OutOfRange) { // OutOfRange should never happen so PANIC!
  334. throw Panic("_snf_LoadNewRulebase() TokenMatrix::OutOfRange");
  335. }
  336. catch (exception e) {
  337. throw;
  338. }
  339. catch (...) { // Something unpredicted happens? PANIC!
  340. throw Panic("_snf_LoadNewRulebase() TokenMatrix.load() ???");
  341. }
  342. // At this point the rulebase looks good. If we need to go big-endian do it!
  343. #ifdef __BIG_ENDIAN__
  344. TryThis->FlipEndian(); // Flip tokens to big-endian format.
  345. #endif
  346. MyLOGmgr.updateActiveUTC(FileUTC(RuleFilePath)); // Update the Active Rulebase UTC.
  347. MyMutex.lock(); // Lock the mutex while changing state.
  348. OldRulebase = Rulebase; // Move the current rulebase and count to
  349. RetiringCount = CurrentCount; // the retiring slot.
  350. if(0>=RetiringCount && NULL!=OldRulebase) { // If nobody cares about the old rulebase
  351. delete OldRulebase; // then delete it, and wipe everything
  352. OldRulebase = NULL; // clean for the next retiree.
  353. RetiringCount = 0;
  354. }
  355. CurrentCount = 0; // Set the current count to zero (it's fresh!)
  356. Rulebase = TryThis; // Copy our new rulebase into production.
  357. MyMutex.unlock(); // Release the hounds!!!
  358. // If there is a GBUdb Ignore List, refresh with it (This might go elsewhere).
  359. // Failure to read the GBUdbIgnoreList if all else went well does not cause
  360. // the rulebase update (if any) to fail.
  361. /**** This section needs work ****/
  362. try {
  363. string IgnoreListPath = CFGData.paths_workspace_path;
  364. IgnoreListPath.append("GBUdbIgnoreList.txt");
  365. if(0 == MyGBUdb.readIgnoreList(IgnoreListPath.c_str())) // We must have at least 1 IP listed.
  366. throw ConfigurationError(
  367. "_snf_LoadNewRulebase() GBUdbIgnoreList min 1 entry!");
  368. }
  369. catch(...) { // Ignore list read might fail.
  370. RefreshInProgress = false; // If so, don't keep things hung.
  371. throw IgnoreListError("_snf_LoadNewRulebase() readIgnoreList() ???"); // If it does, throw FileError.
  372. }
  373. RefreshInProgress = false; // Done with the refresh process.
  374. return; // Our work is done here.
  375. }
  376. // open()
  377. // This loads a new rulebase (usually the first one only) into the handler. This is the first of two loading
  378. // methods on this object. This one checks for isBusy() because it is highly invasive. If it is called after
  379. // the object has been running it is important that it not run while anything in the object is active. This
  380. // is because it is likely in this case we would be loading an entirely new rulebase that would lead to odd
  381. // results if some scanner instances were activily using a different one.
  382. void snf_RulebaseHandler::open(const char* path, const char* licenseid, const char* authentication){
  383. MyMutex.lock(); // Lock the mutex while changing state.
  384. if(isBusy()) { // Be sure we're not busy.
  385. MyMutex.unlock(); throw Busy("snf_RulebaseHandler::open() busy"); // If we are then throw.
  386. }
  387. RefreshInProgress = true; // Set RefreshInProgress.
  388. MyMutex.unlock(); // Unlock the mutex and
  389. MyCFGmgr.initialize(path, licenseid, authentication); // Initialize our configuration.
  390. _snf_LoadNewRulebase(); // get on with loading the rulebase.
  391. MyGBUdbmgr.load(); // Load the GBUdb as configured.
  392. AutoRefresh(true); // Turn on Refresh by default.
  393. logThisInfo("--INITIALIZING--", 0, "Success"); // Log the happy event.
  394. return;
  395. }
  396. // refresh()
  397. // This loads a fresh copy of the current rulebase. This is the second loading method on the object. It is
  398. // specifically designed to work without stopping scanning activities. This one checks for isBusy() because
  399. // there may be an old rulebase that is not yet completely retired --- that is, some scanners may be using it.
  400. // If there is still an old rulebase on it's way out then we can't shove it aside without breaking something,
  401. // so we have to throw.
  402. //
  403. // Under normal circumstances, this call will cause a new rulebase to be loaded without disturbing any scans
  404. // underway on the current rulebase. The current rulebase will be put into retirement while any active scans
  405. // are completed, and then it will quietly go away when the last has finished. The new rulebase will take it's
  406. // place and will be handed out to all new grab() requests.
  407. void snf_RulebaseHandler::refresh(){ // Reloads the rulebase.
  408. MyMutex.lock(); // Lock the mutex while changing states.
  409. if(isBusy()) { // If we're busy then throw.
  410. MyMutex.unlock(); throw Busy("snf_RulebaseHandler::refresh() busy");
  411. }
  412. RefreshInProgress = true; // Set RefreshInProgress and
  413. MyMutex.unlock(); // unlock the mutex. Then get on with
  414. _snf_LoadNewRulebase(); // loading a fresh copy of the rulebase
  415. return;
  416. }
  417. void snf_RulebaseHandler::close(){ // Closes this handler.
  418. try {
  419. AutoRefresh(false); // Stop AutoRefresh if it's on.
  420. }
  421. catch(exception& e) { throw; } // Rethrow good exceptions.
  422. catch(...) { throw Panic("snf_RulebaseHandler::close() AutoRefresh(false) panic!"); } // Panic blank exceptions.
  423. try {
  424. MyXCImgr.stop(); // Stop the XCI manager.
  425. }
  426. catch(exception& e) { throw; } // Rethrow good exceptions.
  427. catch(...) { throw Panic("snf_RulebaseHandler::close() MyXCImgr.stop() panic!"); } // Panic blank exceptions.
  428. if(isBusy() || 0<CurrentCount || 0<ReferenceCount) { // Check that there is no activity.
  429. throw Busy("snf_RulebaseHandler::close() busy"); // With XCI stopped we should not
  430. } // be busy.
  431. try {
  432. MyLOGmgr.stop(); // Stop the LOG manager.
  433. }
  434. catch(exception& e) { throw; } // Rethrow good exceptions.
  435. catch(...) { throw Panic("snf_RulebaseHandler::close() MyLOGmgr.stop() panic!"); } // Panic blank exceptions.
  436. try {
  437. MyNETmgr.stop(); // Stop the NET manager.
  438. }
  439. catch(exception& e) { throw; } // Rethrow good exceptions.
  440. catch(...) { throw Panic("snf_RulebaseHandler::close() MyNETmgr.stop() panic!"); } // Panic blank exceptions.
  441. try {
  442. MyGBUdbmgr.stop(); // Stop the GBUdb manager.
  443. }
  444. catch(exception& e) { throw; } // Rethrow good exceptions.
  445. catch(...) { throw Panic("snf_RulebaseHandler::close() MyGBUdbmgr.stop() panic!"); } // Panic blank exceptions.
  446. try {
  447. if(NULL!=Rulebase) {delete Rulebase; Rulebase=NULL;} // If we have a Rulebase destroy it.
  448. }
  449. catch(exception& e) { throw; } // Rethrow good exceptions.
  450. catch(...) { throw Panic("snf_RulebaseHandler::close() delete Rulebase panic!"); } // Panic blank exceptions.
  451. try {
  452. if(NULL!=OldRulebase) {delete OldRulebase; OldRulebase=NULL;} // Shouldn't happen, but just in case.
  453. }
  454. catch(exception& e) { throw; } // Rethrow good exceptions.
  455. catch(...) { throw Panic("snf_RulebaseHandler::close() delete OldRulebase panic!"); } // Panic blank exceptions.
  456. }
  457. void snf_RulebaseHandler::use(){ // Make use of this Rulebase Handler.
  458. MyMutex.lock(); // Lock the object
  459. ReferenceCount++; // Boost the count
  460. MyMutex.unlock(); // Unlock the object
  461. }
  462. void snf_RulebaseHandler::unuse(){ // Finish with this Rulebase Handler.
  463. MyMutex.lock(); // Lock the object
  464. ReferenceCount--; // Reduce the count
  465. MyMutex.unlock(); // Unlock the object
  466. }
  467. // A word about Generation... In practice whenever the configuration or rulebase
  468. // changes the entire thing is reloaded. The Generation() function gives other
  469. // modules a way to know if they need to update their interpretation of the
  470. // configuration. They can keep track of the last Generation value they got and
  471. // compare it to the latest Generation. If the two are different then they need
  472. // to update their configuration - just in case it has changed.
  473. int snf_RulebaseHandler::Generation() { return MyGeneration; } // Returns the generation number.
  474. // A word about autopanics.
  475. // The first time throgh this we outsmarted ourselves with an ellaborate
  476. // wait-to-insert scheme. That led to the possibilty of a deadlock. Now we
  477. // copy the (usually empty or very short) set of rule panics to the
  478. // configuration packet when it is grabbed and only use the one mutext to hold
  479. // the configuration steady while doing so. All queries are made to the local
  480. // copy of the panic list and all writes are made, under mutex, to the active
  481. // configuration. Simpler, no significant penalty, and no more deadlocks.
  482. // A word about configuration packets.
  483. // Along the way we simplified things by making the snfCFGPacket do it's own
  484. // grab and drop upon construction and destruction. This way we don't have to
  485. // remember to handle all possible cases during a scan or other opertion -- once
  486. // the operation goes out of scope the configuration packet drop()s with it.
  487. void snf_RulebaseHandler::grab(snfCFGPacket& CP) { // Activate this Rulebase.
  488. ScopeMutex HoldStillPlease(MyMutex); // Lock the rulebase until we're done.
  489. CurrentCount++; // Boost the count for myself.
  490. CP.MyTokenMatrix = Rulebase; // Grab the current rulebase.
  491. CP.MyCFGData = MyCFGmgr.ActiveConfiguration(); // Grab the active configuration.
  492. CP.RulePanics = MyCFGmgr.ActiveConfiguration()->RulePanicHandler.IntegerSet; // Copy the RulePanic set.
  493. }
  494. void snf_RulebaseHandler::drop(snfCFGPacket& CP) { // Deactiveate this Rulebase.
  495. const TokenMatrix* t = CP.MyTokenMatrix; // Grab the token matrix pointer.
  496. CP.MyCFGData = NULL; // Null the configuration pointer.
  497. ScopeMutex HoldStillPlease(MyMutex); // Lock the rulebase until we're done.
  498. if(t==Rulebase) { // If we're dropping the current rulebase
  499. CurrentCount--; // then reduce the current count.
  500. } else // If not that then...
  501. if(t==OldRulebase) { // If we're dropping the old rulebase
  502. RetiringCount--; // reduce the retiring count and check...
  503. if(0>=RetiringCount) { // to see if it is completely retired.
  504. if(NULL!=OldRulebase) delete OldRulebase; // If it is then delete it and
  505. OldRulebase = NULL; RetiringCount = 0; // reset it's pointer and counter.
  506. }
  507. } else { // If we're dropping something else,
  508. throw Panic("snf_RulebaseHandler::drop() panic"); // it is time to panic, so, then PANIC!
  509. }
  510. }
  511. // When adding a rule panic entry the rulebase and configuration state cannot
  512. // be changed, nor grabbed by an snfCFGPacket. This ensures that the IntegerSet
  513. // is only adjusted by one thread at a time and that any threads using the set
  514. // will have a consistent result based on their last grab().
  515. void snf_RulebaseHandler::addRulePanic(int RuleID) { // Add a rule panic id dynamically.
  516. ScopeMutex JustMe(MyMutex); // Freeze the rulebase while we adjust
  517. MyCFGmgr.ActiveConfiguration() // the active configuration to
  518. ->RulePanicHandler.IntegerSet.insert(RuleID); // insert the new rule panic ruleid.
  519. } // When we're done, unlock and move on.
  520. IPTestRecord& snf_RulebaseHandler::performIPTest(IPTestRecord& I) { // Perform an IP test.
  521. snfCFGPacket MyCFGPacket(this); // We need a CFG packet.
  522. try { // Safely process the IP.
  523. if(false == MyCFGPacket.bad()) { // If we've got a good packet:
  524. I.G = MyGBUdb.getRecord(I.IP); // Lookup the IP in GBUdb.
  525. I.R = MyCFGPacket.Config()->RangeEvaluation(I.G); // Evaluate it's statistics.
  526. // Convert the RangeEvaluation into the configured Code
  527. switch(I.R) {
  528. case Unknown: // Unknown - not defined.
  529. case Normal: // Benefit of the doubt.
  530. case New: { // It is new to us.
  531. I.Code = 0; // Zero is the default - no code.
  532. break;
  533. }
  534. case White: { // This is a good guy.
  535. I.Code = MyCFGPacket.Config()->WhiteRangeHandler.Symbol;
  536. break;
  537. }
  538. case Caution: { // This is suspicious.
  539. I.Code = MyCFGPacket.Config()->CautionRangeHandler.Symbol;
  540. break;
  541. }
  542. case Black: { // This is bad.
  543. I.Code = MyCFGPacket.Config()->BlackRangeHandler.Symbol;
  544. break;
  545. }
  546. case Truncate: { // Don't even bother looking.
  547. I.Code = MyCFGPacket.Config()
  548. ->gbudb_regions_black_truncate_symbol;
  549. break;
  550. }
  551. }
  552. } // If something is broken we punt.
  553. } catch (...) {} // Ignore exceptions (none expected)
  554. return I; // Return the processed record.
  555. }
  556. void snf_RulebaseHandler::logThisIPTest(IPTestRecord& I, string Action) { // Log an IP test result & action.
  557. MyLOGmgr.logThisIPTest(I, Action);
  558. }
  559. void snf_RulebaseHandler::logThisError( // Log an error message.
  560. string ContextName, int Code, string Text
  561. ) {
  562. MyLOGmgr.logThisError(ContextName, Code, Text);
  563. }
  564. void snf_RulebaseHandler::logThisInfo( // Log an informational message.
  565. string ContextName, int Code, string Text
  566. ) {
  567. MyLOGmgr.logThisInfo(ContextName, Code, Text);
  568. }
  569. string snf_RulebaseHandler::PlatformVersion(string NewPlatformVersion) { // Set platform version info.
  570. return MyLOGmgr.PlatformVersion(NewPlatformVersion);
  571. }
  572. string snf_RulebaseHandler::PlatformVersion() { // Get platform version info.
  573. return MyLOGmgr.PlatformVersion();
  574. }
  575. string snf_RulebaseHandler::PlatformConfiguration() { // Get platform configuration.
  576. ScopeMutex LockAndGrab(MyMutex); // Freeze things for a moment and
  577. return MyCFGmgr.ActiveConfiguration()->PlatformElementContents; // copy the platform configuration.
  578. }
  579. string snf_RulebaseHandler::EngineVersion() { // Get engine version info.
  580. return MyLOGmgr.EngineVersion();
  581. }
  582. void snf_RulebaseHandler::
  583. XCIServerCommandHandler(snfXCIServerCommandHandler& XCH) { // Registers a new XCI Srvr Cmd handler.
  584. ScopeMutex ThereCanBeOnlyOne(XCIServerCommandMutex); // Serialize access to this resource.
  585. myXCIServerCommandHandler = &XCH; // Assign the new handler as provided.
  586. }
  587. string snf_RulebaseHandler::processXCIServerCommandRequest(snf_xci& X) { // Handle a parsed XCI Srvr Cmd request.
  588. ScopeMutex ThereCanBeOnlyOne(XCIServerCommandMutex); // Serialize access to this resource.
  589. if(0 == myXCIServerCommandHandler) { // If we don't have a handler then
  590. snfXCIServerCommandHandler H; // create a base handler and
  591. return H.processXCIRequest(X); // return it's default response.
  592. } // If we do have a handler then pass
  593. return myXCIServerCommandHandler->processXCIRequest(X); // on the request and return the
  594. } // response.
  595. //// snf_IPTestEngine Methods
  596. snf_IPTestEngine::snf_IPTestEngine() : // The constructor is simple - it
  597. Lookup(NULL), ScanData(NULL) { // sets up our internal references.
  598. } // Before use these must be set.
  599. void snf_IPTestEngine::setGBUdb(GBUdb& G) { // Here's how we set the GBUdb.
  600. Lookup = &G;
  601. }
  602. void snf_IPTestEngine::setScanData(snfScanData& S) { // Here's how we set the ScanData object.
  603. ScanData = &S;
  604. }
  605. void snf_IPTestEngine::setCFGData(snfCFGData& C) { // Here's how we set the CFGData.
  606. CFGData = &C;
  607. }
  608. void snf_IPTestEngine::setLOGmgr(snfLOGmgr& L) { // Here's how we set the LOGmgr.
  609. LOGmgr = &L;
  610. }
  611. // 20090127 _M Added special handling for forced IP sources. First, they are
  612. // always considered the source and second if they are in the GBUdb ignore list
  613. // then GBUdb training bypass is established.
  614. string& snf_IPTestEngine::test(string& input, string& output) { // Perform IP lookups and put IPs into ScanData.
  615. if(NULL == Lookup || NULL == ScanData) { // If we are not set up properly then we
  616. output = "{IPTest Config Error}"; // will return an error string.
  617. return output;
  618. }
  619. try { // If we're out of IP records, no analysis.
  620. IPScanRecord& I = ScanData->newIPScanRecord(); // Grab a new IP scan record and
  621. IP4Address IP = input; // Convert the string to an IP.
  622. // Identify forced Source IP addresses
  623. bool ThisSourceIsForced = ( // This IP is a forced source IP if:
  624. (0 == I.Ordinal) && ( // we are looking at the first IP and
  625. (0UL != ScanData->CallerForcedSourceIP()) || // either the Caller forced the IP or
  626. (0UL != ScanData->HeaderDirectiveSourceIP()) // the IP was forced by a header directive.
  627. )
  628. );
  629. // Bad IPs are possible, especially if the source was forced. In that
  630. // case forced source IP is meaningless so we want to ignore it and
  631. // we want to make the case visible in the logs. An ordinary IP that
  632. // is invalid has no consequence so we simply skip those.
  633. // Note that a source IP that has it's ignore flag set causes an
  634. // implied training bypass inside the scan function. Setting the bad
  635. // IP as the source and setting it's ignore flag will have the desired
  636. // effect.
  637. if(0UL == IP) { // If we got a 0 or a bad conversion then
  638. output = "{0.0.0.0 Is Not A Usable IP}"; // we won't be testing this IP.
  639. if(ThisSourceIsForced) { // If this ip is a forced source then
  640. I.GBUdbData.Flag(Ignore); // we will force a training bypass,
  641. ScanData->SourceIPRecord(I); // we will record it as the source,
  642. ScanData->SourceIPEvaluation = output; // and capture the error output.
  643. }
  644. return output;
  645. }
  646. if(0xFFFFFFFF == IP) { // If we got a 255.255.255.255 then
  647. output = "{255.255.255.255 Is Not A Usable IP}"; // we won't be testing this IP.
  648. if(ThisSourceIsForced) { // If this ip is a forced source then
  649. I.GBUdbData.Flag(Ignore); // we will force a training bypass,
  650. ScanData->SourceIPRecord(I); // we will record it as the source,
  651. ScanData->SourceIPEvaluation = output; // and capture the error output.
  652. }
  653. return output;
  654. }
  655. GBUdbRecord R = Lookup->getRecord(IP); // Get the GBUdb record for it.
  656. I.IP = IP; // store the IP and the
  657. I.GBUdbData = R; // GBUdb record we retrieved.
  658. output = "{"; // Next we start to build our IP data insert.
  659. ostringstream S; // We will use a string stream for formatting.
  660. switch(R.Flag()) { // Identify the flag data for this IP.
  661. case Good: S << "Good "; break;
  662. case Bad: S << "Bad "; break;
  663. case Ugly: S << "Ugly "; break;
  664. case Ignore: S << "Ignore "; break;
  665. }
  666. S << "c=" << R.Confidence() << " " // Include the Confidence and
  667. << "p=" << R.Probability(); // Probability.
  668. // Process ordinary Source IP addresses
  669. if( // The message source IP address is the
  670. (false == ScanData->FoundSourceIP()) && // first IP we find that is either forced
  671. (ThisSourceIsForced || (Ignore != R.Flag())) // OR is NOT part of our infrastructure.
  672. ) { // When we find the correct source IP:
  673. if( // Check to see if we're drilling down.
  674. (false == ThisSourceIsForced) && // We drill when the source is NOT forced
  675. (ScanData->isDrillDownSource(I)) // AND we have a matching drilldown.
  676. ) {
  677. Lookup->setIgnore(IP); // If we're drilling down ignore this IP.
  678. }
  679. else { // If not drilling down this is the source:
  680. ScanData->SourceIPRecord(I); // we log it in as the source
  681. S << " Source"; // and report our findings in our tag.
  682. // Since we are dealing with our source IP
  683. // this is a good place to evaluate our truncate feature.
  684. snfIPRange IPR =
  685. ScanData->SourceIPRange(CFGData->RangeEvaluation(R)); // Establish the IP range for this scan.
  686. // We will also emit a range identifier for pattern matches that might use it.
  687. switch(IPR) {
  688. case Unknown: { S << " Unknown"; break; } // Unknown - not defined.
  689. case White: { S << " White"; break; } // This is a good guy.
  690. case Normal: { S << " Normal"; break; } // Benefit of the doubt.
  691. case New: { S << " New"; break; } // It is new to us.
  692. case Caution: { S << " Caution"; break; } // This is suspicious.
  693. case Black: { S << " Black"; break; } // This is bad.
  694. case Truncate: { S << " Truncate"; break; } // Don't even bother looking.
  695. }
  696. ScanData->SourceIPEvaluation = S.str(); // Capture the source IP eval.
  697. // The RangeEvaluation() call above settles a lot of questions for us.
  698. // The Truncate return code only happens when the IP is either Bad w/
  699. // truncate turned on, or the statistics place the IP in the Truncate
  700. // range. If the Good flag is set the function always returns White so
  701. // here we only have to check for the Truncate flag.
  702. if(Truncate == IPR) { // If all of the conditions are met
  703. ScanData->GBUdbTruncateTriggered = true; // then Truncate has been triggered.
  704. ScanData->GBUdbPeekTriggered = LOGmgr->OkToPeek( // Since truncate was triggered, see if
  705. CFGData->gbudb_regions_black_truncate_peek_one_in); // we would also trigger a peek.
  706. // The reason we check the truncate on_off flag here is that the
  707. // IP range _may_ return a Truncate result if no Flags are set on
  708. // the IP and the IP is far enough into the black to reach the
  709. // Truncate threshold.
  710. if(CFGData->gbudb_regions_black_truncate_on_off) { // If truncate is on either peek or truncate.
  711. if(ScanData->GBUdbPeekTriggered) { // If a peek has been triggered then
  712. ScanData->GBUdbPeekExecuted = true; // mark the event and don't truncate.
  713. } else { // If a peek was not triggered then
  714. ScanData->GBUdbTruncateExecuted = true; // Record our trucnate action.
  715. output = ""; // Set up the truncate signal (empty string)
  716. return output; // and return it! We're done!
  717. }
  718. }
  719. }
  720. }
  721. }
  722. // If we're not truncating then we're going to return our IP evaulation tag
  723. // to the filter chain function module so it can emit it into the stream.
  724. output.append(S.str());
  725. output.append("}");
  726. }
  727. catch(snfScanData::NoFreeIPScanRecords) {
  728. output = "{too_many}";
  729. }
  730. catch(...) {
  731. output = "{fault}";
  732. }
  733. return output;
  734. }
  735. //// Engine Handler Methods
  736. snf_EngineHandler::~snf_EngineHandler(){ // Shutdown clenas up and checks for safety.
  737. if(isReady()) close(); // If we're live, close on our way out.
  738. }
  739. void snf_EngineHandler::open(snf_RulebaseHandler* Handler){ // Light up the engine.
  740. MyMutex.lock(); // Serialize this...
  741. if(isReady()) { // If we're already open then we need to
  742. MyMutex.unlock(); // unlock this object and let them know
  743. throw Busy("snf_EngineHandler::open() busy"); // we are busy.
  744. } // If we're not busy, then let's light it up.
  745. MyRulebase=Handler; // Install our rulebase handler.
  746. MyRulebase->use(); // Up the use count to let it know we're here.
  747. MyIPTestEngine.setGBUdb(MyRulebase->MyGBUdb); // Set up the IPTester's GBUdb.
  748. MyIPTestEngine.setScanData(MyScanData); // Set up the IPTester's ScanData reference.
  749. MyIPTestEngine.setLOGmgr(MyRulebase->MyLOGmgr); // Set up the IPTester's LOGmgr.
  750. MyMutex.unlock(); // Unlock our mutex, then...
  751. return; // our work is done.
  752. }
  753. bool snf_EngineHandler::isReady(){ // Is the Engine good to go?
  754. return (NULL!=MyRulebase); // Have rulebase will travel.
  755. }
  756. void snf_EngineHandler::close(){ // Close down the engine.
  757. MyMutex.lock(); // Serialize this...
  758. if(!isReady()){ // If we're not already open we can't close.
  759. MyMutex.unlock(); // Something is seriously wrong, so unlock
  760. throw Panic("snf_EngineHandler::close() !isReady panic"); // and hit the panic button!
  761. } // But, if everything is ok then we can
  762. MyRulebase->unuse(); // unuse our rulebase and quietly forget
  763. MyRulebase = NULL; // about it.
  764. if(NULL!=CurrentMatrix) { // If we have a leftover evaluation matrix
  765. delete CurrentMatrix; // we can let that go and forget about
  766. CurrentMatrix = NULL; // it as well.
  767. }
  768. MyMutex.unlock(); // Finally, we unlock our mutex and...
  769. return; // Our work is done here.
  770. }
  771. enum PatternResultTypes { // To train GBUdb we need a generalized
  772. NoPattern, // way to evaluate the results from the
  773. WhitePattern, // snf pattern matching scan.
  774. BlackPattern,
  775. IPPattern,
  776. AboveBandPattern
  777. };
  778. int snf_EngineHandler::scanMessageFile( // Scan this message file.
  779. const string MessageFilePath, // -- this is the file path (and id)
  780. const int MessageSetupTime, // -- setup time already used.
  781. const IP4Address MessageSource // -- message source IP (for injection).
  782. ) {
  783. Timer AdditionalSetupTime;
  784. ScopeMutex DoingAFileScan(FileScan); // Protect MyScanData @ this entry.
  785. // Preliminary setup. Clearing the ScanData resets the ReadyToClear flag
  786. // and allows us to set some data for more accurate tracking and so that if
  787. // something goes wrong the ScanData will be helpful in determining the
  788. // state of the engine.
  789. MyScanData.clear(); // Clear the scan data.
  790. MyScanData.StartOfJobUTC = MyRulebase->MyLOGmgr.Timestamp(); // Set the job start timestamp.
  791. MyScanData.ScanName = MessageFilePath;
  792. // Now that the preliminaries are established we can begin our work.
  793. int MessageFileSize = 0; // Here will be the size of it.
  794. ifstream MessageFile; // Here will be our input file.
  795. MessageFile.exceptions( // It will throw exceptions for
  796. ifstream::eofbit | ifstream::failbit | ifstream::badbit // these unwanted events.
  797. );
  798. try { // Try opening the message file.
  799. MessageFile.open(MessageFilePath.c_str(), ios::in | ios::binary); // Open the file, binary mode.
  800. MessageFile.seekg(0, ios::end); // Find the end of the file,
  801. MessageFileSize = MessageFile.tellg(); // read that position as the size,
  802. MessageFile.seekg(0, ios::beg); // then go back to the beginning.
  803. MyScanData.ScanSize = MessageFileSize; // Capture the message file size.
  804. }
  805. catch(...) { // Trouble? Throw FileError.
  806. MyRulebase->MyLOGmgr.logThisError( // Log the error.
  807. MyScanData, "scanMessageFile().open",
  808. snf_ERROR_MSG_FILE, "ERROR_MSG_FILE"
  809. );
  810. throw FileError("snf_EngineHandler::scanMessageFile() Open/Seek");
  811. }
  812. if(0 >= MessageFileSize) { // Handle zero length files.
  813. MessageFile.close(); // No need to keep this open.
  814. MyRulebase->MyLOGmgr.logThisError( // Log the error.
  815. MyScanData, "scanMessageFile().isFileEmpty?",
  816. snf_ERROR_MSG_FILE, "ERROR_MSG_FILE"
  817. );
  818. throw FileError("snf_EngineHandler::scanMessageFile() FileEmpty!");
  819. }
  820. boolean NoNeedToReadFullFile = (false == MyScanData.XHeaderInjectOn);
  821. boolean FileSizeLargerThanScanHorizon = (MessageFileSize > snf_ScanHorizon);
  822. if(NoNeedToReadFullFile && FileSizeLargerThanScanHorizon) {
  823. MessageFileSize = snf_ScanHorizon;
  824. }
  825. vector<unsigned char> MessageBuffer; // Allocate a buffer and size
  826. try { MessageBuffer.resize(MessageFileSize, 0); } // it to fit the message.
  827. catch(...) { // Trouble? Throw AllocationError.
  828. MyRulebase->MyLOGmgr.logThisError( // Log the error.
  829. MyScanData, "scanMessageFile().alloc",
  830. snf_ERROR_MSG_FILE, "ERROR_MSG_ALLOC"
  831. );
  832. throw AllocationError("snf_EngineHandler::scanMessageFile() Alloc");
  833. }
  834. try { MessageFile.read((char*) &MessageBuffer[0], MessageFileSize); } // Read the file into the buffer.
  835. catch(...) {
  836. MyRulebase->MyLOGmgr.logThisError( // Log the error.
  837. MyScanData, "scanMessageFile().read",
  838. snf_ERROR_MSG_FILE, "ERROR_MSG_READ"
  839. );
  840. throw FileError("snf_EngineHandler::scanMessageFile() Read");
  841. }
  842. MessageFile.close(); // Close the file.
  843. // Additional Setup Time will be captured as the call is made.
  844. int ScanResultCode = scanMessage( // Scan the message we've loaded.
  845. &MessageBuffer[0], // Here is the buffer pointer,
  846. MessageBuffer.size(), // here is the size of the message,
  847. MessageFilePath, // the path is the identifier,
  848. (AdditionalSetupTime.getElapsedTime() + MessageSetupTime), // and this is our setup time total.
  849. MessageSource // Pass on the source if provided.
  850. );
  851. // Inject headers if required.
  852. if(MyScanData.XHeaderInjectOn) { // If we are to inject headers:
  853. const char* XHDRInjStage = "Begin"; // Keep track of what we're doing.
  854. try {
  855. // The insertion point will be at the end of the existing headers.
  856. // We pick that point to be right between the two <cr><lf> so that
  857. // the first blank line will appear at the end of our headers.
  858. // We accommodate either <cr><lf> or <lf> line endings.
  859. // We are careful not to search past the end of unreasonably short
  860. // message files.
  861. unsigned int InsertPoint = 0; // Find the insertion point.
  862. bool UseLFOnly = false; // Use \n line endings in files?
  863. bool CRLFPresent = false; // Detected \r\n pairs?
  864. unsigned int BiggestPatternSize = 4; // How far we look ahead.
  865. bool BigEnoughMessage = BiggestPatternSize < MessageBuffer.size();
  866. if(BigEnoughMessage){
  867. unsigned int Limit = MessageBuffer.size() - BiggestPatternSize;
  868. bool DataWasSkipped = MessageBuffer.size() > MyScanData.ScanSize;
  869. unsigned int i = 0;
  870. if(DataWasSkipped) { // If our scanner skipped data at
  871. i = MessageBuffer.size() - MyScanData.ScanSize; // the top of the message buffer then
  872. } // we will skip it too.
  873. for(; i < Limit; i++) { // Search for the first blank line.
  874. if( // Detect CRLF pairs if present.
  875. false == CRLFPresent &&
  876. '\r' == MessageBuffer.at(i) &&
  877. '\n' == MessageBuffer.at(i + 1)
  878. ) CRLFPresent = true;
  879. if( // In a properly formatted RFC822
  880. '\r' == MessageBuffer.at(i) && // message that looks like
  881. '\n' == MessageBuffer.at(i + 1) && // <cr><lf><cr><lf>
  882. '\r' == MessageBuffer.at(i + 2) &&
  883. '\n' == MessageBuffer.at(i + 3)
  884. ) {
  885. InsertPoint = i + 2;
  886. break;
  887. } else
  888. if( // In some bizarre cases it might
  889. '\n' == MessageBuffer.at(i) && // look like <lf><lf>.
  890. '\n' == MessageBuffer.at(i + 1)
  891. ) {
  892. InsertPoint = i + 1;
  893. UseLFOnly = true; // We have to strip <CR> from our
  894. break; // injected header line ends.
  895. }
  896. }
  897. }
  898. // Here we must interpret the results of our search. Do we know where
  899. // our insert point is or do we punt and use the top of the message?
  900. if(0 == InsertPoint) { // No blank line? We need to punt.
  901. if(false == CRLFPresent) { // What kind of line ends do we use?
  902. UseLFOnly = true; // If no CRLF found use LF only.
  903. } // Either way we will be inserting
  904. } // our headers at the top of the msg.
  905. // At this point we know where to split the message and insert
  906. // our X Headers.
  907. XHDRInjStage = "Open Temp File"; // Update our process monitor.
  908. string TempFileName = MessageFilePath; // Prepare a temp file name
  909. TempFileName.append(".tmp"); // based on the message file.
  910. ofstream TempFile; // Here will be our temp file.
  911. TempFile.exceptions(ofstream::failbit | ofstream::badbit); // It will throw these exceptions.
  912. TempFile.open(TempFileName.c_str(), ios::binary | ios::trunc); // Open and truncate the file.
  913. // If our insert point is the top of the message we'll skip this.
  914. if(0 < InsertPoint) { // If we have an insert point:
  915. XHDRInjStage = "Write Temp File.1"; // Update our process monitor.
  916. TempFile.write( // Write the message file up
  917. reinterpret_cast<char*>(&MessageBuffer[0]), // to our split.
  918. InsertPoint
  919. );
  920. }
  921. // If our file has \n line ends we need to strip the \r from our
  922. // rfc822 \r\n line ends.
  923. XHDRInjStage = "XHDR <CR><LF> to <LF>";
  924. if(true == UseLFOnly) { // If we are using <LF> only:
  925. string ReworkedHeaders = ""; // Make a new string and rework
  926. for( // our headers.
  927. string::iterator iS = MyScanData.XHDRsText.begin(); // Run through the headers one
  928. iS != MyScanData.XHDRsText.end(); iS++ // byte at a time.
  929. ) {
  930. if('\r' != (*iS)) ReworkedHeaders.push_back(*iS); // Strip out any <CR> chars.
  931. }
  932. MyScanData.XHDRsText.swap(ReworkedHeaders); // Swap in our reworked headers.
  933. }
  934. // Now we are ready to inject our headers.
  935. XHDRInjStage = "Write Temp File.2"; // Update our process monitor.
  936. TempFile.write( // Inject our headers.
  937. MyScanData.XHDRsText.c_str(),
  938. MyScanData.XHDRsText.length()
  939. );
  940. XHDRInjStage = "Write Temp File.3"; // Update our process monitor.
  941. TempFile.write( // Write the rest of the message.
  942. reinterpret_cast<char*>(&MessageBuffer[InsertPoint]),
  943. MessageBuffer.size() - InsertPoint
  944. );
  945. XHDRInjStage = "Close Temp File"; // Update our process monitor.
  946. TempFile.close(); // Close the file (flushing it).
  947. Sleeper PauseBeforeRetry(300); // Delay to use between retries.
  948. XHDRInjStage = "Drop Msg"; // Update our process monitor.
  949. if(remove(MessageFilePath.c_str())) { // Remove the old message file
  950. PauseBeforeRetry(); // If it fails, pause and retry.
  951. if(remove(MessageFilePath.c_str())) { // If that fails,
  952. PauseBeforeRetry(); // pause, then try once more.
  953. if(remove(MessageFilePath.c_str())) { // If that fails, throw.
  954. throw XHDRError("XHDR injector can't remove original!");
  955. }
  956. }
  957. }
  958. XHDRInjStage = "Rename Temp -> Msg"; // Update our process monitor.
  959. if(rename(TempFileName.c_str(), MessageFilePath.c_str())) { // Make Temp our new message file.
  960. PauseBeforeRetry(); // If it fails, pause and retry.
  961. if(rename(TempFileName.c_str(), MessageFilePath.c_str())) { // If that fails,
  962. PauseBeforeRetry(); // pause then try once more.
  963. if(rename(TempFileName.c_str(), MessageFilePath.c_str())) { // If that fails, throw.
  964. throw XHDRError("XHDR injector can't rename tmp file!");
  965. }
  966. }
  967. }
  968. }
  969. catch(XHDRError& e) { // For full XHDRError exceptions.
  970. string ERROR_MSG_XHDRi = "ERROR_MSG_XHDRi: "; // Format the XHDRInj error msg.
  971. ERROR_MSG_XHDRi.append(XHDRInjStage);
  972. ERROR_MSG_XHDRi.append(" ");
  973. ERROR_MSG_XHDRi.append(e.what());
  974. MyRulebase->MyLOGmgr.logThisError( // Log the error.
  975. MyScanData, "scanMessageFile().xhdr.inject",
  976. snf_ERROR_MSG_FILE, ERROR_MSG_XHDRi
  977. );
  978. throw; // Rethrow any XHDRError exceptions.
  979. }
  980. catch(exception& e) { // For ordinary runtime exceptions.
  981. string ERROR_MSG_XHDRi = "ERROR_MSG_XHDRi: "; // Format the XHDRInj error msg.
  982. ERROR_MSG_XHDRi.append(XHDRInjStage);
  983. ERROR_MSG_XHDRi.append(" ");
  984. ERROR_MSG_XHDRi.append(e.what());
  985. MyRulebase->MyLOGmgr.logThisError( // Log the error.
  986. MyScanData, "scanMessageFile().xhdr.inject",
  987. snf_ERROR_MSG_FILE, ERROR_MSG_XHDRi
  988. );
  989. throw XHDRError(ERROR_MSG_XHDRi); // Rethrow as XHDRError exceptions.
  990. }
  991. catch(...) { // If we encounter a problem then
  992. string ERROR_MSG_XHDRi = "ERROR_MSG_XHDRi: "; // Format the XHDRInj error msg.
  993. ERROR_MSG_XHDRi.append(XHDRInjStage);
  994. MyRulebase->MyLOGmgr.logThisError( // Log the error.
  995. MyScanData, "scanMessageFile().xhdr.inject",
  996. snf_ERROR_MSG_FILE, ERROR_MSG_XHDRi
  997. );
  998. string XHDRError_msg = "Message Rewrite Failed: "; // Format our throw message with
  999. XHDRError_msg.append(XHDRInjStage); // our detailed stage data and
  1000. throw XHDRError(XHDRError_msg); // throw our special exception.
  1001. }
  1002. }
  1003. // Create an .xhdr file if required.
  1004. if(MyScanData.XHeaderFileOn) {
  1005. try {
  1006. ofstream XHDRFile; // Output file will be XHDRFile.
  1007. XHDRFile.exceptions(ofstream::failbit | ofstream::badbit); // These events will throw exceptions.
  1008. string XHDRFileName = MessageFilePath; // Build the XHDR file name by adding
  1009. XHDRFileName.append(".xhdr"); // .xhdr to the message file name.
  1010. XHDRFile.open(XHDRFileName.c_str(), ios::binary | ios::trunc); // Open (and truncate) the file.
  1011. XHDRFile << MyScanData.XHDRsText; // Spit out the XHDRs.
  1012. XHDRFile.close(); // All done.
  1013. }
  1014. catch(...) { // If we encounter a problem then
  1015. MyRulebase->MyLOGmgr.logThisError( // Log the error.
  1016. MyScanData, "scanMessageFile().xhdr.file",
  1017. snf_ERROR_MSG_FILE, "ERROR_MSG_XHDRf"
  1018. );
  1019. throw XHDRError(".xhdr file write failed"); // throw our special exception.
  1020. }
  1021. }
  1022. return ScanResultCode; // Return the actual result, of course.
  1023. }
  1024. string snf_EngineHandler::extractMessageID( // Find and return the first Message-ID
  1025. const unsigned char* Msg, // Input the Message buffer to search
  1026. const int Len // and the length of the buffer.
  1027. ) {
  1028. string ExtractedID = ""; // Start with an empty string.
  1029. bool FoundID = false; // Haven't found it yet.
  1030. int C = 0; // Cursor position.
  1031. while(!FoundID && (C < (Len - 12))) { // Loop through the Msg looking for
  1032. if( // the Message-ID: header.
  1033. ('\n' == Msg[C]) && // Starting at the new line find
  1034. ('M' == Msg[C + 1] || 'm' == Msg[C + 1]) && // Message-ID: (per RFC822)
  1035. ('e' == Msg[C + 2] || 'E' == Msg[C + 2]) &&
  1036. ('s' == Msg[C + 3] || 'S' == Msg[C + 3]) && // We use an unrolled comparison
  1037. ('s' == Msg[C + 4] || 'S' == Msg[C + 4]) && // loop here for raw speed and
  1038. ('a' == Msg[C + 5] || 'A' == Msg[C + 5]) && // optimization. Note that we
  1039. ('g' == Msg[C + 6] || 'G' == Msg[C + 6]) && // compare the most likely characters
  1040. ('e' == Msg[C + 7] || 'E' == Msg[C + 7]) && // first in each case, and we don't
  1041. ('-' == Msg[C + 8]) && // need to go through a buffer length
  1042. ('I' == Msg[C + 9] || 'i' == Msg[C + 9]) && // check at each byte for partial
  1043. ('D' == Msg[C + 10] || 'd' == Msg[C + 10]) && // matches.
  1044. (':' == Msg[C + 11]) &&
  1045. (' ' == Msg[C + 12] || '\t' == Msg[C + 12])
  1046. ) {
  1047. C = C + 13; // Starting just after the space
  1048. while(C < Len) { // and staying within bounds
  1049. unsigned char X = Msg[C]; // grab each character in the ID.
  1050. if(isprint(X)) { // If it is printable,
  1051. if(' ' == X) X = '_'; // massage out the spaces as _ and
  1052. if(127 < X) X = '|'; // high characters as | and
  1053. if('\'' == X || '\"' == X) X = '`'; // ' or " to ` in order to make the
  1054. ExtractedID.push_back(X); // ID safe for logging, then push
  1055. } else // the result into our string. When
  1056. if('\r' == X || '\n' == X) break; /* leave copy loop */ // we reach the end we're done.
  1057. ++C; // else get ready for the next byte.
  1058. }
  1059. FoundID = true; // Set the flag: we found Message-ID:
  1060. break; /* leave search loop */ // We got what we came for. Break!
  1061. } else { // When we don't find the Message-ID:
  1062. if( // we check for end of headers.
  1063. ('\n' == Msg[C] && '\n' == Msg[C+1]) || // Either <LF><LF> or
  1064. ('\r' == Msg[C] && '\n' == Msg[C+1] && // <CR><LF><CF><LF>
  1065. '\r' == Msg[C+2] && '\n' == Msg[C+3])
  1066. ) { // If we've found the end of headers
  1067. break; // we're done looking. If we did not
  1068. } // find the end of headers then
  1069. ++C; // we move to the next position.
  1070. }
  1071. }
  1072. // At this point we either have the Extracted ID, or we need a substitute.
  1073. if(0 == ExtractedID.length()) { // If we need a substitute ID then
  1074. MyRulebase->MyLOGmgr.SerialNumber(ExtractedID); // use the next available serial number.
  1075. }
  1076. return ExtractedID; // Return the extracted id or substitute.
  1077. }
  1078. const LogicFault FaultBadMessageBuffer1("snf_EngineHandler::scanMessage():FaultBadMessageBuffer1(NULL == inputMessageBuffer)");
  1079. const LogicFault FaultBadMessageBuffer2("snf_EngineHandler::scanMessage():FaultBadMessageBuffer2(0 >= inputMessageLength)");
  1080. const char Unknown_SNFMatchFlag = '-';
  1081. const char Panic_SNFMatchFlag = 'p';
  1082. const char Match_SNFMatchFlag = 'm';
  1083. const char White_SNFMatchFlag = 'w';
  1084. const char Final_SNFMatchFlag = 'f';
  1085. void captureMatchRecord(snf_match& M, MatchRecord* R) {
  1086. M.flag = Unknown_SNFMatchFlag;
  1087. M.ruleid = R->RuleId();
  1088. M.symbol = R->RuleGroup();
  1089. M.index = R->MatchStartPosition;
  1090. M.endex = R->MatchEndPosition;
  1091. }
  1092. int snf_EngineHandler::scanMessage( // Scan this message (in buffer).
  1093. const unsigned char* inputMessageBuffer, // -- this is the message buffer.
  1094. const int inputMessageLength, // -- this is the length of the buffer.
  1095. const string MessageName, // -- this is the message identifier.
  1096. const int MessageSetupTime, // -- setup time used (for logging).
  1097. const IP4Address MessageSource // -- message source IP (for injection).
  1098. ) {
  1099. ScopeTimer ScanTimeCapture(MyScanData.ScanTime); // Start the scan time clock.
  1100. unsigned char* MessageBuffer = NULL; // Explicitly initialize these two
  1101. int MessageLength = 0; // so the compiler will be happy.
  1102. FaultBadMessageBuffer1(NULL == inputMessageBuffer); // Fault on null message buffer.
  1103. FaultBadMessageBuffer2(0 >= inputMessageLength); // Fault on bad message bfr length.
  1104. // Protect this engine - only one scan at a time per EngineHandler ;-)
  1105. ScopeMutex ScannerIsBusy(MyMutex); // Serialize this...
  1106. // Preliminary job setup.
  1107. // In our pre-processing we may adjust our input buffer so we capture the
  1108. // originals and then use the captured values. For example if we are scanning
  1109. // Communigate message files we will want to skip the communigate headers.
  1110. MessageBuffer = const_cast<unsigned char*>(inputMessageBuffer); // Capture the input buffer.
  1111. MessageLength = inputMessageLength; // Capture the input length.
  1112. MyScanData.clear(); // Clear the scan data.
  1113. MyScanData.ScanSize = MessageLength; // Grab the message length.
  1114. MyScanData.SetupTime = MessageSetupTime; // Capture the setup time.
  1115. if(0 == MyScanData.StartOfJobUTC) { // If the job timestamp is not
  1116. MyScanData.StartOfJobUTC = MyRulebase->MyLOGmgr.Timestamp(); // yet set then set it.
  1117. }
  1118. MyScanData.CallerForcedSourceIP(MessageSource); // Capture the MessageSource if any.
  1119. // Special note about exceptions here...
  1120. // Setting up the filter chain can throw an exception. It can't go in it's own try block or it will
  1121. // be out of scope for the remainder of the function... SO, I've wrapped everything inside of the
  1122. // Lock() in a try block ... and there's a nested one also for scanning the content. The result is
  1123. // that I can put all of the unlock work in the "outer" try block and re-throw anything that's
  1124. // needed.
  1125. snfCFGPacket MyCFGPacket(MyRulebase); // We need this to stay in scope.
  1126. // Set up the filter chain, configure the scanner, and scan the message.
  1127. try {
  1128. if(MyCFGPacket.bad()) { // If it's not there it's a big problem.
  1129. throw Panic("snf_EngineHandler::scanMessage() MyCFGPacket.bad()");
  1130. }
  1131. // Adapt to CGP message files - skip the CGP headers
  1132. MyScanData.MessageFileTypeCGPOn = // Find out if we are expecting
  1133. MyCFGPacket.Config()->MessageFileTypeCGP_on_off; // Communigate message files.
  1134. if(MyScanData.MessageFileTypeCGPOn) { // If we are scanning CGP files:
  1135. while(4 < MessageLength) { // Skip over the CGP headers.
  1136. if( // On Winx systems look for the first
  1137. '\r' == MessageBuffer[0] && // blank line encoded as CRLF CRLF.
  1138. '\n' == MessageBuffer[1] &&
  1139. '\r' == MessageBuffer[2] &&
  1140. '\n' == MessageBuffer[3]
  1141. ) { // If we find it then skip past
  1142. MessageBuffer += 4; // the new line and break out
  1143. MessageLength -= 4; // of the loop.
  1144. break;
  1145. } else // On *nix systems look for the first
  1146. if( // blank line encoded as LF LF.
  1147. '\n' == MessageBuffer[0] &&
  1148. '\n' == MessageBuffer[1]
  1149. ) { // If we find it then skip past
  1150. MessageBuffer += 2; // the blank line and break out
  1151. MessageLength -= 2; // of the loop.
  1152. break;
  1153. }
  1154. else { // If we don't find it then
  1155. ++MessageBuffer; // eat one byte from the buffer
  1156. --MessageLength; // and keep going.
  1157. }
  1158. }
  1159. // At this point our MessagBuffer contains just the message we
  1160. // want to scan.
  1161. MyScanData.ScanSize = MessageLength; // Reset the scan size.
  1162. }
  1163. // Identify this message.
  1164. if( // How do we identify this scan?
  1165. 0 == MessageName.length() || // If no name was provided or
  1166. true == MyCFGPacket.Config()->Scan_Identifier_Force_Message_Id // we are forcing RFC822 IDs then
  1167. ) { // extract the Message-ID from the
  1168. MyScanData.ScanName = extractMessageID(MessageBuffer, MessageLength); // message and use that.
  1169. } else { // If a name was provided and we
  1170. MyScanData.ScanName = MessageName; // are not forcing RFC822 IDs then
  1171. } // use the name provided to us.
  1172. // Set up our filter chain.
  1173. stringstream PrependedHeaders; // Use this to prepend X-Headers.
  1174. FilterChainCBFR IU(MessageBuffer, MessageLength, PrependedHeaders); // Set up the filter chain.
  1175. FilterChainHeaderAnalysis IV(&IU, MyIPTestEngine); // Include header analysis.
  1176. FilterChainBase64 IW(&IV); // Include Base64 decoding.
  1177. FilterChainQuotedPrintable IX(&IW); // Include Quoted Printable decoding.
  1178. FilterChainUrlDecode IY(&IX); // Include URL decoder.
  1179. FilterChainDefunker IZ(&IY); // Include Defunking.
  1180. // Now we set up our scanner and grab the current token matrix.
  1181. if(NULL!=CurrentMatrix) { delete CurrentMatrix; CurrentMatrix=NULL; } // If we have old results, delete them.
  1182. try {
  1183. CurrentMatrix = new EvaluationMatrix(MyCFGPacket.Tokens()); // Allocate a new matrix for this scan.
  1184. } catch(...) { // Check that the allocation worked.
  1185. throw AllocationError("new EvaluationMatrix() ???");
  1186. }
  1187. // Here we get down to it and start scanning the message.
  1188. const char* DebugInfo = "scanMessage() Begin Message Scan"; // If we panic, here we are.
  1189. try {
  1190. // The IPTestEngine has the ability to truncate the message in the filter
  1191. // chain under certain conditions. In order to configure those conditions
  1192. // the IPTestEngine needs to have the configuration data being used for
  1193. // the current scan.
  1194. DebugInfo = "scanMessage() setCFGData()"; // If we panic, here we are.
  1195. MyIPTestEngine.setCFGData(*(MyCFGPacket.Config())); // Setup the CFG data to use.
  1196. // Check processed headers for header directive rules. One of these might
  1197. // include a directive to get the message source IP from a header. If so
  1198. // then MyScanData will have been modified. Also if there are drill-down
  1199. // directives then MyScanData will have been modified to mark any headers
  1200. // that should be ignored -- in this case the IP test used in the filter
  1201. // chain will take appropriate action as it comes across the Received
  1202. // headers that have been marked.
  1203. DebugInfo = "scanMessage() Get Header Directives";
  1204. MyScanData.HeaderDirectiveFlags = 0x00000000; // Clear the header directive flags.
  1205. if(0 < MyCFGPacket.Config()-> // Check to see if we have any
  1206. HeaderDirectivesHandler.HeaderDirectives.size()) { // header directive rules and if we do:
  1207. HeaderFinder HeaderDirectivesParser( // Parse the headers in the message
  1208. &MyScanData, // and update the ScanData using the
  1209. MyCFGPacket.Config()->HeaderDirectivesHandler.HeaderDirectives, // directives in our configuration packet.
  1210. MessageBuffer, // Pass the message as a pointer with
  1211. MessageLength // a specific buffer length.
  1212. );
  1213. MyScanData.HeaderDirectiveFlags = HeaderDirectivesParser(); // Capture the parsed results.
  1214. }
  1215. // Message header rules in earlier versions occasionally failed because there was not
  1216. // a new-line character in front of the very first header. So, now we insert one :-)
  1217. // This allows all header rules to start off with a ^ indicating the start of the line.
  1218. // 20070719_M Added \n to X-snfScanSize: synthetic header.
  1219. // 20070120_M There are some messages where the size is a specific part of
  1220. // the pattern so we will now be emitting this data into the engine. A later
  1221. // version of the engine should handle this kind of thing using a special
  1222. // filter chain module.
  1223. DebugInfo = "scanMessage() ^X-snfScanSize"; // If we panic here we are.
  1224. // Build the scan size info
  1225. PrependedHeaders << "X-snfScanSize: " << MyScanData.ScanSize << "\n"; // and format as an X- header.
  1226. // Add a phantom received header to the top IF the message source has been
  1227. // forced by the caller or by a header directive. After that the normal
  1228. // scanning and header analysis process should pick up the IP as the
  1229. // source of the message. (It will not if the IP is ignored in the GBUdb!)
  1230. DebugInfo = "scanMessage() PhantomReceived"; // If we panic we are here.
  1231. if(0UL != MyScanData.CallerForcedSourceIP()) { // If the caller forced the source IP:
  1232. PrependedHeaders // Make a phantom Received header
  1233. << "Received: Caller.Forced.Source.IP [" // showing that the caller forced
  1234. << (string) MyScanData.CallerForcedSourceIP() << "]\n"; // the source IP.
  1235. } else
  1236. // If not forced by the caller but a
  1237. if(0UL != MyScanData.HeaderDirectiveSourceIP()) { // header directive forced the source IP:
  1238. PrependedHeaders // Make a phantom Received header
  1239. << "Received: Header.Directive.Source.IP [" // showing that a header directive
  1240. << (string) MyScanData.HeaderDirectiveSourceIP() << "]\n"; // established the source IP.
  1241. }
  1242. // Most of the time we will extract the source IP the normal way.
  1243. // If there are other prepended headers to add they should go here.
  1244. /** Add other prepended headers **/
  1245. // 20070719_M Reworked the engine to handle the filter-chain section in
  1246. // a tight loop separately from the scanning section. This should allow
  1247. // for tighter optimization in some cases (less cache thrashing) and also
  1248. // provides for later development of parallel analysis of the pre-filtered
  1249. // data, as well as the ability to output the pre-filtered data for use in
  1250. // rule development and debugging.
  1251. DebugInfo = "scanMessage() IZ.GetByte() ==> FilteredData"; // If we panic we are here.
  1252. unsigned char xb=0;
  1253. MyScanData.FilteredData.clear(); // Clear the FilteredData buffer.
  1254. try { // Watch for exceptions and scan
  1255. for(int a = 0; a < snf_ScanHorizon; a++) // the message through the filter
  1256. MyScanData.FilteredData.push_back(xb=IZ.GetByte()); // chain into the FilteredData buffer.
  1257. } // When we run out of data we will
  1258. catch(FilterChain::Empty) {} // get the Empty exception and stop.
  1259. // Scan each byte in the file up to the horizon or the end of the message.
  1260. // If something goes wrong, an exception will be thrown.
  1261. DebugInfo = "scanMessage() EvaluateThis(FilteredData)"; // If we panic, here we are.
  1262. if(false == MyScanData.GBUdbTruncateExecuted) { // If we haven't already truncated:
  1263. for(int a = 0, b = MyScanData.FilteredData.size(); a < b; a++) // Scan through the filtered data one
  1264. CurrentMatrix->EvaluateThis(MyScanData.FilteredData[a]); // byte at a time.
  1265. }
  1266. DebugInfo = "scanMessage() Scan Data Complete"; // If we panic, here we are.
  1267. }
  1268. catch(EvaluationMatrix::BadAllocation) { // Check for bad allocation during scan.
  1269. throw AllocationError("EvaluationMatrix::BadAllocation");
  1270. }
  1271. catch(EvaluationMatrix::MaxEvalsExceeded) { // Check for too many evaluators.
  1272. throw MaxEvals("EvaluationMatrix::MaxEvalsExceeded");
  1273. }
  1274. catch(EvaluationMatrix::OutOfRange) { // Check for out of range of (bad) matrix.
  1275. throw BadMatrix("EvaluationMatrix::OutOfRange");
  1276. }
  1277. catch(exception& e) { // Some other known exception?
  1278. throw; // rethrow.
  1279. }
  1280. catch(...){ // In order to prevent thread craziness
  1281. throw Panic(DebugInfo); // throw a Panic.
  1282. } // The mutex will unlock in the outer try.
  1283. }
  1284. // Here is the end of the outer try block. We can catch and rethrow whatever happend
  1285. // and we can also keep our mutex properly managed.
  1286. catch(AllocationError& e) { // Allocation Errors pass through.
  1287. MyRulebase->MyLOGmgr.logThisError( // Log the error.
  1288. MyScanData, "scanMessage()",
  1289. snf_ERROR_ALLOCATION, "ERROR_ALLOCATION"
  1290. );
  1291. throw;
  1292. }
  1293. catch(MaxEvals& e) { // MaxEvals == Panic, with a log.
  1294. MyRulebase->MyLOGmgr.logThisError( // Log the error.
  1295. MyScanData, "scanMessage()",
  1296. snf_ERROR_MAX_EVALS, "ERROR_MAX_EVALS"
  1297. );
  1298. throw;
  1299. }
  1300. catch(BadMatrix& e) { // BadMatrix == Panic, with a log.
  1301. MyRulebase->MyLOGmgr.logThisError( // Log the error.
  1302. MyScanData, "scanMessage()",
  1303. snf_ERROR_BAD_MATRIX, "ERROR_BAD_MATRIX"
  1304. );
  1305. throw;
  1306. }
  1307. catch(Panic& e) { // Panic is panic.
  1308. MyRulebase->MyLOGmgr.logThisError( // Log the error.
  1309. MyScanData, "scanMessage()",
  1310. snf_ERROR_BAD_MATRIX, "ERROR_PANIC"
  1311. );
  1312. throw;
  1313. }
  1314. catch(exception& e) { // Other exceptions.
  1315. MyRulebase->MyLOGmgr.logThisError( // Log the error.
  1316. MyScanData, "scanMessage()",
  1317. snf_ERROR_UNKNOWN, "ERROR_EXCEPTION"
  1318. );
  1319. throw;
  1320. }
  1321. catch(...) { // Anything else == Panic.
  1322. MyRulebase->MyLOGmgr.logThisError( // Log the error.
  1323. MyScanData, "scanMessage()",
  1324. snf_ERROR_UNKNOWN, "ERROR_UNKNOWN"
  1325. );
  1326. throw Panic("snf_EngineHandler::scanMessage() ERROR_UNKNOWN!");
  1327. }
  1328. // At this point, we've completed our scan and we're ready to evaluate our results to find the correct symbol to return.
  1329. ResultsCount = 0; // Reset the count,
  1330. ResultsRemaining = 0; // Remaining count,
  1331. FinalResult = NULL; // Final Result marker,
  1332. ResultCursor = CurrentMatrix -> ResultList; // And cursor position for our results.
  1333. // Now that our result processing gadgets are reset, let's process the results list.
  1334. int const CLEAN_RESULT = 0; // CLEAN means no matches or white.
  1335. int const NO_SYMBOL = 999; // NO_SYMBOL is higher than any SYMBOL
  1336. int S = NO_SYMBOL; // so we start there and work down.
  1337. snf_match TmpSNFMatch; // We'll need a buffer for our matches.
  1338. while(NULL!=ResultCursor) { // While we have records to process...
  1339. captureMatchRecord(TmpSNFMatch, ResultCursor); // grab the next record and evaluate it.
  1340. bool isPanickedRule = MyCFGPacket.isRulePanic(TmpSNFMatch.ruleid);
  1341. bool isVotingCandidate = (false == isPanickedRule);
  1342. bool isWhiteRule = (
  1343. MyCFGPacket.Config()->TrainingWhiteRuleHandler.isListed(TmpSNFMatch.ruleid) ||
  1344. 0 == TmpSNFMatch.symbol
  1345. );
  1346. bool isBestResultCode = (TmpSNFMatch.symbol < S);
  1347. // Set an appropriate flag.
  1348. if(isPanickedRule) TmpSNFMatch.flag = Panic_SNFMatchFlag;
  1349. else if(isWhiteRule) TmpSNFMatch.flag = White_SNFMatchFlag;
  1350. else TmpSNFMatch.flag = Match_SNFMatchFlag;
  1351. // Vote for best rule match.
  1352. if(isVotingCandidate && isBestResultCode) {
  1353. FinalResult = ResultCursor;
  1354. S = TmpSNFMatch.symbol;
  1355. }
  1356. // Move on to next result.
  1357. ResultsCount++;
  1358. ResultCursor=ResultCursor->NextMatchRecord;
  1359. }
  1360. if(NO_SYMBOL != S) { // If a pattern match was detected then
  1361. MyScanData.PatternWasFound = true; // trip the flag and record the
  1362. MyScanData.PatternID = FinalResult->RuleId(); // Rule ID and the
  1363. MyScanData.PatternSymbol = FinalResult->RuleGroup(); // Symbol.
  1364. }
  1365. //// GBUdb Integration ///////////////////////////////////////////////////////
  1366. // To integrate GBUdb we need to generalize the result from the pattern scan.
  1367. PatternResultTypes ScanResultType = NoPattern; // What kind of result have we here?
  1368. if(0 < (MyScanData.HeaderDirectiveFlags & HeaderDirectiveWhite)) { // If a white header directive matched
  1369. ScanResultType = WhitePattern; // then we have a "WhitePattern'.
  1370. } else
  1371. if(MyCFGPacket.Config()->TrainingWhiteRuleHandler.isListed(S)) { // If the pattern was mapped to a white
  1372. ScanResultType = WhitePattern; // rule group then we have a 'WhitePattern'.
  1373. } else
  1374. if(CLEAN_RESULT == S) { // If there was a standard white rule
  1375. ScanResultType = WhitePattern; // result then we have a 'WhitePattern'.
  1376. } else
  1377. if(NO_SYMBOL == S) { // If there was no pattern match then
  1378. ScanResultType = NoPattern; // we have 'NoPattern'.
  1379. } else
  1380. if(63 == S) { // If the pattern was a standard IP rule
  1381. ScanResultType = IPPattern; // then we have an 'IPPattern'.
  1382. } else
  1383. if(62 >= S) { // In general, other nonzer rule groups
  1384. ScanResultType = BlackPattern; // indicate we have a 'BlackPatter'.
  1385. } else
  1386. if(63 < S) { // Any pattern number > 63 is special.
  1387. ScanResultType = AboveBandPattern; // Any of these are an 'AboveBandPattern'
  1388. }
  1389. if(MyScanData.FoundSourceIP()) { // We need an identified IP source.
  1390. // Train the GBUdb based on our pattern matching results.
  1391. // Evaluate our training conditions.
  1392. bool TrainingIsTurnedOn = MyCFGPacket.Config()->GBUdbTrainingOn_Off;
  1393. bool MessageWasNotTruncated = (false == MyScanData.GBUdbTruncateExecuted);
  1394. bool ThereIsNoBypassHeaderDirective = (0 == (MyScanData.HeaderDirectiveFlags & HeaderDirectiveBypass));
  1395. bool ThereIsNoBypassResultCodeRule = (false == MyCFGPacket.Config()->TrainingBypassRuleHandler.isListed(S));
  1396. bool ThereIsNoImpliedBypassDirective = (Ignore != (MyScanData.SourceIPRecord().GBUdbData.Flag()));
  1397. // If these conditions are favorable then train the GBUdb.
  1398. if( // Check to see if training is enabled.
  1399. TrainingIsTurnedOn && // If it is turned on AND
  1400. MessageWasNotTruncated && // The message was not truncated AND
  1401. ThereIsNoBypassHeaderDirective && // There is NO Bypass header directive AND
  1402. ThereIsNoBypassResultCodeRule && // There is NO Bypass result code rule AND
  1403. ThereIsNoImpliedBypassDirective // There is NO Implied bypass directive:
  1404. ) {
  1405. // GBUdb training is enabled.
  1406. switch(ScanResultType) { // Evaluate the scan result.
  1407. case NoPattern: // On no pattern (benefit of doubt) or
  1408. case WhitePattern: { // a white pattern:
  1409. MyRulebase->MyGBUdb.addGood( // then add a good count to the
  1410. MyScanData.SourceIPRecord().IP); // source IP.
  1411. break;
  1412. }
  1413. case BlackPattern: { // On a black pattern:
  1414. MyRulebase->MyGBUdb.addBad( // add a bad count to the source IP
  1415. MyScanData.SourceIPRecord().IP); // in the GBUdb.
  1416. break;
  1417. }
  1418. default: break; // In all other cases, don't train.
  1419. }
  1420. }
  1421. // GBUdb Training Is Complete
  1422. // At this point our SourceIPRange tells us exactly how to evaluate
  1423. // the source IP for this message.
  1424. switch(MyScanData.SourceIPRange()) {
  1425. case White: { // If the IP was in the white zone
  1426. MyScanData.GBUdbWhiteTriggered = true; // mark that down.
  1427. if(MyCFGPacket.Config()->WhiteRangeHandler.On_Off) { // If we're also turned on then
  1428. if( // do we need to force the symbol?
  1429. BlackPattern == ScanResultType || // We do if the pattern scan resulted
  1430. IPPattern == ScanResultType // in a black or IPblack match.
  1431. ) { // If we must force a white result:
  1432. S = MyCFGPacket.Config()->WhiteRangeHandler.Symbol; // force the symbol and
  1433. MyScanData.GBUdbWhiteSymbolForced = true; // record that it was done.
  1434. }
  1435. // AutoPanic
  1436. int AutoPanicRangeLowerBound = // Calculate the current lower bound
  1437. MyRulebase->MyLOGmgr.LatestRuleID() - // for rule id's that are eligible to
  1438. MyCFGPacket.Config()->gbudb_regions_white_panic_rule_range; // trigger auto-panics.
  1439. if(BlackPattern == ScanResultType || IPPattern == ScanResultType) { // Was there a pattern/source conflict?
  1440. MyScanData.GBUdbPatternSourceConflict = true; // Record the event.
  1441. if(MyScanData.PatternID > AutoPanicRangeLowerBound) { // If the pattern ID is in range then
  1442. MyScanData.GBUdbAutoPanicTriggered = true; // record that the AutoPanic triggered.
  1443. if(MyCFGPacket.Config()->gbudb_regions_white_panic_on_off) { // If rule panics are turned on then
  1444. MyScanData.GBUdbAutoPanicExecuted = true; // indicate we are executing an autopanic.
  1445. MyRulebase->addRulePanic(MyScanData.PatternID); // Add the rule panic.
  1446. }
  1447. }
  1448. }
  1449. }
  1450. break;
  1451. }
  1452. case Normal: { // If the IP is normal...
  1453. MyScanData.GBUdbNormalTriggered = true; // Count the event.
  1454. break; // That's all.
  1455. }
  1456. case New: {
  1457. break;
  1458. }
  1459. case Caution: { // If the IP is in the caution range.
  1460. MyScanData.GBUdbCautionTriggered = true; // Track that this range fired.
  1461. if(
  1462. MyCFGPacket.Config()->CautionRangeHandler.On_Off && // If we're also turned on and there
  1463. NoPattern == ScanResultType // is no pattern match then
  1464. ) { // we will override the scan result:
  1465. S = MyCFGPacket.Config()->CautionRangeHandler.Symbol; // set the symbol as configured and
  1466. MyScanData.GBUdbCautionSymbolForced = true; // record that it was done.
  1467. }
  1468. break;
  1469. }
  1470. // Truncate is a kind of uber-black, so we do some weirdness here.
  1471. // If Truncate happens, then black was triggered by definition. In
  1472. // peek cases or if Truncate is turned off then Truncate might not
  1473. // execute-- when that happens we need to fall back to Black behavior.
  1474. case Truncate: // If the IP was in the truncate range
  1475. case Black: { // and/or If the IP is in the black range
  1476. MyScanData.GBUdbBlackTriggered = true; // mark that down.
  1477. if(MyScanData.GBUdbTruncateExecuted) { // If the truncate action was executed
  1478. S = MyCFGPacket.Config()->gbudb_regions_black_truncate_symbol; // we set the output symbol accordingly.
  1479. } else // Truncate overrides black.. but if
  1480. if( // Black is in charge do this...
  1481. MyCFGPacket.Config()->BlackRangeHandler.On_Off && // If black action is turned on and there
  1482. NoPattern == ScanResultType // is no pattern match then
  1483. ) { // we will override the scan data:
  1484. S = MyCFGPacket.Config()->BlackRangeHandler.Symbol; // set the symbol as configured and
  1485. MyScanData.GBUdbBlackSymbolForced = true; // record that it was done.
  1486. }
  1487. // Now that all of the overrides have been handled we can handle
  1488. // sampling. When a black IP is detected and a pattern match is not
  1489. // then we may sample the data.
  1490. int BlackSampleRate = // Grab the sample rate to make the
  1491. MyCFGPacket.Config()->gbudb_regions_black_sample_grab_one_in; // logic clearer.
  1492. bool SampleThresholdReached = // Check the spam probability of the
  1493. (MyCFGPacket.Config()->gbudb_regions_black_sample_probability <= // source IP against the configuration
  1494. MyScanData.SourceIPRecord().GBUdbData.Probability()); // to see if this IP is a candidate.
  1495. if( // Should we sample?
  1496. false == MyScanData.GBUdbTruncateExecuted && // If this was not a truncation and
  1497. NoPattern == ScanResultType && // No pattern match was found and
  1498. SampleThresholdReached && // We reached out sample threshold and
  1499. MyRulebase->MyLOGmgr.OkToSample(BlackSampleRate) // It's ok for us to sample this round
  1500. ) { // then our sampling mechanism is triggerd.
  1501. MyScanData.GBUdbSampleTriggered = true; // Mark down that event.
  1502. if(MyCFGPacket.Config()->gbudb_regions_black_sample_on_off) { // If sampling is turned on then
  1503. MyScanData.GBUdbSampleExecuted = true; // we will be sampling this data.
  1504. if(MyCFGPacket.Config()->gbudb_regions_black_sample_passthrough) { // If sampling by passthrough then
  1505. S = MyCFGPacket.Config()-> // Force the symbol value to passthrough
  1506. gbudb_regions_black_sample_passthrough_symbol; // (usually 0 - same as CLEAN).
  1507. } else { // If sampling internally then
  1508. MyRulebase->MyNETmgr.sendSample( // send this message as a sample.
  1509. (*(MyCFGPacket.Config())), // Pass our current config info,
  1510. MyScanData, // our scan data,
  1511. MessageBuffer, // and the message itself.
  1512. MessageLength
  1513. );
  1514. }
  1515. }
  1516. }
  1517. break;
  1518. }
  1519. case Unknown: // Unknown - most likely we couldn't
  1520. default: { // find a usable source.
  1521. break; // Do nothing.
  1522. }
  1523. }
  1524. } // End of IP source depended work (GBUdbOverrides)
  1525. // At this point we know the final result of our scan
  1526. // and the number of results we have. It's time to set up our result
  1527. // processing widgets for further query and return the result of this scan.
  1528. ResultCursor = CurrentMatrix -> ResultList; // Starting at the top of the list
  1529. ResultsRemaining = ResultsCount; // with all of the results ahead of us.
  1530. if(NO_SYMBOL==S) S = CLEAN_RESULT; // When there were no results, CLEAN
  1531. MyScanData.CompositeFinalResult = S; // Record what we will return.
  1532. if( // Prepare our final result.
  1533. CLEAN_RESULT == S && // If we have a clean result code
  1534. ScanResultType != WhitePattern && // and it wasn't forced by a white
  1535. false == MyScanData.GBUdbWhiteSymbolForced) { // rule or white GBUdb then we mark
  1536. TmpSNFMatch.flag = 'c'; // the final record Clean.
  1537. } else { // Otherwise we mark the final record
  1538. TmpSNFMatch.flag = 'f'; // as Final - meaning deliberately zero.
  1539. }
  1540. TmpSNFMatch.index = 0; // Our index is charater zero.
  1541. TmpSNFMatch.endex = CurrentMatrix->CountOfCharacters - 1; // Our endex is the end of the message.
  1542. TmpSNFMatch.symbol = MyScanData.CompositeFinalResult; // Our symbol is in CompositeFinal.
  1543. // The rule id is dependent on what's happened...
  1544. if( // If the symbol has been forced...
  1545. MyScanData.GBUdbTruncateExecuted || // Was it a Truncate-IP scan?
  1546. MyScanData.GBUdbWhiteSymbolForced || // Was it a White-IP scan?
  1547. MyScanData.GBUdbBlackSymbolForced || // Was it a Black-IP scan?
  1548. MyScanData.GBUdbCautionSymbolForced || // Was it a Caution-IP scan?
  1549. NULL == FinalResult // OR there was no valid match
  1550. ) { // then our rule id will be
  1551. TmpSNFMatch.ruleid = 0; // ZERO.
  1552. } else { // Normally the rule id will be
  1553. TmpSNFMatch.ruleid = FinalResult->RuleId(); // that of the winning pattern match.
  1554. }
  1555. MyScanData.MatchRecords.push_back(TmpSNFMatch); // Push our final entry onto the list.
  1556. MyScanData.MatchRecordsCursor = MyScanData.MatchRecords.begin(); // Reset the delivery system to the
  1557. MyScanData.MatchRecordsDelivered = 0; // beginning of the results list.
  1558. MyScanData.ScanDepth = CurrentMatrix->MaximumCountOfEvaluators; // Capture the scan depth.
  1559. MyScanData.ScanTime.stop(); // Stop the scan time clock.
  1560. MyRulebase->MyLOGmgr.logThisScan((*(MyCFGPacket.Config())), MyScanData); // Log the data from this scan.
  1561. // Since V2-9rc19 of this engine, the Engine mutex and snfCFGPacket handle
  1562. // their own cleanup when this call goes out of scope. ScannerIsBusy(MyMutex)
  1563. // will unlock() on destruction and snfCFGPacket will MyRulebase->drop().
  1564. return S; // Return the final scan result.
  1565. }
  1566. int snf_EngineHandler::getResults(snf_match* MatchBuffer){ // Get the next match buffer.
  1567. ScopeMutex SerializeThis(MyMutex); // Serialize this...
  1568. if(NULL == MatchBuffer) { // If we were given the reset signal
  1569. MyScanData.MatchRecordsCursor = MyScanData.MatchRecords.begin(); // Move the cursor to the beginning
  1570. MyScanData.MatchRecordsDelivered = 0; // and reset the delivered count.
  1571. } else { // If we are in delivery mode and
  1572. if(MyScanData.MatchRecords.end() != MyScanData.MatchRecordsCursor) { // there are more to deliver then
  1573. (*MatchBuffer) = (*MyScanData.MatchRecordsCursor); // deliver the current match and
  1574. ++MyScanData.MatchRecordsCursor; // move on to the next. Be sure to
  1575. ++MyScanData.MatchRecordsDelivered; // count this one as delivered.
  1576. }
  1577. }
  1578. return MyScanData.MatchRecords.size() - MyScanData.MatchRecordsDelivered; // Return a count of unseen records.
  1579. }
  1580. int snf_EngineHandler::getDepth(){ // Get the scan depth.
  1581. ScopeMutex SerializeThis(MyMutex); // Protect our reading.
  1582. return MyScanData.ScanDepth; // Return the latest scan depth.
  1583. }
  1584. const string snf_EngineHandler::getClassicLog() { // Get classic log entries for last scan.
  1585. ScopeMutex SerializeThis(MyMutex); // Serialize this...
  1586. return MyScanData.ClassicLogText; // Return the log text.
  1587. }
  1588. const string snf_EngineHandler::getXMLLog() { // Get XML log entries or last scan.
  1589. ScopeMutex SerializeThis(MyMutex); // Serialize this...
  1590. return MyScanData.XMLLogText; // Return the log text.
  1591. }
  1592. const string snf_EngineHandler::getXHDRs() { // Get XHDRs for last scan.
  1593. ScopeMutex SerializeThis(MyMutex); // Serialize this...
  1594. return MyScanData.XHDRsText; // Return the XHeaders text.
  1595. }
  1596. //// Multi Engine Handler Methods
  1597. // snf_RoundRulebaseCursor()
  1598. // Returns the next rulebase slot id wrapping around to zero.
  1599. int snf_MultiEngineHandler::RoundRulebaseCursor(){ // Return the next Rulebase handle
  1600. RulebaseCursor++; // Increase the cursor.
  1601. if(snf_MAX_RULEBASES<=RulebaseCursor) // If we've reached the end of the array
  1602. RulebaseCursor=0; // then we start back at zero.
  1603. return RulebaseCursor; // Return the new handle candidate.
  1604. }
  1605. // snf_RoundEngineCursor()
  1606. // Returns the next engine slot id wrapping around to zero.
  1607. int snf_MultiEngineHandler::RoundEngineCursor(){ // Return the next Engine handle candidate.
  1608. EngineCursor++; // Increase the cursor.
  1609. if(snf_MAX_SCANNERS<=EngineCursor) // If we've reached the end of the array
  1610. EngineCursor=0; // then we start back at zero.
  1611. return EngineCursor; // Return the new handle candidate.
  1612. }
  1613. snf_MultiEngineHandler::~snf_MultiEngineHandler(){ // Clean up, safety check, shut down.
  1614. RulebaseScan.lock(); // Lock both the rulebase and
  1615. EngineScan.lock(); // engine scan rulebases.
  1616. RulebaseCursor = EngineCursor = SHUTDOWN; // Set the cursors to the FINISHED value.
  1617. // The handlers in the arrays will all get closed by their destructors.
  1618. // The SHUTDOWN value in the cursors will force any errant threads to get no love.
  1619. RulebaseScan.unlock();
  1620. EngineScan.unlock();
  1621. }
  1622. // snf_OpenRulebase()
  1623. // Grab the first available rulebse handler and light it up.
  1624. int snf_MultiEngineHandler::OpenRulebase(const char* path, const char* licenseid, const char* authentication){
  1625. RulebaseScan.lock(); // Serialize this.
  1626. if(SHUTDOWN==RulebaseCursor) { // Not ok to open after shutdown.
  1627. RulebaseScan.unlock();
  1628. throw Panic("snf_MultiEngineHandler::OpenRulebase() No open after shutdown");
  1629. }
  1630. int Handle = RoundRulebaseCursor(); // Grab the next hanlder on the list.
  1631. if(RulebaseHandlers[Handle].isReady()) { // Check to see if it's already in use. If so,
  1632. int wherewasi = Handle; // keep track of where we started.
  1633. while(RulebaseHandlers[(Handle=RoundRulebaseCursor())].isReady()){ // Loop to find an free handler.
  1634. if(wherewasi==Handle) { // If we get back where we started
  1635. RulebaseScan.unlock(); // Unlock the Rulebase Scanning process
  1636. throw TooMany("snf_MultiEngineHandler::OpenRulebase() Too Many Open"); // and tell the caller Too Many are open.
  1637. }
  1638. }
  1639. }
  1640. // Now we have a Handle to a free RulebaseHandler. Time to open it up.
  1641. try {
  1642. RulebaseHandlers[Handle].open(path,licenseid,authentication); // Try to open the handler.
  1643. } // If an exception is thrown...
  1644. catch(snf_RulebaseHandler::AuthenticationError& e) // Catch and re-throw the appropriate
  1645. { RulebaseScan.unlock(); throw AuthenticationError(e.what()); } // exception.
  1646. catch(snf_RulebaseHandler::AllocationError& e)
  1647. { RulebaseScan.unlock(); throw AllocationError(e.what()); }
  1648. catch(snf_RulebaseHandler::FileError& e)
  1649. { RulebaseScan.unlock(); throw FileError(e.what()); }
  1650. catch(snf_RulebaseHandler::Busy& e)
  1651. { RulebaseScan.unlock(); throw Panic(e.what()); } // Wasn't busy above!! Shoudn't be here!!!
  1652. catch(exception& e)
  1653. { RulebaseScan.unlock(); throw; }
  1654. catch(...) {
  1655. RulebaseScan.unlock();
  1656. throw Panic("snf_MultiEngineHandler::OpenRulebase() ???");
  1657. }
  1658. RulebaseScan.unlock(); // If everything went well then UnLock
  1659. return Handle; // and return the happy new handle.
  1660. }
  1661. // snf_RefreshRulebase()
  1662. // Reload the rulebase associated with the handler.
  1663. void snf_MultiEngineHandler::RefreshRulebase(int RulebaseHandle){ // Refreshing a rulebase (Not Serialized)
  1664. try {
  1665. RulebaseHandlers[RulebaseHandle].refresh(); // Try to refresh the rulebase.
  1666. } // Catch and rethrow any exceptions.
  1667. catch(snf_RulebaseHandler::AuthenticationError& e) {
  1668. throw AuthenticationError(e.what());
  1669. }
  1670. catch(snf_RulebaseHandler::AllocationError& e) {
  1671. throw AllocationError(e.what());
  1672. }
  1673. catch(snf_RulebaseHandler::FileError& e) {
  1674. throw FileError(e.what());
  1675. }
  1676. catch(snf_RulebaseHandler::Busy& e) {
  1677. throw Busy(e.what());
  1678. }
  1679. catch(exception& e) {
  1680. throw;
  1681. }
  1682. catch(...) {
  1683. throw Panic("snf_MultiEngineHandler::RefreshRulebase() ???");
  1684. }
  1685. }
  1686. // snf_CloseRulebase()
  1687. // Shut down this Rulebase handler.
  1688. void snf_MultiEngineHandler::CloseRulebase(int RulebaseHandle){ // Closing a rulebase handler
  1689. RulebaseScan.lock(); // Serialize this - the handler changes state.
  1690. try { // Try to close the handler.
  1691. RulebaseHandlers[RulebaseHandle].close();
  1692. }
  1693. catch(snf_RulebaseHandler::Busy& e) { // A busy throw we can understand.
  1694. RulebaseScan.unlock(); throw Busy(e.what());
  1695. }
  1696. catch(exception& e) { // Other exceptions? rethrow.
  1697. RulebaseScan.unlock(); throw;
  1698. }
  1699. catch(...) { // Any other throw is big trouble.
  1700. RulebaseScan.unlock();
  1701. throw Panic("snf_MultiEngineHandler::CloseRulebase() ???");
  1702. }
  1703. RulebaseScan.unlock(); // When done, unlock the Rulebase Scan process.
  1704. }
  1705. // snf_OpenEngine()
  1706. // Grab the first available Engine handler and light it up
  1707. int snf_MultiEngineHandler::OpenEngine(int RulebaseHandle){
  1708. EngineScan.lock(); // Serialize this.
  1709. if(SHUTDOWN==EngineCursor) { // Not ok to open after shutdown.
  1710. EngineScan.unlock();
  1711. throw Panic("snf_MultiEngineHandler::OpenEngine() No open after shutdwon");
  1712. }
  1713. int Handle = RoundEngineCursor(); // Grab the next hanlder on the list.
  1714. if(EngineHandlers[Handle].isReady()) { // Check to see if it's already in use. If so,
  1715. int wherewasi = Handle; // keep track of where we started.
  1716. while(EngineHandlers[(Handle=RoundEngineCursor())].isReady()){ // Loop to find an free handler.
  1717. if(wherewasi==Handle) { // If we get back where we started
  1718. EngineScan.unlock(); // Unlock the Rulebase Scanning process
  1719. throw TooMany("snf_MultiEngineHandler::OpenEngine() too many open"); // and tell the caller Too Many are open.
  1720. }
  1721. }
  1722. }
  1723. // Now we have a Handle to a free RulebaseHandler. Time to open it up.
  1724. try {
  1725. EngineHandlers[Handle].open(&RulebaseHandlers[RulebaseHandle]); // Try to open the handler.
  1726. } // If an exception is thrown...
  1727. catch(snf_EngineHandler::AllocationError& e) // Catch and rethrow as appropriate.
  1728. { EngineScan.unlock(); throw AllocationError(e.what()); }
  1729. catch(snf_EngineHandler::Busy& e)
  1730. { EngineScan.unlock(); throw Panic(e.what()); } // Not busy above should not be busy now!!!
  1731. catch(exception& e) {
  1732. EngineScan.unlock();
  1733. throw;
  1734. }
  1735. catch(...) {
  1736. EngineScan.unlock();
  1737. throw Panic("snf_MultiEngineHandler::OpenEngine() ???");
  1738. }
  1739. EngineScan.unlock(); // If everything went well then UnLock
  1740. return Handle; // and return the happy new handle.
  1741. }
  1742. // snf_CloseEngine()
  1743. // Shut down this Engine handler.
  1744. void snf_MultiEngineHandler::CloseEngine(int EngineHandle){ // Closing an engine handler.
  1745. EngineScan.lock(); // Serialize this, the object changes states.
  1746. try {
  1747. EngineHandlers[EngineHandle].close(); // Try closing the handler.
  1748. }
  1749. catch(snf_EngineHandler::AllocationError& e) // Catch and throw any exceptions as needed.
  1750. { EngineScan.unlock(); throw AllocationError(e.what()); }
  1751. catch(snf_EngineHandler::Busy& e)
  1752. { EngineScan.unlock(); throw Busy(e.what()); }
  1753. catch(exception& e) {
  1754. EngineScan.unlock();
  1755. throw;
  1756. }
  1757. catch(...) {
  1758. EngineScan.unlock();
  1759. throw Panic("snf_MultiEngineHandler::CloseEngine() ???");
  1760. }
  1761. EngineScan.unlock(); // Unlock when we're closed.
  1762. }
  1763. // snf_Scan()
  1764. // Scan the MessageBuffer with this Engine.
  1765. int snf_MultiEngineHandler::Scan(int EngineHandle, const unsigned char* MessageBuffer, int MessageLength){
  1766. // NOT serialized. Many scans at once, presumably one scan engine per thread.
  1767. int ScanResult; // ScanResult stays in scope.
  1768. try {
  1769. ScanResult=EngineHandlers[EngineHandle]
  1770. .scanMessage(MessageBuffer,MessageLength); // Try the scan on the given engine.
  1771. }
  1772. catch(snf_EngineHandler::AllocationError& e) { // Re-throw any exceptions as needed.
  1773. throw AllocationError(e.what());
  1774. }
  1775. catch(snf_EngineHandler::Busy& e) { throw Busy(e.what()); }
  1776. catch(exception& e) { throw; }
  1777. catch(...) { throw Panic("snf_MultiEngineHandler::Scan() ???"); }
  1778. return ScanResult; // Return the results.
  1779. }
  1780. // The Engine prvides detailed match results through this function.
  1781. int snf_MultiEngineHandler::getResults(int EngineHandle, snf_match* matchbfr){
  1782. // NOT serialized. Many scans at once, presumably one scan engine per thread.
  1783. int ResultCount; // ResultCount stays in scope.
  1784. try {
  1785. ResultCount=EngineHandlers[EngineHandle].getResults(matchbfr); // Try the scan on the given engine.
  1786. }
  1787. catch(snf_EngineHandler::AllocationError& e) { // Re-throw any exceptions as needed.
  1788. throw AllocationError(e.what());
  1789. }
  1790. catch(snf_EngineHandler::Busy& e) { throw Busy(e.what()); }
  1791. catch(exception& e) { throw; }
  1792. catch(...) { throw Panic("snf_MultiEngineHandler::getResults() ???"); }
  1793. return ResultCount; // Return the results.
  1794. }
  1795. // The Engine provies the scan depth through this function.
  1796. int snf_MultiEngineHandler::getDepth(int EngineHandle){
  1797. // NOT serialized. Many scans at once, presumably one scan engine per thread.
  1798. int DepthResult; // ScanResult stays in scope.
  1799. try {
  1800. DepthResult=EngineHandlers[EngineHandle].getDepth(); // Try the scan on the given engine.
  1801. }
  1802. catch(snf_EngineHandler::AllocationError& e) { // Re-throw any exceptions as needed.
  1803. throw AllocationError(e.what());
  1804. }
  1805. catch(snf_EngineHandler::Busy& e) { throw Busy(e.what()); }
  1806. catch(exception& e) { throw; }
  1807. catch(...) { throw Panic("snf_MultiEngineHandler::getDepth() ???"); }
  1808. return DepthResult; // Return the results.
  1809. }