Statistics.py 40 KB

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