Statistics.py 49 KB

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