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

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