Statistics.py 65 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481
  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. default_ext = False
  490. default_local = False
  491. if(local_conv):
  492. for conv in local_conv:
  493. avg_delay_local += conv[2]
  494. avg_delay_local = (avg_delay_local/len(local_conv)) * 0.001 #ms
  495. else:
  496. # no local conversations in statistics found
  497. avg_delay_local = 0.055
  498. default_local = True
  499. if(external_conv):
  500. for conv in external_conv:
  501. avg_delay_external += conv[2]
  502. avg_delay_external = (avg_delay_external/len(external_conv)) * 0.001 #ms
  503. else:
  504. # no external conversations in statistics found
  505. avg_delay_external = 0.09
  506. default_ext = True
  507. else:
  508. #if no statistics were found, use these numbers
  509. avg_delay_external = 0.09
  510. avg_delay_local = 0.055
  511. default_ext = True
  512. default_local = True
  513. # check whether delay numbers are consistent
  514. if avg_delay_local > avg_delay_external:
  515. avg_delay_external = avg_delay_local*1.2
  516. # print information, that (default) values are used, that are not collected from the Input PCAP
  517. if default_ext or default_local:
  518. if default_ext and default_local:
  519. print("Warning: Could not collect average delays for local or external communication, using following values:")
  520. elif default_ext:
  521. print("Warning: Could not collect average delays for external communication, using following values:")
  522. elif default_local:
  523. print("Warning: Could not collect average delays for local communication, using following values:")
  524. print("Avg delay of external communication: {0}s, Avg delay of local communication: {1}s".format(avg_delay_external, avg_delay_local))
  525. return avg_delay_local, avg_delay_external
  526. def get_filtered_degree(self, degree_type: str):
  527. """
  528. gets the desired type of degree statistics and filters IPs with degree value zero
  529. :param degree_type: the desired type of degrees, one of the following: inDegree, outDegree, overallDegree
  530. :return: the filtered degrees
  531. """
  532. degrees_raw = self.stats_db._process_user_defined_query(
  533. "SELECT ipAddress, %s FROM ip_degrees" % degree_type)
  534. degrees = []
  535. if(degrees_raw):
  536. for deg in degrees_raw:
  537. if int(deg[1]) > 0:
  538. degrees.append(deg)
  539. return degrees
  540. def get_statistics_database(self):
  541. """
  542. :return: A reference to the statistics database object
  543. """
  544. return self.stats_db
  545. def process_db_query(self, query_string_in: str, print_results: bool = False):
  546. """
  547. Executes a string identified previously as a query. This can be a standard SQL SELECT/INSERT query or a named
  548. query.
  549. :param query_string_in: The query to be processed
  550. :param print_results: Indicates whether the results should be printed to terminal
  551. :return: The result of the query
  552. """
  553. return self.stats_db.process_db_query(query_string_in, print_results)
  554. def is_query(self, value: str):
  555. """
  556. Checks whether the given string is a standard SQL query (SELECT, INSERT) or a named query.
  557. :param value: The string to be checked
  558. :return: True if the string is recognized as a query, otherwise False.
  559. """
  560. if not isinstance(value, str):
  561. return False
  562. else:
  563. return (any(x in value.lower().strip() for x in self.stats_db.get_all_named_query_keywords()) or
  564. any(x in value.lower().strip() for x in self.stats_db.get_all_sql_query_keywords()))
  565. def calculate_standard_deviation(self, lst):
  566. """
  567. Calculates the standard deviation of a list of numbers.
  568. :param lst: The list of numbers to calculate its SD.
  569. """
  570. num_items = len(lst)
  571. mean = sum(lst) / num_items
  572. differences = [x - mean for x in lst]
  573. sq_differences = [d ** 2 for d in differences]
  574. ssd = sum(sq_differences)
  575. variance = ssd / num_items
  576. sd = sqrt(variance)
  577. return sd
  578. def plot_statistics(self, format: str = 'pdf'): #'png'
  579. """
  580. Plots the statistics associated with the dataset.
  581. :param format: The format to be used to save the statistics diagrams.
  582. """
  583. def plot_distribution(queryOutput, title, xLabel, yLabel, file_ending: str):
  584. plt.gcf().clear()
  585. graphx, graphy = [], []
  586. for row in queryOutput:
  587. graphx.append(row[0])
  588. graphy.append(row[1])
  589. plt.autoscale(enable=True, axis='both')
  590. plt.title(title)
  591. plt.xlabel(xLabel)
  592. plt.ylabel(yLabel)
  593. width = 0.1
  594. plt.xlim([0, max(graphx)])
  595. plt.grid(True)
  596. plt.bar(graphx, graphy, width, align='center', linewidth=1, color='red', edgecolor='red')
  597. out = self.pcap_filepath.replace('.pcap', '_plot-' + title + file_ending)
  598. plt.savefig(out,dpi=500)
  599. return out
  600. def plot_ttl(file_ending: str):
  601. queryOutput = self.stats_db._process_user_defined_query(
  602. "SELECT ttlValue, SUM(ttlCount) FROM ip_ttl GROUP BY ttlValue")
  603. title = "TTL Distribution"
  604. xLabel = "TTL Value"
  605. yLabel = "Number of Packets"
  606. if queryOutput:
  607. return plot_distribution(queryOutput, title, xLabel, yLabel, file_ending)
  608. def plot_mss(file_ending: str):
  609. queryOutput = self.stats_db._process_user_defined_query(
  610. "SELECT mssValue, SUM(mssCount) FROM tcp_mss GROUP BY mssValue")
  611. title = "MSS Distribution"
  612. xLabel = "MSS Value"
  613. yLabel = "Number of Packets"
  614. if queryOutput:
  615. return plot_distribution(queryOutput, title, xLabel, yLabel, file_ending)
  616. def plot_win(file_ending: str):
  617. queryOutput = self.stats_db._process_user_defined_query(
  618. "SELECT winSize, SUM(winCount) FROM tcp_win GROUP BY winSize")
  619. title = "Window Size Distribution"
  620. xLabel = "Window Size"
  621. yLabel = "Number of Packets"
  622. if queryOutput:
  623. return plot_distribution(queryOutput, title, xLabel, yLabel, file_ending)
  624. def plot_protocol(file_ending: str):
  625. plt.gcf().clear()
  626. result = self.stats_db._process_user_defined_query(
  627. "SELECT protocolName, SUM(protocolCount) FROM ip_protocols GROUP BY protocolName")
  628. if (result):
  629. graphx, graphy = [], []
  630. for row in result:
  631. graphx.append(row[0])
  632. graphy.append(row[1])
  633. plt.autoscale(enable=True, axis='both')
  634. plt.title("Protocols Distribution")
  635. plt.xlabel('Protocols')
  636. plt.ylabel('Number of Packets')
  637. width = 0.1
  638. plt.xlim([0, len(graphx)])
  639. plt.grid(True)
  640. # Protocols' names on x-axis
  641. x = range(0,len(graphx))
  642. my_xticks = graphx
  643. plt.xticks(x, my_xticks)
  644. plt.bar(x, graphy, width, align='center', linewidth=1, color='red', edgecolor='red')
  645. out = self.pcap_filepath.replace('.pcap', '_plot-protocol' + file_ending)
  646. plt.savefig(out,dpi=500)
  647. return out
  648. else:
  649. print("Error plot protocol: No protocol values found!")
  650. def plot_port(file_ending: str):
  651. plt.gcf().clear()
  652. result = self.stats_db._process_user_defined_query(
  653. "SELECT portNumber, SUM(portCount) FROM ip_ports GROUP BY portNumber")
  654. graphx, graphy = [], []
  655. for row in result:
  656. graphx.append(row[0])
  657. graphy.append(row[1])
  658. plt.autoscale(enable=True, axis='both')
  659. plt.title("Ports Distribution")
  660. plt.xlabel('Ports Numbers')
  661. plt.ylabel('Number of Packets')
  662. width = 0.1
  663. plt.xlim([0, max(graphx)])
  664. plt.grid(True)
  665. plt.bar(graphx, graphy, width, align='center', linewidth=1, color='red', edgecolor='red')
  666. out = self.pcap_filepath.replace('.pcap', '_plot-port' + file_ending)
  667. plt.savefig(out,dpi=500)
  668. return out
  669. # This distribution is not drawable for big datasets
  670. def plot_ip_src(file_ending: str):
  671. plt.gcf().clear()
  672. result = self.stats_db._process_user_defined_query(
  673. "SELECT ipAddress, pktsSent FROM ip_statistics")
  674. graphx, graphy = [], []
  675. for row in result:
  676. graphx.append(row[0])
  677. graphy.append(row[1])
  678. plt.autoscale(enable=True, axis='both')
  679. plt.title("Source IP Distribution")
  680. plt.xlabel('Source IP')
  681. plt.ylabel('Number of Packets')
  682. width = 0.1
  683. plt.xlim([0, len(graphx)])
  684. plt.grid(True)
  685. # IPs on x-axis
  686. x = range(0, len(graphx))
  687. my_xticks = graphx
  688. plt.xticks(x, my_xticks, rotation='vertical', fontsize=5)
  689. plt.tight_layout()
  690. # limit the number of xticks
  691. plt.locator_params(axis='x', nbins=20)
  692. plt.bar(x, graphy, width, align='center', linewidth=1, color='red', edgecolor='red')
  693. out = self.pcap_filepath.replace('.pcap', '_plot-ip-src' + file_ending)
  694. plt.savefig(out, dpi=500)
  695. return out
  696. # This distribution is not drawable for big datasets
  697. def plot_ip_dst(file_ending: str):
  698. plt.gcf().clear()
  699. result = self.stats_db._process_user_defined_query(
  700. "SELECT ipAddress, pktsReceived FROM ip_statistics")
  701. graphx, graphy = [], []
  702. for row in result:
  703. graphx.append(row[0])
  704. graphy.append(row[1])
  705. plt.autoscale(enable=True, axis='both')
  706. plt.title("Destination IP Distribution")
  707. plt.xlabel('Destination IP')
  708. plt.ylabel('Number of Packets')
  709. width = 0.1
  710. plt.xlim([0, len(graphx)])
  711. plt.grid(True)
  712. # IPs on x-axis
  713. x = range(0, len(graphx))
  714. my_xticks = graphx
  715. plt.xticks(x, my_xticks, rotation='vertical', fontsize=5)
  716. plt.tight_layout()
  717. # limit the number of xticks
  718. plt.locator_params(axis='x', nbins=20)
  719. plt.bar(x, graphy, width, align='center', linewidth=1, color='red', edgecolor='red')
  720. out = self.pcap_filepath.replace('.pcap', '_plot-ip-dst' + file_ending)
  721. plt.savefig(out, dpi=500)
  722. return out
  723. def plot_interval_statistics(queryOutput, title, xLabel, yLabel, file_ending: str):
  724. plt.gcf().clear()
  725. graphx, graphy = [], []
  726. for row in queryOutput:
  727. graphx.append(row[0])
  728. graphy.append(row[1])
  729. plt.autoscale(enable=True, axis='both')
  730. plt.title(title)
  731. plt.xlabel(xLabel)
  732. plt.ylabel(yLabel)
  733. width = 0.5
  734. plt.xlim([0, len(graphx)])
  735. plt.grid(True)
  736. # timestamp on x-axis
  737. x = range(0, len(graphx))
  738. # limit the number of xticks
  739. plt.locator_params(axis='x', nbins=20)
  740. plt.bar(x, graphy, width, align='center', linewidth=1, color='red', edgecolor='red')
  741. out = self.pcap_filepath.replace('.pcap', '_plot-' + title + file_ending)
  742. plt.savefig(out, dpi=500)
  743. return out
  744. def plot_interval_pktCount(file_ending: str):
  745. queryOutput = self.stats_db._process_user_defined_query(
  746. "SELECT lastPktTimestamp, pktsCount FROM interval_statistics ORDER BY lastPktTimestamp")
  747. title = "Packet Rate"
  748. xLabel = "Time Interval"
  749. yLabel = "Number of Packets"
  750. if queryOutput:
  751. return plot_interval_statistics(queryOutput, title, xLabel, yLabel, file_ending)
  752. def plot_interval_ip_src_ent(file_ending: str):
  753. queryOutput = self.stats_db._process_user_defined_query(
  754. "SELECT lastPktTimestamp, ipSrcEntropy FROM interval_statistics ORDER BY lastPktTimestamp")
  755. title = "Source IP Entropy"
  756. xLabel = "Time Interval"
  757. yLabel = "Entropy"
  758. if queryOutput:
  759. return plot_interval_statistics(queryOutput, title, xLabel, yLabel, file_ending)
  760. def plot_interval_ip_dst_ent(file_ending: str):
  761. queryOutput = self.stats_db._process_user_defined_query(
  762. "SELECT lastPktTimestamp, ipDstEntropy FROM interval_statistics ORDER BY lastPktTimestamp")
  763. title = "Destination IP Entropy"
  764. xLabel = "Time Interval"
  765. yLabel = "Entropy"
  766. if queryOutput:
  767. return plot_interval_statistics(queryOutput, title, xLabel, yLabel, file_ending)
  768. def plot_interval_new_ip(file_ending: str):
  769. queryOutput = self.stats_db._process_user_defined_query(
  770. "SELECT lastPktTimestamp, newIPCount FROM interval_statistics ORDER BY lastPktTimestamp")
  771. title = "IP Novelty Distribution"
  772. xLabel = "Time Interval"
  773. yLabel = "Novel values count"
  774. if queryOutput:
  775. return plot_interval_statistics(queryOutput, title, xLabel, yLabel, file_ending)
  776. def plot_interval_new_port(file_ending: str):
  777. queryOutput = self.stats_db._process_user_defined_query(
  778. "SELECT lastPktTimestamp, newPortCount FROM interval_statistics ORDER BY lastPktTimestamp")
  779. title = "Port Novelty Distribution"
  780. xLabel = "Time Interval"
  781. yLabel = "Novel values count"
  782. if queryOutput:
  783. return plot_interval_statistics(queryOutput, title, xLabel, yLabel, file_ending)
  784. def plot_interval_new_ttl(file_ending: str):
  785. queryOutput = self.stats_db._process_user_defined_query(
  786. "SELECT lastPktTimestamp, newTTLCount FROM interval_statistics ORDER BY lastPktTimestamp")
  787. title = "TTL 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_tos(file_ending: str):
  793. queryOutput = self.stats_db._process_user_defined_query(
  794. "SELECT lastPktTimestamp, newToSCount FROM interval_statistics ORDER BY lastPktTimestamp")
  795. title = "ToS 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_win_size(file_ending: str):
  801. queryOutput = self.stats_db._process_user_defined_query(
  802. "SELECT lastPktTimestamp, newWinSizeCount FROM interval_statistics ORDER BY lastPktTimestamp")
  803. title = "Window Size 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_mss(file_ending: str):
  809. queryOutput = self.stats_db._process_user_defined_query(
  810. "SELECT lastPktTimestamp, newMSSCount FROM interval_statistics ORDER BY lastPktTimestamp")
  811. title = "MSS 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_ip_dst_cum_ent(file_ending: str):
  817. plt.gcf().clear()
  818. result = self.stats_db._process_user_defined_query(
  819. "SELECT lastPktTimestamp, ipDstCumEntropy FROM interval_statistics ORDER BY lastPktTimestamp")
  820. graphx, graphy = [], []
  821. for row in result:
  822. graphx.append(row[0])
  823. graphy.append(row[1])
  824. # If entropy was not calculated do not plot the graph
  825. if graphy[0] != -1:
  826. plt.autoscale(enable=True, axis='both')
  827. plt.title("Destination IP Cumulative Entropy")
  828. # plt.xlabel('Timestamp')
  829. plt.xlabel('Time Interval')
  830. plt.ylabel('Entropy')
  831. plt.xlim([0, len(graphx)])
  832. plt.grid(True)
  833. # timestamp on x-axis
  834. x = range(0, len(graphx))
  835. # my_xticks = graphx
  836. # plt.xticks(x, my_xticks, rotation='vertical', fontsize=5)
  837. # plt.tight_layout()
  838. # limit the number of xticks
  839. plt.locator_params(axis='x', nbins=20)
  840. plt.plot(x, graphy, 'r')
  841. out = self.pcap_filepath.replace('.pcap', '_plot-interval-ip-dst-cum-ent' + file_ending)
  842. plt.savefig(out, dpi=500)
  843. return out
  844. def plot_interval_ip_src_cum_ent(file_ending: str):
  845. plt.gcf().clear()
  846. result = self.stats_db._process_user_defined_query(
  847. "SELECT lastPktTimestamp, ipSrcCumEntropy FROM interval_statistics ORDER BY lastPktTimestamp")
  848. graphx, graphy = [], []
  849. for row in result:
  850. graphx.append(row[0])
  851. graphy.append(row[1])
  852. # If entropy was not calculated do not plot the graph
  853. if graphy[0] != -1:
  854. plt.autoscale(enable=True, axis='both')
  855. plt.title("Source IP Cumulative Entropy")
  856. # plt.xlabel('Timestamp')
  857. plt.xlabel('Time Interval')
  858. plt.ylabel('Entropy')
  859. plt.xlim([0, len(graphx)])
  860. plt.grid(True)
  861. # timestamp on x-axis
  862. x = range(0, len(graphx))
  863. # my_xticks = graphx
  864. # plt.xticks(x, my_xticks, rotation='vertical', fontsize=5)
  865. # plt.tight_layout()
  866. # limit the number of xticks
  867. plt.locator_params(axis='x', nbins=20)
  868. plt.plot(x, graphy, 'r')
  869. out = self.pcap_filepath.replace('.pcap', '_plot-interval-ip-src-cum-ent' + file_ending)
  870. plt.savefig(out, dpi=500)
  871. return out
  872. def plot_in_degree(file_ending: str):
  873. """
  874. Creates a Plot, visualizing the in-degree for every IP Address
  875. :param file_ending: The file extension for the output file containing the plot, e.g. "pdf"
  876. :return: A filepath to the file containing the created plot
  877. """
  878. plt.gcf().clear()
  879. # retrieve data
  880. in_degree = self.get_filtered_degree("inDegree")
  881. graphx, graphy = [], []
  882. for entry in in_degree:
  883. # degree values
  884. graphx.append(entry[1])
  885. # IP labels
  886. graphy.append(entry[0])
  887. # set labels
  888. plt.title("Indegree per IP Address")
  889. plt.ylabel('IpAddress')
  890. plt.xlabel('Indegree')
  891. #set width of the bars
  892. width = 0.3
  893. # set scalings
  894. plt.figure(figsize=(int(len(graphx))/20 + 5, int(len(graphy)/5) + 5)) # these proportions just worked well
  895. #set limits of the axis
  896. plt.ylim([0, len(graphy)])
  897. plt.xlim([0, max(graphx) + 10])
  898. # display numbers at each bar
  899. for i, v in enumerate(graphx):
  900. plt.text(v + 1, i + .1, str(v), color='blue', fontweight='bold')
  901. # display grid for better visuals
  902. plt.grid(True)
  903. # plot the bar
  904. labels = graphy
  905. graphy = list(range(len(graphx)))
  906. plt.barh(graphy, graphx, width, align='center', linewidth=1, color='red', edgecolor='red')
  907. plt.yticks(graphy, labels)
  908. out = self.pcap_filepath.replace('.pcap', '_in_degree' + file_ending)
  909. plt.tight_layout()
  910. plt.savefig(out,dpi=500)
  911. return out
  912. def plot_out_degree(file_ending: str):
  913. """
  914. Creates a Plot, visualizing the out-degree for every IP Address
  915. :param file_ending: The file extension for the output file containing the plot, e.g. "pdf"
  916. :return: A filepath to the file containing the created plot
  917. """
  918. plt.gcf().clear()
  919. # retrieve data
  920. out_degree = self.get_filtered_degree("outDegree")
  921. graphx, graphy = [], []
  922. for entry in out_degree:
  923. # degree values
  924. graphx.append(entry[1])
  925. # IP labels
  926. graphy.append(entry[0])
  927. # set labels
  928. plt.title("Outdegree per IP Address")
  929. plt.ylabel('IpAddress')
  930. plt.xlabel('Outdegree')
  931. #set width of the bars
  932. width = 0.3
  933. # set scalings
  934. plt.figure(figsize=(int(len(graphx))/20 + 5, int(len(graphy)/5) + 5)) # these proportions just worked well
  935. #set limits of the axis
  936. plt.ylim([0, len(graphy)])
  937. plt.xlim([0, max(graphx) + 10])
  938. # display numbers at each bar
  939. for i, v in enumerate(graphx):
  940. plt.text(v + 1, i + .1, str(v), color='blue', fontweight='bold')
  941. # display grid for better visuals
  942. plt.grid(True)
  943. # plot the bar
  944. labels = graphy
  945. graphy = list(range(len(graphx)))
  946. plt.barh(graphy, graphx, width, align='center', linewidth=1, color='red', edgecolor='red')
  947. plt.yticks(graphy, labels)
  948. out = self.pcap_filepath.replace('.pcap', '_out_degree' + file_ending)
  949. plt.tight_layout()
  950. plt.savefig(out,dpi=500)
  951. return out
  952. def plot_overall_degree(file_ending: str):
  953. """
  954. Creates a Plot, visualizing the overall-degree for every IP Address
  955. :param file_ending: The file extension for the output file containing the plot, e.g. "pdf"
  956. :return: A filepath to the file containing the created plot
  957. """
  958. plt.gcf().clear()
  959. # retrieve data
  960. overall_degree = self.get_filtered_degree("overallDegree")
  961. graphx, graphy = [], []
  962. for entry in overall_degree:
  963. # degree values
  964. graphx.append(entry[1])
  965. # IP labels
  966. graphy.append(entry[0])
  967. # set labels
  968. plt.title("Overalldegree per IP Address")
  969. plt.ylabel('IpAddress')
  970. plt.xlabel('Overalldegree')
  971. #set width of the bars
  972. width = 0.3
  973. # set scalings
  974. plt.figure(figsize=(int(len(graphx))/20 + 5, int(len(graphy)/5) + 5)) # these proportions just worked well
  975. #set limits of the axis
  976. plt.ylim([0, len(graphy)])
  977. plt.xlim([0, max(graphx) + 10])
  978. # display numbers at each bar
  979. for i, v in enumerate(graphx):
  980. plt.text(v + 1, i + .1, str(v), color='blue', fontweight='bold')
  981. # display grid for better visuals
  982. plt.grid(True)
  983. # plot the bar
  984. labels = graphy
  985. graphy = list(range(len(graphx)))
  986. plt.barh(graphy, graphx, width, align='center', linewidth=1, color='red', edgecolor='red')
  987. plt.yticks(graphy, labels)
  988. out = self.pcap_filepath.replace('.pcap', '_overall_degree' + file_ending)
  989. plt.tight_layout()
  990. plt.savefig(out,dpi=500)
  991. return out
  992. def plot_big_conv_ext_stat(attr:str, title:str, xlabel:str, suffix:str):
  993. """
  994. Plots the desired statistc per connection as horizontal bar plot.
  995. Included are 'half-open' connections, where only one packet is exchanged.
  996. The given statistics table has to have at least the attributes 'ipAddressA', 'portA', 'ipAddressB',
  997. 'portB' and the specified additional attribute.
  998. Note: there may be cutoff/scaling problems within the plot if there is too little data.
  999. :param attr: The desired statistic, named with respect to its attribute in the given statistics table
  1000. :param table: The statistics table
  1001. :param title: The title of the created plot
  1002. :param xlabel: The name of the x-axis of the created plot
  1003. :param suffix: The suffix of the created file, including file extension
  1004. :return: A filepath to the file containing the created plot
  1005. """
  1006. plt.gcf().clear()
  1007. result = self.stats_db._process_user_defined_query(
  1008. "SELECT ipAddressA, portA, ipAddressB, portB, %s FROM conv_statistics_extended" % attr)
  1009. if (result):
  1010. graphy, graphx = [], []
  1011. # plot data in descending order
  1012. result = sorted(result, key=lambda row: row[4])
  1013. # compute plot data
  1014. for i, row in enumerate(result):
  1015. addr1, addr2 = "%s:%d" % (row[0], row[1]), "%s:%d" % (row[2], row[3])
  1016. # adjust the justification of strings to improve appearance
  1017. len_max = max(len(addr1), len(addr2))
  1018. addr1 = addr1.ljust(len_max)
  1019. addr2 = addr2.ljust(len_max)
  1020. # add plot data
  1021. graphy.append("%s\n%s" % (addr1, addr2))
  1022. graphx.append(row[4])
  1023. # have x axis and its label appear at the top (instead of bottom)
  1024. fig, ax = plt.subplots()
  1025. ax.xaxis.tick_top()
  1026. ax.xaxis.set_label_position("top")
  1027. # compute plot height in inches for scaling the plot
  1028. dist_mult_height, dist_mult_width = 0.55, 0.07 # these values turned out to work well
  1029. # use static scale along the conversation axis, if there are too little entries to use dynamic scaling numbers
  1030. if len(graphy) < 10:
  1031. plt_height = 7.5
  1032. # otherwise use the numbers above
  1033. else:
  1034. plt_height = len(graphy) * dist_mult_height
  1035. # use static scale along the x axis, if the x values are all 0
  1036. if max(graphx) < 200:
  1037. plt_width = 7.5 # 7.5 as static width worked well
  1038. if max(graphx) == 0:
  1039. ax.set_xlim(0, 10)
  1040. # otherwise use the numbers above
  1041. else:
  1042. plt_width = max(graphx) * dist_mult_width
  1043. 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
  1044. # if title would be cut off, set minimum width
  1045. min_width = len(title) * 0.15
  1046. if plt_width < min_width:
  1047. plt_width = min_width
  1048. plt.gcf().set_size_inches(plt_width, plt_height) # set plot size
  1049. # set additional plot parameters
  1050. plt.title(title, y=title_distance)
  1051. plt.xlabel(xlabel)
  1052. plt.ylabel('Connection')
  1053. width = 0.5
  1054. plt.grid(True)
  1055. plt.gca().margins(y=0) # removes the space between data and x-axis within the plot
  1056. # plot the above data, first use plain numbers as graphy to maintain sorting
  1057. plt.barh(range(len(graphy)), graphx, width, align='center', linewidth=0.5, color='red', edgecolor='red')
  1058. # now change the y numbers to the respective address labels
  1059. plt.yticks(range(len(graphy)), graphy)
  1060. # try to use tight layout to cut off unnecessary space
  1061. try:
  1062. plt.tight_layout(pad=4)
  1063. except (ValueError, numpy.linalg.linalg.LinAlgError):
  1064. pass
  1065. # save created figure
  1066. out = self.pcap_filepath.replace('.pcap', suffix)
  1067. plt.savefig(out, dpi=500)
  1068. return out
  1069. def plot_packets_per_connection(file_ending: str):
  1070. """
  1071. Plots the total number of exchanged packets per connection.
  1072. :param file_ending: The file extension for the output file containing the plot
  1073. :return: A filepath to the file containing the created plot
  1074. """
  1075. title = 'Number of exchanged packets per connection'
  1076. suffix = '_plot-PktCount per Connection Distribution' + file_ending
  1077. # plot data and return outpath
  1078. return plot_big_conv_ext_stat("pktsCount", title, "Number of packets", suffix)
  1079. def plot_avg_pkts_per_comm_interval(file_ending: str):
  1080. """
  1081. Plots the average number of exchanged packets per communication interval for every connection.
  1082. :param file_ending: The file extension for the output file containing the plot
  1083. :return: A filepath to the file containing the created plot
  1084. """
  1085. title = 'Average number of exchanged packets per communication interval'
  1086. suffix = '_plot-Avg PktCount Communication Interval Distribution' + file_ending
  1087. # plot data and return outpath
  1088. return plot_big_conv_ext_stat("avgIntervalPktCount", title, "Number of packets", suffix)
  1089. def plot_avg_time_between_comm_interval(file_ending: str):
  1090. """
  1091. Plots the average time between the communication intervals of every connection.
  1092. :param file_ending: The file extension for the output file containing the plot
  1093. :return: A filepath to the file containing the created plot
  1094. """
  1095. title = 'Average time between communication intervals in seconds'
  1096. suffix = '_plot-Avg Time Between Communication Intervals Distribution' + file_ending
  1097. # plot data and return outpath
  1098. return plot_big_conv_ext_stat("avgTimeBetweenIntervals", title, 'Average time between intervals', suffix)
  1099. def plot_avg_comm_interval_time(file_ending: str):
  1100. """
  1101. Plots the average duration of a communication interval of every connection.
  1102. :param file_ending: The file extension for the output file containing the plot
  1103. :return: A filepath to the file containing the created plot
  1104. """
  1105. title = 'Average duration of a communication interval in seconds'
  1106. suffix = '_plot-Avg Duration Communication Interval Distribution' + file_ending
  1107. # plot data and return outpath
  1108. return plot_big_conv_ext_stat("avgIntervalTime", title, 'Average interval time', suffix)
  1109. def plot_total_comm_duration(file_ending: str):
  1110. """
  1111. Plots the total communication duration of every connection.
  1112. :param file_ending: The file extension for the output file containing the plot
  1113. :return: A filepath to the file containing the created plot
  1114. """
  1115. title = 'Total communication duration in seconds'
  1116. suffix = '_plot-Total Communication Duration Distribution' + file_ending
  1117. # plot data and return outpath
  1118. return plot_big_conv_ext_stat("totalConversationDuration", title, 'Duration', suffix)
  1119. def plot_comm_histogram(attr:str, title:str, label:str, suffix:str):
  1120. """
  1121. Plots a histogram about the specified attribute for communications.
  1122. :param attr: The statistics attribute for this histogram
  1123. :param title: The title of the histogram
  1124. :param label: The xlabel of the histogram
  1125. :param suffix: The file suffix
  1126. :return: The path to the created plot
  1127. """
  1128. plt.gcf().clear()
  1129. result_raw = self.stats_db._process_user_defined_query(
  1130. "SELECT %s FROM conv_statistics_extended" % attr)
  1131. # return without plotting if no data available
  1132. if not result_raw:
  1133. return None
  1134. result = []
  1135. for entry in result_raw:
  1136. result.append(entry[0])
  1137. # if title would be cut off, set minimum width
  1138. plt_size = plt.gcf().get_size_inches()
  1139. min_width = len(title) * 0.12
  1140. if plt_size[0] < min_width:
  1141. plt.gcf().set_size_inches(min_width, plt_size[1]) # set plot size
  1142. # set additional plot parameters
  1143. plt.title(title)
  1144. plt.ylabel("Number of connections")
  1145. plt.xlabel(label)
  1146. width = 0.5
  1147. plt.grid(True)
  1148. # create 11 bins
  1149. bins = []
  1150. max_val = max(result)
  1151. for i in range(0, 11):
  1152. bins.append(i * max_val/10)
  1153. # comment out and set weights to normalize
  1154. # weights = numpy.ones_like(result)/float(len(result))
  1155. # plot the above data, first use plain numbers as graphy to maintain sorting
  1156. plt.hist(result, bins=bins, color='red', edgecolor='red', align="mid", rwidth=0.5)
  1157. plt.xticks(bins)
  1158. # save created figure
  1159. out = self.pcap_filepath.replace('.pcap', suffix)
  1160. plt.savefig(out, dpi=500)
  1161. return out
  1162. def plot_histogram_degree(degree_type:str, title:str, label:str, suffix:str):
  1163. """
  1164. Plots a histogram about the specified type for the degree of an IP.
  1165. :param degree_type: The type of degree, i.e. inDegree, outDegree or overallDegree
  1166. :param title: The title of the histogram
  1167. :param label: The xlabel of the histogram
  1168. :param suffix: The file suffix
  1169. :return: The path to the created plot
  1170. """
  1171. plt.gcf().clear()
  1172. result_raw = self.get_filtered_degree(degree_type)
  1173. # return without plotting if no data available
  1174. if not result_raw:
  1175. return None
  1176. result = []
  1177. for entry in result_raw:
  1178. result.append(entry[1])
  1179. # set additional plot parameters
  1180. plt.title(title)
  1181. plt.ylabel("Number of IPs")
  1182. plt.xlabel(label)
  1183. width = 0.5
  1184. plt.grid(True)
  1185. # create 11 bins
  1186. bins = []
  1187. max_val = max(result)
  1188. for i in range(0, 11):
  1189. bins.append(int(i * max_val/10))
  1190. # comment out and set weights to normalize
  1191. # weights = numpy.ones_like(result)/float(len(result))
  1192. # plot the above data, first use plain numbers as graphy to maintain sorting
  1193. plt.hist(result, bins=bins, color='red', edgecolor='red', align="mid", rwidth=0.5)
  1194. plt.xticks(bins)
  1195. # save created figure
  1196. out = self.pcap_filepath.replace('.pcap', suffix)
  1197. plt.savefig(out, dpi=500)
  1198. return out
  1199. ttl_out_path = plot_ttl('.' + format)
  1200. mss_out_path = plot_mss('.' + format)
  1201. win_out_path = plot_win('.' + format)
  1202. protocol_out_path = plot_protocol('.' + format)
  1203. plot_interval_pktCount = plot_interval_pktCount('.' + format)
  1204. plot_interval_ip_src_ent = plot_interval_ip_src_ent('.' + format)
  1205. plot_interval_ip_dst_ent = plot_interval_ip_dst_ent('.' + format)
  1206. plot_interval_ip_src_cum_ent = plot_interval_ip_src_cum_ent('.' + format)
  1207. plot_interval_ip_dst_cum_ent = plot_interval_ip_dst_cum_ent('.' + format)
  1208. plot_interval_new_ip = plot_interval_new_ip('.' + format)
  1209. plot_interval_new_port = plot_interval_new_port('.' + format)
  1210. plot_interval_new_ttl = plot_interval_new_ttl('.' + format)
  1211. plot_interval_new_tos = plot_interval_new_tos('.' + format)
  1212. plot_interval_new_win_size = plot_interval_new_win_size('.' + format)
  1213. plot_interval_new_mss = plot_interval_new_mss('.' + format)
  1214. plot_packets_per_connection_out = plot_packets_per_connection('.' + format)
  1215. plot_out_degree = plot_out_degree('.' + format)
  1216. plot_in_degree = plot_in_degree('.' + format)
  1217. plot_overall_degree = plot_overall_degree('.' + format)
  1218. plot_avg_pkts_per_comm_interval_out = plot_avg_pkts_per_comm_interval('.' + format)
  1219. plot_avg_time_between_comm_interval_out = plot_avg_time_between_comm_interval('.' + format)
  1220. plot_avg_comm_interval_time_out = plot_avg_comm_interval_time("." + format)
  1221. plot_total_comm_duration_out = plot_total_comm_duration("." + format)
  1222. plot_hist_pkts_per_connection_out = plot_comm_histogram("pktsCount", "Histogram - Number of exchanged packets per connection",
  1223. "Number of packets", "_plot-Histogram PktCount per Connection" + "." + format)
  1224. plot_hist_avgpkts_per_commint_out = plot_comm_histogram("avgIntervalPktCount", "Histogram - Average number of exchanged packets per communication interval",
  1225. "Average number of packets", "_plot-Histogram Avg PktCount per Interval per Connection" + "." + format)
  1226. plot_hist_avgtime_betw_commints_out = plot_comm_histogram("avgTimeBetweenIntervals", "Histogram - Average time between communication intervals in seconds",
  1227. "Average time between intervals", "_plot-Histogram Avg Time Between Intervals per Connection" + "." + format)
  1228. plot_hist_avg_int_time_per_connection_out = plot_comm_histogram("avgIntervalTime", "Histogram - Average duration of a communication interval in seconds",
  1229. "Average interval time", "_plot-Histogram Avg Interval Time per Connection" + "." + format)
  1230. plot_hist_total_comm_duration_out = plot_comm_histogram("totalConversationDuration", "Histogram - Total communication duration in seconds",
  1231. "Duration", "_plot-Histogram Communication Duration per Connection" + "." + format)
  1232. # plot_hist_indegree_out = plot_histogram_degree("inDegree", "Histogram - Ingoing degree per IP Address",
  1233. # "Ingoing degree", "_plot-Histogram Ingoing Degree per IP" + format)
  1234. # plot_hist_outdegree_out = plot_histogram_degree("outDegree", "Histogram - Outgoing degree per IP Address",
  1235. # "Outgoing degree", "_plot-Histogram Outgoing Degree per IP" + format)
  1236. # plot_hist_overalldegree_out = plot_histogram_degree("overallDegree", "Histogram - Overall degree per IP Address",
  1237. # "Overall degree", "_plot-Histogram Overall Degree per IP" + format)
  1238. ## Time consuming plot
  1239. # port_out_path = plot_port('.' + format)
  1240. ## Not drawable for too many IPs
  1241. # ip_src_out_path = plot_ip_src('.' + format)
  1242. # ip_dst_out_path = plot_ip_dst('.' + format)
  1243. print("Saved plots in the input PCAP directory.")