Statistics.py 49 KB

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