Statistics.py 49 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144
  1. from operator import itemgetter
  2. from math import sqrt, ceil, log
  3. import os
  4. import time
  5. import ID2TLib.libpcapreader as pr
  6. import matplotlib
  7. matplotlib.use('Agg')
  8. import matplotlib.pyplot as plt
  9. from ID2TLib.PcapFile import PcapFile
  10. from ID2TLib.StatsDatabase import StatsDatabase
  11. class Statistics:
  12. def __init__(self, pcap_file: PcapFile):
  13. """
  14. Creates a new Statistics object.
  15. :param pcap_file: A reference to the PcapFile object
  16. """
  17. # Fields
  18. self.pcap_filepath = pcap_file.pcap_file_path
  19. self.pcap_proc = None
  20. # Aidmar
  21. self.do_tests = False
  22. # Create folder for statistics database if required
  23. self.path_db = pcap_file.get_db_path()
  24. path_dir = os.path.dirname(self.path_db)
  25. if not os.path.isdir(path_dir):
  26. os.makedirs(path_dir)
  27. # Class instances
  28. self.stats_db = StatsDatabase(self.path_db)
  29. def load_pcap_statistics(self, flag_write_file: bool, flag_recalculate_stats: bool, flag_print_statistics: bool):
  30. """
  31. Loads the PCAP statistics for the file specified by pcap_filepath. If the database is not existing yet, the
  32. statistics are calculated by the PCAP file processor and saved into the newly created database. Otherwise the
  33. statistics are gathered directly from the existing database.
  34. :param flag_write_file: Indicates whether the statistics should be written addiotionally into a text file (True)
  35. or not (False)
  36. :param flag_recalculate_stats: Indicates whether eventually existing statistics should be recalculated
  37. :param flag_print_statistics: Indicates whether the gathered basic statistics should be printed to the terminal
  38. """
  39. # Load pcap and get loading time
  40. time_start = time.clock()
  41. # Inform user about recalculation of statistics and its reason
  42. if flag_recalculate_stats:
  43. print("Flag -r/--recalculate found. Recalculating statistics.")
  44. # Recalculate statistics if database does not exist OR param -r/--recalculate is provided
  45. if (not self.stats_db.get_db_exists()) or flag_recalculate_stats:
  46. self.pcap_proc = pr.pcap_processor(self.pcap_filepath, str(self.do_tests)) # Aidmar - do_tests
  47. self.pcap_proc.collect_statistics()
  48. self.pcap_proc.write_to_database(self.path_db)
  49. outstring_datasource = "by PCAP file processor."
  50. else:
  51. outstring_datasource = "from statistics database."
  52. # Load statistics from database
  53. self.file_info = self.stats_db.get_file_info()
  54. time_end = time.clock()
  55. print("Loaded file statistics in " + str(time_end - time_start)[:4] + " sec " + outstring_datasource)
  56. # Write statistics if param -e/--export provided
  57. if flag_write_file:
  58. self.write_statistics_to_file()
  59. # Print statistics if param -s/--statistics provided
  60. if flag_print_statistics:
  61. self.print_statistics()
  62. def get_file_information(self):
  63. """
  64. Returns a list of tuples, each containing a information of the file.
  65. :return: a list of tuples, each consisting of (description, value, unit), where unit is optional.
  66. """
  67. return [("Pcap file", self.pcap_filepath),
  68. ("Packets", self.get_packet_count(), "packets"),
  69. ("Capture length", self.get_capture_duration(), "seconds"),
  70. ("Capture start", self.get_pcap_timestamp_start()),
  71. ("Capture end", self.get_pcap_timestamp_end())]
  72. def get_general_file_statistics(self):
  73. """
  74. Returns a list of tuples, each containing a file statistic.
  75. :return: a list of tuples, each consisting of (description, value, unit).
  76. """
  77. return [("Avg. packet rate", self.file_info['avgPacketRate'], "packets/sec"),
  78. ("Avg. packet size", self.file_info['avgPacketSize'], "kbytes"),
  79. ("Avg. packets sent", self.file_info['avgPacketsSentPerHost'], "packets"),
  80. ("Avg. bandwidth in", self.file_info['avgBandwidthIn'], "kbit/s"),
  81. ("Avg. bandwidth out", self.file_info['avgBandwidthOut'], "kbit/s")]
  82. @staticmethod
  83. def write_list(desc_val_unit_list, func, line_ending="\n"):
  84. """
  85. Takes a list of tuples (statistic name, statistic value, unit) as input, generates a string of these three values
  86. and applies the function func on this string.
  87. Before generating the string, it identifies text containing a float number, casts the string to a
  88. float and rounds the value to two decimal digits.
  89. :param desc_val_unit_list: The list of tuples consisting of (description, value, unit)
  90. :param func: The function to be applied to each generated string
  91. :param line_ending: The formatting string to be applied at the end of each string
  92. """
  93. for entry in desc_val_unit_list:
  94. # Convert text containing float into float
  95. (description, value) = entry[0:2]
  96. if isinstance(value, str) and "." in value:
  97. try:
  98. value = float(value)
  99. except ValueError:
  100. pass # do nothing -> value was not a float
  101. # round float
  102. if isinstance(value, float):
  103. value = round(value, 4)
  104. # write into file
  105. if len(entry) == 3:
  106. unit = entry[2]
  107. func(description + ":\t" + str(value) + " " + unit + line_ending)
  108. else:
  109. func(description + ":\t" + str(value) + line_ending)
  110. def print_statistics(self):
  111. """
  112. Prints the basic file statistics to the terminal.
  113. """
  114. print("\nPCAP FILE INFORMATION ------------------------------")
  115. Statistics.write_list(self.get_file_information(), print, "")
  116. print("\nGENERAL FILE STATISTICS ----------------------------")
  117. Statistics.write_list(self.get_general_file_statistics(), print, "")
  118. print("\n")
  119. #Aidmar
  120. def calculate_entropy(self, frequency:list, normalized:bool = False):
  121. entropy, normalizedEnt, n = 0, 0, 0
  122. sumFreq = sum(frequency)
  123. for i, x in enumerate(frequency):
  124. p_x = float(frequency[i] / sumFreq)
  125. if p_x > 0:
  126. n += 1
  127. entropy += - p_x * log(p_x, 2)
  128. if normalized:
  129. if log(n)>0:
  130. normalizedEnt = entropy/log(n, 2)
  131. return entropy, normalizedEnt
  132. else:
  133. return entropy
  134. # Aidmar
  135. def get_tests_statistics(self):
  136. """
  137. Writes the calculated basic defects tests statistics into a file.
  138. """
  139. # self.stats_db._process_user_defined_query output is list of tuples, thus, we ned [0][0] to access data
  140. def count_frequncy(valuesList):
  141. values, frequency = [] , []
  142. for x in valuesList:
  143. if x in values:
  144. frequency[values.index(x)] += 1
  145. else:
  146. values.append(x)
  147. frequency.append(1)
  148. return values, frequency
  149. ####### Payload Tests #######
  150. sumPayloadCount = self.stats_db._process_user_defined_query("SELECT sum(payloadCount) FROM interval_statistics")
  151. pktCount = self.stats_db._process_user_defined_query("SELECT packetCount FROM file_statistics")
  152. if sumPayloadCount and pktCount:
  153. payloadRatio=0
  154. if(pktCount[0][0]!=0):
  155. payloadRatio = float(sumPayloadCount[0][0] / pktCount[0][0] * 100)
  156. else:
  157. payloadRatio = -1
  158. ####### TCP checksum Tests #######
  159. incorrectChecksumCount = self.stats_db._process_user_defined_query("SELECT sum(incorrectTCPChecksumCount) FROM interval_statistics")
  160. correctChecksumCount = self.stats_db._process_user_defined_query("SELECT avg(correctTCPChecksumCount) FROM interval_statistics")
  161. if incorrectChecksumCount and correctChecksumCount:
  162. incorrectChecksumRatio=0
  163. if(incorrectChecksumCount[0][0] + correctChecksumCount[0][0])!=0:
  164. incorrectChecksumRatio = float(incorrectChecksumCount[0][0] / (incorrectChecksumCount[0][0] + correctChecksumCount[0][0] ) * 100)
  165. else:
  166. incorrectChecksumRatio = -1
  167. ####### IP Src Tests #######
  168. result = self.stats_db._process_user_defined_query("SELECT ipAddress,pktsSent,pktsReceived FROM ip_statistics")
  169. data, srcFrequency, dstFrequency = [], [], []
  170. if result:
  171. for row in result:
  172. srcFrequency.append(row[1])
  173. dstFrequency.append(row[2])
  174. ipSrcEntropy, ipSrcNormEntropy = self.calculate_entropy(srcFrequency, True)
  175. ipDstEntropy, ipDstNormEntropy = self.calculate_entropy(dstFrequency, True)
  176. newIPCount = self.stats_db._process_user_defined_query("SELECT newIPCount FROM interval_statistics")
  177. ipNovelsPerInterval, ipNovelsPerIntervalFrequency = count_frequncy(newIPCount)
  178. ipNoveltyDistEntropy = self.calculate_entropy(ipNovelsPerIntervalFrequency)
  179. # newIPCount = self.stats_db._process_user_defined_query("SELECT newIPCount FROM interval_statistics")
  180. # # Retrieve the last cumulative entropy which is the entropy of the all IPs
  181. # result = self.stats_db._process_user_defined_query("SELECT ipSrcCumEntropy FROM interval_statistics")
  182. # ipSrcEntropy = result[-1][0]
  183. # ipSrcCount = self.stats_db._process_user_defined_query(
  184. # "SELECT COUNT(ipAddress) FROM ip_statistics WHERE pktsSent > 0")
  185. # ipSrcNormEntropy = ipSrcEntropy / log(ipSrcCount[0][0],2)
  186. # result = self.stats_db._process_user_defined_query("SELECT ipDstCumEntropy FROM interval_statistics")
  187. # ipDstEntropy = result[-1][0]
  188. # ipDstCount = self.stats_db._process_user_defined_query(
  189. # "SELECT COUNT(ipAddress) FROM ip_statistics WHERE pktsReceived > 0")
  190. # ipDstNormEntropy = ipDstEntropy / log(ipDstCount[0][0],2)
  191. ####### Ports Tests #######
  192. port0Count = self.stats_db._process_user_defined_query("SELECT SUM(portCount) FROM ip_ports WHERE portNumber = 0")
  193. if not port0Count[0][0]:
  194. port0Count = 0
  195. else:
  196. port0Count = port0Count[0][0]
  197. reservedPortCount = self.stats_db._process_user_defined_query(
  198. "SELECT SUM(portCount) FROM ip_ports WHERE portNumber IN (100,114,1023,1024,49151,49152,65535)")# could be extended
  199. if not reservedPortCount[0][0]:
  200. reservedPortCount = 0
  201. else:
  202. reservedPortCount = reservedPortCount[0][0]
  203. ####### TTL Tests #######
  204. result = self.stats_db._process_user_defined_query("SELECT ttlValue,SUM(ttlCount) FROM ip_ttl GROUP BY ttlValue")
  205. data, frequency = [], []
  206. for row in result:
  207. frequency.append(row[1])
  208. ttlEntropy, ttlNormEntropy = self.calculate_entropy(frequency,True)
  209. newTTLCount = self.stats_db._process_user_defined_query("SELECT newTTLCount FROM interval_statistics")
  210. ttlNovelsPerInterval, ttlNovelsPerIntervalFrequency = count_frequncy(newTTLCount)
  211. ttlNoveltyDistEntropy = self.calculate_entropy(ttlNovelsPerIntervalFrequency)
  212. ####### Window Size Tests #######
  213. result = self.stats_db._process_user_defined_query("SELECT winSize,SUM(winCount) FROM tcp_win GROUP BY winSize")
  214. data, frequency = [], []
  215. for row in result:
  216. frequency.append(row[1])
  217. winEntropy, winNormEntropy = self.calculate_entropy(frequency, True)
  218. newWinSizeCount = self.stats_db._process_user_defined_query("SELECT newWinSizeCount FROM interval_statistics")
  219. winNovelsPerInterval, winNovelsPerIntervalFrequency = count_frequncy(newWinSizeCount)
  220. winNoveltyDistEntropy = self.calculate_entropy(winNovelsPerIntervalFrequency)
  221. ####### ToS Tests #######
  222. result = self.stats_db._process_user_defined_query(
  223. "SELECT tosValue,SUM(tosCount) FROM ip_tos GROUP BY tosValue")
  224. data, frequency = [], []
  225. for row in result:
  226. frequency.append(row[1])
  227. tosEntropy, tosNormEntropy = self.calculate_entropy(frequency, True)
  228. newToSCount = self.stats_db._process_user_defined_query("SELECT newToSCount FROM interval_statistics")
  229. tosNovelsPerInterval, tosNovelsPerIntervalFrequency = count_frequncy(newToSCount)
  230. tosNoveltyDistEntropy = self.calculate_entropy(tosNovelsPerIntervalFrequency)
  231. ####### MSS Tests #######
  232. result = self.stats_db._process_user_defined_query(
  233. "SELECT mssValue,SUM(mssCount) FROM tcp_mss GROUP BY mssValue")
  234. data, frequency = [], []
  235. for row in result:
  236. frequency.append(row[1])
  237. mssEntropy, mssNormEntropy = self.calculate_entropy(frequency, True)
  238. newMSSCount = self.stats_db._process_user_defined_query("SELECT newMSSCount FROM interval_statistics")
  239. mssNovelsPerInterval, mssNovelsPerIntervalFrequency = count_frequncy(newMSSCount)
  240. mssNoveltyDistEntropy = self.calculate_entropy(mssNovelsPerIntervalFrequency)
  241. result = self.stats_db._process_user_defined_query("SELECT SUM(mssCount) FROM tcp_mss WHERE mssValue > 1460")
  242. # The most used MSS < 1460. Calculate the ratio of the values bigger that 1460.
  243. if not result[0][0]:
  244. result = 0
  245. else:
  246. result = result[0][0]
  247. bigMSS = (result / sum(frequency)) * 100
  248. output = [("Payload ratio", payloadRatio, "%"),
  249. ("Incorrect TCP checksum ratio", incorrectChecksumRatio, "%"),
  250. ("# IP addresses", sum([x[0] for x in newIPCount]), ""),
  251. ("IP Src Entropy", ipSrcEntropy, ""),
  252. ("IP Src Normalized Entropy", ipSrcNormEntropy, ""),
  253. ("IP Dst Entropy", ipDstEntropy, ""),
  254. ("IP Dst Normalized Entropy", ipDstNormEntropy, ""),
  255. ("# TTL values", sum([x[0] for x in newTTLCount]), ""),
  256. ("TTL Distribution Entropy", ipNoveltyDistEntropy, ""),
  257. ("TTL Entropy", ttlEntropy, ""),
  258. ("TTL Normalized Entropy", ttlNormEntropy, ""),
  259. ("TTL Distribution Entropy", ttlNoveltyDistEntropy, ""),
  260. ("# WinSize values", sum([x[0] for x in newWinSizeCount]), ""),
  261. ("WinSize Entropy", winEntropy, ""),
  262. ("WinSize Normalized Entropy", winNormEntropy, ""),
  263. ("WinSize Distribution Entropy", winNoveltyDistEntropy, ""),
  264. ("# ToS values", sum([x[0] for x in newToSCount]), ""),
  265. ("ToS Entropy", tosEntropy, ""),
  266. ("ToS Normalized Entropy", tosNormEntropy, ""),
  267. ("ToS Distribution Entropy", tosNoveltyDistEntropy, ""),
  268. ("# MSS values", sum([x[0] for x in newMSSCount]), ""),
  269. ("MSS Entropy", mssEntropy, ""),
  270. ("MSS Normalized Entropy", mssNormEntropy, ""),
  271. ("MSS Distribution Entropy", mssNoveltyDistEntropy, ""),
  272. ("======================","","")]
  273. # Reasoning the statistics values
  274. if payloadRatio > 80:
  275. output.append(("WARNING: Too high payload ratio", payloadRatio, "%."))
  276. if payloadRatio < 30:
  277. output.append(("WARNING: Too low payload ratio", payloadRatio, "% (Injecting attacks that are carried out in the packet payloads is not recommmanded)."))
  278. if incorrectChecksumRatio > 5:
  279. output.append(("WARNING: High incorrect TCP checksum ratio",incorrectChecksumRatio,"%."))
  280. if ipSrcNormEntropy > 0.65:
  281. output.append(("WARNING: High IP source normalized entropy",ipSrcNormEntropy,"."))
  282. if ipSrcNormEntropy < 0.2:
  283. output.append(("WARNING: Low IP source normalized entropy", ipSrcNormEntropy, "."))
  284. if ipDstNormEntropy > 0.65:
  285. output.append(("WARNING: High IP destination normalized entropy", ipDstNormEntropy, "."))
  286. if ipDstNormEntropy < 0.2:
  287. output.append(("WARNING: Low IP destination normalized entropy", ipDstNormEntropy, "."))
  288. if ttlNormEntropy > 0.65:
  289. output.append(("WARNING: High TTL normalized entropy", ttlNormEntropy, "."))
  290. if ttlNormEntropy < 0.2:
  291. output.append(("WARNING: Low TTL normalized entropy", ttlNormEntropy, "."))
  292. if ttlNoveltyDistEntropy < 1:
  293. output.append(("WARNING: Too low TTL novelty distribution entropy", ttlNoveltyDistEntropy,
  294. "(The distribution of the novel TTL values is suspicious)."))
  295. if winNormEntropy > 0.6:
  296. output.append(("WARNING: High Window Size normalized entropy", winNormEntropy, "."))
  297. if winNormEntropy < 0.1:
  298. output.append(("WARNING: Low Window Size normalized entropy", winNormEntropy, "."))
  299. if winNoveltyDistEntropy < 4:
  300. output.append(("WARNING: Low Window Size novelty distribution entropy", winNoveltyDistEntropy,
  301. "(The distribution of the novel Window Size values is suspicious)."))
  302. if tosNormEntropy > 0.4:
  303. output.append(("WARNING: High ToS normalized entropy", tosNormEntropy, "."))
  304. if tosNormEntropy < 0.1:
  305. output.append(("WARNING: Low ToS normalized entropy", tosNormEntropy, "."))
  306. if tosNoveltyDistEntropy < 0.5:
  307. output.append(("WARNING: Low ToS novelty distribution entropy", tosNoveltyDistEntropy,
  308. "(The distribution of the novel ToS values is suspicious)."))
  309. if mssNormEntropy > 0.4:
  310. output.append(("WARNING: High MSS normalized entropy", mssNormEntropy, "."))
  311. if mssNormEntropy < 0.1:
  312. output.append(("WARNING: Low MSS normalized entropy", mssNormEntropy, "."))
  313. if mssNoveltyDistEntropy < 0.5:
  314. output.append(("WARNING: Low MSS novelty distribution entropy", mssNoveltyDistEntropy,
  315. "(The distribution of the novel MSS values is suspicious)."))
  316. if bigMSS > 50:
  317. output.append(("WARNING: High ratio of MSS > 1460", bigMSS, "% (High fragmentation rate in Ethernet)."))
  318. if port0Count > 0:
  319. output.append(("WARNING: Port number 0 is used in ",port0Count,"packets (awkward-looking port)."))
  320. if reservedPortCount > 0:
  321. output.append(("WARNING: Reserved port numbers are used in ",reservedPortCount,"packets (uncommonly-used ports)."))
  322. return output
  323. def write_statistics_to_file(self):
  324. """
  325. Writes the calculated basic statistics into a file.
  326. """
  327. def _write_header(title: str):
  328. """
  329. Writes the section header into the open file.
  330. :param title: The section title
  331. """
  332. target.write("====================== \n")
  333. target.write(title + " \n")
  334. target.write("====================== \n")
  335. target = open(self.pcap_filepath + ".stat", 'w')
  336. target.truncate()
  337. _write_header("PCAP file information")
  338. Statistics.write_list(self.get_file_information(), target.write)
  339. _write_header("General statistics")
  340. Statistics.write_list(self.get_general_file_statistics(), target.write)
  341. _write_header("Tests statistics")
  342. Statistics.write_list(self.get_tests_statistics(), target.write)
  343. target.close()
  344. def get_capture_duration(self):
  345. """
  346. :return: The duration of the capture in seconds
  347. """
  348. return self.file_info['captureDuration']
  349. def get_pcap_timestamp_start(self):
  350. """
  351. :return: The timestamp of the first packet in the PCAP file
  352. """
  353. return self.file_info['timestampFirstPacket']
  354. def get_pcap_timestamp_end(self):
  355. """
  356. :return: The timestamp of the last packet in the PCAP file
  357. """
  358. return self.file_info['timestampLastPacket']
  359. def get_pps_sent(self, ip_address: str):
  360. """
  361. Calculates the sent packets per seconds for a given IP address.
  362. :param ip_address: The IP address whose packets per second should be calculated
  363. :return: The sent packets per seconds for the given IP address
  364. """
  365. packets_sent = self.stats_db.process_db_query("SELECT pktsSent from ip_statistics WHERE ipAddress=?", False,
  366. (ip_address,))
  367. capture_duration = float(self.get_capture_duration())
  368. return int(float(packets_sent) / capture_duration)
  369. def get_pps_received(self, ip_address: str):
  370. """
  371. Calculate the packets per second received for a given IP address.
  372. :param ip_address: The IP address used for the calculation
  373. :return: The number of packets per second received
  374. """
  375. packets_received = self.stats_db.process_db_query("SELECT pktsReceived FROM ip_statistics WHERE ipAddress=?",
  376. False,
  377. (ip_address,))
  378. capture_duration = float(self.get_capture_duration())
  379. return int(float(packets_received) / capture_duration)
  380. def get_packet_count(self):
  381. """
  382. :return: The number of packets in the loaded PCAP file
  383. """
  384. return self.file_info['packetCount']
  385. def get_most_used_ip_address(self):
  386. """
  387. :return: The IP address/addresses with the highest sum of packets sent and received
  388. """
  389. return self.process_db_query("most_used(ipAddress)")
  390. def get_ttl_distribution(self, ipAddress: str):
  391. result = self.process_db_query('SELECT ttlValue, ttlCount from ip_ttl WHERE ipAddress="' + ipAddress + '"')
  392. result_dict = {key: value for (key, value) in result}
  393. return result_dict
  394. # Aidmar
  395. def get_mss_distribution(self, ipAddress: str):
  396. result = self.process_db_query('SELECT mssValue, mssCount from tcp_mss WHERE ipAddress="' + ipAddress + '"')
  397. result_dict = {key: value for (key, value) in result}
  398. return result_dict
  399. # Aidmar
  400. def get_win_distribution(self, ipAddress: str):
  401. result = self.process_db_query('SELECT winSize, winCount from tcp_win WHERE ipAddress="' + ipAddress + '"')
  402. result_dict = {key: value for (key, value) in result}
  403. return result_dict
  404. # Aidmar
  405. def get_tos_distribution(self, ipAddress: str):
  406. result = self.process_db_query('SELECT tosValue, tosCount from ip_tos WHERE ipAddress="' + ipAddress + '"')
  407. result_dict = {key: value for (key, value) in result}
  408. return result_dict
  409. def get_random_ip_address(self, count: int = 1):
  410. """
  411. :param count: The number of IP addreses to return
  412. :return: A randomly chosen IP address from the dataset or iff param count is greater than one, a list of randomly
  413. chosen IP addresses
  414. """
  415. if count == 1:
  416. return self.process_db_query("random(all(ipAddress))")
  417. else:
  418. ip_address_list = []
  419. for i in range(0, count):
  420. ip_address_list.append(self.process_db_query("random(all(ipAddress))"))
  421. return ip_address_list
  422. def get_mac_address(self, ipAddress: str):
  423. """
  424. :return: The MAC address used in the dataset for the given IP address.
  425. """
  426. return self.process_db_query('macAddress(ipAddress=' + ipAddress + ")")
  427. # Aidmar
  428. def get_most_used_mss(self, ipAddress: str):
  429. """
  430. :param ipAddress: The IP address whose used MSS should be determined
  431. :return: The TCP MSS value used by the IP address, or if the IP addresses never specified a MSS,
  432. then None is returned
  433. """
  434. mss_value = self.process_db_query('SELECT mssValue from tcp_mss WHERE ipAddress="' + ipAddress + '" ORDER BY mssCount DESC LIMIT 1')
  435. if isinstance(mss_value, int):
  436. return mss_value
  437. else:
  438. return None
  439. def get_statistics_database(self):
  440. """
  441. :return: A reference to the statistics database object
  442. """
  443. return self.stats_db
  444. def process_db_query(self, query_string_in: str, print_results: bool = False):
  445. """
  446. Executes a string identified previously as a query. This can be a standard SQL SELECT/INSERT query or a named
  447. query.
  448. :param query_string_in: The query to be processed
  449. :param print_results: Indicates whether the results should be printed to terminal
  450. :return: The result of the query
  451. """
  452. return self.stats_db.process_db_query(query_string_in, print_results)
  453. def is_query(self, value: str):
  454. """
  455. Checks whether the given string is a standard SQL query (SELECT, INSERT) or a named query.
  456. :param value: The string to be checked
  457. :return: True if the string is recognized as a query, otherwise False.
  458. """
  459. if not isinstance(value, str):
  460. return False
  461. else:
  462. return (any(x in value.lower().strip() for x in self.stats_db.get_all_named_query_keywords()) or
  463. any(x in value.lower().strip() for x in self.stats_db.get_all_sql_query_keywords()))
  464. # Aidmar
  465. def calculate_standard_deviation(self, lst):
  466. """Calculates the standard deviation for a list of numbers."""
  467. num_items = len(lst)
  468. mean = sum(lst) / num_items
  469. differences = [x - mean for x in lst]
  470. sq_differences = [d ** 2 for d in differences]
  471. ssd = sum(sq_differences)
  472. variance = ssd / num_items
  473. sd = sqrt(variance)
  474. #print('The mean of {} is {}.'.format(lst, mean))
  475. #print('The differences are {}.'.format(differences))
  476. #print('The sum of squared differences is {}.'.format(ssd))
  477. #print('The variance is {}.'.format(variance))
  478. #print('The standard deviation is {}.'.format(sd))
  479. #print('--------------------------')
  480. return sd
  481. def plot_statistics(self, format: str = 'pdf'): #'png'):
  482. """
  483. Plots the statistics associated with the dataset.
  484. :param format: The format to be used to save the statistics diagrams.
  485. """
  486. def plot_ttl(file_ending: str):
  487. plt.gcf().clear()
  488. result = self.stats_db._process_user_defined_query(
  489. "SELECT ttlValue, SUM(ttlCount) FROM ip_ttl GROUP BY ttlValue")
  490. graphx, graphy = [], []
  491. for row in result:
  492. graphx.append(row[0])
  493. graphy.append(row[1])
  494. plt.autoscale(enable=True, axis='both')
  495. plt.title("TTL Distribution")
  496. plt.xlabel('TTL Value')
  497. plt.ylabel('Number of Packets')
  498. width = 0.1
  499. plt.xlim([0, max(graphx)])
  500. plt.grid(True)
  501. plt.bar(graphx, graphy, width, align='center', linewidth=1, color='red', edgecolor='red')
  502. out = self.pcap_filepath.replace('.pcap', '_plot-ttl' + file_ending)
  503. plt.savefig(out,dpi=500)
  504. return out
  505. # Aidmar
  506. def plot_mss(file_ending: str):
  507. plt.gcf().clear()
  508. result = self.stats_db._process_user_defined_query(
  509. "SELECT mssValue, SUM(mssCount) FROM tcp_mss GROUP BY mssValue")
  510. if(result):
  511. graphx, graphy = [], []
  512. for row in result:
  513. graphx.append(row[0])
  514. graphy.append(row[1])
  515. plt.autoscale(enable=True, axis='both')
  516. plt.title("MSS Distribution")
  517. plt.xlabel('MSS Value')
  518. plt.ylabel('Number of Packets')
  519. width = 0.1
  520. plt.xlim([0, max(graphx)])
  521. plt.grid(True)
  522. plt.bar(graphx, graphy, width, align='center', linewidth=1, color='red', edgecolor='red')
  523. out = self.pcap_filepath.replace('.pcap', '_plot-mss' + file_ending)
  524. plt.savefig(out,dpi=500)
  525. return out
  526. else:
  527. print("Error plot MSS: No MSS values found!")
  528. # Aidmar
  529. def plot_win(file_ending: str):
  530. plt.gcf().clear()
  531. result = self.stats_db._process_user_defined_query(
  532. "SELECT winSize, SUM(winCount) FROM tcp_win GROUP BY winSize")
  533. if (result):
  534. graphx, graphy = [], []
  535. for row in result:
  536. graphx.append(row[0])
  537. graphy.append(row[1])
  538. plt.autoscale(enable=True, axis='both')
  539. plt.title("Window Size Distribution")
  540. plt.xlabel('Window Size')
  541. plt.ylabel('Number of Packets')
  542. width = 0.1
  543. plt.xlim([0, max(graphx)])
  544. plt.grid(True)
  545. plt.bar(graphx, graphy, width, align='center', linewidth=1, color='red', edgecolor='red')
  546. out = self.pcap_filepath.replace('.pcap', '_plot-win' + file_ending)
  547. plt.savefig(out,dpi=500)
  548. return out
  549. else:
  550. print("Error plot WinSize: No WinSize values found!")
  551. # Aidmar
  552. def plot_protocol(file_ending: str):
  553. plt.gcf().clear()
  554. result = self.stats_db._process_user_defined_query(
  555. "SELECT protocolName, SUM(protocolCount) FROM ip_protocols GROUP BY protocolName")
  556. if (result):
  557. graphx, graphy = [], []
  558. for row in result:
  559. graphx.append(row[0])
  560. graphy.append(row[1])
  561. plt.autoscale(enable=True, axis='both')
  562. plt.title("Protocols Distribution")
  563. plt.xlabel('Protocols')
  564. plt.ylabel('Number of Packets')
  565. width = 0.1
  566. plt.xlim([0, len(graphx)])
  567. plt.grid(True)
  568. # Protocols' names on x-axis
  569. x = range(0,len(graphx))
  570. my_xticks = graphx
  571. plt.xticks(x, my_xticks)
  572. plt.bar(x, graphy, width, align='center', linewidth=1, color='red', edgecolor='red')
  573. out = self.pcap_filepath.replace('.pcap', '_plot-protocol' + file_ending)
  574. plt.savefig(out,dpi=500)
  575. return out
  576. else:
  577. print("Error plot protocol: No protocol values found!")
  578. # Aidmar
  579. def plot_port(file_ending: str):
  580. plt.gcf().clear()
  581. result = self.stats_db._process_user_defined_query(
  582. "SELECT portNumber, SUM(portCount) FROM ip_ports GROUP BY portNumber")
  583. graphx, graphy = [], []
  584. for row in result:
  585. graphx.append(row[0])
  586. graphy.append(row[1])
  587. plt.autoscale(enable=True, axis='both')
  588. plt.title("Ports Distribution")
  589. plt.xlabel('Ports Numbers')
  590. plt.ylabel('Number of Packets')
  591. width = 0.1
  592. plt.xlim([0, max(graphx)])
  593. plt.grid(True)
  594. plt.bar(graphx, graphy, width, align='center', linewidth=1, color='red', edgecolor='red')
  595. out = self.pcap_filepath.replace('.pcap', '_plot-port' + file_ending)
  596. plt.savefig(out,dpi=500)
  597. return out
  598. # Aidmar - This distribution is not drawable for big datasets
  599. def plot_ip_src(file_ending: str):
  600. plt.gcf().clear()
  601. result = self.stats_db._process_user_defined_query(
  602. "SELECT ipAddress, pktsSent FROM ip_statistics")
  603. graphx, graphy = [], []
  604. for row in result:
  605. graphx.append(row[0])
  606. graphy.append(row[1])
  607. plt.autoscale(enable=True, axis='both')
  608. plt.title("Source IP Distribution")
  609. plt.xlabel('Source IP')
  610. plt.ylabel('Number of Packets')
  611. width = 0.1
  612. plt.xlim([0, len(graphx)])
  613. plt.grid(True)
  614. # IPs on x-axis
  615. x = range(0, len(graphx))
  616. my_xticks = graphx
  617. plt.xticks(x, my_xticks, rotation='vertical', fontsize=5)
  618. plt.tight_layout()
  619. # limit the number of xticks
  620. plt.locator_params(axis='x', nbins=20)
  621. plt.bar(x, graphy, width, align='center', linewidth=1, color='red', edgecolor='red')
  622. out = self.pcap_filepath.replace('.pcap', '_plot-ip-src' + file_ending)
  623. plt.savefig(out, dpi=500)
  624. return out
  625. # This distribution is not drawable for big datasets
  626. def plot_ip_dst(file_ending: str):
  627. plt.gcf().clear()
  628. result = self.stats_db._process_user_defined_query(
  629. "SELECT ipAddress, pktsReceived FROM ip_statistics")
  630. graphx, graphy = [], []
  631. for row in result:
  632. graphx.append(row[0])
  633. graphy.append(row[1])
  634. plt.autoscale(enable=True, axis='both')
  635. plt.title("Destination IP Distribution")
  636. plt.xlabel('Destination IP')
  637. plt.ylabel('Number of Packets')
  638. width = 0.1
  639. plt.xlim([0, len(graphx)])
  640. plt.grid(True)
  641. # IPs on x-axis
  642. x = range(0, len(graphx))
  643. my_xticks = graphx
  644. plt.xticks(x, my_xticks, rotation='vertical', fontsize=5)
  645. plt.tight_layout()
  646. # limit the number of xticks
  647. plt.locator_params(axis='x', nbins=20)
  648. plt.bar(x, graphy, width, align='center', linewidth=1, color='red', edgecolor='red')
  649. out = self.pcap_filepath.replace('.pcap', '_plot-ip-dst' + file_ending)
  650. plt.savefig(out, dpi=500)
  651. return out
  652. def plot_interval_pktCount(file_ending: str):
  653. plt.gcf().clear()
  654. result = self.stats_db._process_user_defined_query(
  655. "SELECT lastPktTimestamp, pktsCount FROM interval_statistics ORDER BY lastPktTimestamp")
  656. graphx, graphy = [], []
  657. for row in result:
  658. graphx.append(row[0])
  659. graphy.append(row[1])
  660. plt.autoscale(enable=True, axis='both')
  661. plt.title("Packet Rate")
  662. plt.xlabel('Timestamp')
  663. plt.ylabel('Number of Packets')
  664. width = 0.5
  665. plt.xlim([0, len(graphx)])
  666. plt.grid(True)
  667. # timestamp on x-axis
  668. x = range(0, len(graphx))
  669. my_xticks = graphx
  670. plt.xticks(x, my_xticks, rotation='vertical', fontsize=5)
  671. plt.tight_layout()
  672. # limit the number of xticks
  673. plt.locator_params(axis='x', nbins=20)
  674. plt.bar(x, graphy, width, align='center', linewidth=1, color='red', edgecolor='red')
  675. out = self.pcap_filepath.replace('.pcap', '_plot-interval-pkt-count' + file_ending)
  676. plt.savefig(out, dpi=500)
  677. return out
  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 Novelty 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 Novelty 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 Novelty 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 Novelty 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 Novelty 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