3
0

StatsDatabase.py 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362
  1. import os.path
  2. import random as rnd
  3. import re
  4. import sqlite3
  5. import sys
  6. # TODO: double check this import
  7. # does it complain because libpcapreader is not a .py?
  8. import ID2TLib.libpcapreader as pr
  9. import Core.QueryParser as qp
  10. import pyparsing as pp
  11. def dict_gen(curs: sqlite3.Cursor):
  12. """
  13. Generates a dictionary of a sqlite3.Cursor object by fetching the query's results.
  14. Taken from Python Essential Reference by David Beazley.
  15. """
  16. field_names = [d[0] for d in curs.description]
  17. while True:
  18. rows = curs.fetchmany()
  19. if not rows:
  20. return
  21. for row in rows:
  22. yield dict(zip(field_names, row))
  23. class StatsDatabase:
  24. def __init__(self, db_path: str):
  25. """
  26. Creates a new StatsDatabase.
  27. :param db_path: The path to the database file
  28. """
  29. self.query_parser = qp.QueryParser()
  30. self.existing_db = os.path.exists(db_path)
  31. self.database = sqlite3.connect(db_path)
  32. self.cursor = self.database.cursor()
  33. # If DB not existing, create a new DB scheme
  34. if self.existing_db:
  35. if self.get_db_outdated():
  36. print('Statistics database outdated. Recreating database at: ', db_path)
  37. else:
  38. print('Located statistics database at: ', db_path)
  39. else:
  40. print('Statistics database not found. Creating new database at: ', db_path)
  41. def get_file_info(self):
  42. """
  43. Retrieves general file statistics from the database. This includes:
  44. - packetCount : Number of packets in the PCAP file
  45. - captureDuration : Duration of the packet capture in seconds
  46. - timestampFirstPacket : Timestamp of the first captured packet
  47. - timestampLastPacket : Timestamp of the last captured packet
  48. - avgPacketRate : Average packet rate
  49. - avgPacketSize : Average packet size
  50. - avgPacketsSentPerHost : Average number of packets sent per host
  51. - avgBandwidthIn : Average incoming bandwidth
  52. - avgBandwidthOut : Average outgoing bandwidth
  53. :return: a dictionary of keys (see above) and their respective values
  54. """
  55. return [r for r in dict_gen(
  56. self.cursor.execute('SELECT * FROM file_statistics'))][0]
  57. def get_db_exists(self):
  58. """
  59. :return: True if the database was already existent, otherwise False
  60. """
  61. return self.existing_db
  62. def get_db_outdated(self):
  63. """
  64. Retrieves the database version from the database and compares it to the version
  65. it should have to check whether the database is outdated and needs to be recreated.
  66. :return: True if the versions match, otherwise False
  67. """
  68. self.cursor.execute('PRAGMA user_version;')
  69. return self.cursor.fetchall()[0][0] != pr.pcap_processor.get_db_version()
  70. @staticmethod
  71. def _get_selector_keywords():
  72. """
  73. :return: a list of selector keywords
  74. """
  75. return ['most_used', 'least_used', 'avg', 'all']
  76. @staticmethod
  77. def _get_parametrized_selector_keywords():
  78. """
  79. :return: a list of parameterizable selector keywords
  80. """
  81. return ['ipaddress', 'macaddress']
  82. @staticmethod
  83. def _get_extractor_keywords():
  84. """
  85. :return: a list of extractor keywords
  86. """
  87. return ['random', 'first', 'last']
  88. def get_all_named_query_keywords(self):
  89. """
  90. :return: a list of all named query keywords, used to identify named queries
  91. """
  92. return (
  93. self._get_selector_keywords() + self._get_parametrized_selector_keywords() + self._get_extractor_keywords())
  94. @staticmethod
  95. def get_all_sql_query_keywords():
  96. """
  97. :return: a list of all supported SQL keywords, used to identify SQL queries
  98. """
  99. return ["select", "insert"]
  100. def process_user_defined_query(self, query_string: str, query_parameters: tuple = None):
  101. """
  102. Takes as input a SQL query query_string and optional a tuple of parameters which are marked by '?' in the query
  103. and later substituted.
  104. :param query_string: The query to execute
  105. :param query_parameters: The tuple of parameters to inject into the query
  106. :return: the results of the query
  107. """
  108. if query_parameters is not None:
  109. self.cursor.execute(query_string, query_parameters)
  110. else:
  111. self.cursor.execute(query_string)
  112. self.database.commit()
  113. return self.cursor.fetchall()
  114. def get_field_types(self, *table_names):
  115. """
  116. Creates a dictionary whose keys are the fields of the given table(s) and whose values are the appropriate field
  117. types, like TEXT for strings and REAL for float numbers.
  118. :param table_names: The name of table(s)
  119. :return: a dictionary of {field_name : field_type} for fields of all tables
  120. """
  121. dic = {}
  122. for table in table_names:
  123. self.cursor.execute("PRAGMA table_info('%s')" % table)
  124. results = self.cursor.fetchall()
  125. for field in results:
  126. dic[field[1].lower()] = field[2]
  127. return dic
  128. def named_query_parameterized(self, keyword: str, param_op_val: list):
  129. """
  130. Executes a parameterizable named query.
  131. :param keyword: The query to be executed, like ipaddress or macadress
  132. :param param_op_val: A list consisting of triples with (parameter, operator, value)
  133. :return: the results of the executed query
  134. """
  135. named_queries = {
  136. "ipaddress": "SELECT DISTINCT ip_statistics.ipAddress from ip_statistics INNER JOIN ip_mac, ip_ttl, "
  137. "ip_ports, ip_protocols ON ip_statistics.ipAddress=ip_mac.ipAddress AND "
  138. "ip_statistics.ipAddress=ip_ttl.ipAddress AND ip_statistics.ipAddress=ip_ports.ipAddress "
  139. "AND ip_statistics.ipAddress=ip_protocols.ipAddress WHERE ",
  140. "macaddress": "SELECT DISTINCT macAddress from ip_mac WHERE "}
  141. query = named_queries.get(keyword)
  142. field_types = self.get_field_types('ip_mac', 'ip_ttl', 'ip_ports', 'ip_protocols', 'ip_statistics', 'ip_mac')
  143. conditions = []
  144. for key, op, value in param_op_val:
  145. if isinstance(value, pp.ParseResults):
  146. # If we have another query instead of a direct value, execute and replace it
  147. value = self._execute_query_list(value)[0][0]
  148. # this makes sure that TEXT fields are queried by strings,
  149. # e.g. ipAddress=192.168.178.1 --is-converted-to--> ipAddress='192.168.178.1'
  150. if field_types.get(key) == 'TEXT':
  151. if not str(value).startswith("'") and not str(value).startswith('"'):
  152. value = "'" + value + "'"
  153. # this replacement is required to remove ambiguity in SQL query
  154. if key == 'ipAddress':
  155. key = 'ip_mac.ipAddress'
  156. conditions.append(key + op + str(value))
  157. where_clause = " AND ".join(conditions)
  158. query += where_clause
  159. self.cursor.execute(query)
  160. return self.cursor.fetchall()
  161. named_queries = {
  162. "most_used.ipaddress": "SELECT ipAddress FROM ip_statistics WHERE (pktsSent+pktsReceived) == "
  163. "(SELECT MAX(pktsSent+pktsReceived) from ip_statistics) ORDER BY ipAddress ASC",
  164. "most_used.macaddress": "SELECT macAddress FROM (SELECT macAddress, COUNT(*) as occ from ip_mac GROUP BY "
  165. "macAddress) WHERE occ=(SELECT COUNT(*) as occ from ip_mac GROUP BY macAddress "
  166. "ORDER BY occ DESC LIMIT 1) ORDER BY macAddress ASC",
  167. "most_used.portnumber": "SELECT portNumber FROM ip_ports GROUP BY portNumber HAVING COUNT(portNumber)="
  168. "(SELECT MAX(cntPort) from (SELECT portNumber, COUNT(portNumber) as cntPort FROM "
  169. "ip_ports GROUP BY portNumber)) ORDER BY portNumber ASC",
  170. "most_used.protocolname": "SELECT protocolName FROM ip_protocols GROUP BY protocolName HAVING "
  171. "COUNT(protocolCount)=(SELECT COUNT(protocolCount) as cnt FROM ip_protocols "
  172. "GROUP BY protocolName ORDER BY cnt DESC LIMIT 1) ORDER BY protocolName ASC",
  173. "most_used.ttlvalue": "SELECT ttlValue FROM (SELECT ttlValue, SUM(ttlCount) as occ FROM ip_ttl GROUP BY "
  174. "ttlValue) WHERE occ=(SELECT SUM(ttlCount) as occ FROM ip_ttl GROUP BY ttlValue "
  175. "ORDER BY occ DESC LIMIT 1) ORDER BY ttlValue ASC",
  176. "most_used.mssvalue": "SELECT mssValue FROM (SELECT mssValue, SUM(mssCount) as occ FROM tcp_mss GROUP BY "
  177. "mssValue) WHERE occ=(SELECT SUM(mssCount) as occ FROM tcp_mss GROUP BY mssValue "
  178. "ORDER BY occ DESC LIMIT 1) ORDER BY mssValue ASC",
  179. "most_used.winsize": "SELECT winSize FROM (SELECT winSize, SUM(winCount) as occ FROM tcp_win GROUP BY "
  180. "winSize) WHERE occ=(SELECT SUM(winCount) as occ FROM tcp_win GROUP BY winSize ORDER "
  181. "BY occ DESC LIMIT 1) ORDER BY winSize ASC",
  182. "most_used.ipclass": "SELECT ipClass FROM (SELECT ipClass, COUNT(*) as occ from ip_statistics GROUP BY "
  183. "ipClass ORDER BY occ DESC) WHERE occ=(SELECT COUNT(*) as occ from ip_statistics "
  184. "GROUP BY ipClass ORDER BY occ DESC LIMIT 1) ORDER BY ipClass ASC",
  185. "least_used.ipaddress": "SELECT ipAddress FROM ip_statistics WHERE (pktsSent+pktsReceived) == (SELECT "
  186. "MIN(pktsSent+pktsReceived) from ip_statistics) ORDER BY ipAddress ASC",
  187. "least_used.macaddress": "SELECT macAddress FROM (SELECT macAddress, COUNT(*) as occ from ip_mac GROUP "
  188. "BY macAddress) WHERE occ=(SELECT COUNT(*) as occ from ip_mac GROUP BY macAddress "
  189. "ORDER BY occ ASC LIMIT 1) ORDER BY macAddress ASC",
  190. "least_used.portnumber": "SELECT portNumber FROM ip_ports GROUP BY portNumber HAVING COUNT(portNumber)="
  191. "(SELECT MIN(cntPort) from (SELECT portNumber, COUNT(portNumber) as cntPort FROM "
  192. "ip_ports GROUP BY portNumber)) ORDER BY portNumber ASC",
  193. "least_used.protocolname": "SELECT protocolName FROM ip_protocols GROUP BY protocolName HAVING "
  194. "COUNT(protocolCount)=(SELECT COUNT(protocolCount) as cnt FROM ip_protocols "
  195. "GROUP BY protocolName ORDER BY cnt ASC LIMIT 1) ORDER BY protocolName ASC",
  196. "least_used.ttlvalue": "SELECT ttlValue FROM (SELECT ttlValue, SUM(ttlCount) as occ FROM ip_ttl GROUP BY "
  197. "ttlValue) WHERE occ=(SELECT SUM(ttlCount) as occ FROM ip_ttl GROUP BY ttlValue "
  198. "ORDER BY occ ASC LIMIT 1) ORDER BY ttlValue ASC",
  199. "least_used.mssvalue": "SELECT mssValue FROM (SELECT mssValue, SUM(mssCount) as occ FROM tcp_mss GROUP BY "
  200. "mssValue) WHERE occ=(SELECT SUM(mssCount) as occ FROM tcp_mss GROUP BY mssValue "
  201. "ORDER BY occ ASC LIMIT 1) ORDER BY mssValue ASC",
  202. "least_used.winsize": "SELECT winSize FROM (SELECT winSize, SUM(winCount) as occ FROM tcp_win GROUP BY "
  203. "winSize) WHERE occ=(SELECT SUM(winCount) as occ FROM tcp_win GROUP BY winSize "
  204. "ORDER BY occ ASC LIMIT 1) ORDER BY winSize ASC",
  205. "avg.pktsreceived": "SELECT avg(pktsReceived) from ip_statistics",
  206. "avg.pktssent": "SELECT avg(pktsSent) from ip_statistics",
  207. "avg.kbytesreceived": "SELECT avg(kbytesReceived) from ip_statistics",
  208. "avg.kbytessent": "SELECT avg(kbytesSent) from ip_statistics",
  209. "avg.ttlvalue": "SELECT avg(ttlValue) from ip_ttl",
  210. "avg.mss": "SELECT avg(mssValue) from tcp_mss",
  211. "all.ipaddress": "SELECT ipAddress from ip_statistics ORDER BY ipAddress ASC",
  212. "all.ttlvalue": "SELECT DISTINCT ttlValue from ip_ttl ORDER BY ttlValue ASC",
  213. "all.mss": "SELECT DISTINCT mssValue from tcp_mss ORDER BY mssValue ASC",
  214. "all.macaddress": "SELECT DISTINCT macAddress from ip_mac ORDER BY macAddress ASC",
  215. "all.portnumber": "SELECT DISTINCT portNumber from ip_ports ORDER BY portNumber ASC",
  216. "all.protocolname": "SELECT DISTINCT protocolName from ip_protocols ORDER BY protocolName ASC"}
  217. def _execute_query_list(self, query_list):
  218. """
  219. Recursively executes a list of named queries. They are of the following form:
  220. ['macaddress_param', [['ipaddress', '=', ['most_used', 'ipaddress']]]]
  221. :param query_list: The query statement list obtained from the query parser
  222. :return: The result of the query (either a single result or a list).
  223. """
  224. if query_list[0] == "random":
  225. return rnd.choice(self._execute_query_list(query_list[1:]))
  226. elif query_list[0] == "first":
  227. return self._execute_query_list(query_list[1:])[0]
  228. elif query_list[0] == "last":
  229. return self._execute_query_list(query_list[1:])[-1]
  230. elif query_list[0] == "macaddress_param":
  231. return self.named_query_parameterized("macaddress", query_list[1])
  232. elif query_list[0] == "ipaddress_param":
  233. return self.named_query_parameterized("ipaddress", query_list[1])
  234. else:
  235. query = self.named_queries.get(query_list[0] + "." + query_list[1])
  236. self.cursor.execute(str(query))
  237. last_result = self.cursor.fetchall()
  238. return last_result
  239. def process_db_query(self, query_string_in: str, print_results=False, sql_query_parameters: tuple = None):
  240. """
  241. Processes a database query. This can either be a standard SQL query or a named query (predefined query).
  242. :param query_string_in: The string containing the query
  243. :param print_results: Indicated whether the results should be printed to terminal (True) or not (False)
  244. :param sql_query_parameters: Parameters for the SQL query (optional)
  245. :return: the results of the query
  246. """
  247. named_query_keywords = self.get_all_named_query_keywords()
  248. # Clean query_string
  249. query_string = query_string_in.lower().lstrip()
  250. # query_string is a user-defined SQL query
  251. result = None
  252. if sql_query_parameters is not None or query_string.startswith("select") or query_string.startswith("insert"):
  253. result = self.process_user_defined_query(query_string, sql_query_parameters)
  254. # query string is a named query -> parse it and pass it to statisticsDB
  255. elif any(k in query_string for k in named_query_keywords) and all(k in query_string for k in ['(', ')']):
  256. if query_string[-1] != ";":
  257. query_string += ";"
  258. query_list = self.query_parser.parse_query(query_string)
  259. result = self._execute_query_list(query_list)
  260. else:
  261. sys.stderr.write(
  262. "Query invalid. Only named queries and SQL SELECT/INSERT allowed. Please check the query's syntax!\n")
  263. return
  264. # If result is tuple/list with single element, extract value from list
  265. requires_extraction = (isinstance(result, list) or isinstance(result, tuple)) and len(result) == 1 and \
  266. (not isinstance(result[0], tuple) or len(result[0]) == 1)
  267. while requires_extraction:
  268. if isinstance(result, list) or isinstance(result, tuple):
  269. result = result[0]
  270. else:
  271. requires_extraction = False
  272. # If tuple of tuples or list of tuples, each consisting of single element is returned,
  273. # then convert it into list of values, because the returned column is clearly specified by the given query
  274. if (isinstance(result, tuple) or isinstance(result, list)) and all(len(val) == 1 for val in result):
  275. result = [c for c in result for c in c]
  276. # Print results if option print_results is True
  277. if print_results:
  278. if isinstance(result, list) and len(result) == 1:
  279. result = result[0]
  280. print("Query returned 1 record:\n")
  281. for i in range(0, len(result)):
  282. print(str(self.cursor.description[i][0]) + ": " + str(result[i]))
  283. else:
  284. self._print_query_results(query_string_in, result)
  285. return result
  286. def _print_query_results(self, query_string_in: str, result):
  287. """
  288. Prints the results of a query.
  289. Based on http://stackoverflow.com/a/20383011/3017719.
  290. :param query_string_in: The query the results belong to
  291. :param result: The results of the query
  292. """
  293. # Print number of results according to type of result
  294. if isinstance(result, list):
  295. print("Query returned " + str(len(result)) + " records:\n")
  296. else:
  297. print("Query returned 1 record:\n")
  298. # Print query results
  299. if query_string_in.lstrip().upper().startswith(
  300. "SELECT") and result is not None and self.cursor.description is not None:
  301. widths = []
  302. columns = []
  303. tavnit = '|'
  304. separator = '+'
  305. for cd in self.cursor.description:
  306. widths.append(len(cd) + 10)
  307. columns.append(cd[0])
  308. for w in widths:
  309. tavnit += " %-" + "%ss |" % (w,)
  310. separator += '-' * w + '--+'
  311. print(separator)
  312. print(tavnit % tuple(columns))
  313. print(separator)
  314. if isinstance(result, list):
  315. for row in result:
  316. print(tavnit % row)
  317. else:
  318. print(tavnit % result)
  319. print(separator)
  320. else:
  321. print(result)