Statistics.py 80 KB

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