statistics.cpp 35 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811
  1. #include <iostream>
  2. #include <fstream>
  3. #include <vector>
  4. #include <math.h>
  5. #include "statistics.h"
  6. #include <sstream>
  7. #include <SQLiteCpp/SQLiteCpp.h>
  8. #include "statistics_db.h"
  9. #include "statistics.h"
  10. #include "utilities.h"
  11. using namespace Tins;
  12. /**
  13. * Checks if there is a payload and increments payloads counter.
  14. * @param pdu_l4 The packet that should be checked if it has a payload or not.
  15. */
  16. void statistics::checkPayload(const PDU *pdu_l4) {
  17. if(this->getDoExtraTests()) {
  18. // pdu_l4: Tarnsport layer 4
  19. int pktSize = pdu_l4->size();
  20. int headerSize = pdu_l4->header_size(); // TCP/UDP header
  21. int payloadSize = pktSize - headerSize;
  22. if (payloadSize > 0)
  23. payloadCount++;
  24. }
  25. }
  26. /**
  27. * Checks the correctness of TCP checksum and increments counter if the checksum was incorrect.
  28. * @param ipAddressSender The source IP.
  29. * @param ipAddressReceiver The destination IP.
  30. * @param tcpPkt The packet to get checked.
  31. */
  32. void statistics::checkTCPChecksum(const std::string &ipAddressSender, const std::string &ipAddressReceiver, TCP tcpPkt) {
  33. if(this->getDoExtraTests()) {
  34. if(check_tcpChecksum(ipAddressSender, ipAddressReceiver, tcpPkt))
  35. correctTCPChecksumCount++;
  36. else incorrectTCPChecksumCount++;
  37. }
  38. }
  39. /**
  40. * Calculates entropy of the source and destination IPs in a time interval.
  41. * @param intervalStartTimestamp The timstamp where the interval starts.
  42. * @return a vector: contains source IP entropy and destination IP entropy.
  43. */
  44. std::vector<float> statistics::calculateLastIntervalIPsEntropy(std::chrono::microseconds intervalStartTimestamp){
  45. if(this->getDoExtraTests()) {
  46. std::cout << "interval start timestamp: " << intervalStartTimestamp.count() << std::endl;
  47. // TODO: change datastructures
  48. std::vector<int> IPsSrcPktsCounts;
  49. std::vector<int> IPsDstPktsCounts;
  50. std::vector<double> IPsSrcProb;
  51. std::vector<double> IPsDstProb;
  52. int pktsSent = 0, pktsReceived = 0;
  53. for (auto i = ip_statistics.begin(); i != ip_statistics.end(); i++) {
  54. int IPsSrcPktsCount = 0;
  55. // TODO: iter backwards and break
  56. for (auto j = i->second.pkts_sent_timestamp.begin(); j != i->second.pkts_sent_timestamp.end(); j++) {
  57. if(*j >= intervalStartTimestamp)
  58. IPsSrcPktsCount++;
  59. }
  60. if(IPsSrcPktsCount != 0) {
  61. IPsSrcPktsCounts.push_back(IPsSrcPktsCount);
  62. pktsSent += IPsSrcPktsCount;
  63. }
  64. int IPsDstPktsCount = 0;
  65. for (auto j = i->second.pkts_received_timestamp.begin(); j != i->second.pkts_received_timestamp.end(); j++) {
  66. if(*j >= intervalStartTimestamp)
  67. IPsDstPktsCount++;
  68. }
  69. if(IPsDstPktsCount != 0) {
  70. IPsDstPktsCounts.push_back(IPsDstPktsCount);
  71. pktsReceived += IPsDstPktsCount;
  72. }
  73. }
  74. std::cout << "ip src count: " << IPsSrcPktsCounts.size() << std::endl;
  75. std::cout << "pkts sent total: " << pktsSent << std::endl;
  76. for (auto i = IPsSrcPktsCounts.begin(); i != IPsSrcPktsCounts.end(); i++) {
  77. IPsSrcProb.push_back(static_cast<double>(*i) / static_cast<double>(pktsSent));
  78. }
  79. for (auto i = IPsDstPktsCounts.begin(); i != IPsDstPktsCounts.end(); i++) {
  80. IPsDstProb.push_back(static_cast<double>(*i) / static_cast<double>(pktsReceived));
  81. }
  82. // Calculate IP source entropy
  83. double IPsSrcEntropy = 0;
  84. for (unsigned i = 0; i < IPsSrcProb.size(); i++) {
  85. if (IPsSrcProb[i] > 0)
  86. IPsSrcEntropy += -IPsSrcProb[i] * log2(IPsSrcProb[i]);
  87. }
  88. // Calculate IP destination entropy
  89. double IPsDstEntropy = 0;
  90. for (unsigned i = 0; i < IPsDstProb.size(); i++) {
  91. if (IPsDstProb[i] > 0)
  92. IPsDstEntropy += -IPsDstProb[i] * log2(IPsDstProb[i]);
  93. }
  94. // FIXME: return doubles not floats
  95. std::vector<float> entropies = {static_cast<float>(IPsSrcEntropy), static_cast<float>(IPsDstEntropy)};
  96. return entropies;
  97. }
  98. else {
  99. return {-1, -1};
  100. }
  101. }
  102. /**
  103. * Calculates the cumulative entropy of the source and destination IPs, i.e., the entropy for packets from the beginning of the pcap file.
  104. * @return a vector: contains the cumulative entropies of source and destination IPs
  105. */
  106. std::vector<float> statistics::calculateIPsCumEntropy(){
  107. if(this->getDoExtraTests()) {
  108. std::vector <std::string> IPs;
  109. std::vector <float> IPsSrcProb;
  110. std::vector <float> IPsDstProb;
  111. for (auto i = ip_statistics.begin(); i != ip_statistics.end(); i++) {
  112. IPs.push_back(i->first);
  113. IPsSrcProb.push_back((float)i->second.pkts_sent/packetCount);
  114. IPsDstProb.push_back((float)i->second.pkts_received/packetCount);
  115. }
  116. // Calculate IP source entropy
  117. float IPsSrcEntropy = 0;
  118. for(unsigned i=0; i < IPsSrcProb.size();i++){
  119. if (IPsSrcProb[i] > 0)
  120. IPsSrcEntropy += - IPsSrcProb[i]*log2(IPsSrcProb[i]);
  121. }
  122. // Calculate IP destination entropy
  123. float IPsDstEntropy = 0;
  124. for(unsigned i=0; i < IPsDstProb.size();i++){
  125. if (IPsDstProb[i] > 0)
  126. IPsDstEntropy += - IPsDstProb[i]*log2(IPsDstProb[i]);
  127. }
  128. std::vector<float> entropies = {IPsSrcEntropy, IPsDstEntropy};
  129. return entropies;
  130. }
  131. else {
  132. return {-1, -1};
  133. }
  134. }
  135. /**
  136. * Calculates sending packet rate for each IP in a time interval. Finds min and max packet rate and adds them to ip_statistics map.
  137. * @param intervalStartTimestamp The timstamp where the interval starts.
  138. */
  139. void statistics::calculateIPIntervalPacketRate(std::chrono::duration<int, std::micro> interval, std::chrono::microseconds intervalStartTimestamp){
  140. for (auto i = ip_statistics.begin(); i != ip_statistics.end(); i++) {
  141. int IPsSrcPktsCount = 0;
  142. for (auto j = i->second.pkts_sent_timestamp.begin(); j != i->second.pkts_sent_timestamp.end(); j++) {
  143. if(*j >= intervalStartTimestamp)
  144. IPsSrcPktsCount++;
  145. }
  146. float interval_pkt_rate = (float) IPsSrcPktsCount * 1000000 / interval.count(); // used 10^6 because interval in microseconds
  147. i->second.interval_pkt_rate.push_back(interval_pkt_rate);
  148. if(interval_pkt_rate > i->second.max_interval_pkt_rate || i->second.max_interval_pkt_rate == 0)
  149. i->second.max_interval_pkt_rate = interval_pkt_rate;
  150. if(interval_pkt_rate < i->second.min_interval_pkt_rate || i->second.min_interval_pkt_rate == 0)
  151. i->second.min_interval_pkt_rate = interval_pkt_rate;
  152. }
  153. }
  154. /**
  155. * Registers statistical data for a time interval.
  156. * @param intervalStartTimestamp The timstamp where the interval starts.
  157. * @param intervalEndTimestamp The timstamp where the interval ends.
  158. * @param previousPacketCount The total number of packets in last interval.
  159. */
  160. void statistics::addIntervalStat(std::chrono::duration<int, std::micro> interval, std::chrono::microseconds intervalStartTimestamp, std::chrono::microseconds intervalEndTimestamp){
  161. // Add packet rate for each IP to ip_statistics map
  162. calculateIPIntervalPacketRate(interval, intervalStartTimestamp);
  163. std::vector<float> ipEntopies = calculateLastIntervalIPsEntropy(intervalStartTimestamp);
  164. std::vector<float> ipCumEntopies = calculateIPsCumEntropy();
  165. std::string lastPktTimestamp_s = std::to_string(intervalEndTimestamp.count());
  166. std::string intervalStartTimestamp_s = std::to_string(intervalStartTimestamp.count());
  167. // The intervalStartTimestamp_s is the previous interval lastPktTimestamp_s
  168. // TODO: check with carlos if first and last packet timestamps are alright
  169. interval_statistics[lastPktTimestamp_s].start = std::to_string(intervalStartTimestamp.count());
  170. interval_statistics[lastPktTimestamp_s].end = std::to_string(intervalEndTimestamp.count());
  171. interval_statistics[lastPktTimestamp_s].pkts_count = packetCount - intervalCumPktCount;
  172. interval_statistics[lastPktTimestamp_s].pkt_rate = static_cast<float>(interval_statistics[lastPktTimestamp_s].pkts_count) / (static_cast<double>(interval.count()) / 1000000);
  173. interval_statistics[lastPktTimestamp_s].kbytes = static_cast<float>(sumPacketSize - intervalCumSumPktSize) / 1024;
  174. interval_statistics[lastPktTimestamp_s].kbyte_rate = interval_statistics[lastPktTimestamp_s].kbytes / (static_cast<double>(interval.count()) / 1000000);
  175. interval_statistics[lastPktTimestamp_s].payload_count = payloadCount - intervalPayloadCount;
  176. interval_statistics[lastPktTimestamp_s].incorrect_tcp_checksum_count = incorrectTCPChecksumCount - intervalIncorrectTCPChecksumCount;
  177. interval_statistics[lastPktTimestamp_s].correct_tcp_checksum_count = correctTCPChecksumCount - intervalCorrectTCPChecksumCount;
  178. interval_statistics[lastPktTimestamp_s].novel_ip_count = ip_statistics.size() - intervalCumNovelIPCount;
  179. interval_statistics[lastPktTimestamp_s].novel_ttl_count = ttl_values.size() - intervalCumNovelTTLCount;
  180. interval_statistics[lastPktTimestamp_s].novel_win_size_count = win_values.size() - intervalCumNovelWinSizeCount;
  181. interval_statistics[lastPktTimestamp_s].novel_tos_count = tos_values.size() - intervalCumNovelToSCount;
  182. interval_statistics[lastPktTimestamp_s].novel_mss_count = mss_values.size() - intervalCumNovelMSSCount;
  183. interval_statistics[lastPktTimestamp_s].novel_port_count = port_values.size() - intervalCumNovelPortCount;
  184. intervalPayloadCount = payloadCount;
  185. intervalIncorrectTCPChecksumCount = incorrectTCPChecksumCount;
  186. intervalCorrectTCPChecksumCount = correctTCPChecksumCount;
  187. intervalCumPktCount = packetCount;
  188. intervalCumSumPktSize = sumPacketSize;
  189. intervalCumNovelIPCount = ip_statistics.size();
  190. intervalCumNovelTTLCount = ttl_values.size();
  191. intervalCumNovelWinSizeCount = win_values.size();
  192. intervalCumNovelToSCount = tos_values.size();
  193. intervalCumNovelMSSCount = mss_values.size();
  194. intervalCumNovelPortCount = port_values.size();
  195. if(ipEntopies.size()>1){
  196. interval_statistics[lastPktTimestamp_s].ip_src_entropy = ipEntopies[0];
  197. interval_statistics[lastPktTimestamp_s].ip_dst_entropy = ipEntopies[1];
  198. }
  199. if(ipCumEntopies.size()>1){
  200. interval_statistics[lastPktTimestamp_s].ip_src_cum_entropy = ipCumEntopies[0];
  201. interval_statistics[lastPktTimestamp_s].ip_dst_cum_entropy = ipCumEntopies[1];
  202. }
  203. }
  204. /**
  205. * Registers statistical data for a sent packet in a given conversation (two IPs, two ports).
  206. * Increments the counter packets_A_B or packets_B_A.
  207. * Adds the timestamp of the packet in pkts_A_B_timestamp or pkts_B_A_timestamp.
  208. * @param ipAddressSender The sender IP address.
  209. * @param sport The source port.
  210. * @param ipAddressReceiver The receiver IP address.
  211. * @param dport The destination port.
  212. * @param timestamp The timestamp of the packet.
  213. */
  214. void statistics::addConvStat(const std::string &ipAddressSender,int sport,const std::string &ipAddressReceiver,int dport, std::chrono::microseconds timestamp){
  215. conv f1 = {ipAddressReceiver, dport, ipAddressSender, sport};
  216. conv f2 = {ipAddressSender, sport, ipAddressReceiver, dport};
  217. // if already exist A(ipAddressReceiver, dport), B(ipAddressSender, sport) conversation
  218. if (conv_statistics.count(f1)>0){
  219. conv_statistics[f1].pkts_count++;
  220. if(conv_statistics[f1].pkts_count<=3)
  221. conv_statistics[f1].interarrival_time.push_back(std::chrono::duration_cast<std::chrono::microseconds> (timestamp - conv_statistics[f1].pkts_timestamp.back()));
  222. conv_statistics[f1].pkts_timestamp.push_back(timestamp);
  223. }
  224. // Add new conversation A(ipAddressSender, sport), B(ipAddressReceiver, dport)
  225. else{
  226. conv_statistics[f2].pkts_count++;
  227. if(conv_statistics[f2].pkts_timestamp.size()>0 && conv_statistics[f2].pkts_count<=3 )
  228. conv_statistics[f2].interarrival_time.push_back(std::chrono::duration_cast<std::chrono::microseconds> (timestamp - conv_statistics[f2].pkts_timestamp.back()));
  229. conv_statistics[f2].pkts_timestamp.push_back(timestamp);
  230. }
  231. }
  232. /**
  233. * Registers statistical data for a sent packet in a given extended conversation (two IPs, two ports, protocol).
  234. * Increments the counter packets_A_B or packets_B_A.
  235. * Adds the timestamp of the packet in pkts_A_B_timestamp or pkts_B_A_timestamp.
  236. * Updates all other statistics of conv_statistics_extended
  237. * @param ipAddressSender The sender IP address.
  238. * @param sport The source port.
  239. * @param ipAddressReceiver The receiver IP address.
  240. * @param dport The destination port.
  241. * @param protocol The used protocol.
  242. * @param timestamp The timestamp of the packet.
  243. */
  244. void statistics::addConvStatExt(const std::string &ipAddressSender,int sport,const std::string &ipAddressReceiver,int dport,const std::string &protocol, std::chrono::microseconds timestamp){
  245. if(this->getDoExtraTests()) {
  246. convWithProt f1 = {ipAddressReceiver, dport, ipAddressSender, sport, protocol};
  247. convWithProt f2 = {ipAddressSender, sport, ipAddressReceiver, dport, protocol};
  248. convWithProt f;
  249. // if there already exists a communication interval for the specified conversation
  250. if (conv_statistics_extended.count(f1) > 0 || conv_statistics_extended.count(f2) > 0){
  251. // find out which direction of conversation is contained in conv_statistics_extended
  252. if (conv_statistics_extended.count(f1) > 0)
  253. f = f1;
  254. else
  255. f = f2;
  256. // increase pkts count and check on delay
  257. conv_statistics_extended[f].pkts_count++;
  258. if (conv_statistics_extended[f].pkts_timestamp.size()>0 && conv_statistics_extended[f].pkts_count<=3)
  259. conv_statistics_extended[f].interarrival_time.push_back(std::chrono::duration_cast<std::chrono::microseconds> (timestamp - conv_statistics_extended[f].pkts_timestamp.back()));
  260. conv_statistics_extended[f].pkts_timestamp.push_back(timestamp);
  261. // if the time difference has exceeded the threshold, create a new interval with this message
  262. if (timestamp - conv_statistics_extended[f].comm_intervals.back().end > (std::chrono::microseconds) ((unsigned long) COMM_INTERVAL_THRESHOLD)) { // > or >= ?
  263. commInterval new_interval = {timestamp, timestamp, 1};
  264. conv_statistics_extended[f].comm_intervals.push_back(new_interval);
  265. }
  266. // otherwise, set the time of the last interval message to the current timestamp and increase interval packet count by 1
  267. else{
  268. conv_statistics_extended[f].comm_intervals.back().end = timestamp;
  269. conv_statistics_extended[f].comm_intervals.back().pkts_count++;
  270. }
  271. }
  272. // if there does not exist a communication interval for the specified conversation
  273. else{
  274. // add initial interval entry for this conversation
  275. commInterval initial_interval = {timestamp, timestamp, 1};
  276. entry_convStatExt entry;
  277. entry.comm_intervals.push_back(initial_interval);
  278. entry.pkts_count = 1;
  279. entry.pkts_timestamp.push_back(timestamp);
  280. conv_statistics_extended[f2] = entry;
  281. }
  282. }
  283. }
  284. /**
  285. * Aggregate the collected information about all communication intervals within conv_statistics_extended of every conversation.
  286. * Do this by computing the average packet rate per interval and the average time between intervals.
  287. * Also compute average interval duration and total communication duration (i.e. last_msg.time - first_msg.time)
  288. */
  289. void statistics::createCommIntervalStats(){
  290. // iterate over all <convWithProt, entry_convStatExt> pairs
  291. for (auto &cur_elem : conv_statistics_extended) {
  292. entry_convStatExt &entry = cur_elem.second;
  293. std::vector<commInterval> &intervals = entry.comm_intervals;
  294. // if there is only one interval, the time between intervals cannot be computed and is therefore set to 0
  295. if (intervals.size() == 1){
  296. double interval_duration = (double) (intervals[0].end - intervals[0].start).count() / (double) 1e6;
  297. entry.avg_int_pkts_count = (double) intervals[0].pkts_count;
  298. entry.avg_time_between_ints = (double) 0;
  299. entry.avg_interval_time = interval_duration;
  300. }
  301. // If there is more than one interval, compute the specified averages
  302. else if (intervals.size() > 1){
  303. long summed_pkts_count = intervals[0].pkts_count;
  304. std::chrono::microseconds time_between_ints_sum = (std::chrono::microseconds) 0;
  305. std::chrono::microseconds summed_int_duration = intervals[0].end - intervals[0].start;
  306. for (std::size_t i = 1; i < intervals.size(); i++) {
  307. summed_pkts_count += intervals[i].pkts_count;
  308. summed_int_duration += intervals[i].end - intervals[i].start;
  309. time_between_ints_sum += intervals[i].start - intervals[i - 1].end;
  310. }
  311. entry.avg_int_pkts_count = summed_pkts_count / ((double) intervals.size());
  312. entry.avg_time_between_ints = (time_between_ints_sum.count() / (double) (intervals.size() - 1)) / (double) 1e6;
  313. entry.avg_interval_time = (summed_int_duration.count() / (double) intervals.size()) / (double) 1e6;
  314. }
  315. entry.total_comm_duration = (double) (entry.pkts_timestamp.back() - entry.pkts_timestamp.front()).count() / (double) 1e6;
  316. }
  317. }
  318. /**
  319. * Increments the packet counter for the given IP address and MSS value.
  320. * @param ipAddress The IP address whose MSS packet counter should be incremented.
  321. * @param mssValue The MSS value of the packet.
  322. */
  323. void statistics::incrementMSScount(const std::string &ipAddress, int mssValue) {
  324. mss_values[mssValue]++;
  325. mss_distribution[{ipAddress, mssValue}]++;
  326. }
  327. /**
  328. * Increments the packet counter for the given IP address and window size.
  329. * @param ipAddress The IP address whose window size packet counter should be incremented.
  330. * @param winSize The window size of the packet.
  331. */
  332. void statistics::incrementWinCount(const std::string &ipAddress, int winSize) {
  333. win_values[winSize]++;
  334. win_distribution[{ipAddress, winSize}]++;
  335. }
  336. /**
  337. * Increments the packet counter for the given IP address and TTL value.
  338. * @param ipAddress The IP address whose TTL packet counter should be incremented.
  339. * @param ttlValue The TTL value of the packet.
  340. */
  341. void statistics::incrementTTLcount(const std::string &ipAddress, int ttlValue) {
  342. ttl_values[ttlValue]++;
  343. ttl_distribution[{ipAddress, ttlValue}]++;
  344. }
  345. /**
  346. * Increments the packet counter for the given IP address and ToS value.
  347. * @param ipAddress The IP address whose ToS packet counter should be incremented.
  348. * @param tosValue The ToS value of the packet.
  349. */
  350. void statistics::incrementToScount(const std::string &ipAddress, int tosValue) {
  351. tos_values[tosValue]++;
  352. tos_distribution[{ipAddress, tosValue}]++;
  353. }
  354. /**
  355. * Increments the protocol counter for the given IP address and protocol.
  356. * @param ipAddress The IP address whose protocol packet counter should be incremented.
  357. * @param protocol The protocol of the packet.
  358. */
  359. void statistics::incrementProtocolCount(const std::string &ipAddress, const std::string &protocol) {
  360. protocol_distribution[{ipAddress, protocol}].count++;
  361. }
  362. /**
  363. * Returns the number of packets seen for the given IP address and protocol.
  364. * @param ipAddress The IP address whose packet count is wanted.
  365. * @param protocol The protocol whose packet count is wanted.
  366. */
  367. int statistics::getProtocolCount(const std::string &ipAddress, const std::string &protocol) {
  368. return protocol_distribution[{ipAddress, protocol}].count;
  369. }
  370. /**
  371. * Increases the byte counter for the given IP address and protocol.
  372. * @param ipAddress The IP address whose protocol byte counter should be increased.
  373. * @param protocol The protocol of the packet.
  374. * @param byteSent The packet's size.
  375. */
  376. void statistics::increaseProtocolByteCount(const std::string &ipAddress, const std::string &protocol, long bytesSent) {
  377. protocol_distribution[{ipAddress, protocol}].byteCount += bytesSent;
  378. }
  379. /**
  380. * Returns the number of bytes seen for the given IP address and protocol.
  381. * @param ipAddress The IP address whose byte count is wanted.
  382. * @param protocol The protocol whose byte count is wanted.
  383. * @return a float: The number of bytes
  384. */
  385. float statistics::getProtocolByteCount(const std::string &ipAddress, const std::string &protocol) {
  386. return protocol_distribution[{ipAddress, protocol}].byteCount;
  387. }
  388. /**
  389. * Increments the packet counter for
  390. * - the given sender IP address with outgoing port and
  391. * - the given receiver IP address with incoming port.
  392. * @param ipAddressSender The IP address of the packet sender.
  393. * @param outgoingPort The port used by the sender.
  394. * @param ipAddressReceiver The IP address of the packet receiver.
  395. * @param incomingPort The port used by the receiver.
  396. */
  397. void statistics::incrementPortCount(const std::string &ipAddressSender, int outgoingPort, const std::string &ipAddressReceiver,
  398. int incomingPort, const std::string &protocol) {
  399. port_values[outgoingPort]++;
  400. port_values[incomingPort]++;
  401. ip_ports[{ipAddressSender, "out", outgoingPort, protocol}].count++;
  402. ip_ports[{ipAddressReceiver, "in", incomingPort, protocol}].count++;
  403. }
  404. /**
  405. * Increases the packet byte counter for
  406. * - the given sender IP address with outgoing port and
  407. * - the given receiver IP address with incoming port.
  408. * @param ipAddressSender The IP address of the packet sender.
  409. * @param outgoingPort The port used by the sender.
  410. * @param ipAddressReceiver The IP address of the packet receiver.
  411. * @param incomingPort The port used by the receiver.
  412. * @param byteSent The packet's size.
  413. */
  414. void statistics::increasePortByteCount(const std::string &ipAddressSender, int outgoingPort, const std::string &ipAddressReceiver,
  415. int incomingPort, long bytesSent, const std::string &protocol) {
  416. ip_ports[{ipAddressSender, "out", outgoingPort, protocol}].byteCount += bytesSent;
  417. ip_ports[{ipAddressReceiver, "in", incomingPort, protocol}].byteCount += bytesSent;
  418. }
  419. /**
  420. * Increments the packet counter for
  421. * - the given sender MAC address and
  422. * - the given receiver MAC address.
  423. * @param srcMac The MAC address of the packet sender.
  424. * @param dstMac The MAC address of the packet receiver.
  425. * @param typeNumber The payload type number of the packet.
  426. */
  427. void statistics::incrementUnrecognizedPDUCount(const std::string &srcMac, const std::string &dstMac, uint32_t typeNumber,
  428. const std::string &timestamp) {
  429. unrecognized_PDUs[{srcMac, dstMac, typeNumber}].count++;
  430. unrecognized_PDUs[{srcMac, dstMac, typeNumber}].timestamp_last_occurrence = timestamp;
  431. }
  432. /**
  433. * Creates a new statistics object.
  434. */
  435. statistics::statistics(std::string resourcePath) {
  436. this->resourcePath = resourcePath;
  437. }
  438. /**
  439. * Stores the assignment IP address -> MAC address.
  440. * @param ipAddress The IP address belonging to the given MAC address.
  441. * @param macAddress The MAC address belonging to the given IP address.
  442. */
  443. void statistics::assignMacAddress(const std::string &ipAddress, const std::string &macAddress) {
  444. ip_mac_mapping[ipAddress] = macAddress;
  445. }
  446. /**
  447. * Registers statistical data for a sent packet. Increments the counter packets_sent for the sender and
  448. * packets_received for the receiver. Adds the bytes as kbytes_sent (sender) and kybtes_received (receiver).
  449. * @param ipAddressSender The IP address of the packet sender.
  450. * @param ipAddressReceiver The IP address of the packet receiver.
  451. * @param bytesSent The packet's size.
  452. */
  453. void statistics::addIpStat_packetSent(const std::string &ipAddressSender, const std::string &ipAddressReceiver, long bytesSent, std::chrono::microseconds timestamp) {
  454. // Adding IP as a sender for first time
  455. if(ip_statistics[ipAddressSender].pkts_sent==0){
  456. // Add the IP class
  457. ip_statistics[ipAddressSender].ip_class = getIPv4Class(ipAddressSender);
  458. }
  459. // Adding IP as a receiver for first time
  460. if(ip_statistics[ipAddressReceiver].pkts_received==0){
  461. // Add the IP class
  462. ip_statistics[ipAddressReceiver].ip_class = getIPv4Class(ipAddressReceiver);
  463. }
  464. // Update stats for packet sender
  465. ip_statistics[ipAddressSender].kbytes_sent += (float(bytesSent) / 1024);
  466. ip_statistics[ipAddressSender].pkts_sent++;
  467. ip_statistics[ipAddressSender].pkts_sent_timestamp.push_back(timestamp);
  468. // Update stats for packet receiver
  469. ip_statistics[ipAddressReceiver].kbytes_received += (float(bytesSent) / 1024);
  470. ip_statistics[ipAddressReceiver].pkts_received++;
  471. ip_statistics[ipAddressReceiver].pkts_received_timestamp.push_back(timestamp);
  472. if(this->getDoExtraTests()) {
  473. // Increment Degrees for sender and receiver, if Sender sends its first packet to this receiver
  474. std::unordered_set<std::string>::const_iterator found_receiver = contacted_ips[ipAddressSender].find(ipAddressReceiver);
  475. if(found_receiver == contacted_ips[ipAddressSender].end()){
  476. // Receiver is NOT contained in the List of IPs, that the Sender has contacted, therefore this is the first packet in this direction
  477. ip_statistics[ipAddressSender].out_degree++;
  478. ip_statistics[ipAddressReceiver].in_degree++;
  479. // Increment overall_degree only if this is the first packet for the connection (both directions)
  480. // Therefore check, whether Receiver has contacted Sender before
  481. std::unordered_set<std::string>::const_iterator sender_contacted = contacted_ips[ipAddressReceiver].find(ipAddressSender);
  482. if(sender_contacted == contacted_ips[ipAddressReceiver].end()){
  483. ip_statistics[ipAddressSender].overall_degree++;
  484. ip_statistics[ipAddressReceiver].overall_degree++;
  485. }
  486. contacted_ips[ipAddressSender].insert(ipAddressReceiver);
  487. }
  488. }
  489. }
  490. /**
  491. * Setter for the timestamp_firstPacket field.
  492. * @param ts The timestamp of the first packet in the PCAP file.
  493. */
  494. void statistics::setTimestampFirstPacket(Tins::Timestamp ts) {
  495. timestamp_firstPacket = ts;
  496. }
  497. /**
  498. * Setter for the timestamp_lastPacket field.
  499. * @param ts The timestamp of the last packet in the PCAP file.
  500. */
  501. void statistics::setTimestampLastPacket(Tins::Timestamp ts) {
  502. timestamp_lastPacket = ts;
  503. }
  504. /**
  505. * Getter for the timestamp_firstPacket field.
  506. */
  507. Tins::Timestamp statistics::getTimestampFirstPacket() {
  508. return timestamp_firstPacket;
  509. }
  510. /**
  511. * Getter for the timestamp_lastPacket field.
  512. */
  513. Tins::Timestamp statistics::getTimestampLastPacket() {
  514. return timestamp_lastPacket;
  515. }
  516. /**
  517. * Getter for the packetCount field.
  518. */
  519. int statistics::getPacketCount() {
  520. return packetCount;
  521. }
  522. /**
  523. * Getter for the sumPacketSize field.
  524. */
  525. int statistics::getSumPacketSize() {
  526. return sumPacketSize;
  527. }
  528. /**
  529. * Returns the average packet size.
  530. * @return a float indicating the average packet size in kbytes.
  531. */
  532. float statistics::getAvgPacketSize() const {
  533. // AvgPktSize = (Sum of all packet sizes / #Packets)
  534. return (sumPacketSize / packetCount) / 1024;
  535. }
  536. /**
  537. * Adds the size of a packet (to be used to calculate the avg. packet size).
  538. * @param packetSize The size of the current packet in bytes.
  539. */
  540. void statistics::addPacketSize(uint32_t packetSize) {
  541. sumPacketSize += ((float) packetSize);
  542. }
  543. /**
  544. * Setter for the doExtraTests field.
  545. */
  546. void statistics::setDoExtraTests(bool var) {
  547. doExtraTests = var;
  548. }
  549. /**
  550. * Getter for the doExtraTests field.
  551. */
  552. bool statistics::getDoExtraTests() {
  553. return doExtraTests;
  554. }
  555. /**
  556. * Calculates the capture duration.
  557. * @return a formatted string HH:MM:SS.mmmmmm with
  558. * HH: hour, MM: minute, SS: second, mmmmmm: microseconds
  559. */
  560. std::string statistics::getCaptureDurationTimestamp() const {
  561. // Calculate duration
  562. timeval fp, lp, d;
  563. fp.tv_sec = timestamp_firstPacket.seconds();
  564. fp.tv_usec = timestamp_firstPacket.microseconds();
  565. lp.tv_sec = timestamp_lastPacket.seconds();
  566. lp.tv_usec = timestamp_lastPacket.microseconds();
  567. timersub(&lp, &fp, &d);
  568. long int hour = d.tv_sec / 3600;
  569. long int remainder = (d.tv_sec - hour * 3600);
  570. long int minute = remainder / 60;
  571. long int second = (remainder - minute * 60) % 60;
  572. long int microseconds = d.tv_usec;
  573. // Build desired output format: YYYY-mm-dd hh:mm:ss
  574. char out[64];
  575. sprintf(out, "%02ld:%02ld:%02ld.%06ld ", hour, minute, second, microseconds);
  576. return std::string(out);
  577. }
  578. /**
  579. * Calculates the capture duration.
  580. * @return a formatted string SS.mmmmmm with
  581. * S: seconds (UNIX time), mmmmmm: microseconds
  582. */
  583. float statistics::getCaptureDurationSeconds() const {
  584. timeval fp, lp, d;
  585. fp.tv_sec = timestamp_firstPacket.seconds();
  586. fp.tv_usec = timestamp_firstPacket.microseconds();
  587. lp.tv_sec = timestamp_lastPacket.seconds();
  588. lp.tv_usec = timestamp_lastPacket.microseconds();
  589. timersub(&lp, &fp, &d);
  590. char buf[64];
  591. snprintf(buf, sizeof(buf), "%u.%06u", static_cast<uint>(d.tv_sec), static_cast<uint>(d.tv_usec));
  592. return std::stof(std::string(buf));
  593. }
  594. /**
  595. * Creates a timestamp based on a time_t seconds (UNIX time format) and microseconds.
  596. * @param seconds
  597. * @param microseconds
  598. * @return a formatted string Y-m-d H:M:S.m with
  599. * Y: year, m: month, d: day, H: hour, M: minute, S: second, m: microseconds
  600. */
  601. std::string statistics::getFormattedTimestamp(time_t seconds, suseconds_t microseconds) const {
  602. timeval tv;
  603. tv.tv_sec = seconds;
  604. tv.tv_usec = microseconds;
  605. char tmbuf[20], buf[64];
  606. auto nowtm = gmtime(&(tv.tv_sec));
  607. strftime(tmbuf, sizeof(tmbuf), "%Y-%m-%d %H:%M:%S", nowtm);
  608. snprintf(buf, sizeof(buf), "%s.%06u", tmbuf, static_cast<uint>(tv.tv_usec));
  609. return std::string(buf);
  610. }
  611. /**
  612. * Calculates the statistics for a given IP address.
  613. * @param ipAddress The IP address whose statistics should be calculated.
  614. * @return a ip_stats struct containing statistical data derived by the statistical data collected.
  615. */
  616. ip_stats statistics::getStatsForIP(const std::string &ipAddress) {
  617. float duration = getCaptureDurationSeconds();
  618. entry_ipStat ipStatEntry = ip_statistics[ipAddress];
  619. ip_stats s;
  620. s.bandwidthKBitsIn = (ipStatEntry.kbytes_received / duration) * 8;
  621. s.bandwidthKBitsOut = (ipStatEntry.kbytes_sent / duration) * 8;
  622. s.packetPerSecondIn = (ipStatEntry.pkts_received / duration);
  623. s.packetPerSecondOut = (ipStatEntry.pkts_sent / duration);
  624. s.AvgPacketSizeSent = (ipStatEntry.kbytes_sent / ipStatEntry.pkts_sent);
  625. s.AvgPacketSizeRecv = (ipStatEntry.kbytes_received / ipStatEntry.pkts_received);
  626. return s;
  627. }
  628. int statistics::getDefaultInterval() {
  629. return this->default_interval;
  630. }
  631. void statistics::setDefaultInterval(int interval) {
  632. this->default_interval = interval;
  633. }
  634. /**
  635. * Increments the packet counter.
  636. */
  637. void statistics::incrementPacketCount() {
  638. packetCount++;
  639. }
  640. /**
  641. * Prints the statistics of the PCAP and IP specific statistics for the given IP address.
  642. * @param ipAddress The IP address whose statistics should be printed. Can be empty "" to print only general file statistics.
  643. */
  644. void statistics::printStats(const std::string &ipAddress) {
  645. std::stringstream ss;
  646. ss << std::endl;
  647. ss << "Capture duration: " << getCaptureDurationSeconds() << " seconds" << std::endl;
  648. ss << "Capture duration (HH:MM:SS.mmmmmm): " << getCaptureDurationTimestamp() << std::endl;
  649. ss << "#Packets: " << packetCount << std::endl;
  650. ss << std::endl;
  651. // Print IP address specific statistics only if IP address was given
  652. if (ipAddress != "") {
  653. entry_ipStat e = ip_statistics[ipAddress];
  654. ss << "\n----- STATS FOR IP ADDRESS [" << ipAddress << "] -------" << std::endl;
  655. ss << std::endl << "KBytes sent: " << e.kbytes_sent << std::endl;
  656. ss << "KBytes received: " << e.kbytes_received << std::endl;
  657. ss << "Packets sent: " << e.pkts_sent << std::endl;
  658. ss << "Packets received: " << e.pkts_received << "\n\n";
  659. ip_stats is = getStatsForIP(ipAddress);
  660. ss << "Bandwidth IN: " << is.bandwidthKBitsIn << " kbit/s" << std::endl;
  661. ss << "Bandwidth OUT: " << is.bandwidthKBitsOut << " kbit/s" << std::endl;
  662. ss << "Packets per second IN: " << is.packetPerSecondIn << std::endl;
  663. ss << "Packets per second OUT: " << is.packetPerSecondOut << std::endl;
  664. ss << "Avg Packet Size Sent: " << is.AvgPacketSizeSent << " kbytes" << std::endl;
  665. ss << "Avg Packet Size Received: " << is.AvgPacketSizeRecv << " kbytes" << std::endl;
  666. }
  667. std::cout << ss.str();
  668. }
  669. /**
  670. * Derives general PCAP file statistics from the collected statistical data and
  671. * writes all data into a SQLite database, located at database_path.
  672. * @param database_path The path of the SQLite database file ending with .sqlite3.
  673. */
  674. void statistics::writeToDatabase(std::string database_path, std::vector<std::chrono::duration<int, std::micro>> timeIntervals, bool del) {
  675. // Generate general file statistics
  676. float duration = getCaptureDurationSeconds();
  677. long sumPacketsSent = 0, senderCountIP = 0;
  678. float sumBandwidthIn = 0.0, sumBandwidthOut = 0.0;
  679. for (auto i = ip_statistics.begin(); i != ip_statistics.end(); i++) {
  680. sumPacketsSent += i->second.pkts_sent;
  681. // Consumed bandwith (bytes) for sending packets
  682. sumBandwidthIn += (i->second.kbytes_received / duration);
  683. sumBandwidthOut += (i->second.kbytes_sent / duration);
  684. senderCountIP++;
  685. }
  686. float avgPacketRate = (packetCount / duration);
  687. long avgPacketSize = getAvgPacketSize();
  688. if(senderCountIP>0) {
  689. long avgPacketsSentPerHost = (sumPacketsSent / senderCountIP);
  690. float avgBandwidthInKBits = (sumBandwidthIn / senderCountIP) * 8;
  691. float avgBandwidthOutInKBits = (sumBandwidthOut / senderCountIP) * 8;
  692. // Create database and write information
  693. statistics_db db(database_path, resourcePath);
  694. db.writeStatisticsFile(packetCount, getCaptureDurationSeconds(),
  695. getFormattedTimestamp(timestamp_firstPacket.seconds(), timestamp_firstPacket.microseconds()),
  696. getFormattedTimestamp(timestamp_lastPacket.seconds(), timestamp_lastPacket.microseconds()),
  697. avgPacketRate, avgPacketSize, avgPacketsSentPerHost, avgBandwidthInKBits,
  698. avgBandwidthOutInKBits, doExtraTests);
  699. db.writeStatisticsIP(ip_statistics);
  700. db.writeStatisticsTTL(ttl_distribution);
  701. db.writeStatisticsIpMac(ip_mac_mapping);
  702. db.writeStatisticsDegree(ip_statistics);
  703. db.writeStatisticsPorts(ip_ports);
  704. db.writeStatisticsProtocols(protocol_distribution);
  705. db.writeStatisticsMSS(mss_distribution);
  706. db.writeStatisticsToS(tos_distribution);
  707. db.writeStatisticsWin(win_distribution);
  708. db.writeStatisticsConv(conv_statistics);
  709. db.writeStatisticsConvExt(conv_statistics_extended);
  710. db.writeStatisticsInterval(interval_statistics, timeIntervals, del, this->default_interval);
  711. db.writeDbVersion();
  712. db.writeStatisticsUnrecognizedPDUs(unrecognized_PDUs);
  713. }
  714. else {
  715. // Tinslib failed to recognize the types of the packets in the input PCAP
  716. std::cerr<<"ERROR: Statistics could not be collected from the input PCAP!"<<"\n";
  717. return;
  718. }
  719. }
  720. void statistics::writeIntervalsToDatabase(std::string database_path, std::vector<std::chrono::duration<int, std::micro>> timeIntervals, bool del) {
  721. statistics_db db(database_path, resourcePath);
  722. db.writeStatisticsInterval(interval_statistics, timeIntervals, del, this->default_interval);
  723. }