Statistics.py 13 KB

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