Statistics.py 74 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686
  1. import os
  2. import random
  3. import time
  4. import numpy
  5. from math import sqrt, ceil, log
  6. from operator import itemgetter
  7. # TODO: double check this import
  8. # does it complain because libpcapreader is not a .py?
  9. import ID2TLib.libpcapreader as pr
  10. import Core.StatsDatabase as statsDB
  11. import ID2TLib.PcapFile as PcapFile
  12. import ID2TLib.Utility as Util
  13. from ID2TLib.IPv4 import IPAddress
  14. import matplotlib.pyplot as plt
  15. class Statistics:
  16. def __init__(self, pcap_file: PcapFile.PcapFile):
  17. """
  18. Creates a new Statistics object.
  19. :param pcap_file: A reference to the PcapFile object
  20. """
  21. # Fields
  22. self.pcap_filepath = pcap_file.pcap_file_path
  23. self.pcap_proc = None
  24. self.do_extra_tests = False
  25. self.file_info = None
  26. # Create folder for statistics database if required
  27. self.path_db = pcap_file.get_db_path()
  28. path_dir = os.path.dirname(self.path_db)
  29. if not os.path.isdir(path_dir):
  30. os.makedirs(path_dir)
  31. # Class instances
  32. self.stats_db = statsDB.StatsDatabase(self.path_db)
  33. def load_pcap_statistics(self, flag_write_file: bool, flag_recalculate_stats: bool, flag_print_statistics: bool,
  34. flag_non_verbose: bool):
  35. """
  36. Loads the PCAP statistics for the file specified by pcap_filepath. If the database is not existing yet, the
  37. statistics are calculated by the PCAP file processor and saved into the newly created database. Otherwise the
  38. statistics are gathered directly from the existing database.
  39. :param flag_write_file: Indicates whether the statistics should be written additionally into a text file (True)
  40. or not (False)
  41. :param flag_recalculate_stats: Indicates whether eventually existing statistics should be recalculated
  42. :param flag_print_statistics: Indicates whether the gathered basic statistics should be printed to the terminal
  43. :param flag_non_verbose: Indicates whether certain prints should be made or not, to reduce terminal clutter
  44. """
  45. # Load pcap and get loading time
  46. time_start = time.clock()
  47. # Inform user about recalculation of statistics and its reason
  48. if flag_recalculate_stats:
  49. print("Flag -r/--recalculate found. Recalculating statistics.")
  50. # Recalculate statistics if database does not exist OR param -r/--recalculate is provided
  51. if (not self.stats_db.get_db_exists()) or flag_recalculate_stats or self.stats_db.get_db_outdated():
  52. self.pcap_proc = pr.pcap_processor(self.pcap_filepath, str(self.do_extra_tests))
  53. self.pcap_proc.collect_statistics()
  54. self.pcap_proc.write_to_database(self.path_db)
  55. outstring_datasource = "by PCAP file processor."
  56. # only print summary of new db if -s flag not set
  57. if not flag_print_statistics and not flag_non_verbose:
  58. self.stats_summary_new_db()
  59. else:
  60. outstring_datasource = "from statistics database."
  61. # Load statistics from database
  62. self.file_info = self.stats_db.get_file_info()
  63. time_end = time.clock()
  64. print("Loaded file statistics in " + str(time_end - time_start)[:4] + " sec " + outstring_datasource)
  65. # Write statistics if param -e/--export provided
  66. if flag_write_file:
  67. self.write_statistics_to_file()
  68. # Print statistics if param -s/--statistics provided
  69. if flag_print_statistics:
  70. self.print_statistics()
  71. def get_file_information(self):
  72. """
  73. Returns a list of tuples, each containing a information of the file.
  74. :return: a list of tuples, each consisting of (description, value, unit), where unit is optional.
  75. """
  76. pdu_count = self.process_db_query("SELECT SUM(pktCount) FROM unrecognized_pdus")
  77. pdu_share = pdu_count / self.get_packet_count() * 100
  78. last_pdu_timestamp = self.process_db_query(
  79. "SELECT MAX(timestampLastOccurrence) FROM unrecognized_pdus")
  80. return [("Pcap file path", self.pcap_filepath),
  81. ("Total packet count", self.get_packet_count(), "packets"),
  82. ("Recognized packets", self.get_packet_count() - pdu_count, "packets"),
  83. ("Unrecognized packets", pdu_count, "PDUs"),
  84. ("% Recognized packets", 100 - pdu_share, "%"),
  85. ("% Unrecognized packets", pdu_share, "%"),
  86. ("Last unknown PDU", last_pdu_timestamp),
  87. ("Capture duration", self.get_capture_duration(), "seconds"),
  88. ("Capture start", "\t" + str(self.get_pcap_timestamp_start())),
  89. ("Capture end", "\t" + str(self.get_pcap_timestamp_end()))]
  90. def get_general_file_statistics(self):
  91. """
  92. Returns a list of tuples, each containing a file statistic.
  93. :return: a list of tuples, each consisting of (description, value, unit).
  94. """
  95. return [("Avg. packet rate", self.file_info['avgPacketRate'], "packets/sec"),
  96. ("Avg. packet size", self.file_info['avgPacketSize'], "kbytes"),
  97. ("Avg. packets sent", self.file_info['avgPacketsSentPerHost'], "packets"),
  98. ("Avg. bandwidth in", self.file_info['avgBandwidthIn'], "kbit/s"),
  99. ("Avg. bandwidth out", self.file_info['avgBandwidthOut'], "kbit/s")]
  100. @staticmethod
  101. def write_list(desc_val_unit_list, func, line_ending="\n"):
  102. """
  103. Takes a list of tuples (statistic name, statistic value, unit) as input, generates a string of these three
  104. values and applies the function func on this string.
  105. Before generating the string, it identifies text containing a float number, casts the string to a
  106. float and rounds the value to two decimal digits.
  107. :param desc_val_unit_list: The list of tuples consisting of (description, value, unit)
  108. :param func: The function to be applied to each generated string
  109. :param line_ending: The formatting string to be applied at the end of each string
  110. """
  111. for entry in desc_val_unit_list:
  112. # Convert text containing float into float
  113. (description, value) = entry[0:2]
  114. if isinstance(value, str) and "." in value:
  115. try:
  116. value = float(value)
  117. except ValueError:
  118. pass # do nothing -> value was not a float
  119. # round float
  120. if isinstance(value, float):
  121. value = round(value, 4)
  122. # write into file
  123. if len(entry) == 3:
  124. unit = entry[2]
  125. func(description + ":\t" + str(value) + " " + unit + line_ending)
  126. else:
  127. func(description + ":\t" + str(value) + line_ending)
  128. def print_statistics(self):
  129. """
  130. Prints the basic file statistics to the terminal.
  131. """
  132. print("\nPCAP FILE INFORMATION ------------------------------")
  133. Statistics.write_list(self.get_file_information(), print, "")
  134. print("\nGENERAL FILE STATISTICS ----------------------------")
  135. Statistics.write_list(self.get_general_file_statistics(), print, "")
  136. print("\n")
  137. @staticmethod
  138. def calculate_entropy(frequency: list, normalized: bool = False):
  139. """
  140. Calculates entropy and normalized entropy of list of elements that have specific frequency
  141. :param frequency: The frequency of the elements.
  142. :param normalized: Calculate normalized entropy
  143. :return: entropy or (entropy, normalized entropy)
  144. """
  145. entropy, normalized_ent, n = 0, 0, 0
  146. sum_freq = sum(frequency)
  147. for i, x in enumerate(frequency):
  148. p_x = float(frequency[i] / sum_freq)
  149. if p_x > 0:
  150. n += 1
  151. entropy += - p_x * log(p_x, 2)
  152. if normalized:
  153. if log(n) > 0:
  154. normalized_ent = entropy / log(n, 2)
  155. return entropy, normalized_ent
  156. else:
  157. return entropy
  158. def calculate_complement_packet_rates(self, pps):
  159. """
  160. Calculates the complement packet rates of the background traffic packet rates for each interval.
  161. Then normalize it to maximum boundary, which is the input parameter pps
  162. :return: normalized packet rates for each time interval.
  163. """
  164. result = self.process_db_query(
  165. "SELECT lastPktTimestamp,pktsCount FROM interval_statistics ORDER BY lastPktTimestamp")
  166. # print(result)
  167. bg_interval_pps = []
  168. complement_interval_pps = []
  169. intervals_sum = 0
  170. if result:
  171. # Get the interval in seconds
  172. for i, row in enumerate(result):
  173. if i < len(result) - 1:
  174. intervals_sum += ceil((int(result[i + 1][0]) * 10 ** -6) - (int(row[0]) * 10 ** -6))
  175. interval = intervals_sum / (len(result) - 1)
  176. # Convert timestamp from micro to seconds, convert packet rate "per interval" to "per second"
  177. for row in result:
  178. bg_interval_pps.append((int(row[0]) * 10 ** -6, int(row[1] / interval)))
  179. # Find max PPS
  180. max_pps = max(bg_interval_pps, key=itemgetter(1))[1]
  181. for row in bg_interval_pps:
  182. complement_interval_pps.append((row[0], int(pps * (max_pps - row[1]) / max_pps)))
  183. return complement_interval_pps
  184. def get_tests_statistics(self):
  185. """
  186. Writes the calculated basic defects tests statistics into a file.
  187. """
  188. # self.stats_db.process_user_defined_query output is list of tuples, thus, we ned [0][0] to access data
  189. def count_frequncy(values_list):
  190. """
  191. TODO : FILL ME
  192. :param values_list:
  193. :return:
  194. """
  195. values, freq_output = [], []
  196. for x in values_list:
  197. if x in values:
  198. freq_output[values.index(x)] += 1
  199. else:
  200. values.append(x)
  201. freq_output.append(1)
  202. return values, freq_output
  203. # Payload Tests
  204. sum_payload_count = self.stats_db.process_user_defined_query("SELECT sum(payloadCount) FROM "
  205. "interval_statistics")
  206. pkt_count = self.stats_db.process_user_defined_query("SELECT packetCount FROM file_statistics")
  207. if sum_payload_count and pkt_count:
  208. payload_ratio = 0
  209. if pkt_count[0][0] != 0:
  210. payload_ratio = float(sum_payload_count[0][0] / pkt_count[0][0] * 100)
  211. else:
  212. payload_ratio = -1
  213. # TCP checksum Tests
  214. incorrect_checksum_count = self.stats_db.process_user_defined_query(
  215. "SELECT sum(incorrectTCPChecksumCount) FROM interval_statistics")
  216. correct_checksum_count = self.stats_db.process_user_defined_query(
  217. "SELECT avg(correctTCPChecksumCount) FROM interval_statistics")
  218. if incorrect_checksum_count and correct_checksum_count:
  219. incorrect_checksum_ratio = 0
  220. if (incorrect_checksum_count[0][0] + correct_checksum_count[0][0]) != 0:
  221. incorrect_checksum_ratio = float(incorrect_checksum_count[0][0] /
  222. (incorrect_checksum_count[0][0] + correct_checksum_count[0][0]) * 100)
  223. else:
  224. incorrect_checksum_ratio = -1
  225. # IP Src & Dst Tests
  226. result = self.stats_db.process_user_defined_query("SELECT ipAddress,pktsSent,pktsReceived FROM ip_statistics")
  227. data, src_frequency, dst_frequency = [], [], []
  228. if result:
  229. for row in result:
  230. src_frequency.append(row[1])
  231. dst_frequency.append(row[2])
  232. ip_src_entropy, ip_src_norm_entropy = self.calculate_entropy(src_frequency, True)
  233. ip_dst_entropy, ip_dst_norm_entropy = self.calculate_entropy(dst_frequency, True)
  234. new_ip_count = self.stats_db.process_user_defined_query("SELECT newIPCount FROM interval_statistics")
  235. ip_novels_per_interval, ip_novels_per_interval_frequency = count_frequncy(new_ip_count)
  236. ip_novelty_dist_entropy = self.calculate_entropy(ip_novels_per_interval_frequency)
  237. # Ports Tests
  238. port0_count = self.stats_db.process_user_defined_query(
  239. "SELECT SUM(portCount) FROM ip_ports WHERE portNumber = 0")
  240. if not port0_count[0][0]:
  241. port0_count = 0
  242. else:
  243. port0_count = port0_count[0][0]
  244. # FIXME: could be extended
  245. reserved_port_count = self.stats_db.process_user_defined_query(
  246. "SELECT SUM(portCount) FROM ip_ports WHERE portNumber IN (100,114,1023,1024,49151,49152,65535)")
  247. if not reserved_port_count[0][0]:
  248. reserved_port_count = 0
  249. else:
  250. reserved_port_count = reserved_port_count[0][0]
  251. # TTL Tests
  252. result = self.stats_db.process_user_defined_query(
  253. "SELECT ttlValue,SUM(ttlCount) FROM ip_ttl GROUP BY ttlValue")
  254. data, frequency = [], []
  255. for row in result:
  256. frequency.append(row[1])
  257. ttl_entropy, ttl_norm_entropy = self.calculate_entropy(frequency, True)
  258. new_ttl_count = self.stats_db.process_user_defined_query("SELECT newTTLCount FROM interval_statistics")
  259. ttl_novels_per_interval, ttl_novels_per_interval_frequency = count_frequncy(new_ttl_count)
  260. ttl_novelty_dist_entropy = self.calculate_entropy(ttl_novels_per_interval_frequency)
  261. # Window Size Tests
  262. result = self.stats_db.process_user_defined_query("SELECT winSize,SUM(winCount) FROM tcp_win GROUP BY winSize")
  263. data, frequency = [], []
  264. for row in result:
  265. frequency.append(row[1])
  266. win_entropy, win_norm_entropy = self.calculate_entropy(frequency, True)
  267. new_win_size_count = self.stats_db.process_user_defined_query("SELECT newWinSizeCount FROM interval_statistics")
  268. win_novels_per_interval, win_novels_per_interval_frequency = count_frequncy(new_win_size_count)
  269. win_novelty_dist_entropy = self.calculate_entropy(win_novels_per_interval_frequency)
  270. # ToS Tests
  271. result = self.stats_db.process_user_defined_query(
  272. "SELECT tosValue,SUM(tosCount) FROM ip_tos GROUP BY tosValue")
  273. data, frequency = [], []
  274. for row in result:
  275. frequency.append(row[1])
  276. tos_entropy, tos_norm_entropy = self.calculate_entropy(frequency, True)
  277. new_tos_count = self.stats_db.process_user_defined_query("SELECT newToSCount FROM interval_statistics")
  278. tos_novels_per_interval, tos_novels_per_interval_frequency = count_frequncy(new_tos_count)
  279. tos_novelty_dist_entropy = self.calculate_entropy(tos_novels_per_interval_frequency)
  280. # MSS Tests
  281. result = self.stats_db.process_user_defined_query(
  282. "SELECT mssValue,SUM(mssCount) FROM tcp_mss GROUP BY mssValue")
  283. data, frequency = [], []
  284. for row in result:
  285. frequency.append(row[1])
  286. mss_entropy, mss_norm_entropy = self.calculate_entropy(frequency, True)
  287. new_mss_count = self.stats_db.process_user_defined_query("SELECT newMSSCount FROM interval_statistics")
  288. mss_novels_per_interval, mss_novels_per_interval_frequency = count_frequncy(new_mss_count)
  289. mss_novelty_dist_entropy = self.calculate_entropy(mss_novels_per_interval_frequency)
  290. result = self.stats_db.process_user_defined_query("SELECT SUM(mssCount) FROM tcp_mss WHERE mssValue > 1460")
  291. # The most used MSS < 1460. Calculate the ratio of the values bigger that 1460.
  292. if not result[0][0]:
  293. result = 0
  294. else:
  295. result = result[0][0]
  296. big_mss = (result / sum(frequency)) * 100
  297. output = []
  298. if self.do_extra_tests:
  299. output = [("Payload ratio", payload_ratio, "%"),
  300. ("Incorrect TCP checksum ratio", incorrect_checksum_ratio, "%")]
  301. output = output + [("# IP addresses", sum([x[0] for x in new_ip_count]), ""),
  302. ("IP Src Entropy", ip_src_entropy, ""),
  303. ("IP Src Normalized Entropy", ip_src_norm_entropy, ""),
  304. ("IP Dst Entropy", ip_dst_entropy, ""),
  305. ("IP Dst Normalized Entropy", ip_dst_norm_entropy, ""),
  306. ("IP Novelty Distribution Entropy", ip_novelty_dist_entropy, ""),
  307. ("# TTL values", sum([x[0] for x in new_ttl_count]), ""),
  308. ("TTL Entropy", ttl_entropy, ""),
  309. ("TTL Normalized Entropy", ttl_norm_entropy, ""),
  310. ("TTL Novelty Distribution Entropy", ttl_novelty_dist_entropy, ""),
  311. ("# WinSize values", sum([x[0] for x in new_win_size_count]), ""),
  312. ("WinSize Entropy", win_entropy, ""),
  313. ("WinSize Normalized Entropy", win_norm_entropy, ""),
  314. ("WinSize Novelty Distribution Entropy", win_novelty_dist_entropy, ""),
  315. ("# ToS values", sum([x[0] for x in new_tos_count]), ""),
  316. ("ToS Entropy", tos_entropy, ""),
  317. ("ToS Normalized Entropy", tos_norm_entropy, ""),
  318. ("ToS Novelty Distribution Entropy", tos_novelty_dist_entropy, ""),
  319. ("# MSS values", sum([x[0] for x in new_mss_count]), ""),
  320. ("MSS Entropy", mss_entropy, ""),
  321. ("MSS Normalized Entropy", mss_norm_entropy, ""),
  322. ("MSS Novelty Distribution Entropy", mss_novelty_dist_entropy, ""),
  323. ("======================", "", "")]
  324. # Reasoning the statistics values
  325. if self.do_extra_tests:
  326. if payload_ratio > 80:
  327. output.append(("WARNING: Too high payload ratio", payload_ratio, "%."))
  328. if payload_ratio < 30:
  329. output.append(("WARNING: Too low payload ratio", payload_ratio, "% (Injecting attacks that are carried "
  330. "out in the packet payloads is not "
  331. "recommmanded)."))
  332. if incorrect_checksum_ratio > 5:
  333. output.append(("WARNING: High incorrect TCP checksum ratio", incorrect_checksum_ratio, "%."))
  334. if ip_src_norm_entropy > 0.65:
  335. output.append(("WARNING: High IP source normalized entropy", ip_src_norm_entropy, "."))
  336. if ip_src_norm_entropy < 0.2:
  337. output.append(("WARNING: Low IP source normalized entropy", ip_src_norm_entropy, "."))
  338. if ip_dst_norm_entropy > 0.65:
  339. output.append(("WARNING: High IP destination normalized entropy", ip_dst_norm_entropy, "."))
  340. if ip_dst_norm_entropy < 0.2:
  341. output.append(("WARNING: Low IP destination normalized entropy", ip_dst_norm_entropy, "."))
  342. if ttl_norm_entropy > 0.65:
  343. output.append(("WARNING: High TTL normalized entropy", ttl_norm_entropy, "."))
  344. if ttl_norm_entropy < 0.2:
  345. output.append(("WARNING: Low TTL normalized entropy", ttl_norm_entropy, "."))
  346. if ttl_novelty_dist_entropy < 1:
  347. output.append(("WARNING: Too low TTL novelty distribution entropy", ttl_novelty_dist_entropy,
  348. "(The distribution of the novel TTL values is suspicious)."))
  349. if win_norm_entropy > 0.6:
  350. output.append(("WARNING: High Window Size normalized entropy", win_norm_entropy, "."))
  351. if win_norm_entropy < 0.1:
  352. output.append(("WARNING: Low Window Size normalized entropy", win_norm_entropy, "."))
  353. if win_novelty_dist_entropy < 4:
  354. output.append(("WARNING: Low Window Size novelty distribution entropy", win_novelty_dist_entropy,
  355. "(The distribution of the novel Window Size values is suspicious)."))
  356. if tos_norm_entropy > 0.4:
  357. output.append(("WARNING: High ToS normalized entropy", tos_norm_entropy, "."))
  358. if tos_norm_entropy < 0.1:
  359. output.append(("WARNING: Low ToS normalized entropy", tos_norm_entropy, "."))
  360. if tos_novelty_dist_entropy < 0.5:
  361. output.append(("WARNING: Low ToS novelty distribution entropy", tos_novelty_dist_entropy,
  362. "(The distribution of the novel ToS values is suspicious)."))
  363. if mss_norm_entropy > 0.4:
  364. output.append(("WARNING: High MSS normalized entropy", mss_norm_entropy, "."))
  365. if mss_norm_entropy < 0.1:
  366. output.append(("WARNING: Low MSS normalized entropy", mss_norm_entropy, "."))
  367. if mss_novelty_dist_entropy < 0.5:
  368. output.append(("WARNING: Low MSS novelty distribution entropy", mss_novelty_dist_entropy,
  369. "(The distribution of the novel MSS values is suspicious)."))
  370. if big_mss > 50:
  371. output.append(("WARNING: High ratio of MSS > 1460", big_mss, "% (High fragmentation rate in Ethernet)."))
  372. if port0_count > 0:
  373. output.append(("WARNING: Port number 0 is used in ", port0_count, "packets (awkward-looking port)."))
  374. if reserved_port_count > 0:
  375. output.append(("WARNING: Reserved port numbers are used in ", reserved_port_count,
  376. "packets (uncommonly-used ports)."))
  377. return output
  378. def write_statistics_to_file(self):
  379. """
  380. Writes the calculated basic statistics into a file.
  381. """
  382. def _write_header(title: str):
  383. """
  384. Writes the section header into the open file.
  385. :param title: The section title
  386. """
  387. target.write("====================== \n")
  388. target.write(title + " \n")
  389. target.write("====================== \n")
  390. target = open(self.pcap_filepath + ".stat", 'w')
  391. target.truncate()
  392. _write_header("PCAP file information")
  393. Statistics.write_list(self.get_file_information(), target.write)
  394. _write_header("General statistics")
  395. Statistics.write_list(self.get_general_file_statistics(), target.write)
  396. _write_header("Tests statistics")
  397. Statistics.write_list(self.get_tests_statistics(), target.write)
  398. target.close()
  399. def get_capture_duration(self):
  400. """
  401. :return: The duration of the capture in seconds
  402. """
  403. return self.file_info['captureDuration']
  404. def get_pcap_timestamp_start(self):
  405. """
  406. :return: The timestamp of the first packet in the PCAP file
  407. """
  408. return self.file_info['timestampFirstPacket']
  409. def get_pcap_timestamp_end(self):
  410. """
  411. :return: The timestamp of the last packet in the PCAP file
  412. """
  413. return self.file_info['timestampLastPacket']
  414. def get_pps_sent(self, ip_address: str):
  415. """
  416. Calculates the sent packets per seconds for a given IP address.
  417. :param ip_address: The IP address whose packets per second should be calculated
  418. :return: The sent packets per seconds for the given IP address
  419. """
  420. packets_sent = self.stats_db.process_db_query("SELECT pktsSent from ip_statistics WHERE ipAddress=?", False,
  421. (ip_address,))
  422. capture_duration = float(self.get_capture_duration())
  423. return int(float(packets_sent) / capture_duration)
  424. def get_pps_received(self, ip_address: str):
  425. """
  426. Calculate the packets per second received for a given IP address.
  427. :param ip_address: The IP address used for the calculation
  428. :return: The number of packets per second received
  429. """
  430. packets_received = self.stats_db.process_db_query("SELECT pktsReceived FROM ip_statistics WHERE ipAddress=?",
  431. False,
  432. (ip_address,))
  433. capture_duration = float(self.get_capture_duration())
  434. return int(float(packets_received) / capture_duration)
  435. def get_packet_count(self):
  436. """
  437. :return: The number of packets in the loaded PCAP file
  438. """
  439. return self.file_info['packetCount']
  440. def get_most_used_ip_address(self):
  441. """
  442. :return: The IP address/addresses with the highest sum of packets sent and received
  443. """
  444. return Util.handle_most_used_outputs(self.process_db_query("most_used(ipAddress)"))
  445. def get_ttl_distribution(self, ip_address: str):
  446. """
  447. TODO: FILL ME
  448. :param ip_address:
  449. :return:
  450. """
  451. result = self.process_db_query('SELECT ttlValue, ttlCount from ip_ttl WHERE ipAddress="' + ip_address + '"')
  452. result_dict = {key: value for (key, value) in result}
  453. return result_dict
  454. def get_mss_distribution(self, ip_address: str):
  455. """
  456. TODO: FILL ME
  457. :param ip_address:
  458. :return:
  459. """
  460. result = self.process_db_query('SELECT mssValue, mssCount from tcp_mss WHERE ipAddress="' + ip_address + '"')
  461. result_dict = {key: value for (key, value) in result}
  462. return result_dict
  463. def get_win_distribution(self, ip_address: str):
  464. """
  465. TODO: FILL ME
  466. :param ip_address:
  467. :return:
  468. """
  469. result = self.process_db_query('SELECT winSize, winCount from tcp_win WHERE ipAddress="' + ip_address + '"')
  470. result_dict = {key: value for (key, value) in result}
  471. return result_dict
  472. def get_tos_distribution(self, ip_address: str):
  473. """
  474. TODO: FILL ME
  475. :param ip_address:
  476. :return:
  477. """
  478. result = self.process_db_query('SELECT tosValue, tosCount from ip_tos WHERE ipAddress="' + ip_address + '"')
  479. result_dict = {key: value for (key, value) in result}
  480. return result_dict
  481. def get_ip_address_count(self):
  482. """
  483. TODO: FILL ME
  484. :return:
  485. """
  486. return self.process_db_query("SELECT COUNT(*) FROM ip_statistics")
  487. def get_ip_addresses(self):
  488. """
  489. TODO: FILL ME
  490. :return:
  491. """
  492. return self.process_db_query("SELECT ipAddress FROM ip_statistics")
  493. def get_random_ip_address(self, count: int = 1):
  494. """
  495. :param count: The number of IP addresses to return
  496. :return: A randomly chosen IP address from the dataset or iff param count is greater than one, a list of
  497. randomly chosen IP addresses
  498. """
  499. ip_address_list = self.process_db_query("SELECT ipAddress from ip_statistics ORDER BY ipAddress ASC")
  500. if count == 1:
  501. return random.choice(ip_address_list)
  502. else:
  503. result_list = []
  504. for i in range(0, count):
  505. random_ip = random.choice(ip_address_list)
  506. result_list.append(random_ip)
  507. ip_address_list.remove(random_ip)
  508. return result_list
  509. def get_ip_address_from_mac(self, mac_address: str):
  510. """
  511. :param mac_address: the MAC address of which the IP shall be returned, if existing in DB
  512. :return: the IP address used in the dataset by a given MAC address
  513. """
  514. return self.process_db_query("SELECT DISTINCT ipAddress FROM ip_mac WHERE macAddress = '" + mac_address + "'")
  515. def get_mac_addresses(self, ip_addresses: list):
  516. """
  517. :return: The MAC addresses used in the dataset for the given IP addresses as a dictionary.
  518. """
  519. return dict(self.process_db_query("SELECT DISTINCT ipAddress, macAddress from ip_mac WHERE ipAddress in ("
  520. + str(ip_addresses)[1:-1] + ")"))
  521. def get_mac_address(self, ip_address: str):
  522. """
  523. :return: The MAC address used in the dataset for the given IP address.
  524. """
  525. return self.process_db_query("SELECT DISTINCT macAddress from ip_mac WHERE ipAddress = '" + ip_address + "'")
  526. def get_most_used_ttl_value(self):
  527. """
  528. :return: The most used TTL value.
  529. """
  530. return self.process_db_query("SELECT ttlValue FROM (SELECT ttlValue, SUM(ttlCount) as occ FROM ip_ttl GROUP BY "
  531. "ttlValue) WHERE occ=(SELECT SUM(ttlCount) as occ FROM ip_ttl GROUP BY ttlValue "
  532. "ORDER BY occ DESC LIMIT 1) ORDER BY ttlValue ASC")
  533. def get_most_used_ip_class(self):
  534. """
  535. :return: The most used IP class.
  536. """
  537. return self.process_db_query("SELECT ipClass FROM (SELECT ipClass, COUNT(*) as occ from ip_statistics GROUP BY "
  538. "ipClass ORDER BY occ DESC) WHERE occ=(SELECT COUNT(*) as occ from ip_statistics "
  539. "GROUP BY ipClass ORDER BY occ DESC LIMIT 1) ORDER BY ipClass ASC")
  540. def get_most_used_win_size(self):
  541. """
  542. :return: The most used window size.
  543. """
  544. return self.process_db_query("SELECT winSize FROM (SELECT winSize, SUM(winCount) as occ FROM tcp_win GROUP BY "
  545. "winSize) WHERE occ=(SELECT SUM(winCount) as occ FROM tcp_win GROUP BY winSize "
  546. "ORDER BY occ DESC LIMIT 1) ORDER BY winSize ASC")
  547. def get_most_used_mss_value(self):
  548. """
  549. :return: The most used mss value.
  550. """
  551. return self.process_db_query("SELECT mssValue FROM (SELECT mssValue, SUM(mssCount) as occ FROM tcp_mss GROUP BY"
  552. " mssValue) WHERE occ=(SELECT SUM(mssCount) as occ FROM tcp_mss GROUP BY mssValue "
  553. "ORDER BY occ DESC LIMIT 1) ORDER BY mssValue ASC")
  554. def get_most_used_mss(self, ip_address: str):
  555. """
  556. :param ip_address: The IP address whose used MSS should be determined
  557. :return: The TCP MSS value used by the IP address, or if the IP addresses never specified a MSS,
  558. then None is returned
  559. """
  560. mss_value = self.process_db_query('SELECT mssValue from tcp_mss WHERE ipAddress="' + ip_address +
  561. '" AND mssCount == (SELECT MAX(mssCount) from tcp_mss WHERE ipAddress="'
  562. + ip_address + '")')
  563. if isinstance(mss_value, int):
  564. return mss_value
  565. elif isinstance(mss_value, list):
  566. if len(mss_value) == 0:
  567. return None
  568. else:
  569. mss_value.sort()
  570. return mss_value[0]
  571. else:
  572. return None
  573. def get_most_used_ttl(self, ip_address: str):
  574. """
  575. :param ip_address: The IP address whose used TTL should be determined
  576. :return: The TTL value used by the IP address, or if the IP addresses never specified a TTL,
  577. then None is returned
  578. """
  579. ttl_value = self.process_db_query('SELECT ttlValue from ip_ttl WHERE ipAddress="' + ip_address +
  580. '" AND ttlCount == (SELECT MAX(ttlCount) from ip_ttl WHERE ipAddress="'
  581. + ip_address + '")')
  582. if isinstance(ttl_value, int):
  583. return ttl_value
  584. elif isinstance(ttl_value, list):
  585. if len(ttl_value) == 0:
  586. return None
  587. else:
  588. ttl_value.sort()
  589. return ttl_value[0]
  590. else:
  591. return None
  592. def get_avg_delay_local_ext(self):
  593. """
  594. Calculates the average delay of a packet for external and local communication, based on the tcp handshakes
  595. :return: tuple consisting of avg delay for local and external communication, (local, external)
  596. """
  597. conv_delays = self.stats_db.process_user_defined_query(
  598. "SELECT ipAddressA, ipAddressB, avgDelay FROM conv_statistics")
  599. if conv_delays:
  600. external_conv = []
  601. local_conv = []
  602. for conv in conv_delays:
  603. ip_a = IPAddress.parse(conv[0])
  604. ip_b = IPAddress.parse(conv[1])
  605. # split into local and external conversations
  606. if not ip_a.is_private() or not ip_b.is_private():
  607. external_conv.append(conv)
  608. else:
  609. local_conv.append(conv)
  610. # calculate avg local and external delay by summing up the respective delays and dividing them by the
  611. # number of conversations
  612. avg_delay_external = 0.0
  613. avg_delay_local = 0.0
  614. default_ext = False
  615. default_local = False
  616. if local_conv:
  617. for conv in local_conv:
  618. avg_delay_local += conv[2]
  619. avg_delay_local = (avg_delay_local / len(local_conv)) * 0.001 # ms
  620. else:
  621. # no local conversations in statistics found
  622. avg_delay_local = 0.055
  623. default_local = True
  624. if external_conv:
  625. for conv in external_conv:
  626. avg_delay_external += conv[2]
  627. avg_delay_external = (avg_delay_external / len(external_conv)) * 0.001 # ms
  628. else:
  629. # no external conversations in statistics found
  630. avg_delay_external = 0.09
  631. default_ext = True
  632. else:
  633. # if no statistics were found, use these numbers
  634. avg_delay_external = 0.09
  635. avg_delay_local = 0.055
  636. default_ext = True
  637. default_local = True
  638. # check whether delay numbers are consistent
  639. if avg_delay_local > avg_delay_external:
  640. avg_delay_external = avg_delay_local * 1.2
  641. # print information, that (default) values are used, that are not collected from the Input PCAP
  642. if default_ext or default_local:
  643. if default_ext and default_local:
  644. print("Warning: Could not collect average delays for local or external communication, using "
  645. "following values:")
  646. elif default_ext:
  647. print("Warning: Could not collect average delays for external communication, using following values:")
  648. elif default_local:
  649. print("Warning: Could not collect average delays for local communication, using following values:")
  650. print("Avg delay of external communication: {0}s, Avg delay of local communication: {1}s".format(
  651. avg_delay_external, avg_delay_local))
  652. return avg_delay_local, avg_delay_external
  653. def get_filtered_degree(self, degree_type: str):
  654. """
  655. gets the desired type of degree statistics and filters IPs with degree value zero
  656. :param degree_type: the desired type of degrees, one of the following: inDegree, outDegree, overallDegree
  657. :return: the filtered degrees
  658. """
  659. degrees_raw = self.stats_db.process_user_defined_query(
  660. "SELECT ipAddress, %s FROM ip_degrees" % degree_type)
  661. degrees = []
  662. if degrees_raw:
  663. for deg in degrees_raw:
  664. if int(deg[1]) > 0:
  665. degrees.append(deg)
  666. return degrees
  667. def get_rnd_win_size(self, pkts_num):
  668. """
  669. :param pkts_num: maximum number of window sizes, that should be returned
  670. :return: A list of randomly chosen window sizes with given length.
  671. """
  672. sql_return = self.process_db_query("SELECT DISTINCT winSize FROM tcp_win ORDER BY winsize ASC;")
  673. if not isinstance(sql_return, list):
  674. return [sql_return]
  675. result = []
  676. for i in range(0, min(pkts_num, len(sql_return))):
  677. result.append(random.choice(sql_return))
  678. sql_return.remove(result[i])
  679. return result
  680. def get_statistics_database(self):
  681. """
  682. :return: A reference to the statistics database object
  683. """
  684. return self.stats_db
  685. def process_db_query(self, query_string_in: str, print_results: bool = False):
  686. """
  687. Executes a string identified previously as a query. This can be a standard SQL SELECT/INSERT query or a named
  688. query.
  689. :param query_string_in: The query to be processed
  690. :param print_results: Indicates whether the results should be printed to terminal
  691. :return: The result of the query
  692. """
  693. return self.stats_db.process_db_query(query_string_in, print_results)
  694. def is_query(self, value: str):
  695. """
  696. Checks whether the given string is a standard SQL query (SELECT, INSERT) or a named query.
  697. :param value: The string to be checked
  698. :return: True if the string is recognized as a query, otherwise False.
  699. """
  700. if not isinstance(value, str):
  701. return False
  702. else:
  703. return (any(x in value.lower().strip() for x in self.stats_db.get_all_named_query_keywords()) or
  704. any(x in value.lower().strip() for x in self.stats_db.get_all_sql_query_keywords()))
  705. @staticmethod
  706. def calculate_standard_deviation(lst):
  707. """
  708. Calculates the standard deviation of a list of numbers.
  709. :param lst: The list of numbers to calculate its SD.
  710. """
  711. num_items = len(lst)
  712. mean = sum(lst) / num_items
  713. differences = [x - mean for x in lst]
  714. sq_differences = [d ** 2 for d in differences]
  715. ssd = sum(sq_differences)
  716. variance = ssd / num_items
  717. sd = sqrt(variance)
  718. return sd
  719. def plot_statistics(self, entropy: int, file_format: str = 'pdf'): # 'png'
  720. """
  721. Plots the statistics associated with the dataset.
  722. :param entropy: the statistics entropy
  723. :param file_format: The format to be used to save the statistics diagrams.
  724. """
  725. def plot_distribution(query_output, title, x_label, y_label, file_ending: str):
  726. """
  727. TODO: FILL ME
  728. :param query_output:
  729. :param title:
  730. :param x_label:
  731. :param y_label:
  732. :param file_ending:
  733. :return:
  734. """
  735. plt.gcf().clear()
  736. graphx, graphy = [], []
  737. for row in query_output:
  738. graphx.append(row[0])
  739. graphy.append(row[1])
  740. plt.autoscale(enable=True, axis='both')
  741. plt.title(title)
  742. plt.xlabel(x_label)
  743. plt.ylabel(y_label)
  744. width = 0.1
  745. plt.xlim([0, (max(graphx) * 1.1)])
  746. plt.grid(True)
  747. plt.bar(graphx, graphy, width, align='center', linewidth=1, color='red', edgecolor='red')
  748. out = self.pcap_filepath.replace('.pcap', '_plot-' + title + file_ending)
  749. plt.savefig(out, dpi=500)
  750. return out
  751. def plot_ttl(file_ending: str):
  752. """
  753. TODO: FILL ME
  754. :param file_ending:
  755. :return:
  756. """
  757. query_output = self.stats_db.process_user_defined_query(
  758. "SELECT ttlValue, SUM(ttlCount) FROM ip_ttl GROUP BY ttlValue")
  759. title = "TTL Distribution"
  760. x_label = "TTL Value"
  761. y_label = "Number of Packets"
  762. if query_output:
  763. return plot_distribution(query_output, title, x_label, y_label, file_ending)
  764. def plot_mss(file_ending: str):
  765. """
  766. TODO: FILL ME
  767. :param file_ending:
  768. :return:
  769. """
  770. query_output = self.stats_db.process_user_defined_query(
  771. "SELECT mssValue, SUM(mssCount) FROM tcp_mss GROUP BY mssValue")
  772. title = "MSS Distribution"
  773. x_label = "MSS Value"
  774. y_label = "Number of Packets"
  775. if query_output:
  776. return plot_distribution(query_output, title, x_label, y_label, file_ending)
  777. def plot_win(file_ending: str):
  778. """
  779. TODO: FILL ME
  780. :param file_ending:
  781. :return:
  782. """
  783. query_output = self.stats_db.process_user_defined_query(
  784. "SELECT winSize, SUM(winCount) FROM tcp_win GROUP BY winSize")
  785. title = "Window Size Distribution"
  786. x_label = "Window Size"
  787. y_label = "Number of Packets"
  788. if query_output:
  789. return plot_distribution(query_output, title, x_label, y_label, file_ending)
  790. def plot_protocol(file_ending: str):
  791. """
  792. TODO: FILL ME
  793. :param file_ending:
  794. :return:
  795. """
  796. plt.gcf().clear()
  797. result = self.stats_db.process_user_defined_query(
  798. "SELECT protocolName, SUM(protocolCount) FROM ip_protocols GROUP BY protocolName")
  799. if result:
  800. graphx, graphy = [], []
  801. for row in result:
  802. graphx.append(row[0])
  803. graphy.append(row[1])
  804. plt.autoscale(enable=True, axis='both')
  805. plt.title("Protocols Distribution")
  806. plt.xlabel('Protocols')
  807. plt.ylabel('Number of Packets')
  808. width = 0.1
  809. plt.xlim([0, len(graphx)])
  810. plt.grid(True)
  811. # Protocols' names on x-axis
  812. x = range(0, len(graphx))
  813. my_xticks = graphx
  814. plt.xticks(x, my_xticks)
  815. plt.bar(x, graphy, width, align='center', linewidth=1, color='red', edgecolor='red')
  816. out = self.pcap_filepath.replace('.pcap', '_plot-protocol' + file_ending)
  817. plt.savefig(out, dpi=500)
  818. return out
  819. else:
  820. print("Error plot protocol: No protocol values found!")
  821. def plot_port(file_ending: str):
  822. """
  823. TODO: FILL ME
  824. :param file_ending:
  825. :return:
  826. """
  827. plt.gcf().clear()
  828. result = self.stats_db.process_user_defined_query(
  829. "SELECT portNumber, SUM(portCount) FROM ip_ports GROUP BY portNumber")
  830. graphx, graphy = [], []
  831. for row in result:
  832. graphx.append(row[0])
  833. graphy.append(row[1])
  834. plt.autoscale(enable=True, axis='both')
  835. plt.title("Ports Distribution")
  836. plt.xlabel('Ports Numbers')
  837. plt.ylabel('Number of Packets')
  838. width = 0.1
  839. plt.xlim([0, max(graphx)])
  840. plt.grid(True)
  841. plt.bar(graphx, graphy, width, align='center', linewidth=1, color='red', edgecolor='red')
  842. out = self.pcap_filepath.replace('.pcap', '_plot-port' + file_ending)
  843. plt.savefig(out, dpi=500)
  844. return out
  845. # This distribution is not drawable for big datasets
  846. def plot_ip_src(file_ending: str):
  847. """
  848. TODO: FILL ME
  849. :param file_ending:
  850. :return:
  851. """
  852. plt.gcf().clear()
  853. result = self.stats_db.process_user_defined_query(
  854. "SELECT ipAddress, pktsSent FROM ip_statistics")
  855. graphx, graphy = [], []
  856. for row in result:
  857. graphx.append(row[0])
  858. graphy.append(row[1])
  859. plt.autoscale(enable=True, axis='both')
  860. plt.title("Source IP Distribution")
  861. plt.xlabel('Source IP')
  862. plt.ylabel('Number of Packets')
  863. width = 0.1
  864. plt.xlim([0, len(graphx)])
  865. plt.grid(True)
  866. # IPs on x-axis
  867. x = range(0, len(graphx))
  868. my_xticks = graphx
  869. plt.xticks(x, my_xticks, rotation='vertical', fontsize=5)
  870. # plt.tight_layout()
  871. # limit the number of xticks
  872. plt.locator_params(axis='x', nbins=20)
  873. plt.bar(x, graphy, width, align='center', linewidth=1, color='red', edgecolor='red')
  874. out = self.pcap_filepath.replace('.pcap', '_plot-ip-src' + file_ending)
  875. plt.savefig(out, dpi=500)
  876. return out
  877. # This distribution is not drawable for big datasets
  878. def plot_ip_dst(file_ending: str):
  879. """
  880. TODO: FILL ME
  881. :param file_ending:
  882. :return:
  883. """
  884. plt.gcf().clear()
  885. result = self.stats_db.process_user_defined_query(
  886. "SELECT ipAddress, pktsReceived FROM ip_statistics")
  887. graphx, graphy = [], []
  888. for row in result:
  889. graphx.append(row[0])
  890. graphy.append(row[1])
  891. plt.autoscale(enable=True, axis='both')
  892. plt.title("Destination IP Distribution")
  893. plt.xlabel('Destination IP')
  894. plt.ylabel('Number of Packets')
  895. width = 0.1
  896. plt.xlim([0, len(graphx)])
  897. plt.grid(True)
  898. # IPs on x-axis
  899. x = range(0, len(graphx))
  900. my_xticks = graphx
  901. plt.xticks(x, my_xticks, rotation='vertical', fontsize=5)
  902. # plt.tight_layout()
  903. # limit the number of xticks
  904. plt.locator_params(axis='x', nbins=20)
  905. plt.bar(x, graphy, width, align='center', linewidth=1, color='red', edgecolor='red')
  906. out = self.pcap_filepath.replace('.pcap', '_plot-ip-dst' + file_ending)
  907. plt.savefig(out, dpi=500)
  908. return out
  909. def plot_interval_statistics(query_output, title, x_label, y_label, file_ending: str):
  910. """
  911. TODO: FILL ME
  912. :param query_output:
  913. :param title:
  914. :param x_label:
  915. :param y_label:
  916. :param file_ending:
  917. :return:
  918. """
  919. plt.gcf().clear()
  920. graphx, graphy = [], []
  921. for row in query_output:
  922. graphx.append(row[0])
  923. graphy.append(row[1])
  924. plt.autoscale(enable=True, axis='both')
  925. plt.title(title)
  926. plt.xlabel(x_label)
  927. plt.ylabel(y_label)
  928. width = 0.5
  929. plt.xlim([0, len(graphx)])
  930. plt.grid(True)
  931. # timestamp on x-axis
  932. x = range(0, len(graphx))
  933. # limit the number of xticks
  934. plt.locator_params(axis='x', nbins=20)
  935. plt.bar(x, graphy, width, align='center', linewidth=1, color='red', edgecolor='red')
  936. out = self.pcap_filepath.replace('.pcap', '_plot-' + title + file_ending)
  937. plt.savefig(out, dpi=500)
  938. return out
  939. def plot_interval_pkt_count(file_ending: str):
  940. """
  941. TODO: FILL ME
  942. :param file_ending:
  943. :return:
  944. """
  945. query_output = self.stats_db.process_user_defined_query(
  946. "SELECT lastPktTimestamp, pktsCount FROM interval_statistics ORDER BY lastPktTimestamp")
  947. title = "Packet Rate"
  948. x_label = "Time Interval"
  949. y_label = "Number of Packets"
  950. if query_output:
  951. return plot_interval_statistics(query_output, title, x_label, y_label, file_ending)
  952. def plot_interval_ip_src_ent(file_ending: str):
  953. """
  954. TODO: FILL ME
  955. :param file_ending:
  956. :return:
  957. """
  958. query_output = self.stats_db.process_user_defined_query(
  959. "SELECT lastPktTimestamp, ipSrcEntropy FROM interval_statistics ORDER BY lastPktTimestamp")
  960. title = "Source IP Entropy"
  961. x_label = "Time Interval"
  962. y_label = "Entropy"
  963. if query_output:
  964. return plot_interval_statistics(query_output, title, x_label, y_label, file_ending)
  965. def plot_interval_ip_dst_ent(file_ending: str):
  966. """
  967. TODO: FILL ME
  968. :param file_ending:
  969. :return:
  970. """
  971. query_output = self.stats_db.process_user_defined_query(
  972. "SELECT lastPktTimestamp, ipDstEntropy FROM interval_statistics ORDER BY lastPktTimestamp")
  973. title = "Destination IP Entropy"
  974. x_label = "Time Interval"
  975. y_label = "Entropy"
  976. if query_output:
  977. return plot_interval_statistics(query_output, title, x_label, y_label, file_ending)
  978. def plot_interval_new_ip(file_ending: str):
  979. """
  980. TODO: FILL ME
  981. :param file_ending:
  982. :return:
  983. """
  984. query_output = self.stats_db.process_user_defined_query(
  985. "SELECT lastPktTimestamp, newIPCount FROM interval_statistics ORDER BY lastPktTimestamp")
  986. title = "IP Novelty Distribution"
  987. x_label = "Time Interval"
  988. y_label = "Novel values count"
  989. if query_output:
  990. return plot_interval_statistics(query_output, title, x_label, y_label, file_ending)
  991. def plot_interval_new_port(file_ending: str):
  992. """
  993. TODO: FILL ME
  994. :param file_ending:
  995. :return:
  996. """
  997. query_output = self.stats_db.process_user_defined_query(
  998. "SELECT lastPktTimestamp, newPortCount FROM interval_statistics ORDER BY lastPktTimestamp")
  999. title = "Port Novelty Distribution"
  1000. x_label = "Time Interval"
  1001. y_label = "Novel values count"
  1002. if query_output:
  1003. return plot_interval_statistics(query_output, title, x_label, y_label, file_ending)
  1004. def plot_interval_new_ttl(file_ending: str):
  1005. """
  1006. TODO: FILL ME
  1007. :param file_ending:
  1008. :return:
  1009. """
  1010. query_output = self.stats_db.process_user_defined_query(
  1011. "SELECT lastPktTimestamp, newTTLCount FROM interval_statistics ORDER BY lastPktTimestamp")
  1012. title = "TTL Novelty Distribution"
  1013. x_label = "Time Interval"
  1014. y_label = "Novel values count"
  1015. if query_output:
  1016. return plot_interval_statistics(query_output, title, x_label, y_label, file_ending)
  1017. def plot_interval_new_tos(file_ending: str):
  1018. """
  1019. TODO: FILL ME
  1020. :param file_ending:
  1021. :return:
  1022. """
  1023. query_output = self.stats_db.process_user_defined_query(
  1024. "SELECT lastPktTimestamp, newToSCount FROM interval_statistics ORDER BY lastPktTimestamp")
  1025. title = "ToS Novelty Distribution"
  1026. x_label = "Time Interval"
  1027. y_label = "Novel values count"
  1028. if query_output:
  1029. return plot_interval_statistics(query_output, title, x_label, y_label, file_ending)
  1030. def plot_interval_new_win_size(file_ending: str):
  1031. """
  1032. TODO: FILL ME
  1033. :param file_ending:
  1034. :return:
  1035. """
  1036. query_output = self.stats_db.process_user_defined_query(
  1037. "SELECT lastPktTimestamp, newWinSizeCount FROM interval_statistics ORDER BY lastPktTimestamp")
  1038. title = "Window Size Novelty Distribution"
  1039. x_label = "Time Interval"
  1040. y_label = "Novel values count"
  1041. if query_output:
  1042. return plot_interval_statistics(query_output, title, x_label, y_label, file_ending)
  1043. def plot_interval_new_mss(file_ending: str):
  1044. """
  1045. TODO: FILL ME
  1046. :param file_ending:
  1047. :return:
  1048. """
  1049. query_output = self.stats_db.process_user_defined_query(
  1050. "SELECT lastPktTimestamp, newMSSCount FROM interval_statistics ORDER BY lastPktTimestamp")
  1051. title = "MSS Novelty Distribution"
  1052. x_label = "Time Interval"
  1053. y_label = "Novel values count"
  1054. if query_output:
  1055. return plot_interval_statistics(query_output, title, x_label, y_label, file_ending)
  1056. def plot_interval_ip_cum_ent(ip_type: str, file_ending: str):
  1057. """
  1058. TODO: FILL ME
  1059. :param ip_type: source or destination
  1060. :param file_ending:
  1061. :return:
  1062. """
  1063. if ip_type is "src":
  1064. sod = "Src"
  1065. full = "Source"
  1066. elif ip_type is "src":
  1067. sod = "Dst"
  1068. full = "Destination"
  1069. else:
  1070. return None
  1071. plt.gcf().clear()
  1072. result = self.stats_db.process_user_defined_query(
  1073. "SELECT lastPktTimestamp, ip%sCumEntropy FROM interval_statistics ORDER BY lastPktTimestamp" % sod)
  1074. graphx, graphy = [], []
  1075. for row in result:
  1076. graphx.append(row[0])
  1077. graphy.append(row[1])
  1078. # If entropy was not calculated do not plot the graph
  1079. if graphy[0] != -1:
  1080. plt.autoscale(enable=True, axis='both')
  1081. plt.title(full + " IP Cumulative Entropy")
  1082. # plt.xlabel('Timestamp')
  1083. plt.xlabel('Time Interval')
  1084. plt.ylabel('Entropy')
  1085. plt.xlim([0, len(graphx)])
  1086. plt.grid(True)
  1087. # timestamp on x-axis
  1088. x = range(0, len(graphx))
  1089. # my_xticks = graphx
  1090. # plt.xticks(x, my_xticks, rotation='vertical', fontsize=5)
  1091. # plt.tight_layout()
  1092. # limit the number of xticks
  1093. plt.locator_params(axis='x', nbins=20)
  1094. plt.plot(x, graphy, 'r')
  1095. out = self.pcap_filepath.replace('.pcap', '_plot-interval-ip-' + ip_type + '-cum-ent' + file_ending)
  1096. plt.savefig(out, dpi=500)
  1097. return out
  1098. def plot_degree(degree_type: str, file_ending: str):
  1099. """
  1100. Creates a Plot, visualizing a degree for every IP Address
  1101. :param degree_type: the type of degree, which should be plotted
  1102. :param file_ending: The file extension for the output file containing the plot, e.g. "pdf"
  1103. :return: A filepath to the file containing the created plot
  1104. """
  1105. if degree_type not in ["in", "out", "overall"]:
  1106. return None
  1107. plt.gcf().clear()
  1108. # retrieve data
  1109. degree = self.stats_db.process_user_defined_query(
  1110. "SELECT ipAddress, %s FROM ip_degrees" % (degree_type + "Degree"))
  1111. if degree is None:
  1112. return None
  1113. graphx, graphy = [], []
  1114. for entry in degree:
  1115. if entry[1] <= 0:
  1116. continue
  1117. # degree values
  1118. graphx.append(entry[1])
  1119. # IP labels
  1120. graphy.append(entry[0])
  1121. # set labels
  1122. plt.title(degree_type + " Degree per IP Address")
  1123. plt.ylabel('IpAddress')
  1124. plt.xlabel(degree_type + 'Degree')
  1125. # set width of the bars
  1126. width = 0.3
  1127. # set scalings
  1128. plt.figure(
  1129. figsize=(int(len(graphx)) / 20 + 5, int(len(graphy) / 5) + 5)) # these proportions just worked well
  1130. # set limits of the axis
  1131. plt.ylim([0, len(graphy)])
  1132. plt.xlim([0, max(graphx) + 10])
  1133. # display numbers at each bar
  1134. for i, v in enumerate(graphx):
  1135. plt.text(v + 1, i + .1, str(v), color='blue', fontweight='bold')
  1136. # display grid for better visuals
  1137. plt.grid(True)
  1138. # plot the bar
  1139. labels = graphy
  1140. graphy = list(range(len(graphx)))
  1141. plt.barh(graphy, graphx, width, align='center', linewidth=1, color='red', edgecolor='red')
  1142. plt.yticks(graphy, labels)
  1143. out = self.pcap_filepath.replace('.pcap', '_plot-' + degree_type + ' Degree of an IP' + file_ending)
  1144. # plt.tight_layout()
  1145. plt.savefig(out, dpi=500)
  1146. return out
  1147. def plot_big_conv_ext_stat(attr: str, title: str, xlabel: str, suffix: str):
  1148. """
  1149. Plots the desired statistc per connection as horizontal bar plot.
  1150. Included are 'half-open' connections, where only one packet is exchanged.
  1151. The given statistics table has to have at least the attributes 'ipAddressA', 'portA', 'ipAddressB',
  1152. 'portB' and the specified additional attribute.
  1153. Note: there may be cutoff/scaling problems within the plot if there is too little data.
  1154. :param attr: The desired statistic, named with respect to its attribute in the given statistics table
  1155. :param title: The title of the created plot
  1156. :param xlabel: The name of the x-axis of the created plot
  1157. :param suffix: The suffix of the created file, including file extension
  1158. :return: A filepath to the file containing the created plot
  1159. """
  1160. plt.gcf().clear()
  1161. result = self.stats_db.process_user_defined_query(
  1162. "SELECT ipAddressA, portA, ipAddressB, portB, %s FROM conv_statistics_extended" % attr)
  1163. if result:
  1164. graphy, graphx = [], []
  1165. # plot data in descending order
  1166. result = sorted(result, key=lambda r: r[4])
  1167. # compute plot data
  1168. for i, row in enumerate(result):
  1169. addr1, addr2 = "%s:%d" % (row[0], row[1]), "%s:%d" % (row[2], row[3])
  1170. # adjust the justification of strings to improve appearance
  1171. len_max = max(len(addr1), len(addr2))
  1172. addr1 = addr1.ljust(len_max)
  1173. addr2 = addr2.ljust(len_max)
  1174. # add plot data
  1175. graphy.append("%s\n%s" % (addr1, addr2))
  1176. graphx.append(row[4])
  1177. # have x axis and its label appear at the top (instead of bottom)
  1178. fig, ax = plt.subplots()
  1179. ax.xaxis.tick_top()
  1180. ax.xaxis.set_label_position("top")
  1181. # compute plot height in inches for scaling the plot
  1182. dist_mult_height = 0.55 # this value turned out to work well
  1183. plt_height = len(graphy) * dist_mult_height
  1184. # originally, a good title distance turned out to be 1.012 with a plot height of 52.8
  1185. title_distance = 1 + 0.012 * 52.8 / plt_height
  1186. plt.gcf().set_size_inches(plt.gcf().get_size_inches()[0], plt_height) # set plot height
  1187. plt.gcf().subplots_adjust(left=0.35)
  1188. # set additional plot parameters
  1189. plt.title(title, y=title_distance)
  1190. plt.xlabel(xlabel)
  1191. plt.ylabel('Connection')
  1192. width = 0.5
  1193. plt.grid(True)
  1194. plt.gca().margins(y=0) # removes the space between data and x-axis within the plot
  1195. # plot the above data, first use plain numbers as graphy to maintain sorting
  1196. plt.barh(range(len(graphy)), graphx, width, align='center', linewidth=0.5, color='red', edgecolor='red')
  1197. # now change the y numbers to the respective address labels
  1198. plt.yticks(range(len(graphy)), graphy)
  1199. # save created figure
  1200. out = self.pcap_filepath.replace('.pcap', suffix)
  1201. plt.savefig(out, dpi=500)
  1202. return out
  1203. def plot_packets_per_connection(file_ending: str):
  1204. """
  1205. Plots the total number of exchanged packets per connection.
  1206. :param file_ending: The file extension for the output file containing the plot
  1207. :return: A filepath to the file containing the created plot
  1208. """
  1209. title = 'Number of exchanged packets per connection'
  1210. suffix = '_plot-PktCount per Connection Distribution' + file_ending
  1211. # plot data and return outpath
  1212. return plot_big_conv_ext_stat("pktsCount", title, "Number of packets", suffix)
  1213. def plot_avg_pkts_per_comm_interval(file_ending: str):
  1214. """
  1215. Plots the average number of exchanged packets per communication interval for every connection.
  1216. :param file_ending: The file extension for the output file containing the plot
  1217. :return: A filepath to the file containing the created plot
  1218. """
  1219. title = 'Average number of exchanged packets per communication interval'
  1220. suffix = '_plot-Avg PktCount Communication Interval Distribution' + file_ending
  1221. # plot data and return outpath
  1222. return plot_big_conv_ext_stat("avgIntervalPktCount", title, "Number of packets", suffix)
  1223. def plot_avg_time_between_comm_interval(file_ending: str):
  1224. """
  1225. Plots the average time between the communication intervals of every connection.
  1226. :param file_ending: The file extension for the output file containing the plot
  1227. :return: A filepath to the file containing the created plot
  1228. """
  1229. title = 'Average time between communication intervals in seconds'
  1230. suffix = '_plot-Avg Time Between Communication Intervals Distribution' + file_ending
  1231. # plot data and return outpath
  1232. return plot_big_conv_ext_stat("avgTimeBetweenIntervals", title, 'Average time between intervals', suffix)
  1233. def plot_avg_comm_interval_time(file_ending: str):
  1234. """
  1235. Plots the average duration of a communication interval of every connection.
  1236. :param file_ending: The file extension for the output file containing the plot
  1237. :return: A filepath to the file containing the created plot
  1238. """
  1239. title = 'Average duration of a communication interval in seconds'
  1240. suffix = '_plot-Avg Duration Communication Interval Distribution' + file_ending
  1241. # plot data and return outpath
  1242. return plot_big_conv_ext_stat("avgIntervalTime", title, 'Average interval time', suffix)
  1243. def plot_total_comm_duration(file_ending: str):
  1244. """
  1245. Plots the total communication duration of every connection.
  1246. :param file_ending: The file extension for the output file containing the plot
  1247. :return: A filepath to the file containing the created plot
  1248. """
  1249. title = 'Total communication duration in seconds'
  1250. suffix = '_plot-Total Communication Duration Distribution' + file_ending
  1251. # plot data and return outpath
  1252. return plot_big_conv_ext_stat("totalConversationDuration", title, 'Duration', suffix)
  1253. def plot_comm_histogram(attr: str, title: str, label: str, suffix: str):
  1254. """
  1255. Plots a histogram about the specified attribute for communications.
  1256. :param attr: The statistics attribute for this histogram
  1257. :param title: The title of the histogram
  1258. :param label: The xlabel of the histogram
  1259. :param suffix: The file suffix
  1260. :return: The path to the created plot
  1261. """
  1262. plt.gcf().clear()
  1263. result_raw = self.stats_db.process_user_defined_query(
  1264. "SELECT %s FROM conv_statistics_extended" % attr)
  1265. # return without plotting if no data available
  1266. if not result_raw:
  1267. return None
  1268. result = []
  1269. for entry in result_raw:
  1270. result.append(entry[0])
  1271. # if title would be cut off, set minimum width
  1272. plt_size = plt.gcf().get_size_inches()
  1273. min_width = len(title) * 0.12
  1274. if plt_size[0] < min_width:
  1275. plt.gcf().set_size_inches(min_width, plt_size[1]) # set plot size
  1276. # set additional plot parameters
  1277. plt.title(title)
  1278. plt.ylabel("Relative frequency of connections")
  1279. plt.xlabel(label)
  1280. plt.grid(True)
  1281. # create 11 bins
  1282. bins = []
  1283. max_val = max(result)
  1284. for i in range(0, 11):
  1285. bins.append(i * max_val / 10)
  1286. # set weights normalize histogram
  1287. weights = numpy.ones_like(result) / float(len(result))
  1288. # plot the above data, first use plain numbers as graphy to maintain sorting
  1289. plt.hist(result, bins=bins, weights=weights, color='red', edgecolor='red', align="mid", rwidth=0.5)
  1290. plt.xticks(bins)
  1291. # save created figure
  1292. out = self.pcap_filepath.replace('.pcap', suffix)
  1293. plt.savefig(out, dpi=500)
  1294. return out
  1295. def plot_histogram_degree(degree_type: str, title: str, label: str, suffix: str):
  1296. """
  1297. Plots a histogram about the specified type for the degree of an IP.
  1298. :param degree_type: The type of degree, i.e. inDegree, outDegree or overallDegree
  1299. :param title: The title of the histogram
  1300. :param label: The xlabel of the histogram
  1301. :param suffix: The file suffix
  1302. :return: The path to the created plot
  1303. """
  1304. plt.gcf().clear()
  1305. result_raw = self.get_filtered_degree(degree_type)
  1306. # return without plotting if no data available
  1307. if not result_raw:
  1308. return None
  1309. result = []
  1310. for entry in result_raw:
  1311. result.append(entry[1])
  1312. # set additional plot parameters
  1313. plt.title(title)
  1314. plt.ylabel("Relative frequency of IPs")
  1315. plt.xlabel(label)
  1316. plt.grid(True)
  1317. # create 11 bins
  1318. bins = []
  1319. max_val = max(result)
  1320. for i in range(0, 11):
  1321. bins.append(int(i * max_val / 10))
  1322. # set weights normalize histogram
  1323. weights = numpy.ones_like(result) / float(len(result))
  1324. # plot the above data, first use plain numbers as graphy to maintain sorting
  1325. plt.hist(result, bins=bins, weights=weights, color='red', edgecolor='red', align="mid", rwidth=0.5)
  1326. plt.xticks(bins)
  1327. # save created figure
  1328. out = self.pcap_filepath.replace('.pcap', suffix)
  1329. plt.savefig(out, dpi=500)
  1330. return out
  1331. ttl_out_path = plot_ttl('.' + file_format)
  1332. print(".", end="", flush=True)
  1333. mss_out_path = plot_mss('.' + file_format)
  1334. print(".", end="", flush=True)
  1335. win_out_path = plot_win('.' + file_format)
  1336. print(".", end="", flush=True)
  1337. protocol_out_path = plot_protocol('.' + file_format)
  1338. print(".", end="", flush=True)
  1339. plot_interval_pktCount = plot_interval_pkt_count('.' + file_format)
  1340. print(".", end="", flush=True)
  1341. if entropy:
  1342. plot_interval_ip_src_ent = plot_interval_ip_src_ent('.' + file_format)
  1343. print(".", end="", flush=True)
  1344. plot_interval_ip_dst_ent = plot_interval_ip_dst_ent('.' + file_format)
  1345. print(".", end="", flush=True)
  1346. plot_interval_ip_src_cum_ent = plot_interval_ip_cum_ent("src", '.' + file_format)
  1347. print(".", end="", flush=True)
  1348. plot_interval_ip_dst_cum_ent = plot_interval_ip_cum_ent("dst", '.' + file_format)
  1349. print(".", end="", flush=True)
  1350. plot_interval_new_ip = plot_interval_new_ip('.' + file_format)
  1351. print(".", end="", flush=True)
  1352. plot_interval_new_port = plot_interval_new_port('.' + file_format)
  1353. print(".", end="", flush=True)
  1354. plot_interval_new_ttl = plot_interval_new_ttl('.' + file_format)
  1355. print(".", end="", flush=True)
  1356. plot_interval_new_tos = plot_interval_new_tos('.' + file_format)
  1357. print(".", end="", flush=True)
  1358. plot_interval_new_win_size = plot_interval_new_win_size('.' + file_format)
  1359. print(".", end="", flush=True)
  1360. plot_interval_new_mss = plot_interval_new_mss('.' + file_format)
  1361. print(".", end="", flush=True)
  1362. plot_hist_indegree_out = plot_histogram_degree("inDegree", "Histogram - Ingoing degree per IP Address",
  1363. "Ingoing degree",
  1364. "_plot-Histogram Ingoing Degree per IP" + file_format)
  1365. print(".", end="", flush=True)
  1366. plot_hist_outdegree_out = plot_histogram_degree("outDegree", "Histogram - Outgoing degree per IP Address",
  1367. "Outgoing degree",
  1368. "_plot-Histogram Outgoing Degree per IP" + file_format)
  1369. print(".", end="", flush=True)
  1370. plot_hist_overalldegree_out = plot_histogram_degree("overallDegree",
  1371. "Histogram - Overall degree per IP Address",
  1372. "Overall degree",
  1373. "_plot-Histogram Overall Degree per IP" + file_format)
  1374. print(".", end="", flush=True)
  1375. plot_hist_pkts_per_connection_out = plot_comm_histogram("pktsCount",
  1376. "Histogram - Number of exchanged packets per connection",
  1377. "Number of packets",
  1378. "_plot-Histogram PktCount per Connection" + "." + file_format)
  1379. print(".", end="", flush=True)
  1380. plot_hist_avgpkts_per_commint_out = plot_comm_histogram("avgIntervalPktCount",
  1381. "Histogram - Average number of exchanged packets per communication interval",
  1382. "Average number of packets",
  1383. "_plot-Histogram Avg PktCount per Interval per Connection" + "." + file_format)
  1384. print(".", end="", flush=True)
  1385. plot_hist_avgtime_betw_commints_out = plot_comm_histogram("avgTimeBetweenIntervals",
  1386. "Histogram - Average time between communication intervals in seconds",
  1387. "Average time between intervals",
  1388. "_plot-Histogram Avg Time Between Intervals per Connection" + "." + file_format)
  1389. print(".", end="", flush=True)
  1390. plot_hist_avg_int_time_per_connection_out = plot_comm_histogram("avgIntervalTime",
  1391. "Histogram - Average duration of a communication interval in seconds",
  1392. "Average interval time",
  1393. "_plot-Histogram Avg Interval Time per Connection" + "." + file_format)
  1394. print(".", end="", flush=True)
  1395. plot_hist_total_comm_duration_out = plot_comm_histogram("totalConversationDuration",
  1396. "Histogram - Total communication duration in seconds",
  1397. "Duration",
  1398. "_plot-Histogram Communication Duration per Connection" + "." + file_format)
  1399. print(".", end="", flush=True)
  1400. plot_out_degree = plot_degree("out", '.' + file_format)
  1401. print(".", end="", flush=True)
  1402. plot_in_degree = plot_degree("in", '.' + file_format)
  1403. print(".", end="", flush=True)
  1404. plot_overall_degree = plot_degree("overall", '.' + file_format)
  1405. print(".", end="", flush=True)
  1406. plot_packets_per_connection_out = plot_packets_per_connection('.' + file_format)
  1407. print(".", end="", flush=True)
  1408. plot_avg_pkts_per_comm_interval_out = plot_avg_pkts_per_comm_interval('.' + file_format)
  1409. print(".", end="", flush=True)
  1410. plot_avg_time_between_comm_interval_out = plot_avg_time_between_comm_interval('.' + file_format)
  1411. print(".", end="", flush=True)
  1412. plot_avg_comm_interval_time_out = plot_avg_comm_interval_time("." + file_format)
  1413. print(".", end="", flush=True)
  1414. plot_total_comm_duration_out = plot_total_comm_duration("." + file_format)
  1415. print(" done.")
  1416. # Time consuming plot
  1417. # port_out_path = plot_port('.' + format)
  1418. # Not drawable for too many IPs
  1419. # ip_src_out_path = plot_ip_src('.' + format)
  1420. # ip_dst_out_path = plot_ip_dst('.' + format)
  1421. print("Saved plots in the input PCAP directory.")
  1422. def stats_summary_post_attack(self, added_packets):
  1423. """
  1424. Prints a summary of relevant statistics after an attack is injected
  1425. :param added_packets: sum of packets added by attacks, gets updated if more than one attack
  1426. :return: None
  1427. """
  1428. total_packet_count = self.get_packet_count() + added_packets
  1429. added_packets_share = added_packets / total_packet_count * 100
  1430. timespan = self.get_capture_duration()
  1431. summary = [("Total packet count", total_packet_count, "packets"),
  1432. ("Added packet count", added_packets, "packets"),
  1433. ("Share of added packets", added_packets_share, "%"),
  1434. ("Capture duration", timespan, "seconds")]
  1435. print("\nPOST INJECTION STATISTICS SUMMARY --------------------------")
  1436. self.write_list(summary, print, "")
  1437. print("------------------------------------------------------------")
  1438. def stats_summary_new_db(self):
  1439. """
  1440. Prints a summary of relevant statistics when a new db is created
  1441. :return: None
  1442. """
  1443. self.file_info = self.stats_db.get_file_info()
  1444. print("\nNew database has been generated, printing statistics summary... ")
  1445. total_packet_count = self.get_packet_count()
  1446. pdu_count = self.process_db_query("SELECT SUM(pktCount) FROM unrecognized_pdus")
  1447. if pdu_count is None:
  1448. pdu_count = 0
  1449. pdu_share = pdu_count / total_packet_count * 100
  1450. last_pdu_timestamp = self.process_db_query(
  1451. "SELECT MAX(timestampLastOccurrence) FROM unrecognized_pdus")
  1452. timespan = self.get_capture_duration()
  1453. summary = [("Total packet count", total_packet_count, "packets"),
  1454. ("Recognized packets", total_packet_count - pdu_count, "packets"),
  1455. ("Unrecognized packets", pdu_count, "PDUs"),
  1456. ("% Recognized packets", 100 - pdu_share, "%"),
  1457. ("% Unrecognized packets", pdu_share, "%"),
  1458. ("Last unknown PDU", last_pdu_timestamp),
  1459. ("Capture duration", timespan, "seconds")]
  1460. print("\nPCAP FILE STATISTICS SUMMARY ------------------------------")
  1461. self.write_list(summary, print, "")
  1462. print("------------------------------------------------------------")