You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

SNFMulti.cpp 140KB

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