Statistics.py 52 KB

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