Statistics.py 77 KB

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