Statistics.py 58 KB

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