Statistics.py 58 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296
  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. from ID2TLib.IPv4 import IPAddress
  12. class Statistics:
  13. def __init__(self, pcap_file: PcapFile):
  14. """
  15. Creates a new Statistics object.
  16. :param pcap_file: A reference to the PcapFile object
  17. """
  18. # Fields
  19. self.pcap_filepath = pcap_file.pcap_file_path
  20. self.pcap_proc = None
  21. self.do_extra_tests = False
  22. # Create folder for statistics database if required
  23. self.path_db = pcap_file.get_db_path()
  24. path_dir = os.path.dirname(self.path_db)
  25. if not os.path.isdir(path_dir):
  26. os.makedirs(path_dir)
  27. # Class instances
  28. self.stats_db = StatsDatabase(self.path_db)
  29. def load_pcap_statistics(self, flag_write_file: bool, flag_recalculate_stats: bool, flag_print_statistics: bool):
  30. """
  31. Loads the PCAP statistics for the file specified by pcap_filepath. If the database is not existing yet, the
  32. statistics are calculated by the PCAP file processor and saved into the newly created database. Otherwise the
  33. statistics are gathered directly from the existing database.
  34. :param flag_write_file: Indicates whether the statistics should be written addiotionally into a text file (True)
  35. or not (False)
  36. :param flag_recalculate_stats: Indicates whether eventually existing statistics should be recalculated
  37. :param flag_print_statistics: Indicates whether the gathered basic statistics should be printed to the terminal
  38. """
  39. # Load pcap and get loading time
  40. time_start = time.clock()
  41. # Inform user about recalculation of statistics and its reason
  42. if flag_recalculate_stats:
  43. print("Flag -r/--recalculate found. Recalculating statistics.")
  44. # Recalculate statistics if database does not exist OR param -r/--recalculate is provided
  45. if (not self.stats_db.get_db_exists()) or flag_recalculate_stats:
  46. self.pcap_proc = pr.pcap_processor(self.pcap_filepath, str(self.do_extra_tests))
  47. self.pcap_proc.collect_statistics()
  48. self.pcap_proc.write_to_database(self.path_db)
  49. outstring_datasource = "by PCAP file processor."
  50. else:
  51. outstring_datasource = "from statistics database."
  52. # Load statistics from database
  53. self.file_info = self.stats_db.get_file_info()
  54. time_end = time.clock()
  55. print("Loaded file statistics in " + str(time_end - time_start)[:4] + " sec " + outstring_datasource)
  56. # Write statistics if param -e/--export provided
  57. if flag_write_file:
  58. self.write_statistics_to_file()
  59. # Print statistics if param -s/--statistics provided
  60. if flag_print_statistics:
  61. self.print_statistics()
  62. def get_file_information(self):
  63. """
  64. Returns a list of tuples, each containing a information of the file.
  65. :return: a list of tuples, each consisting of (description, value, unit), where unit is optional.
  66. """
  67. return [("Pcap file", self.pcap_filepath),
  68. ("Packets", self.get_packet_count(), "packets"),
  69. ("Capture length", self.get_capture_duration(), "seconds"),
  70. ("Capture start", self.get_pcap_timestamp_start()),
  71. ("Capture end", self.get_pcap_timestamp_end())]
  72. def get_general_file_statistics(self):
  73. """
  74. Returns a list of tuples, each containing a file statistic.
  75. :return: a list of tuples, each consisting of (description, value, unit).
  76. """
  77. return [("Avg. packet rate", self.file_info['avgPacketRate'], "packets/sec"),
  78. ("Avg. packet size", self.file_info['avgPacketSize'], "kbytes"),
  79. ("Avg. packets sent", self.file_info['avgPacketsSentPerHost'], "packets"),
  80. ("Avg. bandwidth in", self.file_info['avgBandwidthIn'], "kbit/s"),
  81. ("Avg. bandwidth out", self.file_info['avgBandwidthOut'], "kbit/s")]
  82. @staticmethod
  83. def write_list(desc_val_unit_list, func, line_ending="\n"):
  84. """
  85. Takes a list of tuples (statistic name, statistic value, unit) as input, generates a string of these three values
  86. and applies the function func on this string.
  87. Before generating the string, it identifies text containing a float number, casts the string to a
  88. float and rounds the value to two decimal digits.
  89. :param desc_val_unit_list: The list of tuples consisting of (description, value, unit)
  90. :param func: The function to be applied to each generated string
  91. :param line_ending: The formatting string to be applied at the end of each string
  92. """
  93. for entry in desc_val_unit_list:
  94. # Convert text containing float into float
  95. (description, value) = entry[0:2]
  96. if isinstance(value, str) and "." in value:
  97. try:
  98. value = float(value)
  99. except ValueError:
  100. pass # do nothing -> value was not a float
  101. # round float
  102. if isinstance(value, float):
  103. value = round(value, 4)
  104. # write into file
  105. if len(entry) == 3:
  106. unit = entry[2]
  107. func(description + ":\t" + str(value) + " " + unit + line_ending)
  108. else:
  109. func(description + ":\t" + str(value) + line_ending)
  110. def print_statistics(self):
  111. """
  112. Prints the basic file statistics to the terminal.
  113. """
  114. print("\nPCAP FILE INFORMATION ------------------------------")
  115. Statistics.write_list(self.get_file_information(), print, "")
  116. print("\nGENERAL FILE STATISTICS ----------------------------")
  117. Statistics.write_list(self.get_general_file_statistics(), print, "")
  118. print("\n")
  119. def calculate_entropy(self, frequency:list, normalized:bool = False):
  120. """
  121. Calculates entropy and normalized entropy of list of elements that have specific frequency
  122. :param frequency: The frequency of the elements.
  123. :param normalized: Calculate normalized entropy
  124. :return: entropy or (entropy, normalized entropy)
  125. """
  126. entropy, normalizedEnt, n = 0, 0, 0
  127. sumFreq = sum(frequency)
  128. for i, x in enumerate(frequency):
  129. p_x = float(frequency[i] / sumFreq)
  130. if p_x > 0:
  131. n += 1
  132. entropy += - p_x * log(p_x, 2)
  133. if normalized:
  134. if log(n)>0:
  135. normalizedEnt = entropy/log(n, 2)
  136. return entropy, normalizedEnt
  137. else:
  138. return entropy
  139. def calculate_complement_packet_rates(self, pps):
  140. """
  141. Calculates the complement packet rates of the background traffic packet rates for each interval.
  142. Then normalize it to maximum boundary, which is the input parameter pps
  143. :return: normalized packet rates for each time interval.
  144. """
  145. result = self.process_db_query(
  146. "SELECT lastPktTimestamp,pktsCount FROM interval_statistics ORDER BY lastPktTimestamp")
  147. # print(result)
  148. bg_interval_pps = []
  149. complement_interval_pps = []
  150. intervalsSum = 0
  151. if result:
  152. # Get the interval in seconds
  153. for i, row in enumerate(result):
  154. if i < len(result) - 1:
  155. intervalsSum += ceil((int(result[i + 1][0]) * 10 ** -6) - (int(row[0]) * 10 ** -6))
  156. interval = intervalsSum / (len(result) - 1)
  157. # Convert timestamp from micro to seconds, convert packet rate "per interval" to "per second"
  158. for row in result:
  159. bg_interval_pps.append((int(row[0]) * 10 ** -6, int(row[1] / interval)))
  160. # Find max PPS
  161. maxPPS = max(bg_interval_pps, key=itemgetter(1))[1]
  162. for row in bg_interval_pps:
  163. complement_interval_pps.append((row[0], int(pps * (maxPPS - row[1]) / maxPPS)))
  164. return complement_interval_pps
  165. def get_tests_statistics(self):
  166. """
  167. Writes the calculated basic defects tests statistics into a file.
  168. """
  169. # self.stats_db._process_user_defined_query output is list of tuples, thus, we ned [0][0] to access data
  170. def count_frequncy(valuesList):
  171. values, frequency = [] , []
  172. for x in valuesList:
  173. if x in values:
  174. frequency[values.index(x)] += 1
  175. else:
  176. values.append(x)
  177. frequency.append(1)
  178. return values, frequency
  179. ####### Payload Tests #######
  180. sumPayloadCount = self.stats_db._process_user_defined_query("SELECT sum(payloadCount) FROM interval_statistics")
  181. pktCount = self.stats_db._process_user_defined_query("SELECT packetCount FROM file_statistics")
  182. if sumPayloadCount and pktCount:
  183. payloadRatio=0
  184. if(pktCount[0][0]!=0):
  185. payloadRatio = float(sumPayloadCount[0][0] / pktCount[0][0] * 100)
  186. else:
  187. payloadRatio = -1
  188. ####### TCP checksum Tests #######
  189. incorrectChecksumCount = self.stats_db._process_user_defined_query("SELECT sum(incorrectTCPChecksumCount) FROM interval_statistics")
  190. correctChecksumCount = self.stats_db._process_user_defined_query("SELECT avg(correctTCPChecksumCount) FROM interval_statistics")
  191. if incorrectChecksumCount and correctChecksumCount:
  192. incorrectChecksumRatio=0
  193. if(incorrectChecksumCount[0][0] + correctChecksumCount[0][0])!=0:
  194. incorrectChecksumRatio = float(incorrectChecksumCount[0][0] / (incorrectChecksumCount[0][0] + correctChecksumCount[0][0] ) * 100)
  195. else:
  196. incorrectChecksumRatio = -1
  197. ####### IP Src & Dst Tests #######
  198. result = self.stats_db._process_user_defined_query("SELECT ipAddress,pktsSent,pktsReceived FROM ip_statistics")
  199. data, srcFrequency, dstFrequency = [], [], []
  200. if result:
  201. for row in result:
  202. srcFrequency.append(row[1])
  203. dstFrequency.append(row[2])
  204. ipSrcEntropy, ipSrcNormEntropy = self.calculate_entropy(srcFrequency, True)
  205. ipDstEntropy, ipDstNormEntropy = self.calculate_entropy(dstFrequency, True)
  206. newIPCount = self.stats_db._process_user_defined_query("SELECT newIPCount FROM interval_statistics")
  207. ipNovelsPerInterval, ipNovelsPerIntervalFrequency = count_frequncy(newIPCount)
  208. ipNoveltyDistEntropy = self.calculate_entropy(ipNovelsPerIntervalFrequency)
  209. ####### Ports Tests #######
  210. port0Count = self.stats_db._process_user_defined_query("SELECT SUM(portCount) FROM ip_ports WHERE portNumber = 0")
  211. if not port0Count[0][0]:
  212. port0Count = 0
  213. else:
  214. port0Count = port0Count[0][0]
  215. reservedPortCount = self.stats_db._process_user_defined_query(
  216. "SELECT SUM(portCount) FROM ip_ports WHERE portNumber IN (100,114,1023,1024,49151,49152,65535)")# could be extended
  217. if not reservedPortCount[0][0]:
  218. reservedPortCount = 0
  219. else:
  220. reservedPortCount = reservedPortCount[0][0]
  221. ####### TTL Tests #######
  222. result = self.stats_db._process_user_defined_query("SELECT ttlValue,SUM(ttlCount) FROM ip_ttl GROUP BY ttlValue")
  223. data, frequency = [], []
  224. for row in result:
  225. frequency.append(row[1])
  226. ttlEntropy, ttlNormEntropy = self.calculate_entropy(frequency,True)
  227. newTTLCount = self.stats_db._process_user_defined_query("SELECT newTTLCount FROM interval_statistics")
  228. ttlNovelsPerInterval, ttlNovelsPerIntervalFrequency = count_frequncy(newTTLCount)
  229. ttlNoveltyDistEntropy = self.calculate_entropy(ttlNovelsPerIntervalFrequency)
  230. ####### Window Size Tests #######
  231. result = self.stats_db._process_user_defined_query("SELECT winSize,SUM(winCount) FROM tcp_win GROUP BY winSize")
  232. data, frequency = [], []
  233. for row in result:
  234. frequency.append(row[1])
  235. winEntropy, winNormEntropy = self.calculate_entropy(frequency, True)
  236. newWinSizeCount = self.stats_db._process_user_defined_query("SELECT newWinSizeCount FROM interval_statistics")
  237. winNovelsPerInterval, winNovelsPerIntervalFrequency = count_frequncy(newWinSizeCount)
  238. winNoveltyDistEntropy = self.calculate_entropy(winNovelsPerIntervalFrequency)
  239. ####### ToS Tests #######
  240. result = self.stats_db._process_user_defined_query(
  241. "SELECT tosValue,SUM(tosCount) FROM ip_tos GROUP BY tosValue")
  242. data, frequency = [], []
  243. for row in result:
  244. frequency.append(row[1])
  245. tosEntropy, tosNormEntropy = self.calculate_entropy(frequency, True)
  246. newToSCount = self.stats_db._process_user_defined_query("SELECT newToSCount FROM interval_statistics")
  247. tosNovelsPerInterval, tosNovelsPerIntervalFrequency = count_frequncy(newToSCount)
  248. tosNoveltyDistEntropy = self.calculate_entropy(tosNovelsPerIntervalFrequency)
  249. ####### MSS Tests #######
  250. result = self.stats_db._process_user_defined_query(
  251. "SELECT mssValue,SUM(mssCount) FROM tcp_mss GROUP BY mssValue")
  252. data, frequency = [], []
  253. for row in result:
  254. frequency.append(row[1])
  255. mssEntropy, mssNormEntropy = self.calculate_entropy(frequency, True)
  256. newMSSCount = self.stats_db._process_user_defined_query("SELECT newMSSCount FROM interval_statistics")
  257. mssNovelsPerInterval, mssNovelsPerIntervalFrequency = count_frequncy(newMSSCount)
  258. mssNoveltyDistEntropy = self.calculate_entropy(mssNovelsPerIntervalFrequency)
  259. result = self.stats_db._process_user_defined_query("SELECT SUM(mssCount) FROM tcp_mss WHERE mssValue > 1460")
  260. # The most used MSS < 1460. Calculate the ratio of the values bigger that 1460.
  261. if not result[0][0]:
  262. result = 0
  263. else:
  264. result = result[0][0]
  265. bigMSS = (result / sum(frequency)) * 100
  266. output = []
  267. if self.do_extra_tests:
  268. output = [("Payload ratio", payloadRatio, "%"),
  269. ("Incorrect TCP checksum ratio", incorrectChecksumRatio, "%")]
  270. output = output + [("# IP addresses", sum([x[0] for x in newIPCount]), ""),
  271. ("IP Src Entropy", ipSrcEntropy, ""),
  272. ("IP Src Normalized Entropy", ipSrcNormEntropy, ""),
  273. ("IP Dst Entropy", ipDstEntropy, ""),
  274. ("IP Dst Normalized Entropy", ipDstNormEntropy, ""),
  275. ("IP Novelty Distribution Entropy", ipNoveltyDistEntropy, ""),
  276. ("# TTL values", sum([x[0] for x in newTTLCount]), ""),
  277. ("TTL Entropy", ttlEntropy, ""),
  278. ("TTL Normalized Entropy", ttlNormEntropy, ""),
  279. ("TTL Novelty Distribution Entropy", ttlNoveltyDistEntropy, ""),
  280. ("# WinSize values", sum([x[0] for x in newWinSizeCount]), ""),
  281. ("WinSize Entropy", winEntropy, ""),
  282. ("WinSize Normalized Entropy", winNormEntropy, ""),
  283. ("WinSize Novelty Distribution Entropy", winNoveltyDistEntropy, ""),
  284. ("# ToS values", sum([x[0] for x in newToSCount]), ""),
  285. ("ToS Entropy", tosEntropy, ""),
  286. ("ToS Normalized Entropy", tosNormEntropy, ""),
  287. ("ToS Novelty Distribution Entropy", tosNoveltyDistEntropy, ""),
  288. ("# MSS values", sum([x[0] for x in newMSSCount]), ""),
  289. ("MSS Entropy", mssEntropy, ""),
  290. ("MSS Normalized Entropy", mssNormEntropy, ""),
  291. ("MSS Novelty Distribution Entropy", mssNoveltyDistEntropy, ""),
  292. ("======================","","")]
  293. # Reasoning the statistics values
  294. if self.do_extra_tests:
  295. if payloadRatio > 80:
  296. output.append(("WARNING: Too high payload ratio", payloadRatio, "%."))
  297. if payloadRatio < 30:
  298. output.append(("WARNING: Too low payload ratio", payloadRatio, "% (Injecting attacks that are carried out in the packet payloads is not recommmanded)."))
  299. if incorrectChecksumRatio > 5:
  300. output.append(("WARNING: High incorrect TCP checksum ratio",incorrectChecksumRatio,"%."))
  301. if ipSrcNormEntropy > 0.65:
  302. output.append(("WARNING: High IP source normalized entropy",ipSrcNormEntropy,"."))
  303. if ipSrcNormEntropy < 0.2:
  304. output.append(("WARNING: Low IP source normalized entropy", ipSrcNormEntropy, "."))
  305. if ipDstNormEntropy > 0.65:
  306. output.append(("WARNING: High IP destination normalized entropy", ipDstNormEntropy, "."))
  307. if ipDstNormEntropy < 0.2:
  308. output.append(("WARNING: Low IP destination normalized entropy", ipDstNormEntropy, "."))
  309. if ttlNormEntropy > 0.65:
  310. output.append(("WARNING: High TTL normalized entropy", ttlNormEntropy, "."))
  311. if ttlNormEntropy < 0.2:
  312. output.append(("WARNING: Low TTL normalized entropy", ttlNormEntropy, "."))
  313. if ttlNoveltyDistEntropy < 1:
  314. output.append(("WARNING: Too low TTL novelty distribution entropy", ttlNoveltyDistEntropy,
  315. "(The distribution of the novel TTL values is suspicious)."))
  316. if winNormEntropy > 0.6:
  317. output.append(("WARNING: High Window Size normalized entropy", winNormEntropy, "."))
  318. if winNormEntropy < 0.1:
  319. output.append(("WARNING: Low Window Size normalized entropy", winNormEntropy, "."))
  320. if winNoveltyDistEntropy < 4:
  321. output.append(("WARNING: Low Window Size novelty distribution entropy", winNoveltyDistEntropy,
  322. "(The distribution of the novel Window Size values is suspicious)."))
  323. if tosNormEntropy > 0.4:
  324. output.append(("WARNING: High ToS normalized entropy", tosNormEntropy, "."))
  325. if tosNormEntropy < 0.1:
  326. output.append(("WARNING: Low ToS normalized entropy", tosNormEntropy, "."))
  327. if tosNoveltyDistEntropy < 0.5:
  328. output.append(("WARNING: Low ToS novelty distribution entropy", tosNoveltyDistEntropy,
  329. "(The distribution of the novel ToS values is suspicious)."))
  330. if mssNormEntropy > 0.4:
  331. output.append(("WARNING: High MSS normalized entropy", mssNormEntropy, "."))
  332. if mssNormEntropy < 0.1:
  333. output.append(("WARNING: Low MSS normalized entropy", mssNormEntropy, "."))
  334. if mssNoveltyDistEntropy < 0.5:
  335. output.append(("WARNING: Low MSS novelty distribution entropy", mssNoveltyDistEntropy,
  336. "(The distribution of the novel MSS values is suspicious)."))
  337. if bigMSS > 50:
  338. output.append(("WARNING: High ratio of MSS > 1460", bigMSS, "% (High fragmentation rate in Ethernet)."))
  339. if port0Count > 0:
  340. output.append(("WARNING: Port number 0 is used in ",port0Count,"packets (awkward-looking port)."))
  341. if reservedPortCount > 0:
  342. output.append(("WARNING: Reserved port numbers are used in ",reservedPortCount,"packets (uncommonly-used ports)."))
  343. return output
  344. def write_statistics_to_file(self):
  345. """
  346. Writes the calculated basic statistics into a file.
  347. """
  348. def _write_header(title: str):
  349. """
  350. Writes the section header into the open file.
  351. :param title: The section title
  352. """
  353. target.write("====================== \n")
  354. target.write(title + " \n")
  355. target.write("====================== \n")
  356. target = open(self.pcap_filepath + ".stat", 'w')
  357. target.truncate()
  358. _write_header("PCAP file information")
  359. Statistics.write_list(self.get_file_information(), target.write)
  360. _write_header("General statistics")
  361. Statistics.write_list(self.get_general_file_statistics(), target.write)
  362. _write_header("Tests statistics")
  363. Statistics.write_list(self.get_tests_statistics(), target.write)
  364. target.close()
  365. def get_capture_duration(self):
  366. """
  367. :return: The duration of the capture in seconds
  368. """
  369. return self.file_info['captureDuration']
  370. def get_pcap_timestamp_start(self):
  371. """
  372. :return: The timestamp of the first packet in the PCAP file
  373. """
  374. return self.file_info['timestampFirstPacket']
  375. def get_pcap_timestamp_end(self):
  376. """
  377. :return: The timestamp of the last packet in the PCAP file
  378. """
  379. return self.file_info['timestampLastPacket']
  380. def get_pps_sent(self, ip_address: str):
  381. """
  382. Calculates the sent packets per seconds for a given IP address.
  383. :param ip_address: The IP address whose packets per second should be calculated
  384. :return: The sent packets per seconds for the given IP address
  385. """
  386. packets_sent = self.stats_db.process_db_query("SELECT pktsSent from ip_statistics WHERE ipAddress=?", False,
  387. (ip_address,))
  388. capture_duration = float(self.get_capture_duration())
  389. return int(float(packets_sent) / capture_duration)
  390. def get_pps_received(self, ip_address: str):
  391. """
  392. Calculate the packets per second received for a given IP address.
  393. :param ip_address: The IP address used for the calculation
  394. :return: The number of packets per second received
  395. """
  396. packets_received = self.stats_db.process_db_query("SELECT pktsReceived FROM ip_statistics WHERE ipAddress=?",
  397. False,
  398. (ip_address,))
  399. capture_duration = float(self.get_capture_duration())
  400. return int(float(packets_received) / capture_duration)
  401. def get_packet_count(self):
  402. """
  403. :return: The number of packets in the loaded PCAP file
  404. """
  405. return self.file_info['packetCount']
  406. def get_most_used_ip_address(self):
  407. """
  408. :return: The IP address/addresses with the highest sum of packets sent and received
  409. """
  410. return self.process_db_query("most_used(ipAddress)")
  411. def get_ttl_distribution(self, ipAddress: str):
  412. result = self.process_db_query('SELECT ttlValue, ttlCount from ip_ttl WHERE ipAddress="' + ipAddress + '"')
  413. result_dict = {key: value for (key, value) in result}
  414. return result_dict
  415. def get_mss_distribution(self, ipAddress: str):
  416. result = self.process_db_query('SELECT mssValue, mssCount from tcp_mss WHERE ipAddress="' + ipAddress + '"')
  417. result_dict = {key: value for (key, value) in result}
  418. return result_dict
  419. def get_win_distribution(self, ipAddress: str):
  420. result = self.process_db_query('SELECT winSize, winCount from tcp_win WHERE ipAddress="' + ipAddress + '"')
  421. result_dict = {key: value for (key, value) in result}
  422. return result_dict
  423. def get_tos_distribution(self, ipAddress: str):
  424. result = self.process_db_query('SELECT tosValue, tosCount from ip_tos WHERE ipAddress="' + ipAddress + '"')
  425. result_dict = {key: value for (key, value) in result}
  426. return result_dict
  427. def get_random_ip_address(self, count: int = 1):
  428. """
  429. :param count: The number of IP addreses to return
  430. :return: A randomly chosen IP address from the dataset or iff param count is greater than one, a list of randomly
  431. chosen IP addresses
  432. """
  433. if count == 1:
  434. return self.process_db_query("random(all(ipAddress))")
  435. else:
  436. ip_address_list = []
  437. for i in range(0, count):
  438. ip_address_list.append(self.process_db_query("random(all(ipAddress))"))
  439. return ip_address_list
  440. def get_mac_address(self, ipAddress: str):
  441. """
  442. :return: The MAC address used in the dataset for the given IP address.
  443. """
  444. return self.process_db_query('macAddress(ipAddress=' + ipAddress + ")")
  445. def get_most_used_mss(self, ipAddress: str):
  446. """
  447. :param ipAddress: The IP address whose used MSS should be determined
  448. :return: The TCP MSS value used by the IP address, or if the IP addresses never specified a MSS,
  449. then None is returned
  450. """
  451. mss_value = self.process_db_query('SELECT mssValue from tcp_mss WHERE ipAddress="' + ipAddress + '" ORDER BY mssCount DESC LIMIT 1')
  452. if isinstance(mss_value, int):
  453. return mss_value
  454. else:
  455. return None
  456. def get_most_used_ttl(self, ipAddress: str):
  457. """
  458. :param ipAddress: The IP address whose used TTL should be determined
  459. :return: The TTL value used by the IP address, or if the IP addresses never specified a TTL,
  460. then None is returned
  461. """
  462. ttl_value = self.process_db_query(
  463. 'SELECT ttlValue from ip_ttl WHERE ipAddress="' + ipAddress + '" ORDER BY ttlCount DESC LIMIT 1')
  464. if isinstance(ttl_value, int):
  465. return ttl_value
  466. else:
  467. return None
  468. def get_in_degree(self):
  469. """
  470. determines the in-degree for each ipAddress, i.e. for every IP the count of ipAddresses it has received packets from
  471. :return: a list, each entry consists of one IPAddress and its associated in-degree
  472. """
  473. in_degree_raw = self.stats_db._process_user_defined_query(
  474. "SELECT ipAddressA, Count(DISTINCT ipAddressB) FROM ip_ports JOIN conv_statistics_stateless ON ipAddress = ipAddressA WHERE portDirection=\'in\' AND portNumber = portA GROUP BY ipAddress " +
  475. "UNION " +
  476. "SELECT ipAddressB, Count(DISTINCT ipAddressA) FROM ip_ports JOIN conv_statistics_stateless ON ipAddress = ipAddressB WHERE portDirection=\'in\' AND portNumber = portB GROUP BY ipAddress")
  477. #Because of the structure of the database, there could be 2 entries for the same IP Address, therefore accumulate their sums
  478. in_degree = self.filter_multiples(in_degree_raw)
  479. return in_degree
  480. def get_out_degree(self):
  481. """
  482. determines the out-degree for each ipAddress, i.e. for every IP the count of ipAddresses it has sent packets to
  483. :return: a list, each entry consists of one IPAddress and its associated out-degree
  484. """
  485. out_degree_raw = self.stats_db._process_user_defined_query(
  486. "SELECT ipAddressA, Count(DISTINCT ipAddressB) FROM ip_ports JOIN conv_statistics_stateless ON ipAddress = ipAddressA WHERE portDirection=\'out\' AND portNumber = portA GROUP BY ipAddress " +
  487. "UNION " +
  488. "SELECT ipAddressB, Count(DISTINCT ipAddressA) FROM ip_ports JOIN conv_statistics_stateless ON ipAddress = ipAddressB WHERE portDirection=\'out\' AND portNumber = portB GROUP BY ipAddress")
  489. #Because of the structure of the database, there could be 2 entries for the same IP Address, therefore accumulate their sums
  490. out_degree = self.filter_multiples(out_degree_raw)
  491. return out_degree
  492. def filter_multiples(self, entries):
  493. """
  494. helper function, for get_out_degree and get_in_degree
  495. filters the given list for duplicate IpAddresses and, if duplciates are present, accumulates their values
  496. :param entries: list, each entry consists of an ipAddress and a numeric value
  497. :return: a filtered list, without duplicate ipAddresses
  498. """
  499. filtered_entries = []
  500. done = []
  501. for p1 in entries:
  502. added = False
  503. if p1 in done:
  504. continue
  505. for p2 in entries:
  506. if p1[0] == p2[0] and p1 != p2:
  507. filtered_entries.append((p1[0], p1[1] + p2[1]))
  508. done.append(p1)
  509. done.append(p2)
  510. print("duplicate found:", p1, " and ", p2)
  511. added = True
  512. break
  513. if not added:
  514. filtered_entries.append(p1)
  515. return filtered_entries
  516. def get_avg_delay_local_ext(self):
  517. """
  518. Calculates the average delay of a packet for external and local communication, based on the tcp handshakes
  519. :return: tuple consisting of avg delay for local and external communication, (local, external)
  520. """
  521. conv_delays = self.stats_db._process_user_defined_query("SELECT ipAddressA, ipAddressB, avgDelay FROM conv_statistics")
  522. if(conv_delays):
  523. external_conv = []
  524. local_conv = []
  525. for conv in conv_delays:
  526. IPA = IPAddress.parse(conv[0])
  527. IPB = IPAddress.parse(conv[1])
  528. #split into local and external conversations
  529. if(not IPA.is_private() or not IPB.is_private()):
  530. external_conv.append(conv)
  531. else:
  532. local_conv.append(conv)
  533. # calculate avg local and external delay by summing up the respective delays and dividing them by the number of conversations
  534. avg_delay_external = 0.0
  535. avg_delay_local = 0.0
  536. if(local_conv):
  537. for conv in local_conv:
  538. avg_delay_local += conv[2]
  539. avg_delay_local = (avg_delay_local/len(local_conv)) * 0.001 #ms
  540. else:
  541. # no local conversations in statistics found
  542. avg_delay_local = 0.06
  543. if(external_conv):
  544. for conv in external_conv:
  545. avg_delay_external += conv[2]
  546. avg_delay_external = (avg_delay_external/len(external_conv)) * 0.001 #ms
  547. else:
  548. # no external conversations in statistics found
  549. avg_delay_external = 0.15
  550. else:
  551. #if no statistics were found, use these numbers
  552. avg_delay_external = 0.15
  553. avg_delay_local = 0.06
  554. return avg_delay_local, avg_delay_external
  555. def get_statistics_database(self):
  556. """
  557. :return: A reference to the statistics database object
  558. """
  559. return self.stats_db
  560. def process_db_query(self, query_string_in: str, print_results: bool = False):
  561. """
  562. Executes a string identified previously as a query. This can be a standard SQL SELECT/INSERT query or a named
  563. query.
  564. :param query_string_in: The query to be processed
  565. :param print_results: Indicates whether the results should be printed to terminal
  566. :return: The result of the query
  567. """
  568. return self.stats_db.process_db_query(query_string_in, print_results)
  569. def is_query(self, value: str):
  570. """
  571. Checks whether the given string is a standard SQL query (SELECT, INSERT) or a named query.
  572. :param value: The string to be checked
  573. :return: True if the string is recognized as a query, otherwise False.
  574. """
  575. if not isinstance(value, str):
  576. return False
  577. else:
  578. return (any(x in value.lower().strip() for x in self.stats_db.get_all_named_query_keywords()) or
  579. any(x in value.lower().strip() for x in self.stats_db.get_all_sql_query_keywords()))
  580. def calculate_standard_deviation(self, lst):
  581. """
  582. Calculates the standard deviation of a list of numbers.
  583. :param lst: The list of numbers to calculate its SD.
  584. """
  585. num_items = len(lst)
  586. mean = sum(lst) / num_items
  587. differences = [x - mean for x in lst]
  588. sq_differences = [d ** 2 for d in differences]
  589. ssd = sum(sq_differences)
  590. variance = ssd / num_items
  591. sd = sqrt(variance)
  592. return sd
  593. def plot_statistics(self, format: str = 'pdf'): #'png'
  594. """
  595. Plots the statistics associated with the dataset.
  596. :param format: The format to be used to save the statistics diagrams.
  597. """
  598. def plot_distribution(queryOutput, title, xLabel, yLabel, file_ending: str):
  599. plt.gcf().clear()
  600. graphx, graphy = [], []
  601. for row in queryOutput:
  602. graphx.append(row[0])
  603. graphy.append(row[1])
  604. plt.autoscale(enable=True, axis='both')
  605. plt.title(title)
  606. plt.xlabel(xLabel)
  607. plt.ylabel(yLabel)
  608. width = 0.1
  609. plt.xlim([0, max(graphx)])
  610. plt.grid(True)
  611. plt.bar(graphx, graphy, width, align='center', linewidth=1, color='red', edgecolor='red')
  612. out = self.pcap_filepath.replace('.pcap', '_plot-' + title + file_ending)
  613. plt.savefig(out,dpi=500)
  614. return out
  615. def plot_ttl(file_ending: str):
  616. queryOutput = self.stats_db._process_user_defined_query(
  617. "SELECT ttlValue, SUM(ttlCount) FROM ip_ttl GROUP BY ttlValue")
  618. title = "TTL Distribution"
  619. xLabel = "TTL Value"
  620. yLabel = "Number of Packets"
  621. if queryOutput:
  622. return plot_distribution(queryOutput, title, xLabel, yLabel, file_ending)
  623. def plot_mss(file_ending: str):
  624. queryOutput = self.stats_db._process_user_defined_query(
  625. "SELECT mssValue, SUM(mssCount) FROM tcp_mss GROUP BY mssValue")
  626. title = "MSS Distribution"
  627. xLabel = "MSS Value"
  628. yLabel = "Number of Packets"
  629. if queryOutput:
  630. return plot_distribution(queryOutput, title, xLabel, yLabel, file_ending)
  631. def plot_win(file_ending: str):
  632. queryOutput = self.stats_db._process_user_defined_query(
  633. "SELECT winSize, SUM(winCount) FROM tcp_win GROUP BY winSize")
  634. title = "Window Size Distribution"
  635. xLabel = "Window Size"
  636. yLabel = "Number of Packets"
  637. if queryOutput:
  638. return plot_distribution(queryOutput, title, xLabel, yLabel, file_ending)
  639. def plot_protocol(file_ending: str):
  640. plt.gcf().clear()
  641. result = self.stats_db._process_user_defined_query(
  642. "SELECT protocolName, SUM(protocolCount) FROM ip_protocols GROUP BY protocolName")
  643. if (result):
  644. graphx, graphy = [], []
  645. for row in result:
  646. graphx.append(row[0])
  647. graphy.append(row[1])
  648. plt.autoscale(enable=True, axis='both')
  649. plt.title("Protocols Distribution")
  650. plt.xlabel('Protocols')
  651. plt.ylabel('Number of Packets')
  652. width = 0.1
  653. plt.xlim([0, len(graphx)])
  654. plt.grid(True)
  655. # Protocols' names on x-axis
  656. x = range(0,len(graphx))
  657. my_xticks = graphx
  658. plt.xticks(x, my_xticks)
  659. plt.bar(x, graphy, width, align='center', linewidth=1, color='red', edgecolor='red')
  660. out = self.pcap_filepath.replace('.pcap', '_plot-protocol' + file_ending)
  661. plt.savefig(out,dpi=500)
  662. return out
  663. else:
  664. print("Error plot protocol: No protocol values found!")
  665. def plot_port(file_ending: str):
  666. plt.gcf().clear()
  667. result = self.stats_db._process_user_defined_query(
  668. "SELECT portNumber, SUM(portCount) FROM ip_ports GROUP BY portNumber")
  669. graphx, graphy = [], []
  670. for row in result:
  671. graphx.append(row[0])
  672. graphy.append(row[1])
  673. plt.autoscale(enable=True, axis='both')
  674. plt.title("Ports Distribution")
  675. plt.xlabel('Ports Numbers')
  676. plt.ylabel('Number of Packets')
  677. width = 0.1
  678. plt.xlim([0, max(graphx)])
  679. plt.grid(True)
  680. plt.bar(graphx, graphy, width, align='center', linewidth=1, color='red', edgecolor='red')
  681. out = self.pcap_filepath.replace('.pcap', '_plot-port' + file_ending)
  682. plt.savefig(out,dpi=500)
  683. return out
  684. # This distribution is not drawable for big datasets
  685. def plot_ip_src(file_ending: str):
  686. plt.gcf().clear()
  687. result = self.stats_db._process_user_defined_query(
  688. "SELECT ipAddress, pktsSent FROM ip_statistics")
  689. graphx, graphy = [], []
  690. for row in result:
  691. graphx.append(row[0])
  692. graphy.append(row[1])
  693. plt.autoscale(enable=True, axis='both')
  694. plt.title("Source IP Distribution")
  695. plt.xlabel('Source IP')
  696. plt.ylabel('Number of Packets')
  697. width = 0.1
  698. plt.xlim([0, len(graphx)])
  699. plt.grid(True)
  700. # IPs on x-axis
  701. x = range(0, len(graphx))
  702. my_xticks = graphx
  703. plt.xticks(x, my_xticks, rotation='vertical', fontsize=5)
  704. plt.tight_layout()
  705. # limit the number of xticks
  706. plt.locator_params(axis='x', nbins=20)
  707. plt.bar(x, graphy, width, align='center', linewidth=1, color='red', edgecolor='red')
  708. out = self.pcap_filepath.replace('.pcap', '_plot-ip-src' + file_ending)
  709. plt.savefig(out, dpi=500)
  710. return out
  711. # This distribution is not drawable for big datasets
  712. def plot_ip_dst(file_ending: str):
  713. plt.gcf().clear()
  714. result = self.stats_db._process_user_defined_query(
  715. "SELECT ipAddress, pktsReceived FROM ip_statistics")
  716. graphx, graphy = [], []
  717. for row in result:
  718. graphx.append(row[0])
  719. graphy.append(row[1])
  720. plt.autoscale(enable=True, axis='both')
  721. plt.title("Destination IP Distribution")
  722. plt.xlabel('Destination IP')
  723. plt.ylabel('Number of Packets')
  724. width = 0.1
  725. plt.xlim([0, len(graphx)])
  726. plt.grid(True)
  727. # IPs on x-axis
  728. x = range(0, len(graphx))
  729. my_xticks = graphx
  730. plt.xticks(x, my_xticks, rotation='vertical', fontsize=5)
  731. plt.tight_layout()
  732. # limit the number of xticks
  733. plt.locator_params(axis='x', nbins=20)
  734. plt.bar(x, graphy, width, align='center', linewidth=1, color='red', edgecolor='red')
  735. out = self.pcap_filepath.replace('.pcap', '_plot-ip-dst' + file_ending)
  736. plt.savefig(out, dpi=500)
  737. return out
  738. def plot_interval_statistics(queryOutput, title, xLabel, yLabel, file_ending: str):
  739. plt.gcf().clear()
  740. graphx, graphy = [], []
  741. for row in queryOutput:
  742. graphx.append(row[0])
  743. graphy.append(row[1])
  744. plt.autoscale(enable=True, axis='both')
  745. plt.title(title)
  746. plt.xlabel(xLabel)
  747. plt.ylabel(yLabel)
  748. width = 0.5
  749. plt.xlim([0, len(graphx)])
  750. plt.grid(True)
  751. # timestamp on x-axis
  752. x = range(0, len(graphx))
  753. # limit the number of xticks
  754. plt.locator_params(axis='x', nbins=20)
  755. plt.bar(x, graphy, width, align='center', linewidth=1, color='red', edgecolor='red')
  756. out = self.pcap_filepath.replace('.pcap', '_plot-' + title + file_ending)
  757. plt.savefig(out, dpi=500)
  758. return out
  759. def plot_interval_pktCount(file_ending: str):
  760. queryOutput = self.stats_db._process_user_defined_query(
  761. "SELECT lastPktTimestamp, pktsCount FROM interval_statistics ORDER BY lastPktTimestamp")
  762. title = "Packet Rate"
  763. xLabel = "Time Interval"
  764. yLabel = "Number of Packets"
  765. if queryOutput:
  766. return plot_interval_statistics(queryOutput, title, xLabel, yLabel, file_ending)
  767. def plot_interval_ip_src_ent(file_ending: str):
  768. queryOutput = self.stats_db._process_user_defined_query(
  769. "SELECT lastPktTimestamp, ipSrcEntropy FROM interval_statistics ORDER BY lastPktTimestamp")
  770. title = "Source IP Entropy"
  771. xLabel = "Time Interval"
  772. yLabel = "Entropy"
  773. if queryOutput:
  774. return plot_interval_statistics(queryOutput, title, xLabel, yLabel, file_ending)
  775. def plot_interval_ip_dst_ent(file_ending: str):
  776. queryOutput = self.stats_db._process_user_defined_query(
  777. "SELECT lastPktTimestamp, ipDstEntropy FROM interval_statistics ORDER BY lastPktTimestamp")
  778. title = "Destination IP Entropy"
  779. xLabel = "Time Interval"
  780. yLabel = "Entropy"
  781. if queryOutput:
  782. return plot_interval_statistics(queryOutput, title, xLabel, yLabel, file_ending)
  783. def plot_interval_new_ip(file_ending: str):
  784. queryOutput = self.stats_db._process_user_defined_query(
  785. "SELECT lastPktTimestamp, newIPCount FROM interval_statistics ORDER BY lastPktTimestamp")
  786. title = "IP Novelty Distribution"
  787. xLabel = "Time Interval"
  788. yLabel = "Novel values count"
  789. if queryOutput:
  790. return plot_interval_statistics(queryOutput, title, xLabel, yLabel, file_ending)
  791. def plot_interval_new_port(file_ending: str):
  792. queryOutput = self.stats_db._process_user_defined_query(
  793. "SELECT lastPktTimestamp, newPortCount FROM interval_statistics ORDER BY lastPktTimestamp")
  794. title = "Port Novelty Distribution"
  795. xLabel = "Time Interval"
  796. yLabel = "Novel values count"
  797. if queryOutput:
  798. return plot_interval_statistics(queryOutput, title, xLabel, yLabel, file_ending)
  799. def plot_interval_new_ttl(file_ending: str):
  800. queryOutput = self.stats_db._process_user_defined_query(
  801. "SELECT lastPktTimestamp, newTTLCount FROM interval_statistics ORDER BY lastPktTimestamp")
  802. title = "TTL Novelty Distribution"
  803. xLabel = "Time Interval"
  804. yLabel = "Novel values count"
  805. if queryOutput:
  806. return plot_interval_statistics(queryOutput, title, xLabel, yLabel, file_ending)
  807. def plot_interval_new_tos(file_ending: str):
  808. queryOutput = self.stats_db._process_user_defined_query(
  809. "SELECT lastPktTimestamp, newToSCount FROM interval_statistics ORDER BY lastPktTimestamp")
  810. title = "ToS Novelty Distribution"
  811. xLabel = "Time Interval"
  812. yLabel = "Novel values count"
  813. if queryOutput:
  814. return plot_interval_statistics(queryOutput, title, xLabel, yLabel, file_ending)
  815. def plot_interval_new_win_size(file_ending: str):
  816. queryOutput = self.stats_db._process_user_defined_query(
  817. "SELECT lastPktTimestamp, newWinSizeCount FROM interval_statistics ORDER BY lastPktTimestamp")
  818. title = "Window Size Novelty Distribution"
  819. xLabel = "Time Interval"
  820. yLabel = "Novel values count"
  821. if queryOutput:
  822. return plot_interval_statistics(queryOutput, title, xLabel, yLabel, file_ending)
  823. def plot_interval_new_mss(file_ending: str):
  824. queryOutput = self.stats_db._process_user_defined_query(
  825. "SELECT lastPktTimestamp, newMSSCount FROM interval_statistics ORDER BY lastPktTimestamp")
  826. title = "MSS Novelty Distribution"
  827. xLabel = "Time Interval"
  828. yLabel = "Novel values count"
  829. if queryOutput:
  830. return plot_interval_statistics(queryOutput, title, xLabel, yLabel, file_ending)
  831. def plot_interval_ip_dst_cum_ent(file_ending: str):
  832. plt.gcf().clear()
  833. result = self.stats_db._process_user_defined_query(
  834. "SELECT lastPktTimestamp, ipDstCumEntropy FROM interval_statistics ORDER BY lastPktTimestamp")
  835. graphx, graphy = [], []
  836. for row in result:
  837. graphx.append(row[0])
  838. graphy.append(row[1])
  839. # If entropy was not calculated do not plot the graph
  840. if graphy[0] != -1:
  841. plt.autoscale(enable=True, axis='both')
  842. plt.title("Destination IP Cumulative Entropy")
  843. # plt.xlabel('Timestamp')
  844. plt.xlabel('Time Interval')
  845. plt.ylabel('Entropy')
  846. plt.xlim([0, len(graphx)])
  847. plt.grid(True)
  848. # timestamp on x-axis
  849. x = range(0, len(graphx))
  850. # my_xticks = graphx
  851. # plt.xticks(x, my_xticks, rotation='vertical', fontsize=5)
  852. # plt.tight_layout()
  853. # limit the number of xticks
  854. plt.locator_params(axis='x', nbins=20)
  855. plt.plot(x, graphy, 'r')
  856. out = self.pcap_filepath.replace('.pcap', '_plot-interval-ip-dst-cum-ent' + file_ending)
  857. plt.savefig(out, dpi=500)
  858. return out
  859. def plot_interval_ip_src_cum_ent(file_ending: str):
  860. plt.gcf().clear()
  861. result = self.stats_db._process_user_defined_query(
  862. "SELECT lastPktTimestamp, ipSrcCumEntropy FROM interval_statistics ORDER BY lastPktTimestamp")
  863. graphx, graphy = [], []
  864. for row in result:
  865. graphx.append(row[0])
  866. graphy.append(row[1])
  867. # If entropy was not calculated do not plot the graph
  868. if graphy[0] != -1:
  869. plt.autoscale(enable=True, axis='both')
  870. plt.title("Source IP Cumulative Entropy")
  871. # plt.xlabel('Timestamp')
  872. plt.xlabel('Time Interval')
  873. plt.ylabel('Entropy')
  874. plt.xlim([0, len(graphx)])
  875. plt.grid(True)
  876. # timestamp on x-axis
  877. x = range(0, len(graphx))
  878. # my_xticks = graphx
  879. # plt.xticks(x, my_xticks, rotation='vertical', fontsize=5)
  880. # plt.tight_layout()
  881. # limit the number of xticks
  882. plt.locator_params(axis='x', nbins=20)
  883. plt.plot(x, graphy, 'r')
  884. out = self.pcap_filepath.replace('.pcap', '_plot-interval-ip-src-cum-ent' + file_ending)
  885. plt.savefig(out, dpi=500)
  886. return out
  887. def plot_packets_per_connection(file_ending: str):
  888. """
  889. Plots the exchanged packets per connection as horizontal bar plot.
  890. Included are 'half-open' connections, where only one packet is exchanged.
  891. Note: there may be cutoff problems within the plot if there is to little data.
  892. :param file_ending: The file extension for the output file containing the plot
  893. :return: A filepath to the file containing the created plot
  894. """
  895. plt.gcf().clear()
  896. result = self.stats_db._process_user_defined_query(
  897. "SELECT ipAddressA, portA, ipAddressB, portB, pktsCount FROM conv_statistics_stateless")
  898. if (result):
  899. graphy, graphx = [], []
  900. # plot data in descending order
  901. result = sorted(result, key=lambda row: row[4])
  902. # compute plot data
  903. for i, row in enumerate(result):
  904. addr1, addr2 = "%s:%d" % (row[0], row[1]), "%s:%d" % (row[2], row[3])
  905. # adjust the justification of strings to improve appearance
  906. len_max = max(len(addr1), len(addr2))
  907. addr1 = addr1.ljust(len_max)
  908. addr2 = addr2.ljust(len_max)
  909. # add plot data
  910. graphy.append("%s\n%s" % (addr1, addr2))
  911. graphx.append(row[4])
  912. # compute plot height in inches
  913. dist_mult_height, dist_mult_width = 0.55, 0.07 # these values turned out to work well
  914. plt_height, plt_width = len(graphy) * dist_mult_height, max(graphx) * dist_mult_width
  915. title_distance = 1 + 0.012*52.8/plt_height # orginally, a good title distance turned out to be 1.012 with a plot height of 52.8
  916. # have x axis and its label appear at the top (instead of bottom)
  917. fig, ax = plt.subplots()
  918. ax.xaxis.tick_top()
  919. ax.xaxis.set_label_position("top")
  920. # set additional plot parameters
  921. plt.title("Sent packets per connection", y=title_distance)
  922. plt.xlabel('Number of Packets')
  923. plt.ylabel('Connection')
  924. width = 0.5
  925. plt.grid(True)
  926. plt.gca().margins(y=0) # removes the space between data and x-axis within the plot
  927. plt.gcf().set_size_inches(plt_width, plt_height) # set plot size
  928. # plot the above data, first use plain numbers as graphy to maintain sorting
  929. plt.barh(range(len(graphy)), graphx, width, align='center', linewidth=1, color='red', edgecolor='red')
  930. # now change the y numbers to the respective address labels
  931. plt.yticks(range(len(graphy)), graphy)
  932. # try to use tight layout to cut off unnecessary space
  933. try:
  934. plt.tight_layout(pad=4)
  935. except ValueError:
  936. pass
  937. # save created figure
  938. out = self.pcap_filepath.replace('.pcap', '_plot-PktCount per Connection Distribution' + file_ending)
  939. plt.savefig(out, dpi=500)
  940. return out
  941. else:
  942. print("Error plot protocol: No protocol values found!")
  943. def plot_in_degree(file_ending: str):
  944. """
  945. Creates a Plot, visualizing the in-degree for every IP Address
  946. :param file_ending: The file extension for the output file containing the plot, e.g. "pdf"
  947. :return: A filepath to the file containing the created plot
  948. """
  949. plt.gcf().clear()
  950. # retrieve data
  951. in_degree = self.get_in_degree()
  952. if(in_degree):
  953. graphx, graphy = [], []
  954. for entry in in_degree:
  955. # degree values
  956. graphx.append(entry[1])
  957. # IP labels
  958. graphy.append(entry[0])
  959. # set labels
  960. plt.title("Indegree per IP Address")
  961. plt.ylabel('IpAddress')
  962. plt.xlabel('Indegree')
  963. #set width of the bars
  964. width = 0.3
  965. # set scalings
  966. plt.figure(figsize=(int(len(graphx))/20 + 5, int(len(graphy)/5) + 5)) # these proportions just worked well
  967. #set limits of the axis
  968. plt.ylim([0, len(graphy)])
  969. plt.xlim([0, max(graphx) + 10])
  970. # display numbers at each bar
  971. for i, v in enumerate(graphx):
  972. plt.text(v + 1, i + .1, str(v), color='blue', fontweight='bold')
  973. # display grid for better visuals
  974. plt.grid(True)
  975. # plot the bar
  976. plt.barh(graphy, graphx, width, align='center', linewidth=1, color='red', edgecolor='red')
  977. out = self.pcap_filepath.replace('.pcap', '_in_degree' + file_ending)
  978. plt.tight_layout()
  979. plt.savefig(out,dpi=500)
  980. return out
  981. else:
  982. print("Error: No statistics Information for plotting out-degrees found")
  983. def plot_out_degree(file_ending: str):
  984. """
  985. Creates a Plot, visualizing the out-degree for every IP Address
  986. :param file_ending: The file extension for the output file containing the plot, e.g. "pdf"
  987. :return: A filepath to the file containing the created plot
  988. """
  989. plt.gcf().clear()
  990. # retrieve data
  991. out_degree = self.get_out_degree()
  992. if(out_degree):
  993. graphx, graphy = [], []
  994. for entry in out_degree:
  995. # degree values
  996. graphx.append(entry[1])
  997. # IP labels
  998. graphy.append(entry[0])
  999. # set labels
  1000. plt.title("Outdegree per IP Address")
  1001. plt.ylabel('IpAddress')
  1002. plt.xlabel('Outdegree')
  1003. #set width of the bars
  1004. width = 0.3
  1005. # set scalings
  1006. plt.figure(figsize=(int(len(graphx))/20 + 5, int(len(graphy)/5) + 5)) # these proportions just worked well
  1007. #set limits of the axis
  1008. plt.ylim([0, len(graphy)])
  1009. plt.xlim([0, max(graphx) + 10])
  1010. # display numbers at each bar
  1011. for i, v in enumerate(graphx):
  1012. plt.text(v + 1, i + .1, str(v), color='blue', fontweight='bold')
  1013. # display grid for better visuals
  1014. plt.grid(True)
  1015. # plot the bar
  1016. plt.barh(graphy, graphx, width, align='center', linewidth=1, color='red', edgecolor='red')
  1017. out = self.pcap_filepath.replace('.pcap', '_out_degree' + file_ending)
  1018. plt.tight_layout()
  1019. plt.savefig(out,dpi=500)
  1020. return out
  1021. else:
  1022. print("Error: No statistics Information for plotting out-degrees found")
  1023. def plot_avgpkts_per_comm_interval(file_ending: str):
  1024. """
  1025. Plots the exchanged packets per connection as horizontal bar plot.
  1026. Included are 'half-open' connections, where only one packet is exchanged.
  1027. Note: there may be cutoff problems within the plot if there is to little data.
  1028. :param file_ending: The file extension for the output file containing the plot
  1029. :return: A filepath to the file containing the created plot
  1030. """
  1031. plt.gcf().clear()
  1032. result = self.stats_db._process_user_defined_query(
  1033. "SELECT ipAddressA, portA, ipAddressB, portB, avgPktCount FROM comm_interval_statistics")
  1034. if (result):
  1035. graphy, graphx = [], []
  1036. # plot data in descending order
  1037. result = sorted(result, key=lambda row: row[4])
  1038. # compute plot data
  1039. for i, row in enumerate(result):
  1040. addr1, addr2 = "%s:%d" % (row[0], row[1]), "%s:%d" % (row[2], row[3])
  1041. # adjust the justification of strings to improve appearance
  1042. len_max = max(len(addr1), len(addr2))
  1043. addr1 = addr1.ljust(len_max)
  1044. addr2 = addr2.ljust(len_max)
  1045. # add plot data
  1046. graphy.append("%s\n%s" % (addr1, addr2))
  1047. graphx.append(row[4])
  1048. # compute plot height in inches
  1049. dist_mult_height, dist_mult_width = 0.55, 0.07 # these values turned out to work well
  1050. plt_height, plt_width = len(graphy) * dist_mult_height, max(graphx) * dist_mult_width
  1051. title_distance = 1 + 0.012*52.8/plt_height # orginally, a good title distance turned out to be 1.012 with a plot height of 52.8
  1052. # have x axis and its label appear at the top (instead of bottom)
  1053. fig, ax = plt.subplots()
  1054. ax.xaxis.tick_top()
  1055. ax.xaxis.set_label_position("top")
  1056. # set additional plot parameters
  1057. plt.title("Average number of packets per communication interval", y=title_distance)
  1058. plt.xlabel('Number of Packets')
  1059. plt.ylabel('Connection')
  1060. width = 0.5
  1061. plt.grid(True)
  1062. plt.gca().margins(y=0) # removes the space between data and x-axis within the plot
  1063. plt.gcf().set_size_inches(plt_width, plt_height) # set plot size
  1064. # plot the above data, first use plain numbers as graphy to maintain sorting
  1065. plt.barh(range(len(graphy)), graphx, width, align='center', linewidth=1, color='red', edgecolor='red')
  1066. # now change the y numbers to the respective address labels
  1067. plt.yticks(range(len(graphy)), graphy)
  1068. # try to use tight layout to cut off unnecessary space
  1069. try:
  1070. plt.tight_layout(pad=4)
  1071. except ValueError:
  1072. pass
  1073. # save created figure
  1074. out = self.pcap_filepath.replace('.pcap', '_plot-Avg PktCount Communication Interval Distribution' + file_ending)
  1075. plt.savefig(out, dpi=500)
  1076. return out
  1077. else:
  1078. print("Error plot protocol: No protocol values found!")
  1079. ttl_out_path = plot_ttl('.' + format)
  1080. mss_out_path = plot_mss('.' + format)
  1081. win_out_path = plot_win('.' + format)
  1082. protocol_out_path = plot_protocol('.' + format)
  1083. plot_interval_pktCount = plot_interval_pktCount('.' + format)
  1084. plot_interval_ip_src_ent = plot_interval_ip_src_ent('.' + format)
  1085. plot_interval_ip_dst_ent = plot_interval_ip_dst_ent('.' + format)
  1086. plot_interval_ip_src_cum_ent = plot_interval_ip_src_cum_ent('.' + format)
  1087. plot_interval_ip_dst_cum_ent = plot_interval_ip_dst_cum_ent('.' + format)
  1088. plot_interval_new_ip = plot_interval_new_ip('.' + format)
  1089. plot_interval_new_port = plot_interval_new_port('.' + format)
  1090. plot_interval_new_ttl = plot_interval_new_ttl('.' + format)
  1091. plot_interval_new_tos = plot_interval_new_tos('.' + format)
  1092. plot_interval_new_win_size = plot_interval_new_win_size('.' + format)
  1093. plot_interval_new_mss = plot_interval_new_mss('.' + format)
  1094. plot_packets_per_connection_out = plot_packets_per_connection('.' + format)
  1095. plot_out_degree = plot_out_degree('.' + format)
  1096. plot_in_degree = plot_in_degree('.' + format)
  1097. plot_avgpkts_per_comm_interval_out = plot_avgpkts_per_comm_interval('.' + format)
  1098. ## Time consuming plot
  1099. # port_out_path = plot_port('.' + format)
  1100. ## Not drawable for too many IPs
  1101. # ip_src_out_path = plot_ip_src('.' + format)
  1102. # ip_dst_out_path = plot_ip_dst('.' + format)
  1103. print("Saved plots in the input PCAP directory.")