Statistics.py 45 KB

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