Statistics.py 35 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888
  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. if(result):
  285. graphx, graphy = [], []
  286. for row in result:
  287. graphx.append(row[0])
  288. graphy.append(row[1])
  289. plt.autoscale(enable=True, axis='both')
  290. plt.title("MSS Distribution")
  291. plt.xlabel('MSS Value')
  292. plt.ylabel('Number of Packets')
  293. width = 0.5
  294. plt.xlim([0, max(graphx)])
  295. plt.grid(True)
  296. plt.bar(graphx, graphy, width, align='center', linewidth=2, color='red', edgecolor='red')
  297. out = self.pcap_filepath.replace('.pcap', '_plot-mss' + file_ending)
  298. plt.savefig(out,dpi=500)
  299. return out
  300. else:
  301. print("Error plot MSS: No MSS values found!")
  302. # Aidmar
  303. def plot_win(file_ending: str):
  304. plt.gcf().clear()
  305. result = self.stats_db._process_user_defined_query(
  306. "SELECT winSize, SUM(winCount) FROM tcp_syn_win GROUP BY winSize")
  307. graphx, graphy = [], []
  308. for row in result:
  309. graphx.append(row[0])
  310. graphy.append(row[1])
  311. plt.autoscale(enable=True, axis='both')
  312. plt.title("Window Size Distribution")
  313. plt.xlabel('Window Size')
  314. plt.ylabel('Number of Packets')
  315. width = 0.5
  316. plt.xlim([0, max(graphx)])
  317. plt.grid(True)
  318. plt.bar(graphx, graphy, width, align='center', linewidth=2, color='red', edgecolor='red')
  319. out = self.pcap_filepath.replace('.pcap', '_plot-win' + file_ending)
  320. plt.savefig(out,dpi=500)
  321. return out
  322. # Aidmar
  323. def plot_protocol(file_ending: str):
  324. plt.gcf().clear()
  325. result = self.stats_db._process_user_defined_query(
  326. "SELECT protocolName, SUM(protocolCount) FROM ip_protocols GROUP BY protocolName")
  327. graphx, graphy = [], []
  328. for row in result:
  329. graphx.append(row[0])
  330. graphy.append(row[1])
  331. plt.autoscale(enable=True, axis='both')
  332. plt.title("Protocols Distribution")
  333. plt.xlabel('Protocols')
  334. plt.ylabel('Number of Packets')
  335. width = 0.5
  336. plt.xlim([0, len(graphx)])
  337. plt.grid(True)
  338. # Protocols' names on x-axis
  339. x = range(0,len(graphx))
  340. my_xticks = graphx
  341. plt.xticks(x, my_xticks)
  342. plt.bar(x, graphy, width, align='center', linewidth=2, color='red', edgecolor='red')
  343. out = self.pcap_filepath.replace('.pcap', '_plot-protocol' + file_ending)
  344. plt.savefig(out,dpi=500)
  345. return out
  346. # Aidmar
  347. def plot_port(file_ending: str):
  348. plt.gcf().clear()
  349. result = self.stats_db._process_user_defined_query(
  350. "SELECT portNumber, SUM(portCount) FROM ip_ports GROUP BY portNumber")
  351. graphx, graphy = [], []
  352. for row in result:
  353. graphx.append(row[0])
  354. graphy.append(row[1])
  355. plt.autoscale(enable=True, axis='both')
  356. plt.title("Ports Distribution")
  357. plt.xlabel('Ports Numbers')
  358. plt.ylabel('Number of Packets')
  359. width = 0.5
  360. plt.xlim([0, max(graphx)])
  361. plt.grid(True)
  362. plt.bar(graphx, graphy, width, align='center', linewidth=2, color='red', edgecolor='red')
  363. out = self.pcap_filepath.replace('.pcap', '_plot-port' + file_ending)
  364. plt.savefig(out,dpi=500)
  365. return out
  366. # Aidmar - This distribution is not drawable for big datasets
  367. def plot_ip_src(file_ending: str):
  368. plt.gcf().clear()
  369. result = self.stats_db._process_user_defined_query(
  370. "SELECT ipAddress, pktsSent FROM ip_statistics")
  371. graphx, graphy = [], []
  372. for row in result:
  373. graphx.append(row[0])
  374. graphy.append(row[1])
  375. plt.autoscale(enable=True, axis='both')
  376. plt.title("Source IP Distribution")
  377. plt.xlabel('Source IP')
  378. plt.ylabel('Number of Packets')
  379. width = 0.5
  380. plt.xlim([0, len(graphx)])
  381. plt.grid(True)
  382. # IPs on x-axis
  383. x = range(0, len(graphx))
  384. my_xticks = graphx
  385. plt.xticks(x, my_xticks, rotation='vertical', fontsize=5)
  386. plt.tight_layout()
  387. # limit the number of xticks
  388. plt.locator_params(axis='x', nbins=20)
  389. plt.bar(x, graphy, width, align='center', linewidth=2, color='red', edgecolor='red')
  390. out = self.pcap_filepath.replace('.pcap', '_plot-ip-src' + file_ending)
  391. plt.savefig(out, dpi=500)
  392. return out
  393. # Aidmar - This distribution is not drawable for big datasets
  394. def plot_ip_dst(file_ending: str):
  395. plt.gcf().clear()
  396. result = self.stats_db._process_user_defined_query(
  397. "SELECT ipAddress, pktsReceived FROM ip_statistics")
  398. graphx, graphy = [], []
  399. for row in result:
  400. graphx.append(row[0])
  401. graphy.append(row[1])
  402. plt.autoscale(enable=True, axis='both')
  403. plt.title("Destination IP Distribution")
  404. plt.xlabel('Destination IP')
  405. plt.ylabel('Number of Packets')
  406. width = 0.5
  407. plt.xlim([0, len(graphx)])
  408. plt.grid(True)
  409. # IPs on x-axis
  410. x = range(0, len(graphx))
  411. my_xticks = graphx
  412. plt.xticks(x, my_xticks, rotation='vertical', fontsize=5)
  413. plt.tight_layout()
  414. # limit the number of xticks
  415. plt.locator_params(axis='x', nbins=20)
  416. plt.bar(x, graphy, width, align='center', linewidth=2, color='red', edgecolor='red')
  417. out = self.pcap_filepath.replace('.pcap', '_plot-ip-dst' + file_ending)
  418. plt.savefig(out, dpi=500)
  419. return out
  420. # Aidmar
  421. def plot_interval_pktCount(file_ending: str):
  422. plt.gcf().clear()
  423. result = self.stats_db._process_user_defined_query(
  424. "SELECT lastPktTimestamp, pktsCount FROM interval_statistics ORDER BY lastPktTimestamp")
  425. graphx, graphy = [], []
  426. for row in result:
  427. graphx.append(row[0])
  428. graphy.append(row[1])
  429. plt.autoscale(enable=True, axis='both')
  430. plt.title("Packet Rate")
  431. plt.xlabel('Timestamp')
  432. plt.ylabel('Number of Packets')
  433. width = 0.5
  434. plt.xlim([0, len(graphx)])
  435. plt.grid(True)
  436. # timestamp on x-axis
  437. x = range(0, len(graphx))
  438. my_xticks = graphx
  439. plt.xticks(x, my_xticks, rotation='vertical', fontsize=5)
  440. plt.tight_layout()
  441. # limit the number of xticks
  442. plt.locator_params(axis='x', nbins=20)
  443. plt.bar(x, graphy, width, align='center', linewidth=2, color='red', edgecolor='red')
  444. out = self.pcap_filepath.replace('.pcap', '_plot-interval-pkt-count' + file_ending)
  445. plt.savefig(out, dpi=500)
  446. return out
  447. # Aidmar
  448. def plot_interval_ip_src_ent(file_ending: str):
  449. plt.gcf().clear()
  450. result = self.stats_db._process_user_defined_query(
  451. "SELECT lastPktTimestamp, ipSrcEntropy FROM interval_statistics ORDER BY lastPktTimestamp")
  452. graphx, graphy = [], []
  453. for row in result:
  454. graphx.append(row[0])
  455. graphy.append(row[1])
  456. plt.autoscale(enable=True, axis='both')
  457. plt.title("Source IP Entropy")
  458. plt.xlabel('Timestamp')
  459. plt.ylabel('Entropy')
  460. width = 0.5
  461. plt.xlim([0, len(graphx)])
  462. plt.grid(True)
  463. # timestamp on x-axis
  464. x = range(0, len(graphx))
  465. my_xticks = graphx
  466. plt.xticks(x, my_xticks, rotation='vertical', fontsize=5)
  467. plt.tight_layout()
  468. # limit the number of xticks
  469. plt.locator_params(axis='x', nbins=20)
  470. plt.bar(x, graphy, width, align='center', linewidth=2, color='red', edgecolor='red')
  471. out = self.pcap_filepath.replace('.pcap', '_plot-interval-ip-src-ent' + file_ending)
  472. plt.savefig(out, dpi=500)
  473. return out
  474. # Aidmar
  475. def plot_interval_ip_dst_ent(file_ending: str):
  476. plt.gcf().clear()
  477. result = self.stats_db._process_user_defined_query(
  478. "SELECT lastPktTimestamp, ipDstEntropy FROM interval_statistics ORDER BY lastPktTimestamp")
  479. graphx, graphy = [], []
  480. for row in result:
  481. graphx.append(row[0])
  482. graphy.append(row[1])
  483. plt.autoscale(enable=True, axis='both')
  484. plt.title("Destination IP Entropy")
  485. plt.xlabel('Timestamp')
  486. plt.ylabel('Entropy')
  487. width = 0.5
  488. plt.xlim([0, len(graphx)])
  489. plt.grid(True)
  490. # timestamp on x-axis
  491. x = range(0, len(graphx))
  492. my_xticks = graphx
  493. plt.xticks(x, my_xticks, rotation='vertical', fontsize=5)
  494. plt.tight_layout()
  495. # limit the number of xticks
  496. plt.locator_params(axis='x', nbins=20)
  497. plt.bar(x, graphy, width, align='center', linewidth=2, color='red', edgecolor='red')
  498. out = self.pcap_filepath.replace('.pcap', '_plot-interval-ip-dst-ent' + file_ending)
  499. plt.savefig(out, dpi=500)
  500. return out
  501. # Aidmar
  502. def plot_interval_ip_dst_cum_ent(file_ending: str):
  503. plt.gcf().clear()
  504. result = self.stats_db._process_user_defined_query(
  505. "SELECT lastPktTimestamp, ipDstCumEntropy FROM interval_statistics ORDER BY lastPktTimestamp")
  506. graphx, graphy = [], []
  507. for row in result:
  508. graphx.append(row[0])
  509. graphy.append(row[1])
  510. plt.autoscale(enable=True, axis='both')
  511. plt.title("Destination IP Cumulative Entropy")
  512. plt.xlabel('Timestamp')
  513. plt.ylabel('Entropy')
  514. plt.xlim([0, len(graphx)])
  515. plt.grid(True)
  516. # timestamp on x-axis
  517. x = range(0, len(graphx))
  518. my_xticks = graphx
  519. plt.xticks(x, my_xticks, rotation='vertical', fontsize=5)
  520. plt.tight_layout()
  521. # limit the number of xticks
  522. plt.locator_params(axis='x', nbins=20)
  523. plt.plot(x, graphy, 'r')
  524. out = self.pcap_filepath.replace('.pcap', '_plot-interval-ip-dst-cum-ent' + file_ending)
  525. plt.savefig(out, dpi=500)
  526. return out
  527. # Aidmar
  528. def plot_interval_ip_src_cum_ent(file_ending: str):
  529. plt.gcf().clear()
  530. result = self.stats_db._process_user_defined_query(
  531. "SELECT lastPktTimestamp, ipSrcCumEntropy FROM interval_statistics ORDER BY lastPktTimestamp")
  532. graphx, graphy = [], []
  533. for row in result:
  534. graphx.append(row[0])
  535. graphy.append(row[1])
  536. plt.autoscale(enable=True, axis='both')
  537. plt.title("Source IP Cumulative Entropy")
  538. plt.xlabel('Timestamp')
  539. plt.ylabel('Entropy')
  540. plt.xlim([0, len(graphx)])
  541. plt.grid(True)
  542. # timestamp on x-axis
  543. x = range(0, len(graphx))
  544. my_xticks = graphx
  545. plt.xticks(x, my_xticks, rotation='vertical', fontsize=5)
  546. plt.tight_layout()
  547. # limit the number of xticks
  548. plt.locator_params(axis='x',nbins=20)
  549. plt.plot(x, graphy, 'r')
  550. out = self.pcap_filepath.replace('.pcap', '_plot-interval-ip-src-cum-ent' + file_ending)
  551. plt.savefig(out, dpi=500)
  552. return out
  553. # Aidmar
  554. def plot_interval_new_ip(file_ending: str):
  555. plt.gcf().clear()
  556. result = self.stats_db._process_user_defined_query(
  557. "SELECT lastPktTimestamp, newIPCount FROM interval_statistics ORDER BY lastPktTimestamp")
  558. graphx, graphy = [], []
  559. for row in result:
  560. graphx.append(row[0])
  561. graphy.append(row[1])
  562. plt.autoscale(enable=True, axis='both')
  563. plt.title("IP New Values Distribution")
  564. plt.xlabel('Timestamp')
  565. plt.ylabel('New values count')
  566. plt.xlim([0, len(graphx)])
  567. plt.grid(True)
  568. width = 0.5
  569. # timestamp on x-axis
  570. x = range(0, len(graphx))
  571. my_xticks = graphx
  572. plt.xticks(x, my_xticks, rotation='vertical', fontsize=5)
  573. plt.tight_layout()
  574. # limit the number of xticks
  575. plt.locator_params(axis='x', nbins=20)
  576. plt.bar(x, graphy, width, align='center', linewidth=2, color='red', edgecolor='red')
  577. out = self.pcap_filepath.replace('.pcap', '_plot-interval-new-ip-dist' + file_ending)
  578. plt.savefig(out, dpi=500)
  579. return out
  580. # Aidmar
  581. def plot_interval_new_ttl(file_ending: str):
  582. plt.gcf().clear()
  583. result = self.stats_db._process_user_defined_query(
  584. "SELECT lastPktTimestamp, newTTLCount FROM interval_statistics ORDER BY lastPktTimestamp")
  585. graphx, graphy = [], []
  586. for row in result:
  587. graphx.append(row[0])
  588. graphy.append(row[1])
  589. plt.autoscale(enable=True, axis='both')
  590. plt.title("TTL New Values Distribution")
  591. plt.xlabel('Timestamp')
  592. plt.ylabel('New values count')
  593. plt.xlim([0, len(graphx)])
  594. plt.grid(True)
  595. width = 0.5
  596. # timestamp on x-axis
  597. x = range(0, len(graphx))
  598. my_xticks = graphx
  599. plt.xticks(x, my_xticks, rotation='vertical', fontsize=5)
  600. plt.tight_layout()
  601. # limit the number of xticks
  602. plt.locator_params(axis='x', nbins=20)
  603. plt.bar(x, graphy, width, align='center', linewidth=2, color='red', edgecolor='red')
  604. out = self.pcap_filepath.replace('.pcap', '_plot-interval-new-ttl-dist' + file_ending)
  605. plt.savefig(out, dpi=500)
  606. return out
  607. # Aidmar
  608. def plot_interval_new_tos(file_ending: str):
  609. plt.gcf().clear()
  610. result = self.stats_db._process_user_defined_query(
  611. "SELECT lastPktTimestamp, newToSCount FROM interval_statistics ORDER BY lastPktTimestamp")
  612. graphx, graphy = [], []
  613. for row in result:
  614. graphx.append(row[0])
  615. graphy.append(row[1])
  616. plt.autoscale(enable=True, axis='both')
  617. plt.title("ToS New Values Distribution")
  618. plt.xlabel('Timestamp')
  619. plt.ylabel('New values count')
  620. plt.xlim([0, len(graphx)])
  621. plt.grid(True)
  622. width = 0.5
  623. # timestamp on x-axis
  624. x = range(0, len(graphx))
  625. my_xticks = graphx
  626. plt.xticks(x, my_xticks, rotation='vertical', fontsize=5)
  627. plt.tight_layout()
  628. # limit the number of xticks
  629. plt.locator_params(axis='x', nbins=20)
  630. plt.bar(x, graphy, width, align='center', linewidth=2, color='red', edgecolor='red')
  631. out = self.pcap_filepath.replace('.pcap', '_plot-interval-new-tos-dist' + file_ending)
  632. plt.savefig(out, dpi=500)
  633. return out
  634. # Aidmar
  635. def plot_interval_new_win_size(file_ending: str):
  636. plt.gcf().clear()
  637. result = self.stats_db._process_user_defined_query(
  638. "SELECT lastPktTimestamp, newWinSizeCount FROM interval_statistics ORDER BY lastPktTimestamp")
  639. graphx, graphy = [], []
  640. for row in result:
  641. graphx.append(row[0])
  642. graphy.append(row[1])
  643. plt.autoscale(enable=True, axis='both')
  644. plt.title("Window Size New Values Distribution")
  645. plt.xlabel('Timestamp')
  646. plt.ylabel('New values count')
  647. plt.xlim([0, len(graphx)])
  648. plt.grid(True)
  649. width = 0.5
  650. # timestamp on x-axis
  651. x = range(0, len(graphx))
  652. my_xticks = graphx
  653. plt.xticks(x, my_xticks, rotation='vertical', fontsize=5)
  654. plt.tight_layout()
  655. # limit the number of xticks
  656. plt.locator_params(axis='x', nbins=20)
  657. plt.bar(x, graphy, width, align='center', linewidth=2, color='red', edgecolor='red')
  658. out = self.pcap_filepath.replace('.pcap', '_plot-interval-new-win-size-dist' + file_ending)
  659. plt.savefig(out, dpi=500)
  660. return out
  661. # Aidmar
  662. def plot_interval_new_mss(file_ending: str):
  663. plt.gcf().clear()
  664. result = self.stats_db._process_user_defined_query(
  665. "SELECT lastPktTimestamp, newMSSCount FROM interval_statistics ORDER BY lastPktTimestamp")
  666. graphx, graphy = [], []
  667. for row in result:
  668. graphx.append(row[0])
  669. graphy.append(row[1])
  670. plt.autoscale(enable=True, axis='both')
  671. plt.title("MSS New Values Distribution")
  672. plt.xlabel('Timestamp')
  673. plt.ylabel('New values count')
  674. plt.xlim([0, len(graphx)])
  675. plt.grid(True)
  676. width = 0.5
  677. # timestamp on x-axis
  678. x = range(0, len(graphx))
  679. my_xticks = graphx
  680. plt.xticks(x, my_xticks, rotation='vertical', fontsize=5)
  681. plt.tight_layout()
  682. # limit the number of xticks
  683. plt.locator_params(axis='x', nbins=20)
  684. plt.bar(x, graphy, width, align='center', linewidth=2, color='red', edgecolor='red')
  685. out = self.pcap_filepath.replace('.pcap', '_plot-interval-new-mss-dist' + file_ending)
  686. plt.savefig(out, dpi=500)
  687. return out
  688. ttl_out_path = plot_ttl('.' + format)
  689. mss_out_path = plot_mss('.' + format)
  690. win_out_path = plot_win('.' + format)
  691. protocol_out_path = plot_protocol('.' + format)
  692. port_out_path = plot_port('.' + format)
  693. #ip_src_out_path = plot_ip_src('.' + format)
  694. #ip_dst_out_path = plot_ip_dst('.' + format)
  695. plot_interval_pktCount = plot_interval_pktCount('.' + format)
  696. plot_interval_ip_src_ent = plot_interval_ip_src_ent('.' + format)
  697. plot_interval_ip_dst_ent = plot_interval_ip_dst_ent('.' + format)
  698. plot_interval_ip_src_cum_ent = plot_interval_ip_src_cum_ent('.' + format)
  699. plot_interval_ip_dst_cum_ent = plot_interval_ip_dst_cum_ent('.' + format)
  700. plot_interval_new_ip = plot_interval_new_ip('.' + format)
  701. plot_interval_new_ttl = plot_interval_new_ttl('.' + format)
  702. plot_interval_new_tos = plot_interval_new_tos('.' + format)
  703. plot_interval_new_win_size = plot_interval_new_win_size('.' + format)
  704. plot_interval_new_mss = plot_interval_new_mss('.' + format)
  705. #print("Saved distributions plots at: %s, %s, %s, %s, %s, %s, %s, %s %s" %(ttl_out_path,mss_out_path, win_out_path,
  706. #protocol_out_path, port_out_path,ip_src_out_path,ip_dst_out_path, plot_interval_pktCount))
  707. # Aidmar
  708. def calculate_complement_packet_rates(self, pps):
  709. """
  710. Calculates the complement packet rates of the background traffic packet rates per interval.
  711. Then normalize it to maximum boundary, which is the input parameter pps
  712. :return: normalized packet rates for each time interval.
  713. """
  714. result = self.process_db_query(
  715. "SELECT lastPktTimestamp,pktsCount FROM interval_statistics ORDER BY lastPktTimestamp")
  716. # print(result)
  717. bg_interval_pps = []
  718. complement_interval_pps = []
  719. intervalsSum = 0
  720. if result:
  721. # Get the interval in seconds
  722. for i, row in enumerate(result):
  723. if i < len(result) - 1:
  724. intervalsSum += math.ceil((int(result[i + 1][0]) * 10 ** -6) - (int(row[0]) * 10 ** -6))
  725. interval = intervalsSum / (len(result) - 1)
  726. # Convert timestamp from micro to seconds, convert packet rate "per interval" to "per second"
  727. for row in result:
  728. bg_interval_pps.append((int(row[0]) * 10 ** -6, int(row[1] / interval)))
  729. # Find max PPS
  730. maxPPS = max(bg_interval_pps, key=itemgetter(1))[1]
  731. for row in bg_interval_pps:
  732. complement_interval_pps.append((row[0], int(pps * (maxPPS - row[1]) / maxPPS)))
  733. return complement_interval_pps
  734. """
  735. # Aidmar
  736. # bhattacharyya test
  737. import math
  738. def mean(hist):
  739. mean = 0.0;
  740. for i in hist:
  741. mean += i;
  742. mean /= len(hist);
  743. return mean;
  744. def bhatta(hist1, hist2):
  745. # calculate mean of hist1
  746. h1_ = mean(hist1);
  747. # calculate mean of hist2
  748. h2_ = mean(hist2);
  749. # calculate score
  750. score = 0;
  751. for i in range(len(hist1)):
  752. score += math.sqrt(hist1[i] * hist2[i]);
  753. # print h1_,h2_,score;
  754. score = math.sqrt(1 - (1 / math.sqrt(h1_ * h2_ * len(hist1) * len(hist1))) * score);
  755. return score;
  756. print("\nbhatta distance: " + str(bhatta(graphy, graphy_aftr)))
  757. """