statistics.cpp 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629
  1. // Aidmar
  2. #include <iostream>
  3. #include <fstream>
  4. #include <vector>
  5. #include <math.h>
  6. #include <sstream>
  7. #include <SQLiteCpp/SQLiteCpp.h>
  8. #include "statistics_db.h"
  9. #include "statistics.h"
  10. // Aidmar
  11. /**
  12. * Calculates entropy of source and destination IPs for last time interval.
  13. * The results are written to ip_entropy_interval.csv file.
  14. * @param intervalStartTimestamp The timstamp where the interval starts.
  15. */
  16. std::vector<float> statistics::calculateLastIntervalIPsEntropy(std::chrono::microseconds intervalStartTimestamp){
  17. std::vector <int> IPsSrcPktsCounts;
  18. std::vector <int> IPsDstPktsCounts;
  19. std::vector <float> IPsSrcProb;
  20. std::vector <float> IPsDstProb;
  21. int pktsSent = 0, pktsReceived = 0;
  22. for (auto i = ip_statistics.begin(); i != ip_statistics.end(); i++) {
  23. // TO-DO: should add this condition to avoid Segmentation Fault if(i->second.pktsSentTimestamp.size()>0) realy?
  24. int indexStartSent = getClosestIndex(i->second.pktsSentTimestamp, intervalStartTimestamp);
  25. int IPsSrcPktsCount = i->second.pktsSentTimestamp.size() - indexStartSent;
  26. IPsSrcPktsCounts.push_back(IPsSrcPktsCount);
  27. pktsSent += IPsSrcPktsCount;
  28. int indexStartReceived = getClosestIndex(i->second.pktsReceivedTimestamp, intervalStartTimestamp);
  29. int IPsDstPktsCount = i->second.pktsReceivedTimestamp.size() - indexStartReceived;
  30. IPsDstPktsCounts.push_back(IPsDstPktsCount);
  31. pktsReceived += IPsDstPktsCount;
  32. }
  33. for (auto i = IPsSrcPktsCounts.begin(); i != IPsSrcPktsCounts.end(); i++) {
  34. IPsSrcProb.push_back((float)*i/pktsSent);
  35. }
  36. for (auto i = IPsDstPktsCounts.begin(); i != IPsDstPktsCounts.end(); i++) {
  37. IPsDstProb.push_back((float)*i/pktsReceived);
  38. }
  39. // Calculate IP source entropy
  40. float IPsSrcEntropy = 0;
  41. for(unsigned i=0; i < IPsSrcProb.size();i++){
  42. if (IPsSrcProb[i] > 0)
  43. IPsSrcEntropy += - IPsSrcProb[i]*log2(IPsSrcProb[i]);
  44. }
  45. // Calculate IP destination entropy
  46. float IPsDstEntropy = 0;
  47. for(unsigned i=0; i < IPsDstProb.size();i++){
  48. if (IPsDstProb[i] > 0)
  49. IPsDstEntropy += - IPsDstProb[i]*log2(IPsDstProb[i]);
  50. }
  51. std::vector<float> entropies = {IPsSrcEntropy, IPsDstEntropy};
  52. return entropies;
  53. }
  54. // Aidmar
  55. /**
  56. * Calculates cumulative entropy of source and destination IPs, i.e., the entropy for packets from the beginning of the pcap file.
  57. */
  58. std::vector<float> statistics::calculateIPsCumEntropy(){
  59. std::vector <std::string> IPs;
  60. std::vector <float> IPsSrcProb;
  61. std::vector <float> IPsDstProb;
  62. for (auto i = ip_statistics.begin(); i != ip_statistics.end(); i++) {
  63. IPs.push_back(i->first);
  64. IPsSrcProb.push_back((float)i->second.pkts_sent/packetCount);
  65. IPsDstProb.push_back((float)i->second.pkts_received/packetCount);
  66. }
  67. // Calculate IP source entropy
  68. float IPsSrcEntropy = 0;
  69. for(unsigned i=0; i < IPsSrcProb.size();i++){
  70. if (IPsSrcProb[i] > 0)
  71. IPsSrcEntropy += - IPsSrcProb[i]*log2(IPsSrcProb[i]);
  72. }
  73. //std::cout << packetCount << ": SrcEnt: " << IPsSrcEntropy << "\n";
  74. // Calculate IP destination entropy
  75. float IPsDstEntropy = 0;
  76. for(unsigned i=0; i < IPsDstProb.size();i++){
  77. if (IPsDstProb[i] > 0)
  78. IPsDstEntropy += - IPsDstProb[i]*log2(IPsDstProb[i]);
  79. }
  80. //std::cout << packetCount << ": DstEnt: " << IPsDstEntropy << "\n";
  81. std::vector<float> entropies = {IPsSrcEntropy, IPsDstEntropy};
  82. return entropies;
  83. }
  84. // Aidmar
  85. /**
  86. * Calculates sending packet rate for each IP in last time interval. Finds min and max packet rate and adds them to ip_statistics map.
  87. * @param intervalStartTimestamp The timstamp where the interval starts.
  88. */
  89. void statistics::calculateIPIntervalPacketRate(std::chrono::duration<int, std::micro> interval, std::chrono::microseconds intervalStartTimestamp){
  90. for (auto i = ip_statistics.begin(); i != ip_statistics.end(); i++) {
  91. int indexStartSent = getClosestIndex(i->second.pktsSentTimestamp, intervalStartTimestamp);
  92. int IPsSrcPktsCount = i->second.pktsSentTimestamp.size() - indexStartSent;
  93. float interval_pkt_rate = (float) IPsSrcPktsCount * 1000000 / interval.count(); // used 10^6 because interval in microseconds
  94. i->second.interval_pkt_rate.push_back(interval_pkt_rate);
  95. if(interval_pkt_rate > i->second.max_pkt_rate || i->second.max_pkt_rate == 0)
  96. i->second.max_pkt_rate = interval_pkt_rate;
  97. if(interval_pkt_rate < i->second.min_pkt_rate || i->second.min_pkt_rate == 0)
  98. i->second.min_pkt_rate = interval_pkt_rate;
  99. }
  100. }
  101. // Aidmar
  102. /**
  103. * Registers statistical data for last time interval. Calculates packet rate. Calculates IPs entropy. Calculates IPs cumulative entropy.
  104. * @param intervalStartTimestamp The timstamp where the interval starts.
  105. * @param intervalEndTimestamp The timstamp where the interval ends.
  106. * @param previousPacketCount The total number of packets in last interval.
  107. */
  108. void statistics::addIntervalStat(std::chrono::duration<int, std::micro> interval, std::chrono::microseconds intervalStartTimestamp, std::chrono::microseconds intervalEndTimestamp, int previousPacketCount, float previousSumPacketSize){
  109. // Add packet rate for each IP to ip_statistics map
  110. calculateIPIntervalPacketRate(interval, intervalStartTimestamp);
  111. //std::vector<float> ipEntopies = calculateLastIntervalIPsEntropy(intervalStartTimestamp);
  112. //std::vector<float> ipCumEntopies = calculateIPsCumEntropy();
  113. std::string lastPktTimestamp_s = std::to_string(intervalEndTimestamp.count());
  114. interval_statistics[lastPktTimestamp_s].pkts_count = packetCount - previousPacketCount;
  115. interval_statistics[lastPktTimestamp_s].kbytes = (float(sumPacketSize - previousSumPacketSize) / 1024);
  116. /*if(ipEntopies.size()>1){
  117. interval_statistics[lastPktTimestamp_s].ip_src_entropy = ipEntopies[0];
  118. interval_statistics[lastPktTimestamp_s].ip_dst_entropy = ipEntopies[1];
  119. }
  120. if(ipCumEntopies.size()>1){
  121. interval_statistics[lastPktTimestamp_s].ip_src_cum_entropy = ipCumEntopies[0];
  122. interval_statistics[lastPktTimestamp_s].ip_dst_cum_entropy = ipCumEntopies[1];
  123. }*/
  124. }
  125. // Aidmar
  126. /**
  127. * Registers statistical data for a sent packet in a given conversation (two IPs, two ports).
  128. * Increments the counter packets_A_B or packets_B_A.
  129. * Adds the timestamp of the packet in pkts_A_B_timestamp or pkts_B_A_timestamp.
  130. * @param ipAddressSender The sender IP address.
  131. * @param sport The source port.
  132. * @param ipAddressReceiver The receiver IP address.
  133. * @param dport The destination port.
  134. * @param timestamp The timestamp of the packet.
  135. */
  136. void statistics::addConvStat(std::string ipAddressSender,int sport,std::string ipAddressReceiver,int dport, std::chrono::microseconds timestamp){
  137. conv f1 = {ipAddressReceiver, dport, ipAddressSender, sport};
  138. conv f2 = {ipAddressSender, sport, ipAddressReceiver, dport};
  139. // if already exist A(ipAddressReceiver, dport), B(ipAddressSender, sport)
  140. if (conv_statistics.count(f1)>0){
  141. conv_statistics[f1].pkts_B_A++; // increment packets number from B to A
  142. conv_statistics[f1].pkts_B_A_timestamp.push_back(timestamp);
  143. // Calculate reply delay considering only delay of first two reply packets (TCP handshake)
  144. //if(conv_statistics[f1].pkts_A_B_timestamp.size()>0 && conv_statistics[f1].pkts_A_B_timestamp.size()<=2){
  145. conv_statistics[f1].pkts_delay.push_back(std::chrono::duration_cast<std::chrono::microseconds> (timestamp - conv_statistics[f1].pkts_A_B_timestamp.back()));
  146. //}
  147. }
  148. else{
  149. conv_statistics[f2].pkts_A_B++; // increment packets number from A to B
  150. conv_statistics[f2].pkts_A_B_timestamp.push_back(timestamp);
  151. }
  152. }
  153. // Aidmar
  154. /**
  155. * Increments the packet counter for the given IP address and MSS value.
  156. * @param ipAddress The IP address whose MSS packet counter should be incremented.
  157. * @param mssValue The MSS value of the packet.
  158. */
  159. void statistics::incrementMSScount(std::string ipAddress, int mssValue) {
  160. mss_distribution[{ipAddress, mssValue}]++;
  161. }
  162. // Aidmar
  163. /**
  164. * Increments the packet counter for the given IP address and window size.
  165. * @param ipAddress The IP address whose window size packet counter should be incremented.
  166. * @param winSize The window size of the packet.
  167. */
  168. void statistics::incrementWinCount(std::string ipAddress, int winSize) {
  169. win_distribution[{ipAddress, winSize}]++;
  170. }
  171. /**
  172. * Increments the packet counter for the given IP address and TTL value.
  173. * @param ipAddress The IP address whose TTL packet counter should be incremented.
  174. * @param ttlValue The TTL value of the packet.
  175. */
  176. void statistics::incrementTTLcount(std::string ipAddress, int ttlValue) {
  177. ttl_distribution[{ipAddress, ttlValue}]++;
  178. }
  179. /**
  180. * Increments the protocol counter for the given IP address and protocol.
  181. * @param ipAddress The IP address whose protocol packet counter should be incremented.
  182. * @param protocol The protocol of the packet.
  183. */
  184. void statistics::incrementProtocolCount(std::string ipAddress, std::string protocol) {
  185. protocol_distribution[{ipAddress, protocol}]++;
  186. }
  187. /**
  188. * Returns the number of packets seen for the given IP address and protocol.
  189. * @param ipAddress The IP address whose packet count is wanted.
  190. * @param protocol The protocol whose packet count is wanted.
  191. * @return an integer: the number of packets
  192. */
  193. int statistics::getProtocolCount(std::string ipAddress, std::string protocol) {
  194. return protocol_distribution[{ipAddress, protocol}];
  195. }
  196. /**
  197. * Increments the packet counter for
  198. * - the given sender IP address with outgoing port and
  199. * - the given receiver IP address with incoming port.
  200. * @param ipAddressSender The IP address of the packet sender.
  201. * @param outgoingPort The port used by the sender.
  202. * @param ipAddressReceiver The IP address of the packet receiver.
  203. * @param incomingPort The port used by the receiver.
  204. */
  205. void statistics::incrementPortCount(std::string ipAddressSender, int outgoingPort, std::string ipAddressReceiver,
  206. int incomingPort) {
  207. ip_ports[{ipAddressSender, "out", outgoingPort}]++;
  208. ip_ports[{ipAddressReceiver, "in", incomingPort}]++;
  209. }
  210. /**
  211. * Creates a new statistics object.
  212. */
  213. statistics::statistics(void) {
  214. }
  215. /**
  216. * Stores the assignment IP address -> MAC address.
  217. * @param ipAddress The IP address belonging to the given MAC address.
  218. * @param macAddress The MAC address belonging to the given IP address.
  219. */
  220. void statistics::assignMacAddress(std::string ipAddress, std::string macAddress) {
  221. ip_mac_mapping[ipAddress] = macAddress;
  222. }
  223. /**
  224. * Registers statistical data for a sent packet. Increments the counter packets_sent for the sender and
  225. * packets_received for the receiver. Adds the bytes as kbytes_sent (sender) and kybtes_received (receiver).
  226. * @param ipAddressSender The IP address of the packet sender.
  227. * @param ipAddressReceiver The IP address of the packet receiver.
  228. * @param bytesSent The packet's size.
  229. */
  230. void statistics::addIpStat_packetSent(std::string filePath, std::string ipAddressSender, std::string ipAddressReceiver, long bytesSent, std::chrono::microseconds timestamp) {
  231. // Aidmar - Adding IP as a sender for first time
  232. if(ip_statistics[ipAddressSender].pkts_sent==0){
  233. // Add the IP class
  234. ip_statistics[ipAddressSender].ip_class = getIPv4Class(ipAddressSender);
  235. // Initialize packet rates
  236. /*ip_statistics[ipAddressSender].max_pkt_rate = 0;
  237. ip_statistics[ipAddressSender].min_pkt_rate = 0;
  238. // Caculate Mahoney anomaly score for ip.src
  239. float ipSrc_Mahoney_score = 0;
  240. // s_r: The number of IP sources (the different values)
  241. // n: The number of the total instances
  242. // s_t: The "time" since last anomalous (novel) IP was appeared
  243. int s_t = 0, n = 0, s_r = 0;
  244. for (auto i = ip_statistics.begin(); i != ip_statistics.end(); i++) {
  245. if (i->second.pkts_sent > 0)
  246. s_r++;
  247. }
  248. if(s_r > 0){
  249. // The number of the total instances
  250. n = packetCount;
  251. // The packet count when the last novel IP was added as a sender
  252. int pktCntNvlSndr = 0;
  253. for (auto i = ip_statistics.begin(); i != ip_statistics.end(); i++) {
  254. if (pktCntNvlSndr < i->second.firstAppearAsSenderPktCount)
  255. pktCntNvlSndr = i->second.firstAppearAsSenderPktCount;
  256. }
  257. // The "time" since last anomalous (novel) IP was appeared
  258. s_t = packetCount - pktCntNvlSndr + 1;
  259. ipSrc_Mahoney_score = (float)s_t*n/s_r;
  260. }
  261. ip_statistics[ipAddressSender].firstAppearAsSenderPktCount = packetCount;
  262. ip_statistics[ipAddressSender].sourceAnomalyScore = ipSrc_Mahoney_score;
  263. */
  264. }
  265. // Aidmar - Adding IP as a receiver for first time
  266. if(ip_statistics[ipAddressReceiver].pkts_received==0){
  267. // Add the IP class
  268. ip_statistics[ipAddressReceiver].ip_class = getIPv4Class(ipAddressReceiver);
  269. // Caculate Mahoney anomaly score for ip.dst
  270. /*float ipDst_Mahoney_score = 0;
  271. // s_r: The number of IP sources (the different values)
  272. // n: The number of the total instances
  273. // s_t: The "time" since last anomalous (novel) IP was appeared
  274. int s_t = 0, n = 0, s_r = 0;
  275. for (auto i = ip_statistics.begin(); i != ip_statistics.end(); i++) {
  276. if (i->second.pkts_received > 0)
  277. s_r++;
  278. }
  279. if(s_r > 0){
  280. // The number of the total instances
  281. n = packetCount;
  282. // The packet count when the last novel IP was added as a sender
  283. int pktCntNvlRcvr = 0;
  284. for (auto i = ip_statistics.begin(); i != ip_statistics.end(); i++) {
  285. if (pktCntNvlRcvr < i->second.firstAppearAsReceiverPktCount)
  286. pktCntNvlRcvr = i->second.firstAppearAsReceiverPktCount;
  287. }
  288. // The "time" since last anomalous (novel) IP was appeared
  289. s_t = packetCount - pktCntNvlRcvr + 1;
  290. ipDst_Mahoney_score = (float)s_t*n/s_r;
  291. }
  292. ip_statistics[ipAddressReceiver].firstAppearAsReceiverPktCount = packetCount;
  293. ip_statistics[ipAddressReceiver].destinationAnomalyScore = ipDst_Mahoney_score;
  294. */
  295. }
  296. // Update stats for packet sender
  297. ip_statistics[ipAddressSender].kbytes_sent += (float(bytesSent) / 1024);
  298. ip_statistics[ipAddressSender].pkts_sent++;
  299. // Aidmar
  300. //ip_statistics[ipAddressSender].pktsSentTimestamp.push_back(timestamp);
  301. //// Aidmar - calculate packet rate (assumption: max_pkt_rate=1/smallest time between two consecutive pkts)
  302. // resulting in very big rates, therefore it could be better to calculate pkt rate on time intervals
  303. /*if(ip_statistics[ipAddressSender].pktsSentTimestamp.size() > 0){
  304. std::chrono::microseconds temp_pkt_consecutive_time = timestamp - ip_statistics[ipAddressSender].pktsSentTimestamp.back();
  305. float temp_pkt_rate = (float) 1000000/temp_pkt_consecutive_time.count(); // pkt per sec = 10**6/micro sec
  306. if(temp_pkt_rate > ip_statistics[ipAddressSender].max_pkt_rate || ip_statistics[ipAddressSender].max_pkt_rate == 0)
  307. ip_statistics[ipAddressSender].max_pkt_rate = temp_pkt_rate;
  308. if(temp_pkt_rate < ip_statistics[ipAddressSender].min_pkt_rate || ip_statistics[ipAddressSender].min_pkt_rate == 0)
  309. ip_statistics[ipAddressSender].min_pkt_rate = temp_pkt_rate;
  310. }*/
  311. // Update stats for packet receiver
  312. ip_statistics[ipAddressReceiver].kbytes_received += (float(bytesSent) / 1024);
  313. ip_statistics[ipAddressReceiver].pkts_received++;
  314. // Aidmar
  315. //ip_statistics[ipAddressReceiver].pktsReceivedTimestamp.push_back(timestamp);
  316. }
  317. /**
  318. * Registers a value of the TCP option Maximum Segment Size (MSS).
  319. * @param ipAddress The IP address which sent the TCP packet.
  320. * @param MSSvalue The MSS value found.
  321. */
  322. void statistics::addMSS(std::string ipAddress, int MSSvalue) {
  323. ip_sumMss[ipAddress] += MSSvalue;
  324. }
  325. /**
  326. * Setter for the timestamp_firstPacket field.
  327. * @param ts The timestamp of the first packet in the PCAP file.
  328. */
  329. void statistics::setTimestampFirstPacket(Tins::Timestamp ts) {
  330. timestamp_firstPacket = ts;
  331. }
  332. /**
  333. * Setter for the timestamp_lastPacket field.
  334. * @param ts The timestamp of the last packet in the PCAP file.
  335. */
  336. void statistics::setTimestampLastPacket(Tins::Timestamp ts) {
  337. timestamp_lastPacket = ts;
  338. }
  339. // Aidmar
  340. /**
  341. * Getter for the timestamp_firstPacket field.
  342. */
  343. Tins::Timestamp statistics::getTimestampFirstPacket() {
  344. return timestamp_firstPacket;
  345. }
  346. /**
  347. * Getter for the timestamp_lastPacket field.
  348. */
  349. Tins::Timestamp statistics::getTimestampLastPacket() {
  350. return timestamp_lastPacket;
  351. }
  352. /**
  353. * Getter for the packetCount field.
  354. */
  355. int statistics::getPacketCount() {
  356. return packetCount;
  357. }
  358. /**
  359. * Getter for the sumPacketSize field.
  360. */
  361. int statistics::getSumPacketSize() {
  362. return sumPacketSize;
  363. }
  364. /**
  365. * Calculates the capture duration.
  366. * @return a formatted string HH:MM:SS.mmmmmm with
  367. * HH: hour, MM: minute, SS: second, mmmmmm: microseconds
  368. */
  369. std::string statistics::getCaptureDurationTimestamp() const {
  370. // Calculate duration
  371. time_t t = (timestamp_lastPacket.seconds() - timestamp_firstPacket.seconds());
  372. time_t ms = (timestamp_lastPacket.microseconds() - timestamp_firstPacket.microseconds());
  373. long int hour = t / 3600;
  374. long int remainder = (t - hour * 3600);
  375. long int minute = remainder / 60;
  376. long int second = (remainder - minute * 60) % 60;
  377. long int microseconds = ms;
  378. // Build desired output format: YYYY-mm-dd hh:mm:ss
  379. char out[64];
  380. sprintf(out, "%02ld:%02ld:%02ld.%06ld ", hour, minute, second, microseconds);
  381. return std::string(out);
  382. }
  383. /**
  384. * Calculates the capture duration.
  385. * @return a formatted string SS.mmmmmm with
  386. * S: seconds (UNIX time), mmmmmm: microseconds
  387. */
  388. float statistics::getCaptureDurationSeconds() const {
  389. timeval d;
  390. d.tv_sec = timestamp_lastPacket.seconds() - timestamp_firstPacket.seconds();
  391. d.tv_usec = timestamp_lastPacket.microseconds() - timestamp_firstPacket.microseconds();
  392. char tmbuf[64], buf[64];
  393. auto nowtm = localtime(&(d.tv_sec));
  394. strftime(tmbuf, sizeof(tmbuf), "%S", nowtm);
  395. snprintf(buf, sizeof(buf), "%s.%06u", tmbuf, (uint) d.tv_usec);
  396. return std::stof(std::string(buf));
  397. }
  398. /**
  399. * Creates a timestamp based on a time_t seconds (UNIX time format) and microseconds.
  400. * @param seconds
  401. * @param microseconds
  402. * @return a formatted string Y-m-d H:M:S.m with
  403. * Y: year, m: month, d: day, H: hour, M: minute, S: second, m: microseconds
  404. */
  405. std::string statistics::getFormattedTimestamp(time_t seconds, suseconds_t microseconds) const {
  406. timeval tv;
  407. tv.tv_sec = seconds;
  408. tv.tv_usec = microseconds;
  409. char tmbuf[64], buf[64];
  410. auto nowtm = localtime(&(tv.tv_sec));
  411. strftime(tmbuf, sizeof(tmbuf), "%Y-%m-%d %H:%M:%S", nowtm);
  412. snprintf(buf, sizeof(buf), "%s.%06u", tmbuf, (uint) tv.tv_usec);
  413. return std::string(buf);
  414. }
  415. /**
  416. * Calculates the statistics for a given IP address.
  417. * @param ipAddress The IP address whose statistics should be calculated.
  418. * @return a ip_stats struct containing statistical data derived by the statistical data collected.
  419. */
  420. ip_stats statistics::getStatsForIP(std::string ipAddress) {
  421. float duration = getCaptureDurationSeconds();
  422. entry_ipStat ipStatEntry = ip_statistics[ipAddress];
  423. ip_stats s;
  424. s.bandwidthKBitsIn = (ipStatEntry.kbytes_received / duration) * 8;
  425. s.bandwidthKBitsOut = (ipStatEntry.kbytes_sent / duration) * 8;
  426. s.packetPerSecondIn = (ipStatEntry.pkts_received / duration);
  427. s.packetPerSecondOut = (ipStatEntry.pkts_sent / duration);
  428. s.AvgPacketSizeSent = (ipStatEntry.kbytes_sent / ipStatEntry.pkts_sent);
  429. s.AvgPacketSizeRecv = (ipStatEntry.kbytes_received / ipStatEntry.pkts_received);
  430. int sumMSS = ip_sumMss[ipAddress];
  431. int tcpPacketsSent = getProtocolCount(ipAddress, "TCP");
  432. s.AvgMaxSegmentSizeTCP = ((sumMSS > 0 && tcpPacketsSent > 0) ? (sumMSS / tcpPacketsSent) : 0);
  433. return s;
  434. }
  435. /**
  436. * Increments the packet counter.
  437. */
  438. void statistics::incrementPacketCount() {
  439. packetCount++;
  440. }
  441. /**
  442. * Prints the statistics of the PCAP and IP specific statistics for the given IP address.
  443. * @param ipAddress The IP address whose statistics should be printed. Can be empty "" to print only general file statistics.
  444. */
  445. void statistics::printStats(std::string ipAddress) {
  446. std::stringstream ss;
  447. ss << std::endl;
  448. ss << "Capture duration: " << getCaptureDurationSeconds() << " seconds" << std::endl;
  449. ss << "Capture duration (HH:MM:SS.mmmmmm): " << getCaptureDurationTimestamp() << std::endl;
  450. ss << "#Packets: " << packetCount << std::endl;
  451. ss << std::endl;
  452. // Print IP address specific statistics only if IP address was given
  453. if (ipAddress != "") {
  454. entry_ipStat e = ip_statistics[ipAddress];
  455. ss << "\n----- STATS FOR IP ADDRESS [" << ipAddress << "] -------" << std::endl;
  456. ss << std::endl << "KBytes sent: " << e.kbytes_sent << std::endl;
  457. ss << "KBytes received: " << e.kbytes_received << std::endl;
  458. ss << "Packets sent: " << e.pkts_sent << std::endl;
  459. ss << "Packets received: " << e.pkts_received << "\n\n";
  460. ip_stats is = getStatsForIP(ipAddress);
  461. ss << "Bandwidth IN: " << is.bandwidthKBitsIn << " kbit/s" << std::endl;
  462. ss << "Bandwidth OUT: " << is.bandwidthKBitsOut << " kbit/s" << std::endl;
  463. ss << "Packets per second IN: " << is.packetPerSecondIn << std::endl;
  464. ss << "Packets per second OUT: " << is.packetPerSecondOut << std::endl;
  465. ss << "Avg Packet Size Sent: " << is.AvgPacketSizeSent << " kbytes" << std::endl;
  466. ss << "Avg Packet Size Received: " << is.AvgPacketSizeRecv << " kbytes" << std::endl;
  467. ss << "Avg MSS: " << is.AvgMaxSegmentSizeTCP << " bytes" << std::endl;
  468. }
  469. std::cout << ss.str();
  470. }
  471. /**
  472. * Derives general PCAP file statistics from the collected statistical data and
  473. * writes all data into a SQLite database, located at database_path.
  474. * @param database_path The path of the SQLite database file ending with .sqlite3.
  475. */
  476. void statistics::writeToDatabase(std::string database_path) {
  477. // Generate general file statistics
  478. float duration = getCaptureDurationSeconds();
  479. long sumPacketsSent = 0, senderCountIP = 0;
  480. float sumBandwidthIn = 0.0, sumBandwidthOut = 0.0;
  481. for (auto i = ip_statistics.begin(); i != ip_statistics.end(); i++) {
  482. sumPacketsSent += i->second.pkts_sent;
  483. // Consumed bandwith (bytes) for sending packets
  484. sumBandwidthIn += (i->second.kbytes_received / duration);
  485. sumBandwidthOut += (i->second.kbytes_sent / duration);
  486. senderCountIP++;
  487. }
  488. float avgPacketRate = (packetCount / duration);
  489. long avgPacketSize = getAvgPacketSize();
  490. long avgPacketsSentPerHost = (sumPacketsSent / senderCountIP);
  491. float avgBandwidthInKBits = (sumBandwidthIn / senderCountIP) * 8;
  492. float avgBandwidthOutInKBits = (sumBandwidthOut / senderCountIP) * 8;
  493. // Create database and write information
  494. statistics_db db(database_path);
  495. db.writeStatisticsFile(packetCount, getCaptureDurationSeconds(),
  496. getFormattedTimestamp(timestamp_firstPacket.seconds(), timestamp_firstPacket.microseconds()),
  497. getFormattedTimestamp(timestamp_lastPacket.seconds(), timestamp_lastPacket.microseconds()),
  498. avgPacketRate, avgPacketSize, avgPacketsSentPerHost, avgBandwidthInKBits,
  499. avgBandwidthOutInKBits);
  500. db.writeStatisticsIP(ip_statistics);
  501. db.writeStatisticsTTL(ttl_distribution);
  502. db.writeStatisticsIpMac(ip_mac_mapping);
  503. db.writeStatisticsMss(ip_sumMss);
  504. db.writeStatisticsPorts(ip_ports);
  505. db.writeStatisticsProtocols(protocol_distribution);
  506. // Aidmar
  507. db.writeStatisticsMss_dist(mss_distribution);
  508. db.writeStatisticsWin(win_distribution);
  509. db.writeStatisticsConv(conv_statistics);
  510. db.writeStatisticsInterval(interval_statistics);
  511. }
  512. /**
  513. * Returns the average packet size.
  514. * @return a float indicating the average packet size in kbytes.
  515. */
  516. float statistics::getAvgPacketSize() const {
  517. // AvgPktSize = (Sum of all packet sizes / #Packets)
  518. return (sumPacketSize / packetCount) / 1024;
  519. }
  520. /**
  521. * Adds the size of a packet (to be used to calculate the avg. packet size).
  522. * @param packetSize The size of the current packet in bytes.
  523. */
  524. void statistics::addPacketSize(uint32_t packetSize) {
  525. sumPacketSize += ((float) packetSize);
  526. }