Statistics.py 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317
  1. import os
  2. import time
  3. import ID2TLib.libpcapreader as pr
  4. import matplotlib.pyplot as plt
  5. from ID2TLib.PcapFile import PcapFile
  6. from ID2TLib.StatsDatabase import StatsDatabase
  7. class Statistics:
  8. def __init__(self, pcap_file: PcapFile):
  9. """
  10. Creates a new Statistics object.
  11. :param pcap_file: A reference to the PcapFile object
  12. """
  13. # Fields
  14. self.pcap_filepath = pcap_file.pcap_file_path
  15. self.pcap_proc = None
  16. # Create folder for statistics database if required
  17. self.path_db = pcap_file.get_db_path()
  18. path_dir = os.path.dirname(self.path_db)
  19. if not os.path.isdir(path_dir):
  20. os.makedirs(path_dir)
  21. # Class instances
  22. self.stats_db = StatsDatabase(self.path_db)
  23. def load_pcap_statistics(self, flag_write_file: bool, flag_recalculate_stats: bool, flag_print_statistics: bool):
  24. """
  25. Loads the PCAP statistics for the file specified by pcap_filepath. If the database is not existing yet, the
  26. statistics are calculated by the PCAP file processor and saved into the newly created database. Otherwise the
  27. statistics are gathered directly from the existing database.
  28. :param flag_write_file: Indicates whether the statistics should be written addiotionally into a text file (True)
  29. or not (False)
  30. :param flag_recalculate_stats: Indicates whether eventually existing statistics should be recalculated
  31. :param flag_print_statistics: Indicates whether the gathered basic statistics should be printed to the terminal
  32. """
  33. # Load pcap and get loading time
  34. time_start = time.clock()
  35. # Inform user about recalculation of statistics and its reason
  36. if flag_recalculate_stats:
  37. print("Flag -r/--recalculate found. Recalculating statistics.")
  38. # Recalculate statistics if database not exists OR param -r/--recalculate was provided
  39. if (not self.stats_db.get_db_exists()) or flag_recalculate_stats:
  40. self.pcap_proc = pr.pcap_processor(self.pcap_filepath)
  41. time_s = time.time()
  42. self.pcap_proc.collect_statistics()
  43. time_e = time.time()
  44. f = open("/root/perfresults/runtime_stats.txt", "a")
  45. f.write(str(time_e - time_s) + "\n")
  46. f.close()
  47. self.pcap_proc.write_to_database(self.path_db)
  48. outstring_datasource = "by PCAP file processor."
  49. else:
  50. outstring_datasource = "from statistics database."
  51. # Load statistics from database
  52. self.file_info = self.stats_db.get_file_info()
  53. time_end = time.clock()
  54. print("Loaded file statistics in " + str(time_end - time_start)[:4] + " sec " + outstring_datasource)
  55. # Write statistics if param -e/--export provided
  56. if flag_write_file:
  57. self.write_statistics_to_file()
  58. # Print statistics if param -s/--statistics provided
  59. if flag_print_statistics:
  60. self.print_statistics()
  61. def get_file_information(self):
  62. """
  63. Returns a list of tuples, each containing a information of the file.
  64. :return: a list of tuples, each consisting of (description, value, unit), where unit is optional.
  65. """
  66. return [("Pcap file", self.pcap_filepath),
  67. ("#Packets", self.get_packet_count(), "packets"),
  68. ("Capture length", self.get_capture_duration(), "seconds"),
  69. ("Capture start", self.get_pcap_timestamp_start()),
  70. ("Capture end", self.get_pcap_timestamp_end())]
  71. def get_general_file_statistics(self):
  72. """
  73. Returns a list of tuples, each containing a file statistic.
  74. :return: a list of tuples, each consisting of (description, value, unit).
  75. """
  76. return [("Avg. packet rate", self.file_info['avgPacketRate'], "packets/sec"),
  77. ("Avg. packet size", self.file_info['avgPacketSize'], "kbytes"),
  78. ("Avg. packets sent", self.file_info['avgPacketsSentPerHost'], "packets"),
  79. ("Avg. bandwidth in", self.file_info['avgBandwidthIn'], "kbit/s"),
  80. ("Avg. bandwidth out", self.file_info['avgBandwidthOut'], "kbit/s")]
  81. @staticmethod
  82. def write_list(desc_val_unit_list, func, line_ending="\n"):
  83. """
  84. Takes a list of tuples (statistic name, statistic value, unit) as input, generates a string of these three values
  85. and applies the function func on this string.
  86. Before generating the string, it identifies text containing a float number, casts the string to a
  87. float and rounds the value to two decimal digits.
  88. :param desc_val_unit_list: The list of tuples consisting of (description, value, unit)
  89. :param func: The function to be applied to each generated string
  90. :param line_ending: The formatting string to be applied at the end of each string
  91. """
  92. for entry in desc_val_unit_list:
  93. # Convert text containing float into float
  94. (description, value) = entry[0:2]
  95. if isinstance(value, str) and "." in value:
  96. try:
  97. value = float(value)
  98. except ValueError:
  99. pass # do nothing -> value was not a float
  100. # round float
  101. if isinstance(value, float):
  102. value = round(value, 2)
  103. # write into file
  104. if len(entry) == 3:
  105. unit = entry[2]
  106. func(description + ":\t" + str(value) + " " + unit + line_ending)
  107. else:
  108. func(description + ":\t" + str(value) + line_ending)
  109. def print_statistics(self):
  110. """
  111. Prints the basic file statistics to the terminal.
  112. """
  113. print("\nPCAP FILE INFORMATION ------------------------------")
  114. Statistics.write_list(self.get_file_information(), print, "")
  115. print("\nGENERAL FILE STATISTICS ----------------------------")
  116. Statistics.write_list(self.get_general_file_statistics(), print, "")
  117. print("\n")
  118. def write_statistics_to_file(self):
  119. """
  120. Writes the calculated basic statistics into a file.
  121. """
  122. def _write_header(title: str):
  123. """
  124. Writes the section header into the open file.
  125. :param title: The section title
  126. """
  127. target.write("====================== \n")
  128. target.write(title + " \n")
  129. target.write("====================== \n")
  130. target = open(self.pcap_filepath + ".stat", 'w')
  131. target.truncate()
  132. _write_header("PCAP file information")
  133. Statistics.write_list(self.get_file_information(), target.write)
  134. _write_header("General statistics")
  135. Statistics.write_list(self.get_general_file_statistics(), target.write)
  136. target.close()
  137. def get_capture_duration(self):
  138. """
  139. :return: The duration of the capture in seconds
  140. """
  141. return self.file_info['captureDuration']
  142. def get_pcap_timestamp_start(self):
  143. """
  144. :return: The timestamp of the first packet in the PCAP file
  145. """
  146. return self.file_info['timestampFirstPacket']
  147. def get_pcap_timestamp_end(self):
  148. """
  149. :return: The timestamp of the last packet in the PCAP file
  150. """
  151. return self.file_info['timestampLastPacket']
  152. def get_pps_sent(self, ip_address: str):
  153. """
  154. Calculates the sent packets per seconds for a given IP address.
  155. :param ip_address: The IP address whose packets per second should be calculated
  156. :return: The sent packets per seconds for the given IP address
  157. """
  158. packets_sent = self.stats_db.process_db_query("SELECT pktsSent from ip_statistics WHERE ipAddress=?", False,
  159. (ip_address,))
  160. capture_duration = float(self.get_capture_duration())
  161. return int(float(packets_sent) / capture_duration)
  162. def get_pps_received(self, ip_address: str):
  163. """
  164. Calculate the packets per second received for a given IP address.
  165. :param ip_address: The IP address used for the calculation
  166. :return: The number of packets per second received
  167. """
  168. packets_received = self.stats_db.process_db_query("SELECT pktsReceived FROM ip_statistics WHERE ipAddress=?",
  169. False,
  170. (ip_address,))
  171. capture_duration = float(self.get_capture_duration())
  172. return int(float(packets_received) / capture_duration)
  173. def get_packet_count(self):
  174. """
  175. :return: The number of packets in the loaded PCAP file
  176. """
  177. return self.file_info['packetCount']
  178. def get_most_used_ip_address(self):
  179. """
  180. :return: The IP address/addresses with the highest sum of packets sent and received
  181. """
  182. return self.process_db_query("most_used(ipAddress)")
  183. def get_ttl_distribution(self, ipAddress: str):
  184. result = self.process_db_query('SELECT ttlValue, ttlCount from ip_ttl WHERE ipAddress="' + ipAddress + '"')
  185. result_dict = {key: value for (key, value) in result}
  186. return result_dict
  187. def get_random_ip_address(self, count: int = 1):
  188. """
  189. :param count: The number of IP addreses to return
  190. :return: A randomly chosen IP address from the dataset or iff param count is greater than one, a list of randomly
  191. chosen IP addresses
  192. """
  193. if count == 1:
  194. return self.process_db_query("random(all(ipAddress))")
  195. else:
  196. ip_address_list = []
  197. for i in range(0, count):
  198. ip_address_list.append(self.process_db_query("random(all(ipAddress))"))
  199. return ip_address_list
  200. def get_mac_address(self, ipAddress: str):
  201. """
  202. :return: The MAC address used in the dataset for the given IP address.
  203. """
  204. return self.process_db_query('macAddress(ipAddress=' + ipAddress + ")")
  205. def get_mss(self, ipAddress: str):
  206. """
  207. :param ipAddress: The IP address whose used MSS should be determined
  208. :return: The TCP MSS value used by the IP address, or if the IP addresses never specified a MSS,
  209. then None is returned
  210. """
  211. mss_value = self.process_db_query('SELECT mss from tcp_mss WHERE ipAddress="' + ipAddress + '"')
  212. if isinstance(mss_value, int):
  213. return mss_value
  214. else:
  215. return None
  216. def get_statistics_database(self):
  217. """
  218. :return: A reference to the statistics database object
  219. """
  220. return self.stats_db
  221. def process_db_query(self, query_string_in: str, print_results: bool = False):
  222. """
  223. Executes a string identified previously as a query. This can be a standard SQL SELECT/INSERT query or a named
  224. query.
  225. :param query_string_in: The query to be processed
  226. :param print_results: Indicates whether the results should be printed to terminal
  227. :return: The result of the query
  228. """
  229. return self.stats_db.process_db_query(query_string_in, print_results)
  230. def is_query(self, value: str):
  231. """
  232. Checks whether the given string is a standard SQL query (SELECT, INSERT) or a named query.
  233. :param value: The string to be checked
  234. :return: True if the string is recognized as a query, otherwise False.
  235. """
  236. if not isinstance(value, str):
  237. return False
  238. else:
  239. return (any(x in value.lower().strip() for x in self.stats_db.get_all_named_query_keywords()) or
  240. any(x in value.lower().strip() for x in self.stats_db.get_all_sql_query_keywords()))
  241. def plot_statistics(self, format: str = 'png'):
  242. """
  243. Plots the statistics associated with the dataset prior attack injection.
  244. :param format: The format to be used to save the statistics diagrams.
  245. """
  246. def plot_ttl(file_ending: str):
  247. result = self.stats_db._process_user_defined_query(
  248. "SELECT ttlValue, SUM(ttlCount) FROM ip_ttl GROUP BY ttlValue")
  249. graphx, graphy = [], []
  250. for row in result:
  251. graphx.append(row[0])
  252. graphy.append(row[1])
  253. plt.autoscale(enable=True, axis='both')
  254. plt.title("TTL Distribution")
  255. plt.xlabel('TTL Value')
  256. plt.ylabel('Number of Packets')
  257. width = 0.5
  258. plt.xlim([0, max(graphx)])
  259. plt.grid(True)
  260. plt.bar(graphx, graphy, width, align='center', linewidth=2, color='red', edgecolor='red')
  261. out = self.pcap_filepath.replace('.pcap', '_plot-ttl' + file_ending)
  262. plt.savefig(out)
  263. return out
  264. out_path = plot_ttl('.' + format)
  265. print("Saved TTL distribution plot at: ", out_path)