Statistics.py 50 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161
  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 & Dst 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 = []
  266. if self.do_extra_tests:
  267. output = [("Payload ratio", payloadRatio, "%"),
  268. ("Incorrect TCP checksum ratio", incorrectChecksumRatio, "%")]
  269. output = output + [("# IP addresses", sum([x[0] for x in newIPCount]), ""),
  270. ("IP Src Entropy", ipSrcEntropy, ""),
  271. ("IP Src Normalized Entropy", ipSrcNormEntropy, ""),
  272. ("IP Dst Entropy", ipDstEntropy, ""),
  273. ("IP Dst Normalized Entropy", ipDstNormEntropy, ""),
  274. ("# TTL values", sum([x[0] for x in newTTLCount]), ""),
  275. ("TTL Distribution Entropy", ipNoveltyDistEntropy, ""),
  276. ("TTL Entropy", ttlEntropy, ""),
  277. ("TTL Normalized Entropy", ttlNormEntropy, ""),
  278. ("TTL Distribution Entropy", ttlNoveltyDistEntropy, ""),
  279. ("# WinSize values", sum([x[0] for x in newWinSizeCount]), ""),
  280. ("WinSize Entropy", winEntropy, ""),
  281. ("WinSize Normalized Entropy", winNormEntropy, ""),
  282. ("WinSize Distribution Entropy", winNoveltyDistEntropy, ""),
  283. ("# ToS values", sum([x[0] for x in newToSCount]), ""),
  284. ("ToS Entropy", tosEntropy, ""),
  285. ("ToS Normalized Entropy", tosNormEntropy, ""),
  286. ("ToS Distribution Entropy", tosNoveltyDistEntropy, ""),
  287. ("# MSS values", sum([x[0] for x in newMSSCount]), ""),
  288. ("MSS Entropy", mssEntropy, ""),
  289. ("MSS Normalized Entropy", mssNormEntropy, ""),
  290. ("MSS Distribution Entropy", mssNoveltyDistEntropy, ""),
  291. ("======================","","")]
  292. # Reasoning the statistics values
  293. if self.do_extra_tests:
  294. if payloadRatio > 80:
  295. output.append(("WARNING: Too high payload ratio", payloadRatio, "%."))
  296. if payloadRatio < 30:
  297. output.append(("WARNING: Too low payload ratio", payloadRatio, "% (Injecting attacks that are carried out in the packet payloads is not recommmanded)."))
  298. if incorrectChecksumRatio > 5:
  299. output.append(("WARNING: High incorrect TCP checksum ratio",incorrectChecksumRatio,"%."))
  300. if ipSrcNormEntropy > 0.65:
  301. output.append(("WARNING: High IP source normalized entropy",ipSrcNormEntropy,"."))
  302. if ipSrcNormEntropy < 0.2:
  303. output.append(("WARNING: Low IP source normalized entropy", ipSrcNormEntropy, "."))
  304. if ipDstNormEntropy > 0.65:
  305. output.append(("WARNING: High IP destination normalized entropy", ipDstNormEntropy, "."))
  306. if ipDstNormEntropy < 0.2:
  307. output.append(("WARNING: Low IP destination normalized entropy", ipDstNormEntropy, "."))
  308. if ttlNormEntropy > 0.65:
  309. output.append(("WARNING: High TTL normalized entropy", ttlNormEntropy, "."))
  310. if ttlNormEntropy < 0.2:
  311. output.append(("WARNING: Low TTL normalized entropy", ttlNormEntropy, "."))
  312. if ttlNoveltyDistEntropy < 1:
  313. output.append(("WARNING: Too low TTL novelty distribution entropy", ttlNoveltyDistEntropy,
  314. "(The distribution of the novel TTL values is suspicious)."))
  315. if winNormEntropy > 0.6:
  316. output.append(("WARNING: High Window Size normalized entropy", winNormEntropy, "."))
  317. if winNormEntropy < 0.1:
  318. output.append(("WARNING: Low Window Size normalized entropy", winNormEntropy, "."))
  319. if winNoveltyDistEntropy < 4:
  320. output.append(("WARNING: Low Window Size novelty distribution entropy", winNoveltyDistEntropy,
  321. "(The distribution of the novel Window Size values is suspicious)."))
  322. if tosNormEntropy > 0.4:
  323. output.append(("WARNING: High ToS normalized entropy", tosNormEntropy, "."))
  324. if tosNormEntropy < 0.1:
  325. output.append(("WARNING: Low ToS normalized entropy", tosNormEntropy, "."))
  326. if tosNoveltyDistEntropy < 0.5:
  327. output.append(("WARNING: Low ToS novelty distribution entropy", tosNoveltyDistEntropy,
  328. "(The distribution of the novel ToS values is suspicious)."))
  329. if mssNormEntropy > 0.4:
  330. output.append(("WARNING: High MSS normalized entropy", mssNormEntropy, "."))
  331. if mssNormEntropy < 0.1:
  332. output.append(("WARNING: Low MSS normalized entropy", mssNormEntropy, "."))
  333. if mssNoveltyDistEntropy < 0.5:
  334. output.append(("WARNING: Low MSS novelty distribution entropy", mssNoveltyDistEntropy,
  335. "(The distribution of the novel MSS values is suspicious)."))
  336. if bigMSS > 50:
  337. output.append(("WARNING: High ratio of MSS > 1460", bigMSS, "% (High fragmentation rate in Ethernet)."))
  338. if port0Count > 0:
  339. output.append(("WARNING: Port number 0 is used in ",port0Count,"packets (awkward-looking port)."))
  340. if reservedPortCount > 0:
  341. output.append(("WARNING: Reserved port numbers are used in ",reservedPortCount,"packets (uncommonly-used ports)."))
  342. return output
  343. def write_statistics_to_file(self):
  344. """
  345. Writes the calculated basic statistics into a file.
  346. """
  347. def _write_header(title: str):
  348. """
  349. Writes the section header into the open file.
  350. :param title: The section title
  351. """
  352. target.write("====================== \n")
  353. target.write(title + " \n")
  354. target.write("====================== \n")
  355. target = open(self.pcap_filepath + ".stat", 'w')
  356. target.truncate()
  357. _write_header("PCAP file information")
  358. Statistics.write_list(self.get_file_information(), target.write)
  359. _write_header("General statistics")
  360. Statistics.write_list(self.get_general_file_statistics(), target.write)
  361. _write_header("Tests statistics")
  362. Statistics.write_list(self.get_tests_statistics(), target.write)
  363. target.close()
  364. def get_capture_duration(self):
  365. """
  366. :return: The duration of the capture in seconds
  367. """
  368. return self.file_info['captureDuration']
  369. def get_pcap_timestamp_start(self):
  370. """
  371. :return: The timestamp of the first packet in the PCAP file
  372. """
  373. return self.file_info['timestampFirstPacket']
  374. def get_pcap_timestamp_end(self):
  375. """
  376. :return: The timestamp of the last packet in the PCAP file
  377. """
  378. return self.file_info['timestampLastPacket']
  379. def get_pps_sent(self, ip_address: str):
  380. """
  381. Calculates the sent packets per seconds for a given IP address.
  382. :param ip_address: The IP address whose packets per second should be calculated
  383. :return: The sent packets per seconds for the given IP address
  384. """
  385. packets_sent = self.stats_db.process_db_query("SELECT pktsSent from ip_statistics WHERE ipAddress=?", False,
  386. (ip_address,))
  387. capture_duration = float(self.get_capture_duration())
  388. return int(float(packets_sent) / capture_duration)
  389. def get_pps_received(self, ip_address: str):
  390. """
  391. Calculate the packets per second received for a given IP address.
  392. :param ip_address: The IP address used for the calculation
  393. :return: The number of packets per second received
  394. """
  395. packets_received = self.stats_db.process_db_query("SELECT pktsReceived FROM ip_statistics WHERE ipAddress=?",
  396. False,
  397. (ip_address,))
  398. capture_duration = float(self.get_capture_duration())
  399. return int(float(packets_received) / capture_duration)
  400. def get_packet_count(self):
  401. """
  402. :return: The number of packets in the loaded PCAP file
  403. """
  404. return self.file_info['packetCount']
  405. def get_most_used_ip_address(self):
  406. """
  407. :return: The IP address/addresses with the highest sum of packets sent and received
  408. """
  409. return self.process_db_query("most_used(ipAddress)")
  410. def get_ttl_distribution(self, ipAddress: str):
  411. result = self.process_db_query('SELECT ttlValue, ttlCount from ip_ttl WHERE ipAddress="' + ipAddress + '"')
  412. result_dict = {key: value for (key, value) in result}
  413. return result_dict
  414. def get_mss_distribution(self, ipAddress: str):
  415. result = self.process_db_query('SELECT mssValue, mssCount from tcp_mss WHERE ipAddress="' + ipAddress + '"')
  416. result_dict = {key: value for (key, value) in result}
  417. return result_dict
  418. def get_win_distribution(self, ipAddress: str):
  419. result = self.process_db_query('SELECT winSize, winCount from tcp_win WHERE ipAddress="' + ipAddress + '"')
  420. result_dict = {key: value for (key, value) in result}
  421. return result_dict
  422. def get_tos_distribution(self, ipAddress: str):
  423. result = self.process_db_query('SELECT tosValue, tosCount from ip_tos WHERE ipAddress="' + ipAddress + '"')
  424. result_dict = {key: value for (key, value) in result}
  425. return result_dict
  426. def get_random_ip_address(self, count: int = 1):
  427. """
  428. :param count: The number of IP addreses to return
  429. :return: A randomly chosen IP address from the dataset or iff param count is greater than one, a list of randomly
  430. chosen IP addresses
  431. """
  432. if count == 1:
  433. return self.process_db_query("random(all(ipAddress))")
  434. else:
  435. ip_address_list = []
  436. for i in range(0, count):
  437. ip_address_list.append(self.process_db_query("random(all(ipAddress))"))
  438. return ip_address_list
  439. def get_mac_address(self, ipAddress: str):
  440. """
  441. :return: The MAC address used in the dataset for the given IP address.
  442. """
  443. return self.process_db_query('macAddress(ipAddress=' + ipAddress + ")")
  444. def get_most_used_mss(self, ipAddress: str):
  445. """
  446. :param ipAddress: The IP address whose used MSS should be determined
  447. :return: The TCP MSS value used by the IP address, or if the IP addresses never specified a MSS,
  448. then None is returned
  449. """
  450. mss_value = self.process_db_query('SELECT mssValue from tcp_mss WHERE ipAddress="' + ipAddress + '" ORDER BY mssCount DESC LIMIT 1')
  451. if isinstance(mss_value, int):
  452. return mss_value
  453. else:
  454. return None
  455. def get_most_used_ttl(self, ipAddress: str):
  456. """
  457. :param ipAddress: The IP address whose used TTL should be determined
  458. :return: The TTL value used by the IP address, or if the IP addresses never specified a TTL,
  459. then None is returned
  460. """
  461. ttl_value = self.process_db_query(
  462. 'SELECT ttlValue from ip_ttl WHERE ipAddress="' + ipAddress + '" ORDER BY ttlCount DESC LIMIT 1')
  463. if isinstance(ttl_value, int):
  464. return ttl_value
  465. else:
  466. return None
  467. def get_statistics_database(self):
  468. """
  469. :return: A reference to the statistics database object
  470. """
  471. return self.stats_db
  472. def process_db_query(self, query_string_in: str, print_results: bool = False):
  473. """
  474. Executes a string identified previously as a query. This can be a standard SQL SELECT/INSERT query or a named
  475. query.
  476. :param query_string_in: The query to be processed
  477. :param print_results: Indicates whether the results should be printed to terminal
  478. :return: The result of the query
  479. """
  480. return self.stats_db.process_db_query(query_string_in, print_results)
  481. def is_query(self, value: str):
  482. """
  483. Checks whether the given string is a standard SQL query (SELECT, INSERT) or a named query.
  484. :param value: The string to be checked
  485. :return: True if the string is recognized as a query, otherwise False.
  486. """
  487. if not isinstance(value, str):
  488. return False
  489. else:
  490. return (any(x in value.lower().strip() for x in self.stats_db.get_all_named_query_keywords()) or
  491. any(x in value.lower().strip() for x in self.stats_db.get_all_sql_query_keywords()))
  492. def calculate_standard_deviation(self, lst):
  493. """
  494. Calculates the standard deviation of a list of numbers.
  495. :param lst: The list of numbers to calculate its SD.
  496. """
  497. num_items = len(lst)
  498. mean = sum(lst) / num_items
  499. differences = [x - mean for x in lst]
  500. sq_differences = [d ** 2 for d in differences]
  501. ssd = sum(sq_differences)
  502. variance = ssd / num_items
  503. sd = sqrt(variance)
  504. return sd
  505. def plot_statistics(self, format: str = 'pdf'): #'png'
  506. """
  507. Plots the statistics associated with the dataset.
  508. :param format: The format to be used to save the statistics diagrams.
  509. """
  510. def plot_ttl(file_ending: str):
  511. plt.gcf().clear()
  512. result = self.stats_db._process_user_defined_query(
  513. "SELECT ttlValue, SUM(ttlCount) FROM ip_ttl GROUP BY ttlValue")
  514. graphx, graphy = [], []
  515. for row in result:
  516. graphx.append(row[0])
  517. graphy.append(row[1])
  518. plt.autoscale(enable=True, axis='both')
  519. plt.title("TTL Distribution")
  520. plt.xlabel('TTL Value')
  521. plt.ylabel('Number of Packets')
  522. width = 0.1
  523. plt.xlim([0, max(graphx)])
  524. plt.grid(True)
  525. plt.bar(graphx, graphy, width, align='center', linewidth=1, color='red', edgecolor='red')
  526. out = self.pcap_filepath.replace('.pcap', '_plot-ttl' + file_ending)
  527. plt.savefig(out,dpi=500)
  528. return out
  529. def plot_mss(file_ending: str):
  530. plt.gcf().clear()
  531. result = self.stats_db._process_user_defined_query(
  532. "SELECT mssValue, SUM(mssCount) FROM tcp_mss GROUP BY mssValue")
  533. if(result):
  534. graphx, graphy = [], []
  535. for row in result:
  536. graphx.append(row[0])
  537. graphy.append(row[1])
  538. plt.autoscale(enable=True, axis='both')
  539. plt.title("MSS Distribution")
  540. plt.xlabel('MSS Value')
  541. plt.ylabel('Number of Packets')
  542. width = 0.1
  543. plt.xlim([0, max(graphx)])
  544. plt.grid(True)
  545. plt.bar(graphx, graphy, width, align='center', linewidth=1, color='red', edgecolor='red')
  546. out = self.pcap_filepath.replace('.pcap', '_plot-mss' + file_ending)
  547. plt.savefig(out,dpi=500)
  548. return out
  549. else:
  550. print("Error plot MSS: No MSS values found!")
  551. def plot_win(file_ending: str):
  552. plt.gcf().clear()
  553. result = self.stats_db._process_user_defined_query(
  554. "SELECT winSize, SUM(winCount) FROM tcp_win GROUP BY winSize")
  555. if (result):
  556. graphx, graphy = [], []
  557. for row in result:
  558. graphx.append(row[0])
  559. graphy.append(row[1])
  560. plt.autoscale(enable=True, axis='both')
  561. plt.title("Window Size Distribution")
  562. plt.xlabel('Window Size')
  563. plt.ylabel('Number of Packets')
  564. width = 0.1
  565. plt.xlim([0, max(graphx)])
  566. plt.grid(True)
  567. plt.bar(graphx, graphy, width, align='center', linewidth=1, color='red', edgecolor='red')
  568. out = self.pcap_filepath.replace('.pcap', '_plot-win' + file_ending)
  569. plt.savefig(out,dpi=500)
  570. return out
  571. else:
  572. print("Error plot WinSize: No WinSize values found!")
  573. def plot_protocol(file_ending: str):
  574. plt.gcf().clear()
  575. result = self.stats_db._process_user_defined_query(
  576. "SELECT protocolName, SUM(protocolCount) FROM ip_protocols GROUP BY protocolName")
  577. if (result):
  578. graphx, graphy = [], []
  579. for row in result:
  580. graphx.append(row[0])
  581. graphy.append(row[1])
  582. plt.autoscale(enable=True, axis='both')
  583. plt.title("Protocols Distribution")
  584. plt.xlabel('Protocols')
  585. plt.ylabel('Number of Packets')
  586. width = 0.1
  587. plt.xlim([0, len(graphx)])
  588. plt.grid(True)
  589. # Protocols' names on x-axis
  590. x = range(0,len(graphx))
  591. my_xticks = graphx
  592. plt.xticks(x, my_xticks)
  593. plt.bar(x, graphy, width, align='center', linewidth=1, color='red', edgecolor='red')
  594. out = self.pcap_filepath.replace('.pcap', '_plot-protocol' + file_ending)
  595. plt.savefig(out,dpi=500)
  596. return out
  597. else:
  598. print("Error plot protocol: No protocol values found!")
  599. def plot_port(file_ending: str):
  600. plt.gcf().clear()
  601. result = self.stats_db._process_user_defined_query(
  602. "SELECT portNumber, SUM(portCount) FROM ip_ports GROUP BY portNumber")
  603. graphx, graphy = [], []
  604. for row in result:
  605. graphx.append(row[0])
  606. graphy.append(row[1])
  607. plt.autoscale(enable=True, axis='both')
  608. plt.title("Ports Distribution")
  609. plt.xlabel('Ports Numbers')
  610. plt.ylabel('Number of Packets')
  611. width = 0.1
  612. plt.xlim([0, max(graphx)])
  613. plt.grid(True)
  614. plt.bar(graphx, graphy, width, align='center', linewidth=1, color='red', edgecolor='red')
  615. out = self.pcap_filepath.replace('.pcap', '_plot-port' + file_ending)
  616. plt.savefig(out,dpi=500)
  617. return out
  618. # This distribution is not drawable for big datasets
  619. def plot_ip_src(file_ending: str):
  620. plt.gcf().clear()
  621. result = self.stats_db._process_user_defined_query(
  622. "SELECT ipAddress, pktsSent FROM ip_statistics")
  623. graphx, graphy = [], []
  624. for row in result:
  625. graphx.append(row[0])
  626. graphy.append(row[1])
  627. plt.autoscale(enable=True, axis='both')
  628. plt.title("Source IP Distribution")
  629. plt.xlabel('Source IP')
  630. plt.ylabel('Number of Packets')
  631. width = 0.1
  632. plt.xlim([0, len(graphx)])
  633. plt.grid(True)
  634. # IPs on x-axis
  635. x = range(0, len(graphx))
  636. my_xticks = graphx
  637. plt.xticks(x, my_xticks, rotation='vertical', fontsize=5)
  638. plt.tight_layout()
  639. # limit the number of xticks
  640. plt.locator_params(axis='x', nbins=20)
  641. plt.bar(x, graphy, width, align='center', linewidth=1, color='red', edgecolor='red')
  642. out = self.pcap_filepath.replace('.pcap', '_plot-ip-src' + file_ending)
  643. plt.savefig(out, dpi=500)
  644. return out
  645. # This distribution is not drawable for big datasets
  646. def plot_ip_dst(file_ending: str):
  647. plt.gcf().clear()
  648. result = self.stats_db._process_user_defined_query(
  649. "SELECT ipAddress, pktsReceived FROM ip_statistics")
  650. graphx, graphy = [], []
  651. for row in result:
  652. graphx.append(row[0])
  653. graphy.append(row[1])
  654. plt.autoscale(enable=True, axis='both')
  655. plt.title("Destination IP Distribution")
  656. plt.xlabel('Destination IP')
  657. plt.ylabel('Number of Packets')
  658. width = 0.1
  659. plt.xlim([0, len(graphx)])
  660. plt.grid(True)
  661. # IPs on x-axis
  662. x = range(0, len(graphx))
  663. my_xticks = graphx
  664. plt.xticks(x, my_xticks, rotation='vertical', fontsize=5)
  665. plt.tight_layout()
  666. # limit the number of xticks
  667. plt.locator_params(axis='x', nbins=20)
  668. plt.bar(x, graphy, width, align='center', linewidth=1, color='red', edgecolor='red')
  669. out = self.pcap_filepath.replace('.pcap', '_plot-ip-dst' + file_ending)
  670. plt.savefig(out, dpi=500)
  671. return out
  672. def plot_interval_pktCount(file_ending: str):
  673. plt.gcf().clear()
  674. result = self.stats_db._process_user_defined_query(
  675. "SELECT lastPktTimestamp, pktsCount FROM interval_statistics ORDER BY lastPktTimestamp")
  676. graphx, graphy = [], []
  677. for row in result:
  678. graphx.append(row[0])
  679. graphy.append(row[1])
  680. plt.autoscale(enable=True, axis='both')
  681. plt.title("Packet Rate")
  682. # plt.xlabel('Timestamp')
  683. plt.xlabel('Time Interval')
  684. plt.ylabel('Number of Packets')
  685. width = 0.5
  686. plt.xlim([0, len(graphx)])
  687. plt.grid(True)
  688. # timestamp on x-axis
  689. x = range(0, len(graphx))
  690. # my_xticks = graphx
  691. # plt.xticks(x, my_xticks, rotation='vertical', fontsize=5)
  692. # plt.tight_layout()
  693. # limit the number of xticks
  694. plt.locator_params(axis='x', nbins=20)
  695. plt.bar(x, graphy, width, align='center', linewidth=1, color='red', edgecolor='red')
  696. out = self.pcap_filepath.replace('.pcap', '_plot-interval-pkt-count' + file_ending)
  697. plt.savefig(out, dpi=500)
  698. return out
  699. def plot_interval_ip_src_ent(file_ending: str):
  700. plt.gcf().clear()
  701. result = self.stats_db._process_user_defined_query(
  702. "SELECT lastPktTimestamp, ipSrcEntropy FROM interval_statistics ORDER BY lastPktTimestamp")
  703. graphx, graphy = [], []
  704. for row in result:
  705. graphx.append(row[0])
  706. graphy.append(row[1])
  707. # If entropy was not calculated do not plot the graph
  708. if graphy[0] != -1:
  709. plt.autoscale(enable=True, axis='both')
  710. plt.title("Source IP Entropy")
  711. # plt.xlabel('Timestamp')
  712. plt.xlabel('Time Interval')
  713. plt.ylabel('Entropy')
  714. width = 0.5
  715. plt.xlim([0, len(graphx)])
  716. plt.grid(True)
  717. # timestamp on x-axis
  718. x = range(0, len(graphx))
  719. # my_xticks = graphx
  720. # plt.xticks(x, my_xticks, rotation='vertical', fontsize=5)
  721. # plt.tight_layout()
  722. # limit the number of xticks
  723. plt.locator_params(axis='x', nbins=20)
  724. plt.bar(x, graphy, width, align='center', linewidth=1, color='red', edgecolor='red')
  725. out = self.pcap_filepath.replace('.pcap', '_plot-interval-ip-src-ent' + file_ending)
  726. plt.savefig(out, dpi=500)
  727. return out
  728. def plot_interval_ip_dst_ent(file_ending: str):
  729. plt.gcf().clear()
  730. result = self.stats_db._process_user_defined_query(
  731. "SELECT lastPktTimestamp, ipDstEntropy FROM interval_statistics ORDER BY lastPktTimestamp")
  732. graphx, graphy = [], []
  733. for row in result:
  734. graphx.append(row[0])
  735. graphy.append(row[1])
  736. # If entropy was not calculated do not plot the graph
  737. if graphy[0] != -1:
  738. plt.autoscale(enable=True, axis='both')
  739. plt.title("Destination IP Entropy")
  740. # plt.xlabel('Timestamp')
  741. plt.xlabel('Time Interval')
  742. plt.ylabel('Entropy')
  743. width = 0.5
  744. plt.xlim([0, len(graphx)])
  745. plt.grid(True)
  746. # timestamp on x-axis
  747. x = range(0, len(graphx))
  748. # my_xticks = graphx
  749. # plt.xticks(x, my_xticks, rotation='vertical', fontsize=5)
  750. # plt.tight_layout()
  751. # limit the number of xticks
  752. plt.locator_params(axis='x', nbins=20)
  753. plt.bar(x, graphy, width, align='center', linewidth=1, color='red', edgecolor='red')
  754. out = self.pcap_filepath.replace('.pcap', '_plot-interval-ip-dst-ent' + file_ending)
  755. plt.savefig(out, dpi=500)
  756. return out
  757. def plot_interval_ip_dst_cum_ent(file_ending: str):
  758. plt.gcf().clear()
  759. result = self.stats_db._process_user_defined_query(
  760. "SELECT lastPktTimestamp, ipDstCumEntropy FROM interval_statistics ORDER BY lastPktTimestamp")
  761. graphx, graphy = [], []
  762. for row in result:
  763. graphx.append(row[0])
  764. graphy.append(row[1])
  765. # If entropy was not calculated do not plot the graph
  766. if graphy[0] != -1:
  767. plt.autoscale(enable=True, axis='both')
  768. plt.title("Destination IP Cumulative Entropy")
  769. # plt.xlabel('Timestamp')
  770. plt.xlabel('Time Interval')
  771. plt.ylabel('Entropy')
  772. plt.xlim([0, len(graphx)])
  773. plt.grid(True)
  774. # timestamp on x-axis
  775. x = range(0, len(graphx))
  776. # my_xticks = graphx
  777. # plt.xticks(x, my_xticks, rotation='vertical', fontsize=5)
  778. # plt.tight_layout()
  779. # limit the number of xticks
  780. plt.locator_params(axis='x', nbins=20)
  781. plt.plot(x, graphy, 'r')
  782. out = self.pcap_filepath.replace('.pcap', '_plot-interval-ip-dst-cum-ent' + file_ending)
  783. plt.savefig(out, dpi=500)
  784. return out
  785. def plot_interval_ip_src_cum_ent(file_ending: str):
  786. plt.gcf().clear()
  787. result = self.stats_db._process_user_defined_query(
  788. "SELECT lastPktTimestamp, ipSrcCumEntropy FROM interval_statistics ORDER BY lastPktTimestamp")
  789. graphx, graphy = [], []
  790. for row in result:
  791. graphx.append(row[0])
  792. graphy.append(row[1])
  793. # If entropy was not calculated do not plot the graph
  794. if graphy[0] != -1:
  795. plt.autoscale(enable=True, axis='both')
  796. plt.title("Source IP Cumulative Entropy")
  797. # plt.xlabel('Timestamp')
  798. plt.xlabel('Time Interval')
  799. plt.ylabel('Entropy')
  800. plt.xlim([0, len(graphx)])
  801. plt.grid(True)
  802. # timestamp on x-axis
  803. x = range(0, len(graphx))
  804. # my_xticks = graphx
  805. # plt.xticks(x, my_xticks, rotation='vertical', fontsize=5)
  806. # plt.tight_layout()
  807. # limit the number of xticks
  808. plt.locator_params(axis='x',nbins=20)
  809. plt.plot(x, graphy, 'r')
  810. out = self.pcap_filepath.replace('.pcap', '_plot-interval-ip-src-cum-ent' + file_ending)
  811. plt.savefig(out, dpi=500)
  812. return out
  813. def plot_interval_new_ip(file_ending: str):
  814. plt.gcf().clear()
  815. result = self.stats_db._process_user_defined_query(
  816. "SELECT lastPktTimestamp, newIPCount FROM interval_statistics ORDER BY lastPktTimestamp")
  817. graphx, graphy = [], []
  818. for row in result:
  819. graphx.append(row[0])
  820. graphy.append(row[1])
  821. plt.autoscale(enable=True, axis='both')
  822. plt.title("IP Novelty Distribution")
  823. # plt.xlabel('Timestamp')
  824. plt.xlabel('Time Interval')
  825. plt.ylabel('Novel values count')
  826. plt.xlim([0, len(graphx)])
  827. plt.grid(True)
  828. width = 0.5
  829. # timestamp on x-axis
  830. x = range(0, len(graphx))
  831. # my_xticks = graphx
  832. # plt.xticks(x, my_xticks, rotation='vertical', fontsize=5)
  833. # plt.tight_layout()
  834. # limit the number of xticks
  835. plt.locator_params(axis='x', nbins=20)
  836. plt.bar(x, graphy, width, align='center', linewidth=1, color='red', edgecolor='red')
  837. out = self.pcap_filepath.replace('.pcap', '_plot-interval-novel-ip-dist' + file_ending)
  838. plt.savefig(out, dpi=500)
  839. return out
  840. def plot_interval_new_port(file_ending: str):
  841. plt.gcf().clear()
  842. result = self.stats_db._process_user_defined_query(
  843. "SELECT lastPktTimestamp, newPortCount FROM interval_statistics ORDER BY lastPktTimestamp")
  844. graphx, graphy = [], []
  845. for row in result:
  846. graphx.append(row[0])
  847. graphy.append(row[1])
  848. plt.autoscale(enable=True, axis='both')
  849. plt.title("Port Novelty Distribution")
  850. # plt.xlabel('Timestamp')
  851. plt.xlabel('Time Interval')
  852. plt.ylabel('Novel values count')
  853. plt.xlim([0, len(graphx)])
  854. plt.grid(True)
  855. width = 0.5
  856. # timestamp on x-axis
  857. x = range(0, len(graphx))
  858. # my_xticks = graphx
  859. # plt.xticks(x, my_xticks, rotation='vertical', fontsize=5)
  860. # plt.tight_layout()
  861. # limit the number of xticks
  862. plt.locator_params(axis='x', nbins=20)
  863. plt.bar(x, graphy, width, align='center', linewidth=1, color='red', edgecolor='red')
  864. out = self.pcap_filepath.replace('.pcap', '_plot-interval-novel-port-dist' + file_ending)
  865. plt.savefig(out, dpi=500)
  866. return out
  867. def plot_interval_new_ttl(file_ending: str):
  868. plt.gcf().clear()
  869. result = self.stats_db._process_user_defined_query(
  870. "SELECT lastPktTimestamp, newTTLCount FROM interval_statistics ORDER BY lastPktTimestamp")
  871. if(result):
  872. graphx, graphy = [], []
  873. for row in result:
  874. graphx.append(row[0])
  875. graphy.append(row[1])
  876. plt.autoscale(enable=True, axis='both')
  877. plt.title("TTL Novelty Distribution")
  878. # plt.xlabel('Timestamp')
  879. plt.xlabel('Time Interval')
  880. plt.ylabel('Novel values count')
  881. plt.xlim([0, len(graphx)])
  882. plt.grid(True)
  883. width = 0.5
  884. # timestamp on x-axis
  885. x = range(0, len(graphx))
  886. # my_xticks = graphx
  887. # plt.xticks(x, my_xticks, rotation='vertical', fontsize=5)
  888. # plt.tight_layout()
  889. # limit the number of xticks
  890. plt.locator_params(axis='x', nbins=20)
  891. plt.bar(x, graphy, width, align='center', linewidth=1, color='red', edgecolor='red')
  892. out = self.pcap_filepath.replace('.pcap', '_plot-interval-novel-ttl-dist' + file_ending)
  893. plt.savefig(out, dpi=500)
  894. return out
  895. else:
  896. print("Error plot TTL: No TTL values found!")
  897. def plot_interval_new_tos(file_ending: str):
  898. plt.gcf().clear()
  899. result = self.stats_db._process_user_defined_query(
  900. "SELECT lastPktTimestamp, newToSCount FROM interval_statistics ORDER BY lastPktTimestamp")
  901. graphx, graphy = [], []
  902. for row in result:
  903. graphx.append(row[0])
  904. graphy.append(row[1])
  905. plt.autoscale(enable=True, axis='both')
  906. plt.title("ToS Novelty Distribution")
  907. # plt.xlabel('Timestamp')
  908. plt.xlabel('Time Interval')
  909. plt.ylabel('Novel values count')
  910. plt.xlim([0, len(graphx)])
  911. plt.grid(True)
  912. width = 0.5
  913. # timestamp on x-axis
  914. x = range(0, len(graphx))
  915. # my_xticks = graphx
  916. # plt.xticks(x, my_xticks, rotation='vertical', fontsize=5)
  917. # plt.tight_layout()
  918. # limit the number of xticks
  919. plt.locator_params(axis='x', nbins=20)
  920. plt.bar(x, graphy, width, align='center', linewidth=1, color='red', edgecolor='red')
  921. out = self.pcap_filepath.replace('.pcap', '_plot-interval-novel-tos-dist' + file_ending)
  922. plt.savefig(out, dpi=500)
  923. return out
  924. def plot_interval_new_win_size(file_ending: str):
  925. plt.gcf().clear()
  926. result = self.stats_db._process_user_defined_query(
  927. "SELECT lastPktTimestamp, newWinSizeCount FROM interval_statistics ORDER BY lastPktTimestamp")
  928. if(result):
  929. graphx, graphy = [], []
  930. for row in result:
  931. graphx.append(row[0])
  932. graphy.append(row[1])
  933. plt.autoscale(enable=True, axis='both')
  934. plt.title("Window Size Novelty Distribution")
  935. # plt.xlabel('Timestamp')
  936. plt.xlabel('Time Interval')
  937. plt.ylabel('Novel values count')
  938. plt.xlim([0, len(graphx)])
  939. plt.grid(True)
  940. width = 0.5
  941. # timestamp on x-axis
  942. x = range(0, len(graphx))
  943. # my_xticks = graphx
  944. # plt.xticks(x, my_xticks, rotation='vertical', fontsize=5)
  945. # plt.tight_layout()
  946. # limit the number of xticks
  947. plt.locator_params(axis='x', nbins=20)
  948. plt.bar(x, graphy, width, align='center', linewidth=1, color='red', edgecolor='red')
  949. out = self.pcap_filepath.replace('.pcap', '_plot-interval-novel-win-size-dist' + file_ending)
  950. plt.savefig(out, dpi=500)
  951. return out
  952. else:
  953. print("Error plot new values WinSize: No WinSize values found!")
  954. def plot_interval_new_mss(file_ending: str):
  955. plt.gcf().clear()
  956. result = self.stats_db._process_user_defined_query(
  957. "SELECT lastPktTimestamp, newMSSCount FROM interval_statistics ORDER BY lastPktTimestamp")
  958. if(result):
  959. graphx, graphy = [], []
  960. for row in result:
  961. graphx.append(row[0])
  962. graphy.append(row[1])
  963. plt.autoscale(enable=True, axis='both')
  964. plt.title("MSS Novelty Distribution")
  965. # plt.xlabel('Timestamp')
  966. plt.xlabel('Time Interval')
  967. plt.ylabel('Novel values count')
  968. plt.xlim([0, len(graphx)])
  969. plt.grid(True)
  970. width = 0.5
  971. # timestamp on x-axis
  972. x = range(0, len(graphx))
  973. # my_xticks = graphx
  974. # plt.xticks(x, my_xticks, rotation='vertical', fontsize=5)
  975. # plt.tight_layout()
  976. # limit the number of xticks
  977. plt.locator_params(axis='x', nbins=20)
  978. plt.bar(x, graphy, width, align='center', linewidth=1, color='red', edgecolor='red')
  979. out = self.pcap_filepath.replace('.pcap', '_plot-interval-novel-mss-dist' + file_ending)
  980. plt.savefig(out, dpi=500)
  981. return out
  982. else:
  983. print("Error plot new values MSS: No MSS values found!")
  984. ttl_out_path = plot_ttl('.' + format)
  985. mss_out_path = plot_mss('.' + format)
  986. win_out_path = plot_win('.' + format)
  987. protocol_out_path = plot_protocol('.' + format)
  988. port_out_path = plot_port('.' + format)
  989. #ip_src_out_path = plot_ip_src('.' + format)
  990. #ip_dst_out_path = plot_ip_dst('.' + format)
  991. plot_interval_pktCount = plot_interval_pktCount('.' + format)
  992. plot_interval_ip_src_ent = plot_interval_ip_src_ent('.' + format)
  993. plot_interval_ip_dst_ent = plot_interval_ip_dst_ent('.' + format)
  994. plot_interval_ip_src_cum_ent = plot_interval_ip_src_cum_ent('.' + format)
  995. plot_interval_ip_dst_cum_ent = plot_interval_ip_dst_cum_ent('.' + format)
  996. plot_interval_new_ip = plot_interval_new_ip('.' + format)
  997. plot_interval_new_port = plot_interval_new_port('.' + format)
  998. plot_interval_new_ttl = plot_interval_new_ttl('.' + format)
  999. plot_interval_new_tos = plot_interval_new_tos('.' + format)
  1000. plot_interval_new_win_size = plot_interval_new_win_size('.' + format)
  1001. plot_interval_new_mss = plot_interval_new_mss('.' + format)
  1002. print("Saved plots in the input PCAP directory.")