Statistics.py 82 KB

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