Statistics.py 46 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013
  1. import os
  2. import random
  3. import time
  4. from math import sqrt, ceil, log
  5. from operator import itemgetter
  6. # TODO: double check this import
  7. # does it complain because libpcapreader is not a .py?
  8. import ID2TLib.libpcapreader as pr
  9. import matplotlib
  10. import Core.StatsDatabase as statsDB
  11. import ID2TLib.PcapFile as PcapFile
  12. import ID2TLib.Utility as Util
  13. matplotlib.use('Agg', force=True)
  14. import matplotlib.pyplot as plt
  15. class Statistics:
  16. def __init__(self, pcap_file: PcapFile.PcapFile):
  17. """
  18. Creates a new Statistics object.
  19. :param pcap_file: A reference to the PcapFile object
  20. """
  21. # Fields
  22. self.pcap_filepath = pcap_file.pcap_file_path
  23. self.pcap_proc = None
  24. self.do_extra_tests = False
  25. self.file_info = None
  26. # Create folder for statistics database if required
  27. self.path_db = pcap_file.get_db_path()
  28. path_dir = os.path.dirname(self.path_db)
  29. if not os.path.isdir(path_dir):
  30. os.makedirs(path_dir)
  31. # Class instances
  32. self.stats_db = statsDB.StatsDatabase(self.path_db)
  33. def load_pcap_statistics(self, flag_write_file: bool, flag_recalculate_stats: bool, flag_print_statistics: bool):
  34. """
  35. Loads the PCAP statistics for the file specified by pcap_filepath. If the database is not existing yet, the
  36. statistics are calculated by the PCAP file processor and saved into the newly created database. Otherwise the
  37. statistics are gathered directly from the existing database.
  38. :param flag_write_file: Indicates whether the statistics should be written addiotionally into a text file (True)
  39. or not (False)
  40. :param flag_recalculate_stats: Indicates whether eventually existing statistics should be recalculated
  41. :param flag_print_statistics: Indicates whether the gathered basic statistics should be printed to the terminal
  42. """
  43. # Load pcap and get loading time
  44. time_start = time.clock()
  45. # Inform user about recalculation of statistics and its reason
  46. if flag_recalculate_stats:
  47. print("Flag -r/--recalculate found. Recalculating statistics.")
  48. # Recalculate statistics if database does not exist OR param -r/--recalculate is provided
  49. if (not self.stats_db.get_db_exists()) or flag_recalculate_stats or self.stats_db.get_db_outdated():
  50. self.pcap_proc = pr.pcap_processor(self.pcap_filepath, str(self.do_extra_tests))
  51. self.pcap_proc.collect_statistics()
  52. self.pcap_proc.write_to_database(self.path_db)
  53. outstring_datasource = "by PCAP file processor."
  54. else:
  55. outstring_datasource = "from statistics database."
  56. # Load statistics from database
  57. self.file_info = self.stats_db.get_file_info()
  58. time_end = time.clock()
  59. print("Loaded file statistics in " + str(time_end - time_start)[:4] + " sec " + outstring_datasource)
  60. # Write statistics if param -e/--export provided
  61. if flag_write_file:
  62. self.write_statistics_to_file()
  63. # Print statistics if param -s/--statistics provided
  64. if flag_print_statistics:
  65. self.print_statistics()
  66. def get_file_information(self):
  67. """
  68. Returns a list of tuples, each containing a information of the file.
  69. :return: a list of tuples, each consisting of (description, value, unit), where unit is optional.
  70. """
  71. return [("Pcap file", self.pcap_filepath),
  72. ("Packets", self.get_packet_count(), "packets"),
  73. ("Capture length", self.get_capture_duration(), "seconds"),
  74. ("Capture start", self.get_pcap_timestamp_start()),
  75. ("Capture end", self.get_pcap_timestamp_end())]
  76. def get_general_file_statistics(self):
  77. """
  78. Returns a list of tuples, each containing a file statistic.
  79. :return: a list of tuples, each consisting of (description, value, unit).
  80. """
  81. return [("Avg. packet rate", self.file_info['avgPacketRate'], "packets/sec"),
  82. ("Avg. packet size", self.file_info['avgPacketSize'], "kbytes"),
  83. ("Avg. packets sent", self.file_info['avgPacketsSentPerHost'], "packets"),
  84. ("Avg. bandwidth in", self.file_info['avgBandwidthIn'], "kbit/s"),
  85. ("Avg. bandwidth out", self.file_info['avgBandwidthOut'], "kbit/s")]
  86. @staticmethod
  87. def write_list(desc_val_unit_list, func, line_ending="\n"):
  88. """
  89. Takes a list of tuples (statistic name, statistic value, unit) as input, generates a string of these three
  90. values and applies the function func on this string.
  91. Before generating the string, it identifies text containing a float number, casts the string to a
  92. float and rounds the value to two decimal digits.
  93. :param desc_val_unit_list: The list of tuples consisting of (description, value, unit)
  94. :param func: The function to be applied to each generated string
  95. :param line_ending: The formatting string to be applied at the end of each string
  96. """
  97. for entry in desc_val_unit_list:
  98. # Convert text containing float into float
  99. (description, value) = entry[0:2]
  100. if isinstance(value, str) and "." in value:
  101. try:
  102. value = float(value)
  103. except ValueError:
  104. pass # do nothing -> value was not a float
  105. # round float
  106. if isinstance(value, float):
  107. value = round(value, 4)
  108. # write into file
  109. if len(entry) == 3:
  110. unit = entry[2]
  111. func(description + ":\t" + str(value) + " " + unit + line_ending)
  112. else:
  113. func(description + ":\t" + str(value) + line_ending)
  114. def print_statistics(self):
  115. """
  116. Prints the basic file statistics to the terminal.
  117. """
  118. print("\nPCAP FILE INFORMATION ------------------------------")
  119. Statistics.write_list(self.get_file_information(), print, "")
  120. print("\nGENERAL FILE STATISTICS ----------------------------")
  121. Statistics.write_list(self.get_general_file_statistics(), print, "")
  122. print("\n")
  123. @staticmethod
  124. def calculate_entropy(frequency: list, normalized: bool = False):
  125. """
  126. Calculates entropy and normalized entropy of list of elements that have specific frequency
  127. :param frequency: The frequency of the elements.
  128. :param normalized: Calculate normalized entropy
  129. :return: entropy or (entropy, normalized entropy)
  130. """
  131. entropy, normalized_ent, n = 0, 0, 0
  132. sum_freq = sum(frequency)
  133. for i, x in enumerate(frequency):
  134. p_x = float(frequency[i] / sum_freq)
  135. if p_x > 0:
  136. n += 1
  137. entropy += - p_x * log(p_x, 2)
  138. if normalized:
  139. if log(n) > 0:
  140. normalized_ent = entropy / log(n, 2)
  141. return entropy, normalized_ent
  142. else:
  143. return entropy
  144. def calculate_complement_packet_rates(self, pps):
  145. """
  146. Calculates the complement packet rates of the background traffic packet rates for each interval.
  147. Then normalize it to maximum boundary, which is the input parameter pps
  148. :return: normalized packet rates for each time interval.
  149. """
  150. result = self.process_db_query(
  151. "SELECT lastPktTimestamp,pktsCount FROM interval_statistics ORDER BY lastPktTimestamp")
  152. # print(result)
  153. bg_interval_pps = []
  154. complement_interval_pps = []
  155. intervals_sum = 0
  156. if result:
  157. # Get the interval in seconds
  158. for i, row in enumerate(result):
  159. if i < len(result) - 1:
  160. intervals_sum += ceil((int(result[i + 1][0]) * 10 ** -6) - (int(row[0]) * 10 ** -6))
  161. interval = intervals_sum / (len(result) - 1)
  162. # Convert timestamp from micro to seconds, convert packet rate "per interval" to "per second"
  163. for row in result:
  164. bg_interval_pps.append((int(row[0]) * 10 ** -6, int(row[1] / interval)))
  165. # Find max PPS
  166. max_pps = max(bg_interval_pps, key=itemgetter(1))[1]
  167. for row in bg_interval_pps:
  168. complement_interval_pps.append((row[0], int(pps * (max_pps - row[1]) / max_pps)))
  169. return complement_interval_pps
  170. def get_tests_statistics(self):
  171. """
  172. Writes the calculated basic defects tests statistics into a file.
  173. """
  174. # self.stats_db.process_user_defined_query output is list of tuples, thus, we ned [0][0] to access data
  175. def count_frequncy(values_list):
  176. values, freq_output = [], []
  177. for x in values_list:
  178. if x in values:
  179. freq_output[values.index(x)] += 1
  180. else:
  181. values.append(x)
  182. freq_output.append(1)
  183. return values, freq_output
  184. # Payload Tests
  185. sum_payload_count = self.stats_db.process_user_defined_query("SELECT sum(payloadCount) FROM "
  186. "interval_statistics")
  187. pkt_count = self.stats_db.process_user_defined_query("SELECT packetCount FROM file_statistics")
  188. if sum_payload_count and pkt_count:
  189. payload_ratio = 0
  190. if pkt_count[0][0] != 0:
  191. payload_ratio = float(sum_payload_count[0][0] / pkt_count[0][0] * 100)
  192. else:
  193. payload_ratio = -1
  194. # TCP checksum Tests
  195. incorrect_checksum_count = self.stats_db.process_user_defined_query(
  196. "SELECT sum(incorrectTCPChecksumCount) FROM interval_statistics")
  197. correct_checksum_count = self.stats_db.process_user_defined_query(
  198. "SELECT avg(correctTCPChecksumCount) FROM interval_statistics")
  199. if incorrect_checksum_count and correct_checksum_count:
  200. incorrect_checksum_ratio = 0
  201. if (incorrect_checksum_count[0][0] + correct_checksum_count[0][0]) != 0:
  202. incorrect_checksum_ratio = float(incorrect_checksum_count[0][0] /
  203. (incorrect_checksum_count[0][0] + correct_checksum_count[0][0]) * 100)
  204. else:
  205. incorrect_checksum_ratio = -1
  206. # IP Src & Dst Tests
  207. result = self.stats_db.process_user_defined_query("SELECT ipAddress,pktsSent,pktsReceived FROM ip_statistics")
  208. data, src_frequency, dst_frequency = [], [], []
  209. if result:
  210. for row in result:
  211. src_frequency.append(row[1])
  212. dst_frequency.append(row[2])
  213. ip_src_entropy, ip_src_norm_entropy = self.calculate_entropy(src_frequency, True)
  214. ip_dst_entropy, ip_dst_norm_entropy = self.calculate_entropy(dst_frequency, True)
  215. new_ip_count = self.stats_db.process_user_defined_query("SELECT newIPCount FROM interval_statistics")
  216. ip_novels_per_interval, ip_novels_per_interval_frequency = count_frequncy(new_ip_count)
  217. ip_novelty_dist_entropy = self.calculate_entropy(ip_novels_per_interval_frequency)
  218. # Ports Tests
  219. port0_count = self.stats_db.process_user_defined_query(
  220. "SELECT SUM(portCount) FROM ip_ports WHERE portNumber = 0")
  221. if not port0_count[0][0]:
  222. port0_count = 0
  223. else:
  224. port0_count = port0_count[0][0]
  225. # FIXME: could be extended
  226. reserved_port_count = self.stats_db.process_user_defined_query(
  227. "SELECT SUM(portCount) FROM ip_ports WHERE portNumber IN (100,114,1023,1024,49151,49152,65535)")
  228. if not reserved_port_count[0][0]:
  229. reserved_port_count = 0
  230. else:
  231. reserved_port_count = reserved_port_count[0][0]
  232. # TTL Tests
  233. result = self.stats_db.process_user_defined_query(
  234. "SELECT ttlValue,SUM(ttlCount) FROM ip_ttl GROUP BY ttlValue")
  235. data, frequency = [], []
  236. for row in result:
  237. frequency.append(row[1])
  238. ttl_entropy, ttl_norm_entropy = self.calculate_entropy(frequency, True)
  239. new_ttl_count = self.stats_db.process_user_defined_query("SELECT newTTLCount FROM interval_statistics")
  240. ttl_novels_per_interval, ttl_novels_per_interval_frequency = count_frequncy(new_ttl_count)
  241. ttl_novelty_dist_entropy = self.calculate_entropy(ttl_novels_per_interval_frequency)
  242. # Window Size Tests
  243. result = self.stats_db.process_user_defined_query("SELECT winSize,SUM(winCount) FROM tcp_win GROUP BY winSize")
  244. data, frequency = [], []
  245. for row in result:
  246. frequency.append(row[1])
  247. win_entropy, win_norm_entropy = self.calculate_entropy(frequency, True)
  248. new_win_size_count = self.stats_db.process_user_defined_query("SELECT newWinSizeCount FROM interval_statistics")
  249. win_novels_per_interval, win_novels_per_interval_frequency = count_frequncy(new_win_size_count)
  250. win_novelty_dist_entropy = self.calculate_entropy(win_novels_per_interval_frequency)
  251. # ToS Tests
  252. result = self.stats_db.process_user_defined_query(
  253. "SELECT tosValue,SUM(tosCount) FROM ip_tos GROUP BY tosValue")
  254. data, frequency = [], []
  255. for row in result:
  256. frequency.append(row[1])
  257. tos_entropy, tos_norm_entropy = self.calculate_entropy(frequency, True)
  258. new_tos_count = self.stats_db.process_user_defined_query("SELECT newToSCount FROM interval_statistics")
  259. tos_novels_per_interval, tos_novels_per_interval_frequency = count_frequncy(new_tos_count)
  260. tos_novelty_dist_entropy = self.calculate_entropy(tos_novels_per_interval_frequency)
  261. # MSS Tests
  262. result = self.stats_db.process_user_defined_query(
  263. "SELECT mssValue,SUM(mssCount) FROM tcp_mss GROUP BY mssValue")
  264. data, frequency = [], []
  265. for row in result:
  266. frequency.append(row[1])
  267. mss_entropy, mss_norm_entropy = self.calculate_entropy(frequency, True)
  268. new_mss_count = self.stats_db.process_user_defined_query("SELECT newMSSCount FROM interval_statistics")
  269. mss_novels_per_interval, mss_novels_per_interval_frequency = count_frequncy(new_mss_count)
  270. mss_novelty_dist_entropy = self.calculate_entropy(mss_novels_per_interval_frequency)
  271. result = self.stats_db.process_user_defined_query("SELECT SUM(mssCount) FROM tcp_mss WHERE mssValue > 1460")
  272. # The most used MSS < 1460. Calculate the ratio of the values bigger that 1460.
  273. if not result[0][0]:
  274. result = 0
  275. else:
  276. result = result[0][0]
  277. big_mss = (result / sum(frequency)) * 100
  278. output = []
  279. if self.do_extra_tests:
  280. output = [("Payload ratio", payload_ratio, "%"),
  281. ("Incorrect TCP checksum ratio", incorrect_checksum_ratio, "%")]
  282. output = output + [("# IP addresses", sum([x[0] for x in new_ip_count]), ""),
  283. ("IP Src Entropy", ip_src_entropy, ""),
  284. ("IP Src Normalized Entropy", ip_src_norm_entropy, ""),
  285. ("IP Dst Entropy", ip_dst_entropy, ""),
  286. ("IP Dst Normalized Entropy", ip_dst_norm_entropy, ""),
  287. ("IP Novelty Distribution Entropy", ip_novelty_dist_entropy, ""),
  288. ("# TTL values", sum([x[0] for x in new_ttl_count]), ""),
  289. ("TTL Entropy", ttl_entropy, ""),
  290. ("TTL Normalized Entropy", ttl_norm_entropy, ""),
  291. ("TTL Novelty Distribution Entropy", ttl_novelty_dist_entropy, ""),
  292. ("# WinSize values", sum([x[0] for x in new_win_size_count]), ""),
  293. ("WinSize Entropy", win_entropy, ""),
  294. ("WinSize Normalized Entropy", win_norm_entropy, ""),
  295. ("WinSize Novelty Distribution Entropy", win_novelty_dist_entropy, ""),
  296. ("# ToS values", sum([x[0] for x in new_tos_count]), ""),
  297. ("ToS Entropy", tos_entropy, ""),
  298. ("ToS Normalized Entropy", tos_norm_entropy, ""),
  299. ("ToS Novelty Distribution Entropy", tos_novelty_dist_entropy, ""),
  300. ("# MSS values", sum([x[0] for x in new_mss_count]), ""),
  301. ("MSS Entropy", mss_entropy, ""),
  302. ("MSS Normalized Entropy", mss_norm_entropy, ""),
  303. ("MSS Novelty Distribution Entropy", mss_novelty_dist_entropy, ""),
  304. ("======================", "", "")]
  305. # Reasoning the statistics values
  306. if self.do_extra_tests:
  307. if payload_ratio > 80:
  308. output.append(("WARNING: Too high payload ratio", payload_ratio, "%."))
  309. if payload_ratio < 30:
  310. output.append(("WARNING: Too low payload ratio", payload_ratio, "% (Injecting attacks that are carried "
  311. "out in the packet payloads is not "
  312. "recommmanded)."))
  313. if incorrect_checksum_ratio > 5:
  314. output.append(("WARNING: High incorrect TCP checksum ratio", incorrect_checksum_ratio, "%."))
  315. if ip_src_norm_entropy > 0.65:
  316. output.append(("WARNING: High IP source normalized entropy", ip_src_norm_entropy, "."))
  317. if ip_src_norm_entropy < 0.2:
  318. output.append(("WARNING: Low IP source normalized entropy", ip_src_norm_entropy, "."))
  319. if ip_dst_norm_entropy > 0.65:
  320. output.append(("WARNING: High IP destination normalized entropy", ip_dst_norm_entropy, "."))
  321. if ip_dst_norm_entropy < 0.2:
  322. output.append(("WARNING: Low IP destination normalized entropy", ip_dst_norm_entropy, "."))
  323. if ttl_norm_entropy > 0.65:
  324. output.append(("WARNING: High TTL normalized entropy", ttl_norm_entropy, "."))
  325. if ttl_norm_entropy < 0.2:
  326. output.append(("WARNING: Low TTL normalized entropy", ttl_norm_entropy, "."))
  327. if ttl_novelty_dist_entropy < 1:
  328. output.append(("WARNING: Too low TTL novelty distribution entropy", ttl_novelty_dist_entropy,
  329. "(The distribution of the novel TTL values is suspicious)."))
  330. if win_norm_entropy > 0.6:
  331. output.append(("WARNING: High Window Size normalized entropy", win_norm_entropy, "."))
  332. if win_norm_entropy < 0.1:
  333. output.append(("WARNING: Low Window Size normalized entropy", win_norm_entropy, "."))
  334. if win_novelty_dist_entropy < 4:
  335. output.append(("WARNING: Low Window Size novelty distribution entropy", win_novelty_dist_entropy,
  336. "(The distribution of the novel Window Size values is suspicious)."))
  337. if tos_norm_entropy > 0.4:
  338. output.append(("WARNING: High ToS normalized entropy", tos_norm_entropy, "."))
  339. if tos_norm_entropy < 0.1:
  340. output.append(("WARNING: Low ToS normalized entropy", tos_norm_entropy, "."))
  341. if tos_novelty_dist_entropy < 0.5:
  342. output.append(("WARNING: Low ToS novelty distribution entropy", tos_novelty_dist_entropy,
  343. "(The distribution of the novel ToS values is suspicious)."))
  344. if mss_norm_entropy > 0.4:
  345. output.append(("WARNING: High MSS normalized entropy", mss_norm_entropy, "."))
  346. if mss_norm_entropy < 0.1:
  347. output.append(("WARNING: Low MSS normalized entropy", mss_norm_entropy, "."))
  348. if mss_novelty_dist_entropy < 0.5:
  349. output.append(("WARNING: Low MSS novelty distribution entropy", mss_novelty_dist_entropy,
  350. "(The distribution of the novel MSS values is suspicious)."))
  351. if big_mss > 50:
  352. output.append(("WARNING: High ratio of MSS > 1460", big_mss, "% (High fragmentation rate in Ethernet)."))
  353. if port0_count > 0:
  354. output.append(("WARNING: Port number 0 is used in ", port0_count, "packets (awkward-looking port)."))
  355. if reserved_port_count > 0:
  356. output.append(("WARNING: Reserved port numbers are used in ", reserved_port_count,
  357. "packets (uncommonly-used ports)."))
  358. return output
  359. def write_statistics_to_file(self):
  360. """
  361. Writes the calculated basic statistics into a file.
  362. """
  363. def _write_header(title: str):
  364. """
  365. Writes the section header into the open file.
  366. :param title: The section title
  367. """
  368. target.write("====================== \n")
  369. target.write(title + " \n")
  370. target.write("====================== \n")
  371. target = open(self.pcap_filepath + ".stat", 'w')
  372. target.truncate()
  373. _write_header("PCAP file information")
  374. Statistics.write_list(self.get_file_information(), target.write)
  375. _write_header("General statistics")
  376. Statistics.write_list(self.get_general_file_statistics(), target.write)
  377. _write_header("Tests statistics")
  378. Statistics.write_list(self.get_tests_statistics(), target.write)
  379. target.close()
  380. def get_capture_duration(self):
  381. """
  382. :return: The duration of the capture in seconds
  383. """
  384. return self.file_info['captureDuration']
  385. def get_pcap_timestamp_start(self):
  386. """
  387. :return: The timestamp of the first packet in the PCAP file
  388. """
  389. return self.file_info['timestampFirstPacket']
  390. def get_pcap_timestamp_end(self):
  391. """
  392. :return: The timestamp of the last packet in the PCAP file
  393. """
  394. return self.file_info['timestampLastPacket']
  395. def get_pps_sent(self, ip_address: str):
  396. """
  397. Calculates the sent packets per seconds for a given IP address.
  398. :param ip_address: The IP address whose packets per second should be calculated
  399. :return: The sent packets per seconds for the given IP address
  400. """
  401. packets_sent = self.stats_db.process_db_query("SELECT pktsSent from ip_statistics WHERE ipAddress=?", False,
  402. (ip_address,))
  403. capture_duration = float(self.get_capture_duration())
  404. return int(float(packets_sent) / capture_duration)
  405. def get_pps_received(self, ip_address: str):
  406. """
  407. Calculate the packets per second received for a given IP address.
  408. :param ip_address: The IP address used for the calculation
  409. :return: The number of packets per second received
  410. """
  411. packets_received = self.stats_db.process_db_query("SELECT pktsReceived FROM ip_statistics WHERE ipAddress=?",
  412. False,
  413. (ip_address,))
  414. capture_duration = float(self.get_capture_duration())
  415. return int(float(packets_received) / capture_duration)
  416. def get_packet_count(self):
  417. """
  418. :return: The number of packets in the loaded PCAP file
  419. """
  420. return self.file_info['packetCount']
  421. def get_most_used_ip_address(self):
  422. """
  423. :return: The IP address/addresses with the highest sum of packets sent and received
  424. """
  425. return Util.handle_most_used_outputs(self.process_db_query("most_used(ipAddress)"))
  426. def get_ttl_distribution(self, ip_address: str):
  427. result = self.process_db_query('SELECT ttlValue, ttlCount from ip_ttl WHERE ipAddress="' + ip_address + '"')
  428. result_dict = {key: value for (key, value) in result}
  429. return result_dict
  430. def get_mss_distribution(self, ip_address: str):
  431. result = self.process_db_query('SELECT mssValue, mssCount from tcp_mss WHERE ipAddress="' + ip_address + '"')
  432. result_dict = {key: value for (key, value) in result}
  433. return result_dict
  434. def get_win_distribution(self, ip_address: str):
  435. result = self.process_db_query('SELECT winSize, winCount from tcp_win WHERE ipAddress="' + ip_address + '"')
  436. result_dict = {key: value for (key, value) in result}
  437. return result_dict
  438. def get_tos_distribution(self, ip_address: str):
  439. result = self.process_db_query('SELECT tosValue, tosCount from ip_tos WHERE ipAddress="' + ip_address + '"')
  440. result_dict = {key: value for (key, value) in result}
  441. return result_dict
  442. def get_ip_address_count(self):
  443. return self.process_db_query("SELECT COUNT(*) FROM ip_statistics")
  444. def get_ip_addresses(self):
  445. return self.process_db_query("SELECT ipAddress FROM ip_statistics")
  446. def get_random_ip_address(self, count: int = 1):
  447. """
  448. :param count: The number of IP addreses to return
  449. :return: A randomly chosen IP address from the dataset or iff param count is greater than one, a list of
  450. randomly chosen IP addresses
  451. """
  452. ip_address_list = self.process_db_query("all(ipAddress)")
  453. if count == 1:
  454. return random.choice(ip_address_list)
  455. else:
  456. result_list = []
  457. for i in range(0, count):
  458. random_ip = random.choice(ip_address_list)
  459. result_list.append(random_ip)
  460. ip_address_list.remove(random_ip)
  461. return result_list
  462. def get_ip_address_from_mac(self, mac_address: str):
  463. """
  464. :param mac_address: the MAC address of which the IP shall be returned, if existing in DB
  465. :return: the IP address used in the dataset by a given MAC address
  466. """
  467. return self.process_db_query('ipAddress(macAddress=' + mac_address + ")")
  468. def get_mac_address(self, ip_address: str):
  469. """
  470. :return: The MAC address used in the dataset for the given IP address.
  471. """
  472. return self.process_db_query('macAddress(ipAddress=' + ip_address + ")")
  473. def get_most_used_mss(self, ip_address: str):
  474. """
  475. :param ip_address: The IP address whose used MSS should be determined
  476. :return: The TCP MSS value used by the IP address, or if the IP addresses never specified a MSS,
  477. then None is returned
  478. """
  479. mss_value = self.process_db_query('SELECT mssValue from tcp_mss WHERE ipAddress="' + ip_address +
  480. '" AND mssCount == (SELECT MAX(mssCount) from tcp_mss WHERE ipAddress="'
  481. + ip_address + '")')
  482. if isinstance(mss_value, int):
  483. return mss_value
  484. elif isinstance(mss_value, list):
  485. if len(mss_value) == 0:
  486. return None
  487. else:
  488. mss_value.sort()
  489. return mss_value[0]
  490. else:
  491. return None
  492. def get_most_used_ttl(self, ip_address: str):
  493. """
  494. :param ip_address: The IP address whose used TTL should be determined
  495. :return: The TTL value used by the IP address, or if the IP addresses never specified a TTL,
  496. then None is returned
  497. """
  498. ttl_value = self.process_db_query('SELECT ttlValue from ip_ttl WHERE ipAddress="' + ip_address +
  499. '" AND ttlCount == (SELECT MAX(ttlCount) from ip_ttl WHERE ipAddress="'
  500. + ip_address + '")')
  501. if isinstance(ttl_value, int):
  502. return ttl_value
  503. elif isinstance(ttl_value, list):
  504. if len(ttl_value) == 0:
  505. return None
  506. else:
  507. ttl_value.sort()
  508. return ttl_value[0]
  509. else:
  510. return None
  511. def get_rnd_win_size(self, pkts_num):
  512. """
  513. :param pkts_num: maximum number of window sizes, that should be returned
  514. :return: A list of randomly chosen window sizes with given length.
  515. """
  516. sql_return = self.process_db_query("SELECT DISTINCT winSize FROM tcp_win ORDER BY winsize ASC;")
  517. if not isinstance(sql_return, list):
  518. return [sql_return]
  519. result = []
  520. for i in range(0, min(pkts_num, len(sql_return))):
  521. result.append(random.choice(sql_return))
  522. sql_return.remove(result[i])
  523. return result
  524. def get_statistics_database(self):
  525. """
  526. :return: A reference to the statistics database object
  527. """
  528. return self.stats_db
  529. def process_db_query(self, query_string_in: str, print_results: bool = False):
  530. """
  531. Executes a string identified previously as a query. This can be a standard SQL SELECT/INSERT query or a named
  532. query.
  533. :param query_string_in: The query to be processed
  534. :param print_results: Indicates whether the results should be printed to terminal
  535. :return: The result of the query
  536. """
  537. return self.stats_db.process_db_query(query_string_in, print_results)
  538. def is_query(self, value: str):
  539. """
  540. Checks whether the given string is a standard SQL query (SELECT, INSERT) or a named query.
  541. :param value: The string to be checked
  542. :return: True if the string is recognized as a query, otherwise False.
  543. """
  544. if not isinstance(value, str):
  545. return False
  546. else:
  547. return (any(x in value.lower().strip() for x in self.stats_db.get_all_named_query_keywords()) or
  548. any(x in value.lower().strip() for x in self.stats_db.get_all_sql_query_keywords()))
  549. @staticmethod
  550. def calculate_standard_deviation(lst):
  551. """
  552. Calculates the standard deviation of a list of numbers.
  553. :param lst: The list of numbers to calculate its SD.
  554. """
  555. num_items = len(lst)
  556. mean = sum(lst) / num_items
  557. differences = [x - mean for x in lst]
  558. sq_differences = [d ** 2 for d in differences]
  559. ssd = sum(sq_differences)
  560. variance = ssd / num_items
  561. sd = sqrt(variance)
  562. return sd
  563. def plot_statistics(self, entropy: int, file_format: str = 'pdf'): # 'png'
  564. """
  565. Plots the statistics associated with the dataset.
  566. :param entropy: the statistics entropy
  567. :param file_format: The format to be used to save the statistics diagrams.
  568. """
  569. def plot_distribution(query_output, title, x_label, y_label, file_ending: str):
  570. plt.gcf().clear()
  571. graphx, graphy = [], []
  572. for row in query_output:
  573. graphx.append(row[0])
  574. graphy.append(row[1])
  575. plt.autoscale(enable=True, axis='both')
  576. plt.title(title)
  577. plt.xlabel(x_label)
  578. plt.ylabel(y_label)
  579. width = 0.1
  580. plt.xlim([0, (max(graphx) * 1.1)])
  581. plt.grid(True)
  582. plt.bar(graphx, graphy, width, align='center', linewidth=1, color='red', edgecolor='red')
  583. out = self.pcap_filepath.replace('.pcap', '_plot-' + title + file_ending)
  584. plt.savefig(out, dpi=500)
  585. return out
  586. def plot_ttl(file_ending: str):
  587. query_output = self.stats_db.process_user_defined_query(
  588. "SELECT ttlValue, SUM(ttlCount) FROM ip_ttl GROUP BY ttlValue")
  589. title = "TTL Distribution"
  590. x_label = "TTL Value"
  591. y_label = "Number of Packets"
  592. if query_output:
  593. return plot_distribution(query_output, title, x_label, y_label, file_ending)
  594. def plot_mss(file_ending: str):
  595. query_output = self.stats_db.process_user_defined_query(
  596. "SELECT mssValue, SUM(mssCount) FROM tcp_mss GROUP BY mssValue")
  597. title = "MSS Distribution"
  598. x_label = "MSS Value"
  599. y_label = "Number of Packets"
  600. if query_output:
  601. return plot_distribution(query_output, title, x_label, y_label, file_ending)
  602. def plot_win(file_ending: str):
  603. query_output = self.stats_db.process_user_defined_query(
  604. "SELECT winSize, SUM(winCount) FROM tcp_win GROUP BY winSize")
  605. title = "Window Size Distribution"
  606. x_label = "Window Size"
  607. y_label = "Number of Packets"
  608. if query_output:
  609. return plot_distribution(query_output, title, x_label, y_label, file_ending)
  610. def plot_protocol(file_ending: str):
  611. plt.gcf().clear()
  612. result = self.stats_db.process_user_defined_query(
  613. "SELECT protocolName, SUM(protocolCount) FROM ip_protocols GROUP BY protocolName")
  614. if result:
  615. graphx, graphy = [], []
  616. for row in result:
  617. graphx.append(row[0])
  618. graphy.append(row[1])
  619. plt.autoscale(enable=True, axis='both')
  620. plt.title("Protocols Distribution")
  621. plt.xlabel('Protocols')
  622. plt.ylabel('Number of Packets')
  623. width = 0.1
  624. plt.xlim([0, len(graphx)])
  625. plt.grid(True)
  626. # Protocols' names on x-axis
  627. x = range(0, len(graphx))
  628. my_xticks = graphx
  629. plt.xticks(x, my_xticks)
  630. plt.bar(x, graphy, width, align='center', linewidth=1, color='red', edgecolor='red')
  631. out = self.pcap_filepath.replace('.pcap', '_plot-protocol' + file_ending)
  632. plt.savefig(out, dpi=500)
  633. return out
  634. else:
  635. print("Error plot protocol: No protocol values found!")
  636. def plot_port(file_ending: str):
  637. plt.gcf().clear()
  638. result = self.stats_db.process_user_defined_query(
  639. "SELECT portNumber, SUM(portCount) FROM ip_ports GROUP BY portNumber")
  640. graphx, graphy = [], []
  641. for row in result:
  642. graphx.append(row[0])
  643. graphy.append(row[1])
  644. plt.autoscale(enable=True, axis='both')
  645. plt.title("Ports Distribution")
  646. plt.xlabel('Ports Numbers')
  647. plt.ylabel('Number of Packets')
  648. width = 0.1
  649. plt.xlim([0, max(graphx)])
  650. plt.grid(True)
  651. plt.bar(graphx, graphy, width, align='center', linewidth=1, color='red', edgecolor='red')
  652. out = self.pcap_filepath.replace('.pcap', '_plot-port' + file_ending)
  653. plt.savefig(out, dpi=500)
  654. return out
  655. # This distribution is not drawable for big datasets
  656. def plot_ip_src(file_ending: str):
  657. plt.gcf().clear()
  658. result = self.stats_db.process_user_defined_query(
  659. "SELECT ipAddress, pktsSent FROM ip_statistics")
  660. graphx, graphy = [], []
  661. for row in result:
  662. graphx.append(row[0])
  663. graphy.append(row[1])
  664. plt.autoscale(enable=True, axis='both')
  665. plt.title("Source IP Distribution")
  666. plt.xlabel('Source IP')
  667. plt.ylabel('Number of Packets')
  668. width = 0.1
  669. plt.xlim([0, len(graphx)])
  670. plt.grid(True)
  671. # IPs on x-axis
  672. x = range(0, len(graphx))
  673. my_xticks = graphx
  674. plt.xticks(x, my_xticks, rotation='vertical', fontsize=5)
  675. plt.tight_layout()
  676. # limit the number of xticks
  677. plt.locator_params(axis='x', nbins=20)
  678. plt.bar(x, graphy, width, align='center', linewidth=1, color='red', edgecolor='red')
  679. out = self.pcap_filepath.replace('.pcap', '_plot-ip-src' + file_ending)
  680. plt.savefig(out, dpi=500)
  681. return out
  682. # This distribution is not drawable for big datasets
  683. def plot_ip_dst(file_ending: str):
  684. plt.gcf().clear()
  685. result = self.stats_db.process_user_defined_query(
  686. "SELECT ipAddress, pktsReceived FROM ip_statistics")
  687. graphx, graphy = [], []
  688. for row in result:
  689. graphx.append(row[0])
  690. graphy.append(row[1])
  691. plt.autoscale(enable=True, axis='both')
  692. plt.title("Destination IP Distribution")
  693. plt.xlabel('Destination IP')
  694. plt.ylabel('Number of Packets')
  695. width = 0.1
  696. plt.xlim([0, len(graphx)])
  697. plt.grid(True)
  698. # IPs on x-axis
  699. x = range(0, len(graphx))
  700. my_xticks = graphx
  701. plt.xticks(x, my_xticks, rotation='vertical', fontsize=5)
  702. plt.tight_layout()
  703. # limit the number of xticks
  704. plt.locator_params(axis='x', nbins=20)
  705. plt.bar(x, graphy, width, align='center', linewidth=1, color='red', edgecolor='red')
  706. out = self.pcap_filepath.replace('.pcap', '_plot-ip-dst' + file_ending)
  707. plt.savefig(out, dpi=500)
  708. return out
  709. def plot_interval_statistics(query_output, title, x_label, y_label, file_ending: str):
  710. plt.gcf().clear()
  711. graphx, graphy = [], []
  712. for row in query_output:
  713. graphx.append(row[0])
  714. graphy.append(row[1])
  715. plt.autoscale(enable=True, axis='both')
  716. plt.title(title)
  717. plt.xlabel(x_label)
  718. plt.ylabel(y_label)
  719. width = 0.5
  720. plt.xlim([0, len(graphx)])
  721. plt.grid(True)
  722. # timestamp on x-axis
  723. x = range(0, len(graphx))
  724. # limit the number of xticks
  725. plt.locator_params(axis='x', nbins=20)
  726. plt.bar(x, graphy, width, align='center', linewidth=1, color='red', edgecolor='red')
  727. out = self.pcap_filepath.replace('.pcap', '_plot-' + title + file_ending)
  728. plt.savefig(out, dpi=500)
  729. return out
  730. def plot_interval_pkt_count(file_ending: str):
  731. query_output = self.stats_db.process_user_defined_query(
  732. "SELECT lastPktTimestamp, pktsCount FROM interval_statistics ORDER BY lastPktTimestamp")
  733. title = "Packet Rate"
  734. x_label = "Time Interval"
  735. y_label = "Number of Packets"
  736. if query_output:
  737. return plot_interval_statistics(query_output, title, x_label, y_label, file_ending)
  738. def plot_interval_ip_src_ent(file_ending: str):
  739. query_output = self.stats_db.process_user_defined_query(
  740. "SELECT lastPktTimestamp, ipSrcEntropy FROM interval_statistics ORDER BY lastPktTimestamp")
  741. title = "Source IP Entropy"
  742. x_label = "Time Interval"
  743. y_label = "Entropy"
  744. if query_output:
  745. return plot_interval_statistics(query_output, title, x_label, y_label, file_ending)
  746. def plot_interval_ip_dst_ent(file_ending: str):
  747. query_output = self.stats_db.process_user_defined_query(
  748. "SELECT lastPktTimestamp, ipDstEntropy FROM interval_statistics ORDER BY lastPktTimestamp")
  749. title = "Destination IP Entropy"
  750. x_label = "Time Interval"
  751. y_label = "Entropy"
  752. if query_output:
  753. return plot_interval_statistics(query_output, title, x_label, y_label, file_ending)
  754. def plot_interval_new_ip(file_ending: str):
  755. query_output = self.stats_db.process_user_defined_query(
  756. "SELECT lastPktTimestamp, newIPCount FROM interval_statistics ORDER BY lastPktTimestamp")
  757. title = "IP Novelty Distribution"
  758. x_label = "Time Interval"
  759. y_label = "Novel values count"
  760. if query_output:
  761. return plot_interval_statistics(query_output, title, x_label, y_label, file_ending)
  762. def plot_interval_new_port(file_ending: str):
  763. query_output = self.stats_db.process_user_defined_query(
  764. "SELECT lastPktTimestamp, newPortCount FROM interval_statistics ORDER BY lastPktTimestamp")
  765. title = "Port Novelty Distribution"
  766. x_label = "Time Interval"
  767. y_label = "Novel values count"
  768. if query_output:
  769. return plot_interval_statistics(query_output, title, x_label, y_label, file_ending)
  770. def plot_interval_new_ttl(file_ending: str):
  771. query_output = self.stats_db.process_user_defined_query(
  772. "SELECT lastPktTimestamp, newTTLCount FROM interval_statistics ORDER BY lastPktTimestamp")
  773. title = "TTL Novelty Distribution"
  774. x_label = "Time Interval"
  775. y_label = "Novel values count"
  776. if query_output:
  777. return plot_interval_statistics(query_output, title, x_label, y_label, file_ending)
  778. def plot_interval_new_tos(file_ending: str):
  779. query_output = self.stats_db.process_user_defined_query(
  780. "SELECT lastPktTimestamp, newToSCount FROM interval_statistics ORDER BY lastPktTimestamp")
  781. title = "ToS Novelty Distribution"
  782. x_label = "Time Interval"
  783. y_label = "Novel values count"
  784. if query_output:
  785. return plot_interval_statistics(query_output, title, x_label, y_label, file_ending)
  786. def plot_interval_new_win_size(file_ending: str):
  787. query_output = self.stats_db.process_user_defined_query(
  788. "SELECT lastPktTimestamp, newWinSizeCount FROM interval_statistics ORDER BY lastPktTimestamp")
  789. title = "Window Size Novelty Distribution"
  790. x_label = "Time Interval"
  791. y_label = "Novel values count"
  792. if query_output:
  793. return plot_interval_statistics(query_output, title, x_label, y_label, file_ending)
  794. def plot_interval_new_mss(file_ending: str):
  795. query_output = self.stats_db.process_user_defined_query(
  796. "SELECT lastPktTimestamp, newMSSCount FROM interval_statistics ORDER BY lastPktTimestamp")
  797. title = "MSS Novelty Distribution"
  798. x_label = "Time Interval"
  799. y_label = "Novel values count"
  800. if query_output:
  801. return plot_interval_statistics(query_output, title, x_label, y_label, file_ending)
  802. def plot_interval_ip_dst_cum_ent(file_ending: str):
  803. plt.gcf().clear()
  804. result = self.stats_db.process_user_defined_query(
  805. "SELECT lastPktTimestamp, ipDstCumEntropy FROM interval_statistics ORDER BY lastPktTimestamp")
  806. graphx, graphy = [], []
  807. for row in result:
  808. graphx.append(row[0])
  809. graphy.append(row[1])
  810. # If entropy was not calculated do not plot the graph
  811. if graphy[0] != -1:
  812. plt.autoscale(enable=True, axis='both')
  813. plt.title("Destination IP Cumulative Entropy")
  814. # plt.xlabel('Timestamp')
  815. plt.xlabel('Time Interval')
  816. plt.ylabel('Entropy')
  817. plt.xlim([0, len(graphx)])
  818. plt.grid(True)
  819. # timestamp on x-axis
  820. x = range(0, len(graphx))
  821. # my_xticks = graphx
  822. # plt.xticks(x, my_xticks, rotation='vertical', fontsize=5)
  823. # plt.tight_layout()
  824. # limit the number of xticks
  825. plt.locator_params(axis='x', nbins=20)
  826. plt.plot(x, graphy, 'r')
  827. out = self.pcap_filepath.replace('.pcap', '_plot-interval-ip-dst-cum-ent' + file_ending)
  828. plt.savefig(out, dpi=500)
  829. return out
  830. def plot_interval_ip_src_cum_ent(file_ending: str):
  831. plt.gcf().clear()
  832. result = self.stats_db.process_user_defined_query(
  833. "SELECT lastPktTimestamp, ipSrcCumEntropy FROM interval_statistics ORDER BY lastPktTimestamp")
  834. graphx, graphy = [], []
  835. for row in result:
  836. graphx.append(row[0])
  837. graphy.append(row[1])
  838. # If entropy was not calculated do not plot the graph
  839. if graphy[0] != -1:
  840. plt.autoscale(enable=True, axis='both')
  841. plt.title("Source IP Cumulative Entropy")
  842. # plt.xlabel('Timestamp')
  843. plt.xlabel('Time Interval')
  844. plt.ylabel('Entropy')
  845. plt.xlim([0, len(graphx)])
  846. plt.grid(True)
  847. # timestamp on x-axis
  848. x = range(0, len(graphx))
  849. # my_xticks = graphx
  850. # plt.xticks(x, my_xticks, rotation='vertical', fontsize=5)
  851. # plt.tight_layout()
  852. # limit the number of xticks
  853. plt.locator_params(axis='x', nbins=20)
  854. plt.plot(x, graphy, 'r')
  855. out = self.pcap_filepath.replace('.pcap', '_plot-interval-ip-src-cum-ent' + file_ending)
  856. plt.savefig(out, dpi=500)
  857. return out
  858. ttl_out_path = plot_ttl('.' + file_format)
  859. mss_out_path = plot_mss('.' + file_format)
  860. win_out_path = plot_win('.' + file_format)
  861. protocol_out_path = plot_protocol('.' + file_format)
  862. plot_interval_pktCount = plot_interval_pkt_count('.' + file_format)
  863. if entropy:
  864. plot_interval_ip_src_ent = plot_interval_ip_src_ent('.' + file_format)
  865. plot_interval_ip_dst_ent = plot_interval_ip_dst_ent('.' + file_format)
  866. plot_interval_ip_src_cum_ent = plot_interval_ip_src_cum_ent('.' + file_format)
  867. plot_interval_ip_dst_cum_ent = plot_interval_ip_dst_cum_ent('.' + file_format)
  868. plot_interval_new_ip = plot_interval_new_ip('.' + file_format)
  869. plot_interval_new_port = plot_interval_new_port('.' + file_format)
  870. plot_interval_new_ttl = plot_interval_new_ttl('.' + file_format)
  871. plot_interval_new_tos = plot_interval_new_tos('.' + file_format)
  872. plot_interval_new_win_size = plot_interval_new_win_size('.' + file_format)
  873. plot_interval_new_mss = plot_interval_new_mss('.' + file_format)
  874. # Time consuming plot
  875. # port_out_path = plot_port('.' + format)
  876. # Not drawable for too many IPs
  877. # ip_src_out_path = plot_ip_src('.' + format)
  878. # ip_dst_out_path = plot_ip_dst('.' + format)
  879. print("Saved plots in the input PCAP directory.")