Statistics.py 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716
  1. # Aidmar
  2. from operator import itemgetter
  3. import math
  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, 2)
  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. def write_statistics_to_file(self):
  121. """
  122. Writes the calculated basic statistics into a file.
  123. """
  124. def _write_header(title: str):
  125. """
  126. Writes the section header into the open file.
  127. :param title: The section title
  128. """
  129. target.write("====================== \n")
  130. target.write(title + " \n")
  131. target.write("====================== \n")
  132. target = open(self.pcap_filepath + ".stat", 'w')
  133. target.truncate()
  134. _write_header("PCAP file information")
  135. Statistics.write_list(self.get_file_information(), target.write)
  136. _write_header("General statistics")
  137. Statistics.write_list(self.get_general_file_statistics(), target.write)
  138. target.close()
  139. def get_capture_duration(self):
  140. """
  141. :return: The duration of the capture in seconds
  142. """
  143. return self.file_info['captureDuration']
  144. def get_pcap_timestamp_start(self):
  145. """
  146. :return: The timestamp of the first packet in the PCAP file
  147. """
  148. return self.file_info['timestampFirstPacket']
  149. def get_pcap_timestamp_end(self):
  150. """
  151. :return: The timestamp of the last packet in the PCAP file
  152. """
  153. return self.file_info['timestampLastPacket']
  154. def get_pps_sent(self, ip_address: str):
  155. """
  156. Calculates the sent packets per seconds for a given IP address.
  157. :param ip_address: The IP address whose packets per second should be calculated
  158. :return: The sent packets per seconds for the given IP address
  159. """
  160. packets_sent = self.stats_db.process_db_query("SELECT pktsSent from ip_statistics WHERE ipAddress=?", False,
  161. (ip_address,))
  162. capture_duration = float(self.get_capture_duration())
  163. return int(float(packets_sent) / capture_duration)
  164. def get_pps_received(self, ip_address: str):
  165. """
  166. Calculate the packets per second received for a given IP address.
  167. :param ip_address: The IP address used for the calculation
  168. :return: The number of packets per second received
  169. """
  170. packets_received = self.stats_db.process_db_query("SELECT pktsReceived FROM ip_statistics WHERE ipAddress=?",
  171. False,
  172. (ip_address,))
  173. capture_duration = float(self.get_capture_duration())
  174. return int(float(packets_received) / capture_duration)
  175. def get_packet_count(self):
  176. """
  177. :return: The number of packets in the loaded PCAP file
  178. """
  179. return self.file_info['packetCount']
  180. def get_most_used_ip_address(self):
  181. """
  182. :return: The IP address/addresses with the highest sum of packets sent and received
  183. """
  184. return self.process_db_query("most_used(ipAddress)")
  185. def get_ttl_distribution(self, ipAddress: str):
  186. result = self.process_db_query('SELECT ttlValue, ttlCount from ip_ttl WHERE ipAddress="' + ipAddress + '"')
  187. result_dict = {key: value for (key, value) in result}
  188. return result_dict
  189. def get_random_ip_address(self, count: int = 1):
  190. """
  191. :param count: The number of IP addreses to return
  192. :return: A randomly chosen IP address from the dataset or iff param count is greater than one, a list of randomly
  193. chosen IP addresses
  194. """
  195. if count == 1:
  196. return self.process_db_query("random(all(ipAddress))")
  197. else:
  198. ip_address_list = []
  199. for i in range(0, count):
  200. ip_address_list.append(self.process_db_query("random(all(ipAddress))"))
  201. return ip_address_list
  202. def get_mac_address(self, ipAddress: str):
  203. """
  204. :return: The MAC address used in the dataset for the given IP address.
  205. """
  206. return self.process_db_query('macAddress(ipAddress=' + ipAddress + ")")
  207. def get_mss(self, ipAddress: str):
  208. """
  209. :param ipAddress: The IP address whose used MSS should be determined
  210. :return: The TCP MSS value used by the IP address, or if the IP addresses never specified a MSS,
  211. then None is returned
  212. """
  213. mss_value = self.process_db_query('SELECT mss from tcp_mss WHERE ipAddress="' + ipAddress + '"')
  214. if isinstance(mss_value, int):
  215. return mss_value
  216. else:
  217. return None
  218. # Aidmar
  219. def get_most_used_mss(self, ipAddress: str):
  220. """
  221. :param ipAddress: The IP address whose used MSS should be determined
  222. :return: The TCP MSS value used by the IP address, or if the IP addresses never specified a MSS,
  223. then None is returned
  224. """
  225. mss_value = self.process_db_query('SELECT mssValue from tcp_mss_dist WHERE ipAddress="' + ipAddress + '" ORDER BY mssCount DESC LIMIT 1')
  226. if isinstance(mss_value, int):
  227. return mss_value
  228. else:
  229. return None
  230. def get_statistics_database(self):
  231. """
  232. :return: A reference to the statistics database object
  233. """
  234. return self.stats_db
  235. def process_db_query(self, query_string_in: str, print_results: bool = False):
  236. """
  237. Executes a string identified previously as a query. This can be a standard SQL SELECT/INSERT query or a named
  238. query.
  239. :param query_string_in: The query to be processed
  240. :param print_results: Indicates whether the results should be printed to terminal
  241. :return: The result of the query
  242. """
  243. return self.stats_db.process_db_query(query_string_in, print_results)
  244. def is_query(self, value: str):
  245. """
  246. Checks whether the given string is a standard SQL query (SELECT, INSERT) or a named query.
  247. :param value: The string to be checked
  248. :return: True if the string is recognized as a query, otherwise False.
  249. """
  250. if not isinstance(value, str):
  251. return False
  252. else:
  253. return (any(x in value.lower().strip() for x in self.stats_db.get_all_named_query_keywords()) or
  254. any(x in value.lower().strip() for x in self.stats_db.get_all_sql_query_keywords()))
  255. def plot_statistics(self, format: str = 'pdf'): #'png'):
  256. """
  257. Plots the statistics associated with the dataset prior attack injection.
  258. :param format: The format to be used to save the statistics diagrams.
  259. """
  260. def plot_ttl(file_ending: str):
  261. plt.gcf().clear()
  262. result = self.stats_db._process_user_defined_query(
  263. "SELECT ttlValue, SUM(ttlCount) FROM ip_ttl GROUP BY ttlValue")
  264. graphx, graphy = [], []
  265. for row in result:
  266. graphx.append(row[0])
  267. graphy.append(row[1])
  268. plt.autoscale(enable=True, axis='both')
  269. plt.title("TTL Distribution")
  270. plt.xlabel('TTL Value')
  271. plt.ylabel('Number of Packets')
  272. width = 0.5
  273. plt.xlim([0, max(graphx)])
  274. plt.grid(True)
  275. plt.bar(graphx, graphy, width, align='center', linewidth=2, color='red', edgecolor='red')
  276. out = self.pcap_filepath.replace('.pcap', '_plot-ttl' + file_ending)
  277. plt.savefig(out,dpi=500)
  278. return out
  279. # Aidmar
  280. def plot_mss(file_ending: str):
  281. plt.gcf().clear()
  282. result = self.stats_db._process_user_defined_query(
  283. "SELECT mssValue, SUM(mssCount) FROM tcp_mss_dist GROUP BY mssValue")
  284. graphx, graphy = [], []
  285. for row in result:
  286. graphx.append(row[0])
  287. graphy.append(row[1])
  288. plt.autoscale(enable=True, axis='both')
  289. plt.title("MSS Distribution")
  290. plt.xlabel('MSS Value')
  291. plt.ylabel('Number of Packets')
  292. width = 0.5
  293. plt.xlim([0, max(graphx)])
  294. plt.grid(True)
  295. plt.bar(graphx, graphy, width, align='center', linewidth=2, color='red', edgecolor='red')
  296. out = self.pcap_filepath.replace('.pcap', '_plot-mss' + file_ending)
  297. plt.savefig(out,dpi=500)
  298. return out
  299. # Aidmar
  300. def plot_win(file_ending: str):
  301. plt.gcf().clear()
  302. result = self.stats_db._process_user_defined_query(
  303. "SELECT winSize, SUM(winCount) FROM tcp_syn_win GROUP BY winSize")
  304. graphx, graphy = [], []
  305. for row in result:
  306. graphx.append(row[0])
  307. graphy.append(row[1])
  308. plt.autoscale(enable=True, axis='both')
  309. plt.title("Window Size Distribution")
  310. plt.xlabel('Window Size')
  311. plt.ylabel('Number of Packets')
  312. width = 0.5
  313. plt.xlim([0, max(graphx)])
  314. plt.grid(True)
  315. plt.bar(graphx, graphy, width, align='center', linewidth=2, color='red', edgecolor='red')
  316. out = self.pcap_filepath.replace('.pcap', '_plot-win' + file_ending)
  317. plt.savefig(out,dpi=500)
  318. return out
  319. # Aidmar
  320. def plot_protocol(file_ending: str):
  321. plt.gcf().clear()
  322. result = self.stats_db._process_user_defined_query(
  323. "SELECT protocolName, SUM(protocolCount) FROM ip_protocols GROUP BY protocolName")
  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("Protocols Distribution")
  330. plt.xlabel('Protocols')
  331. plt.ylabel('Number of Packets')
  332. width = 0.5
  333. plt.xlim([0, len(graphx)])
  334. plt.grid(True)
  335. # Protocols' names on x-axis
  336. x = range(0,len(graphx))
  337. my_xticks = graphx
  338. plt.xticks(x, my_xticks)
  339. plt.bar(x, graphy, width, align='center', linewidth=2, color='red', edgecolor='red')
  340. out = self.pcap_filepath.replace('.pcap', '_plot-protocol' + file_ending)
  341. plt.savefig(out,dpi=500)
  342. return out
  343. # Aidmar
  344. def plot_port(file_ending: str):
  345. plt.gcf().clear()
  346. result = self.stats_db._process_user_defined_query(
  347. "SELECT portNumber, SUM(portCount) FROM ip_ports GROUP BY portNumber")
  348. graphx, graphy = [], []
  349. for row in result:
  350. graphx.append(row[0])
  351. graphy.append(row[1])
  352. plt.autoscale(enable=True, axis='both')
  353. plt.title("Ports Distribution")
  354. plt.xlabel('Ports Numbers')
  355. plt.ylabel('Number of Packets')
  356. width = 0.5
  357. plt.xlim([0, max(graphx)])
  358. plt.grid(True)
  359. plt.bar(graphx, graphy, width, align='center', linewidth=2, color='red', edgecolor='red')
  360. out = self.pcap_filepath.replace('.pcap', '_plot-port' + file_ending)
  361. plt.savefig(out,dpi=500)
  362. return out
  363. # Aidmar - This distribution is not drawable for big datasets
  364. def plot_ip_src(file_ending: str):
  365. plt.gcf().clear()
  366. result = self.stats_db._process_user_defined_query(
  367. "SELECT ipAddress, pktsSent FROM ip_statistics")
  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("Source IP Distribution")
  374. plt.xlabel('Source IP')
  375. plt.ylabel('Number of Packets')
  376. width = 0.5
  377. plt.xlim([0, len(graphx)])
  378. plt.grid(True)
  379. # IPs on x-axis
  380. x = range(0, len(graphx))
  381. my_xticks = graphx
  382. plt.xticks(x, my_xticks, rotation='vertical', fontsize=5)
  383. plt.tight_layout()
  384. # limit the number of xticks
  385. plt.locator_params(axis='x', nbins=20)
  386. plt.bar(x, graphy, width, align='center', linewidth=2, color='red', edgecolor='red')
  387. out = self.pcap_filepath.replace('.pcap', '_plot-ip-src' + file_ending)
  388. plt.savefig(out, dpi=500)
  389. return out
  390. # Aidmar - This distribution is not drawable for big datasets
  391. def plot_ip_dst(file_ending: str):
  392. plt.gcf().clear()
  393. result = self.stats_db._process_user_defined_query(
  394. "SELECT ipAddress, pktsReceived FROM ip_statistics")
  395. graphx, graphy = [], []
  396. for row in result:
  397. graphx.append(row[0])
  398. graphy.append(row[1])
  399. plt.autoscale(enable=True, axis='both')
  400. plt.title("Destination IP Distribution")
  401. plt.xlabel('Destination IP')
  402. plt.ylabel('Number of Packets')
  403. width = 0.5
  404. plt.xlim([0, len(graphx)])
  405. plt.grid(True)
  406. # IPs on x-axis
  407. x = range(0, len(graphx))
  408. my_xticks = graphx
  409. plt.xticks(x, my_xticks, rotation='vertical', fontsize=5)
  410. plt.tight_layout()
  411. # limit the number of xticks
  412. plt.locator_params(axis='x', nbins=20)
  413. plt.bar(x, graphy, width, align='center', linewidth=2, color='red', edgecolor='red')
  414. out = self.pcap_filepath.replace('.pcap', '_plot-ip-dst' + file_ending)
  415. plt.savefig(out, dpi=500)
  416. return out
  417. # Aidmar
  418. def plot_interval_pktCount(file_ending: str):
  419. plt.gcf().clear()
  420. result = self.stats_db._process_user_defined_query(
  421. "SELECT lastPktTimestamp, pktsCount FROM interval_statistics ORDER BY lastPktTimestamp")
  422. graphx, graphy = [], []
  423. for row in result:
  424. graphx.append(row[0])
  425. graphy.append(row[1])
  426. plt.autoscale(enable=True, axis='both')
  427. plt.title("Packet Rate")
  428. plt.xlabel('Timestamp')
  429. plt.ylabel('Number of Packets')
  430. width = 0.5
  431. plt.xlim([0, len(graphx)])
  432. plt.grid(True)
  433. # timestamp on x-axis
  434. x = range(0, len(graphx))
  435. my_xticks = graphx
  436. plt.xticks(x, my_xticks, rotation='vertical', fontsize=5)
  437. plt.tight_layout()
  438. # limit the number of xticks
  439. plt.locator_params(axis='x', nbins=20)
  440. plt.bar(x, graphy, width, align='center', linewidth=2, color='red', edgecolor='red')
  441. out = self.pcap_filepath.replace('.pcap', '_plot-interval-pkt-count' + file_ending)
  442. plt.savefig(out, dpi=500)
  443. return out
  444. # Aidmar
  445. def plot_interval_ip_src_ent(file_ending: str):
  446. plt.gcf().clear()
  447. result = self.stats_db._process_user_defined_query(
  448. "SELECT lastPktTimestamp, ipSrcEntropy FROM interval_statistics ORDER BY lastPktTimestamp")
  449. graphx, graphy = [], []
  450. for row in result:
  451. graphx.append(row[0])
  452. graphy.append(row[1])
  453. plt.autoscale(enable=True, axis='both')
  454. plt.title("Source IP Entropy")
  455. plt.xlabel('Timestamp')
  456. plt.ylabel('Entropy')
  457. width = 0.5
  458. plt.xlim([0, len(graphx)])
  459. plt.grid(True)
  460. # timestamp on x-axis
  461. x = range(0, len(graphx))
  462. my_xticks = graphx
  463. plt.xticks(x, my_xticks, rotation='vertical', fontsize=5)
  464. plt.tight_layout()
  465. # limit the number of xticks
  466. plt.locator_params(axis='x', nbins=20)
  467. plt.bar(x, graphy, width, align='center', linewidth=2, color='red', edgecolor='red')
  468. out = self.pcap_filepath.replace('.pcap', '_plot-interval-ip-src-ent' + file_ending)
  469. plt.savefig(out, dpi=500)
  470. return out
  471. # Aidmar
  472. def plot_interval_ip_dst_ent(file_ending: str):
  473. plt.gcf().clear()
  474. result = self.stats_db._process_user_defined_query(
  475. "SELECT lastPktTimestamp, ipDstEntropy FROM interval_statistics ORDER BY lastPktTimestamp")
  476. graphx, graphy = [], []
  477. for row in result:
  478. graphx.append(row[0])
  479. graphy.append(row[1])
  480. plt.autoscale(enable=True, axis='both')
  481. plt.title("Destination IP Entropy")
  482. plt.xlabel('Timestamp')
  483. plt.ylabel('Entropy')
  484. width = 0.5
  485. plt.xlim([0, len(graphx)])
  486. plt.grid(True)
  487. # timestamp on x-axis
  488. x = range(0, len(graphx))
  489. my_xticks = graphx
  490. plt.xticks(x, my_xticks, rotation='vertical', fontsize=5)
  491. plt.tight_layout()
  492. # limit the number of xticks
  493. plt.locator_params(axis='x', nbins=20)
  494. plt.bar(x, graphy, width, align='center', linewidth=2, color='red', edgecolor='red')
  495. out = self.pcap_filepath.replace('.pcap', '_plot-interval-ip-dst-ent' + file_ending)
  496. plt.savefig(out, dpi=500)
  497. return out
  498. # Aidmar
  499. def plot_interval_ip_dst_cum_ent(file_ending: str):
  500. plt.gcf().clear()
  501. result = self.stats_db._process_user_defined_query(
  502. "SELECT lastPktTimestamp, ipDstCumEntropy FROM interval_statistics ORDER BY lastPktTimestamp")
  503. graphx, graphy = [], []
  504. for row in result:
  505. graphx.append(row[0])
  506. graphy.append(row[1])
  507. plt.autoscale(enable=True, axis='both')
  508. plt.title("Destination IP Cumulative Entropy")
  509. plt.xlabel('Timestamp')
  510. plt.ylabel('Entropy')
  511. plt.xlim([0, len(graphx)])
  512. plt.grid(True)
  513. # timestamp on x-axis
  514. x = range(0, len(graphx))
  515. my_xticks = graphx
  516. plt.xticks(x, my_xticks, rotation='vertical', fontsize=5)
  517. plt.tight_layout()
  518. # limit the number of xticks
  519. plt.locator_params(axis='x', nbins=20)
  520. plt.plot(x, graphy, 'r')
  521. out = self.pcap_filepath.replace('.pcap', '_plot-interval-ip-dst-cum-ent' + file_ending)
  522. plt.savefig(out, dpi=500)
  523. return out
  524. # Aidmar
  525. def plot_interval_ip_src_cum_ent(file_ending: str):
  526. plt.gcf().clear()
  527. result = self.stats_db._process_user_defined_query(
  528. "SELECT lastPktTimestamp, ipSrcCumEntropy FROM interval_statistics ORDER BY lastPktTimestamp")
  529. graphx, graphy = [], []
  530. for row in result:
  531. graphx.append(row[0])
  532. graphy.append(row[1])
  533. plt.autoscale(enable=True, axis='both')
  534. plt.title("Source IP Cumulative Entropy")
  535. plt.xlabel('Timestamp')
  536. plt.ylabel('Entropy')
  537. plt.xlim([0, len(graphx)])
  538. plt.grid(True)
  539. # timestamp on x-axis
  540. x = range(0, len(graphx))
  541. my_xticks = graphx
  542. plt.xticks(x, my_xticks, rotation='vertical', fontsize=5)
  543. plt.tight_layout()
  544. # limit the number of xticks
  545. plt.locator_params(axis='x',nbins=20)
  546. plt.plot(x, graphy, 'r')
  547. out = self.pcap_filepath.replace('.pcap', '_plot-interval-ip-src-cum-ent' + file_ending)
  548. plt.savefig(out, dpi=500)
  549. return out
  550. ttl_out_path = plot_ttl('.' + format)
  551. mss_out_path = plot_mss('.' + format)
  552. win_out_path = plot_win('.' + format)
  553. protocol_out_path = plot_protocol('.' + format)
  554. port_out_path = plot_port('.' + format)
  555. #ip_src_out_path = plot_ip_src('.' + format)
  556. #ip_dst_out_path = plot_ip_dst('.' + format)
  557. plot_interval_pktCount = plot_interval_pktCount('.' + format)
  558. plot_interval_ip_src_ent = plot_interval_ip_src_ent('.' + format)
  559. plot_interval_ip_dst_ent = plot_interval_ip_dst_ent('.' + format)
  560. plot_interval_ip_src_cum_ent = plot_interval_ip_src_cum_ent('.' + format)
  561. plot_interval_ip_dst_cum_ent = plot_interval_ip_dst_cum_ent('.' + format)
  562. #print("Saved distributions plots at: %s, %s, %s, %s, %s, %s, %s, %s %s" %(ttl_out_path,mss_out_path, win_out_path,
  563. #protocol_out_path, port_out_path,ip_src_out_path,ip_dst_out_path, plot_interval_pktCount))
  564. # Aidmar
  565. def calculate_complement_packet_rates(self, pps):
  566. """
  567. Calculates the complement packet rates of the background traffic packet rates per interval.
  568. Then normalize it to maximum boundary, which is the input parameter pps
  569. :return: normalized packet rates for each time interval.
  570. """
  571. result = self.process_db_query(
  572. "SELECT lastPktTimestamp,pktsCount FROM interval_statistics ORDER BY lastPktTimestamp")
  573. # print(result)
  574. bg_interval_pps = []
  575. complement_interval_pps = []
  576. intervalsSum = 0
  577. if result:
  578. # Get the interval in seconds
  579. for i, row in enumerate(result):
  580. if i < len(result) - 1:
  581. intervalsSum += math.ceil((int(result[i + 1][0]) * 10 ** -6) - (int(row[0]) * 10 ** -6))
  582. interval = intervalsSum / (len(result) - 1)
  583. # Convert timestamp from micro to seconds, convert packet rate "per interval" to "per second"
  584. for row in result:
  585. bg_interval_pps.append((int(row[0]) * 10 ** -6, int(row[1] / interval)))
  586. # Find max PPS
  587. maxPPS = max(bg_interval_pps, key=itemgetter(1))[1]
  588. for row in bg_interval_pps:
  589. complement_interval_pps.append((row[0], int(pps * (maxPPS - row[1]) / maxPPS)))
  590. return complement_interval_pps
  591. """
  592. # Aidmar
  593. # bhattacharyya test
  594. import math
  595. def mean(hist):
  596. mean = 0.0;
  597. for i in hist:
  598. mean += i;
  599. mean /= len(hist);
  600. return mean;
  601. def bhatta(hist1, hist2):
  602. # calculate mean of hist1
  603. h1_ = mean(hist1);
  604. # calculate mean of hist2
  605. h2_ = mean(hist2);
  606. # calculate score
  607. score = 0;
  608. for i in range(len(hist1)):
  609. score += math.sqrt(hist1[i] * hist2[i]);
  610. # print h1_,h2_,score;
  611. score = math.sqrt(1 - (1 / math.sqrt(h1_ * h2_ * len(hist1) * len(hist1))) * score);
  612. return score;
  613. print("\nbhatta distance: " + str(bhatta(graphy, graphy_aftr)))
  614. """