Statistics.py 80 KB

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