Statistics.py 71 KB

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