3
0

Statistics.py 43 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963
  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_statistics_database(self):
  478. """
  479. :return: A reference to the statistics database object
  480. """
  481. return self.stats_db
  482. def process_db_query(self, query_string_in: str, print_results: bool = False):
  483. """
  484. Executes a string identified previously as a query. This can be a standard SQL SELECT/INSERT query or a named
  485. query.
  486. :param query_string_in: The query to be processed
  487. :param print_results: Indicates whether the results should be printed to terminal
  488. :return: The result of the query
  489. """
  490. return self.stats_db.process_db_query(query_string_in, print_results)
  491. def is_query(self, value: str):
  492. """
  493. Checks whether the given string is a standard SQL query (SELECT, INSERT) or a named query.
  494. :param value: The string to be checked
  495. :return: True if the string is recognized as a query, otherwise False.
  496. """
  497. if not isinstance(value, str):
  498. return False
  499. else:
  500. return (any(x in value.lower().strip() for x in self.stats_db.get_all_named_query_keywords()) or
  501. any(x in value.lower().strip() for x in self.stats_db.get_all_sql_query_keywords()))
  502. def calculate_standard_deviation(self, lst):
  503. """
  504. Calculates the standard deviation of a list of numbers.
  505. :param lst: The list of numbers to calculate its SD.
  506. """
  507. num_items = len(lst)
  508. mean = sum(lst) / num_items
  509. differences = [x - mean for x in lst]
  510. sq_differences = [d ** 2 for d in differences]
  511. ssd = sum(sq_differences)
  512. variance = ssd / num_items
  513. sd = sqrt(variance)
  514. return sd
  515. def plot_statistics(self, format: str = 'pdf'): #'png'
  516. """
  517. Plots the statistics associated with the dataset.
  518. :param format: The format to be used to save the statistics diagrams.
  519. """
  520. def plot_distribution(queryOutput, title, xLabel, yLabel, file_ending: str):
  521. plt.gcf().clear()
  522. graphx, graphy = [], []
  523. for row in queryOutput:
  524. graphx.append(row[0])
  525. graphy.append(row[1])
  526. plt.autoscale(enable=True, axis='both')
  527. plt.title(title)
  528. plt.xlabel(xLabel)
  529. plt.ylabel(yLabel)
  530. width = 0.1
  531. plt.xlim([0, max(graphx)])
  532. plt.grid(True)
  533. plt.bar(graphx, graphy, width, align='center', linewidth=1, color='red', edgecolor='red')
  534. out = self.pcap_filepath.replace('.pcap', '_plot-' + title + file_ending)
  535. plt.savefig(out,dpi=500)
  536. return out
  537. def plot_ttl(file_ending: str):
  538. queryOutput = self.stats_db._process_user_defined_query(
  539. "SELECT ttlValue, SUM(ttlCount) FROM ip_ttl GROUP BY ttlValue")
  540. title = "TTL Distribution"
  541. xLabel = "TTL Value"
  542. yLabel = "Number of Packets"
  543. if queryOutput:
  544. return plot_distribution(queryOutput, title, xLabel, yLabel, file_ending)
  545. def plot_mss(file_ending: str):
  546. queryOutput = self.stats_db._process_user_defined_query(
  547. "SELECT mssValue, SUM(mssCount) FROM tcp_mss GROUP BY mssValue")
  548. title = "MSS Distribution"
  549. xLabel = "MSS Value"
  550. yLabel = "Number of Packets"
  551. if queryOutput:
  552. return plot_distribution(queryOutput, title, xLabel, yLabel, file_ending)
  553. def plot_win(file_ending: str):
  554. queryOutput = self.stats_db._process_user_defined_query(
  555. "SELECT winSize, SUM(winCount) FROM tcp_win GROUP BY winSize")
  556. title = "Window Size Distribution"
  557. xLabel = "Window Size"
  558. yLabel = "Number of Packets"
  559. if queryOutput:
  560. return plot_distribution(queryOutput, title, xLabel, yLabel, file_ending)
  561. def plot_protocol(file_ending: str):
  562. plt.gcf().clear()
  563. result = self.stats_db._process_user_defined_query(
  564. "SELECT protocolName, SUM(protocolCount) FROM ip_protocols GROUP BY protocolName")
  565. if (result):
  566. graphx, graphy = [], []
  567. for row in result:
  568. graphx.append(row[0])
  569. graphy.append(row[1])
  570. plt.autoscale(enable=True, axis='both')
  571. plt.title("Protocols Distribution")
  572. plt.xlabel('Protocols')
  573. plt.ylabel('Number of Packets')
  574. width = 0.1
  575. plt.xlim([0, len(graphx)])
  576. plt.grid(True)
  577. # Protocols' names on x-axis
  578. x = range(0,len(graphx))
  579. my_xticks = graphx
  580. plt.xticks(x, my_xticks)
  581. plt.bar(x, graphy, width, align='center', linewidth=1, color='red', edgecolor='red')
  582. out = self.pcap_filepath.replace('.pcap', '_plot-protocol' + file_ending)
  583. plt.savefig(out,dpi=500)
  584. return out
  585. else:
  586. print("Error plot protocol: No protocol values found!")
  587. def plot_port(file_ending: str):
  588. plt.gcf().clear()
  589. result = self.stats_db._process_user_defined_query(
  590. "SELECT portNumber, SUM(portCount) FROM ip_ports GROUP BY portNumber")
  591. graphx, graphy = [], []
  592. for row in result:
  593. graphx.append(row[0])
  594. graphy.append(row[1])
  595. plt.autoscale(enable=True, axis='both')
  596. plt.title("Ports Distribution")
  597. plt.xlabel('Ports Numbers')
  598. plt.ylabel('Number of Packets')
  599. width = 0.1
  600. plt.xlim([0, max(graphx)])
  601. plt.grid(True)
  602. plt.bar(graphx, graphy, width, align='center', linewidth=1, color='red', edgecolor='red')
  603. out = self.pcap_filepath.replace('.pcap', '_plot-port' + file_ending)
  604. plt.savefig(out,dpi=500)
  605. return out
  606. # This distribution is not drawable for big datasets
  607. def plot_ip_src(file_ending: str):
  608. plt.gcf().clear()
  609. result = self.stats_db._process_user_defined_query(
  610. "SELECT ipAddress, pktsSent FROM ip_statistics")
  611. graphx, graphy = [], []
  612. for row in result:
  613. graphx.append(row[0])
  614. graphy.append(row[1])
  615. plt.autoscale(enable=True, axis='both')
  616. plt.title("Source IP Distribution")
  617. plt.xlabel('Source IP')
  618. plt.ylabel('Number of Packets')
  619. width = 0.1
  620. plt.xlim([0, len(graphx)])
  621. plt.grid(True)
  622. # IPs on x-axis
  623. x = range(0, len(graphx))
  624. my_xticks = graphx
  625. plt.xticks(x, my_xticks, rotation='vertical', fontsize=5)
  626. plt.tight_layout()
  627. # limit the number of xticks
  628. plt.locator_params(axis='x', nbins=20)
  629. plt.bar(x, graphy, width, align='center', linewidth=1, color='red', edgecolor='red')
  630. out = self.pcap_filepath.replace('.pcap', '_plot-ip-src' + file_ending)
  631. plt.savefig(out, dpi=500)
  632. return out
  633. # This distribution is not drawable for big datasets
  634. def plot_ip_dst(file_ending: str):
  635. plt.gcf().clear()
  636. result = self.stats_db._process_user_defined_query(
  637. "SELECT ipAddress, pktsReceived FROM ip_statistics")
  638. graphx, graphy = [], []
  639. for row in result:
  640. graphx.append(row[0])
  641. graphy.append(row[1])
  642. plt.autoscale(enable=True, axis='both')
  643. plt.title("Destination IP Distribution")
  644. plt.xlabel('Destination IP')
  645. plt.ylabel('Number of Packets')
  646. width = 0.1
  647. plt.xlim([0, len(graphx)])
  648. plt.grid(True)
  649. # IPs on x-axis
  650. x = range(0, len(graphx))
  651. my_xticks = graphx
  652. plt.xticks(x, my_xticks, rotation='vertical', fontsize=5)
  653. plt.tight_layout()
  654. # limit the number of xticks
  655. plt.locator_params(axis='x', nbins=20)
  656. plt.bar(x, graphy, width, align='center', linewidth=1, color='red', edgecolor='red')
  657. out = self.pcap_filepath.replace('.pcap', '_plot-ip-dst' + file_ending)
  658. plt.savefig(out, dpi=500)
  659. return out
  660. def plot_interval_statistics(queryOutput, title, xLabel, yLabel, file_ending: str):
  661. plt.gcf().clear()
  662. graphx, graphy = [], []
  663. for row in queryOutput:
  664. graphx.append(row[0])
  665. graphy.append(row[1])
  666. plt.autoscale(enable=True, axis='both')
  667. plt.title(title)
  668. plt.xlabel(xLabel)
  669. plt.ylabel(yLabel)
  670. width = 0.5
  671. plt.xlim([0, len(graphx)])
  672. plt.grid(True)
  673. # timestamp on x-axis
  674. x = range(0, len(graphx))
  675. # limit the number of xticks
  676. plt.locator_params(axis='x', nbins=20)
  677. plt.bar(x, graphy, width, align='center', linewidth=1, color='red', edgecolor='red')
  678. out = self.pcap_filepath.replace('.pcap', '_plot-' + title + file_ending)
  679. plt.savefig(out, dpi=500)
  680. return out
  681. def plot_interval_pktCount(file_ending: str):
  682. queryOutput = self.stats_db._process_user_defined_query(
  683. "SELECT lastPktTimestamp, pktsCount FROM interval_statistics ORDER BY lastPktTimestamp")
  684. title = "Packet Rate"
  685. xLabel = "Time Interval"
  686. yLabel = "Number of Packets"
  687. if queryOutput:
  688. return plot_interval_statistics(queryOutput, title, xLabel, yLabel, file_ending)
  689. def plot_interval_ip_src_ent(file_ending: str):
  690. queryOutput = self.stats_db._process_user_defined_query(
  691. "SELECT lastPktTimestamp, ipSrcEntropy FROM interval_statistics ORDER BY lastPktTimestamp")
  692. title = "Source IP Entropy"
  693. xLabel = "Time Interval"
  694. yLabel = "Entropy"
  695. if queryOutput:
  696. return plot_interval_statistics(queryOutput, title, xLabel, yLabel, file_ending)
  697. def plot_interval_ip_dst_ent(file_ending: str):
  698. queryOutput = self.stats_db._process_user_defined_query(
  699. "SELECT lastPktTimestamp, ipDstEntropy FROM interval_statistics ORDER BY lastPktTimestamp")
  700. title = "Destination IP Entropy"
  701. xLabel = "Time Interval"
  702. yLabel = "Entropy"
  703. if queryOutput:
  704. return plot_interval_statistics(queryOutput, title, xLabel, yLabel, file_ending)
  705. def plot_interval_new_ip(file_ending: str):
  706. queryOutput = self.stats_db._process_user_defined_query(
  707. "SELECT lastPktTimestamp, newIPCount FROM interval_statistics ORDER BY lastPktTimestamp")
  708. title = "IP Novelty Distribution"
  709. xLabel = "Time Interval"
  710. yLabel = "Novel values count"
  711. if queryOutput:
  712. return plot_interval_statistics(queryOutput, title, xLabel, yLabel, file_ending)
  713. def plot_interval_new_port(file_ending: str):
  714. queryOutput = self.stats_db._process_user_defined_query(
  715. "SELECT lastPktTimestamp, newPortCount FROM interval_statistics ORDER BY lastPktTimestamp")
  716. title = "Port Novelty Distribution"
  717. xLabel = "Time Interval"
  718. yLabel = "Novel values count"
  719. if queryOutput:
  720. return plot_interval_statistics(queryOutput, title, xLabel, yLabel, file_ending)
  721. def plot_interval_new_ttl(file_ending: str):
  722. queryOutput = self.stats_db._process_user_defined_query(
  723. "SELECT lastPktTimestamp, newTTLCount FROM interval_statistics ORDER BY lastPktTimestamp")
  724. title = "TTL Novelty Distribution"
  725. xLabel = "Time Interval"
  726. yLabel = "Novel values count"
  727. if queryOutput:
  728. return plot_interval_statistics(queryOutput, title, xLabel, yLabel, file_ending)
  729. def plot_interval_new_tos(file_ending: str):
  730. queryOutput = self.stats_db._process_user_defined_query(
  731. "SELECT lastPktTimestamp, newToSCount FROM interval_statistics ORDER BY lastPktTimestamp")
  732. title = "ToS Novelty Distribution"
  733. xLabel = "Time Interval"
  734. yLabel = "Novel values count"
  735. if queryOutput:
  736. return plot_interval_statistics(queryOutput, title, xLabel, yLabel, file_ending)
  737. def plot_interval_new_win_size(file_ending: str):
  738. queryOutput = self.stats_db._process_user_defined_query(
  739. "SELECT lastPktTimestamp, newWinSizeCount FROM interval_statistics ORDER BY lastPktTimestamp")
  740. title = "Window Size Novelty Distribution"
  741. xLabel = "Time Interval"
  742. yLabel = "Novel values count"
  743. if queryOutput:
  744. return plot_interval_statistics(queryOutput, title, xLabel, yLabel, file_ending)
  745. def plot_interval_new_mss(file_ending: str):
  746. queryOutput = self.stats_db._process_user_defined_query(
  747. "SELECT lastPktTimestamp, newMSSCount FROM interval_statistics ORDER BY lastPktTimestamp")
  748. title = "MSS Novelty Distribution"
  749. xLabel = "Time Interval"
  750. yLabel = "Novel values count"
  751. if queryOutput:
  752. return plot_interval_statistics(queryOutput, title, xLabel, yLabel, file_ending)
  753. def plot_interval_ip_dst_cum_ent(file_ending: str):
  754. plt.gcf().clear()
  755. result = self.stats_db._process_user_defined_query(
  756. "SELECT lastPktTimestamp, ipDstCumEntropy FROM interval_statistics ORDER BY lastPktTimestamp")
  757. graphx, graphy = [], []
  758. for row in result:
  759. graphx.append(row[0])
  760. graphy.append(row[1])
  761. # If entropy was not calculated do not plot the graph
  762. if graphy[0] != -1:
  763. plt.autoscale(enable=True, axis='both')
  764. plt.title("Destination IP Cumulative Entropy")
  765. # plt.xlabel('Timestamp')
  766. plt.xlabel('Time Interval')
  767. plt.ylabel('Entropy')
  768. plt.xlim([0, len(graphx)])
  769. plt.grid(True)
  770. # timestamp on x-axis
  771. x = range(0, len(graphx))
  772. # my_xticks = graphx
  773. # plt.xticks(x, my_xticks, rotation='vertical', fontsize=5)
  774. # plt.tight_layout()
  775. # limit the number of xticks
  776. plt.locator_params(axis='x', nbins=20)
  777. plt.plot(x, graphy, 'r')
  778. out = self.pcap_filepath.replace('.pcap', '_plot-interval-ip-dst-cum-ent' + file_ending)
  779. plt.savefig(out, dpi=500)
  780. return out
  781. def plot_interval_ip_src_cum_ent(file_ending: str):
  782. plt.gcf().clear()
  783. result = self.stats_db._process_user_defined_query(
  784. "SELECT lastPktTimestamp, ipSrcCumEntropy FROM interval_statistics ORDER BY lastPktTimestamp")
  785. graphx, graphy = [], []
  786. for row in result:
  787. graphx.append(row[0])
  788. graphy.append(row[1])
  789. # If entropy was not calculated do not plot the graph
  790. if graphy[0] != -1:
  791. plt.autoscale(enable=True, axis='both')
  792. plt.title("Source IP Cumulative Entropy")
  793. # plt.xlabel('Timestamp')
  794. plt.xlabel('Time Interval')
  795. plt.ylabel('Entropy')
  796. plt.xlim([0, len(graphx)])
  797. plt.grid(True)
  798. # timestamp on x-axis
  799. x = range(0, len(graphx))
  800. # my_xticks = graphx
  801. # plt.xticks(x, my_xticks, rotation='vertical', fontsize=5)
  802. # plt.tight_layout()
  803. # limit the number of xticks
  804. plt.locator_params(axis='x', nbins=20)
  805. plt.plot(x, graphy, 'r')
  806. out = self.pcap_filepath.replace('.pcap', '_plot-interval-ip-src-cum-ent' + file_ending)
  807. plt.savefig(out, dpi=500)
  808. return out
  809. ttl_out_path = plot_ttl('.' + format)
  810. mss_out_path = plot_mss('.' + format)
  811. win_out_path = plot_win('.' + format)
  812. protocol_out_path = plot_protocol('.' + format)
  813. plot_interval_pktCount = plot_interval_pktCount('.' + format)
  814. plot_interval_ip_src_ent = plot_interval_ip_src_ent('.' + format)
  815. plot_interval_ip_dst_ent = plot_interval_ip_dst_ent('.' + format)
  816. plot_interval_ip_src_cum_ent = plot_interval_ip_src_cum_ent('.' + format)
  817. plot_interval_ip_dst_cum_ent = plot_interval_ip_dst_cum_ent('.' + format)
  818. plot_interval_new_ip = plot_interval_new_ip('.' + format)
  819. plot_interval_new_port = plot_interval_new_port('.' + format)
  820. plot_interval_new_ttl = plot_interval_new_ttl('.' + format)
  821. plot_interval_new_tos = plot_interval_new_tos('.' + format)
  822. plot_interval_new_win_size = plot_interval_new_win_size('.' + format)
  823. plot_interval_new_mss = plot_interval_new_mss('.' + format)
  824. ## Time consuming plot
  825. # port_out_path = plot_port('.' + format)
  826. ## Not drawable for too many IPs
  827. # ip_src_out_path = plot_ip_src('.' + format)
  828. # ip_dst_out_path = plot_ip_dst('.' + format)
  829. print("Saved plots in the input PCAP directory.")