DebianModel.py 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376
  1. import configparser
  2. import json
  3. import datetime
  4. import logging
  5. from pymongo import MongoClient
  6. import numpy as np
  7. import os
  8. from dateutil import parser
  9. from .DebianAdvisory import DebianAdvisory
  10. from .CVEParse import CVEParse
  11. class DebianModel:
  12. """
  13. This class represents M-Star debian module. It is responsible for handling debian package infos.
  14. """
  15. module_path = os.path.dirname(__file__)
  16. """
  17. TODO: Tables to manage.
  18. """
  19. dsatable = dict()
  20. src2dsa = dict()
  21. dsa2cve = dict()
  22. cvetable = dict()
  23. src2month = dict()
  24. src2sloccount = dict()
  25. src2pop = dict()
  26. src2deps = dict()
  27. pkg_with_cvss = dict()
  28. src2sum = dict()
  29. def __init__(self, action, configfile=os.path.join(module_path, 'config_default.txt')):
  30. ## DBs to track
  31. ## config
  32. self.configfile = configfile
  33. self.config = configparser.ConfigParser()
  34. if not self.config.read(configfile):
  35. raise IOError('Cannot open configuration file: ')
  36. (self.state, self.err) = self.load_state()
  37. self.client = MongoClient()
  38. if action == 'update':
  39. self.load_dbs()
  40. self.update_dbs()
  41. self.store_dbs()
  42. self.save_state(self.state)
  43. # lstm.predict(src2month, src2sloccount, src2pop, src2deps)
  44. """
  45. with open('dsatable.txt', 'w') as file:
  46. file.write(str(sorted(self.dsatable.keys(), key=lambda x: str(x).lower())))
  47. with open('src2dsa.txt', 'w') as file:
  48. file.write(str(sorted(self.src2dsa.keys(), key=lambda x: str(x).lower())))
  49. with open('dsa2cve.txt', 'w') as file:
  50. file.write(str(sorted(self.dsa2cve.keys(), key=lambda x: str(x).lower())))
  51. with open('cvetable.txt', 'w') as file:
  52. file.write(str(sorted(self.cvetable.keys(), key=lambda x: str(x).lower())))
  53. with open('src2month.txt', 'w') as file:
  54. file.write(str(sorted(self.src2month.keys(), key=lambda x: str(x).lower())))
  55. with open('src2sloccount.txt', 'w') as file:
  56. file.write(str(sorted(self.src2sloccount.keys(), key=lambda x: str(x).lower())))
  57. with open('src2pop.txt', 'w') as file:
  58. file.write(str(sorted(self.src2pop.keys(), key=lambda x: str(x).lower())))
  59. with open('src2deps.txt', 'w') as file:
  60. file.write(str(sorted(self.src2deps.keys(), key=lambda x: str(x).lower())))
  61. """
  62. elif action == 'status':
  63. self.load_dbs()
  64. # aptsec_status(sys.argv[2])
  65. elif action == 'show':
  66. self.load_dbs()
  67. self.store_dbs()
  68. else:
  69. self.print_help(self)
  70. def load_dbs(self):
  71. """
  72. Loads the required databases into the model. Can either be implemented as read from file, or read from DB.
  73. Currently reading it from files in the cache folder.
  74. """
  75. self.dsatable = self.load_single_db_from_cache('dsatable')
  76. self.src2dsa = self.load_single_db_from_cache('src2dsa')
  77. self.dsa2cve = self.load_single_db_from_cache('dsa2cve')
  78. self.cvetable = self.load_single_db_from_cache('cvetable')
  79. self.src2deps = self.load_single_db_from_cache('src2deps')
  80. self.src2month = self.load_single_db_from_cache('src2month')
  81. self.src2sloccount = self.load_single_db_from_cache('src2sloccount')
  82. self.src2pop = self.load_single_db_from_cache('src2pop')
  83. def load_single_db_from_cache(self, file_name):
  84. cache_dir = os.path.join(self.module_path, self.config['DIR']['cache_dir'])
  85. try:
  86. with open(os.path.join(cache_dir, file_name)) as f:
  87. return json.load(f)
  88. except (IOError, ValueError):
  89. print('Read cache ' + file_name + ' failed!! Maybe first run of the system?')
  90. def store_dbs(self):
  91. self.store_db_single('dsatable', self.dsatable)
  92. self.store_db_single('src2dsa', self.src2dsa)
  93. self.store_db_single('dsa2cve', self.dsa2cve)
  94. self.store_db_single('cvetable', self.cvetable)
  95. self.store_db_single('src2deps', self.src2deps)
  96. self.store_db_single('src2sloccount', self.src2sloccount)
  97. self.store_db_single('src2pop', self.src2pop)
  98. # src2month needs special handling
  99. cache_src2month = os.path.join(self.module_path, self.config['DIR']['cache_dir'], 'src2month')
  100. int_list = dict()
  101. for element in self.src2month:
  102. for i in range(len(self.src2month[element])):
  103. if element in int_list:
  104. int_list[element].append(int(self.src2month[element][i]))
  105. else:
  106. int_list[element] = []
  107. int_list[element].append(int(self.src2month[element][i]))
  108. try:
  109. with open(cache_src2month, 'w') as fp:
  110. json.dump(int_list, fp, default=self.converter)
  111. except IOError:
  112. print('write cache src2month failed!! Fatal error')
  113. def store_db_single(self, file_name, db):
  114. cache_dir = os.path.join(self.module_path, self.config['DIR']['cache_dir'])
  115. try:
  116. with open(os.path.join(cache_dir, file_name), 'w') as f:
  117. json.dump(db, f, default=self.converter)
  118. except (IOError, ValueError):
  119. print('Read cache ' + file_name + ' failed!! Maybe first run of the system?')
  120. def save_state(self, state):
  121. """Save state, different from DBs in that we always need it"""
  122. state_file = os.path.join(self.module_path, self.config['DIR']['cache_dir'], 'state')
  123. try:
  124. with open(state_file, 'w') as sf:
  125. json.dump(state, sf)
  126. except IOError:
  127. print('Write cache state failed!! Fatal error')
  128. def converter(self, o):
  129. """Help for save_DBs"""
  130. if isinstance(o, datetime.datetime) or isinstance(o, datetime.timedelta):
  131. return str(o)
  132. if isinstance(o, np.float):
  133. return o.astype(int)
  134. def update_dbs(self):
  135. now = datetime.datetime.now()
  136. new_adv = DebianAdvisory.checkDSAs(self.state, self.config)
  137. for id in new_adv:
  138. if id in self.dsatable:
  139. logging.info(self.state['vendor'] + ' advisory ' + id + ' already known.\n')
  140. else:
  141. ## store advisory and parse it
  142. self.dsatable[id] = new_adv[id]
  143. self.updateCVETables(id)
  144. # recompute all pkg statistics
  145. for srcpkg in self.src2dsa:
  146. self.processCVEs(srcpkg, now)
  147. def updateCVETables(self, myid):
  148. logging.info('Updating vulnerability database with advisory ' + self.state['vendor'] + str(myid) + ' \n')
  149. adv = self.dsatable[myid]
  150. dsastats = DebianAdvisory.parseDSAhtml(adv)
  151. dsastats = DebianAdvisory.fixDSAquirks(myid, dsastats)
  152. for srcpkg in dsastats[0]:
  153. if srcpkg in self.src2dsa:
  154. self.src2dsa[srcpkg].append(myid)
  155. else:
  156. self.src2dsa[srcpkg] = []
  157. self.src2dsa[srcpkg].append(myid)
  158. self.dsa2cve[str(myid)] = dsastats[2]
  159. for cve_id in dsastats[2]:
  160. # No fetch CVE We use mongodb and cve-search
  161. cve = CVEParse.fetchCVE(cve_id, self.client)
  162. cvestats = CVEParse.parseCVE(cve_id, cve)
  163. finaldate = cvestats[0]
  164. if cvestats[0] > dsastats[1] or cvestats[0] == 0:
  165. finaldate = dsastats[1]
  166. self.cvetable[cve_id] = (finaldate, dsastats[1] - finaldate, cvestats[1], cvestats[2], cvestats[3])
  167. @staticmethod
  168. def print_help():
  169. """
  170. Prints help message to this vendor model.
  171. """
  172. print("Debian mstar model supports only update status and show actions.")
  173. def load_state(self):
  174. """
  175. Load state, different from DBs in that we always need it.
  176. Retrieves the cached state for current configuration.
  177. :return: state , error number
  178. """
  179. state_file = os.path.join(self.module_path, self.config['DIR']['cache_dir'], 'state')
  180. err = 0
  181. try:
  182. with open(state_file) as json_data:
  183. state = json.load(json_data)
  184. except FileNotFoundError:
  185. # Load default state - start from the beginning
  186. print('File not found in: ' + state_file)
  187. print('Loading default state.')
  188. state = dict()
  189. state['cache_dir'] = 'cache/'
  190. state['next_adv'] = 0
  191. state['next_fsa'] = 0
  192. state['Packages'] = ''
  193. state['Sources'] = ''
  194. state['Sha1Sums'] = ''
  195. err += 1
  196. return state, err
  197. def processCVEs(self, srcpkg, now):
  198. """
  199. compute and store MTBF, MTBR and Scores of each src pkg
  200. output: %src2mtbf
  201. (srcpkg=> ())
  202. """
  203. stats = [now, 0, 0, 0, 0, 0, 0]
  204. cvestats = dict()
  205. logging.info('Processing package: ' + srcpkg + '.\n')
  206. ## keep track of the number of low-medium-high severity vulnerabilities
  207. ## TODO see how cvss affects vulnerability prediction - if some packages show patterns
  208. with_cvss = dict()
  209. ## To eliminate duplicate cves
  210. haveseen = dict()
  211. ## cvestats = (date: number)
  212. for dsa_id in self.src2dsa[srcpkg]:
  213. for cve_id in self.dsa2cve[str(dsa_id)]:
  214. if cve_id in haveseen:
  215. continue
  216. else:
  217. haveseen[cve_id] = 1
  218. tt = self.cvetable[cve_id][0]
  219. if tt in cvestats:
  220. cvestats[tt] += 1
  221. else:
  222. cvestats[tt] = 1
  223. stats[1] += 1
  224. ## Date at the moment taken from CVE? - not sure.
  225. ## with_cvss = (date: number low, number med, number high)
  226. for dsa_id in self.src2dsa[srcpkg]:
  227. for cve_id in self.dsa2cve[str(dsa_id)]:
  228. tt = self.cvetable[cve_id][0]
  229. try:
  230. temp_cvss = float(self.cvetable[cve_id][2])
  231. except TypeError:
  232. print(cve_id)
  233. continue
  234. if tt in with_cvss:
  235. if (temp_cvss < 4.0):
  236. with_cvss[tt][0] += 1
  237. elif (temp_cvss < 7.0):
  238. with_cvss[tt][1] += 1
  239. else:
  240. with_cvss[tt][2] += 1
  241. else:
  242. with_cvss[tt] = [0, 0, 0]
  243. if (temp_cvss < 4.0):
  244. with_cvss[tt][0] += 1
  245. elif (temp_cvss < 7.0):
  246. with_cvss[tt][1] += 1
  247. else:
  248. with_cvss[tt][2] += 1
  249. # Ignore pkgs with less than one incident, should not happen..
  250. if stats[1] < 1:
  251. return
  252. dates = sorted(cvestats, key=cvestats.get)
  253. try:
  254. stats[0] = dates[0]
  255. except IndexError:
  256. print(srcpkg + str(dates))
  257. stats[0] = 0
  258. count = sum(cvestats.values())
  259. self.format_data(srcpkg, with_cvss, self.pkg_with_cvss, True)
  260. self.format_data(srcpkg, cvestats, self.src2month, False)
  261. def format_data(self, pkg, cvestats, src2month, cvss):
  262. x = []
  263. y = []
  264. monthyear = []
  265. year = []
  266. temp_items = list(cvestats.items())
  267. items = []
  268. for data_dict in temp_items:
  269. if isinstance(data_dict[0], str):
  270. tmpx = (parser.parse(data_dict[0]))
  271. else:
  272. tmpx = data_dict[0]
  273. x.append(tmpx)
  274. try:
  275. tmpy = int(data_dict[1])
  276. except TypeError:
  277. tmpy = data_dict[1]
  278. y.append(tmpy)
  279. items.append((tmpx, tmpy))
  280. items.sort(key=lambda tup: tup[0])
  281. for i in range(2000, 2018):
  282. temp = []
  283. for j in range(12):
  284. if cvss:
  285. temp.append([0, 0, 0])
  286. else:
  287. temp.append(0)
  288. monthyear.append(temp)
  289. for i in range(len(x)):
  290. if cvss:
  291. tmp0 = y[i][0]
  292. tmp1 = y[i][1]
  293. tmp2 = y[i][2]
  294. monthyear[x[i].year - 2000][x[i].month - 1][0] += tmp0
  295. monthyear[x[i].year - 2000][x[i].month - 1][1] += tmp1
  296. monthyear[x[i].year - 2000][x[i].month - 1][2] += tmp2
  297. else:
  298. monthyear[x[i].year - 2000][x[i].month - 1] += y[i]
  299. months_list = [item for sublist in monthyear for item in sublist]
  300. if not cvss:
  301. temp_months = np.zeros(len(months_list))
  302. i = 0
  303. for element in months_list:
  304. temp_months[i] = np.float32(element)
  305. i += 1
  306. src2month[pkg] = temp_months
  307. else:
  308. src2month[pkg] = months_list
  309. return