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

snfNETmgr.cpp 48KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786
  1. // snfNETmgr.cpp
  2. //
  3. // (C) Copyright 2006 - 2009 ARM Research Labs, LLC
  4. // See www.armresearch.com for the copyright terms.
  5. //
  6. // See snfNETmgr.hpp for details.
  7. #include <sys/types.h>
  8. #include <sys/stat.h>
  9. #include <ctime>
  10. #include <cstring>
  11. #include <string>
  12. #include <vector>
  13. #include <fstream>
  14. #include <sstream>
  15. #include "SNFMulti/snfNETmgr.hpp"
  16. #include "SNFMulti/snf_sync.hpp"
  17. #include "CodeDweller/mangler.hpp"
  18. #include "CodeDweller/base64codec.hpp"
  19. // #include "tcp_watchdog.hpp" No longer using TCPWatchdog -- see below _M
  20. using namespace std;
  21. using namespace CodeDweller;
  22. namespace SNFMulti {
  23. ///// utilities ////////////////////////////////////////////////////////////////
  24. const int MSecsInSecs = 1000; // Multiplier - seconds to milliseconds.
  25. unsigned long long int SecsAsMSecs(unsigned int Secs) {
  26. return (MSecsInSecs * Secs);
  27. }
  28. //// snfNETmgr /////////////////////////////////////////////////////////////////
  29. const ThreadType snfNETmgr::Type("snfNETManager"); // The thread's type.
  30. const ThreadState snfNETmgr::Sleeping("Sleeping"); // Taking a break.
  31. const ThreadState snfNETmgr::SYNC_Connect("Connecting"); // Connecting to SYNC server.
  32. const ThreadState snfNETmgr::SYNC_Read_Challenge("Reading challenge"); // Reading challenge.
  33. const ThreadState snfNETmgr::SYNC_Compute_Response("Computing crypto"); // Computing crypto response.
  34. const ThreadState snfNETmgr::SYNC_Send_Response("Sending crypto"); // Sending crypto response.
  35. const ThreadState snfNETmgr::SYNC_Read_Availabilty("Reading Availability"); // Reading rulebase status.
  36. const ThreadState snfNETmgr::SYNC_Send_GBUdb_Alerts("Sending GBUdb"); // Sending GBUdb alerts.
  37. const ThreadState snfNETmgr::SYNC_Send_Status_Reports("Sending Status"); // Sending status reports.
  38. const ThreadState snfNETmgr::SYNC_Send_Samples("Sending Samples"); // Sending message samples.
  39. const ThreadState snfNETmgr::SYNC_Send_End_Of_Report("Sending End"); // Sending end of client data.
  40. const ThreadState snfNETmgr::SYNC_Read_Server_Response("Reading Server"); // Reading server data.
  41. const ThreadState snfNETmgr::SYNC_Close_Connection("Closing Connection"); // Closing connection.
  42. const ThreadState snfNETmgr::SYNC_Parse_GBUdb_Reflections("Parsing GBUdb"); // Parsing GBUdb reflections.
  43. const ThreadState snfNETmgr::SYNC_Log_Event("Logging SYNC"); // Logging SYNC event.
  44. snfNETmgr::snfNETmgr() : // Starting up the NETmgr
  45. Thread(snfNETmgr::Type, "NET Manager"), // Network manager and Name.
  46. myLOGmgr(NULL), // No LOGmgr yet.
  47. isTimeToStop(false), // Not time to stop yet.
  48. isConfigured(false), // Not configured yet.
  49. SYNCTimer(30000), // Sync every 30 secs by default.
  50. SyncSecsOverride(-1) { // Override is -1 (off) by default.
  51. run(); // Run the thread.
  52. }
  53. snfNETmgr::~snfNETmgr() { // On descruction, NETmgr must
  54. stop(); // Stop it's thread (if not already)
  55. myLOGmgr = NULL; // Clear out the LOGmgr hookup
  56. isConfigured = false; // and the configured flag.
  57. }
  58. void snfNETmgr::stop() { // The stop method...
  59. if(!isTimeToStop) { // only does it's work once:
  60. isTimeToStop = true; // tells it's thread to stop
  61. join(); // and waits for it to shut down.
  62. }
  63. }
  64. void snfNETmgr::myTask() { // Here's the thread task.
  65. Sleeper WaitASecond(1000); // Heartbeat timer.
  66. while(false == isTimeToStop) { // Until it's time to stop,
  67. CurrentThreadState(Sleeping); // post our status,
  68. WaitASecond(); // pause for a second,
  69. if(isConfigured) { // then poll our tasks.
  70. // Do stuff here that requires configuration data.
  71. if(SYNCTimer.isExpired()) { sync(); SYNCTimer.restart(); } // If it's time to sync - do it :-)
  72. }
  73. }
  74. }
  75. void snfNETmgr::linkLOGmgr(snfLOGmgr& L) { // Set the LOGmgr.
  76. myLOGmgr = &L;
  77. }
  78. void snfNETmgr::linkGBUdbmgr(snfGBUdbmgr& G) { // Set the GBUdbmgr.
  79. myGBUdbmgr = &G;
  80. }
  81. // In theory, configure will get called each time the rulebase manager loads
  82. // a new configuration / rulebase. The configure() method updates the bits of
  83. // NETmgr that run background tasks. Live-Data tasks pass their grab()bed
  84. // CFGData object in order to maintain self-consistency.
  85. void snfNETmgr::configure(snfCFGData& CFGData) { // Update the configuration.
  86. ScopeMutex CFGDataExchange(ConfigMutex); // Lock the config data during updates.
  87. // Update the internal config data from CFGData while we are locked.
  88. // Internal functions which depend on this data will lock the object,
  89. // grab the bits they depend upon for that pass, and then unlock.
  90. RulebaseFilePath = CFGData.RuleFilePath; // Where we can find our rulebase?
  91. SyncHostName = CFGData.network_sync_host; // Where do we connect to sync?
  92. SyncHostPort = CFGData.network_sync_port; // What port do we use to sync?
  93. HandshakeFilePath = CFGData.paths_workspace_path + ".handshake"; // Where we store our handshake.
  94. UpdateReadyFilePath = CFGData.paths_workspace_path + "UpdateReady.txt"; // Where we put update trigger files.
  95. SyncSecsConfigured = CFGData.network_sync_secs; // Capture the configured sync time.
  96. if(0 > SyncSecsOverride) { // If the sync timer isn't in override,
  97. if(SYNCTimer.getDuration() != SecsAsMSecs(SyncSecsConfigured)) { // And the config time is different than
  98. SYNCTimer.setDuration(SecsAsMSecs(SyncSecsConfigured)); // the timer's current setting then set
  99. } // the timer to the new value.
  100. } // If we are in override, timer is set.
  101. License = CFGData.node_licenseid; // Capture our node id (license id).
  102. SecurityKey = CFGData.SecurityKey; // Capture our security key.
  103. evolvePad(CFGData.SecurityKey); // Seed our Pad generator with it.
  104. // Safety check before turning this on ;-)
  105. if(
  106. NULL != myLOGmgr &&
  107. NULL != myGBUdbmgr
  108. ) { // If we are properly linked then
  109. isConfigured = true; // at this point we are configured!
  110. }
  111. }
  112. void snfNETmgr::sendSample( // Send a sampled message...
  113. snfCFGData& CFGData, // Use this configuration,
  114. snfScanData& ScanData, // Include this scan data,
  115. const unsigned char* MessageBuffer, // This is the message itself
  116. int MessageLength // and it is this size.
  117. ) {
  118. string TimeStamp; (*myLOGmgr).Timestamp(TimeStamp); // Grab a timestamp.
  119. ostringstream XML; // Make formatting easier with this.
  120. //-- <sample...>
  121. XML << "<sample node=\'" << CFGData.node_licenseid << "\' "
  122. << "time=\'" << TimeStamp << "\' "
  123. << "result=\'" << ScanData.CompositeFinalResult << "\'>" << endl;
  124. //-- <ip...>
  125. XML << "<ip range=\'";
  126. string IPRange;
  127. switch(ScanData.SourceIPRange()) {
  128. case Unknown: { IPRange = "Unknown"; break; } // Unknown - not defined.
  129. case White: { IPRange = "White"; break; } // This is a good guy.
  130. case Normal: { IPRange = "Normal"; break; } // Benefit of the doubt.
  131. case New: { IPRange = "New"; break; } // It is new to us.
  132. case Caution: { IPRange = "Caution"; break; } // This is suspicious.
  133. case Black: { IPRange = "Black"; break; } // This is bad.
  134. case Truncate: { IPRange = "Truncate"; break; } // Don't even bother looking.
  135. }
  136. SocketAddress IP;
  137. IP.setAddress(ScanData.SourceIPRecord().IP);
  138. XML << IPRange << "\' ip=\'" << (string) IP4Address(IP.getAddress()) << "\' t=\'";
  139. string IPType;
  140. switch(ScanData.SourceIPRecord().GBUdbData.Flag()) {
  141. case Good: { IPType = "Good"; break; }
  142. case Bad: { IPType = "Bad"; break; }
  143. case Ugly: { IPType = "Ugly"; break; }
  144. case Ignore: { IPType = "Ignore"; break; }
  145. }
  146. XML << IPType << "\' b=\'" << ScanData.SourceIPRecord().GBUdbData.Bad()
  147. << "\' g=\'" << ScanData.SourceIPRecord().GBUdbData.Good()
  148. << "\'/>" << endl;
  149. //-- <match...> as many as needed
  150. if(0 < ScanData.MatchRecords.size()) { // If we have match records - emit them.
  151. list<snf_match>::iterator iM; // Grab an iterator.
  152. for( // Emit each snf_match entry.
  153. iM = ScanData.MatchRecords.begin();
  154. iM != ScanData.MatchRecords.end();
  155. iM++) {
  156. XML << "<match r=\'" << (*iM).ruleid << "\' "
  157. << "g=\'" << (*iM).symbol << "\' "
  158. << "i=\'" << (*iM).index << "\' "
  159. << "e=\'" << (*iM).endex << "\' "
  160. << "f=\'" << (*iM).flag << "\'/>";
  161. }
  162. }
  163. //-- <msg...>
  164. XML << "<msg size=\'" << ScanData.ScanSize << "'>" << endl; // Starting with the msg element.
  165. to_base64 EncodedMessageData(
  166. reinterpret_cast<const char*>(MessageBuffer), MessageLength); // Encode the message to base64.
  167. const int SampleLineLength = 64; // 64 bytes per line is good.
  168. for(int i = 0; i < MessageLength;) { // Now we break it into lines
  169. for(int l = 0; l < SampleLineLength && i < MessageLength; l++, i++) { // that are a reasonable length.
  170. XML << EncodedMessageData.at(i); // Emit one character at a time...
  171. } // At the end of a reasonable
  172. XML << endl; // length we terminate the line.
  173. }
  174. XML << "</msg>" << endl; // End of the <msg> element.
  175. //-- done with the sample!
  176. XML << "</sample>" << endl;
  177. // Last thing we do is post the formatted string to the buffer.
  178. const unsigned int SampleSafetyLimit = 100000; // 100 Kbyte limit on samples.
  179. ScopeMutex DoNotDisturb(myMutex); // Don't bug me man I'm busy.
  180. if(SampleSafetyLimit < SamplesBuffer.length()) // If the samples buffer is full
  181. SamplesBuffer.clear(); // clear it before adding more.
  182. SamplesBuffer.append(XML.str()); // Append the XML to the buffer.
  183. }
  184. string snfNETmgr::getSamples() { // Synchronized way to get Samples.
  185. ScopeMutex DoNotDisturb(myMutex); // Lock the mutex to protect our work.
  186. string SamplesBatch = SamplesBuffer; // Copy the samples to a new string.
  187. SamplesBuffer.clear(); // Clear the samples buffer.
  188. return SamplesBatch; // Return a batch of Samples.
  189. }
  190. void snfNETmgr::sendReport(const string& S) { // How to send a status report.
  191. const unsigned int ReportSafetyLimit = 100000; // 100 Kbytes limit on reports.
  192. ScopeMutex DoNotDisturb(myMutex); // Lock the mutex for a moment.
  193. if(ReportSafetyLimit < ReportsBuffer.length()) // If the reports buffer is full
  194. ReportsBuffer.clear(); // clear it before adding more.
  195. ReportsBuffer.append(S); // Append the report.
  196. }
  197. string snfNETmgr::getReports() { // Synchronized way to get Reports.
  198. ScopeMutex DoNotDisturb(myMutex); // Lock the mutex to protect our work.
  199. string ReportsBatch = ReportsBuffer; // Copy the reports to a new string.
  200. ReportsBuffer.clear(); // Clear the reports buffer.
  201. return ReportsBatch; // Return a batch of Reports.
  202. }
  203. string& snfNETmgr::RulebaseUTC(string& t) { // Gets local rulebase file UTC.
  204. struct stat RulebaseStat; // First we need a stat buffer.
  205. if(0 != stat(RulebaseFilePath.c_str(), &RulebaseStat)) { // If we can't get the stat we
  206. t.append("000000000000"); return t; // will return 000000000000 to
  207. } // make sure we should get the file.
  208. struct tm RulebaseTime; // Allocate a time structure.
  209. RulebaseTime = *(gmtime(&RulebaseStat.st_mtime)); // Copy the file time to it as UTC.
  210. char TimestampBfr[20]; // Timestamp buffer.
  211. (void) snprintf( // Format yyyymmddhhmmss
  212. TimestampBfr, sizeof(TimestampBfr),
  213. "%04d%02d%02d%02d%02d%02d",
  214. RulebaseTime.tm_year+1900,
  215. RulebaseTime.tm_mon+1,
  216. RulebaseTime.tm_mday,
  217. RulebaseTime.tm_hour,
  218. RulebaseTime.tm_min,
  219. RulebaseTime.tm_sec
  220. );
  221. t.append(TimestampBfr); // Append the timestamp to t
  222. return t; // and return it to the caller.
  223. }
  224. unsigned long snfNETmgr::ResolveHostIPFromName(const string& N) { // Host name resolution tool.
  225. ScopeMutex OneAtATimePlease(ResolverMutex); // Resolve only one at a time.
  226. unsigned long IP = inet_addr(N.c_str()); // See if it's an IP.
  227. if (INADDR_NONE == IP) { // If it's not an IP resolve it.
  228. hostent* H = gethostbyname(N.c_str()); // Resolve the host.
  229. if (NULL == H) { // If we didn't get a resolution
  230. return INADDR_NONE; // return no address.
  231. } // If we did resolve the address
  232. IP = *((unsigned long*)H->h_addr_list[0]); // get the primary entry.
  233. }
  234. return ntohl(IP); // Return what we got (host order)
  235. }
  236. // The Evolving One Time Pad engine is just slightly better than calling
  237. // rand() with the system time as a seed. However, it does have the advantage
  238. // that in order to guess it's initial state an attacker would need to already
  239. // know the license id and authentication. It also has the advantage that it
  240. // adds small amounts of entropy over time and never really forgets them. For
  241. // example, the exact time between calls to evolvePad is dependent on how long
  242. // it takes to sync which is dependent on how much data there is to report
  243. // which is dependent on the number and size of messages scanned etc... and
  244. // this is also impacted a bit by network performance issues during the sync.
  245. // Sensitivity to this entropy has millisecond resolution. This is a cross-
  246. // platform solution that depends only on our own code ;-)
  247. void snfNETmgr::evolvePad(string Entropy) { // Add entropy and evolve.
  248. ScopeMutex OneAtATimePlease(PadMutex); // Protect the one time pad.
  249. myLOGmgr->Timestamp(Entropy); // Time matters ;-)
  250. for(unsigned int a = 0; a < Entropy.length(); a++) { // Add the entropy to our generator.
  251. PadGenerator.Encrypt(Entropy.at(a));
  252. }
  253. msclock rt = myLOGmgr->RunningTime(); // Get the elapsed running time so far.
  254. unsigned char* rtb = reinterpret_cast<unsigned char*>(&rt); // Convert that long long into bytes.
  255. for(unsigned int a = 0; a < sizeof(msclock); a++) { // Encrypt those bytes one by one
  256. PadGenerator.Encrypt(rtb[a]); // to add more entropy.
  257. }
  258. }
  259. // To get a pad of any length you like, use the OneTimePad()
  260. // Note that we don't assign a value to x before using it! If we get lucky,
  261. // we will get some random value from ram as additional entropy ;-) If we end
  262. // up starting with zero, that's ok too.
  263. PadBuffer snfNETmgr::OneTimePad(int Len) { // Get Len bytes of one time pad.
  264. PadBuffer B; // Start with a buffer.
  265. B.reserve(Len); // Reserve Len bytes.
  266. unsigned char x = PadGenerator.Encrypt(0); // Get an unexposed byte to start with.
  267. for(int a = 0; a < Len; a++) { // Create Len bytes of pad by evolving
  268. B.push_back(x = PadGenerator.Encrypt(x)); // x through itself and copying the
  269. } // data into the buffer.
  270. return B; // Return the result.
  271. }
  272. // Handshake tries to return the current stored handshake. If it can't then it
  273. // returns a new handshake based on data from the pad generator.
  274. PadBuffer snfNETmgr::Handshake() { // What is the current handshake?
  275. if(CurrentHandshake.size() != SNFHandshakeSize) { // If we don't have one make one!
  276. CurrentHandshake = OneTimePad(SNFHandshakeSize); // Set up a default handshake to use
  277. try { // if we can't remember the real one.
  278. ifstream HSF(HandshakeFilePath.c_str(), ios::binary); // Open the handshake file.
  279. char* bfr = reinterpret_cast<char*>(&CurrentHandshake[0]); // Manufacture a proper pointer.
  280. HSF.read(bfr, SNFHandshakeSize); // Read the data (overwrite the HSB).
  281. HSF.close(); // Close the file.
  282. } catch(...) { } // Ignore any errors.
  283. }
  284. return CurrentHandshake; // Return the buffer.
  285. }
  286. PadBuffer& snfNETmgr::Handshake(PadBuffer& NewHandshake) { // Store a new handshake.
  287. CurrentHandshake = NewHandshake; // Grab the new handshake
  288. try { // then try to store it...
  289. ofstream HSF(HandshakeFilePath.c_str(), ios::binary | ios::trunc); // Open the handshake file.
  290. char* bfr = reinterpret_cast<char*>(&NewHandshake[0]); // Access the raw buffer.
  291. HSF.write(bfr, NewHandshake.size()); // Replace the old handshake
  292. HSF.close(); // close the file.
  293. } catch(...) {} // Ignore errors.
  294. return NewHandshake; // Return what we were given.
  295. }
  296. void snfNETmgr::postUpdateTrigger(string& updateUTC) { // Post an update trigger file.
  297. try { // Safely post an update trigger.
  298. ofstream HSF(UpdateReadyFilePath.c_str(), ios::binary | ios::trunc); // Open/create the trigger file.
  299. char* bfr = reinterpret_cast<char*>(&updateUTC[0]); // Access the raw UTC buffer.
  300. HSF.write(bfr, updateUTC.size()); // Write the update timestamp.
  301. HSF.close(); // close the file.
  302. } catch(...) {} // Ignore errors.
  303. }
  304. // Utility to read a line from a non-blocking TCPHost & check the timeout.
  305. const unsigned int MaxReadLineLength = 1024; // How long a line can be.
  306. string readLineTimeout(TCPHost& S, Timeout& T) { // Read a line from S until T.
  307. Sleeper WaitForMoreData(50); // How long to wait when no data.
  308. string LineBuffer = ""; // Buffer for the line.
  309. while( // Keep going as long as:
  310. false == T.isExpired() && // our timeout has not expired AND
  311. MaxReadLineLength > LineBuffer.length() // we haven't reached our limit.
  312. ) {
  313. char c = 0; // One byte at a time
  314. if(1 == S.receive(&c, sizeof(c))) { // Read from the TCPHost.
  315. LineBuffer.push_back(c); // Push the byte onto the string.
  316. if('\n' == c) break; // If it was a newline we're done!
  317. } else { // If we didn't get any data
  318. WaitForMoreData(); // pause before our next run.
  319. }
  320. }
  321. return LineBuffer; // Always return our buffer.
  322. }
  323. // Utility to write data to a non-blocking TCPHost & check the timeout.
  324. // Some networks can only handle small packets and fragmentation can be a
  325. // problem. Also, on Win* especially, sending small chunks is _MUCH_ more
  326. // reliable than trying to send large buffers all at once. SO - here we break
  327. // down our sending operations into medium sized chunks of data. The underlying
  328. // os can reorganize these chunks as needed for the outgouing stream. If the OS
  329. // needs us to slow down (doesn't send full chunks) then we introduce a small
  330. // delay between chunks to give the channel more time.
  331. const int MaxSendChunkSize = 512; // Size of one chunk in a write.
  332. void sendDataTimeout(TCPHost& S, Timeout& T, char* Bfr, int Len) { // Send and keep track of time.
  333. Sleeper WaitForMoreRoom(15); // Wait to send more data.
  334. int Remaining = Len; // This is how much we have left.
  335. while( // For as long as:
  336. false == T.isExpired() && // We still have time left AND
  337. 0 < Remaining // We still have data left
  338. ) {
  339. int ThisChunkSize = Remaining; // Hope to send it all in one chunk
  340. if(MaxSendChunkSize < ThisChunkSize) ThisChunkSize = MaxSendChunkSize; // but break it down as needed.
  341. int SentThisTime = S.transmit(Bfr, ThisChunkSize); // Send the data. How much went?
  342. Remaining -= SentThisTime; // Calculate how much is left.
  343. Bfr += SentThisTime; // Move our pointer (old school!)
  344. if(ThisChunkSize > SentThisTime) WaitForMoreRoom(); // If some of this chunk didn't go
  345. } // the pause before the next chunk.
  346. }
  347. void sendDataTimeout(TCPHost& S, Timeout& T, string& D) { // Send a string and keep track
  348. sendDataTimeout(S, T, const_cast<char*>(D.c_str()), D.length()); // of time. (Polymorphism is fun)
  349. }
  350. void snfNETmgr::sync() { // Synchronize with central command.
  351. // Keep these things in scope. This is how we roll.
  352. string HostName;
  353. int HostPort;
  354. string Secret;
  355. string Node;
  356. // Grab our configuration data (marchng orders).
  357. if(!isConfigured) return; // If we're not configured, don't!
  358. else {
  359. ScopeMutex GettingConfig(ConfigMutex); // Temporarily lock our config.
  360. HostName = SyncHostName; // We will connect to this host.
  361. HostPort = SyncHostPort; // We will connect to this port.
  362. Secret = SecurityKey; // Get the security key.
  363. Node = License; // Get the Node ID.
  364. }
  365. try { // Lots can go wrong so catch it :-)
  366. // 20080326 _M Blocking sockets tend to lock up so I've refactored this
  367. // code to use non-blocking sockets. This is actually part of the previous
  368. // refactor (TCPWatchdog see below) since without the watchdog there is no
  369. // way to get out of a blocking socket if it's dead.
  370. // 20080325 _M TCPWatchdog is a brute. It doesn't pay attention to thread
  371. // states. A weird bug showed up where the SYNC session seemed to hang and
  372. // the TCPWatchdog was left alive. In the process of hunting down this bug
  373. // I decided to remove the TCPWatchdog and put appropriate timeout checking
  374. // in each of the comms loops instead. So, from now on:
  375. // if(SessionDog.isExpired()) throw SyncFailed("Out Of Time");
  376. const int SyncSessionTimeout = 2 * SYNCTimer.getDuration(); // Timeout is twice poll time.
  377. Timeout SessionDog(SyncSessionTimeout); // Give this long for a session.
  378. // Connect to the sync host.
  379. CurrentThreadState(SYNC_Connect);
  380. SocketAddress SyncHostAddress; // We'll need an address.
  381. SyncHostAddress.setPort(HostPort); // Set the port.
  382. SyncHostAddress.setAddress(ResolveHostIPFromName(HostName)); // Resolve and set the IP.
  383. TCPHost SyncServer(SyncHostAddress); // Set up a host connection.
  384. SyncServer.makeNonBlocking(); // Make the connection non-blocking.
  385. PollTimer WaitForOpen(10, 340); // Expand 10ms to 340ms between tries.
  386. while(!SessionDog.isExpired()) { // Wait & Watch for a good connection.
  387. try { SyncServer.open(); } // Try opening the connection.
  388. catch(exception& e) { // If we get an exception then
  389. string ConnectFailMessage = "snfNETmgr::sync().open() "; // format a useful message about
  390. ConnectFailMessage.append(e.what()); // the error and then throw
  391. throw SyncFailed(ConnectFailMessage); // a SyncFailed exception.
  392. }
  393. if(SyncServer.isOpen()) break; // When successful, let's Go!
  394. else WaitForOpen.pause(); // When not yet successful, pause
  395. } // then try again if we have time.
  396. if(!SyncServer.isOpen()) throw SyncFailed("Connect Timed Out"); // Check our connection.
  397. if(SessionDog.isExpired()) throw SyncFailed("Out Of Time"); // Check our session time.
  398. // Start communicating.
  399. string LineBuffer = ""; // Input Line Buffer.
  400. // Read challenge
  401. CurrentThreadState(SYNC_Read_Challenge);
  402. LineBuffer = readLineTimeout(SyncServer, SessionDog); // Read the challenge line.
  403. snf_sync Challenge(LineBuffer.c_str(), LineBuffer.length()); // Interpret what we read.
  404. if( // Check that it's good...
  405. Challenge.bad() || // A complete packet was read
  406. 0 >= Challenge.snf_sync_challenge_txt.length() // and the challenge is present.
  407. ) throw SyncFailed("sync() Challenge.bad()"); // If not then throw.
  408. if(SessionDog.isExpired()) throw SyncFailed("Out Of Time"); // Check our session time.
  409. // Write response
  410. CurrentThreadState(SYNC_Compute_Response);
  411. from_base64 DecodedChallenge(Challenge.snf_sync_challenge_txt); // Decode the challenge.
  412. //--- Prepare the secret.
  413. MANGLER ResponseGenerator; // Grab a mangler.
  414. for(unsigned int i = 0; i < Secret.length(); i++) // Fill it with the
  415. ResponseGenerator.Encrypt(Secret.at(i)); // security key.
  416. const int ManglerKeyExpansionCount = 1024; // Loop this many to randomize.
  417. for(int x = 0, i = 0; i < ManglerKeyExpansionCount; i++) // For the required number of loops,
  418. x = ResponseGenerator.Encrypt(x); // have Mangler chase it's tail.
  419. //--- Absorb the challenge.
  420. for(unsigned int i = 0; i < DecodedChallenge.size(); i++) // Evolve through the challenge.
  421. ResponseGenerator.Encrypt(DecodedChallenge.at(i));
  422. /*** We now have half of the key for this session ***/
  423. //--- Encrypt our Pad.
  424. PadBuffer NewPad = OneTimePad(); // Grab a new Pad (default size).
  425. base64buffer ResponseBin; // With the key now established,
  426. for(unsigned int i = 0; i < NewPad.size(); i++) // encrypt the one time pad for
  427. ResponseBin.push_back( // transfer.
  428. ResponseGenerator.Encrypt(NewPad[i]));
  429. //--- Encrypt our Handshake.
  430. PadBuffer CurrentHandshake = Handshake(); // Recall the secret handshake.
  431. for(unsigned int i = 0; i < CurrentHandshake.size(); i++) // Encrypt that into the stream.
  432. ResponseBin.push_back(
  433. ResponseGenerator.Encrypt(CurrentHandshake[i]));
  434. //--- Encrypt our Signature.
  435. for(unsigned int x = 0, i = 0; i < SNFSignatureSize; i++) // Generate a hash by having Mangler
  436. ResponseBin.push_back( // chase it's tail for the appropriate
  437. x = ResponseGenerator.Encrypt(x)); // number of bytes.
  438. //--- Encode our response as base64 and send it.
  439. to_base64 ResponseTxt(ResponseBin); // Encode the cyphertext as base64.
  440. string ResponseTxtString; // Create a handy string and place
  441. ResponseTxtString.assign(ResponseTxt.begin(), ResponseTxt.end()); // the base 64 text into it.
  442. string ResponseMsg; // Build an appropriate response
  443. ResponseMsg.append("<snf><sync><response nodeid=\'"); // identifying this node
  444. ResponseMsg.append(Node); // with the license id
  445. ResponseMsg.append("\' text=\'"); // and providing an appropriately
  446. ResponseMsg.append(ResponseTxtString); // mangled response string
  447. ResponseMsg.append("\'/></sync></snf>\n"); // for authentication.
  448. CurrentThreadState(SYNC_Send_Response);
  449. sendDataTimeout(SyncServer, SessionDog, ResponseMsg); // Send the response.
  450. if(SessionDog.isExpired()) throw SyncFailed("Out Of Time"); // Check our session time.
  451. // Read rulebase info or error
  452. CurrentThreadState(SYNC_Read_Availabilty);
  453. LineBuffer = readLineTimeout(SyncServer, SessionDog); // Read the rulebase status line.
  454. snf_sync RulebaseResponse(LineBuffer.c_str(), LineBuffer.length()); // Interpret what we read.
  455. if( // Check that it's good...
  456. RulebaseResponse.bad() // A complete packet was read.
  457. ) throw SyncFailed("sync() Response.bad()"); // If not then throw.
  458. if(0 < RulebaseResponse.snf_sync_error_message.length()) { // If the response was an error
  459. PadBuffer NewNullHandshake; // then we will assume we are out
  460. NewNullHandshake.assign(SNFHandshakeSize, 0); // of sync with the server so we
  461. Handshake(NewNullHandshake); // will set the NULL handshake and
  462. throw SyncFailed("sync() Response error message"); // fail this sync attempt.
  463. }
  464. if(SessionDog.isExpired()) throw SyncFailed("Out Of Time"); // Check our session time.
  465. // Update Handshake
  466. for(int x = 0, i = 0; i < ManglerKeyExpansionCount; i++) // For the required number of loops,
  467. x = ResponseGenerator.Encrypt(x); // have Mangler chase it's tail.
  468. PadBuffer NewHandshake; // Grab a new handshake buffer.
  469. for(unsigned int x = 0, i = 0; i < SNFHandshakeSize; i++) // Create the new handshake as a
  470. NewHandshake.push_back( // mangler hash of the current
  471. x = ResponseGenerator.Encrypt(x)); // key state (proper length of course).
  472. Handshake(NewHandshake); // Save our new handshake to disk.
  473. // Interpret Rulebase Response
  474. myLOGmgr->updateAvailableUTC(RulebaseResponse.snf_sync_rulebase_utc); // Store the latest update UTC.
  475. if(myLOGmgr->isUpdateAvailable()) { // If a new update is read then
  476. postUpdateTrigger(RulebaseResponse.snf_sync_rulebase_utc); // create an update trigger file.
  477. }
  478. // Write our Client reports (multi-line)
  479. CurrentThreadState(SYNC_Send_GBUdb_Alerts);
  480. string ClientReport;
  481. ClientReport.append("<snf><sync><client>\n");
  482. sendDataTimeout(SyncServer, SessionDog, ClientReport);
  483. ClientReport = "";
  484. if(SessionDog.isExpired()) throw SyncFailed("Out Of Time"); // Check our session time.
  485. // Insert our GBUdb Alerts.
  486. list<GBUdbAlert> Alerts; // Make a list of GBUdb Alerts.
  487. myGBUdbmgr->GetAlertsForSync(Alerts); // Get them from our GBUdb.
  488. list<GBUdbAlert>::iterator iA;
  489. for(iA = Alerts.begin(); iA != Alerts.end(); iA++) { // Convert each alert in our list
  490. ClientReport.append((*iA).toXML()); // into XML, follow it up
  491. ClientReport.append("\n"); // with a new line, and send it
  492. }
  493. sendDataTimeout(SyncServer, SessionDog, ClientReport); // Send the Client report data.
  494. ClientReport = ""; // Clear the buffer.
  495. if(SessionDog.isExpired()) throw SyncFailed("Out Of Time"); // Check our session time.
  496. // Send Status Reports - one line at a time.
  497. CurrentThreadState(SYNC_Send_Status_Reports);
  498. /**
  499. *** Instead of splitting up the reports by line we will try sending them
  500. *** all at once using the new sendDataTimeout() function.
  501. ***
  502. if(0 < ReportsBuffer.length()) { // If we have reports - send them.
  503. string DataToSend = getReports(); // Grab a copy and clear the buffer.
  504. int Cursor = 0; // We need a cursor and a length
  505. int Length = 0; // to help us feed this line by line.
  506. while(Cursor < DataToSend.length()) { // While we have more data...
  507. Length = DataToSend.find_first_of('\n', Cursor); // Find the end of the first line.
  508. if(string::npos == Length) break; // If we can't then we're done.
  509. Length = (Length + 1) - Cursor; // If we can, convert that to length.
  510. SyncServer.transmit( // Get and send the line using the
  511. DataToSend.substr(Cursor, Length).c_str(), // substring function.
  512. Length
  513. );
  514. Cursor = Cursor + Length; // Move the cursor for the next line.
  515. if(SessionDog.isExpired()) throw SyncFailed("Out Of Time"); // Check our session time.
  516. }
  517. }
  518. **/
  519. if(0 < ReportsBuffer.length()) { // If we have reports to send
  520. string DataToSend = getReports(); // get (and clear) the reports and
  521. sendDataTimeout(SyncServer, SessionDog, DataToSend); // send them (mindful of timeout).
  522. }
  523. if(SessionDog.isExpired()) throw SyncFailed("Out Of Time"); // Check our session time.
  524. // Send Samples - one line at a time.
  525. CurrentThreadState(SYNC_Send_Samples);
  526. /***
  527. if(0 < SamplesBuffer.length()) {
  528. string DataToSend = getSamples();
  529. int Cursor = 0; // We need a cursor and a length
  530. int Length = 0; // to help us feed this line by line.
  531. while(Cursor < DataToSend.length()) { // While we have more data...
  532. Length = DataToSend.find_first_of('\n', Cursor); // Find the end of the first line.
  533. if(string::npos == Length) break; // If we can't then we're done.
  534. Length = (Length + 1) - Cursor; // If we can, convert that to length.
  535. SyncServer.transmit( // Get and send the line using the
  536. DataToSend.substr(Cursor, Length).c_str(), // substring function.
  537. Length
  538. );
  539. Cursor = Cursor + Length; // Move the cursor for the next line.
  540. if(SessionDog.isExpired()) throw SyncFailed("Out Of Time"); // Check our session time.
  541. }
  542. }
  543. ***/
  544. if(0 < SamplesBuffer.length()) { // If we have samples to send
  545. string DataToSend = getSamples(); // get (and clear) the samples and
  546. sendDataTimeout(SyncServer, SessionDog, DataToSend); // send them (mindful of timeout).
  547. }
  548. if(SessionDog.isExpired()) throw SyncFailed("Out Of Time"); // Check our session time.
  549. // Terminate the client messages.
  550. CurrentThreadState(SYNC_Send_End_Of_Report);
  551. ClientReport.append("</client></sync></snf>\n");
  552. sendDataTimeout(SyncServer, SessionDog, ClientReport); // Send the Client report.
  553. if(SessionDog.isExpired()) throw SyncFailed("Out Of Time"); // Check our session time.
  554. // Read the Server response (multi-line)
  555. CurrentThreadState(SYNC_Read_Server_Response);
  556. string ServerResponse;
  557. string ResponseLine;
  558. while(string::npos == ResponseLine.find("</snf>\n")) { // Until we find the ending...
  559. ResponseLine = readLineTimeout(SyncServer, SessionDog); // Read a line.
  560. if(0 >= ResponseLine.length()) { // If we get an empty line
  561. throw SyncFailed("sync() server response empty line"); // then it's an error.
  562. }
  563. ServerResponse.append(ResponseLine); // Append the line.
  564. if(SessionDog.isExpired()) throw SyncFailed("Out Of Time"); // Check our session time.
  565. }
  566. snf_sync ServerMessages(
  567. ServerResponse.c_str(), ServerResponse.length()); // Interpret what we read.
  568. if( // Check that it's good...
  569. ServerMessages.bad() // A complete packet was read.
  570. ) throw SyncFailed("sync() ServerMessages.bad()"); // If not then throw.
  571. // At this point we should have a good Server response.
  572. CurrentThreadState(SYNC_Close_Connection);
  573. SyncServer.close(); // Close the connection.
  574. evolvePad(Challenge.snf_sync_challenge_txt); // Use this event for more entropy.
  575. // Import any GBUdb reflections.
  576. CurrentThreadState(SYNC_Parse_GBUdb_Reflections);
  577. if(0 < ServerMessages.ServerGBUAlertHandler.AlertList.size()) { // If we have received reflections
  578. myGBUdbmgr->ProcessReflections( // then process them through our
  579. ServerMessages.ServerGBUAlertHandler.AlertList // GBUdb.
  580. );
  581. }
  582. /*** On Sync Override set sync timer to override time. If no override
  583. **** then be sure to reset the timer to the current CFG value if it
  584. **** is not already there. Also, if sync override is not engaged then
  585. **** be sure the overrid flag is set to -1 indicating it is off.
  586. **** Configure() code assumes we are handling the override sync timer
  587. **** functions this way.
  588. ***/
  589. // Assign the SyncSecsOverride with the value we retrieved. It will
  590. // either be a seconds value, or a -1 indicating it was absent from
  591. // the server message.
  592. SyncSecsOverride = ServerMessages.snf_sync_server_resync_secs; // What was the SyncOverride?
  593. const int SecsAsms = 1000; // Multiplier - seconds to milliseconds.
  594. if(0 > SyncSecsOverride) { // If the sync timer IS NOT in override,
  595. if(SYNCTimer.getDuration() != SecsAsMSecs(SyncSecsConfigured)) { // And the config time is different than
  596. SYNCTimer.setDuration(SyncSecsConfigured * SecsAsms); // the timer's current setting then set
  597. } // the timer to the new value.
  598. } else { // If the sync timer IS in override now,
  599. if(SYNCTimer.getDuration() != SecsAsMSecs(SyncSecsOverride)) { // and the override is different than the
  600. SYNCTimer.setDuration(SecsAsMSecs(SyncSecsOverride)); // current setting then override the setting
  601. } // with the new value.
  602. }
  603. // All done
  604. CurrentThreadState(SYNC_Log_Event);
  605. (*myLOGmgr).RecordSyncEvent(); // Finished that -- so log the event.
  606. }
  607. catch (exception& e) { // SYNC Failed and we know more.
  608. const int snf_UNKNOWN_ERROR = 99; // Report an error (unknown code)
  609. string ERROR_SYNC_FAILEDmsg = CurrentThreadState().Name; // Format a useful state message.
  610. ERROR_SYNC_FAILEDmsg.append(": ");
  611. ERROR_SYNC_FAILEDmsg.append(e.what());
  612. (*myLOGmgr).logThisError( // Log the error (if possible)
  613. "SNF_NETWORK", snf_UNKNOWN_ERROR, ERROR_SYNC_FAILEDmsg
  614. );
  615. }
  616. catch (...) { // SYNC Failed if we're here.
  617. const int snf_UNKNOWN_ERROR = 99; // Report an error (unknown code)
  618. string ERROR_SYNC_FAILEDmsg = CurrentThreadState().Name; // Format a useful state message.
  619. ERROR_SYNC_FAILEDmsg.append(": Panic!");
  620. (*myLOGmgr).logThisError( // Log the error (if possible)
  621. "SNF_NETWORK", snf_UNKNOWN_ERROR, ERROR_SYNC_FAILEDmsg
  622. );
  623. }
  624. }
  625. }