Statistics.py 77 KB

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