Statistics.py 37 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941
  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, 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. # Aidmar - comment out
  208. # def get_mss(self, ipAddress: str):
  209. # """
  210. # :param ipAddress: The IP address whose used MSS should be determined
  211. # :return: The TCP MSS value used by the IP address, or if the IP addresses never specified a MSS,
  212. # then None is returned
  213. # """
  214. # mss_value = self.process_db_query('SELECT mss from tcp_mss WHERE ipAddress="' + ipAddress + '"')
  215. # if isinstance(mss_value, int):
  216. # return mss_value
  217. # else:
  218. # return None
  219. # Aidmar
  220. def get_most_used_mss(self, ipAddress: str):
  221. """
  222. :param ipAddress: The IP address whose used MSS should be determined
  223. :return: The TCP MSS value used by the IP address, or if the IP addresses never specified a MSS,
  224. then None is returned
  225. """
  226. mss_value = self.process_db_query('SELECT mssValue from tcp_mss_dist WHERE ipAddress="' + ipAddress + '" ORDER BY mssCount DESC LIMIT 1')
  227. if isinstance(mss_value, int):
  228. return mss_value
  229. else:
  230. return None
  231. def get_statistics_database(self):
  232. """
  233. :return: A reference to the statistics database object
  234. """
  235. return self.stats_db
  236. def process_db_query(self, query_string_in: str, print_results: bool = False):
  237. """
  238. Executes a string identified previously as a query. This can be a standard SQL SELECT/INSERT query or a named
  239. query.
  240. :param query_string_in: The query to be processed
  241. :param print_results: Indicates whether the results should be printed to terminal
  242. :return: The result of the query
  243. """
  244. return self.stats_db.process_db_query(query_string_in, print_results)
  245. def is_query(self, value: str):
  246. """
  247. Checks whether the given string is a standard SQL query (SELECT, INSERT) or a named query.
  248. :param value: The string to be checked
  249. :return: True if the string is recognized as a query, otherwise False.
  250. """
  251. if not isinstance(value, str):
  252. return False
  253. else:
  254. return (any(x in value.lower().strip() for x in self.stats_db.get_all_named_query_keywords()) or
  255. any(x in value.lower().strip() for x in self.stats_db.get_all_sql_query_keywords()))
  256. def calculate_standard_deviation(self, lst):
  257. """Calculates the standard deviation for a list of numbers."""
  258. num_items = len(lst)
  259. mean = sum(lst) / num_items
  260. differences = [x - mean for x in lst]
  261. sq_differences = [d ** 2 for d in differences]
  262. ssd = sum(sq_differences)
  263. variance = ssd / num_items
  264. sd = sqrt(variance)
  265. #print('The mean of {} is {}.'.format(lst, mean))
  266. #print('The differences are {}.'.format(differences))
  267. #print('The sum of squared differences is {}.'.format(ssd))
  268. #print('The variance is {}.'.format(variance))
  269. print('The standard deviation is {}.'.format(sd))
  270. print('--------------------------')
  271. return sd
  272. def plot_statistics(self, format: str = 'pdf'): #'png'):
  273. """
  274. Plots the statistics associated with the dataset prior attack injection.
  275. :param format: The format to be used to save the statistics diagrams.
  276. """
  277. def plot_ttl(file_ending: str):
  278. plt.gcf().clear()
  279. result = self.stats_db._process_user_defined_query(
  280. "SELECT ttlValue, SUM(ttlCount) FROM ip_ttl GROUP BY ttlValue")
  281. graphx, graphy = [], []
  282. for row in result:
  283. graphx.append(row[0])
  284. graphy.append(row[1])
  285. plt.autoscale(enable=True, axis='both')
  286. plt.title("TTL Distribution")
  287. plt.xlabel('TTL Value')
  288. plt.ylabel('Number of Packets')
  289. width = 0.5
  290. plt.xlim([0, max(graphx)])
  291. plt.grid(True)
  292. plt.bar(graphx, graphy, width, align='center', linewidth=2, color='red', edgecolor='red')
  293. out = self.pcap_filepath.replace('.pcap', '_plot-ttl' + file_ending)
  294. plt.savefig(out,dpi=500)
  295. return out
  296. # Aidmar
  297. def plot_mss(file_ending: str):
  298. plt.gcf().clear()
  299. result = self.stats_db._process_user_defined_query(
  300. "SELECT mssValue, SUM(mssCount) FROM tcp_mss_dist GROUP BY mssValue")
  301. if(result):
  302. graphx, graphy = [], []
  303. for row in result:
  304. graphx.append(row[0])
  305. graphy.append(row[1])
  306. plt.autoscale(enable=True, axis='both')
  307. plt.title("MSS Distribution")
  308. plt.xlabel('MSS Value')
  309. plt.ylabel('Number of Packets')
  310. width = 0.5
  311. plt.xlim([0, max(graphx)])
  312. plt.grid(True)
  313. plt.bar(graphx, graphy, width, align='center', linewidth=2, color='red', edgecolor='red')
  314. out = self.pcap_filepath.replace('.pcap', '_plot-mss' + file_ending)
  315. plt.savefig(out,dpi=500)
  316. return out
  317. else:
  318. print("Error plot MSS: No MSS values found!")
  319. # Aidmar
  320. def plot_win(file_ending: str):
  321. plt.gcf().clear()
  322. result = self.stats_db._process_user_defined_query(
  323. "SELECT winSize, SUM(winCount) FROM tcp_syn_win GROUP BY winSize")
  324. if (result):
  325. graphx, graphy = [], []
  326. for row in result:
  327. graphx.append(row[0])
  328. graphy.append(row[1])
  329. plt.autoscale(enable=True, axis='both')
  330. plt.title("Window Size Distribution")
  331. plt.xlabel('Window Size')
  332. plt.ylabel('Number of Packets')
  333. width = 0.5
  334. plt.xlim([0, max(graphx)])
  335. plt.grid(True)
  336. plt.bar(graphx, graphy, width, align='center', linewidth=2, color='red', edgecolor='red')
  337. out = self.pcap_filepath.replace('.pcap', '_plot-win' + file_ending)
  338. plt.savefig(out,dpi=500)
  339. return out
  340. else:
  341. print("Error plot WinSize: No WinSize values found!")
  342. # Aidmar
  343. def plot_protocol(file_ending: str):
  344. plt.gcf().clear()
  345. result = self.stats_db._process_user_defined_query(
  346. "SELECT protocolName, SUM(protocolCount) FROM ip_protocols GROUP BY protocolName")
  347. if (result):
  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("Protocols Distribution")
  354. plt.xlabel('Protocols')
  355. plt.ylabel('Number of Packets')
  356. width = 0.5
  357. plt.xlim([0, len(graphx)])
  358. plt.grid(True)
  359. # Protocols' names on x-axis
  360. x = range(0,len(graphx))
  361. my_xticks = graphx
  362. plt.xticks(x, my_xticks)
  363. plt.bar(x, graphy, width, align='center', linewidth=2, color='red', edgecolor='red')
  364. out = self.pcap_filepath.replace('.pcap', '_plot-protocol' + file_ending)
  365. plt.savefig(out,dpi=500)
  366. return out
  367. else:
  368. print("Error plot protocol: No protocol values found!")
  369. # Aidmar
  370. def plot_port(file_ending: str):
  371. plt.gcf().clear()
  372. result = self.stats_db._process_user_defined_query(
  373. "SELECT portNumber, SUM(portCount) FROM ip_ports GROUP BY portNumber")
  374. graphx, graphy = [], []
  375. for row in result:
  376. graphx.append(row[0])
  377. graphy.append(row[1])
  378. plt.autoscale(enable=True, axis='both')
  379. plt.title("Ports Distribution")
  380. plt.xlabel('Ports Numbers')
  381. plt.ylabel('Number of Packets')
  382. width = 0.5
  383. plt.xlim([0, max(graphx)])
  384. plt.grid(True)
  385. plt.bar(graphx, graphy, width, align='center', linewidth=2, color='red', edgecolor='red')
  386. out = self.pcap_filepath.replace('.pcap', '_plot-port' + file_ending)
  387. plt.savefig(out,dpi=500)
  388. return out
  389. # Aidmar - This distribution is not drawable for big datasets
  390. def plot_ip_src(file_ending: str):
  391. plt.gcf().clear()
  392. result = self.stats_db._process_user_defined_query(
  393. "SELECT ipAddress, pktsSent FROM ip_statistics")
  394. graphx, graphy = [], []
  395. for row in result:
  396. graphx.append(row[0])
  397. graphy.append(row[1])
  398. plt.autoscale(enable=True, axis='both')
  399. plt.title("Source IP Distribution")
  400. plt.xlabel('Source IP')
  401. plt.ylabel('Number of Packets')
  402. width = 0.5
  403. plt.xlim([0, len(graphx)])
  404. plt.grid(True)
  405. # IPs on x-axis
  406. x = range(0, len(graphx))
  407. my_xticks = graphx
  408. plt.xticks(x, my_xticks, rotation='vertical', fontsize=5)
  409. plt.tight_layout()
  410. # limit the number of xticks
  411. plt.locator_params(axis='x', nbins=20)
  412. plt.bar(x, graphy, width, align='center', linewidth=2, color='red', edgecolor='red')
  413. out = self.pcap_filepath.replace('.pcap', '_plot-ip-src' + file_ending)
  414. plt.savefig(out, dpi=500)
  415. return out
  416. # Aidmar - This distribution is not drawable for big datasets
  417. def plot_ip_dst(file_ending: str):
  418. plt.gcf().clear()
  419. result = self.stats_db._process_user_defined_query(
  420. "SELECT ipAddress, pktsReceived FROM ip_statistics")
  421. graphx, graphy = [], []
  422. for row in result:
  423. graphx.append(row[0])
  424. graphy.append(row[1])
  425. plt.autoscale(enable=True, axis='both')
  426. plt.title("Destination IP Distribution")
  427. plt.xlabel('Destination IP')
  428. plt.ylabel('Number of Packets')
  429. width = 0.5
  430. plt.xlim([0, len(graphx)])
  431. plt.grid(True)
  432. # IPs on x-axis
  433. x = range(0, len(graphx))
  434. my_xticks = graphx
  435. plt.xticks(x, my_xticks, rotation='vertical', fontsize=5)
  436. plt.tight_layout()
  437. # limit the number of xticks
  438. plt.locator_params(axis='x', nbins=20)
  439. plt.bar(x, graphy, width, align='center', linewidth=2, color='red', edgecolor='red')
  440. out = self.pcap_filepath.replace('.pcap', '_plot-ip-dst' + file_ending)
  441. plt.savefig(out, dpi=500)
  442. return out
  443. # Aidmar
  444. def plot_interval_pktCount(file_ending: str):
  445. plt.gcf().clear()
  446. result = self.stats_db._process_user_defined_query(
  447. "SELECT lastPktTimestamp, pktsCount FROM interval_statistics ORDER BY lastPktTimestamp")
  448. graphx, graphy = [], []
  449. for row in result:
  450. graphx.append(row[0])
  451. graphy.append(row[1])
  452. plt.autoscale(enable=True, axis='both')
  453. plt.title("Packet Rate")
  454. plt.xlabel('Timestamp')
  455. plt.ylabel('Number of Packets')
  456. width = 0.5
  457. plt.xlim([0, len(graphx)])
  458. plt.grid(True)
  459. # timestamp on x-axis
  460. x = range(0, len(graphx))
  461. my_xticks = graphx
  462. plt.xticks(x, my_xticks, rotation='vertical', fontsize=5)
  463. plt.tight_layout()
  464. # limit the number of xticks
  465. plt.locator_params(axis='x', nbins=20)
  466. plt.bar(x, graphy, width, align='center', linewidth=2, color='red', edgecolor='red')
  467. out = self.pcap_filepath.replace('.pcap', '_plot-interval-pkt-count' + file_ending)
  468. plt.savefig(out, dpi=500)
  469. return out
  470. # Aidmar
  471. def plot_interval_ip_src_ent(file_ending: str):
  472. plt.gcf().clear()
  473. result = self.stats_db._process_user_defined_query(
  474. "SELECT lastPktTimestamp, ipSrcEntropy FROM interval_statistics ORDER BY lastPktTimestamp")
  475. graphx, graphy = [], []
  476. for row in result:
  477. graphx.append(row[0])
  478. graphy.append(row[1])
  479. plt.autoscale(enable=True, axis='both')
  480. plt.title("Source IP Entropy")
  481. plt.xlabel('Timestamp')
  482. plt.ylabel('Entropy')
  483. width = 0.5
  484. plt.xlim([0, len(graphx)])
  485. plt.grid(True)
  486. # timestamp on x-axis
  487. x = range(0, len(graphx))
  488. my_xticks = graphx
  489. plt.xticks(x, my_xticks, rotation='vertical', fontsize=5)
  490. plt.tight_layout()
  491. # limit the number of xticks
  492. plt.locator_params(axis='x', nbins=20)
  493. plt.bar(x, graphy, width, align='center', linewidth=2, color='red', edgecolor='red')
  494. out = self.pcap_filepath.replace('.pcap', '_plot-interval-ip-src-ent' + file_ending)
  495. plt.savefig(out, dpi=500)
  496. return out
  497. # Aidmar
  498. def plot_interval_ip_dst_ent(file_ending: str):
  499. plt.gcf().clear()
  500. result = self.stats_db._process_user_defined_query(
  501. "SELECT lastPktTimestamp, ipDstEntropy FROM interval_statistics ORDER BY lastPktTimestamp")
  502. graphx, graphy = [], []
  503. for row in result:
  504. graphx.append(row[0])
  505. graphy.append(row[1])
  506. plt.autoscale(enable=True, axis='both')
  507. plt.title("Destination IP Entropy")
  508. plt.xlabel('Timestamp')
  509. plt.ylabel('Entropy')
  510. width = 0.5
  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.bar(x, graphy, width, align='center', linewidth=2, color='red', edgecolor='red')
  521. out = self.pcap_filepath.replace('.pcap', '_plot-interval-ip-dst-ent' + file_ending)
  522. plt.savefig(out, dpi=500)
  523. return out
  524. # Aidmar
  525. def plot_interval_ip_dst_cum_ent(file_ending: str):
  526. plt.gcf().clear()
  527. result = self.stats_db._process_user_defined_query(
  528. "SELECT lastPktTimestamp, ipDstCumEntropy 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("Destination 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-dst-cum-ent' + file_ending)
  548. plt.savefig(out, dpi=500)
  549. return out
  550. # Aidmar
  551. def plot_interval_ip_src_cum_ent(file_ending: str):
  552. plt.gcf().clear()
  553. result = self.stats_db._process_user_defined_query(
  554. "SELECT lastPktTimestamp, ipSrcCumEntropy FROM interval_statistics ORDER BY lastPktTimestamp")
  555. graphx, graphy = [], []
  556. for row in result:
  557. graphx.append(row[0])
  558. graphy.append(row[1])
  559. plt.autoscale(enable=True, axis='both')
  560. plt.title("Source IP Cumulative Entropy")
  561. plt.xlabel('Timestamp')
  562. plt.ylabel('Entropy')
  563. plt.xlim([0, len(graphx)])
  564. plt.grid(True)
  565. # timestamp on x-axis
  566. x = range(0, len(graphx))
  567. my_xticks = graphx
  568. plt.xticks(x, my_xticks, rotation='vertical', fontsize=5)
  569. plt.tight_layout()
  570. # limit the number of xticks
  571. plt.locator_params(axis='x',nbins=20)
  572. plt.plot(x, graphy, 'r')
  573. out = self.pcap_filepath.replace('.pcap', '_plot-interval-ip-src-cum-ent' + file_ending)
  574. plt.savefig(out, dpi=500)
  575. return out
  576. # Aidmar
  577. def plot_interval_new_ip(file_ending: str):
  578. plt.gcf().clear()
  579. result = self.stats_db._process_user_defined_query(
  580. "SELECT lastPktTimestamp, newIPCount FROM interval_statistics ORDER BY lastPktTimestamp")
  581. graphx, graphy = [], []
  582. for row in result:
  583. graphx.append(row[0])
  584. graphy.append(row[1])
  585. plt.autoscale(enable=True, axis='both')
  586. plt.title("IP New Values Distribution")
  587. plt.xlabel('Timestamp')
  588. plt.ylabel('New values count')
  589. plt.xlim([0, len(graphx)])
  590. plt.grid(True)
  591. width = 0.5
  592. # timestamp on x-axis
  593. x = range(0, len(graphx))
  594. my_xticks = graphx
  595. plt.xticks(x, my_xticks, rotation='vertical', fontsize=5)
  596. plt.tight_layout()
  597. # limit the number of xticks
  598. plt.locator_params(axis='x', nbins=20)
  599. plt.bar(x, graphy, width, align='center', linewidth=2, color='red', edgecolor='red')
  600. out = self.pcap_filepath.replace('.pcap', '_plot-interval-new-ip-dist' + file_ending)
  601. plt.savefig(out, dpi=500)
  602. print("IP Standard Deviation:")
  603. self.calculate_standard_deviation(graphy)
  604. return out
  605. # Aidmar
  606. def plot_interval_new_ttl(file_ending: str):
  607. plt.gcf().clear()
  608. result = self.stats_db._process_user_defined_query(
  609. "SELECT lastPktTimestamp, newTTLCount FROM interval_statistics ORDER BY lastPktTimestamp")
  610. if(result):
  611. graphx, graphy = [], []
  612. for row in result:
  613. graphx.append(row[0])
  614. graphy.append(row[1])
  615. plt.autoscale(enable=True, axis='both')
  616. plt.title("TTL New Values Distribution")
  617. plt.xlabel('Timestamp')
  618. plt.ylabel('New values count')
  619. plt.xlim([0, len(graphx)])
  620. plt.grid(True)
  621. width = 0.5
  622. # timestamp on x-axis
  623. x = range(0, len(graphx))
  624. my_xticks = graphx
  625. plt.xticks(x, my_xticks, rotation='vertical', fontsize=5)
  626. plt.tight_layout()
  627. # limit the number of xticks
  628. plt.locator_params(axis='x', nbins=20)
  629. plt.bar(x, graphy, width, align='center', linewidth=2, color='red', edgecolor='red')
  630. out = self.pcap_filepath.replace('.pcap', '_plot-interval-new-ttl-dist' + file_ending)
  631. plt.savefig(out, dpi=500)
  632. print("TTL Standard Deviation:")
  633. self.calculate_standard_deviation(graphy)
  634. return out
  635. else:
  636. print("Error plot TTL: No TTL values found!")
  637. # Aidmar
  638. def plot_interval_new_tos(file_ending: str):
  639. plt.gcf().clear()
  640. result = self.stats_db._process_user_defined_query(
  641. "SELECT lastPktTimestamp, newToSCount FROM interval_statistics ORDER BY lastPktTimestamp")
  642. graphx, graphy = [], []
  643. for row in result:
  644. graphx.append(row[0])
  645. graphy.append(row[1])
  646. plt.autoscale(enable=True, axis='both')
  647. plt.title("ToS New Values Distribution")
  648. plt.xlabel('Timestamp')
  649. plt.ylabel('New values count')
  650. plt.xlim([0, len(graphx)])
  651. plt.grid(True)
  652. width = 0.5
  653. # timestamp on x-axis
  654. x = range(0, len(graphx))
  655. my_xticks = graphx
  656. plt.xticks(x, my_xticks, rotation='vertical', fontsize=5)
  657. plt.tight_layout()
  658. # limit the number of xticks
  659. plt.locator_params(axis='x', nbins=20)
  660. plt.bar(x, graphy, width, align='center', linewidth=2, color='red', edgecolor='red')
  661. out = self.pcap_filepath.replace('.pcap', '_plot-interval-new-tos-dist' + file_ending)
  662. plt.savefig(out, dpi=500)
  663. print("ToS Standard Deviation:")
  664. self.calculate_standard_deviation(graphy)
  665. return out
  666. # Aidmar
  667. def plot_interval_new_win_size(file_ending: str):
  668. plt.gcf().clear()
  669. result = self.stats_db._process_user_defined_query(
  670. "SELECT lastPktTimestamp, newWinSizeCount FROM interval_statistics ORDER BY lastPktTimestamp")
  671. if(result):
  672. graphx, graphy = [], []
  673. for row in result:
  674. graphx.append(row[0])
  675. graphy.append(row[1])
  676. plt.autoscale(enable=True, axis='both')
  677. plt.title("Window Size New Values Distribution")
  678. plt.xlabel('Timestamp')
  679. plt.ylabel('New values count')
  680. plt.xlim([0, len(graphx)])
  681. plt.grid(True)
  682. width = 0.5
  683. # timestamp on x-axis
  684. x = range(0, len(graphx))
  685. my_xticks = graphx
  686. plt.xticks(x, my_xticks, rotation='vertical', fontsize=5)
  687. plt.tight_layout()
  688. # limit the number of xticks
  689. plt.locator_params(axis='x', nbins=20)
  690. plt.bar(x, graphy, width, align='center', linewidth=2, color='red', edgecolor='red')
  691. out = self.pcap_filepath.replace('.pcap', '_plot-interval-new-win-size-dist' + file_ending)
  692. plt.savefig(out, dpi=500)
  693. # Calculate Standart Deviation
  694. print("Window Size Standard Deviation:")
  695. self.calculate_standard_deviation(graphy)
  696. return out
  697. else:
  698. print("Error plot new values WinSize: No WinSize values found!")
  699. # Aidmar
  700. def plot_interval_new_mss(file_ending: str):
  701. plt.gcf().clear()
  702. result = self.stats_db._process_user_defined_query(
  703. "SELECT lastPktTimestamp, newMSSCount FROM interval_statistics ORDER BY lastPktTimestamp")
  704. if(result):
  705. graphx, graphy = [], []
  706. for row in result:
  707. graphx.append(row[0])
  708. graphy.append(row[1])
  709. plt.autoscale(enable=True, axis='both')
  710. plt.title("MSS New Values Distribution")
  711. plt.xlabel('Timestamp')
  712. plt.ylabel('New values count')
  713. plt.xlim([0, len(graphx)])
  714. plt.grid(True)
  715. width = 0.5
  716. # timestamp on x-axis
  717. x = range(0, len(graphx))
  718. my_xticks = graphx
  719. plt.xticks(x, my_xticks, rotation='vertical', fontsize=5)
  720. plt.tight_layout()
  721. # limit the number of xticks
  722. plt.locator_params(axis='x', nbins=20)
  723. plt.bar(x, graphy, width, align='center', linewidth=2, color='red', edgecolor='red')
  724. out = self.pcap_filepath.replace('.pcap', '_plot-interval-new-mss-dist' + file_ending)
  725. plt.savefig(out, dpi=500)
  726. # Calculate Standart Deviation
  727. print("MSS Standard Deviation:")
  728. self.calculate_standard_deviation(graphy)
  729. return out
  730. else:
  731. print("Error plot new values MSS: No MSS values found!")
  732. ttl_out_path = plot_ttl('.' + format)
  733. mss_out_path = plot_mss('.' + format)
  734. win_out_path = plot_win('.' + format)
  735. protocol_out_path = plot_protocol('.' + format)
  736. port_out_path = plot_port('.' + format)
  737. #ip_src_out_path = plot_ip_src('.' + format)
  738. #ip_dst_out_path = plot_ip_dst('.' + format)
  739. plot_interval_pktCount = plot_interval_pktCount('.' + format)
  740. plot_interval_ip_src_ent = plot_interval_ip_src_ent('.' + format)
  741. plot_interval_ip_dst_ent = plot_interval_ip_dst_ent('.' + format)
  742. plot_interval_ip_src_cum_ent = plot_interval_ip_src_cum_ent('.' + format)
  743. plot_interval_ip_dst_cum_ent = plot_interval_ip_dst_cum_ent('.' + format)
  744. plot_interval_new_ip = plot_interval_new_ip('.' + format)
  745. plot_interval_new_ttl = plot_interval_new_ttl('.' + format)
  746. plot_interval_new_tos = plot_interval_new_tos('.' + format)
  747. plot_interval_new_win_size = plot_interval_new_win_size('.' + format)
  748. plot_interval_new_mss = plot_interval_new_mss('.' + format)
  749. #print("Saved distributions plots at: %s, %s, %s, %s, %s, %s, %s, %s %s" %(ttl_out_path,mss_out_path, win_out_path,
  750. #protocol_out_path, port_out_path,ip_src_out_path,ip_dst_out_path, plot_interval_pktCount))
  751. # Aidmar
  752. def calculate_complement_packet_rates(self, pps):
  753. """
  754. Calculates the complement packet rates of the background traffic packet rates per interval.
  755. Then normalize it to maximum boundary, which is the input parameter pps
  756. :return: normalized packet rates for each time interval.
  757. """
  758. result = self.process_db_query(
  759. "SELECT lastPktTimestamp,pktsCount FROM interval_statistics ORDER BY lastPktTimestamp")
  760. # print(result)
  761. bg_interval_pps = []
  762. complement_interval_pps = []
  763. intervalsSum = 0
  764. if result:
  765. # Get the interval in seconds
  766. for i, row in enumerate(result):
  767. if i < len(result) - 1:
  768. intervalsSum += ceil((int(result[i + 1][0]) * 10 ** -6) - (int(row[0]) * 10 ** -6))
  769. interval = intervalsSum / (len(result) - 1)
  770. # Convert timestamp from micro to seconds, convert packet rate "per interval" to "per second"
  771. for row in result:
  772. bg_interval_pps.append((int(row[0]) * 10 ** -6, int(row[1] / interval)))
  773. # Find max PPS
  774. maxPPS = max(bg_interval_pps, key=itemgetter(1))[1]
  775. for row in bg_interval_pps:
  776. complement_interval_pps.append((row[0], int(pps * (maxPPS - row[1]) / maxPPS)))
  777. return complement_interval_pps
  778. """
  779. # Aidmar
  780. # bhattacharyya test
  781. import math
  782. def mean(hist):
  783. mean = 0.0;
  784. for i in hist:
  785. mean += i;
  786. mean /= len(hist);
  787. return mean;
  788. def bhatta(hist1, hist2):
  789. # calculate mean of hist1
  790. h1_ = mean(hist1);
  791. # calculate mean of hist2
  792. h2_ = mean(hist2);
  793. # calculate score
  794. score = 0;
  795. for i in range(len(hist1)):
  796. score += math.sqrt(hist1[i] * hist2[i]);
  797. # print h1_,h2_,score;
  798. score = math.sqrt(1 - (1 / math.sqrt(h1_ * h2_ * len(hist1) * len(hist1))) * score);
  799. return score;
  800. print("\nbhatta distance: " + str(bhatta(graphy, graphy_aftr)))
  801. """