3
0

Statistics.py 51 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113
  1. import os
  2. import random
  3. import time
  4. from math import sqrt, ceil, log
  5. from operator import itemgetter
  6. # TODO: double check this import
  7. # does it complain because libpcapreader is not a .py?
  8. import ID2TLib.libpcapreader as pr
  9. import matplotlib
  10. import Core.StatsDatabase as statsDB
  11. import ID2TLib.PcapFile as PcapFile
  12. import ID2TLib.Utility as Util
  13. matplotlib.use('Agg', force=True)
  14. import matplotlib.pyplot as plt
  15. class Statistics:
  16. def __init__(self, pcap_file: PcapFile.PcapFile):
  17. """
  18. Creates a new Statistics object.
  19. :param pcap_file: A reference to the PcapFile object
  20. """
  21. # Fields
  22. self.pcap_filepath = pcap_file.pcap_file_path
  23. self.pcap_proc = None
  24. self.do_extra_tests = False
  25. self.file_info = None
  26. # Create folder for statistics database if required
  27. self.path_db = pcap_file.get_db_path()
  28. path_dir = os.path.dirname(self.path_db)
  29. if not os.path.isdir(path_dir):
  30. os.makedirs(path_dir)
  31. # Class instances
  32. self.stats_db = statsDB.StatsDatabase(self.path_db)
  33. def load_pcap_statistics(self, flag_write_file: bool, flag_recalculate_stats: bool, flag_print_statistics: bool,
  34. flag_non_verbose: bool):
  35. """
  36. Loads the PCAP statistics for the file specified by pcap_filepath. If the database is not existing yet, the
  37. statistics are calculated by the PCAP file processor and saved into the newly created database. Otherwise the
  38. statistics are gathered directly from the existing database.
  39. :param flag_write_file: Indicates whether the statistics should be written addiotionally into a text file (True)
  40. or not (False)
  41. :param flag_recalculate_stats: Indicates whether eventually existing statistics should be recalculated
  42. :param flag_print_statistics: Indicates whether the gathered basic statistics should be printed to the terminal
  43. :param flag_non_verbose: Indicates whether certain prints should be made or not, to reduce terminal clutter
  44. """
  45. # Load pcap and get loading time
  46. time_start = time.clock()
  47. # Inform user about recalculation of statistics and its reason
  48. if flag_recalculate_stats:
  49. print("Flag -r/--recalculate found. Recalculating statistics.")
  50. # Recalculate statistics if database does not exist OR param -r/--recalculate is provided
  51. if (not self.stats_db.get_db_exists()) or flag_recalculate_stats or self.stats_db.get_db_outdated():
  52. self.pcap_proc = pr.pcap_processor(self.pcap_filepath, str(self.do_extra_tests))
  53. self.pcap_proc.collect_statistics()
  54. self.pcap_proc.write_to_database(self.path_db)
  55. outstring_datasource = "by PCAP file processor."
  56. # only print summary of new db if -s flag not set
  57. if not flag_print_statistics and not flag_non_verbose:
  58. self.stats_summary_new_db()
  59. else:
  60. outstring_datasource = "from statistics database."
  61. # Load statistics from database
  62. self.file_info = self.stats_db.get_file_info()
  63. time_end = time.clock()
  64. print("Loaded file statistics in " + str(time_end - time_start)[:4] + " sec " + outstring_datasource)
  65. # Write statistics if param -e/--export provided
  66. if flag_write_file:
  67. self.write_statistics_to_file()
  68. # Print statistics if param -s/--statistics provided
  69. if flag_print_statistics:
  70. self.print_statistics()
  71. def get_file_information(self):
  72. """
  73. Returns a list of tuples, each containing a information of the file.
  74. :return: a list of tuples, each consisting of (description, value, unit), where unit is optional.
  75. """
  76. pdu_count = self.process_db_query("SELECT SUM(pktCount) FROM unrecognized_pdus")
  77. pdu_share = pdu_count / self.get_packet_count() * 100
  78. last_pdu_timestamp = self.process_db_query(
  79. "SELECT MAX(timestampLastOccurrence) FROM unrecognized_pdus")
  80. return [("Pcap file path", self.pcap_filepath),
  81. ("Total packet count", self.get_packet_count(), "packets"),
  82. ("Recognized packets", self.get_packet_count() - pdu_count, "packets"),
  83. ("Unrecognized packets", pdu_count, "PDUs"),
  84. ("% Recognized packets", 100 - pdu_share, "%"),
  85. ("% Unrecognized packets", pdu_share, "%"),
  86. ("Last unknown PDU", last_pdu_timestamp),
  87. ("Capture duration", self.get_capture_duration(), "seconds"),
  88. ("Capture start", "\t" + str(self.get_pcap_timestamp_start())),
  89. ("Capture end", "\t" + str(self.get_pcap_timestamp_end()))]
  90. def get_general_file_statistics(self):
  91. """
  92. Returns a list of tuples, each containing a file statistic.
  93. :return: a list of tuples, each consisting of (description, value, unit).
  94. """
  95. return [("Avg. packet rate", self.file_info['avgPacketRate'], "packets/sec"),
  96. ("Avg. packet size", self.file_info['avgPacketSize'], "kbytes"),
  97. ("Avg. packets sent", self.file_info['avgPacketsSentPerHost'], "packets"),
  98. ("Avg. bandwidth in", self.file_info['avgBandwidthIn'], "kbit/s"),
  99. ("Avg. bandwidth out", self.file_info['avgBandwidthOut'], "kbit/s")]
  100. @staticmethod
  101. def write_list(desc_val_unit_list, func, line_ending="\n"):
  102. """
  103. Takes a list of tuples (statistic name, statistic value, unit) as input, generates a string of these three
  104. values and applies the function func on this string.
  105. Before generating the string, it identifies text containing a float number, casts the string to a
  106. float and rounds the value to two decimal digits.
  107. :param desc_val_unit_list: The list of tuples consisting of (description, value, unit)
  108. :param func: The function to be applied to each generated string
  109. :param line_ending: The formatting string to be applied at the end of each string
  110. """
  111. for entry in desc_val_unit_list:
  112. # Convert text containing float into float
  113. (description, value) = entry[0:2]
  114. if isinstance(value, str) and "." in value:
  115. try:
  116. value = float(value)
  117. except ValueError:
  118. pass # do nothing -> value was not a float
  119. # round float
  120. if isinstance(value, float):
  121. value = round(value, 4)
  122. # write into file
  123. if len(entry) == 3:
  124. unit = entry[2]
  125. func(description + ":\t" + str(value) + " " + unit + line_ending)
  126. else:
  127. func(description + ":\t" + str(value) + line_ending)
  128. def print_statistics(self):
  129. """
  130. Prints the basic file statistics to the terminal.
  131. """
  132. print("\nPCAP FILE INFORMATION ------------------------------")
  133. Statistics.write_list(self.get_file_information(), print, "")
  134. print("\nGENERAL FILE STATISTICS ----------------------------")
  135. Statistics.write_list(self.get_general_file_statistics(), print, "")
  136. print("\n")
  137. @staticmethod
  138. def calculate_entropy(frequency: list, normalized: bool = False):
  139. """
  140. Calculates entropy and normalized entropy of list of elements that have specific frequency
  141. :param frequency: The frequency of the elements.
  142. :param normalized: Calculate normalized entropy
  143. :return: entropy or (entropy, normalized entropy)
  144. """
  145. entropy, normalized_ent, n = 0, 0, 0
  146. sum_freq = sum(frequency)
  147. for i, x in enumerate(frequency):
  148. p_x = float(frequency[i] / sum_freq)
  149. if p_x > 0:
  150. n += 1
  151. entropy += - p_x * log(p_x, 2)
  152. if normalized:
  153. if log(n) > 0:
  154. normalized_ent = entropy / log(n, 2)
  155. return entropy, normalized_ent
  156. else:
  157. return entropy
  158. def calculate_complement_packet_rates(self, pps):
  159. """
  160. Calculates the complement packet rates of the background traffic packet rates for each interval.
  161. Then normalize it to maximum boundary, which is the input parameter pps
  162. :return: normalized packet rates for each time interval.
  163. """
  164. result = self.process_db_query(
  165. "SELECT lastPktTimestamp,pktsCount FROM interval_statistics ORDER BY lastPktTimestamp")
  166. # print(result)
  167. bg_interval_pps = []
  168. complement_interval_pps = []
  169. intervals_sum = 0
  170. if result:
  171. # Get the interval in seconds
  172. for i, row in enumerate(result):
  173. if i < len(result) - 1:
  174. intervals_sum += ceil((int(result[i + 1][0]) * 10 ** -6) - (int(row[0]) * 10 ** -6))
  175. interval = intervals_sum / (len(result) - 1)
  176. # Convert timestamp from micro to seconds, convert packet rate "per interval" to "per second"
  177. for row in result:
  178. bg_interval_pps.append((int(row[0]) * 10 ** -6, int(row[1] / interval)))
  179. # Find max PPS
  180. max_pps = max(bg_interval_pps, key=itemgetter(1))[1]
  181. for row in bg_interval_pps:
  182. complement_interval_pps.append((row[0], int(pps * (max_pps - row[1]) / max_pps)))
  183. return complement_interval_pps
  184. def get_tests_statistics(self):
  185. """
  186. Writes the calculated basic defects tests statistics into a file.
  187. """
  188. # self.stats_db.process_user_defined_query output is list of tuples, thus, we ned [0][0] to access data
  189. def count_frequncy(values_list):
  190. values, freq_output = [], []
  191. for x in values_list:
  192. if x in values:
  193. freq_output[values.index(x)] += 1
  194. else:
  195. values.append(x)
  196. freq_output.append(1)
  197. return values, freq_output
  198. # Payload Tests
  199. sum_payload_count = self.stats_db.process_user_defined_query("SELECT sum(payloadCount) FROM "
  200. "interval_statistics")
  201. pkt_count = self.stats_db.process_user_defined_query("SELECT packetCount FROM file_statistics")
  202. if sum_payload_count and pkt_count:
  203. payload_ratio = 0
  204. if pkt_count[0][0] != 0:
  205. payload_ratio = float(sum_payload_count[0][0] / pkt_count[0][0] * 100)
  206. else:
  207. payload_ratio = -1
  208. # TCP checksum Tests
  209. incorrect_checksum_count = self.stats_db.process_user_defined_query(
  210. "SELECT sum(incorrectTCPChecksumCount) FROM interval_statistics")
  211. correct_checksum_count = self.stats_db.process_user_defined_query(
  212. "SELECT avg(correctTCPChecksumCount) FROM interval_statistics")
  213. if incorrect_checksum_count and correct_checksum_count:
  214. incorrect_checksum_ratio = 0
  215. if (incorrect_checksum_count[0][0] + correct_checksum_count[0][0]) != 0:
  216. incorrect_checksum_ratio = float(incorrect_checksum_count[0][0] /
  217. (incorrect_checksum_count[0][0] + correct_checksum_count[0][0]) * 100)
  218. else:
  219. incorrect_checksum_ratio = -1
  220. # IP Src & Dst Tests
  221. result = self.stats_db.process_user_defined_query("SELECT ipAddress,pktsSent,pktsReceived FROM ip_statistics")
  222. data, src_frequency, dst_frequency = [], [], []
  223. if result:
  224. for row in result:
  225. src_frequency.append(row[1])
  226. dst_frequency.append(row[2])
  227. ip_src_entropy, ip_src_norm_entropy = self.calculate_entropy(src_frequency, True)
  228. ip_dst_entropy, ip_dst_norm_entropy = self.calculate_entropy(dst_frequency, True)
  229. new_ip_count = self.stats_db.process_user_defined_query("SELECT newIPCount FROM interval_statistics")
  230. ip_novels_per_interval, ip_novels_per_interval_frequency = count_frequncy(new_ip_count)
  231. ip_novelty_dist_entropy = self.calculate_entropy(ip_novels_per_interval_frequency)
  232. # Ports Tests
  233. port0_count = self.stats_db.process_user_defined_query(
  234. "SELECT SUM(portCount) FROM ip_ports WHERE portNumber = 0")
  235. if not port0_count[0][0]:
  236. port0_count = 0
  237. else:
  238. port0_count = port0_count[0][0]
  239. # FIXME: could be extended
  240. reserved_port_count = self.stats_db.process_user_defined_query(
  241. "SELECT SUM(portCount) FROM ip_ports WHERE portNumber IN (100,114,1023,1024,49151,49152,65535)")
  242. if not reserved_port_count[0][0]:
  243. reserved_port_count = 0
  244. else:
  245. reserved_port_count = reserved_port_count[0][0]
  246. # TTL Tests
  247. result = self.stats_db.process_user_defined_query(
  248. "SELECT ttlValue,SUM(ttlCount) FROM ip_ttl GROUP BY ttlValue")
  249. data, frequency = [], []
  250. for row in result:
  251. frequency.append(row[1])
  252. ttl_entropy, ttl_norm_entropy = self.calculate_entropy(frequency, True)
  253. new_ttl_count = self.stats_db.process_user_defined_query("SELECT newTTLCount FROM interval_statistics")
  254. ttl_novels_per_interval, ttl_novels_per_interval_frequency = count_frequncy(new_ttl_count)
  255. ttl_novelty_dist_entropy = self.calculate_entropy(ttl_novels_per_interval_frequency)
  256. # Window Size Tests
  257. result = self.stats_db.process_user_defined_query("SELECT winSize,SUM(winCount) FROM tcp_win GROUP BY winSize")
  258. data, frequency = [], []
  259. for row in result:
  260. frequency.append(row[1])
  261. win_entropy, win_norm_entropy = self.calculate_entropy(frequency, True)
  262. new_win_size_count = self.stats_db.process_user_defined_query("SELECT newWinSizeCount FROM interval_statistics")
  263. win_novels_per_interval, win_novels_per_interval_frequency = count_frequncy(new_win_size_count)
  264. win_novelty_dist_entropy = self.calculate_entropy(win_novels_per_interval_frequency)
  265. # ToS Tests
  266. result = self.stats_db.process_user_defined_query(
  267. "SELECT tosValue,SUM(tosCount) FROM ip_tos GROUP BY tosValue")
  268. data, frequency = [], []
  269. for row in result:
  270. frequency.append(row[1])
  271. tos_entropy, tos_norm_entropy = self.calculate_entropy(frequency, True)
  272. new_tos_count = self.stats_db.process_user_defined_query("SELECT newToSCount FROM interval_statistics")
  273. tos_novels_per_interval, tos_novels_per_interval_frequency = count_frequncy(new_tos_count)
  274. tos_novelty_dist_entropy = self.calculate_entropy(tos_novels_per_interval_frequency)
  275. # MSS Tests
  276. result = self.stats_db.process_user_defined_query(
  277. "SELECT mssValue,SUM(mssCount) FROM tcp_mss GROUP BY mssValue")
  278. data, frequency = [], []
  279. for row in result:
  280. frequency.append(row[1])
  281. mss_entropy, mss_norm_entropy = self.calculate_entropy(frequency, True)
  282. new_mss_count = self.stats_db.process_user_defined_query("SELECT newMSSCount FROM interval_statistics")
  283. mss_novels_per_interval, mss_novels_per_interval_frequency = count_frequncy(new_mss_count)
  284. mss_novelty_dist_entropy = self.calculate_entropy(mss_novels_per_interval_frequency)
  285. result = self.stats_db.process_user_defined_query("SELECT SUM(mssCount) FROM tcp_mss WHERE mssValue > 1460")
  286. # The most used MSS < 1460. Calculate the ratio of the values bigger that 1460.
  287. if not result[0][0]:
  288. result = 0
  289. else:
  290. result = result[0][0]
  291. big_mss = (result / sum(frequency)) * 100
  292. output = []
  293. if self.do_extra_tests:
  294. output = [("Payload ratio", payload_ratio, "%"),
  295. ("Incorrect TCP checksum ratio", incorrect_checksum_ratio, "%")]
  296. output = output + [("# IP addresses", sum([x[0] for x in new_ip_count]), ""),
  297. ("IP Src Entropy", ip_src_entropy, ""),
  298. ("IP Src Normalized Entropy", ip_src_norm_entropy, ""),
  299. ("IP Dst Entropy", ip_dst_entropy, ""),
  300. ("IP Dst Normalized Entropy", ip_dst_norm_entropy, ""),
  301. ("IP Novelty Distribution Entropy", ip_novelty_dist_entropy, ""),
  302. ("# TTL values", sum([x[0] for x in new_ttl_count]), ""),
  303. ("TTL Entropy", ttl_entropy, ""),
  304. ("TTL Normalized Entropy", ttl_norm_entropy, ""),
  305. ("TTL Novelty Distribution Entropy", ttl_novelty_dist_entropy, ""),
  306. ("# WinSize values", sum([x[0] for x in new_win_size_count]), ""),
  307. ("WinSize Entropy", win_entropy, ""),
  308. ("WinSize Normalized Entropy", win_norm_entropy, ""),
  309. ("WinSize Novelty Distribution Entropy", win_novelty_dist_entropy, ""),
  310. ("# ToS values", sum([x[0] for x in new_tos_count]), ""),
  311. ("ToS Entropy", tos_entropy, ""),
  312. ("ToS Normalized Entropy", tos_norm_entropy, ""),
  313. ("ToS Novelty Distribution Entropy", tos_novelty_dist_entropy, ""),
  314. ("# MSS values", sum([x[0] for x in new_mss_count]), ""),
  315. ("MSS Entropy", mss_entropy, ""),
  316. ("MSS Normalized Entropy", mss_norm_entropy, ""),
  317. ("MSS Novelty Distribution Entropy", mss_novelty_dist_entropy, ""),
  318. ("======================", "", "")]
  319. # Reasoning the statistics values
  320. if self.do_extra_tests:
  321. if payload_ratio > 80:
  322. output.append(("WARNING: Too high payload ratio", payload_ratio, "%."))
  323. if payload_ratio < 30:
  324. output.append(("WARNING: Too low payload ratio", payload_ratio, "% (Injecting attacks that are carried "
  325. "out in the packet payloads is not "
  326. "recommmanded)."))
  327. if incorrect_checksum_ratio > 5:
  328. output.append(("WARNING: High incorrect TCP checksum ratio", incorrect_checksum_ratio, "%."))
  329. if ip_src_norm_entropy > 0.65:
  330. output.append(("WARNING: High IP source normalized entropy", ip_src_norm_entropy, "."))
  331. if ip_src_norm_entropy < 0.2:
  332. output.append(("WARNING: Low IP source normalized entropy", ip_src_norm_entropy, "."))
  333. if ip_dst_norm_entropy > 0.65:
  334. output.append(("WARNING: High IP destination normalized entropy", ip_dst_norm_entropy, "."))
  335. if ip_dst_norm_entropy < 0.2:
  336. output.append(("WARNING: Low IP destination normalized entropy", ip_dst_norm_entropy, "."))
  337. if ttl_norm_entropy > 0.65:
  338. output.append(("WARNING: High TTL normalized entropy", ttl_norm_entropy, "."))
  339. if ttl_norm_entropy < 0.2:
  340. output.append(("WARNING: Low TTL normalized entropy", ttl_norm_entropy, "."))
  341. if ttl_novelty_dist_entropy < 1:
  342. output.append(("WARNING: Too low TTL novelty distribution entropy", ttl_novelty_dist_entropy,
  343. "(The distribution of the novel TTL values is suspicious)."))
  344. if win_norm_entropy > 0.6:
  345. output.append(("WARNING: High Window Size normalized entropy", win_norm_entropy, "."))
  346. if win_norm_entropy < 0.1:
  347. output.append(("WARNING: Low Window Size normalized entropy", win_norm_entropy, "."))
  348. if win_novelty_dist_entropy < 4:
  349. output.append(("WARNING: Low Window Size novelty distribution entropy", win_novelty_dist_entropy,
  350. "(The distribution of the novel Window Size values is suspicious)."))
  351. if tos_norm_entropy > 0.4:
  352. output.append(("WARNING: High ToS normalized entropy", tos_norm_entropy, "."))
  353. if tos_norm_entropy < 0.1:
  354. output.append(("WARNING: Low ToS normalized entropy", tos_norm_entropy, "."))
  355. if tos_novelty_dist_entropy < 0.5:
  356. output.append(("WARNING: Low ToS novelty distribution entropy", tos_novelty_dist_entropy,
  357. "(The distribution of the novel ToS values is suspicious)."))
  358. if mss_norm_entropy > 0.4:
  359. output.append(("WARNING: High MSS normalized entropy", mss_norm_entropy, "."))
  360. if mss_norm_entropy < 0.1:
  361. output.append(("WARNING: Low MSS normalized entropy", mss_norm_entropy, "."))
  362. if mss_novelty_dist_entropy < 0.5:
  363. output.append(("WARNING: Low MSS novelty distribution entropy", mss_novelty_dist_entropy,
  364. "(The distribution of the novel MSS values is suspicious)."))
  365. if big_mss > 50:
  366. output.append(("WARNING: High ratio of MSS > 1460", big_mss, "% (High fragmentation rate in Ethernet)."))
  367. if port0_count > 0:
  368. output.append(("WARNING: Port number 0 is used in ", port0_count, "packets (awkward-looking port)."))
  369. if reserved_port_count > 0:
  370. output.append(("WARNING: Reserved port numbers are used in ", reserved_port_count,
  371. "packets (uncommonly-used ports)."))
  372. return output
  373. def write_statistics_to_file(self):
  374. """
  375. Writes the calculated basic statistics into a file.
  376. """
  377. def _write_header(title: str):
  378. """
  379. Writes the section header into the open file.
  380. :param title: The section title
  381. """
  382. target.write("====================== \n")
  383. target.write(title + " \n")
  384. target.write("====================== \n")
  385. target = open(self.pcap_filepath + ".stat", 'w')
  386. target.truncate()
  387. _write_header("PCAP file information")
  388. Statistics.write_list(self.get_file_information(), target.write)
  389. _write_header("General statistics")
  390. Statistics.write_list(self.get_general_file_statistics(), target.write)
  391. _write_header("Tests statistics")
  392. Statistics.write_list(self.get_tests_statistics(), target.write)
  393. target.close()
  394. def get_capture_duration(self):
  395. """
  396. :return: The duration of the capture in seconds
  397. """
  398. return self.file_info['captureDuration']
  399. def get_pcap_timestamp_start(self):
  400. """
  401. :return: The timestamp of the first packet in the PCAP file
  402. """
  403. return self.file_info['timestampFirstPacket']
  404. def get_pcap_timestamp_end(self):
  405. """
  406. :return: The timestamp of the last packet in the PCAP file
  407. """
  408. return self.file_info['timestampLastPacket']
  409. def get_pps_sent(self, ip_address: str):
  410. """
  411. Calculates the sent packets per seconds for a given IP address.
  412. :param ip_address: The IP address whose packets per second should be calculated
  413. :return: The sent packets per seconds for the given IP address
  414. """
  415. packets_sent = self.stats_db.process_db_query("SELECT pktsSent from ip_statistics WHERE ipAddress=?", False,
  416. (ip_address,))
  417. capture_duration = float(self.get_capture_duration())
  418. return int(float(packets_sent) / capture_duration)
  419. def get_pps_received(self, ip_address: str):
  420. """
  421. Calculate the packets per second received for a given IP address.
  422. :param ip_address: The IP address used for the calculation
  423. :return: The number of packets per second received
  424. """
  425. packets_received = self.stats_db.process_db_query("SELECT pktsReceived FROM ip_statistics WHERE ipAddress=?",
  426. False,
  427. (ip_address,))
  428. capture_duration = float(self.get_capture_duration())
  429. return int(float(packets_received) / capture_duration)
  430. def get_packet_count(self):
  431. """
  432. :return: The number of packets in the loaded PCAP file
  433. """
  434. return self.file_info['packetCount']
  435. def get_most_used_ip_address(self):
  436. """
  437. :return: The IP address/addresses with the highest sum of packets sent and received
  438. """
  439. return Util.handle_most_used_outputs(self.process_db_query("most_used(ipAddress)"))
  440. def get_ttl_distribution(self, ip_address: str):
  441. result = self.process_db_query('SELECT ttlValue, ttlCount from ip_ttl WHERE ipAddress="' + ip_address + '"')
  442. result_dict = {key: value for (key, value) in result}
  443. return result_dict
  444. def get_mss_distribution(self, ip_address: str):
  445. result = self.process_db_query('SELECT mssValue, mssCount from tcp_mss WHERE ipAddress="' + ip_address + '"')
  446. result_dict = {key: value for (key, value) in result}
  447. return result_dict
  448. def get_win_distribution(self, ip_address: str):
  449. result = self.process_db_query('SELECT winSize, winCount from tcp_win WHERE ipAddress="' + ip_address + '"')
  450. result_dict = {key: value for (key, value) in result}
  451. return result_dict
  452. def get_tos_distribution(self, ip_address: str):
  453. result = self.process_db_query('SELECT tosValue, tosCount from ip_tos WHERE ipAddress="' + ip_address + '"')
  454. result_dict = {key: value for (key, value) in result}
  455. return result_dict
  456. def get_ip_address_count(self):
  457. return self.process_db_query("SELECT COUNT(*) FROM ip_statistics")
  458. def get_ip_addresses(self):
  459. return self.process_db_query("SELECT ipAddress FROM ip_statistics")
  460. def get_random_ip_address(self, count: int = 1):
  461. """
  462. :param count: The number of IP addreses to return
  463. :return: A randomly chosen IP address from the dataset or iff param count is greater than one, a list of
  464. randomly chosen IP addresses
  465. """
  466. ip_address_list = self.process_db_query("SELECT ipAddress from ip_statistics ORDER BY ipAddress ASC")
  467. if count == 1:
  468. return random.choice(ip_address_list)
  469. else:
  470. result_list = []
  471. for i in range(0, count):
  472. random_ip = random.choice(ip_address_list)
  473. result_list.append(random_ip)
  474. ip_address_list.remove(random_ip)
  475. return result_list
  476. def get_ip_address_from_mac(self, mac_address: str):
  477. """
  478. :param mac_address: the MAC address of which the IP shall be returned, if existing in DB
  479. :return: the IP address used in the dataset by a given MAC address
  480. """
  481. return self.process_db_query("SELECT DISTINCT ipAddress FROM ip_mac WHERE macAddress = '" + mac_address + "'")
  482. def get_mac_address(self, ip_address: str):
  483. """
  484. :return: The MAC address used in the dataset for the given IP address.
  485. """
  486. return self.process_db_query("SELECT DISTINCT macAddress from ip_mac WHERE ipAddress = '" + ip_address + "'")
  487. def get_most_used_ttl_value(self):
  488. """
  489. :return: The most used TTL value.
  490. """
  491. return self.process_db_query("SELECT ttlValue FROM (SELECT ttlValue, SUM(ttlCount) as occ FROM ip_ttl GROUP BY "
  492. "ttlValue) WHERE occ=(SELECT SUM(ttlCount) as occ FROM ip_ttl GROUP BY ttlValue "
  493. "ORDER BY occ DESC LIMIT 1) ORDER BY ttlValue ASC")
  494. def get_most_used_ip_class(self):
  495. """
  496. :return: The most used IP class.
  497. """
  498. return self.process_db_query("SELECT ipClass FROM (SELECT ipClass, COUNT(*) as occ from ip_statistics GROUP BY "
  499. "ipClass ORDER BY occ DESC) WHERE occ=(SELECT COUNT(*) as occ from ip_statistics "
  500. "GROUP BY ipClass ORDER BY occ DESC LIMIT 1) ORDER BY ipClass ASC")
  501. def get_most_used_win_size(self):
  502. """
  503. :return: The most used window size.
  504. """
  505. return self.process_db_query("SELECT winSize FROM (SELECT winSize, SUM(winCount) as occ FROM tcp_win GROUP BY "
  506. "winSize) WHERE occ=(SELECT SUM(winCount) as occ FROM tcp_win GROUP BY winSize "
  507. "ORDER BY occ DESC LIMIT 1) ORDER BY winSize ASC")
  508. def get_most_used_mss_value(self):
  509. """
  510. :return: The most used mss value.
  511. """
  512. return self.process_db_query("SELECT mssValue FROM (SELECT mssValue, SUM(mssCount) as occ FROM tcp_mss GROUP BY"
  513. " mssValue) WHERE occ=(SELECT SUM(mssCount) as occ FROM tcp_mss GROUP BY mssValue "
  514. "ORDER BY occ DESC LIMIT 1) ORDER BY mssValue ASC")
  515. def get_most_used_mss(self, ip_address: str):
  516. """
  517. :param ip_address: The IP address whose used MSS should be determined
  518. :return: The TCP MSS value used by the IP address, or if the IP addresses never specified a MSS,
  519. then None is returned
  520. """
  521. mss_value = self.process_db_query('SELECT mssValue from tcp_mss WHERE ipAddress="' + ip_address +
  522. '" AND mssCount == (SELECT MAX(mssCount) from tcp_mss WHERE ipAddress="'
  523. + ip_address + '")')
  524. if isinstance(mss_value, int):
  525. return mss_value
  526. elif isinstance(mss_value, list):
  527. if len(mss_value) == 0:
  528. return None
  529. else:
  530. mss_value.sort()
  531. return mss_value[0]
  532. else:
  533. return None
  534. def get_most_used_ttl(self, ip_address: str):
  535. """
  536. :param ip_address: The IP address whose used TTL should be determined
  537. :return: The TTL value used by the IP address, or if the IP addresses never specified a TTL,
  538. then None is returned
  539. """
  540. ttl_value = self.process_db_query('SELECT ttlValue from ip_ttl WHERE ipAddress="' + ip_address +
  541. '" AND ttlCount == (SELECT MAX(ttlCount) from ip_ttl WHERE ipAddress="'
  542. + ip_address + '")')
  543. if isinstance(ttl_value, int):
  544. return ttl_value
  545. elif isinstance(ttl_value, list):
  546. if len(ttl_value) == 0:
  547. return None
  548. else:
  549. ttl_value.sort()
  550. return ttl_value[0]
  551. else:
  552. return None
  553. def get_rnd_win_size(self, pkts_num):
  554. """
  555. :param pkts_num: maximum number of window sizes, that should be returned
  556. :return: A list of randomly chosen window sizes with given length.
  557. """
  558. sql_return = self.process_db_query("SELECT DISTINCT winSize FROM tcp_win ORDER BY winsize ASC;")
  559. if not isinstance(sql_return, list):
  560. return [sql_return]
  561. result = []
  562. for i in range(0, min(pkts_num, len(sql_return))):
  563. result.append(random.choice(sql_return))
  564. sql_return.remove(result[i])
  565. return result
  566. def get_statistics_database(self):
  567. """
  568. :return: A reference to the statistics database object
  569. """
  570. return self.stats_db
  571. def process_db_query(self, query_string_in: str, print_results: bool = False):
  572. """
  573. Executes a string identified previously as a query. This can be a standard SQL SELECT/INSERT query or a named
  574. query.
  575. :param query_string_in: The query to be processed
  576. :param print_results: Indicates whether the results should be printed to terminal
  577. :return: The result of the query
  578. """
  579. return self.stats_db.process_db_query(query_string_in, print_results)
  580. def is_query(self, value: str):
  581. """
  582. Checks whether the given string is a standard SQL query (SELECT, INSERT) or a named query.
  583. :param value: The string to be checked
  584. :return: True if the string is recognized as a query, otherwise False.
  585. """
  586. if not isinstance(value, str):
  587. return False
  588. else:
  589. return (any(x in value.lower().strip() for x in self.stats_db.get_all_named_query_keywords()) or
  590. any(x in value.lower().strip() for x in self.stats_db.get_all_sql_query_keywords()))
  591. @staticmethod
  592. def calculate_standard_deviation(lst):
  593. """
  594. Calculates the standard deviation of a list of numbers.
  595. :param lst: The list of numbers to calculate its SD.
  596. """
  597. num_items = len(lst)
  598. mean = sum(lst) / num_items
  599. differences = [x - mean for x in lst]
  600. sq_differences = [d ** 2 for d in differences]
  601. ssd = sum(sq_differences)
  602. variance = ssd / num_items
  603. sd = sqrt(variance)
  604. return sd
  605. def plot_statistics(self, entropy: int, file_format: str = 'pdf'): # 'png'
  606. """
  607. Plots the statistics associated with the dataset.
  608. :param entropy: the statistics entropy
  609. :param file_format: The format to be used to save the statistics diagrams.
  610. """
  611. def plot_distribution(query_output, title, x_label, y_label, file_ending: str):
  612. plt.gcf().clear()
  613. graphx, graphy = [], []
  614. for row in query_output:
  615. graphx.append(row[0])
  616. graphy.append(row[1])
  617. plt.autoscale(enable=True, axis='both')
  618. plt.title(title)
  619. plt.xlabel(x_label)
  620. plt.ylabel(y_label)
  621. width = 0.1
  622. plt.xlim([0, (max(graphx) * 1.1)])
  623. plt.grid(True)
  624. plt.bar(graphx, graphy, width, align='center', linewidth=1, color='red', edgecolor='red')
  625. out = self.pcap_filepath.replace('.pcap', '_plot-' + title + file_ending)
  626. plt.savefig(out, dpi=500)
  627. return out
  628. def plot_ttl(file_ending: str):
  629. query_output = self.stats_db.process_user_defined_query(
  630. "SELECT ttlValue, SUM(ttlCount) FROM ip_ttl GROUP BY ttlValue")
  631. title = "TTL Distribution"
  632. x_label = "TTL Value"
  633. y_label = "Number of Packets"
  634. if query_output:
  635. return plot_distribution(query_output, title, x_label, y_label, file_ending)
  636. def plot_mss(file_ending: str):
  637. query_output = self.stats_db.process_user_defined_query(
  638. "SELECT mssValue, SUM(mssCount) FROM tcp_mss GROUP BY mssValue")
  639. title = "MSS Distribution"
  640. x_label = "MSS Value"
  641. y_label = "Number of Packets"
  642. if query_output:
  643. return plot_distribution(query_output, title, x_label, y_label, file_ending)
  644. def plot_win(file_ending: str):
  645. query_output = self.stats_db.process_user_defined_query(
  646. "SELECT winSize, SUM(winCount) FROM tcp_win GROUP BY winSize")
  647. title = "Window Size Distribution"
  648. x_label = "Window Size"
  649. y_label = "Number of Packets"
  650. if query_output:
  651. return plot_distribution(query_output, title, x_label, y_label, file_ending)
  652. def plot_protocol(file_ending: str):
  653. plt.gcf().clear()
  654. result = self.stats_db.process_user_defined_query(
  655. "SELECT protocolName, SUM(protocolCount) FROM ip_protocols GROUP BY protocolName")
  656. if result:
  657. graphx, graphy = [], []
  658. for row in result:
  659. graphx.append(row[0])
  660. graphy.append(row[1])
  661. plt.autoscale(enable=True, axis='both')
  662. plt.title("Protocols Distribution")
  663. plt.xlabel('Protocols')
  664. plt.ylabel('Number of Packets')
  665. width = 0.1
  666. plt.xlim([0, len(graphx)])
  667. plt.grid(True)
  668. # Protocols' names on x-axis
  669. x = range(0, len(graphx))
  670. my_xticks = graphx
  671. plt.xticks(x, my_xticks)
  672. plt.bar(x, graphy, width, align='center', linewidth=1, color='red', edgecolor='red')
  673. out = self.pcap_filepath.replace('.pcap', '_plot-protocol' + file_ending)
  674. plt.savefig(out, dpi=500)
  675. return out
  676. else:
  677. print("Error plot protocol: No protocol values found!")
  678. def plot_port(file_ending: str):
  679. plt.gcf().clear()
  680. result = self.stats_db.process_user_defined_query(
  681. "SELECT portNumber, SUM(portCount) FROM ip_ports GROUP BY portNumber")
  682. graphx, graphy = [], []
  683. for row in result:
  684. graphx.append(row[0])
  685. graphy.append(row[1])
  686. plt.autoscale(enable=True, axis='both')
  687. plt.title("Ports Distribution")
  688. plt.xlabel('Ports Numbers')
  689. plt.ylabel('Number of Packets')
  690. width = 0.1
  691. plt.xlim([0, max(graphx)])
  692. plt.grid(True)
  693. plt.bar(graphx, graphy, width, align='center', linewidth=1, color='red', edgecolor='red')
  694. out = self.pcap_filepath.replace('.pcap', '_plot-port' + file_ending)
  695. plt.savefig(out, dpi=500)
  696. return out
  697. # This distribution is not drawable for big datasets
  698. def plot_ip_src(file_ending: str):
  699. plt.gcf().clear()
  700. result = self.stats_db.process_user_defined_query(
  701. "SELECT ipAddress, pktsSent FROM ip_statistics")
  702. graphx, graphy = [], []
  703. for row in result:
  704. graphx.append(row[0])
  705. graphy.append(row[1])
  706. plt.autoscale(enable=True, axis='both')
  707. plt.title("Source IP Distribution")
  708. plt.xlabel('Source IP')
  709. plt.ylabel('Number of Packets')
  710. width = 0.1
  711. plt.xlim([0, len(graphx)])
  712. plt.grid(True)
  713. # IPs on x-axis
  714. x = range(0, len(graphx))
  715. my_xticks = graphx
  716. plt.xticks(x, my_xticks, rotation='vertical', fontsize=5)
  717. plt.tight_layout()
  718. # limit the number of xticks
  719. plt.locator_params(axis='x', nbins=20)
  720. plt.bar(x, graphy, width, align='center', linewidth=1, color='red', edgecolor='red')
  721. out = self.pcap_filepath.replace('.pcap', '_plot-ip-src' + file_ending)
  722. plt.savefig(out, dpi=500)
  723. return out
  724. # This distribution is not drawable for big datasets
  725. def plot_ip_dst(file_ending: str):
  726. plt.gcf().clear()
  727. result = self.stats_db.process_user_defined_query(
  728. "SELECT ipAddress, pktsReceived FROM ip_statistics")
  729. graphx, graphy = [], []
  730. for row in result:
  731. graphx.append(row[0])
  732. graphy.append(row[1])
  733. plt.autoscale(enable=True, axis='both')
  734. plt.title("Destination IP Distribution")
  735. plt.xlabel('Destination IP')
  736. plt.ylabel('Number of Packets')
  737. width = 0.1
  738. plt.xlim([0, len(graphx)])
  739. plt.grid(True)
  740. # IPs on x-axis
  741. x = range(0, len(graphx))
  742. my_xticks = graphx
  743. plt.xticks(x, my_xticks, rotation='vertical', fontsize=5)
  744. plt.tight_layout()
  745. # limit the number of xticks
  746. plt.locator_params(axis='x', nbins=20)
  747. plt.bar(x, graphy, width, align='center', linewidth=1, color='red', edgecolor='red')
  748. out = self.pcap_filepath.replace('.pcap', '_plot-ip-dst' + file_ending)
  749. plt.savefig(out, dpi=500)
  750. return out
  751. def plot_interval_statistics(query_output, title, x_label, y_label, file_ending: str):
  752. plt.gcf().clear()
  753. graphx, graphy = [], []
  754. for row in query_output:
  755. graphx.append(row[0])
  756. graphy.append(row[1])
  757. plt.autoscale(enable=True, axis='both')
  758. plt.title(title)
  759. plt.xlabel(x_label)
  760. plt.ylabel(y_label)
  761. width = 0.5
  762. plt.xlim([0, len(graphx)])
  763. plt.grid(True)
  764. # timestamp on x-axis
  765. x = range(0, len(graphx))
  766. # limit the number of xticks
  767. plt.locator_params(axis='x', nbins=20)
  768. plt.bar(x, graphy, width, align='center', linewidth=1, color='red', edgecolor='red')
  769. out = self.pcap_filepath.replace('.pcap', '_plot-' + title + file_ending)
  770. plt.savefig(out, dpi=500)
  771. return out
  772. def plot_interval_pkt_count(file_ending: str):
  773. query_output = self.stats_db.process_user_defined_query(
  774. "SELECT lastPktTimestamp, pktsCount FROM interval_statistics ORDER BY lastPktTimestamp")
  775. title = "Packet Rate"
  776. x_label = "Time Interval"
  777. y_label = "Number of Packets"
  778. if query_output:
  779. return plot_interval_statistics(query_output, title, x_label, y_label, file_ending)
  780. def plot_interval_ip_src_ent(file_ending: str):
  781. query_output = self.stats_db.process_user_defined_query(
  782. "SELECT lastPktTimestamp, ipSrcEntropy FROM interval_statistics ORDER BY lastPktTimestamp")
  783. title = "Source IP Entropy"
  784. x_label = "Time Interval"
  785. y_label = "Entropy"
  786. if query_output:
  787. return plot_interval_statistics(query_output, title, x_label, y_label, file_ending)
  788. def plot_interval_ip_dst_ent(file_ending: str):
  789. query_output = self.stats_db.process_user_defined_query(
  790. "SELECT lastPktTimestamp, ipDstEntropy FROM interval_statistics ORDER BY lastPktTimestamp")
  791. title = "Destination IP Entropy"
  792. x_label = "Time Interval"
  793. y_label = "Entropy"
  794. if query_output:
  795. return plot_interval_statistics(query_output, title, x_label, y_label, file_ending)
  796. def plot_interval_new_ip(file_ending: str):
  797. query_output = self.stats_db.process_user_defined_query(
  798. "SELECT lastPktTimestamp, newIPCount FROM interval_statistics ORDER BY lastPktTimestamp")
  799. title = "IP Novelty Distribution"
  800. x_label = "Time Interval"
  801. y_label = "Novel values count"
  802. if query_output:
  803. return plot_interval_statistics(query_output, title, x_label, y_label, file_ending)
  804. def plot_interval_new_port(file_ending: str):
  805. query_output = self.stats_db.process_user_defined_query(
  806. "SELECT lastPktTimestamp, newPortCount FROM interval_statistics ORDER BY lastPktTimestamp")
  807. title = "Port Novelty Distribution"
  808. x_label = "Time Interval"
  809. y_label = "Novel values count"
  810. if query_output:
  811. return plot_interval_statistics(query_output, title, x_label, y_label, file_ending)
  812. def plot_interval_new_ttl(file_ending: str):
  813. query_output = self.stats_db.process_user_defined_query(
  814. "SELECT lastPktTimestamp, newTTLCount FROM interval_statistics ORDER BY lastPktTimestamp")
  815. title = "TTL Novelty Distribution"
  816. x_label = "Time Interval"
  817. y_label = "Novel values count"
  818. if query_output:
  819. return plot_interval_statistics(query_output, title, x_label, y_label, file_ending)
  820. def plot_interval_new_tos(file_ending: str):
  821. query_output = self.stats_db.process_user_defined_query(
  822. "SELECT lastPktTimestamp, newToSCount FROM interval_statistics ORDER BY lastPktTimestamp")
  823. title = "ToS Novelty Distribution"
  824. x_label = "Time Interval"
  825. y_label = "Novel values count"
  826. if query_output:
  827. return plot_interval_statistics(query_output, title, x_label, y_label, file_ending)
  828. def plot_interval_new_win_size(file_ending: str):
  829. query_output = self.stats_db.process_user_defined_query(
  830. "SELECT lastPktTimestamp, newWinSizeCount FROM interval_statistics ORDER BY lastPktTimestamp")
  831. title = "Window Size Novelty Distribution"
  832. x_label = "Time Interval"
  833. y_label = "Novel values count"
  834. if query_output:
  835. return plot_interval_statistics(query_output, title, x_label, y_label, file_ending)
  836. def plot_interval_new_mss(file_ending: str):
  837. query_output = self.stats_db.process_user_defined_query(
  838. "SELECT lastPktTimestamp, newMSSCount FROM interval_statistics ORDER BY lastPktTimestamp")
  839. title = "MSS Novelty Distribution"
  840. x_label = "Time Interval"
  841. y_label = "Novel values count"
  842. if query_output:
  843. return plot_interval_statistics(query_output, title, x_label, y_label, file_ending)
  844. def plot_interval_ip_dst_cum_ent(file_ending: str):
  845. plt.gcf().clear()
  846. result = self.stats_db.process_user_defined_query(
  847. "SELECT lastPktTimestamp, ipDstCumEntropy FROM interval_statistics ORDER BY lastPktTimestamp")
  848. graphx, graphy = [], []
  849. for row in result:
  850. graphx.append(row[0])
  851. graphy.append(row[1])
  852. # If entropy was not calculated do not plot the graph
  853. if graphy[0] != -1:
  854. plt.autoscale(enable=True, axis='both')
  855. plt.title("Destination IP Cumulative Entropy")
  856. # plt.xlabel('Timestamp')
  857. plt.xlabel('Time Interval')
  858. plt.ylabel('Entropy')
  859. plt.xlim([0, len(graphx)])
  860. plt.grid(True)
  861. # timestamp on x-axis
  862. x = range(0, len(graphx))
  863. # my_xticks = graphx
  864. # plt.xticks(x, my_xticks, rotation='vertical', fontsize=5)
  865. # plt.tight_layout()
  866. # limit the number of xticks
  867. plt.locator_params(axis='x', nbins=20)
  868. plt.plot(x, graphy, 'r')
  869. out = self.pcap_filepath.replace('.pcap', '_plot-interval-ip-dst-cum-ent' + file_ending)
  870. plt.savefig(out, dpi=500)
  871. return out
  872. def plot_interval_ip_src_cum_ent(file_ending: str):
  873. plt.gcf().clear()
  874. result = self.stats_db.process_user_defined_query(
  875. "SELECT lastPktTimestamp, ipSrcCumEntropy FROM interval_statistics ORDER BY lastPktTimestamp")
  876. graphx, graphy = [], []
  877. for row in result:
  878. graphx.append(row[0])
  879. graphy.append(row[1])
  880. # If entropy was not calculated do not plot the graph
  881. if graphy[0] != -1:
  882. plt.autoscale(enable=True, axis='both')
  883. plt.title("Source IP Cumulative Entropy")
  884. # plt.xlabel('Timestamp')
  885. plt.xlabel('Time Interval')
  886. plt.ylabel('Entropy')
  887. plt.xlim([0, len(graphx)])
  888. plt.grid(True)
  889. # timestamp on x-axis
  890. x = range(0, len(graphx))
  891. # my_xticks = graphx
  892. # plt.xticks(x, my_xticks, rotation='vertical', fontsize=5)
  893. # plt.tight_layout()
  894. # limit the number of xticks
  895. plt.locator_params(axis='x', nbins=20)
  896. plt.plot(x, graphy, 'r')
  897. out = self.pcap_filepath.replace('.pcap', '_plot-interval-ip-src-cum-ent' + file_ending)
  898. plt.savefig(out, dpi=500)
  899. return out
  900. ttl_out_path = plot_ttl('.' + file_format)
  901. mss_out_path = plot_mss('.' + file_format)
  902. win_out_path = plot_win('.' + file_format)
  903. protocol_out_path = plot_protocol('.' + file_format)
  904. plot_interval_pktCount = plot_interval_pkt_count('.' + file_format)
  905. if entropy:
  906. plot_interval_ip_src_ent = plot_interval_ip_src_ent('.' + file_format)
  907. plot_interval_ip_dst_ent = plot_interval_ip_dst_ent('.' + file_format)
  908. plot_interval_ip_src_cum_ent = plot_interval_ip_src_cum_ent('.' + file_format)
  909. plot_interval_ip_dst_cum_ent = plot_interval_ip_dst_cum_ent('.' + file_format)
  910. plot_interval_new_ip = plot_interval_new_ip('.' + file_format)
  911. plot_interval_new_port = plot_interval_new_port('.' + file_format)
  912. plot_interval_new_ttl = plot_interval_new_ttl('.' + file_format)
  913. plot_interval_new_tos = plot_interval_new_tos('.' + file_format)
  914. plot_interval_new_win_size = plot_interval_new_win_size('.' + file_format)
  915. plot_interval_new_mss = plot_interval_new_mss('.' + file_format)
  916. # Time consuming plot
  917. # port_out_path = plot_port('.' + format)
  918. # Not drawable for too many IPs
  919. # ip_src_out_path = plot_ip_src('.' + format)
  920. # ip_dst_out_path = plot_ip_dst('.' + format)
  921. print("Saved plots in the input PCAP directory.")
  922. def stats_summary_post_attack(self, added_packets):
  923. """
  924. Prints a summary of relevant statistics after an attack is injected
  925. :param added_packets: sum of packets added by attacks, gets updated if more than one attack
  926. :return: None
  927. """
  928. total_packet_count = self.get_packet_count() + added_packets
  929. added_packets_share = added_packets / total_packet_count * 100
  930. timespan = self.get_capture_duration()
  931. summary = [("Total packet count", total_packet_count, "packets"),
  932. ("Added packet count", added_packets, "packets"),
  933. ("Share of added packets", added_packets_share, "%"),
  934. ("Capture duration", timespan, "seconds")]
  935. print("\nPOST INJECTION STATISTICS SUMMARY --------------------------")
  936. self.write_list(summary, print, "")
  937. print("------------------------------------------------------------")
  938. def stats_summary_new_db(self):
  939. """
  940. Prints a summary of relevant statistics when a new db is created
  941. :return: None
  942. """
  943. self.file_info = self.stats_db.get_file_info()
  944. print("\nNew database has been generated, printing statistics summary... ")
  945. total_packet_count = self.get_packet_count()
  946. pdu_count = self.process_db_query("SELECT SUM(pktCount) FROM unrecognized_pdus")
  947. if pdu_count is None:
  948. pdu_count = 0
  949. pdu_share = pdu_count / total_packet_count * 100
  950. last_pdu_timestamp = self.process_db_query(
  951. "SELECT MAX(timestampLastOccurrence) FROM unrecognized_pdus")
  952. timespan = self.get_capture_duration()
  953. summary = [("Total packet count", total_packet_count, "packets"),
  954. ("Recognized packets", total_packet_count - pdu_count, "packets"),
  955. ("Unrecognized packets", pdu_count, "PDUs"),
  956. ("% Recognized packets", 100 - pdu_share, "%"),
  957. ("% Unrecognized packets", pdu_share, "%"),
  958. ("Last unknown PDU", last_pdu_timestamp),
  959. ("Capture duration", timespan, "seconds")]
  960. print("\nPCAP FILE STATISTICS SUMMARY ------------------------------")
  961. self.write_list(summary, print, "")
  962. print("------------------------------------------------------------")