apt-sec.py 42 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377
  1. #!/usr/bin/python3
  2. ## Based on the perl code of Trustminer by CASED
  3. ## Nikos
  4. import sys
  5. import os
  6. from pymongo import MongoClient
  7. #mongodb assumes database at default path
  8. import logging
  9. import configparser
  10. import json
  11. import csv
  12. import urllib.request
  13. import datetime
  14. import debian_advisory as da
  15. import cveparse as cv
  16. import matplotlib.pyplot as plt
  17. import numpy as np
  18. from dateutil import parser
  19. import plotly.plotly as py
  20. import plotly.graph_objs as go
  21. #import lstm_reg as lstm
  22. import metadata as meta
  23. import deps
  24. import psycopg2
  25. import powerlaw as pl
  26. import DLAmine as dla
  27. import pickle
  28. import paper_plots as carlosplt
  29. import stat_tests as stats
  30. from matplotlib2tikz import save as tikz_save
  31. import prediction as pred
  32. import scipy.stats as stats
  33. logging.basicConfig(stream=sys.stderr, level=logging.DEBUG)
  34. ## Increase the recursion limit by much to allow bs to parse large files
  35. ## This is not good practise
  36. sys.setrecursionlimit(6000)
  37. #load config file as library
  38. config = configparser.ConfigParser()
  39. config.read('config_test')
  40. if config.sections == []:
  41. print('configuration file not found\n')
  42. sys.exit(1)
  43. #global variables
  44. secperday = 60*60*24
  45. now = datetime.datetime.now()
  46. verbosity = 1
  47. ###############################################################################
  48. ## logging
  49. # 1 fatal errors
  50. # 2 errors
  51. # 3 note
  52. # 4 trace
  53. # 5 debug
  54. def msg(lvl,msg):
  55. if lvl <= int(config['LOG']['loglevel']):
  56. print(msg)
  57. def debug(msg):
  58. msg(5, msg)
  59. # Need to see if this is necessary
  60. ## load state, different from DBs in that we always need it
  61. def load_state():
  62. cache = config['DIR']['cache_dir'] + 'state'
  63. err = 0
  64. state = dict()
  65. try:
  66. with open(cache) as json_data:
  67. state = json.load(json_data)
  68. except FileNotFoundError:
  69. # Load default state - start from the beginning
  70. state['cache_dir'] = cache
  71. state['next_adv'] = 0
  72. state['next_fsa'] = 0
  73. state['Packages'] = ''
  74. state['Sources'] = ''
  75. state['Sha1Sums'] = ''
  76. err += 1
  77. return (state, err)
  78. ###############################################################################
  79. ## save state, different from DBs in that we always need it
  80. def save_state(state):
  81. cache = config['DIR']['cache_dir'] + 'state'
  82. try:
  83. with open(cache, 'w') as fp:
  84. json.dump(state, fp)
  85. except IOError:
  86. print('write cache state failed!! Fatal error')
  87. sys.exit(1)
  88. ###############################################################################
  89. ## load sha lists :TODO later
  90. def load_sha1lists():
  91. cache = config['DIR']['cache_dir'] + 'state'
  92. ###############################################################################
  93. ## save sha lists :TODO later
  94. def save_sha1lists():
  95. pass
  96. ###############################################################################
  97. ## load from files
  98. def load_DBs():
  99. dsatable = dict()
  100. src2dsa = dict()
  101. dsa2cve = dict()
  102. cvetable = dict()
  103. src2month = dict()
  104. src2sloccount = dict()
  105. src2pop = dict()
  106. src2deps = dict()
  107. pkg_with_cvss = dict()
  108. cache = config['DIR']['cache_dir']
  109. cache_dsatable = cache + 'dsatable'
  110. try:
  111. with open(cache_dsatable) as fp:
  112. dsatable = json.load(fp)
  113. except (IOError, ValueError):
  114. print('read cache dsatable failed!! Maybe first run of the system?')
  115. cache_src2dsa = cache + 'src2dsa'
  116. try:
  117. with open(cache_src2dsa) as fp:
  118. src2dsa = json.load(fp)
  119. except (IOError, ValueError):
  120. print('read cache src2dsa failed!! Maybe first run of the system?')
  121. cache_dsa2cve = cache + 'dsa2cve'
  122. try:
  123. with open(cache_dsa2cve) as fp:
  124. dsa2cve = json.load(fp)
  125. except (IOError, ValueError):
  126. print('read cache dsa2cve failed!! Maybe first run of the system?')
  127. cache_cvetable = cache + 'cvetable'
  128. try:
  129. with open(cache_cvetable) as fp:
  130. cvetable = json.load(fp)
  131. except (IOError, ValueError):
  132. print('read cache cvetable failed!! Maybe first run of the system?')
  133. cache_src2deps = cache + 'src2deps'
  134. try:
  135. with open(cache_src2deps) as fp:
  136. src2deps = json.load(fp)
  137. except (IOError, ValueError):
  138. print('read cache src2deps failed!! Maybe first run of the system?')
  139. cache_src2month = cache + 'src2month'
  140. try:
  141. with open(cache_src2month) as fp:
  142. src2month = json.load(fp)
  143. except (IOError, ValueError):
  144. print('read cache src2month failed!! Maybe first run of the system?')
  145. cache_pkg_with_cvss = cache + 'pkg_with_cvss'
  146. try:
  147. with open(cache_pkg_with_cvss) as fp:
  148. pkg_with_cvss = json.load(fp)
  149. except (IOError, ValueError):
  150. print('read cache pkg_with_cvss failed!! Maybe first run of the system?')
  151. cache_src2sloccount = cache + 'src2sloccount'
  152. try:
  153. with open(cache_src2sloccount) as fp:
  154. src2sloccount = json.load(fp)
  155. except (IOError, ValueError):
  156. print('read cache src2sloccount failed!! Maybe first run of the system?')
  157. cache_src2pop = cache + 'src2pop'
  158. try:
  159. with open(cache_src2pop) as fp:
  160. src2pop = json.load(fp)
  161. except (IOError, ValueError):
  162. print('read cache src2pop failed!! Maybe first run of the system?')
  163. return(dsatable, src2dsa, dsa2cve, cvetable, src2month, src2sloccount, src2pop, src2deps, pkg_with_cvss)
  164. ###############################################################################
  165. ## help for save_DBs
  166. def myconverter(o):
  167. if isinstance(o, datetime.datetime) or isinstance(o, datetime.timedelta):
  168. return str(o)
  169. if isinstance(o, np.float):
  170. return o.astype(int)
  171. ###############################################################################
  172. ## save to files
  173. def save_DBs(dsatable, src2dsa, dsa2cve, cvetable, src2month, src2sloccount, src2pop, src2deps, src2sum, pkg_with_cvss):
  174. cache = config['DIR']['cache_dir']
  175. cache_dsatable = cache + 'dsatable'
  176. try:
  177. with open(cache_dsatable, 'w') as fp:
  178. json.dump(dsatable, fp, default = myconverter)
  179. except IOError:
  180. print('write cache dsatable failed!! Fatal error')
  181. sys.exit(1)
  182. cache_src2dsa = cache + 'src2dsa'
  183. try:
  184. with open(cache_src2dsa, 'w') as fp:
  185. json.dump(src2dsa, fp)
  186. except IOError:
  187. print('write cache src2dsa failed!! Fatal error')
  188. sys.exit(1)
  189. cache_dsa2cve = cache + 'dsa2cve'
  190. try:
  191. with open(cache_dsa2cve, 'w') as fp:
  192. json.dump(dsa2cve, fp)
  193. except IOError:
  194. print('write cache dsa2cve failed!! Fatal error')
  195. sys.exit(1)
  196. cache_cvetable = cache + 'cvetable'
  197. try:
  198. with open(cache_cvetable, 'w') as fp:
  199. json.dump(cvetable, fp, default = myconverter)
  200. except IOError:
  201. print('write cache cvetable failed!! Fatal error')
  202. sys.exit(1)
  203. cache_src2sloccount = cache + 'src2sloccount'
  204. try:
  205. with open(cache_src2sloccount, 'w') as fp:
  206. json.dump(src2sloccount, fp, default = myconverter)
  207. except IOError:
  208. print('write cache src2sloccount failed!! Fatal error')
  209. sys.exit(1)
  210. cache_src2pop = cache + 'src2pop'
  211. try:
  212. with open(cache_src2pop, 'w') as fp:
  213. json.dump(src2pop, fp, default = myconverter)
  214. except IOError:
  215. print('write cache src2pop failed!! Fatal error')
  216. sys.exit(1)
  217. cache_src2deps = cache + 'src2deps'
  218. try:
  219. with open(cache_src2deps, 'w') as fp:
  220. json.dump(src2deps, fp, default = myconverter)
  221. except IOError:
  222. print('write cache src2deps failed!! Fatal error')
  223. sys.exit(1)
  224. cache_src2sum = cache + 'src2sum'
  225. try:
  226. with open(cache_src2sum, 'w') as fp:
  227. json.dump(src2sum, fp, default = myconverter)
  228. except IOError:
  229. print('write cache src2deps failed!! Fatal error')
  230. sys.exit(1)
  231. cache_src2month = cache + 'src2month'
  232. int_list = dict()
  233. for element in src2month:
  234. for i in range(len(src2month[element])):
  235. if element in int_list:
  236. int_list[element].append(int(src2month[element][i]))
  237. else:
  238. int_list[element] = []
  239. int_list[element].append(int(src2month[element][i]))
  240. try:
  241. with open(cache_src2month, 'w') as fp:
  242. json.dump(int_list, fp, default = myconverter)
  243. except IOError:
  244. print('write cache src2month failed!! Fatal error')
  245. sys.exit(1)
  246. cache_pkg_with_cvss = cache + 'pkg_with_cvss'
  247. int_list = dict()
  248. for element in pkg_with_cvss:
  249. for i in range(len(pkg_with_cvss[element])):
  250. if element in int_list:
  251. int_list[element].append(pkg_with_cvss[element][i])
  252. else:
  253. int_list[element] = []
  254. int_list[element].append(pkg_with_cvss[element][i])
  255. try:
  256. with open(cache_pkg_with_cvss, 'w') as fp:
  257. json.dump(int_list, fp, default = myconverter)
  258. except IOError:
  259. print('write cache pkg_with_cvss failed!! Fatal error')
  260. sys.exit(1)
  261. ###############################################################################
  262. ## Fetch current Packages, Sources and sha1sums files
  263. ## These are needed to find CVE stats by sha1sums/pkg-names
  264. ## Only Sha1Sums is custom generated, others are from Debian.
  265. ## FIXME: Server might do on-the-fly gzip (but should not for bzip2)
  266. ## Return: 1 on success, to signal that new parsing is needed.
  267. def fetchMeta(filename):
  268. urlbase = config['URL']['pkg_base_url']
  269. mydir = config['DIR']['cache_dir']
  270. bzFile = filename + '.bz2'
  271. url = urlbase + bzFile
  272. logging.info('Checking meta file from ' + url + '\n')
  273. # Download file
  274. urllib.request.urlretrieve(url, mydir + bzfile)
  275. # TODO catch exceptions like file not found
  276. # TODO check if file has changed, if it is new unpack
  277. ###############################################################################
  278. # Sources and Packages are not completely consistent, esp for debian-multimedia
  279. # He we store manual mappings for these..
  280. def addOrphanPkgs(pkg2src):
  281. pkg2src['liblame-dev'] = "lame";
  282. pkg2src['lame-extras'] = "lame";
  283. pkg2src['moonlight'] = "moon";
  284. pkg2src['libmoon0'] = "moon";
  285. pkg2src['xmms-mp4'] = "xmms2";
  286. pkg2src['xmms-mp4'] = "xmms2";
  287. pkg2src['lazarus-src-0.9.30'] = "lazarus";
  288. pkg2src['lazarus-ide-0.9.30'] = "lazarus";
  289. pkg2src['lcl-qt4-0.9.30'] = "lazarus";
  290. pkg2src['lazarus-ide-qt4-0.9.30'] = "lazarus";
  291. pkg2src['lcl-gtk2-0.9.30'] = "lazarus";
  292. pkg2src['lazarus-ide-gtk2-0.9.30'] = "lazarus";
  293. pkg2src['lcl-units-0.9.30'] = "lazarus";
  294. pkg2src['lazarus-0.9.30'] = "lazarus";
  295. pkg2src['lazarus-doc-0.9.30'] = "lazarus";
  296. pkg2src['lcl-0.9.30'] = "lazarus";
  297. pkg2src['lcl-utils-0.9.30'] = "lazarus";
  298. pkg2src['lcl-nogui-0.9.30'] = "lazarus";
  299. pkg2src['libx264-65'] = "x264";
  300. pkg2src['libx264-114'] = "x264";
  301. pkg2src['libx264-60'] = "x264";
  302. # pkg2src['libmlt3']
  303. # pkg2src['libgmerlin-avdec0']
  304. # pkg2src['libxul-dev']
  305. # pkg2src['libmyth-0.23.1-0']
  306. # pkg2src['libmpeg3hv']
  307. # pkg2src['libquicktimehv']
  308. # pkg2src['libxul0d']
  309. # pkg2src['acroread-fonts-kor']
  310. ###############################################################################
  311. ## Parse dpkg Packages file, create map deb-name->pkg-name
  312. def parsePackages(pkgfile):
  313. mydir = cache = config['DIR']['cache_dir']
  314. deb2pkg = dict()
  315. pkg2virt = dict()
  316. virt2pkg = ()
  317. logging.info('Parsing Packages file...\n')
  318. pkgfile = mydir + pkgfile
  319. #TODO open and parse pkg file
  320. ###############################################################################
  321. ## Parse dpkg Sources file, create map pkg-name->src-name
  322. def parseSources(srcfile):
  323. mydir = cache = config['DIR']['cache_dir']
  324. checklinecont = 0
  325. pkg2src = dict()
  326. logging.info('Parsing Sources file...\n')
  327. srcfile = mydir + srcfile
  328. #TODO open and parse sources file
  329. ###############################################################################
  330. def getSHA1(myhash, collection):
  331. return collection.find({"hash": myhash})
  332. ###############################################################################
  333. def addSHA1(myhash, deb, src):
  334. dic = getSHA1(myhash)
  335. thash = dic["hash"]
  336. tdeb = dic["deb"]
  337. tsrc = dic["src"]
  338. #TODO insert SHA to database
  339. ###############################################################################
  340. ## Parse Sha1Sums file. Format: "sha1sum::deb-name::unix-file-path"
  341. ## Create 2 maps: sha1sum->file, file->deb-name
  342. def parseSha1Sums(sha1file):
  343. pass
  344. ###############################################################################
  345. ## Parse local dpkg status, return list of debs
  346. def parseStatus(stsfile):
  347. pass
  348. ###############################################################################
  349. ## Parse Advisory (only Debian supported atm
  350. def parseAdvisory(adv):
  351. if state['vendor'] == 'debian':
  352. return da.parseDSAhtml(adv)
  353. else:
  354. print('Unsupported distribution. We only support Debian at the moment')
  355. system.exit(1)
  356. ###############################################################################
  357. ## Manually fix problems with Advisory entries
  358. def fixAdvisoryQuirks(arg, state, dsastats):
  359. if state['vendor'] == 'debian':
  360. return da.fixDSAquirks(arg, dsastats)
  361. else:
  362. print('Unsupported distribution. We only support Debian at the moment')
  363. system.exit(1)
  364. ###############################################################################
  365. ## Extract CVE ids from new advisories and print URL for mirror script
  366. def printCVEs(myid,adv, state):
  367. logging.info('Looking for CVEs in advisory...\n')
  368. dsastats = parseAdvisory(adv)
  369. if dsastats == []:
  370. return
  371. ## fix DSAs that don't contain correct CVE refs
  372. dsastats = fixAdvisoryQuirks(myid, state, dsastats);
  373. #TODO Fix this part
  374. ##for cve_id in dsastats
  375. ###############################################################################
  376. ## Update internal vuln. DB with new Advisory info
  377. ## Creates CVEtable for MTBF computation:
  378. ## ( cve-id => (date, delay, score1, score2, score3))
  379. def updateCVETables(myid, dsatable, state, src2dsa, dsa2cve, cvetable, client):
  380. logging.info('Updating vulnerability database with advisory ' + state['vendor'] + str(myid) + ' \n')
  381. adv = dsatable[myid]
  382. dsastats = parseAdvisory(adv)
  383. if dsastats == []:
  384. return
  385. dsastats = fixAdvisoryQuirks(myid, state, dsastats)
  386. print('Did you fix it?')
  387. for srcpkg in dsastats[0]:
  388. if srcpkg in src2dsa:
  389. src2dsa[srcpkg].append(myid)
  390. else:
  391. src2dsa[srcpkg] = []
  392. src2dsa[srcpkg].append(myid)
  393. dsa2cve[str(myid)] = dsastats[2]
  394. for cve_id in dsastats[2]:
  395. # No fetch CVE We use mongodb and cve-search
  396. cve = cv.fetchCVE(cve_id, client)
  397. cvestats = cv.parseCVE(cve_id, cve)
  398. # print(cvestats)
  399. # print(dsastats)
  400. finaldate = cvestats[0]
  401. if cvestats[0] > dsastats[1] or cvestats[0] == 0:
  402. finaldate = dsastats[1]
  403. cvedata = (finaldate, dsastats[1]-finaldate, cvestats[1], cvestats[2], cvestats[3])
  404. ## print(cvedata)
  405. cvetable[cve_id] = cvedata
  406. return cvetable
  407. ###############################################################################
  408. ## Check for updates on Package information
  409. def aptsec_update(state, config, dsatable, client, src2dsa, dsa2cve, src2month, cvetable, pkg_with_cvss):
  410. args = sys.argv
  411. # if not('--offline' in args):
  412. # fetchMeta('Packages')
  413. # fetchMeta('Sources')
  414. # fetchMeta('Sha1Sums')
  415. now = datetime.datetime.now()
  416. if not('--cves' in args):
  417. parsePackages('Packages')
  418. parseSources('Sources')
  419. # if not('--nosha1' in args):
  420. # parseSha1sums('Sha1Sums')
  421. if state['vendor'] == 'debian':
  422. newAdv = da.checkDSAs(state, config)
  423. else:
  424. print('Unsupported distribution. We only support Debian at the moment')
  425. system.exit(1)
  426. for myid in newAdv:
  427. if myid in dsatable:
  428. logging.info(state['vendor'] + ' advisory ' + myid + ' already known.\n')
  429. elif '--cves' in args:
  430. ## scan for CVE urls only?
  431. printCVEs(myid, newAdv[myid])
  432. else:
  433. ## store advisory and parse it
  434. dsatable[myid] = newAdv[myid]
  435. updateCVETables(myid, dsatable, state, src2dsa, dsa2cve, cvetable, client)
  436. # recompute all pkg statistics
  437. for srcpkg in src2dsa:
  438. processCVEs(srcpkg, now, src2dsa, dsa2cve, src2month, cvetable, pkg_with_cvss, config)
  439. return 0
  440. ###############################################################################
  441. ## find list of src pkgs from bin pkgs based on pkg2src
  442. def resolvePkg2Src(pkglist, pkg2src):
  443. srclist = []
  444. for pkg in pkglist:
  445. if pkg in pkg2src:
  446. srcpkg = pkg2src[pkg]
  447. srclist.append(srcpkg)
  448. else:
  449. logging.info('Could not find source package for: ' + pkg + ' .\n')
  450. return srclist
  451. ###############################################################################
  452. ## compute and store MTBF, MTBR and Scores of each src pkg
  453. ## output: %src2mtbf:
  454. ## (srcpkg=> ())
  455. def processCVEs(pkg, now, src2dsa, dsa2cve, src2month, cvetable, pkg_with_cvss, config):
  456. stats = [now, 0, 0, 0, 0, 0, 0]
  457. #mylambda = config['TRUST']['lambda']
  458. mylambda = 0
  459. cvestats = dict()
  460. logging.info('Processing package: ' + pkg + '.\n')
  461. ## keep track of the number of low-medium-high severity vulnerabilities
  462. ## TODO see how cvss affects vulnerability prediction - if some packages show patterns
  463. temp_cvss = 10.0
  464. with_cvss = dict()
  465. ## To eliminate duplicate cves
  466. haveseen = dict()
  467. ## cvestats = (date: number)
  468. for dsa_id in src2dsa[pkg]:
  469. for cve_id in dsa2cve[str(dsa_id)]:
  470. if cve_id in haveseen:
  471. continue
  472. else:
  473. haveseen[cve_id] = 1
  474. tt = cvetable[cve_id][0]
  475. if tt in cvestats:
  476. cvestats[tt] += 1
  477. else:
  478. cvestats[tt] = 1
  479. stats[1] += 1
  480. ## Date at the moment taken from CVE? - not sure.
  481. ## with_cvss = (date: number low, number med, number high)
  482. haveseen = dict()
  483. for dsa_id in src2dsa[pkg]:
  484. for cve_id in dsa2cve[str(dsa_id)]:
  485. if cve_id in haveseen:
  486. continue
  487. else:
  488. haveseen[cve_id] = 1
  489. tt = cvetable[cve_id][0]
  490. try: temp_cvss = float(cvetable[cve_id][2])
  491. except TypeError:
  492. print(cve_id)
  493. continue
  494. if pkg=='linux':
  495. print(tt, temp_cvss)
  496. if tt in with_cvss:
  497. if (temp_cvss<4.0):
  498. with_cvss[tt][0] += 1
  499. elif (temp_cvss<7.0):
  500. with_cvss[tt][1] += 1
  501. else:
  502. with_cvss[tt][2] += 1
  503. else:
  504. with_cvss[tt] = [0, 0, 0]
  505. if (temp_cvss<4.0):
  506. with_cvss[tt][0] += 1
  507. elif (temp_cvss<7.0):
  508. with_cvss[tt][1] += 1
  509. else:
  510. with_cvss[tt][2] += 1
  511. if pkg=='linux':
  512. print(with_cvss)
  513. # Ignore pkgs with less than one incident, should not happen..
  514. if stats[1] < 1:
  515. return
  516. prev_date = 0
  517. weight = 0
  518. dates = sorted(cvestats, key = cvestats.get)
  519. try:
  520. stats[0] = dates[0]
  521. except IndexError:
  522. print(pkg + str(dates))
  523. stats[0] = 0
  524. count = sum(cvestats.values())
  525. print(pkg + ' ' + str(count))
  526. #pkg_with_cvss[pkg] = with_cvss
  527. format_data(pkg, with_cvss, pkg_with_cvss, True)
  528. format_data(pkg, cvestats, src2month, False)
  529. ###############################################################################
  530. ## format vulnerability data into monthly intervals, suitable for tensorflow
  531. def format_data(pkg, cvestats, src2month, cvss):
  532. x = []
  533. y = []
  534. monthyear = []
  535. year = []
  536. temp_items=list(cvestats.items())
  537. items = []
  538. for data_dict in temp_items:
  539. if isinstance(data_dict[0], str):
  540. tmpx = (parser.parse(data_dict[0]))
  541. else:
  542. tmpx = data_dict[0]
  543. x.append(tmpx)
  544. try:
  545. tmpy = int(data_dict[1])
  546. except TypeError:
  547. tmpy = data_dict[1]
  548. y.append(tmpy)
  549. items.append((tmpx, tmpy))
  550. items.sort(key=lambda tup: tup[0])
  551. for i in range(2000, 2019):
  552. temp = []
  553. for j in range(12):
  554. if cvss:
  555. temp.append([0, 0, 0])
  556. else:
  557. temp.append(0)
  558. monthyear.append(temp)
  559. for i in range(len(x)):
  560. if cvss:
  561. tmp0 = y[i][0]
  562. tmp1 = y[i][1]
  563. tmp2 = y[i][2]
  564. monthyear[x[i].year-2000][x[i].month-1][0] += tmp0
  565. monthyear[x[i].year-2000][x[i].month-1][1] += tmp1
  566. monthyear[x[i].year-2000][x[i].month-1][2] += tmp2
  567. else:
  568. monthyear[x[i].year-2000][x[i].month-1] += y[i]
  569. months_list = [item for sublist in monthyear for item in sublist]
  570. if not cvss:
  571. temp_months = np.zeros(len(months_list))
  572. i = 0
  573. for element in months_list:
  574. temp_months[i] = np.float32(element)
  575. i += 1
  576. src2month[pkg] = temp_months
  577. else:
  578. src2month[pkg] = months_list
  579. return
  580. ###############################################################################
  581. ## plot vulnerability time distribution for a single package
  582. def pkg_plot(pkg, cvestats):
  583. colors = list("rgbcmyk")
  584. items = list(cvestats.items())
  585. #print(items)
  586. items.sort(key=lambda tup: tup[0])
  587. x = []
  588. y = []
  589. for data_dict in items:
  590. x.append(parser.parse(data_dict[0]))
  591. y.append(data_dict[1])
  592. monthyear = []
  593. year = []
  594. # initialize list
  595. for i in range(2000,2017):
  596. temp = []
  597. for j in range(12):
  598. temp.append(0)
  599. monthyear.append(temp)
  600. for i in range(len(x)):
  601. # print(str(x[i].year) + str(x[i].month))
  602. monthyear[x[i].year-2000][x[i].month-1] += y[i]
  603. newx = []
  604. yearsx = []
  605. year = []
  606. monthlabel = []
  607. month = []
  608. m1 = 0
  609. m2 = 0
  610. k = 0
  611. label_months = []
  612. months_list = [item for sublist in monthyear for item in sublist]
  613. for i in range(len(months_list)):
  614. label_months.append(i)
  615. plt.bar(label_months, months_list)
  616. for i in range(len(monthyear)):
  617. year.append(0)
  618. cc = 0
  619. for j in range(len(monthyear[i])):
  620. cc += monthyear[i][j]
  621. if j == 5:
  622. m1 = cc
  623. month.append(m1)
  624. if j == 11:
  625. month.append(cc - m1)
  626. k += 1
  627. year[i] = cc
  628. for i in range(len(year)):
  629. yearsx.append(i + 2000)
  630. k = 2000
  631. datapoints = []
  632. for i in range(len(month)):
  633. datapoints.append(i+1)
  634. if i%2 == 0:
  635. monthlabel.append(str(k) + '-1')
  636. else:
  637. monthlabel.append('-2')
  638. k += 1
  639. # plt.xticks(datapoints, monthlabel)
  640. # print(year)
  641. # plt.plot.hist(yearsx,year)
  642. # plt.bar(yearsx, year, 1, color='blue')
  643. # plt.bar(datapoints, month, 1, color='blue')
  644. # ts.predict(month)
  645. plt.legend([pkg], loc='upper left')
  646. plt.show()
  647. return 0
  648. ###############################################################################
  649. ## populate src2sloccount dictionary with number of source lines of code in
  650. ## format (total, [ansic, cpp, asm, java, python, perl, sh])
  651. def getslocs(src2month, src2sloccount):
  652. with open('./sloc_report.txt') as f:
  653. content = f.readlines()
  654. for i in content:
  655. (total, ansic, cpp, asm, java, python, perl, sh) = (0, 0, 0, 0, 0, 0, 0, 0)
  656. words=i.split()
  657. total = int(words[0])
  658. pkg = words[1]
  659. for w in words[2:]:
  660. ww = w.split('=')
  661. if ww[0] == 'ansic':
  662. ansic = int(ww[1])
  663. if ww[0] == 'cpp':
  664. cpp = int(ww[1])
  665. if ww[0] == 'asm':
  666. asm = int(ww[1])
  667. if ww[0] == 'java':
  668. java = int(ww[1])
  669. if ww[0] == 'python':
  670. python = int(ww[1])
  671. if ww[0] == 'perl':
  672. perl = int(ww[1])
  673. if ww[0] == 'sh':
  674. sh = int(ww[1])
  675. src2sloccount[pkg] = (total, [ansic, cpp, asm, java, python, perl, sh])
  676. ###############################################################################
  677. ## get popularity contest data in format src_pkg -> (installed, vote, old, recent)
  678. def getpop(src2dsa, src2pop):
  679. with open('by_vote.csv', newline = '') as csvfile:
  680. reader = csv.reader(csvfile, delimiter = ',', quotechar = '|')
  681. for row in reader:
  682. try:
  683. if row[1] in src2dsa:
  684. src2pop[row[1]] = row[3]
  685. except IndexError:
  686. print(row)
  687. continue
  688. return
  689. ###############################################################################
  690. ## get dependencies of a given source
  691. def getdeps(src2dsa, src2deps):
  692. for srcpkg in src2dsa:
  693. deps.getdeps(srcpkg, src2deps)
  694. ###############################################################################
  695. ## print some meta-info on internal data
  696. def aptsec_about(dsatable, cvetable, pkg2src, src2dsa):
  697. num_dsa = len(dsatable)
  698. num_cve = len(cvetable)
  699. num_pkg = len(pkg2src)
  700. num_src = len(src2dsa)
  701. print('\nThe current database records %d binary packages and %d DSAs.\n', num_pkg, num_src)
  702. print('%d CVEs are associated with %d source packages.\n', num_cve, num_src)
  703. return
  704. ###############################################################################
  705. ## use scores to suggest alternative packages
  706. def aptsec_alternatives(pkg):
  707. pass
  708. ###############################################################################
  709. ## print overview for pkg high scores
  710. def aptsec_hitlist():
  711. pass
  712. ###############################################################################
  713. ## evaluation helper
  714. ## compute stats until date given in $2, then compute stats
  715. ## for the next year to check accuracy of the prediction.
  716. ## @cvestats = (date base-score impact-score exploit-score)
  717. def simulate_stats(pkg, year):
  718. pass
  719. ###############################################################################
  720. ##TODO Printing functions
  721. def plot_all(src2month, src2sloccount, pkg_with_cvss):
  722. ## Sum of vulnerabilities by package
  723. src2sum = dict()
  724. src2year = dict()
  725. src2month_loc=dict()
  726. src2lastyears = dict()
  727. src2dens = dict()
  728. src2month_temp = dict()
  729. for i in pkg_with_cvss:
  730. src2month_temp[i]=[]
  731. for j in range(len(src2month[i])):
  732. #src2month_temp[i].append(pkg_with_cvss[i][j][1]+pkg_with_cvss[i][j][2])
  733. src2month_temp[i].append(pkg_with_cvss[i][j][2])
  734. for i in src2month:
  735. src2month_loc[i]=src2month_temp[i][:-12] #cut data for 2018
  736. years = 17 # 2001 - 2000 + years
  737. year_sum = [0] * years
  738. year_num = [0] * years
  739. for pkg in src2month_loc:
  740. for j in range(years):
  741. temp = sum(src2month_loc[pkg][12*(1+j):12*(2+j)])
  742. if (temp>0):
  743. year_num[j] += 1
  744. year_sum[j] += temp
  745. ## For last 2 years
  746. total = sum(src2month_loc[pkg][:])
  747. last_years = sum(src2month_loc[pkg][-24:])
  748. print(pkg + '; ' + str(last_years))
  749. if (total>1):
  750. src2sum[pkg] = total
  751. src2lastyears[pkg] = last_years
  752. #calc total
  753. sum_total = 0
  754. one_only=0
  755. one_plus=0
  756. for p in src2month:
  757. sum_part = sum(src2month_loc[p][:])
  758. sum_total += sum_part
  759. if (sum_part == 1):
  760. one_only += 1
  761. elif (sum_part>1):
  762. one_plus += 1
  763. print('Total last 2 years = ', sum_total)
  764. print('one_only = ', one_only)
  765. print('one_plus = ', one_plus)
  766. values = sorted(src2sum.values(),reverse=True)
  767. #print(values)
  768. keys = list(sorted(src2sum, key=src2sum.__getitem__, reverse=True))
  769. density = []
  770. density_keys=[]
  771. size = []
  772. size_dens = []
  773. for pkg in keys:
  774. try:
  775. size.append(src2sloccount[pkg][0]/1000)
  776. except (KeyError):
  777. size.append(0)
  778. j=0
  779. for pkg in keys:
  780. try:
  781. if (src2sloccount[pkg][0])>0:
  782. density.append((values[j]/src2sloccount[pkg][0])*1000)
  783. density_keys.append(pkg)
  784. src2dens[pkg] = (values[j]/src2sloccount[pkg][0])*1000
  785. size_dens.append(src2sloccount[pkg][0])
  786. except(KeyError):
  787. pass
  788. j += 1
  789. i = 0
  790. few_keys = []
  791. #print(keys)
  792. for k in keys:
  793. if (i==0):
  794. few_keys.append(k)
  795. i+=1
  796. if (i==10):
  797. i = 0
  798. print('package number =' + str(len(values)) + '... ' + str(len(keys)))
  799. carlosplt.pre_paper_plot(True)
  800. #plt.style.use('ggplot')
  801. print('Spearman correlation: ',stats.spearmanr(values,size))
  802. with open('sizes.txt', 'w') as thefile:
  803. for item in size:
  804. thefile.write("%.3f\n" % item)
  805. plt.figure(figsize=(10,5))
  806. plt.plot(values, color='darkblue', lw = 2)
  807. #plt.plot(size, 'ro', color='darkred', lw = 2, label='Size in KSLoC')
  808. plt.xticks(np.arange(0,len(src2sum),10.0),few_keys, rotation="vertical")
  809. plt.ylabel('Vulnerabilities')
  810. plt.yscale('log')
  811. plt.grid()
  812. #plt.xscale('log')
  813. plt.tight_layout()
  814. plt.legend()
  815. carlosplt.post_paper_plot(True,True,True)
  816. plt.show()
  817. print('Yearly vulnerabilites in total' + str(year_sum))
  818. src2sloc = dict()
  819. for pkg in src2sloccount:
  820. src2sloc[pkg] = src2sloccount[pkg][0]
  821. ## Density
  822. density = sorted(src2dens.values(),reverse=True)
  823. with open('densities.txt', 'w') as thefile:
  824. for item in density:
  825. thefile.write("%.3f\n" % item)
  826. density_keys = list(sorted(src2dens, key=src2dens.__getitem__, reverse=True))
  827. density_few_keys =[]
  828. for k in density_keys:
  829. if (i==0):
  830. density_few_keys.append(k)
  831. i+=1
  832. if (i==10):
  833. i = 0
  834. plt.figure(figsize=(10,5))
  835. plt.plot(size_dens, density, 'ro', color='darkblue', lw = 2)
  836. plt.xticks(np.arange(0,len(density),10.0),density_few_keys, rotation="vertical")
  837. plt.ylabel('Vulnerability density')
  838. plt.yscale('log')
  839. plt.xscale('log')
  840. plt.tight_layout()
  841. carlosplt.post_paper_plot(True,True,True)
  842. plt.show()
  843. ## Spearman density size
  844. print('Spearman correlation: ',stats.spearmanr(density,size_dens))
  845. ## SLoCs
  846. values = sorted(src2sloc.values(),reverse=True)
  847. #print(values)
  848. keys = list(sorted(src2sloc, key=src2sloc.__getitem__, reverse=True))
  849. i = 0
  850. few_keys = []
  851. for k in keys:
  852. if (i==0):
  853. few_keys.append(k)
  854. i+=1
  855. if (i==10):
  856. i = 0
  857. carlosplt.pre_paper_plot(True)
  858. plt.figure(figsize=(10,5))
  859. plt.plot(values, color='darkblue', lw = 2)
  860. plt.xticks(np.arange(0,len(src2sloc),10.0),few_keys, rotation="vertical")
  861. plt.ylabel('SLoC')
  862. plt.yscale('log')
  863. plt.xscale('log')
  864. plt.tight_layout()
  865. carlosplt.post_paper_plot(True,True,True)
  866. plt.show()
  867. ## Number of affected packages
  868. n = len(year_sum)
  869. yearsx = []
  870. for i in range(1,years+1):
  871. yearsx.append('\''+str(i).zfill(2))
  872. x = range(years)
  873. width = 1/2
  874. plt.bar(x, year_num, width, color='darkblue', edgecolor='black')
  875. plt.xticks(np.arange(0,n),yearsx)
  876. plt.ylabel('Number of affected packages')
  877. plt.xlabel('Year')
  878. carlosplt.post_paper_plot(True,True,True)
  879. plt.show()
  880. ## Average number of vulnerabilities per package per year
  881. average_per_year = [0] * years
  882. for j in range(years):
  883. average_per_year[j] = year_sum[j]/float(year_num[j])
  884. #print(average_per_year)
  885. x_values = list(range(1,years+1))
  886. #print(x_values)
  887. slope = np.polyfit(x_values,average_per_year,1)
  888. #slope = np.polyval(slope,x_values)
  889. print('Slope: ' + str(slope))
  890. n = len(year_sum)
  891. x = range(years)
  892. width = 1/2
  893. #plt.bar(x, year_sum, width)
  894. plt.bar(x, average_per_year, width, color='darkblue', edgecolor='black')
  895. plt.xticks(np.arange(0,n),yearsx)
  896. plt.ylabel('Average vulnerabilities per package')
  897. plt.xlabel('Year')
  898. carlosplt.post_paper_plot(True,True,True)
  899. plt.show()
  900. ## Work on selected packages (php7.0, openjdk8, wireshark, chromium-browser, icedove, linux)
  901. src2quarter = dict()
  902. quarter_num = years*4
  903. # Here for only up to 2016 - let's change that
  904. #return(src2sum)
  905. # pkg = 'php5'
  906. # quarter_sum = [0] * quarter_num
  907. # for j in range(quarter_num):
  908. # temp = sum(src2month_loc[pkg][12+3*j:12+3*(j+1)])
  909. # quarter_sum[j] = temp
  910. # src2quarter[pkg] = quarter_sum
  911. # for pkg in src2quarter:
  912. # n = len(src2quarter[pkg])
  913. quartersx = []
  914. for i in range(1,years+1):
  915. for j in range(1,5):
  916. if j==1:
  917. quartersx.append('Q' + str(j)+'\''+str(i).zfill(2))
  918. else:
  919. quartersx.append(' ')
  920. # x = range(quarter_num)
  921. # width = 1/2
  922. ## Plot different colors for php
  923. # before = src2quarter[pkg][:-8] + ([0] * 8)
  924. # after = ([0] * (len(before)-8)) + src2quarter[pkg][-8:]
  925. # print(len(src2quarter[pkg]))
  926. #
  927. # bar1 = plt.bar(x[:-26], before[24:-2], width, color='darkblue', label='before php7', edgecolor='black')
  928. # bar2 = plt.bar(x[:-26], after[24:-2], width, color='darkred', label='after php7', edgecolor='black')
  929. # plt.legend(handles=[bar1, bar2])
  930. #
  931. # print('PHP Sum before: ' + str(sum(before)))
  932. # print('PHP Sum after: ' + str(sum(after)))
  933. # plt.xticks(np.arange(0,n-26),quartersx[24:-2], rotation="vertical")
  934. # plt.ylabel('Vulnerabilities per quarter of package ' + pkg)
  935. # plt.xlabel('Quarter')
  936. # carlosplt.post_paper_plot(True,True,True)
  937. # plt.show()
  938. # ## Plot for openjdk-7
  939. #pkg = 'openjdk-8'
  940. #pkg = 'openjdk-7'
  941. #quarter_sum = [0] * quarter_num
  942. #for j in range(quarter_num):
  943. # temp = sum(src2month_loc[pkg][12+3*j:12+3*(j+1)])
  944. # quarter_sum[j] = temp
  945. #src2quarter[pkg] = quarter_sum
  946. #n = len(src2quarter[pkg])
  947. #x = range(quarter_num)
  948. #width = 1/2
  949. # ## Plot different colors for openjdk
  950. #before = src2quarter[pkg][:-10] + ([0] * 10)
  951. #after = ([0] * (len(before)-10)) + src2quarter[pkg][-10:]
  952. #print(len(src2quarter[pkg]))
  953. #bar1 = plt.bar(x[:-48], before[48:], width, color='darkblue', label='before openjdk-8', edgecolor='black')
  954. #bar2 = plt.bar(x[:-48], after[48:], width, color='darkred', label='after openjdk-8', edgecolor='black')
  955. #plt.legend(handles=[bar1, bar2])
  956. #print('OpenJDK Sum before: ' + str(sum(before)))
  957. #print('OpenJDK Sum after: ' + str(sum(after)))
  958. #plt.bar(x, src2quarter[pkg], width, color='red')
  959. #plt.xticks(np.arange(0,n-48),quartersx[48:], rotation="vertical")
  960. #plt.ylabel('Vulnerabilities per quarter of package ' + pkg)
  961. #plt.xlabel('Quarter')
  962. #carlosplt.post_paper_plot(True,True,True)
  963. #plt.show()
  964. ###############################################################################################
  965. n = len(year_sum)
  966. x = range(years)
  967. width = 1/2
  968. plt.bar(x, year_sum, width, color='darkblue', edgecolor='black')
  969. #plt.bar(x, average_per_year, width)
  970. plt.xticks(np.arange(0,n),yearsx)
  971. plt.ylabel('Total vulnerabilities')
  972. plt.xlabel('Year')
  973. carlosplt.post_paper_plot(True,True,True)
  974. plt.show()
  975. sum_all = sum(values)
  976. print("Total: ", sum_all)
  977. ###############################################################################################
  978. # Get LTS and plot
  979. try:
  980. with open("DLA_sum.txt","rb") as fp:
  981. ltslist = pickle.load(fp)
  982. except IOError:
  983. ltslist = dla.getDLAs()
  984. print(ltslist)
  985. ## Plot for wheezy
  986. quarter_num += 1
  987. quarter_sum = [0] * quarter_num
  988. totalLTS = [0] * (14 * 12) + ltslist
  989. for pkg in src2month_loc:
  990. for j in range(quarter_num):
  991. temp = sum(src2month_loc[pkg][12+(3*j):12+3*(j+1)])
  992. quarter_sum[j] += temp
  993. LTS_quarter = []
  994. for j in range(quarter_num):
  995. temp = sum(totalLTS[12+(3*j):12+3*(j+1)])
  996. LTS_quarter.append(temp)
  997. quartersx.append("Q1'18")
  998. ## Print all LTS
  999. cut = 12*4+1
  1000. n = len(quarter_sum)
  1001. x = range(quarter_num)
  1002. width = 1/2
  1003. plt.bar(x, LTS_quarter, width, color='brown', label='regular support', edgecolor='black')
  1004. plt.xticks(np.arange(0,n),quartersx, rotation="vertical")
  1005. plt.ylabel('Vulnerabilities per quarter of Debian LTS')
  1006. plt.xlabel('Quarter')
  1007. carlosplt.post_paper_plot(True,True,True)
  1008. plt.show()
  1009. ## Filter only wheezy:
  1010. quarter_sum_regular = [0] * (12*4+1) + quarter_sum[12*4+1:12*4+9] + [0] * 12
  1011. quarter_sum_errors = [0] * (12*4 + 9) + quarter_sum[12*4+9:12*4+9+5] + [0] * 7
  1012. LTS_quarter = [0] * (15*4+2) + LTS_quarter[15*4+2:]
  1013. #print(quarter_sum_errors)
  1014. cut = 12*4+1
  1015. n = len(quarter_sum) - cut
  1016. x = range(quarter_num-cut)
  1017. width = 1/2
  1018. #print(len(LTS_quarter))
  1019. bar1 = plt.bar(x, quarter_sum_regular[cut:], width, color='darkblue', label='regular', edgecolor='black')
  1020. bar12 = plt.bar(x, quarter_sum_errors[cut:], width, color='darkorange', label='regular*', edgecolor='black')
  1021. bar2 = plt.bar(x, LTS_quarter[cut:], width, color='darkred', label ='long-term', edgecolor='black')
  1022. plt.legend(handles=[bar1, bar12, bar2])
  1023. plt.xticks(np.arange(0,n),quartersx[cut:], rotation="vertical")
  1024. plt.ylabel('Vulnerabilities per quarter of Debian Wheezy')
  1025. plt.xlabel('Quarter')
  1026. carlosplt.post_paper_plot(True,True,True)
  1027. plt.show()
  1028. ## power-law fit
  1029. #print(values)
  1030. #results=pl.Fit(values, discrete=True, xmin=1)
  1031. #print(results.power_law.alpha)
  1032. #print(results.truncated_power_law.alpha)
  1033. #print(results.power_law.xmin)
  1034. #print(results.truncated_power_law.xmin)
  1035. #print(results.truncated_power_law.xmax)
  1036. #print(results.power_law.discrete)
  1037. #print(results.lognormal.mu)
  1038. #results.plot_ccdf(color = 'blue')
  1039. #myax = plt.gca()
  1040. ##results.lognormal.plot_pdf(color = 'yellow')
  1041. ##results.exponential.plot_pdf(color = 'purple')
  1042. #results.stretched_exponential.plot_pdf(color = 'black')
  1043. #results.power_law.plot_ccdf(color = 'green', ax=myax)
  1044. #results.truncated_power_law.plot_ccdf(color = 'red', ax=myax)
  1045. #results.lognormal.plot_ccdf(color = 'pink', ax=myax)
  1046. ##results.exponential.plot_ccdf(color = 'pink', ax=myax)
  1047. ##plt.plot(results.data)
  1048. #plt.show()
  1049. #R, p=results.distribution_compare('power_law','stretched_exponential')
  1050. #print(R,p)
  1051. #R, p=results.distribution_compare('power_law','lognormal')
  1052. #print(R,p)
  1053. #R, p=results.distribution_compare('power_law','exponential')
  1054. #print(R,p)
  1055. #R, p=results.distribution_compare('power_law','truncated_power_law')
  1056. #print(R,p)
  1057. #R, p=results.distribution_compare('power_law','lognormal_positive')
  1058. #print(R,p)
  1059. #R, p=results.distribution_compare('truncated_power_law','lognormal')
  1060. #print(R,p)
  1061. ###############################################################################################
  1062. ##
  1063. return(src2sum)
  1064. ###############################################################################
  1065. ## print help text
  1066. def aptsec_help():
  1067. print('See manual for correct usage\n')
  1068. ###############################################################################
  1069. ## Print system status report from component(files) measurements (sha1sums)
  1070. ## Expected input format is Linux IMA. We assume input was validated.
  1071. ##
  1072. ## Note: aptsec_status(), considers *reportedly installed* packages, while this
  1073. ## one looks at *actually loaded* software that influenced the CPU since bootup.
  1074. try:
  1075. action = sys.argv[1]
  1076. except IndexError:
  1077. print('No argument given')
  1078. action='update'
  1079. #aptsec_help()
  1080. #sys.exit(0)
  1081. #action = ''
  1082. client = MongoClient()
  1083. dsatable = dict()
  1084. cve_db = client.cvedb
  1085. src2dsa = dict()
  1086. dsa2cve = dict()
  1087. cvetable = dict()
  1088. src2month = dict()
  1089. src2deps = dict()
  1090. pkg_with_cvss = dict()
  1091. src2sloccount = dict()
  1092. src2pop = dict()
  1093. src2sum = dict()
  1094. (state, err) = load_state()
  1095. state['vendor'] = 'debian'
  1096. #detect_distribution()
  1097. #d = state['cache_dir']
  1098. #if not os.path.exists(d):
  1099. # os.makedirs(d)
  1100. if action == 'update':
  1101. (dsatable, src2dsa, dsa2cve, cvetable, src2month, src2sloccount, src2pop, src2deps, pkg_with_cvss) = load_DBs()
  1102. # loadsha1lists()
  1103. aptsec_update(state,config, dsatable, client, src2dsa, dsa2cve, src2month, cvetable, pkg_with_cvss)
  1104. # save_sha1lists()
  1105. # getslocs(src2month, src2sloccount)
  1106. # getpop(src2dsa, src2pop)
  1107. # getdeps(src2dsa, src2deps)
  1108. save_DBs(dsatable, src2dsa, dsa2cve, cvetable, src2month, src2sloccount, src2pop, src2deps, src2sum, pkg_with_cvss)
  1109. save_state(state)
  1110. # stats.test(src2month, src2pop, src2sloccount)
  1111. # lstm.predict(src2month, src2sloccount, src2pop, src2deps)
  1112. pred.predict(src2month, 0)
  1113. # print(pkg_with_cvss['linux'])
  1114. low = []
  1115. med = []
  1116. high = []
  1117. elif action == 'status':
  1118. (dsatable, src2dsa, dsa2cve, cvetable, src2month, src2sloccount, src2pop, src2deps, pkg_with_cvss) = load_DBs()
  1119. aptsec_status(sys.argv[2])
  1120. elif action == 'show':
  1121. (dsatable, src2dsa, dsa2cve, cvetable, src2month, src2sloccount, src2pop, src2deps, pkg_with_cvss) = load_DBs()
  1122. src2sum = plot_all(src2month, src2sloccount, pkg_with_cvss)
  1123. save_DBs(dsatable, src2dsa, dsa2cve, cvetable, src2month, src2sloccount, src2pop, src2deps, src2sum, pkg_with_cvss)
  1124. else:
  1125. aptsec_help()
  1126. save_state(state)