Statistics.py 45 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064
  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 = 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. entropy += - p_x * log(p_x, 2)
  130. if normalized:
  131. normalizedEnt = entropy/log(len(frequency), 2)
  132. return entropy, normalizedEnt
  133. else:
  134. return entropy
  135. # Aidmar
  136. def get_tests_statistics(self):
  137. """
  138. Writes the calculated basic defects tests statistics into a file.
  139. """
  140. # self.stats_db._process_user_defined_query output is list of tuples, thus, we ned [0][0] to access data
  141. def count_frequncy(valuesList):
  142. values, frequency = [] , []
  143. for x in valuesList:
  144. if x in values:
  145. frequency[values.index(x)] += 1
  146. else:
  147. values.append(x)
  148. frequency.append(1)
  149. return values, frequency
  150. ####### Payload Tests #######
  151. sumPayloadCount = self.stats_db._process_user_defined_query("SELECT sum(payloadCount) FROM interval_statistics")
  152. pktCount = self.stats_db._process_user_defined_query("SELECT packetCount FROM file_statistics")
  153. payloadRatio=0
  154. if(pktCount[0][0]!=0):
  155. payloadRatio = float(sumPayloadCount[0][0] / pktCount[0][0] * 100)
  156. ####### TCP checksum Tests #######
  157. incorrectChecksumCount = self.stats_db._process_user_defined_query("SELECT sum(incorrectTCPChecksumCount) FROM interval_statistics")
  158. correctChecksumCount = self.stats_db._process_user_defined_query("SELECT avg(correctTCPChecksumCount) FROM interval_statistics")
  159. incorrectChecksumRatio=0
  160. if(incorrectChecksumCount[0][0] + correctChecksumCount[0][0])!=0:
  161. incorrectChecksumRatio = float(incorrectChecksumCount[0][0] / (incorrectChecksumCount[0][0] + correctChecksumCount[0][0] ) * 100)
  162. ####### IP Tests #######
  163. newIPCount = self.stats_db._process_user_defined_query("SELECT newIPCount FROM interval_statistics")
  164. # Retrieve the last cumulative entropy which is the entropy of the all IPs
  165. result = self.stats_db._process_user_defined_query("SELECT ipSrcCumEntropy FROM interval_statistics")
  166. ipSrcEntropy = result[-1][0]
  167. ipSrcCount = self.stats_db._process_user_defined_query(
  168. "SELECT COUNT(ipAddress) FROM ip_statistics WHERE pktsSent > 0")
  169. ipSrcNormEntropy = ipSrcEntropy / log(ipSrcCount[0][0],2)
  170. result = self.stats_db._process_user_defined_query("SELECT ipDstCumEntropy FROM interval_statistics")
  171. ipDstEntropy = result[-1][0]
  172. ipDstCount = self.stats_db._process_user_defined_query(
  173. "SELECT COUNT(ipAddress) FROM ip_statistics WHERE pktsReceived > 0")
  174. ipDstNormEntropy = ipDstEntropy / log(ipDstCount[0][0],2)
  175. ####### Ports Tests #######
  176. port0Count = self.stats_db._process_user_defined_query("SELECT SUM(portCount) FROM ip_ports WHERE portNumber = 0")
  177. if not port0Count[0][0]:
  178. port0Count = 0
  179. else:
  180. port0Count = port0Count[0][0]
  181. reservedPortCount = self.stats_db._process_user_defined_query(
  182. "SELECT SUM(portCount) FROM ip_ports WHERE portNumber IN (0,100,114,1023,1024,49151,49152,65535)")# could be extended
  183. if not reservedPortCount[0][0]:
  184. reservedPortCount = 0
  185. else:
  186. reservedPortCount = reservedPortCount[0][0]
  187. totalPortCount = self.stats_db._process_user_defined_query("SELECT SUM(portCount) FROM ip_ports")
  188. reservedPortRatio = (reservedPortCount/ totalPortCount[0][0]) * 100
  189. ####### TTL Tests #######
  190. newTTLCount = self.stats_db._process_user_defined_query("SELECT newTTLCount FROM interval_statistics")
  191. result = self.stats_db._process_user_defined_query("SELECT ttlValue,SUM(ttlCount) FROM ip_ttl GROUP BY ttlValue")
  192. data, frequency = [], []
  193. for row in result:
  194. frequency.append(row[1])
  195. ttlEntopy, ttlNormEntopy = self.calculate_entropy(frequency,True)
  196. ttlNovelsPerInterval, ttlNovelsPerIntervalFrequency = count_frequncy(newTTLCount)
  197. ttlNovelityDistEntropy = self.calculate_entropy(ttlNovelsPerIntervalFrequency)
  198. ####### Window Size Tests #######
  199. newWinSizeCount = self.stats_db._process_user_defined_query("SELECT newWinSizeCount FROM interval_statistics")
  200. result = self.stats_db._process_user_defined_query("SELECT winSize,SUM(winCount) FROM tcp_syn_win GROUP BY winSize")
  201. data, frequency = [], []
  202. for row in result:
  203. frequency.append(row[1])
  204. winEntopy, winNormEntopy = self.calculate_entropy(frequency, True)
  205. winNovelsPerInterval, winNovelsPerIntervalFrequency = count_frequncy(newWinSizeCount)
  206. winNovelityDistEntropy = self.calculate_entropy(winNovelsPerIntervalFrequency)
  207. ####### ToS Tests #######
  208. newToSCount = self.stats_db._process_user_defined_query("SELECT newToSCount FROM interval_statistics")
  209. result = self.stats_db._process_user_defined_query(
  210. "SELECT tosValue,SUM(tosCount) FROM ip_tos GROUP BY tosValue")
  211. data, frequency = [], []
  212. for row in result:
  213. frequency.append(row[1])
  214. tosEntopy, tosNormEntopy = self.calculate_entropy(frequency, True)
  215. tosNovelsPerInterval, tosNovelsPerIntervalFrequency = count_frequncy(newToSCount)
  216. tosNovelityDistEntropy = self.calculate_entropy(tosNovelsPerIntervalFrequency)
  217. ####### MSS Tests #######
  218. newMSSCount = self.stats_db._process_user_defined_query("SELECT newMSSCount FROM interval_statistics")
  219. result = self.stats_db._process_user_defined_query(
  220. "SELECT mssValue,SUM(mssCount) FROM tcp_mss_dist GROUP BY mssValue")
  221. data, frequency = [], []
  222. for row in result:
  223. frequency.append(row[1])
  224. mssEntopy, mssNormEntopy = self.calculate_entropy(frequency, True)
  225. mssNovelsPerInterval, mssNovelsPerIntervalFrequency = count_frequncy(newMSSCount)
  226. mssNovelityDistEntropy = self.calculate_entropy(mssNovelsPerIntervalFrequency)
  227. result = self.stats_db._process_user_defined_query("SELECT SUM(mssCount) FROM tcp_mss_dist WHERE mssValue > 536 AND mssValue < 1460")
  228. # The most used range of MSS: 536 < MSS < 1460. Calculate the ratio of the values in this range to total values.
  229. if not result[0][0]:
  230. result = 0
  231. else:
  232. result = result[0][0]
  233. mss5361460 = (result / sum(frequency)) * 100
  234. return [("Payload ratio", payloadRatio, "%"),
  235. ("Incorrect TCP checksum ratio", incorrectChecksumRatio, "%"),
  236. ("IP Src Entropy", ipSrcEntropy, ""),
  237. ("IP Src Normalized Entropy", ipSrcNormEntropy, ""),
  238. ("IP Dst Entropy", ipDstEntropy, ""),
  239. ("IP Dst Normalized Entropy", ipDstNormEntropy, ""),
  240. ("Port 0 count", port0Count, ""),
  241. ("Reserved ports", reservedPortRatio, "%"),
  242. ("TTL Entropy", ttlEntopy, ""),
  243. ("TTL Normalized Entropy", ttlNormEntopy, ""),
  244. ("TTL Distribution Entropy", ttlNovelityDistEntropy, ""),
  245. ("WinSize Entropy", winEntopy, ""),
  246. ("WinSize Normalized Entropy", winNormEntopy, ""),
  247. ("WinSize Distribution Entropy", winNovelityDistEntropy, ""),
  248. ("ToS Entropy", tosEntopy, ""),
  249. ("ToS Normalized Entropy", tosNormEntopy, ""),
  250. ("ToS Distribution Entropy", tosNovelityDistEntropy, ""),
  251. ("MSS Entropy", mssEntopy, ""),
  252. ("MSS Normalized Entropy", mssNormEntopy, ""),
  253. ("MSS Distribution Entropy", mssNovelityDistEntropy, ""),
  254. ("536 < MSS < 1460", mss5361460, "%")]
  255. def write_statistics_to_file(self):
  256. """
  257. Writes the calculated basic statistics into a file.
  258. """
  259. def _write_header(title: str):
  260. """
  261. Writes the section header into the open file.
  262. :param title: The section title
  263. """
  264. target.write("====================== \n")
  265. target.write(title + " \n")
  266. target.write("====================== \n")
  267. target = open(self.pcap_filepath + ".stat", 'w')
  268. target.truncate()
  269. _write_header("PCAP file information")
  270. Statistics.write_list(self.get_file_information(), target.write)
  271. _write_header("General statistics")
  272. Statistics.write_list(self.get_general_file_statistics(), target.write)
  273. _write_header("Tests statistics")
  274. Statistics.write_list(self.get_tests_statistics(), target.write)
  275. target.close()
  276. def get_capture_duration(self):
  277. """
  278. :return: The duration of the capture in seconds
  279. """
  280. return self.file_info['captureDuration']
  281. def get_pcap_timestamp_start(self):
  282. """
  283. :return: The timestamp of the first packet in the PCAP file
  284. """
  285. return self.file_info['timestampFirstPacket']
  286. def get_pcap_timestamp_end(self):
  287. """
  288. :return: The timestamp of the last packet in the PCAP file
  289. """
  290. return self.file_info['timestampLastPacket']
  291. def get_pps_sent(self, ip_address: str):
  292. """
  293. Calculates the sent packets per seconds for a given IP address.
  294. :param ip_address: The IP address whose packets per second should be calculated
  295. :return: The sent packets per seconds for the given IP address
  296. """
  297. packets_sent = self.stats_db.process_db_query("SELECT pktsSent from ip_statistics WHERE ipAddress=?", False,
  298. (ip_address,))
  299. capture_duration = float(self.get_capture_duration())
  300. return int(float(packets_sent) / capture_duration)
  301. def get_pps_received(self, ip_address: str):
  302. """
  303. Calculate the packets per second received for a given IP address.
  304. :param ip_address: The IP address used for the calculation
  305. :return: The number of packets per second received
  306. """
  307. packets_received = self.stats_db.process_db_query("SELECT pktsReceived FROM ip_statistics WHERE ipAddress=?",
  308. False,
  309. (ip_address,))
  310. capture_duration = float(self.get_capture_duration())
  311. return int(float(packets_received) / capture_duration)
  312. def get_packet_count(self):
  313. """
  314. :return: The number of packets in the loaded PCAP file
  315. """
  316. return self.file_info['packetCount']
  317. def get_most_used_ip_address(self):
  318. """
  319. :return: The IP address/addresses with the highest sum of packets sent and received
  320. """
  321. return self.process_db_query("most_used(ipAddress)")
  322. def get_ttl_distribution(self, ipAddress: str):
  323. result = self.process_db_query('SELECT ttlValue, ttlCount from ip_ttl WHERE ipAddress="' + ipAddress + '"')
  324. result_dict = {key: value for (key, value) in result}
  325. return result_dict
  326. # Aidmar
  327. def get_mss_distribution(self, ipAddress: str):
  328. result = self.process_db_query('SELECT mssValue, mssCount from tcp_mss_dist WHERE ipAddress="' + ipAddress + '"')
  329. result_dict = {key: value for (key, value) in result}
  330. return result_dict
  331. # Aidmar
  332. def get_win_distribution(self, ipAddress: str):
  333. result = self.process_db_query('SELECT winSize, winCount from tcp_syn_win WHERE ipAddress="' + ipAddress + '"')
  334. result_dict = {key: value for (key, value) in result}
  335. return result_dict
  336. # Aidmar
  337. def get_tos_distribution(self, ipAddress: str):
  338. result = self.process_db_query('SELECT tosValue, tosCount from ip_tos WHERE ipAddress="' + ipAddress + '"')
  339. result_dict = {key: value for (key, value) in result}
  340. return result_dict
  341. def get_random_ip_address(self, count: int = 1):
  342. """
  343. :param count: The number of IP addreses to return
  344. :return: A randomly chosen IP address from the dataset or iff param count is greater than one, a list of randomly
  345. chosen IP addresses
  346. """
  347. if count == 1:
  348. return self.process_db_query("random(all(ipAddress))")
  349. else:
  350. ip_address_list = []
  351. for i in range(0, count):
  352. ip_address_list.append(self.process_db_query("random(all(ipAddress))"))
  353. return ip_address_list
  354. def get_mac_address(self, ipAddress: str):
  355. """
  356. :return: The MAC address used in the dataset for the given IP address.
  357. """
  358. return self.process_db_query('macAddress(ipAddress=' + ipAddress + ")")
  359. # Aidmar
  360. def get_most_used_mss(self, ipAddress: str):
  361. """
  362. :param ipAddress: The IP address whose used MSS should be determined
  363. :return: The TCP MSS value used by the IP address, or if the IP addresses never specified a MSS,
  364. then None is returned
  365. """
  366. mss_value = self.process_db_query('SELECT mssValue from tcp_mss_dist WHERE ipAddress="' + ipAddress + '" ORDER BY mssCount DESC LIMIT 1')
  367. if isinstance(mss_value, int):
  368. return mss_value
  369. else:
  370. return None
  371. def get_statistics_database(self):
  372. """
  373. :return: A reference to the statistics database object
  374. """
  375. return self.stats_db
  376. def process_db_query(self, query_string_in: str, print_results: bool = False):
  377. """
  378. Executes a string identified previously as a query. This can be a standard SQL SELECT/INSERT query or a named
  379. query.
  380. :param query_string_in: The query to be processed
  381. :param print_results: Indicates whether the results should be printed to terminal
  382. :return: The result of the query
  383. """
  384. return self.stats_db.process_db_query(query_string_in, print_results)
  385. def is_query(self, value: str):
  386. """
  387. Checks whether the given string is a standard SQL query (SELECT, INSERT) or a named query.
  388. :param value: The string to be checked
  389. :return: True if the string is recognized as a query, otherwise False.
  390. """
  391. if not isinstance(value, str):
  392. return False
  393. else:
  394. return (any(x in value.lower().strip() for x in self.stats_db.get_all_named_query_keywords()) or
  395. any(x in value.lower().strip() for x in self.stats_db.get_all_sql_query_keywords()))
  396. # Aidmar
  397. def calculate_standard_deviation(self, lst):
  398. """Calculates the standard deviation for a list of numbers."""
  399. num_items = len(lst)
  400. mean = sum(lst) / num_items
  401. differences = [x - mean for x in lst]
  402. sq_differences = [d ** 2 for d in differences]
  403. ssd = sum(sq_differences)
  404. variance = ssd / num_items
  405. sd = sqrt(variance)
  406. #print('The mean of {} is {}.'.format(lst, mean))
  407. #print('The differences are {}.'.format(differences))
  408. #print('The sum of squared differences is {}.'.format(ssd))
  409. #print('The variance is {}.'.format(variance))
  410. print('The standard deviation is {}.'.format(sd))
  411. print('--------------------------')
  412. return sd
  413. def plot_statistics(self, format: str = 'pdf'): #'png'):
  414. """
  415. Plots the statistics associated with the dataset prior attack injection.
  416. :param format: The format to be used to save the statistics diagrams.
  417. """
  418. def plot_ttl(file_ending: str):
  419. plt.gcf().clear()
  420. result = self.stats_db._process_user_defined_query(
  421. "SELECT ttlValue, SUM(ttlCount) FROM ip_ttl GROUP BY ttlValue")
  422. graphx, graphy = [], []
  423. for row in result:
  424. graphx.append(row[0])
  425. graphy.append(row[1])
  426. plt.autoscale(enable=True, axis='both')
  427. plt.title("TTL Distribution")
  428. plt.xlabel('TTL Value')
  429. plt.ylabel('Number of Packets')
  430. width = 0.1
  431. plt.xlim([0, max(graphx)])
  432. plt.grid(True)
  433. plt.bar(graphx, graphy, width, align='center', linewidth=1, color='red', edgecolor='red')
  434. out = self.pcap_filepath.replace('.pcap', '_plot-ttl' + file_ending)
  435. plt.savefig(out,dpi=500)
  436. return out
  437. # Aidmar
  438. def plot_mss(file_ending: str):
  439. plt.gcf().clear()
  440. result = self.stats_db._process_user_defined_query(
  441. "SELECT mssValue, SUM(mssCount) FROM tcp_mss_dist GROUP BY mssValue")
  442. if(result):
  443. graphx, graphy = [], []
  444. for row in result:
  445. graphx.append(row[0])
  446. graphy.append(row[1])
  447. plt.autoscale(enable=True, axis='both')
  448. plt.title("MSS Distribution")
  449. plt.xlabel('MSS Value')
  450. plt.ylabel('Number of Packets')
  451. width = 0.1
  452. plt.xlim([0, max(graphx)])
  453. plt.grid(True)
  454. plt.bar(graphx, graphy, width, align='center', linewidth=1, color='red', edgecolor='red')
  455. out = self.pcap_filepath.replace('.pcap', '_plot-mss' + file_ending)
  456. plt.savefig(out,dpi=500)
  457. return out
  458. else:
  459. print("Error plot MSS: No MSS values found!")
  460. # Aidmar
  461. def plot_win(file_ending: str):
  462. plt.gcf().clear()
  463. result = self.stats_db._process_user_defined_query(
  464. "SELECT winSize, SUM(winCount) FROM tcp_syn_win GROUP BY winSize")
  465. if (result):
  466. graphx, graphy = [], []
  467. for row in result:
  468. graphx.append(row[0])
  469. graphy.append(row[1])
  470. plt.autoscale(enable=True, axis='both')
  471. plt.title("Window Size Distribution")
  472. plt.xlabel('Window Size')
  473. plt.ylabel('Number of Packets')
  474. width = 0.1
  475. plt.xlim([0, max(graphx)])
  476. plt.grid(True)
  477. plt.bar(graphx, graphy, width, align='center', linewidth=1, color='red', edgecolor='red')
  478. out = self.pcap_filepath.replace('.pcap', '_plot-win' + file_ending)
  479. plt.savefig(out,dpi=500)
  480. return out
  481. else:
  482. print("Error plot WinSize: No WinSize values found!")
  483. # Aidmar
  484. def plot_protocol(file_ending: str):
  485. plt.gcf().clear()
  486. result = self.stats_db._process_user_defined_query(
  487. "SELECT protocolName, SUM(protocolCount) FROM ip_protocols GROUP BY protocolName")
  488. if (result):
  489. graphx, graphy = [], []
  490. for row in result:
  491. graphx.append(row[0])
  492. graphy.append(row[1])
  493. plt.autoscale(enable=True, axis='both')
  494. plt.title("Protocols Distribution")
  495. plt.xlabel('Protocols')
  496. plt.ylabel('Number of Packets')
  497. width = 0.1
  498. plt.xlim([0, len(graphx)])
  499. plt.grid(True)
  500. # Protocols' names on x-axis
  501. x = range(0,len(graphx))
  502. my_xticks = graphx
  503. plt.xticks(x, my_xticks)
  504. plt.bar(x, graphy, width, align='center', linewidth=1, color='red', edgecolor='red')
  505. out = self.pcap_filepath.replace('.pcap', '_plot-protocol' + file_ending)
  506. plt.savefig(out,dpi=500)
  507. return out
  508. else:
  509. print("Error plot protocol: No protocol values found!")
  510. # Aidmar
  511. def plot_port(file_ending: str):
  512. plt.gcf().clear()
  513. result = self.stats_db._process_user_defined_query(
  514. "SELECT portNumber, SUM(portCount) FROM ip_ports GROUP BY portNumber")
  515. graphx, graphy = [], []
  516. for row in result:
  517. graphx.append(row[0])
  518. graphy.append(row[1])
  519. plt.autoscale(enable=True, axis='both')
  520. plt.title("Ports Distribution")
  521. plt.xlabel('Ports Numbers')
  522. plt.ylabel('Number of Packets')
  523. width = 0.1
  524. plt.xlim([0, max(graphx)])
  525. plt.grid(True)
  526. plt.bar(graphx, graphy, width, align='center', linewidth=1, color='red', edgecolor='red')
  527. out = self.pcap_filepath.replace('.pcap', '_plot-port' + file_ending)
  528. plt.savefig(out,dpi=500)
  529. return out
  530. # Aidmar - This distribution is not drawable for big datasets
  531. def plot_ip_src(file_ending: str):
  532. plt.gcf().clear()
  533. result = self.stats_db._process_user_defined_query(
  534. "SELECT ipAddress, pktsSent FROM ip_statistics")
  535. graphx, graphy = [], []
  536. for row in result:
  537. graphx.append(row[0])
  538. graphy.append(row[1])
  539. plt.autoscale(enable=True, axis='both')
  540. plt.title("Source IP Distribution")
  541. plt.xlabel('Source IP')
  542. plt.ylabel('Number of Packets')
  543. width = 0.1
  544. plt.xlim([0, len(graphx)])
  545. plt.grid(True)
  546. # IPs on x-axis
  547. x = range(0, len(graphx))
  548. my_xticks = graphx
  549. plt.xticks(x, my_xticks, rotation='vertical', fontsize=5)
  550. plt.tight_layout()
  551. # limit the number of xticks
  552. plt.locator_params(axis='x', nbins=20)
  553. plt.bar(x, graphy, width, align='center', linewidth=1, color='red', edgecolor='red')
  554. out = self.pcap_filepath.replace('.pcap', '_plot-ip-src' + file_ending)
  555. plt.savefig(out, dpi=500)
  556. return out
  557. # Aidmar - This distribution is not drawable for big datasets
  558. def plot_ip_dst(file_ending: str):
  559. plt.gcf().clear()
  560. result = self.stats_db._process_user_defined_query(
  561. "SELECT ipAddress, pktsReceived FROM ip_statistics")
  562. graphx, graphy = [], []
  563. for row in result:
  564. graphx.append(row[0])
  565. graphy.append(row[1])
  566. plt.autoscale(enable=True, axis='both')
  567. plt.title("Destination IP Distribution")
  568. plt.xlabel('Destination IP')
  569. plt.ylabel('Number of Packets')
  570. width = 0.1
  571. plt.xlim([0, len(graphx)])
  572. plt.grid(True)
  573. # IPs on x-axis
  574. x = range(0, len(graphx))
  575. my_xticks = graphx
  576. plt.xticks(x, my_xticks, rotation='vertical', fontsize=5)
  577. plt.tight_layout()
  578. # limit the number of xticks
  579. plt.locator_params(axis='x', nbins=20)
  580. plt.bar(x, graphy, width, align='center', linewidth=1, color='red', edgecolor='red')
  581. out = self.pcap_filepath.replace('.pcap', '_plot-ip-dst' + file_ending)
  582. plt.savefig(out, dpi=500)
  583. return out
  584. # Aidmar
  585. def plot_interval_pktCount(file_ending: str):
  586. plt.gcf().clear()
  587. result = self.stats_db._process_user_defined_query(
  588. "SELECT lastPktTimestamp, pktsCount FROM interval_statistics ORDER BY lastPktTimestamp")
  589. graphx, graphy = [], []
  590. for row in result:
  591. graphx.append(row[0])
  592. graphy.append(row[1])
  593. plt.autoscale(enable=True, axis='both')
  594. plt.title("Packet Rate")
  595. plt.xlabel('Timestamp')
  596. plt.ylabel('Number of Packets')
  597. width = 0.1
  598. plt.xlim([0, len(graphx)])
  599. plt.grid(True)
  600. # timestamp on x-axis
  601. x = range(0, len(graphx))
  602. my_xticks = graphx
  603. plt.xticks(x, my_xticks, rotation='vertical', fontsize=5)
  604. plt.tight_layout()
  605. # limit the number of xticks
  606. plt.locator_params(axis='x', nbins=20)
  607. plt.bar(x, graphy, width, align='center', linewidth=1, color='red', edgecolor='red')
  608. out = self.pcap_filepath.replace('.pcap', '_plot-interval-pkt-count' + file_ending)
  609. plt.savefig(out, dpi=500)
  610. return out
  611. # Aidmar
  612. def plot_interval_ip_src_ent(file_ending: str):
  613. plt.gcf().clear()
  614. result = self.stats_db._process_user_defined_query(
  615. "SELECT lastPktTimestamp, ipSrcEntropy FROM interval_statistics ORDER BY lastPktTimestamp")
  616. graphx, graphy = [], []
  617. for row in result:
  618. graphx.append(row[0])
  619. graphy.append(row[1])
  620. plt.autoscale(enable=True, axis='both')
  621. plt.title("Source IP Entropy")
  622. plt.xlabel('Timestamp')
  623. plt.ylabel('Entropy')
  624. width = 0.1
  625. plt.xlim([0, len(graphx)])
  626. plt.grid(True)
  627. # timestamp on x-axis
  628. x = range(0, len(graphx))
  629. my_xticks = graphx
  630. plt.xticks(x, my_xticks, rotation='vertical', fontsize=5)
  631. plt.tight_layout()
  632. # limit the number of xticks
  633. plt.locator_params(axis='x', nbins=20)
  634. plt.bar(x, graphy, width, align='center', linewidth=1, color='red', edgecolor='red')
  635. out = self.pcap_filepath.replace('.pcap', '_plot-interval-ip-src-ent' + file_ending)
  636. plt.savefig(out, dpi=500)
  637. return out
  638. # Aidmar
  639. def plot_interval_ip_dst_ent(file_ending: str):
  640. plt.gcf().clear()
  641. result = self.stats_db._process_user_defined_query(
  642. "SELECT lastPktTimestamp, ipDstEntropy FROM interval_statistics ORDER BY lastPktTimestamp")
  643. graphx, graphy = [], []
  644. for row in result:
  645. graphx.append(row[0])
  646. graphy.append(row[1])
  647. plt.autoscale(enable=True, axis='both')
  648. plt.title("Destination IP Entropy")
  649. plt.xlabel('Timestamp')
  650. plt.ylabel('Entropy')
  651. width = 0.1
  652. plt.xlim([0, len(graphx)])
  653. plt.grid(True)
  654. # timestamp on x-axis
  655. x = range(0, len(graphx))
  656. my_xticks = graphx
  657. plt.xticks(x, my_xticks, rotation='vertical', fontsize=5)
  658. plt.tight_layout()
  659. # limit the number of xticks
  660. plt.locator_params(axis='x', nbins=20)
  661. plt.bar(x, graphy, width, align='center', linewidth=1, color='red', edgecolor='red')
  662. out = self.pcap_filepath.replace('.pcap', '_plot-interval-ip-dst-ent' + file_ending)
  663. plt.savefig(out, dpi=500)
  664. return out
  665. # Aidmar
  666. def plot_interval_ip_dst_cum_ent(file_ending: str):
  667. plt.gcf().clear()
  668. result = self.stats_db._process_user_defined_query(
  669. "SELECT lastPktTimestamp, ipDstCumEntropy FROM interval_statistics ORDER BY lastPktTimestamp")
  670. graphx, graphy = [], []
  671. for row in result:
  672. graphx.append(row[0])
  673. graphy.append(row[1])
  674. plt.autoscale(enable=True, axis='both')
  675. plt.title("Destination IP Cumulative Entropy")
  676. plt.xlabel('Timestamp')
  677. plt.ylabel('Entropy')
  678. plt.xlim([0, len(graphx)])
  679. plt.grid(True)
  680. # timestamp on x-axis
  681. x = range(0, len(graphx))
  682. my_xticks = graphx
  683. plt.xticks(x, my_xticks, rotation='vertical', fontsize=5)
  684. plt.tight_layout()
  685. # limit the number of xticks
  686. plt.locator_params(axis='x', nbins=20)
  687. plt.plot(x, graphy, 'r')
  688. out = self.pcap_filepath.replace('.pcap', '_plot-interval-ip-dst-cum-ent' + file_ending)
  689. plt.savefig(out, dpi=500)
  690. return out
  691. # Aidmar
  692. def plot_interval_ip_src_cum_ent(file_ending: str):
  693. plt.gcf().clear()
  694. result = self.stats_db._process_user_defined_query(
  695. "SELECT lastPktTimestamp, ipSrcCumEntropy FROM interval_statistics ORDER BY lastPktTimestamp")
  696. graphx, graphy = [], []
  697. for row in result:
  698. graphx.append(row[0])
  699. graphy.append(row[1])
  700. plt.autoscale(enable=True, axis='both')
  701. plt.title("Source IP Cumulative Entropy")
  702. plt.xlabel('Timestamp')
  703. plt.ylabel('Entropy')
  704. plt.xlim([0, len(graphx)])
  705. plt.grid(True)
  706. # timestamp on x-axis
  707. x = range(0, len(graphx))
  708. my_xticks = graphx
  709. plt.xticks(x, my_xticks, rotation='vertical', fontsize=5)
  710. plt.tight_layout()
  711. # limit the number of xticks
  712. plt.locator_params(axis='x',nbins=20)
  713. plt.plot(x, graphy, 'r')
  714. out = self.pcap_filepath.replace('.pcap', '_plot-interval-ip-src-cum-ent' + file_ending)
  715. plt.savefig(out, dpi=500)
  716. return out
  717. # Aidmar
  718. def plot_interval_new_ip(file_ending: str):
  719. plt.gcf().clear()
  720. result = self.stats_db._process_user_defined_query(
  721. "SELECT lastPktTimestamp, newIPCount FROM interval_statistics ORDER BY lastPktTimestamp")
  722. graphx, graphy = [], []
  723. for row in result:
  724. graphx.append(row[0])
  725. graphy.append(row[1])
  726. plt.autoscale(enable=True, axis='both')
  727. plt.title("IP Novelity Distribution")
  728. plt.xlabel('Timestamp')
  729. plt.ylabel('Novel values count')
  730. plt.xlim([0, len(graphx)])
  731. plt.grid(True)
  732. width = 0.1
  733. # timestamp on x-axis
  734. x = range(0, len(graphx))
  735. my_xticks = graphx
  736. plt.xticks(x, my_xticks, rotation='vertical', fontsize=5)
  737. plt.tight_layout()
  738. # limit the number of xticks
  739. plt.locator_params(axis='x', nbins=20)
  740. plt.bar(x, graphy, width, align='center', linewidth=1, color='red', edgecolor='red')
  741. out = self.pcap_filepath.replace('.pcap', '_plot-interval-novel-ip-dist' + file_ending)
  742. plt.savefig(out, dpi=500)
  743. print("IP Standard Deviation:")
  744. self.calculate_standard_deviation(graphy)
  745. return out
  746. # Aidmar
  747. def plot_interval_new_ttl(file_ending: str):
  748. plt.gcf().clear()
  749. result = self.stats_db._process_user_defined_query(
  750. "SELECT lastPktTimestamp, newTTLCount FROM interval_statistics ORDER BY lastPktTimestamp")
  751. if(result):
  752. graphx, graphy = [], []
  753. for row in result:
  754. graphx.append(row[0])
  755. graphy.append(row[1])
  756. plt.autoscale(enable=True, axis='both')
  757. plt.title("TTL Novelity Distribution")
  758. plt.xlabel('Timestamp')
  759. plt.ylabel('Novel values count')
  760. plt.xlim([0, len(graphx)])
  761. plt.grid(True)
  762. width = 0.1
  763. # timestamp on x-axis
  764. x = range(0, len(graphx))
  765. my_xticks = graphx
  766. plt.xticks(x, my_xticks, rotation='vertical', fontsize=5)
  767. plt.tight_layout()
  768. # limit the number of xticks
  769. plt.locator_params(axis='x', nbins=20)
  770. plt.bar(x, graphy, width, align='center', linewidth=1, color='red', edgecolor='red')
  771. out = self.pcap_filepath.replace('.pcap', '_plot-interval-novel-ttl-dist' + file_ending)
  772. plt.savefig(out, dpi=500)
  773. print("TTL Standard Deviation:")
  774. self.calculate_standard_deviation(graphy)
  775. return out
  776. else:
  777. print("Error plot TTL: No TTL values found!")
  778. # Aidmar
  779. def plot_interval_new_tos(file_ending: str):
  780. plt.gcf().clear()
  781. result = self.stats_db._process_user_defined_query(
  782. "SELECT lastPktTimestamp, newToSCount FROM interval_statistics ORDER BY lastPktTimestamp")
  783. graphx, graphy = [], []
  784. for row in result:
  785. graphx.append(row[0])
  786. graphy.append(row[1])
  787. plt.autoscale(enable=True, axis='both')
  788. plt.title("ToS Novelity Distribution")
  789. plt.xlabel('Timestamp')
  790. plt.ylabel('Novel values count')
  791. plt.xlim([0, len(graphx)])
  792. plt.grid(True)
  793. width = 0.1
  794. # timestamp on x-axis
  795. x = range(0, len(graphx))
  796. my_xticks = graphx
  797. plt.xticks(x, my_xticks, rotation='vertical', fontsize=5)
  798. plt.tight_layout()
  799. # limit the number of xticks
  800. plt.locator_params(axis='x', nbins=20)
  801. plt.bar(x, graphy, width, align='center', linewidth=1, color='red', edgecolor='red')
  802. out = self.pcap_filepath.replace('.pcap', '_plot-interval-novel-tos-dist' + file_ending)
  803. plt.savefig(out, dpi=500)
  804. print("ToS Standard Deviation:")
  805. self.calculate_standard_deviation(graphy)
  806. return out
  807. # Aidmar
  808. def plot_interval_new_win_size(file_ending: str):
  809. plt.gcf().clear()
  810. result = self.stats_db._process_user_defined_query(
  811. "SELECT lastPktTimestamp, newWinSizeCount FROM interval_statistics ORDER BY lastPktTimestamp")
  812. if(result):
  813. graphx, graphy = [], []
  814. for row in result:
  815. graphx.append(row[0])
  816. graphy.append(row[1])
  817. plt.autoscale(enable=True, axis='both')
  818. plt.title("Window Size Novelity Distribution")
  819. plt.xlabel('Timestamp')
  820. plt.ylabel('Novel values count')
  821. plt.xlim([0, len(graphx)])
  822. plt.grid(True)
  823. width = 0.1
  824. # timestamp on x-axis
  825. x = range(0, len(graphx))
  826. my_xticks = graphx
  827. plt.xticks(x, my_xticks, rotation='vertical', fontsize=5)
  828. plt.tight_layout()
  829. # limit the number of xticks
  830. plt.locator_params(axis='x', nbins=20)
  831. plt.bar(x, graphy, width, align='center', linewidth=1, color='red', edgecolor='red')
  832. out = self.pcap_filepath.replace('.pcap', '_plot-interval-novel-win-size-dist' + file_ending)
  833. plt.savefig(out, dpi=500)
  834. # Calculate Standart Deviation
  835. print("Window Size Standard Deviation:")
  836. self.calculate_standard_deviation(graphy)
  837. return out
  838. else:
  839. print("Error plot new values WinSize: No WinSize values found!")
  840. # Aidmar
  841. def plot_interval_new_mss(file_ending: str):
  842. plt.gcf().clear()
  843. result = self.stats_db._process_user_defined_query(
  844. "SELECT lastPktTimestamp, newMSSCount FROM interval_statistics ORDER BY lastPktTimestamp")
  845. if(result):
  846. graphx, graphy = [], []
  847. for row in result:
  848. graphx.append(row[0])
  849. graphy.append(row[1])
  850. plt.autoscale(enable=True, axis='both')
  851. plt.title("MSS Novelity Distribution")
  852. plt.xlabel('Timestamp')
  853. plt.ylabel('Novel values count')
  854. plt.xlim([0, len(graphx)])
  855. plt.grid(True)
  856. width = 0.1
  857. # timestamp on x-axis
  858. x = range(0, len(graphx))
  859. my_xticks = graphx
  860. plt.xticks(x, my_xticks, rotation='vertical', fontsize=5)
  861. plt.tight_layout()
  862. # limit the number of xticks
  863. plt.locator_params(axis='x', nbins=20)
  864. plt.bar(x, graphy, width, align='center', linewidth=1, color='red', edgecolor='red')
  865. out = self.pcap_filepath.replace('.pcap', '_plot-interval-novel-mss-dist' + file_ending)
  866. plt.savefig(out, dpi=500)
  867. # Calculate Standart Deviation
  868. print("MSS Standard Deviation:")
  869. self.calculate_standard_deviation(graphy)
  870. return out
  871. else:
  872. print("Error plot new values MSS: No MSS values found!")
  873. ttl_out_path = plot_ttl('.' + format)
  874. mss_out_path = plot_mss('.' + format)
  875. win_out_path = plot_win('.' + format)
  876. protocol_out_path = plot_protocol('.' + format)
  877. port_out_path = plot_port('.' + format)
  878. #ip_src_out_path = plot_ip_src('.' + format)
  879. #ip_dst_out_path = plot_ip_dst('.' + format)
  880. plot_interval_pktCount = plot_interval_pktCount('.' + format)
  881. plot_interval_ip_src_ent = plot_interval_ip_src_ent('.' + format)
  882. plot_interval_ip_dst_ent = plot_interval_ip_dst_ent('.' + format)
  883. plot_interval_ip_src_cum_ent = plot_interval_ip_src_cum_ent('.' + format)
  884. plot_interval_ip_dst_cum_ent = plot_interval_ip_dst_cum_ent('.' + format)
  885. plot_interval_new_ip = plot_interval_new_ip('.' + format)
  886. plot_interval_new_ttl = plot_interval_new_ttl('.' + format)
  887. plot_interval_new_tos = plot_interval_new_tos('.' + format)
  888. plot_interval_new_win_size = plot_interval_new_win_size('.' + format)
  889. plot_interval_new_mss = plot_interval_new_mss('.' + format)
  890. #print("Saved distributions plots at: %s, %s, %s, %s, %s, %s, %s, %s %s" %(ttl_out_path,mss_out_path, win_out_path,
  891. #protocol_out_path, port_out_path,ip_src_out_path,ip_dst_out_path, plot_interval_pktCount))
  892. # Aidmar
  893. def calculate_complement_packet_rates(self, pps):
  894. """
  895. Calculates the complement packet rates of the background traffic packet rates for each interval.
  896. Then normalize it to maximum boundary, which is the input parameter pps
  897. :return: normalized packet rates for each time interval.
  898. """
  899. result = self.process_db_query(
  900. "SELECT lastPktTimestamp,pktsCount FROM interval_statistics ORDER BY lastPktTimestamp")
  901. # print(result)
  902. bg_interval_pps = []
  903. complement_interval_pps = []
  904. intervalsSum = 0
  905. if result:
  906. # Get the interval in seconds
  907. for i, row in enumerate(result):
  908. if i < len(result) - 1:
  909. intervalsSum += ceil((int(result[i + 1][0]) * 10 ** -6) - (int(row[0]) * 10 ** -6))
  910. interval = intervalsSum / (len(result) - 1)
  911. # Convert timestamp from micro to seconds, convert packet rate "per interval" to "per second"
  912. for row in result:
  913. bg_interval_pps.append((int(row[0]) * 10 ** -6, int(row[1] / interval)))
  914. # Find max PPS
  915. maxPPS = max(bg_interval_pps, key=itemgetter(1))[1]
  916. for row in bg_interval_pps:
  917. complement_interval_pps.append((row[0], int(pps * (maxPPS - row[1]) / maxPPS)))
  918. return complement_interval_pps