Statistics.py 52 KB

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