Statistics.py 81 KB

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