Statistics.py 80 KB

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