Statistics.py 45 KB

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