Statistics.py 42 KB

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