statistics.cpp 40 KB

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