Statistics.py 80 KB

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