DebianModel.py 14 KB

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