statistics.cpp 28 KB

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