3
0

Statistics.py 44 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994
  1. from operator import itemgetter
  2. from math import sqrt, ceil, log
  3. import os
  4. import time
  5. import random
  6. import ID2TLib.libpcapreader as pr
  7. import matplotlib
  8. matplotlib.use('Agg', force=True)
  9. import matplotlib.pyplot as plt
  10. from ID2TLib.PcapFile import PcapFile
  11. from ID2TLib.StatsDatabase import StatsDatabase
  12. from ID2TLib.Utility import handle_most_used_outputs
  13. class Statistics:
  14. def __init__(self, pcap_file: PcapFile):
  15. """
  16. Creates a new Statistics object.
  17. :param pcap_file: A reference to the PcapFile object
  18. """
  19. # Fields
  20. self.pcap_filepath = pcap_file.pcap_file_path
  21. self.pcap_proc = None
  22. self.do_extra_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 does not exist OR param -r/--recalculate is provided
  46. if (not self.stats_db.get_db_exists()) or flag_recalculate_stats or self.stats_db.get_db_outdated():
  47. self.pcap_proc = pr.pcap_processor(self.pcap_filepath, str(self.do_extra_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, 4)
  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 calculate_entropy(self, frequency:list, normalized:bool = False):
  121. """
  122. Calculates entropy and normalized entropy of list of elements that have specific frequency
  123. :param frequency: The frequency of the elements.
  124. :param normalized: Calculate normalized entropy
  125. :return: entropy or (entropy, normalized entropy)
  126. """
  127. entropy, normalizedEnt, n = 0, 0, 0
  128. sumFreq = sum(frequency)
  129. for i, x in enumerate(frequency):
  130. p_x = float(frequency[i] / sumFreq)
  131. if p_x > 0:
  132. n += 1
  133. entropy += - p_x * log(p_x, 2)
  134. if normalized:
  135. if log(n)>0:
  136. normalizedEnt = entropy/log(n, 2)
  137. return entropy, normalizedEnt
  138. else:
  139. return entropy
  140. def calculate_complement_packet_rates(self, pps):
  141. """
  142. Calculates the complement packet rates of the background traffic packet rates for each interval.
  143. Then normalize it to maximum boundary, which is the input parameter pps
  144. :return: normalized packet rates for each time interval.
  145. """
  146. result = self.process_db_query(
  147. "SELECT lastPktTimestamp,pktsCount FROM interval_statistics ORDER BY lastPktTimestamp")
  148. # print(result)
  149. bg_interval_pps = []
  150. complement_interval_pps = []
  151. intervalsSum = 0
  152. if result:
  153. # Get the interval in seconds
  154. for i, row in enumerate(result):
  155. if i < len(result) - 1:
  156. intervalsSum += ceil((int(result[i + 1][0]) * 10 ** -6) - (int(row[0]) * 10 ** -6))
  157. interval = intervalsSum / (len(result) - 1)
  158. # Convert timestamp from micro to seconds, convert packet rate "per interval" to "per second"
  159. for row in result:
  160. bg_interval_pps.append((int(row[0]) * 10 ** -6, int(row[1] / interval)))
  161. # Find max PPS
  162. maxPPS = max(bg_interval_pps, key=itemgetter(1))[1]
  163. for row in bg_interval_pps:
  164. complement_interval_pps.append((row[0], int(pps * (maxPPS - row[1]) / maxPPS)))
  165. return complement_interval_pps
  166. def get_tests_statistics(self):
  167. """
  168. Writes the calculated basic defects tests statistics into a file.
  169. """
  170. # self.stats_db._process_user_defined_query output is list of tuples, thus, we ned [0][0] to access data
  171. def count_frequncy(valuesList):
  172. values, frequency = [] , []
  173. for x in valuesList:
  174. if x in values:
  175. frequency[values.index(x)] += 1
  176. else:
  177. values.append(x)
  178. frequency.append(1)
  179. return values, frequency
  180. ####### Payload Tests #######
  181. sumPayloadCount = self.stats_db._process_user_defined_query("SELECT sum(payloadCount) FROM interval_statistics")
  182. pktCount = self.stats_db._process_user_defined_query("SELECT packetCount FROM file_statistics")
  183. if sumPayloadCount and pktCount:
  184. payloadRatio=0
  185. if(pktCount[0][0]!=0):
  186. payloadRatio = float(sumPayloadCount[0][0] / pktCount[0][0] * 100)
  187. else:
  188. payloadRatio = -1
  189. ####### TCP checksum Tests #######
  190. incorrectChecksumCount = self.stats_db._process_user_defined_query("SELECT sum(incorrectTCPChecksumCount) FROM interval_statistics")
  191. correctChecksumCount = self.stats_db._process_user_defined_query("SELECT avg(correctTCPChecksumCount) FROM interval_statistics")
  192. if incorrectChecksumCount and correctChecksumCount:
  193. incorrectChecksumRatio=0
  194. if(incorrectChecksumCount[0][0] + correctChecksumCount[0][0])!=0:
  195. incorrectChecksumRatio = float(incorrectChecksumCount[0][0] / (incorrectChecksumCount[0][0] + correctChecksumCount[0][0] ) * 100)
  196. else:
  197. incorrectChecksumRatio = -1
  198. ####### IP Src & Dst Tests #######
  199. result = self.stats_db._process_user_defined_query("SELECT ipAddress,pktsSent,pktsReceived FROM ip_statistics")
  200. data, srcFrequency, dstFrequency = [], [], []
  201. if result:
  202. for row in result:
  203. srcFrequency.append(row[1])
  204. dstFrequency.append(row[2])
  205. ipSrcEntropy, ipSrcNormEntropy = self.calculate_entropy(srcFrequency, True)
  206. ipDstEntropy, ipDstNormEntropy = self.calculate_entropy(dstFrequency, True)
  207. newIPCount = self.stats_db._process_user_defined_query("SELECT newIPCount FROM interval_statistics")
  208. ipNovelsPerInterval, ipNovelsPerIntervalFrequency = count_frequncy(newIPCount)
  209. ipNoveltyDistEntropy = self.calculate_entropy(ipNovelsPerIntervalFrequency)
  210. ####### Ports Tests #######
  211. port0Count = self.stats_db._process_user_defined_query("SELECT SUM(portCount) FROM ip_ports WHERE portNumber = 0")
  212. if not port0Count[0][0]:
  213. port0Count = 0
  214. else:
  215. port0Count = port0Count[0][0]
  216. reservedPortCount = self.stats_db._process_user_defined_query(
  217. "SELECT SUM(portCount) FROM ip_ports WHERE portNumber IN (100,114,1023,1024,49151,49152,65535)")# could be extended
  218. if not reservedPortCount[0][0]:
  219. reservedPortCount = 0
  220. else:
  221. reservedPortCount = reservedPortCount[0][0]
  222. ####### TTL Tests #######
  223. result = self.stats_db._process_user_defined_query("SELECT ttlValue,SUM(ttlCount) FROM ip_ttl GROUP BY ttlValue")
  224. data, frequency = [], []
  225. for row in result:
  226. frequency.append(row[1])
  227. ttlEntropy, ttlNormEntropy = self.calculate_entropy(frequency,True)
  228. newTTLCount = self.stats_db._process_user_defined_query("SELECT newTTLCount FROM interval_statistics")
  229. ttlNovelsPerInterval, ttlNovelsPerIntervalFrequency = count_frequncy(newTTLCount)
  230. ttlNoveltyDistEntropy = self.calculate_entropy(ttlNovelsPerIntervalFrequency)
  231. ####### Window Size Tests #######
  232. result = self.stats_db._process_user_defined_query("SELECT winSize,SUM(winCount) FROM tcp_win GROUP BY winSize")
  233. data, frequency = [], []
  234. for row in result:
  235. frequency.append(row[1])
  236. winEntropy, winNormEntropy = self.calculate_entropy(frequency, True)
  237. newWinSizeCount = self.stats_db._process_user_defined_query("SELECT newWinSizeCount FROM interval_statistics")
  238. winNovelsPerInterval, winNovelsPerIntervalFrequency = count_frequncy(newWinSizeCount)
  239. winNoveltyDistEntropy = self.calculate_entropy(winNovelsPerIntervalFrequency)
  240. ####### ToS Tests #######
  241. result = self.stats_db._process_user_defined_query(
  242. "SELECT tosValue,SUM(tosCount) FROM ip_tos GROUP BY tosValue")
  243. data, frequency = [], []
  244. for row in result:
  245. frequency.append(row[1])
  246. tosEntropy, tosNormEntropy = self.calculate_entropy(frequency, True)
  247. newToSCount = self.stats_db._process_user_defined_query("SELECT newToSCount FROM interval_statistics")
  248. tosNovelsPerInterval, tosNovelsPerIntervalFrequency = count_frequncy(newToSCount)
  249. tosNoveltyDistEntropy = self.calculate_entropy(tosNovelsPerIntervalFrequency)
  250. ####### MSS Tests #######
  251. result = self.stats_db._process_user_defined_query(
  252. "SELECT mssValue,SUM(mssCount) FROM tcp_mss GROUP BY mssValue")
  253. data, frequency = [], []
  254. for row in result:
  255. frequency.append(row[1])
  256. mssEntropy, mssNormEntropy = self.calculate_entropy(frequency, True)
  257. newMSSCount = self.stats_db._process_user_defined_query("SELECT newMSSCount FROM interval_statistics")
  258. mssNovelsPerInterval, mssNovelsPerIntervalFrequency = count_frequncy(newMSSCount)
  259. mssNoveltyDistEntropy = self.calculate_entropy(mssNovelsPerIntervalFrequency)
  260. result = self.stats_db._process_user_defined_query("SELECT SUM(mssCount) FROM tcp_mss WHERE mssValue > 1460")
  261. # The most used MSS < 1460. Calculate the ratio of the values bigger that 1460.
  262. if not result[0][0]:
  263. result = 0
  264. else:
  265. result = result[0][0]
  266. bigMSS = (result / sum(frequency)) * 100
  267. output = []
  268. if self.do_extra_tests:
  269. output = [("Payload ratio", payloadRatio, "%"),
  270. ("Incorrect TCP checksum ratio", incorrectChecksumRatio, "%")]
  271. output = output + [("# IP addresses", sum([x[0] for x in newIPCount]), ""),
  272. ("IP Src Entropy", ipSrcEntropy, ""),
  273. ("IP Src Normalized Entropy", ipSrcNormEntropy, ""),
  274. ("IP Dst Entropy", ipDstEntropy, ""),
  275. ("IP Dst Normalized Entropy", ipDstNormEntropy, ""),
  276. ("IP Novelty Distribution Entropy", ipNoveltyDistEntropy, ""),
  277. ("# TTL values", sum([x[0] for x in newTTLCount]), ""),
  278. ("TTL Entropy", ttlEntropy, ""),
  279. ("TTL Normalized Entropy", ttlNormEntropy, ""),
  280. ("TTL Novelty Distribution Entropy", ttlNoveltyDistEntropy, ""),
  281. ("# WinSize values", sum([x[0] for x in newWinSizeCount]), ""),
  282. ("WinSize Entropy", winEntropy, ""),
  283. ("WinSize Normalized Entropy", winNormEntropy, ""),
  284. ("WinSize Novelty Distribution Entropy", winNoveltyDistEntropy, ""),
  285. ("# ToS values", sum([x[0] for x in newToSCount]), ""),
  286. ("ToS Entropy", tosEntropy, ""),
  287. ("ToS Normalized Entropy", tosNormEntropy, ""),
  288. ("ToS Novelty Distribution Entropy", tosNoveltyDistEntropy, ""),
  289. ("# MSS values", sum([x[0] for x in newMSSCount]), ""),
  290. ("MSS Entropy", mssEntropy, ""),
  291. ("MSS Normalized Entropy", mssNormEntropy, ""),
  292. ("MSS Novelty Distribution Entropy", mssNoveltyDistEntropy, ""),
  293. ("======================","","")]
  294. # Reasoning the statistics values
  295. if self.do_extra_tests:
  296. if payloadRatio > 80:
  297. output.append(("WARNING: Too high payload ratio", payloadRatio, "%."))
  298. if payloadRatio < 30:
  299. output.append(("WARNING: Too low payload ratio", payloadRatio, "% (Injecting attacks that are carried out in the packet payloads is not recommmanded)."))
  300. if incorrectChecksumRatio > 5:
  301. output.append(("WARNING: High incorrect TCP checksum ratio",incorrectChecksumRatio,"%."))
  302. if ipSrcNormEntropy > 0.65:
  303. output.append(("WARNING: High IP source normalized entropy",ipSrcNormEntropy,"."))
  304. if ipSrcNormEntropy < 0.2:
  305. output.append(("WARNING: Low IP source normalized entropy", ipSrcNormEntropy, "."))
  306. if ipDstNormEntropy > 0.65:
  307. output.append(("WARNING: High IP destination normalized entropy", ipDstNormEntropy, "."))
  308. if ipDstNormEntropy < 0.2:
  309. output.append(("WARNING: Low IP destination normalized entropy", ipDstNormEntropy, "."))
  310. if ttlNormEntropy > 0.65:
  311. output.append(("WARNING: High TTL normalized entropy", ttlNormEntropy, "."))
  312. if ttlNormEntropy < 0.2:
  313. output.append(("WARNING: Low TTL normalized entropy", ttlNormEntropy, "."))
  314. if ttlNoveltyDistEntropy < 1:
  315. output.append(("WARNING: Too low TTL novelty distribution entropy", ttlNoveltyDistEntropy,
  316. "(The distribution of the novel TTL values is suspicious)."))
  317. if winNormEntropy > 0.6:
  318. output.append(("WARNING: High Window Size normalized entropy", winNormEntropy, "."))
  319. if winNormEntropy < 0.1:
  320. output.append(("WARNING: Low Window Size normalized entropy", winNormEntropy, "."))
  321. if winNoveltyDistEntropy < 4:
  322. output.append(("WARNING: Low Window Size novelty distribution entropy", winNoveltyDistEntropy,
  323. "(The distribution of the novel Window Size values is suspicious)."))
  324. if tosNormEntropy > 0.4:
  325. output.append(("WARNING: High ToS normalized entropy", tosNormEntropy, "."))
  326. if tosNormEntropy < 0.1:
  327. output.append(("WARNING: Low ToS normalized entropy", tosNormEntropy, "."))
  328. if tosNoveltyDistEntropy < 0.5:
  329. output.append(("WARNING: Low ToS novelty distribution entropy", tosNoveltyDistEntropy,
  330. "(The distribution of the novel ToS values is suspicious)."))
  331. if mssNormEntropy > 0.4:
  332. output.append(("WARNING: High MSS normalized entropy", mssNormEntropy, "."))
  333. if mssNormEntropy < 0.1:
  334. output.append(("WARNING: Low MSS normalized entropy", mssNormEntropy, "."))
  335. if mssNoveltyDistEntropy < 0.5:
  336. output.append(("WARNING: Low MSS novelty distribution entropy", mssNoveltyDistEntropy,
  337. "(The distribution of the novel MSS values is suspicious)."))
  338. if bigMSS > 50:
  339. output.append(("WARNING: High ratio of MSS > 1460", bigMSS, "% (High fragmentation rate in Ethernet)."))
  340. if port0Count > 0:
  341. output.append(("WARNING: Port number 0 is used in ",port0Count,"packets (awkward-looking port)."))
  342. if reservedPortCount > 0:
  343. output.append(("WARNING: Reserved port numbers are used in ",reservedPortCount,"packets (uncommonly-used ports)."))
  344. return output
  345. def write_statistics_to_file(self):
  346. """
  347. Writes the calculated basic statistics into a file.
  348. """
  349. def _write_header(title: str):
  350. """
  351. Writes the section header into the open file.
  352. :param title: The section title
  353. """
  354. target.write("====================== \n")
  355. target.write(title + " \n")
  356. target.write("====================== \n")
  357. target = open(self.pcap_filepath + ".stat", 'w')
  358. target.truncate()
  359. _write_header("PCAP file information")
  360. Statistics.write_list(self.get_file_information(), target.write)
  361. _write_header("General statistics")
  362. Statistics.write_list(self.get_general_file_statistics(), target.write)
  363. _write_header("Tests statistics")
  364. Statistics.write_list(self.get_tests_statistics(), target.write)
  365. target.close()
  366. def get_capture_duration(self):
  367. """
  368. :return: The duration of the capture in seconds
  369. """
  370. return self.file_info['captureDuration']
  371. def get_pcap_timestamp_start(self):
  372. """
  373. :return: The timestamp of the first packet in the PCAP file
  374. """
  375. return self.file_info['timestampFirstPacket']
  376. def get_pcap_timestamp_end(self):
  377. """
  378. :return: The timestamp of the last packet in the PCAP file
  379. """
  380. return self.file_info['timestampLastPacket']
  381. def get_pps_sent(self, ip_address: str):
  382. """
  383. Calculates the sent packets per seconds for a given IP address.
  384. :param ip_address: The IP address whose packets per second should be calculated
  385. :return: The sent packets per seconds for the given IP address
  386. """
  387. packets_sent = self.stats_db.process_db_query("SELECT pktsSent from ip_statistics WHERE ipAddress=?", False,
  388. (ip_address,))
  389. capture_duration = float(self.get_capture_duration())
  390. return int(float(packets_sent) / capture_duration)
  391. def get_pps_received(self, ip_address: str):
  392. """
  393. Calculate the packets per second received for a given IP address.
  394. :param ip_address: The IP address used for the calculation
  395. :return: The number of packets per second received
  396. """
  397. packets_received = self.stats_db.process_db_query("SELECT pktsReceived FROM ip_statistics WHERE ipAddress=?",
  398. False,
  399. (ip_address,))
  400. capture_duration = float(self.get_capture_duration())
  401. return int(float(packets_received) / capture_duration)
  402. def get_packet_count(self):
  403. """
  404. :return: The number of packets in the loaded PCAP file
  405. """
  406. return self.file_info['packetCount']
  407. def get_most_used_ip_address(self):
  408. """
  409. :return: The IP address/addresses with the highest sum of packets sent and received
  410. """
  411. return handle_most_used_outputs(self.process_db_query("most_used(ipAddress)"))
  412. def get_ttl_distribution(self, ipAddress: str):
  413. result = self.process_db_query('SELECT ttlValue, ttlCount from ip_ttl WHERE ipAddress="' + ipAddress + '"')
  414. result_dict = {key: value for (key, value) in result}
  415. return result_dict
  416. def get_mss_distribution(self, ipAddress: str):
  417. result = self.process_db_query('SELECT mssValue, mssCount from tcp_mss WHERE ipAddress="' + ipAddress + '"')
  418. result_dict = {key: value for (key, value) in result}
  419. return result_dict
  420. def get_win_distribution(self, ipAddress: str):
  421. result = self.process_db_query('SELECT winSize, winCount from tcp_win WHERE ipAddress="' + ipAddress + '"')
  422. result_dict = {key: value for (key, value) in result}
  423. return result_dict
  424. def get_tos_distribution(self, ipAddress: str):
  425. result = self.process_db_query('SELECT tosValue, tosCount from ip_tos WHERE ipAddress="' + ipAddress + '"')
  426. result_dict = {key: value for (key, value) in result}
  427. return result_dict
  428. def get_ip_address_count(self):
  429. return self.process_db_query("SELECT COUNT(*) FROM ip_statistics")
  430. def get_ip_addresses(self):
  431. return self.process_db_query("SELECT ipAddress FROM ip_statistics")
  432. def get_random_ip_address(self, count: int = 1):
  433. """
  434. :param count: The number of IP addreses to return
  435. :return: A randomly chosen IP address from the dataset or iff param count is greater than one, a list of randomly
  436. chosen IP addresses
  437. """
  438. ip_address_list = self.process_db_query("all(ipAddress)")
  439. if count == 1:
  440. return random.choice(ip_address_list)
  441. else:
  442. result_list = []
  443. for i in range(0, count):
  444. random_ip = random.choice(ip_address_list)
  445. result_list.append(random_ip)
  446. ip_address_list.remove(random_ip)
  447. return result_list
  448. def get_ip_address_from_mac(self, macAddress: str):
  449. """
  450. :param macAddress: the MAC address of which the IP shall be returned, if existing in DB
  451. :return: the IP address used in the dataset by a given MAC address
  452. """
  453. return self.process_db_query('ipAddress(macAddress=' + macAddress + ")")
  454. def get_mac_address(self, ipAddress: str):
  455. """
  456. :return: The MAC address used in the dataset for the given IP address.
  457. """
  458. return self.process_db_query('macAddress(ipAddress=' + ipAddress + ")")
  459. def get_most_used_mss(self, ipAddress: str):
  460. """
  461. :param ipAddress: The IP address whose used MSS should be determined
  462. :return: The TCP MSS value used by the IP address, or if the IP addresses never specified a MSS,
  463. then None is returned
  464. """
  465. mss_value = self.process_db_query('SELECT mssValue from tcp_mss WHERE ipAddress="' + ipAddress + '" AND mssCount == (SELECT MAX(mssCount) from tcp_mss WHERE ipAddress="' + ipAddress + '")')
  466. if isinstance(mss_value, int):
  467. return mss_value
  468. elif isinstance(mss_value, list):
  469. if len(mss_value) == 0:
  470. return None
  471. else:
  472. mss_value.sort()
  473. return mss_value[0]
  474. else:
  475. return None
  476. def get_most_used_ttl(self, ipAddress: str):
  477. """
  478. :param ipAddress: The IP address whose used TTL should be determined
  479. :return: The TTL value used by the IP address, or if the IP addresses never specified a TTL,
  480. then None is returned
  481. """
  482. ttl_value = self.process_db_query(
  483. 'SELECT ttlValue from ip_ttl WHERE ipAddress="' + ipAddress + '" AND ttlCount == (SELECT MAX(ttlCount) from ip_ttl WHERE ipAddress="' + ipAddress + '")')
  484. if isinstance(ttl_value, int):
  485. return ttl_value
  486. elif isinstance(ttl_value, list):
  487. if len(ttl_value) == 0:
  488. return None
  489. else:
  490. ttl_value.sort()
  491. return ttl_value[0]
  492. else:
  493. return None
  494. def get_rnd_win_size(self, pkts_num):
  495. """
  496. :param pkts_num: maximum number of window sizes, that should be returned
  497. :return: A list of randomly chosen window sizes with given length.
  498. """
  499. sql_return = self.process_db_query("SELECT DISTINCT winSize FROM tcp_win ORDER BY winsize ASC;")
  500. if not isinstance(sql_return, list):
  501. return [sql_return]
  502. result = []
  503. for i in range(0, min(pkts_num, len(sql_return))):
  504. result.append(random.choice(sql_return))
  505. sql_return.remove(result[i])
  506. return result
  507. def get_statistics_database(self):
  508. """
  509. :return: A reference to the statistics database object
  510. """
  511. return self.stats_db
  512. def process_db_query(self, query_string_in: str, print_results: bool = False):
  513. """
  514. Executes a string identified previously as a query. This can be a standard SQL SELECT/INSERT query or a named
  515. query.
  516. :param query_string_in: The query to be processed
  517. :param print_results: Indicates whether the results should be printed to terminal
  518. :return: The result of the query
  519. """
  520. return self.stats_db.process_db_query(query_string_in, print_results)
  521. def is_query(self, value: str):
  522. """
  523. Checks whether the given string is a standard SQL query (SELECT, INSERT) or a named query.
  524. :param value: The string to be checked
  525. :return: True if the string is recognized as a query, otherwise False.
  526. """
  527. if not isinstance(value, str):
  528. return False
  529. else:
  530. return (any(x in value.lower().strip() for x in self.stats_db.get_all_named_query_keywords()) or
  531. any(x in value.lower().strip() for x in self.stats_db.get_all_sql_query_keywords()))
  532. def calculate_standard_deviation(self, lst):
  533. """
  534. Calculates the standard deviation of a list of numbers.
  535. :param lst: The list of numbers to calculate its SD.
  536. """
  537. num_items = len(lst)
  538. mean = sum(lst) / num_items
  539. differences = [x - mean for x in lst]
  540. sq_differences = [d ** 2 for d in differences]
  541. ssd = sum(sq_differences)
  542. variance = ssd / num_items
  543. sd = sqrt(variance)
  544. return sd
  545. def plot_statistics(self,entropy : int , format: str = 'pdf'): #'png'
  546. """
  547. Plots the statistics associated with the dataset.
  548. :param format: The format to be used to save the statistics diagrams.
  549. """
  550. def plot_distribution(queryOutput, title, xLabel, yLabel, file_ending: str):
  551. plt.gcf().clear()
  552. graphx, graphy = [], []
  553. for row in queryOutput:
  554. graphx.append(row[0])
  555. graphy.append(row[1])
  556. plt.autoscale(enable=True, axis='both')
  557. plt.title(title)
  558. plt.xlabel(xLabel)
  559. plt.ylabel(yLabel)
  560. width = 0.1
  561. plt.xlim([0, max(graphx)])
  562. plt.grid(True)
  563. plt.bar(graphx, graphy, width, align='center', linewidth=1, color='red', edgecolor='red')
  564. out = self.pcap_filepath.replace('.pcap', '_plot-' + title + file_ending)
  565. plt.savefig(out,dpi=500)
  566. return out
  567. def plot_ttl(file_ending: str):
  568. queryOutput = self.stats_db._process_user_defined_query(
  569. "SELECT ttlValue, SUM(ttlCount) FROM ip_ttl GROUP BY ttlValue")
  570. title = "TTL Distribution"
  571. xLabel = "TTL Value"
  572. yLabel = "Number of Packets"
  573. if queryOutput:
  574. return plot_distribution(queryOutput, title, xLabel, yLabel, file_ending)
  575. def plot_mss(file_ending: str):
  576. queryOutput = self.stats_db._process_user_defined_query(
  577. "SELECT mssValue, SUM(mssCount) FROM tcp_mss GROUP BY mssValue")
  578. title = "MSS Distribution"
  579. xLabel = "MSS Value"
  580. yLabel = "Number of Packets"
  581. if queryOutput:
  582. return plot_distribution(queryOutput, title, xLabel, yLabel, file_ending)
  583. def plot_win(file_ending: str):
  584. queryOutput = self.stats_db._process_user_defined_query(
  585. "SELECT winSize, SUM(winCount) FROM tcp_win GROUP BY winSize")
  586. title = "Window Size Distribution"
  587. xLabel = "Window Size"
  588. yLabel = "Number of Packets"
  589. if queryOutput:
  590. return plot_distribution(queryOutput, title, xLabel, yLabel, file_ending)
  591. def plot_protocol(file_ending: str):
  592. plt.gcf().clear()
  593. result = self.stats_db._process_user_defined_query(
  594. "SELECT protocolName, SUM(protocolCount) FROM ip_protocols GROUP BY protocolName")
  595. if (result):
  596. graphx, graphy = [], []
  597. for row in result:
  598. graphx.append(row[0])
  599. graphy.append(row[1])
  600. plt.autoscale(enable=True, axis='both')
  601. plt.title("Protocols Distribution")
  602. plt.xlabel('Protocols')
  603. plt.ylabel('Number of Packets')
  604. width = 0.1
  605. plt.xlim([0, len(graphx)])
  606. plt.grid(True)
  607. # Protocols' names on x-axis
  608. x = range(0,len(graphx))
  609. my_xticks = graphx
  610. plt.xticks(x, my_xticks)
  611. plt.bar(x, graphy, width, align='center', linewidth=1, color='red', edgecolor='red')
  612. out = self.pcap_filepath.replace('.pcap', '_plot-protocol' + file_ending)
  613. plt.savefig(out,dpi=500)
  614. return out
  615. else:
  616. print("Error plot protocol: No protocol values found!")
  617. def plot_port(file_ending: str):
  618. plt.gcf().clear()
  619. result = self.stats_db._process_user_defined_query(
  620. "SELECT portNumber, SUM(portCount) FROM ip_ports GROUP BY portNumber")
  621. graphx, graphy = [], []
  622. for row in result:
  623. graphx.append(row[0])
  624. graphy.append(row[1])
  625. plt.autoscale(enable=True, axis='both')
  626. plt.title("Ports Distribution")
  627. plt.xlabel('Ports Numbers')
  628. plt.ylabel('Number of Packets')
  629. width = 0.1
  630. plt.xlim([0, max(graphx)])
  631. plt.grid(True)
  632. plt.bar(graphx, graphy, width, align='center', linewidth=1, color='red', edgecolor='red')
  633. out = self.pcap_filepath.replace('.pcap', '_plot-port' + file_ending)
  634. plt.savefig(out,dpi=500)
  635. return out
  636. # This distribution is not drawable for big datasets
  637. def plot_ip_src(file_ending: str):
  638. plt.gcf().clear()
  639. result = self.stats_db._process_user_defined_query(
  640. "SELECT ipAddress, pktsSent FROM ip_statistics")
  641. graphx, graphy = [], []
  642. for row in result:
  643. graphx.append(row[0])
  644. graphy.append(row[1])
  645. plt.autoscale(enable=True, axis='both')
  646. plt.title("Source IP Distribution")
  647. plt.xlabel('Source IP')
  648. plt.ylabel('Number of Packets')
  649. width = 0.1
  650. plt.xlim([0, len(graphx)])
  651. plt.grid(True)
  652. # IPs on x-axis
  653. x = range(0, len(graphx))
  654. my_xticks = graphx
  655. plt.xticks(x, my_xticks, rotation='vertical', fontsize=5)
  656. plt.tight_layout()
  657. # limit the number of xticks
  658. plt.locator_params(axis='x', nbins=20)
  659. plt.bar(x, graphy, width, align='center', linewidth=1, color='red', edgecolor='red')
  660. out = self.pcap_filepath.replace('.pcap', '_plot-ip-src' + file_ending)
  661. plt.savefig(out, dpi=500)
  662. return out
  663. # This distribution is not drawable for big datasets
  664. def plot_ip_dst(file_ending: str):
  665. plt.gcf().clear()
  666. result = self.stats_db._process_user_defined_query(
  667. "SELECT ipAddress, pktsReceived FROM ip_statistics")
  668. graphx, graphy = [], []
  669. for row in result:
  670. graphx.append(row[0])
  671. graphy.append(row[1])
  672. plt.autoscale(enable=True, axis='both')
  673. plt.title("Destination IP Distribution")
  674. plt.xlabel('Destination IP')
  675. plt.ylabel('Number of Packets')
  676. width = 0.1
  677. plt.xlim([0, len(graphx)])
  678. plt.grid(True)
  679. # IPs on x-axis
  680. x = range(0, len(graphx))
  681. my_xticks = graphx
  682. plt.xticks(x, my_xticks, rotation='vertical', fontsize=5)
  683. plt.tight_layout()
  684. # limit the number of xticks
  685. plt.locator_params(axis='x', nbins=20)
  686. plt.bar(x, graphy, width, align='center', linewidth=1, color='red', edgecolor='red')
  687. out = self.pcap_filepath.replace('.pcap', '_plot-ip-dst' + file_ending)
  688. plt.savefig(out, dpi=500)
  689. return out
  690. def plot_interval_statistics(queryOutput, title, xLabel, yLabel, file_ending: str):
  691. plt.gcf().clear()
  692. graphx, graphy = [], []
  693. for row in queryOutput:
  694. graphx.append(row[0])
  695. graphy.append(row[1])
  696. plt.autoscale(enable=True, axis='both')
  697. plt.title(title)
  698. plt.xlabel(xLabel)
  699. plt.ylabel(yLabel)
  700. width = 0.5
  701. plt.xlim([0, len(graphx)])
  702. plt.grid(True)
  703. # timestamp on x-axis
  704. x = range(0, len(graphx))
  705. # limit the number of xticks
  706. plt.locator_params(axis='x', nbins=20)
  707. plt.bar(x, graphy, width, align='center', linewidth=1, color='red', edgecolor='red')
  708. out = self.pcap_filepath.replace('.pcap', '_plot-' + title + file_ending)
  709. plt.savefig(out, dpi=500)
  710. return out
  711. def plot_interval_pktCount(file_ending: str):
  712. queryOutput = self.stats_db._process_user_defined_query(
  713. "SELECT lastPktTimestamp, pktsCount FROM interval_statistics ORDER BY lastPktTimestamp")
  714. title = "Packet Rate"
  715. xLabel = "Time Interval"
  716. yLabel = "Number of Packets"
  717. if queryOutput:
  718. return plot_interval_statistics(queryOutput, title, xLabel, yLabel, file_ending)
  719. def plot_interval_ip_src_ent(file_ending: str):
  720. queryOutput = self.stats_db._process_user_defined_query(
  721. "SELECT lastPktTimestamp, ipSrcEntropy FROM interval_statistics ORDER BY lastPktTimestamp")
  722. title = "Source IP Entropy"
  723. xLabel = "Time Interval"
  724. yLabel = "Entropy"
  725. if queryOutput:
  726. return plot_interval_statistics(queryOutput, title, xLabel, yLabel, file_ending)
  727. def plot_interval_ip_dst_ent(file_ending: str):
  728. queryOutput = self.stats_db._process_user_defined_query(
  729. "SELECT lastPktTimestamp, ipDstEntropy FROM interval_statistics ORDER BY lastPktTimestamp")
  730. title = "Destination IP Entropy"
  731. xLabel = "Time Interval"
  732. yLabel = "Entropy"
  733. if queryOutput:
  734. return plot_interval_statistics(queryOutput, title, xLabel, yLabel, file_ending)
  735. def plot_interval_new_ip(file_ending: str):
  736. queryOutput = self.stats_db._process_user_defined_query(
  737. "SELECT lastPktTimestamp, newIPCount FROM interval_statistics ORDER BY lastPktTimestamp")
  738. title = "IP Novelty Distribution"
  739. xLabel = "Time Interval"
  740. yLabel = "Novel values count"
  741. if queryOutput:
  742. return plot_interval_statistics(queryOutput, title, xLabel, yLabel, file_ending)
  743. def plot_interval_new_port(file_ending: str):
  744. queryOutput = self.stats_db._process_user_defined_query(
  745. "SELECT lastPktTimestamp, newPortCount FROM interval_statistics ORDER BY lastPktTimestamp")
  746. title = "Port Novelty Distribution"
  747. xLabel = "Time Interval"
  748. yLabel = "Novel values count"
  749. if queryOutput:
  750. return plot_interval_statistics(queryOutput, title, xLabel, yLabel, file_ending)
  751. def plot_interval_new_ttl(file_ending: str):
  752. queryOutput = self.stats_db._process_user_defined_query(
  753. "SELECT lastPktTimestamp, newTTLCount FROM interval_statistics ORDER BY lastPktTimestamp")
  754. title = "TTL Novelty Distribution"
  755. xLabel = "Time Interval"
  756. yLabel = "Novel values count"
  757. if queryOutput:
  758. return plot_interval_statistics(queryOutput, title, xLabel, yLabel, file_ending)
  759. def plot_interval_new_tos(file_ending: str):
  760. queryOutput = self.stats_db._process_user_defined_query(
  761. "SELECT lastPktTimestamp, newToSCount FROM interval_statistics ORDER BY lastPktTimestamp")
  762. title = "ToS Novelty Distribution"
  763. xLabel = "Time Interval"
  764. yLabel = "Novel values count"
  765. if queryOutput:
  766. return plot_interval_statistics(queryOutput, title, xLabel, yLabel, file_ending)
  767. def plot_interval_new_win_size(file_ending: str):
  768. queryOutput = self.stats_db._process_user_defined_query(
  769. "SELECT lastPktTimestamp, newWinSizeCount FROM interval_statistics ORDER BY lastPktTimestamp")
  770. title = "Window Size Novelty Distribution"
  771. xLabel = "Time Interval"
  772. yLabel = "Novel values count"
  773. if queryOutput:
  774. return plot_interval_statistics(queryOutput, title, xLabel, yLabel, file_ending)
  775. def plot_interval_new_mss(file_ending: str):
  776. queryOutput = self.stats_db._process_user_defined_query(
  777. "SELECT lastPktTimestamp, newMSSCount FROM interval_statistics ORDER BY lastPktTimestamp")
  778. title = "MSS Novelty Distribution"
  779. xLabel = "Time Interval"
  780. yLabel = "Novel values count"
  781. if queryOutput:
  782. return plot_interval_statistics(queryOutput, title, xLabel, yLabel, file_ending)
  783. def plot_interval_ip_dst_cum_ent(file_ending: str):
  784. plt.gcf().clear()
  785. result = self.stats_db._process_user_defined_query(
  786. "SELECT lastPktTimestamp, ipDstCumEntropy FROM interval_statistics ORDER BY lastPktTimestamp")
  787. graphx, graphy = [], []
  788. for row in result:
  789. graphx.append(row[0])
  790. graphy.append(row[1])
  791. # If entropy was not calculated do not plot the graph
  792. if graphy[0] != -1:
  793. plt.autoscale(enable=True, axis='both')
  794. plt.title("Destination IP Cumulative Entropy")
  795. # plt.xlabel('Timestamp')
  796. plt.xlabel('Time Interval')
  797. plt.ylabel('Entropy')
  798. plt.xlim([0, len(graphx)])
  799. plt.grid(True)
  800. # timestamp on x-axis
  801. x = range(0, len(graphx))
  802. # my_xticks = graphx
  803. # plt.xticks(x, my_xticks, rotation='vertical', fontsize=5)
  804. # plt.tight_layout()
  805. # limit the number of xticks
  806. plt.locator_params(axis='x', nbins=20)
  807. plt.plot(x, graphy, 'r')
  808. out = self.pcap_filepath.replace('.pcap', '_plot-interval-ip-dst-cum-ent' + file_ending)
  809. plt.savefig(out, dpi=500)
  810. return out
  811. def plot_interval_ip_src_cum_ent(file_ending: str):
  812. plt.gcf().clear()
  813. result = self.stats_db._process_user_defined_query(
  814. "SELECT lastPktTimestamp, ipSrcCumEntropy FROM interval_statistics ORDER BY lastPktTimestamp")
  815. graphx, graphy = [], []
  816. for row in result:
  817. graphx.append(row[0])
  818. graphy.append(row[1])
  819. # If entropy was not calculated do not plot the graph
  820. if graphy[0] != -1:
  821. plt.autoscale(enable=True, axis='both')
  822. plt.title("Source IP Cumulative Entropy")
  823. # plt.xlabel('Timestamp')
  824. plt.xlabel('Time Interval')
  825. plt.ylabel('Entropy')
  826. plt.xlim([0, len(graphx)])
  827. plt.grid(True)
  828. # timestamp on x-axis
  829. x = range(0, len(graphx))
  830. # my_xticks = graphx
  831. # plt.xticks(x, my_xticks, rotation='vertical', fontsize=5)
  832. # plt.tight_layout()
  833. # limit the number of xticks
  834. plt.locator_params(axis='x', nbins=20)
  835. plt.plot(x, graphy, 'r')
  836. out = self.pcap_filepath.replace('.pcap', '_plot-interval-ip-src-cum-ent' + file_ending)
  837. plt.savefig(out, dpi=500)
  838. return out
  839. ttl_out_path = plot_ttl('.' + format)
  840. mss_out_path = plot_mss('.' + format)
  841. win_out_path = plot_win('.' + format)
  842. protocol_out_path = plot_protocol('.' + format)
  843. plot_interval_pktCount = plot_interval_pktCount('.' + format)
  844. if entropy:
  845. plot_interval_ip_src_ent = plot_interval_ip_src_ent('.' + format)
  846. plot_interval_ip_dst_ent = plot_interval_ip_dst_ent('.' + format)
  847. plot_interval_ip_src_cum_ent = plot_interval_ip_src_cum_ent('.' + format)
  848. plot_interval_ip_dst_cum_ent = plot_interval_ip_dst_cum_ent('.' + format)
  849. plot_interval_new_ip = plot_interval_new_ip('.' + format)
  850. plot_interval_new_port = plot_interval_new_port('.' + format)
  851. plot_interval_new_ttl = plot_interval_new_ttl('.' + format)
  852. plot_interval_new_tos = plot_interval_new_tos('.' + format)
  853. plot_interval_new_win_size = plot_interval_new_win_size('.' + format)
  854. plot_interval_new_mss = plot_interval_new_mss('.' + format)
  855. ## Time consuming plot
  856. # port_out_path = plot_port('.' + format)
  857. ## Not drawable for too many IPs
  858. # ip_src_out_path = plot_ip_src('.' + format)
  859. # ip_dst_out_path = plot_ip_dst('.' + format)
  860. print("Saved plots in the input PCAP directory.")