Statistics.py 46 KB

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