Statistics.py 77 KB

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