DebianModel.py 14 KB

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