Statistics.py 77 KB

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