Statistics.py 81 KB

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