Nevar pievienot vairāk kā 25 tēmas Tēmai ir jāsākas ar burtu vai ciparu, tā var saturēt domu zīmes ('-') un var būt līdz 35 simboliem gara.

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