Statistics.py 58 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340
  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_avg_delay_local_ext(self):
  470. """
  471. Calculates the average delay of a packet for external and local communication, based on the tcp handshakes
  472. :return: tuple consisting of avg delay for local and external communication, (local, external)
  473. """
  474. conv_delays = self.stats_db._process_user_defined_query("SELECT ipAddressA, ipAddressB, avgDelay FROM conv_statistics")
  475. if(conv_delays):
  476. external_conv = []
  477. local_conv = []
  478. for conv in conv_delays:
  479. IPA = IPAddress.parse(conv[0])
  480. IPB = IPAddress.parse(conv[1])
  481. #split into local and external conversations
  482. if(not IPA.is_private() or not IPB.is_private()):
  483. external_conv.append(conv)
  484. else:
  485. local_conv.append(conv)
  486. # calculate avg local and external delay by summing up the respective delays and dividing them by the number of conversations
  487. avg_delay_external = 0.0
  488. avg_delay_local = 0.0
  489. if(local_conv):
  490. for conv in local_conv:
  491. avg_delay_local += conv[2]
  492. avg_delay_local = (avg_delay_local/len(local_conv)) * 0.001 #ms
  493. else:
  494. # no local conversations in statistics found
  495. avg_delay_local = 0.06
  496. if(external_conv):
  497. for conv in external_conv:
  498. avg_delay_external += conv[2]
  499. avg_delay_external = (avg_delay_external/len(external_conv)) * 0.001 #ms
  500. else:
  501. # no external conversations in statistics found
  502. avg_delay_external = 0.15
  503. else:
  504. #if no statistics were found, use these numbers
  505. avg_delay_external = 0.15
  506. avg_delay_local = 0.06
  507. return avg_delay_local, avg_delay_external
  508. def get_filtered_degree(self, degree_type: str):
  509. """
  510. gets the desired type of degree statistics and filters IPs with degree value zero
  511. :param degree_type: the desired type of degrees, one of the following: inDegree, outDegree, overallDegree
  512. :return: the filtered degrees
  513. """
  514. degrees_raw = self.stats_db._process_user_defined_query(
  515. "SELECT ipAddress, %s FROM ip_degrees" % degree_type)
  516. degrees = []
  517. if(degrees_raw):
  518. for deg in degrees_raw:
  519. if int(deg[1]) > 0:
  520. degrees.append(deg)
  521. return degrees
  522. def get_statistics_database(self):
  523. """
  524. :return: A reference to the statistics database object
  525. """
  526. return self.stats_db
  527. def process_db_query(self, query_string_in: str, print_results: bool = False):
  528. """
  529. Executes a string identified previously as a query. This can be a standard SQL SELECT/INSERT query or a named
  530. query.
  531. :param query_string_in: The query to be processed
  532. :param print_results: Indicates whether the results should be printed to terminal
  533. :return: The result of the query
  534. """
  535. return self.stats_db.process_db_query(query_string_in, print_results)
  536. def is_query(self, value: str):
  537. """
  538. Checks whether the given string is a standard SQL query (SELECT, INSERT) or a named query.
  539. :param value: The string to be checked
  540. :return: True if the string is recognized as a query, otherwise False.
  541. """
  542. if not isinstance(value, str):
  543. return False
  544. else:
  545. return (any(x in value.lower().strip() for x in self.stats_db.get_all_named_query_keywords()) or
  546. any(x in value.lower().strip() for x in self.stats_db.get_all_sql_query_keywords()))
  547. def calculate_standard_deviation(self, lst):
  548. """
  549. Calculates the standard deviation of a list of numbers.
  550. :param lst: The list of numbers to calculate its SD.
  551. """
  552. num_items = len(lst)
  553. mean = sum(lst) / num_items
  554. differences = [x - mean for x in lst]
  555. sq_differences = [d ** 2 for d in differences]
  556. ssd = sum(sq_differences)
  557. variance = ssd / num_items
  558. sd = sqrt(variance)
  559. return sd
  560. def plot_statistics(self, format: str = 'pdf'): #'png'
  561. """
  562. Plots the statistics associated with the dataset.
  563. :param format: The format to be used to save the statistics diagrams.
  564. """
  565. def plot_distribution(queryOutput, title, xLabel, yLabel, file_ending: str):
  566. plt.gcf().clear()
  567. graphx, graphy = [], []
  568. for row in queryOutput:
  569. graphx.append(row[0])
  570. graphy.append(row[1])
  571. plt.autoscale(enable=True, axis='both')
  572. plt.title(title)
  573. plt.xlabel(xLabel)
  574. plt.ylabel(yLabel)
  575. width = 0.1
  576. plt.xlim([0, max(graphx)])
  577. plt.grid(True)
  578. plt.bar(graphx, graphy, width, align='center', linewidth=1, color='red', edgecolor='red')
  579. out = self.pcap_filepath.replace('.pcap', '_plot-' + title + file_ending)
  580. plt.savefig(out,dpi=500)
  581. return out
  582. def plot_ttl(file_ending: str):
  583. queryOutput = self.stats_db._process_user_defined_query(
  584. "SELECT ttlValue, SUM(ttlCount) FROM ip_ttl GROUP BY ttlValue")
  585. title = "TTL Distribution"
  586. xLabel = "TTL Value"
  587. yLabel = "Number of Packets"
  588. if queryOutput:
  589. return plot_distribution(queryOutput, title, xLabel, yLabel, file_ending)
  590. def plot_mss(file_ending: str):
  591. queryOutput = self.stats_db._process_user_defined_query(
  592. "SELECT mssValue, SUM(mssCount) FROM tcp_mss GROUP BY mssValue")
  593. title = "MSS Distribution"
  594. xLabel = "MSS Value"
  595. yLabel = "Number of Packets"
  596. if queryOutput:
  597. return plot_distribution(queryOutput, title, xLabel, yLabel, file_ending)
  598. def plot_win(file_ending: str):
  599. queryOutput = self.stats_db._process_user_defined_query(
  600. "SELECT winSize, SUM(winCount) FROM tcp_win GROUP BY winSize")
  601. title = "Window Size Distribution"
  602. xLabel = "Window Size"
  603. yLabel = "Number of Packets"
  604. if queryOutput:
  605. return plot_distribution(queryOutput, title, xLabel, yLabel, file_ending)
  606. def plot_protocol(file_ending: str):
  607. plt.gcf().clear()
  608. result = self.stats_db._process_user_defined_query(
  609. "SELECT protocolName, SUM(protocolCount) FROM ip_protocols GROUP BY protocolName")
  610. if (result):
  611. graphx, graphy = [], []
  612. for row in result:
  613. graphx.append(row[0])
  614. graphy.append(row[1])
  615. plt.autoscale(enable=True, axis='both')
  616. plt.title("Protocols Distribution")
  617. plt.xlabel('Protocols')
  618. plt.ylabel('Number of Packets')
  619. width = 0.1
  620. plt.xlim([0, len(graphx)])
  621. plt.grid(True)
  622. # Protocols' names on x-axis
  623. x = range(0,len(graphx))
  624. my_xticks = graphx
  625. plt.xticks(x, my_xticks)
  626. plt.bar(x, graphy, width, align='center', linewidth=1, color='red', edgecolor='red')
  627. out = self.pcap_filepath.replace('.pcap', '_plot-protocol' + file_ending)
  628. plt.savefig(out,dpi=500)
  629. return out
  630. else:
  631. print("Error plot protocol: No protocol values found!")
  632. def plot_port(file_ending: str):
  633. plt.gcf().clear()
  634. result = self.stats_db._process_user_defined_query(
  635. "SELECT portNumber, SUM(portCount) FROM ip_ports GROUP BY portNumber")
  636. graphx, graphy = [], []
  637. for row in result:
  638. graphx.append(row[0])
  639. graphy.append(row[1])
  640. plt.autoscale(enable=True, axis='both')
  641. plt.title("Ports Distribution")
  642. plt.xlabel('Ports Numbers')
  643. plt.ylabel('Number of Packets')
  644. width = 0.1
  645. plt.xlim([0, max(graphx)])
  646. plt.grid(True)
  647. plt.bar(graphx, graphy, width, align='center', linewidth=1, color='red', edgecolor='red')
  648. out = self.pcap_filepath.replace('.pcap', '_plot-port' + file_ending)
  649. plt.savefig(out,dpi=500)
  650. return out
  651. # This distribution is not drawable for big datasets
  652. def plot_ip_src(file_ending: str):
  653. plt.gcf().clear()
  654. result = self.stats_db._process_user_defined_query(
  655. "SELECT ipAddress, pktsSent FROM ip_statistics")
  656. graphx, graphy = [], []
  657. for row in result:
  658. graphx.append(row[0])
  659. graphy.append(row[1])
  660. plt.autoscale(enable=True, axis='both')
  661. plt.title("Source IP Distribution")
  662. plt.xlabel('Source IP')
  663. plt.ylabel('Number of Packets')
  664. width = 0.1
  665. plt.xlim([0, len(graphx)])
  666. plt.grid(True)
  667. # IPs on x-axis
  668. x = range(0, len(graphx))
  669. my_xticks = graphx
  670. plt.xticks(x, my_xticks, rotation='vertical', fontsize=5)
  671. plt.tight_layout()
  672. # limit the number of xticks
  673. plt.locator_params(axis='x', nbins=20)
  674. plt.bar(x, graphy, width, align='center', linewidth=1, color='red', edgecolor='red')
  675. out = self.pcap_filepath.replace('.pcap', '_plot-ip-src' + file_ending)
  676. plt.savefig(out, dpi=500)
  677. return out
  678. # This distribution is not drawable for big datasets
  679. def plot_ip_dst(file_ending: str):
  680. plt.gcf().clear()
  681. result = self.stats_db._process_user_defined_query(
  682. "SELECT ipAddress, pktsReceived FROM ip_statistics")
  683. graphx, graphy = [], []
  684. for row in result:
  685. graphx.append(row[0])
  686. graphy.append(row[1])
  687. plt.autoscale(enable=True, axis='both')
  688. plt.title("Destination IP Distribution")
  689. plt.xlabel('Destination IP')
  690. plt.ylabel('Number of Packets')
  691. width = 0.1
  692. plt.xlim([0, len(graphx)])
  693. plt.grid(True)
  694. # IPs on x-axis
  695. x = range(0, len(graphx))
  696. my_xticks = graphx
  697. plt.xticks(x, my_xticks, rotation='vertical', fontsize=5)
  698. plt.tight_layout()
  699. # limit the number of xticks
  700. plt.locator_params(axis='x', nbins=20)
  701. plt.bar(x, graphy, width, align='center', linewidth=1, color='red', edgecolor='red')
  702. out = self.pcap_filepath.replace('.pcap', '_plot-ip-dst' + file_ending)
  703. plt.savefig(out, dpi=500)
  704. return out
  705. def plot_interval_statistics(queryOutput, title, xLabel, yLabel, file_ending: str):
  706. plt.gcf().clear()
  707. graphx, graphy = [], []
  708. for row in queryOutput:
  709. graphx.append(row[0])
  710. graphy.append(row[1])
  711. plt.autoscale(enable=True, axis='both')
  712. plt.title(title)
  713. plt.xlabel(xLabel)
  714. plt.ylabel(yLabel)
  715. width = 0.5
  716. plt.xlim([0, len(graphx)])
  717. plt.grid(True)
  718. # timestamp on x-axis
  719. x = range(0, len(graphx))
  720. # limit the number of xticks
  721. plt.locator_params(axis='x', nbins=20)
  722. plt.bar(x, graphy, width, align='center', linewidth=1, color='red', edgecolor='red')
  723. out = self.pcap_filepath.replace('.pcap', '_plot-' + title + file_ending)
  724. plt.savefig(out, dpi=500)
  725. return out
  726. def plot_interval_pktCount(file_ending: str):
  727. queryOutput = self.stats_db._process_user_defined_query(
  728. "SELECT lastPktTimestamp, pktsCount FROM interval_statistics ORDER BY lastPktTimestamp")
  729. title = "Packet Rate"
  730. xLabel = "Time Interval"
  731. yLabel = "Number of Packets"
  732. if queryOutput:
  733. return plot_interval_statistics(queryOutput, title, xLabel, yLabel, file_ending)
  734. def plot_interval_ip_src_ent(file_ending: str):
  735. queryOutput = self.stats_db._process_user_defined_query(
  736. "SELECT lastPktTimestamp, ipSrcEntropy FROM interval_statistics ORDER BY lastPktTimestamp")
  737. title = "Source IP Entropy"
  738. xLabel = "Time Interval"
  739. yLabel = "Entropy"
  740. if queryOutput:
  741. return plot_interval_statistics(queryOutput, title, xLabel, yLabel, file_ending)
  742. def plot_interval_ip_dst_ent(file_ending: str):
  743. queryOutput = self.stats_db._process_user_defined_query(
  744. "SELECT lastPktTimestamp, ipDstEntropy FROM interval_statistics ORDER BY lastPktTimestamp")
  745. title = "Destination IP Entropy"
  746. xLabel = "Time Interval"
  747. yLabel = "Entropy"
  748. if queryOutput:
  749. return plot_interval_statistics(queryOutput, title, xLabel, yLabel, file_ending)
  750. def plot_interval_new_ip(file_ending: str):
  751. queryOutput = self.stats_db._process_user_defined_query(
  752. "SELECT lastPktTimestamp, newIPCount FROM interval_statistics ORDER BY lastPktTimestamp")
  753. title = "IP Novelty Distribution"
  754. xLabel = "Time Interval"
  755. yLabel = "Novel values count"
  756. if queryOutput:
  757. return plot_interval_statistics(queryOutput, title, xLabel, yLabel, file_ending)
  758. def plot_interval_new_port(file_ending: str):
  759. queryOutput = self.stats_db._process_user_defined_query(
  760. "SELECT lastPktTimestamp, newPortCount FROM interval_statistics ORDER BY lastPktTimestamp")
  761. title = "Port Novelty Distribution"
  762. xLabel = "Time Interval"
  763. yLabel = "Novel values count"
  764. if queryOutput:
  765. return plot_interval_statistics(queryOutput, title, xLabel, yLabel, file_ending)
  766. def plot_interval_new_ttl(file_ending: str):
  767. queryOutput = self.stats_db._process_user_defined_query(
  768. "SELECT lastPktTimestamp, newTTLCount FROM interval_statistics ORDER BY lastPktTimestamp")
  769. title = "TTL Novelty Distribution"
  770. xLabel = "Time Interval"
  771. yLabel = "Novel values count"
  772. if queryOutput:
  773. return plot_interval_statistics(queryOutput, title, xLabel, yLabel, file_ending)
  774. def plot_interval_new_tos(file_ending: str):
  775. queryOutput = self.stats_db._process_user_defined_query(
  776. "SELECT lastPktTimestamp, newToSCount FROM interval_statistics ORDER BY lastPktTimestamp")
  777. title = "ToS Novelty Distribution"
  778. xLabel = "Time Interval"
  779. yLabel = "Novel values count"
  780. if queryOutput:
  781. return plot_interval_statistics(queryOutput, title, xLabel, yLabel, file_ending)
  782. def plot_interval_new_win_size(file_ending: str):
  783. queryOutput = self.stats_db._process_user_defined_query(
  784. "SELECT lastPktTimestamp, newWinSizeCount FROM interval_statistics ORDER BY lastPktTimestamp")
  785. title = "Window Size Novelty Distribution"
  786. xLabel = "Time Interval"
  787. yLabel = "Novel values count"
  788. if queryOutput:
  789. return plot_interval_statistics(queryOutput, title, xLabel, yLabel, file_ending)
  790. def plot_interval_new_mss(file_ending: str):
  791. queryOutput = self.stats_db._process_user_defined_query(
  792. "SELECT lastPktTimestamp, newMSSCount FROM interval_statistics ORDER BY lastPktTimestamp")
  793. title = "MSS Novelty Distribution"
  794. xLabel = "Time Interval"
  795. yLabel = "Novel values count"
  796. if queryOutput:
  797. return plot_interval_statistics(queryOutput, title, xLabel, yLabel, file_ending)
  798. def plot_interval_ip_dst_cum_ent(file_ending: str):
  799. plt.gcf().clear()
  800. result = self.stats_db._process_user_defined_query(
  801. "SELECT lastPktTimestamp, ipDstCumEntropy FROM interval_statistics ORDER BY lastPktTimestamp")
  802. graphx, graphy = [], []
  803. for row in result:
  804. graphx.append(row[0])
  805. graphy.append(row[1])
  806. # If entropy was not calculated do not plot the graph
  807. if graphy[0] != -1:
  808. plt.autoscale(enable=True, axis='both')
  809. plt.title("Destination IP Cumulative Entropy")
  810. # plt.xlabel('Timestamp')
  811. plt.xlabel('Time Interval')
  812. plt.ylabel('Entropy')
  813. plt.xlim([0, len(graphx)])
  814. plt.grid(True)
  815. # timestamp on x-axis
  816. x = range(0, len(graphx))
  817. # my_xticks = graphx
  818. # plt.xticks(x, my_xticks, rotation='vertical', fontsize=5)
  819. # plt.tight_layout()
  820. # limit the number of xticks
  821. plt.locator_params(axis='x', nbins=20)
  822. plt.plot(x, graphy, 'r')
  823. out = self.pcap_filepath.replace('.pcap', '_plot-interval-ip-dst-cum-ent' + file_ending)
  824. plt.savefig(out, dpi=500)
  825. return out
  826. def plot_interval_ip_src_cum_ent(file_ending: str):
  827. plt.gcf().clear()
  828. result = self.stats_db._process_user_defined_query(
  829. "SELECT lastPktTimestamp, ipSrcCumEntropy FROM interval_statistics ORDER BY lastPktTimestamp")
  830. graphx, graphy = [], []
  831. for row in result:
  832. graphx.append(row[0])
  833. graphy.append(row[1])
  834. # If entropy was not calculated do not plot the graph
  835. if graphy[0] != -1:
  836. plt.autoscale(enable=True, axis='both')
  837. plt.title("Source IP Cumulative Entropy")
  838. # plt.xlabel('Timestamp')
  839. plt.xlabel('Time Interval')
  840. plt.ylabel('Entropy')
  841. plt.xlim([0, len(graphx)])
  842. plt.grid(True)
  843. # timestamp on x-axis
  844. x = range(0, len(graphx))
  845. # my_xticks = graphx
  846. # plt.xticks(x, my_xticks, rotation='vertical', fontsize=5)
  847. # plt.tight_layout()
  848. # limit the number of xticks
  849. plt.locator_params(axis='x', nbins=20)
  850. plt.plot(x, graphy, 'r')
  851. out = self.pcap_filepath.replace('.pcap', '_plot-interval-ip-src-cum-ent' + file_ending)
  852. plt.savefig(out, dpi=500)
  853. return out
  854. def plot_in_degree(file_ending: str):
  855. """
  856. Creates a Plot, visualizing the in-degree for every IP Address
  857. :param file_ending: The file extension for the output file containing the plot, e.g. "pdf"
  858. :return: A filepath to the file containing the created plot
  859. """
  860. plt.gcf().clear()
  861. # retrieve data
  862. in_degree = self.get_filtered_degree("inDegree")
  863. graphx, graphy = [], []
  864. for entry in in_degree:
  865. # degree values
  866. graphx.append(entry[1])
  867. # IP labels
  868. graphy.append(entry[0])
  869. # set labels
  870. plt.title("Indegree per IP Address")
  871. plt.ylabel('IpAddress')
  872. plt.xlabel('Indegree')
  873. #set width of the bars
  874. width = 0.3
  875. # set scalings
  876. plt.figure(figsize=(int(len(graphx))/20 + 5, int(len(graphy)/5) + 5)) # these proportions just worked well
  877. #set limits of the axis
  878. plt.ylim([0, len(graphy)])
  879. plt.xlim([0, max(graphx) + 10])
  880. # display numbers at each bar
  881. for i, v in enumerate(graphx):
  882. plt.text(v + 1, i + .1, str(v), color='blue', fontweight='bold')
  883. # display grid for better visuals
  884. plt.grid(True)
  885. # plot the bar
  886. labels = graphy
  887. graphy = list(range(len(graphx)))
  888. plt.barh(graphy, graphx, width, align='center', linewidth=1, color='red', edgecolor='red')
  889. plt.yticks(graphy, labels)
  890. out = self.pcap_filepath.replace('.pcap', '_in_degree' + file_ending)
  891. plt.tight_layout()
  892. plt.savefig(out,dpi=500)
  893. return out
  894. def plot_out_degree(file_ending: str):
  895. """
  896. Creates a Plot, visualizing the out-degree for every IP Address
  897. :param file_ending: The file extension for the output file containing the plot, e.g. "pdf"
  898. :return: A filepath to the file containing the created plot
  899. """
  900. plt.gcf().clear()
  901. # retrieve data
  902. out_degree = self.get_filtered_degree("outDegree")
  903. graphx, graphy = [], []
  904. for entry in out_degree:
  905. # degree values
  906. graphx.append(entry[1])
  907. # IP labels
  908. graphy.append(entry[0])
  909. # set labels
  910. plt.title("Outdegree per IP Address")
  911. plt.ylabel('IpAddress')
  912. plt.xlabel('Outdegree')
  913. #set width of the bars
  914. width = 0.3
  915. # set scalings
  916. plt.figure(figsize=(int(len(graphx))/20 + 5, int(len(graphy)/5) + 5)) # these proportions just worked well
  917. #set limits of the axis
  918. plt.ylim([0, len(graphy)])
  919. plt.xlim([0, max(graphx) + 10])
  920. # display numbers at each bar
  921. for i, v in enumerate(graphx):
  922. plt.text(v + 1, i + .1, str(v), color='blue', fontweight='bold')
  923. # display grid for better visuals
  924. plt.grid(True)
  925. # plot the bar
  926. labels = graphy
  927. graphy = list(range(len(graphx)))
  928. plt.barh(graphy, graphx, width, align='center', linewidth=1, color='red', edgecolor='red')
  929. plt.yticks(graphy, labels)
  930. out = self.pcap_filepath.replace('.pcap', '_out_degree' + file_ending)
  931. plt.tight_layout()
  932. plt.savefig(out,dpi=500)
  933. return out
  934. def plot_overall_degree(file_ending: str):
  935. """
  936. Creates a Plot, visualizing the overall-degree for every IP Address
  937. :param file_ending: The file extension for the output file containing the plot, e.g. "pdf"
  938. :return: A filepath to the file containing the created plot
  939. """
  940. plt.gcf().clear()
  941. # retrieve data
  942. overall_degree = self.get_filtered_degree("overallDegree")
  943. graphx, graphy = [], []
  944. for entry in overall_degree:
  945. # degree values
  946. graphx.append(entry[1])
  947. # IP labels
  948. graphy.append(entry[0])
  949. # set labels
  950. plt.title("Overalldegree per IP Address")
  951. plt.ylabel('IpAddress')
  952. plt.xlabel('Overalldegree')
  953. #set width of the bars
  954. width = 0.3
  955. # set scalings
  956. plt.figure(figsize=(int(len(graphx))/20 + 5, int(len(graphy)/5) + 5)) # these proportions just worked well
  957. #set limits of the axis
  958. plt.ylim([0, len(graphy)])
  959. plt.xlim([0, max(graphx) + 10])
  960. # display numbers at each bar
  961. for i, v in enumerate(graphx):
  962. plt.text(v + 1, i + .1, str(v), color='blue', fontweight='bold')
  963. # display grid for better visuals
  964. plt.grid(True)
  965. # plot the bar
  966. labels = graphy
  967. graphy = list(range(len(graphx)))
  968. plt.barh(graphy, graphx, width, align='center', linewidth=1, color='red', edgecolor='red')
  969. plt.yticks(graphy, labels)
  970. out = self.pcap_filepath.replace('.pcap', '_overall_degree' + file_ending)
  971. plt.tight_layout()
  972. plt.savefig(out,dpi=500)
  973. return out
  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. addr1, addr2 = "%s:%d" % (row[0], row[1]), "%s:%d" % (row[2], row[3])
  998. # adjust the justification of strings to improve appearance
  999. len_max = max(len(addr1), len(addr2))
  1000. addr1 = addr1.ljust(len_max)
  1001. addr2 = addr2.ljust(len_max)
  1002. # add plot data
  1003. graphy.append("%s\n%s" % (addr1, addr2))
  1004. graphx.append(row[4])
  1005. # have x axis and its label appear at the top (instead of bottom)
  1006. fig, ax = plt.subplots()
  1007. ax.xaxis.tick_top()
  1008. ax.xaxis.set_label_position("top")
  1009. # compute plot height in inches for scaling the plot
  1010. dist_mult_height, dist_mult_width = 0.55, 0.07 # these values turned out to work well
  1011. # use static scale along the conversation axis, if there are too little entries to use dynamic scaling numbers
  1012. if len(graphy) < 10:
  1013. plt_height = 7.5
  1014. # otherwise use the numbers above
  1015. else:
  1016. plt_height = len(graphy) * dist_mult_height
  1017. # use static scale along the x axis, if the x values are all 0
  1018. if max(graphx) < 200:
  1019. plt_width = 7.5 # 7.5 as static width worked well
  1020. if max(graphx) == 0:
  1021. ax.set_xlim(0, 10)
  1022. # otherwise use the numbers above
  1023. else:
  1024. plt_width = max(graphx) * dist_mult_width
  1025. 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
  1026. plt.gcf().set_size_inches(plt_width, plt_height) # set plot size
  1027. # set additional plot parameters
  1028. plt.title(title, y=title_distance)
  1029. plt.xlabel(xlabel)
  1030. plt.ylabel('Connection')
  1031. width = 0.5
  1032. plt.grid(True)
  1033. plt.gca().margins(y=0) # removes the space between data and x-axis within the plot
  1034. # plot the above data, first use plain numbers as graphy to maintain sorting
  1035. plt.barh(range(len(graphy)), graphx, width, align='center', linewidth=0.5, color='red', edgecolor='red')
  1036. # now change the y numbers to the respective address labels
  1037. plt.yticks(range(len(graphy)), graphy)
  1038. # try to use tight layout to cut off unnecessary space
  1039. try:
  1040. plt.tight_layout(pad=4)
  1041. except (ValueError, numpy.linalg.linalg.LinAlgError):
  1042. pass
  1043. # save created figure
  1044. out = self.pcap_filepath.replace('.pcap', suffix)
  1045. plt.savefig(out, dpi=500)
  1046. return out
  1047. def plot_packets_per_connection(file_ending: str):
  1048. """
  1049. Plots the total number of exchanged packets per connection.
  1050. :param file_ending: The file extension for the output file containing the plot
  1051. :return: A filepath to the file containing the created plot
  1052. """
  1053. title = 'Number of exchanged packets per connection'
  1054. suffix = '_plot-PktCount per Connection Distribution' + file_ending
  1055. # plot data and return outpath
  1056. return plot_big_comm_interval_stat("pktsCount", "conv_statistics_stateless", title, "Number of packets", suffix)
  1057. def plot_avg_pkts_per_comm_interval(file_ending: str):
  1058. """
  1059. Plots the average number of exchanged packets per communication interval for every connection.
  1060. :param file_ending: The file extension for the output file containing the plot
  1061. :return: A filepath to the file containing the created plot
  1062. """
  1063. title = 'Average number of exchanged packets per communication interval'
  1064. suffix = '_plot-Avg PktCount Communication Interval Distribution' + file_ending
  1065. # plot data and return outpath
  1066. return plot_big_comm_interval_stat("avgPktCount", "comm_interval_statistics" ,title, "Number of packets", suffix)
  1067. def plot_avg_time_between_comm_interval(file_ending: str):
  1068. """
  1069. Plots the average time between the communication intervals of every connection.
  1070. :param file_ending: The file extension for the output file containing the plot
  1071. :return: A filepath to the file containing the created plot
  1072. """
  1073. title = 'Average time between communication intervals in seconds'
  1074. suffix = '_plot-Avg Time Between Communication Intervals Distribution' + file_ending
  1075. # plot data and return outpath
  1076. return plot_big_comm_interval_stat("avgTimeBetweenIntervals", "comm_interval_statistics", title, 'Average time between intervals', suffix)
  1077. def plot_avg_comm_interval_time(file_ending: str):
  1078. """
  1079. Plots the average duration of a communication interval of every connection.
  1080. :param file_ending: The file extension for the output file containing the plot
  1081. :return: A filepath to the file containing the created plot
  1082. """
  1083. title = 'Average duration of a communication interval in seconds'
  1084. suffix = '_plot-Avg Duration Communication Interval Distribution' + file_ending
  1085. # plot data and return outpath
  1086. return plot_big_comm_interval_stat("avgIntervalTime", "comm_interval_statistics", title, 'Average interval time', suffix)
  1087. def plot_total_comm_duration(file_ending: str):
  1088. """
  1089. Plots the total communication duration of every connection.
  1090. :param file_ending: The file extension for the output file containing the plot
  1091. :return: A filepath to the file containing the created plot
  1092. """
  1093. title = 'Total communication duration in seconds'
  1094. suffix = '_plot-Total Communication Duration Distribution' + file_ending
  1095. # plot data and return outpath
  1096. return plot_big_comm_interval_stat("totalCommDuration", "comm_interval_statistics", title, 'Duration', suffix)
  1097. ttl_out_path = plot_ttl('.' + format)
  1098. mss_out_path = plot_mss('.' + format)
  1099. win_out_path = plot_win('.' + format)
  1100. protocol_out_path = plot_protocol('.' + format)
  1101. plot_interval_pktCount = plot_interval_pktCount('.' + format)
  1102. plot_interval_ip_src_ent = plot_interval_ip_src_ent('.' + format)
  1103. plot_interval_ip_dst_ent = plot_interval_ip_dst_ent('.' + format)
  1104. plot_interval_ip_src_cum_ent = plot_interval_ip_src_cum_ent('.' + format)
  1105. plot_interval_ip_dst_cum_ent = plot_interval_ip_dst_cum_ent('.' + format)
  1106. plot_interval_new_ip = plot_interval_new_ip('.' + format)
  1107. plot_interval_new_port = plot_interval_new_port('.' + format)
  1108. plot_interval_new_ttl = plot_interval_new_ttl('.' + format)
  1109. plot_interval_new_tos = plot_interval_new_tos('.' + format)
  1110. plot_interval_new_win_size = plot_interval_new_win_size('.' + format)
  1111. plot_interval_new_mss = plot_interval_new_mss('.' + format)
  1112. plot_packets_per_connection_out = plot_packets_per_connection('.' + format)
  1113. plot_out_degree = plot_out_degree('.' + format)
  1114. plot_in_degree = plot_in_degree('.' + format)
  1115. plot_overall_degree = plot_overall_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.")