3
0

Statistics.py 49 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079
  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("all(ipAddress)")
  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('ipAddress(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('macAddress(ipAddress=' + ip_address + ")")
  487. def get_most_used_mss(self, ip_address: str):
  488. """
  489. :param ip_address: The IP address whose used MSS should be determined
  490. :return: The TCP MSS value used by the IP address, or if the IP addresses never specified a MSS,
  491. then None is returned
  492. """
  493. mss_value = self.process_db_query('SELECT mssValue from tcp_mss WHERE ipAddress="' + ip_address +
  494. '" AND mssCount == (SELECT MAX(mssCount) from tcp_mss WHERE ipAddress="'
  495. + ip_address + '")')
  496. if isinstance(mss_value, int):
  497. return mss_value
  498. elif isinstance(mss_value, list):
  499. if len(mss_value) == 0:
  500. return None
  501. else:
  502. mss_value.sort()
  503. return mss_value[0]
  504. else:
  505. return None
  506. def get_most_used_ttl(self, ip_address: str):
  507. """
  508. :param ip_address: The IP address whose used TTL should be determined
  509. :return: The TTL value used by the IP address, or if the IP addresses never specified a TTL,
  510. then None is returned
  511. """
  512. ttl_value = self.process_db_query('SELECT ttlValue from ip_ttl WHERE ipAddress="' + ip_address +
  513. '" AND ttlCount == (SELECT MAX(ttlCount) from ip_ttl WHERE ipAddress="'
  514. + ip_address + '")')
  515. if isinstance(ttl_value, int):
  516. return ttl_value
  517. elif isinstance(ttl_value, list):
  518. if len(ttl_value) == 0:
  519. return None
  520. else:
  521. ttl_value.sort()
  522. return ttl_value[0]
  523. else:
  524. return None
  525. def get_rnd_win_size(self, pkts_num):
  526. """
  527. :param pkts_num: maximum number of window sizes, that should be returned
  528. :return: A list of randomly chosen window sizes with given length.
  529. """
  530. sql_return = self.process_db_query("SELECT DISTINCT winSize FROM tcp_win ORDER BY winsize ASC;")
  531. if not isinstance(sql_return, list):
  532. return [sql_return]
  533. result = []
  534. for i in range(0, min(pkts_num, len(sql_return))):
  535. result.append(random.choice(sql_return))
  536. sql_return.remove(result[i])
  537. return result
  538. def get_statistics_database(self):
  539. """
  540. :return: A reference to the statistics database object
  541. """
  542. return self.stats_db
  543. def process_db_query(self, query_string_in: str, print_results: bool = False):
  544. """
  545. Executes a string identified previously as a query. This can be a standard SQL SELECT/INSERT query or a named
  546. query.
  547. :param query_string_in: The query to be processed
  548. :param print_results: Indicates whether the results should be printed to terminal
  549. :return: The result of the query
  550. """
  551. return self.stats_db.process_db_query(query_string_in, print_results)
  552. def is_query(self, value: str):
  553. """
  554. Checks whether the given string is a standard SQL query (SELECT, INSERT) or a named query.
  555. :param value: The string to be checked
  556. :return: True if the string is recognized as a query, otherwise False.
  557. """
  558. if not isinstance(value, str):
  559. return False
  560. else:
  561. return (any(x in value.lower().strip() for x in self.stats_db.get_all_named_query_keywords()) or
  562. any(x in value.lower().strip() for x in self.stats_db.get_all_sql_query_keywords()))
  563. @staticmethod
  564. def calculate_standard_deviation(lst):
  565. """
  566. Calculates the standard deviation of a list of numbers.
  567. :param lst: The list of numbers to calculate its SD.
  568. """
  569. num_items = len(lst)
  570. mean = sum(lst) / num_items
  571. differences = [x - mean for x in lst]
  572. sq_differences = [d ** 2 for d in differences]
  573. ssd = sum(sq_differences)
  574. variance = ssd / num_items
  575. sd = sqrt(variance)
  576. return sd
  577. def plot_statistics(self, entropy: int, file_format: str = 'pdf'): # 'png'
  578. """
  579. Plots the statistics associated with the dataset.
  580. :param entropy: the statistics entropy
  581. :param file_format: The format to be used to save the statistics diagrams.
  582. """
  583. def plot_distribution(query_output, title, x_label, y_label, file_ending: str):
  584. plt.gcf().clear()
  585. graphx, graphy = [], []
  586. for row in query_output:
  587. graphx.append(row[0])
  588. graphy.append(row[1])
  589. plt.autoscale(enable=True, axis='both')
  590. plt.title(title)
  591. plt.xlabel(x_label)
  592. plt.ylabel(y_label)
  593. width = 0.1
  594. plt.xlim([0, (max(graphx) * 1.1)])
  595. plt.grid(True)
  596. plt.bar(graphx, graphy, width, align='center', linewidth=1, color='red', edgecolor='red')
  597. out = self.pcap_filepath.replace('.pcap', '_plot-' + title + file_ending)
  598. plt.savefig(out, dpi=500)
  599. return out
  600. def plot_ttl(file_ending: str):
  601. query_output = self.stats_db.process_user_defined_query(
  602. "SELECT ttlValue, SUM(ttlCount) FROM ip_ttl GROUP BY ttlValue")
  603. title = "TTL Distribution"
  604. x_label = "TTL Value"
  605. y_label = "Number of Packets"
  606. if query_output:
  607. return plot_distribution(query_output, title, x_label, y_label, file_ending)
  608. def plot_mss(file_ending: str):
  609. query_output = self.stats_db.process_user_defined_query(
  610. "SELECT mssValue, SUM(mssCount) FROM tcp_mss GROUP BY mssValue")
  611. title = "MSS Distribution"
  612. x_label = "MSS Value"
  613. y_label = "Number of Packets"
  614. if query_output:
  615. return plot_distribution(query_output, title, x_label, y_label, file_ending)
  616. def plot_win(file_ending: str):
  617. query_output = self.stats_db.process_user_defined_query(
  618. "SELECT winSize, SUM(winCount) FROM tcp_win GROUP BY winSize")
  619. title = "Window Size Distribution"
  620. x_label = "Window Size"
  621. y_label = "Number of Packets"
  622. if query_output:
  623. return plot_distribution(query_output, title, x_label, y_label, file_ending)
  624. def plot_protocol(file_ending: str):
  625. plt.gcf().clear()
  626. result = self.stats_db.process_user_defined_query(
  627. "SELECT protocolName, SUM(protocolCount) FROM ip_protocols GROUP BY protocolName")
  628. if result:
  629. graphx, graphy = [], []
  630. for row in result:
  631. graphx.append(row[0])
  632. graphy.append(row[1])
  633. plt.autoscale(enable=True, axis='both')
  634. plt.title("Protocols Distribution")
  635. plt.xlabel('Protocols')
  636. plt.ylabel('Number of Packets')
  637. width = 0.1
  638. plt.xlim([0, len(graphx)])
  639. plt.grid(True)
  640. # Protocols' names on x-axis
  641. x = range(0, len(graphx))
  642. my_xticks = graphx
  643. plt.xticks(x, my_xticks)
  644. plt.bar(x, graphy, width, align='center', linewidth=1, color='red', edgecolor='red')
  645. out = self.pcap_filepath.replace('.pcap', '_plot-protocol' + file_ending)
  646. plt.savefig(out, dpi=500)
  647. return out
  648. else:
  649. print("Error plot protocol: No protocol values found!")
  650. def plot_port(file_ending: str):
  651. plt.gcf().clear()
  652. result = self.stats_db.process_user_defined_query(
  653. "SELECT portNumber, SUM(portCount) FROM ip_ports GROUP BY portNumber")
  654. graphx, graphy = [], []
  655. for row in result:
  656. graphx.append(row[0])
  657. graphy.append(row[1])
  658. plt.autoscale(enable=True, axis='both')
  659. plt.title("Ports Distribution")
  660. plt.xlabel('Ports Numbers')
  661. plt.ylabel('Number of Packets')
  662. width = 0.1
  663. plt.xlim([0, max(graphx)])
  664. plt.grid(True)
  665. plt.bar(graphx, graphy, width, align='center', linewidth=1, color='red', edgecolor='red')
  666. out = self.pcap_filepath.replace('.pcap', '_plot-port' + file_ending)
  667. plt.savefig(out, dpi=500)
  668. return out
  669. # This distribution is not drawable for big datasets
  670. def plot_ip_src(file_ending: str):
  671. plt.gcf().clear()
  672. result = self.stats_db.process_user_defined_query(
  673. "SELECT ipAddress, pktsSent FROM ip_statistics")
  674. graphx, graphy = [], []
  675. for row in result:
  676. graphx.append(row[0])
  677. graphy.append(row[1])
  678. plt.autoscale(enable=True, axis='both')
  679. plt.title("Source IP Distribution")
  680. plt.xlabel('Source IP')
  681. plt.ylabel('Number of Packets')
  682. width = 0.1
  683. plt.xlim([0, len(graphx)])
  684. plt.grid(True)
  685. # IPs on x-axis
  686. x = range(0, len(graphx))
  687. my_xticks = graphx
  688. plt.xticks(x, my_xticks, rotation='vertical', fontsize=5)
  689. plt.tight_layout()
  690. # limit the number of xticks
  691. plt.locator_params(axis='x', nbins=20)
  692. plt.bar(x, graphy, width, align='center', linewidth=1, color='red', edgecolor='red')
  693. out = self.pcap_filepath.replace('.pcap', '_plot-ip-src' + file_ending)
  694. plt.savefig(out, dpi=500)
  695. return out
  696. # This distribution is not drawable for big datasets
  697. def plot_ip_dst(file_ending: str):
  698. plt.gcf().clear()
  699. result = self.stats_db.process_user_defined_query(
  700. "SELECT ipAddress, pktsReceived FROM ip_statistics")
  701. graphx, graphy = [], []
  702. for row in result:
  703. graphx.append(row[0])
  704. graphy.append(row[1])
  705. plt.autoscale(enable=True, axis='both')
  706. plt.title("Destination IP Distribution")
  707. plt.xlabel('Destination IP')
  708. plt.ylabel('Number of Packets')
  709. width = 0.1
  710. plt.xlim([0, len(graphx)])
  711. plt.grid(True)
  712. # IPs on x-axis
  713. x = range(0, len(graphx))
  714. my_xticks = graphx
  715. plt.xticks(x, my_xticks, rotation='vertical', fontsize=5)
  716. plt.tight_layout()
  717. # limit the number of xticks
  718. plt.locator_params(axis='x', nbins=20)
  719. plt.bar(x, graphy, width, align='center', linewidth=1, color='red', edgecolor='red')
  720. out = self.pcap_filepath.replace('.pcap', '_plot-ip-dst' + file_ending)
  721. plt.savefig(out, dpi=500)
  722. return out
  723. def plot_interval_statistics(query_output, title, x_label, y_label, file_ending: str):
  724. plt.gcf().clear()
  725. graphx, graphy = [], []
  726. for row in query_output:
  727. graphx.append(row[0])
  728. graphy.append(row[1])
  729. plt.autoscale(enable=True, axis='both')
  730. plt.title(title)
  731. plt.xlabel(x_label)
  732. plt.ylabel(y_label)
  733. width = 0.5
  734. plt.xlim([0, len(graphx)])
  735. plt.grid(True)
  736. # timestamp on x-axis
  737. x = range(0, len(graphx))
  738. # limit the number of xticks
  739. plt.locator_params(axis='x', nbins=20)
  740. plt.bar(x, graphy, width, align='center', linewidth=1, color='red', edgecolor='red')
  741. out = self.pcap_filepath.replace('.pcap', '_plot-' + title + file_ending)
  742. plt.savefig(out, dpi=500)
  743. return out
  744. def plot_interval_pkt_count(file_ending: str):
  745. query_output = self.stats_db.process_user_defined_query(
  746. "SELECT lastPktTimestamp, pktsCount FROM interval_statistics ORDER BY lastPktTimestamp")
  747. title = "Packet Rate"
  748. x_label = "Time Interval"
  749. y_label = "Number of Packets"
  750. if query_output:
  751. return plot_interval_statistics(query_output, title, x_label, y_label, file_ending)
  752. def plot_interval_ip_src_ent(file_ending: str):
  753. query_output = self.stats_db.process_user_defined_query(
  754. "SELECT lastPktTimestamp, ipSrcEntropy FROM interval_statistics ORDER BY lastPktTimestamp")
  755. title = "Source IP Entropy"
  756. x_label = "Time Interval"
  757. y_label = "Entropy"
  758. if query_output:
  759. return plot_interval_statistics(query_output, title, x_label, y_label, file_ending)
  760. def plot_interval_ip_dst_ent(file_ending: str):
  761. query_output = self.stats_db.process_user_defined_query(
  762. "SELECT lastPktTimestamp, ipDstEntropy FROM interval_statistics ORDER BY lastPktTimestamp")
  763. title = "Destination IP Entropy"
  764. x_label = "Time Interval"
  765. y_label = "Entropy"
  766. if query_output:
  767. return plot_interval_statistics(query_output, title, x_label, y_label, file_ending)
  768. def plot_interval_new_ip(file_ending: str):
  769. query_output = self.stats_db.process_user_defined_query(
  770. "SELECT lastPktTimestamp, newIPCount FROM interval_statistics ORDER BY lastPktTimestamp")
  771. title = "IP Novelty Distribution"
  772. x_label = "Time Interval"
  773. y_label = "Novel values count"
  774. if query_output:
  775. return plot_interval_statistics(query_output, title, x_label, y_label, file_ending)
  776. def plot_interval_new_port(file_ending: str):
  777. query_output = self.stats_db.process_user_defined_query(
  778. "SELECT lastPktTimestamp, newPortCount FROM interval_statistics ORDER BY lastPktTimestamp")
  779. title = "Port Novelty Distribution"
  780. x_label = "Time Interval"
  781. y_label = "Novel values count"
  782. if query_output:
  783. return plot_interval_statistics(query_output, title, x_label, y_label, file_ending)
  784. def plot_interval_new_ttl(file_ending: str):
  785. query_output = self.stats_db.process_user_defined_query(
  786. "SELECT lastPktTimestamp, newTTLCount FROM interval_statistics ORDER BY lastPktTimestamp")
  787. title = "TTL Novelty Distribution"
  788. x_label = "Time Interval"
  789. y_label = "Novel values count"
  790. if query_output:
  791. return plot_interval_statistics(query_output, title, x_label, y_label, file_ending)
  792. def plot_interval_new_tos(file_ending: str):
  793. query_output = self.stats_db.process_user_defined_query(
  794. "SELECT lastPktTimestamp, newToSCount FROM interval_statistics ORDER BY lastPktTimestamp")
  795. title = "ToS Novelty Distribution"
  796. x_label = "Time Interval"
  797. y_label = "Novel values count"
  798. if query_output:
  799. return plot_interval_statistics(query_output, title, x_label, y_label, file_ending)
  800. def plot_interval_new_win_size(file_ending: str):
  801. query_output = self.stats_db.process_user_defined_query(
  802. "SELECT lastPktTimestamp, newWinSizeCount FROM interval_statistics ORDER BY lastPktTimestamp")
  803. title = "Window Size Novelty Distribution"
  804. x_label = "Time Interval"
  805. y_label = "Novel values count"
  806. if query_output:
  807. return plot_interval_statistics(query_output, title, x_label, y_label, file_ending)
  808. def plot_interval_new_mss(file_ending: str):
  809. query_output = self.stats_db.process_user_defined_query(
  810. "SELECT lastPktTimestamp, newMSSCount FROM interval_statistics ORDER BY lastPktTimestamp")
  811. title = "MSS Novelty Distribution"
  812. x_label = "Time Interval"
  813. y_label = "Novel values count"
  814. if query_output:
  815. return plot_interval_statistics(query_output, title, x_label, y_label, file_ending)
  816. def plot_interval_ip_dst_cum_ent(file_ending: str):
  817. plt.gcf().clear()
  818. result = self.stats_db.process_user_defined_query(
  819. "SELECT lastPktTimestamp, ipDstCumEntropy FROM interval_statistics ORDER BY lastPktTimestamp")
  820. graphx, graphy = [], []
  821. for row in result:
  822. graphx.append(row[0])
  823. graphy.append(row[1])
  824. # If entropy was not calculated do not plot the graph
  825. if graphy[0] != -1:
  826. plt.autoscale(enable=True, axis='both')
  827. plt.title("Destination IP Cumulative Entropy")
  828. # plt.xlabel('Timestamp')
  829. plt.xlabel('Time Interval')
  830. plt.ylabel('Entropy')
  831. plt.xlim([0, len(graphx)])
  832. plt.grid(True)
  833. # timestamp on x-axis
  834. x = range(0, len(graphx))
  835. # my_xticks = graphx
  836. # plt.xticks(x, my_xticks, rotation='vertical', fontsize=5)
  837. # plt.tight_layout()
  838. # limit the number of xticks
  839. plt.locator_params(axis='x', nbins=20)
  840. plt.plot(x, graphy, 'r')
  841. out = self.pcap_filepath.replace('.pcap', '_plot-interval-ip-dst-cum-ent' + file_ending)
  842. plt.savefig(out, dpi=500)
  843. return out
  844. def plot_interval_ip_src_cum_ent(file_ending: str):
  845. plt.gcf().clear()
  846. result = self.stats_db.process_user_defined_query(
  847. "SELECT lastPktTimestamp, ipSrcCumEntropy 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("Source 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-src-cum-ent' + file_ending)
  870. plt.savefig(out, dpi=500)
  871. return out
  872. ttl_out_path = plot_ttl('.' + file_format)
  873. mss_out_path = plot_mss('.' + file_format)
  874. win_out_path = plot_win('.' + file_format)
  875. protocol_out_path = plot_protocol('.' + file_format)
  876. plot_interval_pktCount = plot_interval_pkt_count('.' + file_format)
  877. if entropy:
  878. plot_interval_ip_src_ent = plot_interval_ip_src_ent('.' + file_format)
  879. plot_interval_ip_dst_ent = plot_interval_ip_dst_ent('.' + file_format)
  880. plot_interval_ip_src_cum_ent = plot_interval_ip_src_cum_ent('.' + file_format)
  881. plot_interval_ip_dst_cum_ent = plot_interval_ip_dst_cum_ent('.' + file_format)
  882. plot_interval_new_ip = plot_interval_new_ip('.' + file_format)
  883. plot_interval_new_port = plot_interval_new_port('.' + file_format)
  884. plot_interval_new_ttl = plot_interval_new_ttl('.' + file_format)
  885. plot_interval_new_tos = plot_interval_new_tos('.' + file_format)
  886. plot_interval_new_win_size = plot_interval_new_win_size('.' + file_format)
  887. plot_interval_new_mss = plot_interval_new_mss('.' + file_format)
  888. # Time consuming plot
  889. # port_out_path = plot_port('.' + format)
  890. # Not drawable for too many IPs
  891. # ip_src_out_path = plot_ip_src('.' + format)
  892. # ip_dst_out_path = plot_ip_dst('.' + format)
  893. print("Saved plots in the input PCAP directory.")
  894. def stats_summary_post_attack(self, added_packets):
  895. """
  896. Prints a summary of relevant statistics after an attack is injected
  897. :param added_packets: sum of packets added by attacks, gets updated if more than one attack
  898. :return: None
  899. """
  900. total_packet_count = self.get_packet_count() + added_packets
  901. added_packets_share = added_packets / total_packet_count * 100
  902. timespan = self.get_capture_duration()
  903. summary = [("Total packet count", total_packet_count, "packets"),
  904. ("Added packet count", added_packets, "packets"),
  905. ("Share of added packets", added_packets_share, "%"),
  906. ("Capture duration", timespan, "seconds")]
  907. print("\nPOST INJECTION STATISTICS SUMMARY --------------------------")
  908. self.write_list(summary, print, "")
  909. print("------------------------------------------------------------")
  910. def stats_summary_new_db(self):
  911. """
  912. Prints a summary of relevant statistics when a new db is created
  913. :return: None
  914. """
  915. self.file_info = self.stats_db.get_file_info()
  916. print("\nNew database has been generated, printing statistics summary... ")
  917. total_packet_count = self.get_packet_count()
  918. pdu_count = self.process_db_query("SELECT SUM(pktCount) FROM unrecognized_pdus")
  919. pdu_share = pdu_count / total_packet_count * 100
  920. last_pdu_timestamp = self.process_db_query(
  921. "SELECT MAX(timestampLastOccurrence) FROM unrecognized_pdus")
  922. timespan = self.get_capture_duration()
  923. summary = [("Total packet count", total_packet_count, "packets"),
  924. ("Recognized packets", total_packet_count - pdu_count, "packets"),
  925. ("Unrecognized packets", pdu_count, "PDUs"),
  926. ("% Recognized packets", 100 - pdu_share, "%"),
  927. ("% Unrecognized packets", pdu_share, "%"),
  928. ("Last unknown PDU", last_pdu_timestamp),
  929. ("Capture duration", timespan, "seconds")]
  930. print("\nPCAP FILE STATISTICS SUMMARY ------------------------------")
  931. self.write_list(summary, print, "")
  932. print("------------------------------------------------------------")