Statistics.py 81 KB

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