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

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