Statistics.py 59 KB

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