Statistics.py 43 KB

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