Statistics.py 49 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140
  1. from operator import itemgetter
  2. from math import sqrt, ceil, log
  3. import os
  4. import time
  5. import ID2TLib.libpcapreader as pr
  6. import matplotlib
  7. matplotlib.use('Agg')
  8. import matplotlib.pyplot as plt
  9. from ID2TLib.PcapFile import PcapFile
  10. from ID2TLib.StatsDatabase import StatsDatabase
  11. class Statistics:
  12. def __init__(self, pcap_file: PcapFile):
  13. """
  14. Creates a new Statistics object.
  15. :param pcap_file: A reference to the PcapFile object
  16. """
  17. # Fields
  18. self.pcap_filepath = pcap_file.pcap_file_path
  19. self.pcap_proc = None
  20. self.do_extra_tests = False
  21. # Create folder for statistics database if required
  22. self.path_db = pcap_file.get_db_path()
  23. path_dir = os.path.dirname(self.path_db)
  24. if not os.path.isdir(path_dir):
  25. os.makedirs(path_dir)
  26. # Class instances
  27. self.stats_db = StatsDatabase(self.path_db)
  28. def load_pcap_statistics(self, flag_write_file: bool, flag_recalculate_stats: bool, flag_print_statistics: bool):
  29. """
  30. Loads the PCAP statistics for the file specified by pcap_filepath. If the database is not existing yet, the
  31. statistics are calculated by the PCAP file processor and saved into the newly created database. Otherwise the
  32. statistics are gathered directly from the existing database.
  33. :param flag_write_file: Indicates whether the statistics should be written addiotionally into a text file (True)
  34. or not (False)
  35. :param flag_recalculate_stats: Indicates whether eventually existing statistics should be recalculated
  36. :param flag_print_statistics: Indicates whether the gathered basic statistics should be printed to the terminal
  37. """
  38. # Load pcap and get loading time
  39. time_start = time.clock()
  40. # Inform user about recalculation of statistics and its reason
  41. if flag_recalculate_stats:
  42. print("Flag -r/--recalculate found. Recalculating statistics.")
  43. # Recalculate statistics if database does not exist OR param -r/--recalculate is provided
  44. if (not self.stats_db.get_db_exists()) or flag_recalculate_stats:
  45. self.pcap_proc = pr.pcap_processor(self.pcap_filepath, str(self.do_extra_tests))
  46. self.pcap_proc.collect_statistics()
  47. self.pcap_proc.write_to_database(self.path_db)
  48. outstring_datasource = "by PCAP file processor."
  49. else:
  50. outstring_datasource = "from statistics database."
  51. # Load statistics from database
  52. self.file_info = self.stats_db.get_file_info()
  53. time_end = time.clock()
  54. print("Loaded file statistics in " + str(time_end - time_start)[:4] + " sec " + outstring_datasource)
  55. # Write statistics if param -e/--export provided
  56. if flag_write_file:
  57. self.write_statistics_to_file()
  58. # Print statistics if param -s/--statistics provided
  59. if flag_print_statistics:
  60. self.print_statistics()
  61. def get_file_information(self):
  62. """
  63. Returns a list of tuples, each containing a information of the file.
  64. :return: a list of tuples, each consisting of (description, value, unit), where unit is optional.
  65. """
  66. return [("Pcap file", self.pcap_filepath),
  67. ("Packets", self.get_packet_count(), "packets"),
  68. ("Capture length", self.get_capture_duration(), "seconds"),
  69. ("Capture start", self.get_pcap_timestamp_start()),
  70. ("Capture end", self.get_pcap_timestamp_end())]
  71. def get_general_file_statistics(self):
  72. """
  73. Returns a list of tuples, each containing a file statistic.
  74. :return: a list of tuples, each consisting of (description, value, unit).
  75. """
  76. return [("Avg. packet rate", self.file_info['avgPacketRate'], "packets/sec"),
  77. ("Avg. packet size", self.file_info['avgPacketSize'], "kbytes"),
  78. ("Avg. packets sent", self.file_info['avgPacketsSentPerHost'], "packets"),
  79. ("Avg. bandwidth in", self.file_info['avgBandwidthIn'], "kbit/s"),
  80. ("Avg. bandwidth out", self.file_info['avgBandwidthOut'], "kbit/s")]
  81. @staticmethod
  82. def write_list(desc_val_unit_list, func, line_ending="\n"):
  83. """
  84. Takes a list of tuples (statistic name, statistic value, unit) as input, generates a string of these three values
  85. and applies the function func on this string.
  86. Before generating the string, it identifies text containing a float number, casts the string to a
  87. float and rounds the value to two decimal digits.
  88. :param desc_val_unit_list: The list of tuples consisting of (description, value, unit)
  89. :param func: The function to be applied to each generated string
  90. :param line_ending: The formatting string to be applied at the end of each string
  91. """
  92. for entry in desc_val_unit_list:
  93. # Convert text containing float into float
  94. (description, value) = entry[0:2]
  95. if isinstance(value, str) and "." in value:
  96. try:
  97. value = float(value)
  98. except ValueError:
  99. pass # do nothing -> value was not a float
  100. # round float
  101. if isinstance(value, float):
  102. value = round(value, 4)
  103. # write into file
  104. if len(entry) == 3:
  105. unit = entry[2]
  106. func(description + ":\t" + str(value) + " " + unit + line_ending)
  107. else:
  108. func(description + ":\t" + str(value) + line_ending)
  109. def print_statistics(self):
  110. """
  111. Prints the basic file statistics to the terminal.
  112. """
  113. print("\nPCAP FILE INFORMATION ------------------------------")
  114. Statistics.write_list(self.get_file_information(), print, "")
  115. print("\nGENERAL FILE STATISTICS ----------------------------")
  116. Statistics.write_list(self.get_general_file_statistics(), print, "")
  117. print("\n")
  118. def calculate_entropy(self, frequency:list, normalized:bool = False):
  119. """
  120. Calculates entropy and normalized entropy of list of elements that have specific frequency
  121. :param frequency: The frequency of the elements.
  122. :param normalized: Calculate normalized entropy
  123. :return: entropy or (entropy, normalized entropy)
  124. """
  125. entropy, normalizedEnt, n = 0, 0, 0
  126. sumFreq = sum(frequency)
  127. for i, x in enumerate(frequency):
  128. p_x = float(frequency[i] / sumFreq)
  129. if p_x > 0:
  130. n += 1
  131. entropy += - p_x * log(p_x, 2)
  132. if normalized:
  133. if log(n)>0:
  134. normalizedEnt = entropy/log(n, 2)
  135. return entropy, normalizedEnt
  136. else:
  137. return entropy
  138. def calculate_complement_packet_rates(self, pps):
  139. """
  140. Calculates the complement packet rates of the background traffic packet rates for each interval.
  141. Then normalize it to maximum boundary, which is the input parameter pps
  142. :return: normalized packet rates for each time interval.
  143. """
  144. result = self.process_db_query(
  145. "SELECT lastPktTimestamp,pktsCount FROM interval_statistics ORDER BY lastPktTimestamp")
  146. # print(result)
  147. bg_interval_pps = []
  148. complement_interval_pps = []
  149. intervalsSum = 0
  150. if result:
  151. # Get the interval in seconds
  152. for i, row in enumerate(result):
  153. if i < len(result) - 1:
  154. intervalsSum += ceil((int(result[i + 1][0]) * 10 ** -6) - (int(row[0]) * 10 ** -6))
  155. interval = intervalsSum / (len(result) - 1)
  156. # Convert timestamp from micro to seconds, convert packet rate "per interval" to "per second"
  157. for row in result:
  158. bg_interval_pps.append((int(row[0]) * 10 ** -6, int(row[1] / interval)))
  159. # Find max PPS
  160. maxPPS = max(bg_interval_pps, key=itemgetter(1))[1]
  161. for row in bg_interval_pps:
  162. complement_interval_pps.append((row[0], int(pps * (maxPPS - row[1]) / maxPPS)))
  163. return complement_interval_pps
  164. def get_tests_statistics(self):
  165. """
  166. Writes the calculated basic defects tests statistics into a file.
  167. """
  168. # self.stats_db._process_user_defined_query output is list of tuples, thus, we ned [0][0] to access data
  169. def count_frequncy(valuesList):
  170. values, frequency = [] , []
  171. for x in valuesList:
  172. if x in values:
  173. frequency[values.index(x)] += 1
  174. else:
  175. values.append(x)
  176. frequency.append(1)
  177. return values, frequency
  178. ####### Payload Tests #######
  179. sumPayloadCount = self.stats_db._process_user_defined_query("SELECT sum(payloadCount) FROM interval_statistics")
  180. pktCount = self.stats_db._process_user_defined_query("SELECT packetCount FROM file_statistics")
  181. if sumPayloadCount and pktCount:
  182. payloadRatio=0
  183. if(pktCount[0][0]!=0):
  184. payloadRatio = float(sumPayloadCount[0][0] / pktCount[0][0] * 100)
  185. else:
  186. payloadRatio = -1
  187. ####### TCP checksum Tests #######
  188. incorrectChecksumCount = self.stats_db._process_user_defined_query("SELECT sum(incorrectTCPChecksumCount) FROM interval_statistics")
  189. correctChecksumCount = self.stats_db._process_user_defined_query("SELECT avg(correctTCPChecksumCount) FROM interval_statistics")
  190. if incorrectChecksumCount and correctChecksumCount:
  191. incorrectChecksumRatio=0
  192. if(incorrectChecksumCount[0][0] + correctChecksumCount[0][0])!=0:
  193. incorrectChecksumRatio = float(incorrectChecksumCount[0][0] / (incorrectChecksumCount[0][0] + correctChecksumCount[0][0] ) * 100)
  194. else:
  195. incorrectChecksumRatio = -1
  196. ####### IP Src Tests #######
  197. result = self.stats_db._process_user_defined_query("SELECT ipAddress,pktsSent,pktsReceived FROM ip_statistics")
  198. data, srcFrequency, dstFrequency = [], [], []
  199. if result:
  200. for row in result:
  201. srcFrequency.append(row[1])
  202. dstFrequency.append(row[2])
  203. ipSrcEntropy, ipSrcNormEntropy = self.calculate_entropy(srcFrequency, True)
  204. ipDstEntropy, ipDstNormEntropy = self.calculate_entropy(dstFrequency, True)
  205. newIPCount = self.stats_db._process_user_defined_query("SELECT newIPCount FROM interval_statistics")
  206. ipNovelsPerInterval, ipNovelsPerIntervalFrequency = count_frequncy(newIPCount)
  207. ipNoveltyDistEntropy = self.calculate_entropy(ipNovelsPerIntervalFrequency)
  208. ####### Ports Tests #######
  209. port0Count = self.stats_db._process_user_defined_query("SELECT SUM(portCount) FROM ip_ports WHERE portNumber = 0")
  210. if not port0Count[0][0]:
  211. port0Count = 0
  212. else:
  213. port0Count = port0Count[0][0]
  214. reservedPortCount = self.stats_db._process_user_defined_query(
  215. "SELECT SUM(portCount) FROM ip_ports WHERE portNumber IN (100,114,1023,1024,49151,49152,65535)")# could be extended
  216. if not reservedPortCount[0][0]:
  217. reservedPortCount = 0
  218. else:
  219. reservedPortCount = reservedPortCount[0][0]
  220. ####### TTL Tests #######
  221. result = self.stats_db._process_user_defined_query("SELECT ttlValue,SUM(ttlCount) FROM ip_ttl GROUP BY ttlValue")
  222. data, frequency = [], []
  223. for row in result:
  224. frequency.append(row[1])
  225. ttlEntropy, ttlNormEntropy = self.calculate_entropy(frequency,True)
  226. newTTLCount = self.stats_db._process_user_defined_query("SELECT newTTLCount FROM interval_statistics")
  227. ttlNovelsPerInterval, ttlNovelsPerIntervalFrequency = count_frequncy(newTTLCount)
  228. ttlNoveltyDistEntropy = self.calculate_entropy(ttlNovelsPerIntervalFrequency)
  229. ####### Window Size Tests #######
  230. result = self.stats_db._process_user_defined_query("SELECT winSize,SUM(winCount) FROM tcp_win GROUP BY winSize")
  231. data, frequency = [], []
  232. for row in result:
  233. frequency.append(row[1])
  234. winEntropy, winNormEntropy = self.calculate_entropy(frequency, True)
  235. newWinSizeCount = self.stats_db._process_user_defined_query("SELECT newWinSizeCount FROM interval_statistics")
  236. winNovelsPerInterval, winNovelsPerIntervalFrequency = count_frequncy(newWinSizeCount)
  237. winNoveltyDistEntropy = self.calculate_entropy(winNovelsPerIntervalFrequency)
  238. ####### ToS Tests #######
  239. result = self.stats_db._process_user_defined_query(
  240. "SELECT tosValue,SUM(tosCount) FROM ip_tos GROUP BY tosValue")
  241. data, frequency = [], []
  242. for row in result:
  243. frequency.append(row[1])
  244. tosEntropy, tosNormEntropy = self.calculate_entropy(frequency, True)
  245. newToSCount = self.stats_db._process_user_defined_query("SELECT newToSCount FROM interval_statistics")
  246. tosNovelsPerInterval, tosNovelsPerIntervalFrequency = count_frequncy(newToSCount)
  247. tosNoveltyDistEntropy = self.calculate_entropy(tosNovelsPerIntervalFrequency)
  248. ####### MSS Tests #######
  249. result = self.stats_db._process_user_defined_query(
  250. "SELECT mssValue,SUM(mssCount) FROM tcp_mss GROUP BY mssValue")
  251. data, frequency = [], []
  252. for row in result:
  253. frequency.append(row[1])
  254. mssEntropy, mssNormEntropy = self.calculate_entropy(frequency, True)
  255. newMSSCount = self.stats_db._process_user_defined_query("SELECT newMSSCount FROM interval_statistics")
  256. mssNovelsPerInterval, mssNovelsPerIntervalFrequency = count_frequncy(newMSSCount)
  257. mssNoveltyDistEntropy = self.calculate_entropy(mssNovelsPerIntervalFrequency)
  258. result = self.stats_db._process_user_defined_query("SELECT SUM(mssCount) FROM tcp_mss WHERE mssValue > 1460")
  259. # The most used MSS < 1460. Calculate the ratio of the values bigger that 1460.
  260. if not result[0][0]:
  261. result = 0
  262. else:
  263. result = result[0][0]
  264. bigMSS = (result / sum(frequency)) * 100
  265. output = [("Payload ratio", payloadRatio, "%"),
  266. ("Incorrect TCP checksum ratio", incorrectChecksumRatio, "%"),
  267. ("# IP addresses", sum([x[0] for x in newIPCount]), ""),
  268. ("IP Src Entropy", ipSrcEntropy, ""),
  269. ("IP Src Normalized Entropy", ipSrcNormEntropy, ""),
  270. ("IP Dst Entropy", ipDstEntropy, ""),
  271. ("IP Dst Normalized Entropy", ipDstNormEntropy, ""),
  272. ("# TTL values", sum([x[0] for x in newTTLCount]), ""),
  273. ("TTL Distribution Entropy", ipNoveltyDistEntropy, ""),
  274. ("TTL Entropy", ttlEntropy, ""),
  275. ("TTL Normalized Entropy", ttlNormEntropy, ""),
  276. ("TTL Distribution Entropy", ttlNoveltyDistEntropy, ""),
  277. ("# WinSize values", sum([x[0] for x in newWinSizeCount]), ""),
  278. ("WinSize Entropy", winEntropy, ""),
  279. ("WinSize Normalized Entropy", winNormEntropy, ""),
  280. ("WinSize Distribution Entropy", winNoveltyDistEntropy, ""),
  281. ("# ToS values", sum([x[0] for x in newToSCount]), ""),
  282. ("ToS Entropy", tosEntropy, ""),
  283. ("ToS Normalized Entropy", tosNormEntropy, ""),
  284. ("ToS Distribution Entropy", tosNoveltyDistEntropy, ""),
  285. ("# MSS values", sum([x[0] for x in newMSSCount]), ""),
  286. ("MSS Entropy", mssEntropy, ""),
  287. ("MSS Normalized Entropy", mssNormEntropy, ""),
  288. ("MSS Distribution Entropy", mssNoveltyDistEntropy, ""),
  289. ("======================","","")]
  290. # Reasoning the statistics values
  291. if payloadRatio > 80:
  292. output.append(("WARNING: Too high payload ratio", payloadRatio, "%."))
  293. if payloadRatio < 30:
  294. output.append(("WARNING: Too low payload ratio", payloadRatio, "% (Injecting attacks that are carried out in the packet payloads is not recommmanded)."))
  295. if incorrectChecksumRatio > 5:
  296. output.append(("WARNING: High incorrect TCP checksum ratio",incorrectChecksumRatio,"%."))
  297. if ipSrcNormEntropy > 0.65:
  298. output.append(("WARNING: High IP source normalized entropy",ipSrcNormEntropy,"."))
  299. if ipSrcNormEntropy < 0.2:
  300. output.append(("WARNING: Low IP source normalized entropy", ipSrcNormEntropy, "."))
  301. if ipDstNormEntropy > 0.65:
  302. output.append(("WARNING: High IP destination normalized entropy", ipDstNormEntropy, "."))
  303. if ipDstNormEntropy < 0.2:
  304. output.append(("WARNING: Low IP destination normalized entropy", ipDstNormEntropy, "."))
  305. if ttlNormEntropy > 0.65:
  306. output.append(("WARNING: High TTL normalized entropy", ttlNormEntropy, "."))
  307. if ttlNormEntropy < 0.2:
  308. output.append(("WARNING: Low TTL normalized entropy", ttlNormEntropy, "."))
  309. if ttlNoveltyDistEntropy < 1:
  310. output.append(("WARNING: Too low TTL novelty distribution entropy", ttlNoveltyDistEntropy,
  311. "(The distribution of the novel TTL values is suspicious)."))
  312. if winNormEntropy > 0.6:
  313. output.append(("WARNING: High Window Size normalized entropy", winNormEntropy, "."))
  314. if winNormEntropy < 0.1:
  315. output.append(("WARNING: Low Window Size normalized entropy", winNormEntropy, "."))
  316. if winNoveltyDistEntropy < 4:
  317. output.append(("WARNING: Low Window Size novelty distribution entropy", winNoveltyDistEntropy,
  318. "(The distribution of the novel Window Size values is suspicious)."))
  319. if tosNormEntropy > 0.4:
  320. output.append(("WARNING: High ToS normalized entropy", tosNormEntropy, "."))
  321. if tosNormEntropy < 0.1:
  322. output.append(("WARNING: Low ToS normalized entropy", tosNormEntropy, "."))
  323. if tosNoveltyDistEntropy < 0.5:
  324. output.append(("WARNING: Low ToS novelty distribution entropy", tosNoveltyDistEntropy,
  325. "(The distribution of the novel ToS values is suspicious)."))
  326. if mssNormEntropy > 0.4:
  327. output.append(("WARNING: High MSS normalized entropy", mssNormEntropy, "."))
  328. if mssNormEntropy < 0.1:
  329. output.append(("WARNING: Low MSS normalized entropy", mssNormEntropy, "."))
  330. if mssNoveltyDistEntropy < 0.5:
  331. output.append(("WARNING: Low MSS novelty distribution entropy", mssNoveltyDistEntropy,
  332. "(The distribution of the novel MSS values is suspicious)."))
  333. if bigMSS > 50:
  334. output.append(("WARNING: High ratio of MSS > 1460", bigMSS, "% (High fragmentation rate in Ethernet)."))
  335. if port0Count > 0:
  336. output.append(("WARNING: Port number 0 is used in ",port0Count,"packets (awkward-looking port)."))
  337. if reservedPortCount > 0:
  338. output.append(("WARNING: Reserved port numbers are used in ",reservedPortCount,"packets (uncommonly-used ports)."))
  339. return output
  340. def write_statistics_to_file(self):
  341. """
  342. Writes the calculated basic statistics into a file.
  343. """
  344. def _write_header(title: str):
  345. """
  346. Writes the section header into the open file.
  347. :param title: The section title
  348. """
  349. target.write("====================== \n")
  350. target.write(title + " \n")
  351. target.write("====================== \n")
  352. target = open(self.pcap_filepath + ".stat", 'w')
  353. target.truncate()
  354. _write_header("PCAP file information")
  355. Statistics.write_list(self.get_file_information(), target.write)
  356. _write_header("General statistics")
  357. Statistics.write_list(self.get_general_file_statistics(), target.write)
  358. _write_header("Tests statistics")
  359. Statistics.write_list(self.get_tests_statistics(), target.write)
  360. target.close()
  361. def get_capture_duration(self):
  362. """
  363. :return: The duration of the capture in seconds
  364. """
  365. return self.file_info['captureDuration']
  366. def get_pcap_timestamp_start(self):
  367. """
  368. :return: The timestamp of the first packet in the PCAP file
  369. """
  370. return self.file_info['timestampFirstPacket']
  371. def get_pcap_timestamp_end(self):
  372. """
  373. :return: The timestamp of the last packet in the PCAP file
  374. """
  375. return self.file_info['timestampLastPacket']
  376. def get_pps_sent(self, ip_address: str):
  377. """
  378. Calculates the sent packets per seconds for a given IP address.
  379. :param ip_address: The IP address whose packets per second should be calculated
  380. :return: The sent packets per seconds for the given IP address
  381. """
  382. packets_sent = self.stats_db.process_db_query("SELECT pktsSent from ip_statistics WHERE ipAddress=?", False,
  383. (ip_address,))
  384. capture_duration = float(self.get_capture_duration())
  385. return int(float(packets_sent) / capture_duration)
  386. def get_pps_received(self, ip_address: str):
  387. """
  388. Calculate the packets per second received for a given IP address.
  389. :param ip_address: The IP address used for the calculation
  390. :return: The number of packets per second received
  391. """
  392. packets_received = self.stats_db.process_db_query("SELECT pktsReceived FROM ip_statistics WHERE ipAddress=?",
  393. False,
  394. (ip_address,))
  395. capture_duration = float(self.get_capture_duration())
  396. return int(float(packets_received) / capture_duration)
  397. def get_packet_count(self):
  398. """
  399. :return: The number of packets in the loaded PCAP file
  400. """
  401. return self.file_info['packetCount']
  402. def get_most_used_ip_address(self):
  403. """
  404. :return: The IP address/addresses with the highest sum of packets sent and received
  405. """
  406. return self.process_db_query("most_used(ipAddress)")
  407. def get_ttl_distribution(self, ipAddress: str):
  408. result = self.process_db_query('SELECT ttlValue, ttlCount from ip_ttl WHERE ipAddress="' + ipAddress + '"')
  409. result_dict = {key: value for (key, value) in result}
  410. return result_dict
  411. def get_mss_distribution(self, ipAddress: str):
  412. result = self.process_db_query('SELECT mssValue, mssCount from tcp_mss WHERE ipAddress="' + ipAddress + '"')
  413. result_dict = {key: value for (key, value) in result}
  414. return result_dict
  415. def get_win_distribution(self, ipAddress: str):
  416. result = self.process_db_query('SELECT winSize, winCount from tcp_win WHERE ipAddress="' + ipAddress + '"')
  417. result_dict = {key: value for (key, value) in result}
  418. return result_dict
  419. def get_tos_distribution(self, ipAddress: str):
  420. result = self.process_db_query('SELECT tosValue, tosCount from ip_tos WHERE ipAddress="' + ipAddress + '"')
  421. result_dict = {key: value for (key, value) in result}
  422. return result_dict
  423. def get_random_ip_address(self, count: int = 1):
  424. """
  425. :param count: The number of IP addreses to return
  426. :return: A randomly chosen IP address from the dataset or iff param count is greater than one, a list of randomly
  427. chosen IP addresses
  428. """
  429. if count == 1:
  430. return self.process_db_query("random(all(ipAddress))")
  431. else:
  432. ip_address_list = []
  433. for i in range(0, count):
  434. ip_address_list.append(self.process_db_query("random(all(ipAddress))"))
  435. return ip_address_list
  436. def get_mac_address(self, ipAddress: str):
  437. """
  438. :return: The MAC address used in the dataset for the given IP address.
  439. """
  440. return self.process_db_query('macAddress(ipAddress=' + ipAddress + ")")
  441. def get_most_used_mss(self, ipAddress: str):
  442. """
  443. :param ipAddress: The IP address whose used MSS should be determined
  444. :return: The TCP MSS value used by the IP address, or if the IP addresses never specified a MSS,
  445. then None is returned
  446. """
  447. mss_value = self.process_db_query('SELECT mssValue from tcp_mss WHERE ipAddress="' + ipAddress + '" ORDER BY mssCount DESC LIMIT 1')
  448. if isinstance(mss_value, int):
  449. return mss_value
  450. else:
  451. return None
  452. def get_most_used_ttl(self, ipAddress: str):
  453. """
  454. :param ipAddress: The IP address whose used TTL should be determined
  455. :return: The TTL value used by the IP address, or if the IP addresses never specified a TTL,
  456. then None is returned
  457. """
  458. ttl_value = self.process_db_query(
  459. 'SELECT ttlValue from ip_ttl WHERE ipAddress="' + ipAddress + '" ORDER BY ttlCount DESC LIMIT 1')
  460. if isinstance(ttl_value, int):
  461. return ttl_value
  462. else:
  463. return None
  464. def get_statistics_database(self):
  465. """
  466. :return: A reference to the statistics database object
  467. """
  468. return self.stats_db
  469. def process_db_query(self, query_string_in: str, print_results: bool = False):
  470. """
  471. Executes a string identified previously as a query. This can be a standard SQL SELECT/INSERT query or a named
  472. query.
  473. :param query_string_in: The query to be processed
  474. :param print_results: Indicates whether the results should be printed to terminal
  475. :return: The result of the query
  476. """
  477. return self.stats_db.process_db_query(query_string_in, print_results)
  478. def is_query(self, value: str):
  479. """
  480. Checks whether the given string is a standard SQL query (SELECT, INSERT) or a named query.
  481. :param value: The string to be checked
  482. :return: True if the string is recognized as a query, otherwise False.
  483. """
  484. if not isinstance(value, str):
  485. return False
  486. else:
  487. return (any(x in value.lower().strip() for x in self.stats_db.get_all_named_query_keywords()) or
  488. any(x in value.lower().strip() for x in self.stats_db.get_all_sql_query_keywords()))
  489. def calculate_standard_deviation(self, lst):
  490. """
  491. Calculates the standard deviation of a list of numbers.
  492. :param lst: The list of numbers to calculate its SD.
  493. """
  494. num_items = len(lst)
  495. mean = sum(lst) / num_items
  496. differences = [x - mean for x in lst]
  497. sq_differences = [d ** 2 for d in differences]
  498. ssd = sum(sq_differences)
  499. variance = ssd / num_items
  500. sd = sqrt(variance)
  501. return sd
  502. def plot_statistics(self, format: str = 'pdf'): #'png'
  503. """
  504. Plots the statistics associated with the dataset.
  505. :param format: The format to be used to save the statistics diagrams.
  506. """
  507. def plot_ttl(file_ending: str):
  508. plt.gcf().clear()
  509. result = self.stats_db._process_user_defined_query(
  510. "SELECT ttlValue, SUM(ttlCount) FROM ip_ttl GROUP BY ttlValue")
  511. graphx, graphy = [], []
  512. for row in result:
  513. graphx.append(row[0])
  514. graphy.append(row[1])
  515. plt.autoscale(enable=True, axis='both')
  516. plt.title("TTL Distribution")
  517. plt.xlabel('TTL Value')
  518. plt.ylabel('Number of Packets')
  519. width = 0.1
  520. plt.xlim([0, max(graphx)])
  521. plt.grid(True)
  522. plt.bar(graphx, graphy, width, align='center', linewidth=1, color='red', edgecolor='red')
  523. out = self.pcap_filepath.replace('.pcap', '_plot-ttl' + file_ending)
  524. plt.savefig(out,dpi=500)
  525. return out
  526. def plot_mss(file_ending: str):
  527. plt.gcf().clear()
  528. result = self.stats_db._process_user_defined_query(
  529. "SELECT mssValue, SUM(mssCount) FROM tcp_mss GROUP BY mssValue")
  530. if(result):
  531. graphx, graphy = [], []
  532. for row in result:
  533. graphx.append(row[0])
  534. graphy.append(row[1])
  535. plt.autoscale(enable=True, axis='both')
  536. plt.title("MSS Distribution")
  537. plt.xlabel('MSS Value')
  538. plt.ylabel('Number of Packets')
  539. width = 0.1
  540. plt.xlim([0, max(graphx)])
  541. plt.grid(True)
  542. plt.bar(graphx, graphy, width, align='center', linewidth=1, color='red', edgecolor='red')
  543. out = self.pcap_filepath.replace('.pcap', '_plot-mss' + file_ending)
  544. plt.savefig(out,dpi=500)
  545. return out
  546. else:
  547. print("Error plot MSS: No MSS values found!")
  548. def plot_win(file_ending: str):
  549. plt.gcf().clear()
  550. result = self.stats_db._process_user_defined_query(
  551. "SELECT winSize, SUM(winCount) FROM tcp_win GROUP BY winSize")
  552. if (result):
  553. graphx, graphy = [], []
  554. for row in result:
  555. graphx.append(row[0])
  556. graphy.append(row[1])
  557. plt.autoscale(enable=True, axis='both')
  558. plt.title("Window Size Distribution")
  559. plt.xlabel('Window Size')
  560. plt.ylabel('Number of Packets')
  561. width = 0.1
  562. plt.xlim([0, max(graphx)])
  563. plt.grid(True)
  564. plt.bar(graphx, graphy, width, align='center', linewidth=1, color='red', edgecolor='red')
  565. out = self.pcap_filepath.replace('.pcap', '_plot-win' + file_ending)
  566. plt.savefig(out,dpi=500)
  567. return out
  568. else:
  569. print("Error plot WinSize: No WinSize values found!")
  570. def plot_protocol(file_ending: str):
  571. plt.gcf().clear()
  572. result = self.stats_db._process_user_defined_query(
  573. "SELECT protocolName, SUM(protocolCount) FROM ip_protocols GROUP BY protocolName")
  574. if (result):
  575. graphx, graphy = [], []
  576. for row in result:
  577. graphx.append(row[0])
  578. graphy.append(row[1])
  579. plt.autoscale(enable=True, axis='both')
  580. plt.title("Protocols Distribution")
  581. plt.xlabel('Protocols')
  582. plt.ylabel('Number of Packets')
  583. width = 0.1
  584. plt.xlim([0, len(graphx)])
  585. plt.grid(True)
  586. # Protocols' names on x-axis
  587. x = range(0,len(graphx))
  588. my_xticks = graphx
  589. plt.xticks(x, my_xticks)
  590. plt.bar(x, graphy, width, align='center', linewidth=1, color='red', edgecolor='red')
  591. out = self.pcap_filepath.replace('.pcap', '_plot-protocol' + file_ending)
  592. plt.savefig(out,dpi=500)
  593. return out
  594. else:
  595. print("Error plot protocol: No protocol values found!")
  596. def plot_port(file_ending: str):
  597. plt.gcf().clear()
  598. result = self.stats_db._process_user_defined_query(
  599. "SELECT portNumber, SUM(portCount) FROM ip_ports GROUP BY portNumber")
  600. graphx, graphy = [], []
  601. for row in result:
  602. graphx.append(row[0])
  603. graphy.append(row[1])
  604. plt.autoscale(enable=True, axis='both')
  605. plt.title("Ports Distribution")
  606. plt.xlabel('Ports Numbers')
  607. plt.ylabel('Number of Packets')
  608. width = 0.1
  609. plt.xlim([0, max(graphx)])
  610. plt.grid(True)
  611. plt.bar(graphx, graphy, width, align='center', linewidth=1, color='red', edgecolor='red')
  612. out = self.pcap_filepath.replace('.pcap', '_plot-port' + file_ending)
  613. plt.savefig(out,dpi=500)
  614. return out
  615. # This distribution is not drawable for big datasets
  616. def plot_ip_src(file_ending: str):
  617. plt.gcf().clear()
  618. result = self.stats_db._process_user_defined_query(
  619. "SELECT ipAddress, pktsSent FROM ip_statistics")
  620. graphx, graphy = [], []
  621. for row in result:
  622. graphx.append(row[0])
  623. graphy.append(row[1])
  624. plt.autoscale(enable=True, axis='both')
  625. plt.title("Source IP Distribution")
  626. plt.xlabel('Source IP')
  627. plt.ylabel('Number of Packets')
  628. width = 0.1
  629. plt.xlim([0, len(graphx)])
  630. plt.grid(True)
  631. # IPs on x-axis
  632. x = range(0, len(graphx))
  633. my_xticks = graphx
  634. plt.xticks(x, my_xticks, rotation='vertical', fontsize=5)
  635. plt.tight_layout()
  636. # limit the number of xticks
  637. plt.locator_params(axis='x', nbins=20)
  638. plt.bar(x, graphy, width, align='center', linewidth=1, color='red', edgecolor='red')
  639. out = self.pcap_filepath.replace('.pcap', '_plot-ip-src' + file_ending)
  640. plt.savefig(out, dpi=500)
  641. return out
  642. # This distribution is not drawable for big datasets
  643. def plot_ip_dst(file_ending: str):
  644. plt.gcf().clear()
  645. result = self.stats_db._process_user_defined_query(
  646. "SELECT ipAddress, pktsReceived FROM ip_statistics")
  647. graphx, graphy = [], []
  648. for row in result:
  649. graphx.append(row[0])
  650. graphy.append(row[1])
  651. plt.autoscale(enable=True, axis='both')
  652. plt.title("Destination IP Distribution")
  653. plt.xlabel('Destination IP')
  654. plt.ylabel('Number of Packets')
  655. width = 0.1
  656. plt.xlim([0, len(graphx)])
  657. plt.grid(True)
  658. # IPs on x-axis
  659. x = range(0, len(graphx))
  660. my_xticks = graphx
  661. plt.xticks(x, my_xticks, rotation='vertical', fontsize=5)
  662. plt.tight_layout()
  663. # limit the number of xticks
  664. plt.locator_params(axis='x', nbins=20)
  665. plt.bar(x, graphy, width, align='center', linewidth=1, color='red', edgecolor='red')
  666. out = self.pcap_filepath.replace('.pcap', '_plot-ip-dst' + file_ending)
  667. plt.savefig(out, dpi=500)
  668. return out
  669. def plot_interval_pktCount(file_ending: str):
  670. plt.gcf().clear()
  671. result = self.stats_db._process_user_defined_query(
  672. "SELECT lastPktTimestamp, pktsCount FROM interval_statistics ORDER BY lastPktTimestamp")
  673. graphx, graphy = [], []
  674. for row in result:
  675. graphx.append(row[0])
  676. graphy.append(row[1])
  677. plt.autoscale(enable=True, axis='both')
  678. plt.title("Packet Rate")
  679. plt.xlabel('Timestamp')
  680. plt.ylabel('Number of Packets')
  681. width = 0.5
  682. plt.xlim([0, len(graphx)])
  683. plt.grid(True)
  684. # timestamp on x-axis
  685. x = range(0, len(graphx))
  686. my_xticks = graphx
  687. plt.xticks(x, my_xticks, rotation='vertical', fontsize=5)
  688. plt.tight_layout()
  689. # limit the number of xticks
  690. plt.locator_params(axis='x', nbins=20)
  691. plt.bar(x, graphy, width, align='center', linewidth=1, color='red', edgecolor='red')
  692. out = self.pcap_filepath.replace('.pcap', '_plot-interval-pkt-count' + file_ending)
  693. plt.savefig(out, dpi=500)
  694. return out
  695. def plot_interval_ip_src_ent(file_ending: str):
  696. plt.gcf().clear()
  697. result = self.stats_db._process_user_defined_query(
  698. "SELECT lastPktTimestamp, ipSrcEntropy FROM interval_statistics ORDER BY lastPktTimestamp")
  699. graphx, graphy = [], []
  700. for row in result:
  701. graphx.append(row[0])
  702. graphy.append(row[1])
  703. plt.autoscale(enable=True, axis='both')
  704. plt.title("Source IP Entropy")
  705. plt.xlabel('Timestamp')
  706. plt.ylabel('Entropy')
  707. width = 0.5
  708. plt.xlim([0, len(graphx)])
  709. plt.grid(True)
  710. # timestamp on x-axis
  711. x = range(0, len(graphx))
  712. my_xticks = graphx
  713. plt.xticks(x, my_xticks, rotation='vertical', fontsize=5)
  714. plt.tight_layout()
  715. # limit the number of xticks
  716. plt.locator_params(axis='x', nbins=20)
  717. plt.bar(x, graphy, width, align='center', linewidth=1, color='red', edgecolor='red')
  718. out = self.pcap_filepath.replace('.pcap', '_plot-interval-ip-src-ent' + file_ending)
  719. plt.savefig(out, dpi=500)
  720. return out
  721. def plot_interval_ip_dst_ent(file_ending: str):
  722. plt.gcf().clear()
  723. result = self.stats_db._process_user_defined_query(
  724. "SELECT lastPktTimestamp, ipDstEntropy FROM interval_statistics ORDER BY lastPktTimestamp")
  725. graphx, graphy = [], []
  726. for row in result:
  727. graphx.append(row[0])
  728. graphy.append(row[1])
  729. plt.autoscale(enable=True, axis='both')
  730. plt.title("Destination IP Entropy")
  731. plt.xlabel('Timestamp')
  732. plt.ylabel('Entropy')
  733. width = 0.5
  734. plt.xlim([0, len(graphx)])
  735. plt.grid(True)
  736. # timestamp on x-axis
  737. x = range(0, len(graphx))
  738. my_xticks = graphx
  739. plt.xticks(x, my_xticks, rotation='vertical', fontsize=5)
  740. plt.tight_layout()
  741. # limit the number of xticks
  742. plt.locator_params(axis='x', nbins=20)
  743. plt.bar(x, graphy, width, align='center', linewidth=1, color='red', edgecolor='red')
  744. out = self.pcap_filepath.replace('.pcap', '_plot-interval-ip-dst-ent' + file_ending)
  745. plt.savefig(out, dpi=500)
  746. return out
  747. def plot_interval_ip_dst_cum_ent(file_ending: str):
  748. plt.gcf().clear()
  749. result = self.stats_db._process_user_defined_query(
  750. "SELECT lastPktTimestamp, ipDstCumEntropy FROM interval_statistics ORDER BY lastPktTimestamp")
  751. graphx, graphy = [], []
  752. for row in result:
  753. graphx.append(row[0])
  754. graphy.append(row[1])
  755. plt.autoscale(enable=True, axis='both')
  756. plt.title("Destination IP Cumulative Entropy")
  757. plt.xlabel('Timestamp')
  758. plt.ylabel('Entropy')
  759. plt.xlim([0, len(graphx)])
  760. plt.grid(True)
  761. # timestamp on x-axis
  762. x = range(0, len(graphx))
  763. my_xticks = graphx
  764. plt.xticks(x, my_xticks, rotation='vertical', fontsize=5)
  765. plt.tight_layout()
  766. # limit the number of xticks
  767. plt.locator_params(axis='x', nbins=20)
  768. plt.plot(x, graphy, 'r')
  769. out = self.pcap_filepath.replace('.pcap', '_plot-interval-ip-dst-cum-ent' + file_ending)
  770. plt.savefig(out, dpi=500)
  771. return out
  772. def plot_interval_ip_src_cum_ent(file_ending: str):
  773. plt.gcf().clear()
  774. result = self.stats_db._process_user_defined_query(
  775. "SELECT lastPktTimestamp, ipSrcCumEntropy FROM interval_statistics ORDER BY lastPktTimestamp")
  776. graphx, graphy = [], []
  777. for row in result:
  778. graphx.append(row[0])
  779. graphy.append(row[1])
  780. plt.autoscale(enable=True, axis='both')
  781. plt.title("Source IP Cumulative Entropy")
  782. plt.xlabel('Timestamp')
  783. plt.ylabel('Entropy')
  784. plt.xlim([0, len(graphx)])
  785. plt.grid(True)
  786. # timestamp on x-axis
  787. x = range(0, len(graphx))
  788. my_xticks = graphx
  789. plt.xticks(x, my_xticks, rotation='vertical', fontsize=5)
  790. plt.tight_layout()
  791. # limit the number of xticks
  792. plt.locator_params(axis='x',nbins=20)
  793. plt.plot(x, graphy, 'r')
  794. out = self.pcap_filepath.replace('.pcap', '_plot-interval-ip-src-cum-ent' + file_ending)
  795. plt.savefig(out, dpi=500)
  796. return out
  797. def plot_interval_new_ip(file_ending: str):
  798. plt.gcf().clear()
  799. result = self.stats_db._process_user_defined_query(
  800. "SELECT lastPktTimestamp, newIPCount FROM interval_statistics ORDER BY lastPktTimestamp")
  801. graphx, graphy = [], []
  802. for row in result:
  803. graphx.append(row[0])
  804. graphy.append(row[1])
  805. plt.autoscale(enable=True, axis='both')
  806. plt.title("IP Novelty Distribution")
  807. plt.xlabel('Timestamp')
  808. plt.ylabel('Novel values count')
  809. plt.xlim([0, len(graphx)])
  810. plt.grid(True)
  811. width = 0.5
  812. # timestamp on x-axis
  813. x = range(0, len(graphx))
  814. my_xticks = graphx
  815. plt.xticks(x, my_xticks, rotation='vertical', fontsize=5)
  816. plt.tight_layout()
  817. # limit the number of xticks
  818. plt.locator_params(axis='x', nbins=20)
  819. plt.bar(x, graphy, width, align='center', linewidth=1, color='red', edgecolor='red')
  820. out = self.pcap_filepath.replace('.pcap', '_plot-interval-novel-ip-dist' + file_ending)
  821. plt.savefig(out, dpi=500)
  822. return out
  823. def plot_interval_new_port(file_ending: str):
  824. plt.gcf().clear()
  825. result = self.stats_db._process_user_defined_query(
  826. "SELECT lastPktTimestamp, newPortCount FROM interval_statistics ORDER BY lastPktTimestamp")
  827. graphx, graphy = [], []
  828. for row in result:
  829. graphx.append(row[0])
  830. graphy.append(row[1])
  831. plt.autoscale(enable=True, axis='both')
  832. plt.title("Port Novelty Distribution")
  833. plt.xlabel('Timestamp')
  834. plt.ylabel('Novel values count')
  835. plt.xlim([0, len(graphx)])
  836. plt.grid(True)
  837. width = 0.5
  838. # timestamp on x-axis
  839. x = range(0, len(graphx))
  840. my_xticks = graphx
  841. plt.xticks(x, my_xticks, rotation='vertical', fontsize=5)
  842. plt.tight_layout()
  843. # limit the number of xticks
  844. plt.locator_params(axis='x', nbins=20)
  845. plt.bar(x, graphy, width, align='center', linewidth=1, color='red', edgecolor='red')
  846. out = self.pcap_filepath.replace('.pcap', '_plot-interval-novel-port-dist' + file_ending)
  847. plt.savefig(out, dpi=500)
  848. return out
  849. def plot_interval_new_ttl(file_ending: str):
  850. plt.gcf().clear()
  851. result = self.stats_db._process_user_defined_query(
  852. "SELECT lastPktTimestamp, newTTLCount FROM interval_statistics ORDER BY lastPktTimestamp")
  853. if(result):
  854. graphx, graphy = [], []
  855. for row in result:
  856. graphx.append(row[0])
  857. graphy.append(row[1])
  858. plt.autoscale(enable=True, axis='both')
  859. plt.title("TTL Novelty Distribution")
  860. plt.xlabel('Timestamp')
  861. plt.ylabel('Novel values count')
  862. plt.xlim([0, len(graphx)])
  863. plt.grid(True)
  864. width = 0.5
  865. # timestamp on x-axis
  866. x = range(0, len(graphx))
  867. my_xticks = graphx
  868. plt.xticks(x, my_xticks, rotation='vertical', fontsize=5)
  869. plt.tight_layout()
  870. # limit the number of xticks
  871. plt.locator_params(axis='x', nbins=20)
  872. plt.bar(x, graphy, width, align='center', linewidth=1, color='red', edgecolor='red')
  873. out = self.pcap_filepath.replace('.pcap', '_plot-interval-novel-ttl-dist' + file_ending)
  874. plt.savefig(out, dpi=500)
  875. return out
  876. else:
  877. print("Error plot TTL: No TTL values found!")
  878. def plot_interval_new_tos(file_ending: str):
  879. plt.gcf().clear()
  880. result = self.stats_db._process_user_defined_query(
  881. "SELECT lastPktTimestamp, newToSCount FROM interval_statistics ORDER BY lastPktTimestamp")
  882. graphx, graphy = [], []
  883. for row in result:
  884. graphx.append(row[0])
  885. graphy.append(row[1])
  886. plt.autoscale(enable=True, axis='both')
  887. plt.title("ToS Novelty Distribution")
  888. plt.xlabel('Timestamp')
  889. plt.ylabel('Novel values count')
  890. plt.xlim([0, len(graphx)])
  891. plt.grid(True)
  892. width = 0.5
  893. # timestamp on x-axis
  894. x = range(0, len(graphx))
  895. my_xticks = graphx
  896. plt.xticks(x, my_xticks, rotation='vertical', fontsize=5)
  897. plt.tight_layout()
  898. # limit the number of xticks
  899. plt.locator_params(axis='x', nbins=20)
  900. plt.bar(x, graphy, width, align='center', linewidth=1, color='red', edgecolor='red')
  901. out = self.pcap_filepath.replace('.pcap', '_plot-interval-novel-tos-dist' + file_ending)
  902. plt.savefig(out, dpi=500)
  903. return out
  904. def plot_interval_new_win_size(file_ending: str):
  905. plt.gcf().clear()
  906. result = self.stats_db._process_user_defined_query(
  907. "SELECT lastPktTimestamp, newWinSizeCount FROM interval_statistics ORDER BY lastPktTimestamp")
  908. if(result):
  909. graphx, graphy = [], []
  910. for row in result:
  911. graphx.append(row[0])
  912. graphy.append(row[1])
  913. plt.autoscale(enable=True, axis='both')
  914. plt.title("Window Size Novelty Distribution")
  915. plt.xlabel('Timestamp')
  916. plt.ylabel('Novel values count')
  917. plt.xlim([0, len(graphx)])
  918. plt.grid(True)
  919. width = 0.5
  920. # timestamp on x-axis
  921. x = range(0, len(graphx))
  922. my_xticks = graphx
  923. plt.xticks(x, my_xticks, rotation='vertical', fontsize=5)
  924. plt.tight_layout()
  925. # limit the number of xticks
  926. plt.locator_params(axis='x', nbins=20)
  927. plt.bar(x, graphy, width, align='center', linewidth=1, color='red', edgecolor='red')
  928. out = self.pcap_filepath.replace('.pcap', '_plot-interval-novel-win-size-dist' + file_ending)
  929. plt.savefig(out, dpi=500)
  930. return out
  931. else:
  932. print("Error plot new values WinSize: No WinSize values found!")
  933. def plot_interval_new_mss(file_ending: str):
  934. plt.gcf().clear()
  935. result = self.stats_db._process_user_defined_query(
  936. "SELECT lastPktTimestamp, newMSSCount FROM interval_statistics ORDER BY lastPktTimestamp")
  937. if(result):
  938. graphx, graphy = [], []
  939. for row in result:
  940. graphx.append(row[0])
  941. graphy.append(row[1])
  942. plt.autoscale(enable=True, axis='both')
  943. plt.title("MSS Novelty Distribution")
  944. plt.xlabel('Timestamp')
  945. plt.ylabel('Novel values count')
  946. plt.xlim([0, len(graphx)])
  947. plt.grid(True)
  948. width = 0.5
  949. # timestamp on x-axis
  950. x = range(0, len(graphx))
  951. my_xticks = graphx
  952. plt.xticks(x, my_xticks, rotation='vertical', fontsize=5)
  953. plt.tight_layout()
  954. # limit the number of xticks
  955. plt.locator_params(axis='x', nbins=20)
  956. plt.bar(x, graphy, width, align='center', linewidth=1, color='red', edgecolor='red')
  957. out = self.pcap_filepath.replace('.pcap', '_plot-interval-novel-mss-dist' + file_ending)
  958. plt.savefig(out, dpi=500)
  959. return out
  960. else:
  961. print("Error plot new values MSS: No MSS values found!")
  962. ttl_out_path = plot_ttl('.' + format)
  963. mss_out_path = plot_mss('.' + format)
  964. win_out_path = plot_win('.' + format)
  965. protocol_out_path = plot_protocol('.' + format)
  966. port_out_path = plot_port('.' + format)
  967. #ip_src_out_path = plot_ip_src('.' + format)
  968. #ip_dst_out_path = plot_ip_dst('.' + format)
  969. plot_interval_pktCount = plot_interval_pktCount('.' + format)
  970. plot_interval_ip_src_ent = plot_interval_ip_src_ent('.' + format)
  971. plot_interval_ip_dst_ent = plot_interval_ip_dst_ent('.' + format)
  972. plot_interval_ip_src_cum_ent = plot_interval_ip_src_cum_ent('.' + format)
  973. plot_interval_ip_dst_cum_ent = plot_interval_ip_dst_cum_ent('.' + format)
  974. plot_interval_new_ip = plot_interval_new_ip('.' + format)
  975. plot_interval_new_port = plot_interval_new_port('.' + format)
  976. plot_interval_new_ttl = plot_interval_new_ttl('.' + format)
  977. plot_interval_new_tos = plot_interval_new_tos('.' + format)
  978. plot_interval_new_win_size = plot_interval_new_win_size('.' + format)
  979. plot_interval_new_mss = plot_interval_new_mss('.' + format)
  980. print("Saved plots in the input PCAP directory.")