Statistics.py 49 KB

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