pkg-stats 48 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305
  1. #!/usr/bin/env python3
  2. # Copyright (C) 2009 by Thomas Petazzoni <thomas.petazzoni@free-electrons.com>
  3. #
  4. # This program is free software; you can redistribute it and/or modify
  5. # it under the terms of the GNU General Public License as published by
  6. # the Free Software Foundation; either version 2 of the License, or
  7. # (at your option) any later version.
  8. #
  9. # This program is distributed in the hope that it will be useful,
  10. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  11. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  12. # General Public License for more details.
  13. #
  14. # You should have received a copy of the GNU General Public License
  15. # along with this program; if not, write to the Free Software
  16. # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
  17. import aiohttp
  18. import argparse
  19. import asyncio
  20. import datetime
  21. import fnmatch
  22. import os
  23. from collections import defaultdict
  24. import re
  25. import subprocess
  26. import json
  27. import sys
  28. import time
  29. import gzip
  30. import xml.etree.ElementTree
  31. import requests
  32. brpath = os.path.normpath(os.path.join(os.path.dirname(__file__), "..", ".."))
  33. sys.path.append(os.path.join(brpath, "utils"))
  34. from getdeveloperlib import parse_developers # noqa: E402
  35. from cpedb import CPEDB_URL # noqa: E402
  36. INFRA_RE = re.compile(r"\$\(eval \$\(([a-z-]*)-package\)\)")
  37. URL_RE = re.compile(r"\s*https?://\S*\s*$")
  38. RM_API_STATUS_ERROR = 1
  39. RM_API_STATUS_FOUND_BY_DISTRO = 2
  40. RM_API_STATUS_FOUND_BY_PATTERN = 3
  41. RM_API_STATUS_NOT_FOUND = 4
  42. class Defconfig:
  43. def __init__(self, name, path):
  44. self.name = name
  45. self.path = path
  46. self.developers = None
  47. def set_developers(self, developers):
  48. """
  49. Fills in the .developers field
  50. """
  51. self.developers = [
  52. developer.name
  53. for developer in developers
  54. if developer.hasfile(self.path)
  55. ]
  56. def get_defconfig_list():
  57. """
  58. Builds the list of Buildroot defconfigs, returning a list of Defconfig
  59. objects.
  60. """
  61. return [
  62. Defconfig(name[:-len('_defconfig')], os.path.join('configs', name))
  63. for name in os.listdir(os.path.join(brpath, 'configs'))
  64. if name.endswith('_defconfig')
  65. ]
  66. class Package:
  67. all_licenses = dict()
  68. all_license_files = list()
  69. all_versions = dict()
  70. all_ignored_cves = dict()
  71. all_cpeids = dict()
  72. # This is the list of all possible checks. Add new checks to this list so
  73. # a tool that post-processeds the json output knows the checks before
  74. # iterating over the packages.
  75. status_checks = ['cve', 'developers', 'hash', 'license',
  76. 'license-files', 'patches', 'pkg-check', 'url', 'version']
  77. def __init__(self, name, path):
  78. self.name = name
  79. self.path = path
  80. self.pkg_path = os.path.dirname(path)
  81. # Contains a list of tuple (type, infra), such as ("target",
  82. # "autotools"). When pkg-stats is run without -c, it contains
  83. # the list of all infra/type supported by the package. When
  84. # pkg-stats is run with -c, it contains the list of infra/type
  85. # used by the current configuration.
  86. self.infras = None
  87. self.license = None
  88. self.has_license = False
  89. self.has_license_files = False
  90. self.has_hash = False
  91. self.patch_files = []
  92. self.warnings = 0
  93. self.current_version = None
  94. self.url = None
  95. self.url_worker = None
  96. self.cpeid = None
  97. self.cves = list()
  98. self.ignored_cves = list()
  99. self.unsure_cves = list()
  100. self.latest_version = {'status': RM_API_STATUS_ERROR, 'version': None, 'id': None}
  101. self.status = {}
  102. def pkgvar(self):
  103. return self.name.upper().replace("-", "_")
  104. def set_url(self):
  105. """
  106. Fills in the .url field
  107. """
  108. self.status['url'] = ("warning", "no Config.in")
  109. pkgdir = os.path.dirname(os.path.join(brpath, self.path))
  110. for filename in os.listdir(pkgdir):
  111. if fnmatch.fnmatch(filename, 'Config.*'):
  112. fp = open(os.path.join(pkgdir, filename), "r")
  113. for config_line in fp:
  114. if URL_RE.match(config_line):
  115. self.url = config_line.strip()
  116. self.status['url'] = ("ok", "found")
  117. fp.close()
  118. return
  119. self.status['url'] = ("error", "missing")
  120. fp.close()
  121. @property
  122. def patch_count(self):
  123. return len(self.patch_files)
  124. @property
  125. def has_valid_infra(self):
  126. if self.infras is None:
  127. return False
  128. return len(self.infras) > 0
  129. @property
  130. def is_actual_package(self):
  131. try:
  132. if not self.has_valid_infra:
  133. return False
  134. if self.infras[0][1] == 'virtual':
  135. return False
  136. except IndexError:
  137. return False
  138. return True
  139. def set_infra(self, show_info_js):
  140. """
  141. Fills in the .infras field
  142. """
  143. # If we're running pkg-stats for a given Buildroot
  144. # configuration, keep only the type/infra that applies
  145. if show_info_js:
  146. keep_host = "host-%s" % self.name in show_info_js
  147. keep_target = self.name in show_info_js
  148. # Otherwise, keep all
  149. else:
  150. keep_host = True
  151. keep_target = True
  152. self.infras = list()
  153. with open(os.path.join(brpath, self.path), 'r') as f:
  154. lines = f.readlines()
  155. for line in lines:
  156. match = INFRA_RE.match(line)
  157. if not match:
  158. continue
  159. infra = match.group(1)
  160. if infra.startswith("host-") and keep_host:
  161. self.infras.append(("host", infra[5:]))
  162. elif keep_target:
  163. self.infras.append(("target", infra))
  164. def set_license(self):
  165. """
  166. Fills in the .status['license'] and .status['license-files'] fields
  167. """
  168. if not self.is_actual_package:
  169. self.status['license'] = ("na", "no valid package infra")
  170. self.status['license-files'] = ("na", "no valid package infra")
  171. return
  172. var = self.pkgvar()
  173. self.status['license'] = ("error", "missing")
  174. self.status['license-files'] = ("error", "missing")
  175. if var in self.all_licenses:
  176. self.license = self.all_licenses[var]
  177. self.status['license'] = ("ok", "found")
  178. if var in self.all_license_files:
  179. self.status['license-files'] = ("ok", "found")
  180. def set_hash_info(self):
  181. """
  182. Fills in the .status['hash'] field
  183. """
  184. if not self.is_actual_package:
  185. self.status['hash'] = ("na", "no valid package infra")
  186. self.status['hash-license'] = ("na", "no valid package infra")
  187. return
  188. hashpath = self.path.replace(".mk", ".hash")
  189. if os.path.exists(os.path.join(brpath, hashpath)):
  190. self.status['hash'] = ("ok", "found")
  191. else:
  192. self.status['hash'] = ("error", "missing")
  193. def set_patch_count(self):
  194. """
  195. Fills in the .patch_count, .patch_files and .status['patches'] fields
  196. """
  197. if not self.is_actual_package:
  198. self.status['patches'] = ("na", "no valid package infra")
  199. return
  200. pkgdir = os.path.dirname(os.path.join(brpath, self.path))
  201. for subdir, _, _ in os.walk(pkgdir):
  202. self.patch_files = fnmatch.filter(os.listdir(subdir), '*.patch')
  203. if self.patch_count == 0:
  204. self.status['patches'] = ("ok", "no patches")
  205. elif self.patch_count < 5:
  206. self.status['patches'] = ("warning", "some patches")
  207. else:
  208. self.status['patches'] = ("error", "lots of patches")
  209. def set_current_version(self):
  210. """
  211. Fills in the .current_version field
  212. """
  213. var = self.pkgvar()
  214. if var in self.all_versions:
  215. self.current_version = self.all_versions[var]
  216. def set_cpeid(self):
  217. """
  218. Fills in the .cpeid field
  219. """
  220. var = self.pkgvar()
  221. if not self.is_actual_package:
  222. self.status['cpe'] = ("na", "N/A - virtual pkg")
  223. return
  224. if not self.current_version:
  225. self.status['cpe'] = ("na", "no version information available")
  226. return
  227. if var in self.all_cpeids:
  228. self.cpeid = self.all_cpeids[var]
  229. # Set a preliminary status, it might be overridden by check_package_cpes()
  230. self.status['cpe'] = ("warning", "not checked against CPE dictionnary")
  231. else:
  232. self.status['cpe'] = ("error", "no verified CPE identifier")
  233. def set_check_package_warnings(self):
  234. """
  235. Fills in the .warnings and .status['pkg-check'] fields
  236. """
  237. cmd = [os.path.join(brpath, "utils/check-package")]
  238. pkgdir = os.path.dirname(os.path.join(brpath, self.path))
  239. self.status['pkg-check'] = ("error", "Missing")
  240. for root, dirs, files in os.walk(pkgdir):
  241. for f in files:
  242. if f.endswith(".mk") or f.endswith(".hash") or f == "Config.in" or f == "Config.in.host":
  243. cmd.append(os.path.join(root, f))
  244. o = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE).communicate()[1]
  245. lines = o.splitlines()
  246. for line in lines:
  247. m = re.match("^([0-9]*) warnings generated", line.decode())
  248. if m:
  249. self.warnings = int(m.group(1))
  250. if self.warnings == 0:
  251. self.status['pkg-check'] = ("ok", "no warnings")
  252. else:
  253. self.status['pkg-check'] = ("error", "{} warnings".format(self.warnings))
  254. return
  255. def set_ignored_cves(self):
  256. """
  257. Give the list of CVEs ignored by the package
  258. """
  259. self.ignored_cves = list(self.all_ignored_cves.get(self.pkgvar(), []))
  260. def set_developers(self, developers):
  261. """
  262. Fills in the .developers and .status['developers'] field
  263. """
  264. self.developers = [
  265. dev.name
  266. for dev in developers
  267. if dev.hasfile(self.path)
  268. ]
  269. if self.developers:
  270. self.status['developers'] = ("ok", "{} developers".format(len(self.developers)))
  271. else:
  272. self.status['developers'] = ("warning", "no developers")
  273. def is_status_ok(self, name):
  274. return name in self.status and self.status[name][0] == 'ok'
  275. def is_status_error(self, name):
  276. return name in self.status and self.status[name][0] == 'error'
  277. def is_status_na(self, name):
  278. return name in self.status and self.status[name][0] == 'na'
  279. def __eq__(self, other):
  280. return self.path == other.path
  281. def __lt__(self, other):
  282. return self.path < other.path
  283. def __str__(self):
  284. return "%s (path='%s', license='%s', license_files='%s', hash='%s', patches=%d)" % \
  285. (self.name, self.path, self.is_status_ok('license'),
  286. self.is_status_ok('license-files'), self.status['hash'], self.patch_count)
  287. def get_pkglist(npackages, package_list):
  288. """
  289. Builds the list of Buildroot packages, returning a list of Package
  290. objects. Only the .name and .path fields of the Package object are
  291. initialized.
  292. npackages: limit to N packages
  293. package_list: limit to those packages in this list
  294. """
  295. WALK_USEFUL_SUBDIRS = ["boot", "linux", "package", "toolchain"]
  296. WALK_EXCLUDES = ["boot/common.mk",
  297. "linux/linux-ext-.*.mk",
  298. "package/freescale-imx/freescale-imx.mk",
  299. "package/gcc/gcc.mk",
  300. "package/gstreamer/gstreamer.mk",
  301. "package/gstreamer1/gstreamer1.mk",
  302. "package/gtk2-themes/gtk2-themes.mk",
  303. "package/matchbox/matchbox.mk",
  304. "package/opengl/opengl.mk",
  305. "package/qt5/qt5.mk",
  306. "package/x11r7/x11r7.mk",
  307. "package/doc-asciidoc.mk",
  308. "package/pkg-.*.mk",
  309. "toolchain/toolchain-external/pkg-toolchain-external.mk",
  310. "toolchain/toolchain-external/toolchain-external.mk",
  311. "toolchain/toolchain.mk",
  312. "toolchain/helpers.mk",
  313. "toolchain/toolchain-wrapper.mk"]
  314. packages = list()
  315. count = 0
  316. for root, dirs, files in os.walk(brpath):
  317. root = os.path.relpath(root, brpath)
  318. rootdir = root.split("/")
  319. if len(rootdir) < 1:
  320. continue
  321. if rootdir[0] not in WALK_USEFUL_SUBDIRS:
  322. continue
  323. for f in files:
  324. if not f.endswith(".mk"):
  325. continue
  326. # Strip ending ".mk"
  327. pkgname = f[:-3]
  328. if package_list and pkgname not in package_list:
  329. continue
  330. pkgpath = os.path.join(root, f)
  331. skip = False
  332. for exclude in WALK_EXCLUDES:
  333. if re.match(exclude, pkgpath):
  334. skip = True
  335. continue
  336. if skip:
  337. continue
  338. p = Package(pkgname, pkgpath)
  339. packages.append(p)
  340. count += 1
  341. if npackages and count == npackages:
  342. return packages
  343. return packages
  344. def get_show_info_js():
  345. cmd = ["make", "--no-print-directory", "show-info"]
  346. return json.loads(subprocess.check_output(cmd))
  347. def package_init_make_info():
  348. # Fetch all variables at once
  349. variables = subprocess.check_output(["make", "--no-print-directory", "-s",
  350. "BR2_HAVE_DOT_CONFIG=y", "printvars",
  351. "VARS=%_LICENSE %_LICENSE_FILES %_VERSION %_IGNORE_CVES %_CPE_ID"])
  352. variable_list = variables.decode().splitlines()
  353. # We process first the host package VERSION, and then the target
  354. # package VERSION. This means that if a package exists in both
  355. # target and host variants, with different values (eg. version
  356. # numbers (unlikely)), we'll report the target one.
  357. variable_list = [x[5:] for x in variable_list if x.startswith("HOST_")] + \
  358. [x for x in variable_list if not x.startswith("HOST_")]
  359. for item in variable_list:
  360. # Get variable name and value
  361. pkgvar, value = item.split("=", maxsplit=1)
  362. # Strip the suffix according to the variable
  363. if pkgvar.endswith("_LICENSE"):
  364. # If value is "unknown", no license details available
  365. if value == "unknown":
  366. continue
  367. pkgvar = pkgvar[:-8]
  368. Package.all_licenses[pkgvar] = value
  369. elif pkgvar.endswith("_LICENSE_FILES"):
  370. if pkgvar.endswith("_MANIFEST_LICENSE_FILES"):
  371. continue
  372. pkgvar = pkgvar[:-14]
  373. Package.all_license_files.append(pkgvar)
  374. elif pkgvar.endswith("_VERSION"):
  375. if pkgvar.endswith("_DL_VERSION"):
  376. continue
  377. pkgvar = pkgvar[:-8]
  378. Package.all_versions[pkgvar] = value
  379. elif pkgvar.endswith("_IGNORE_CVES"):
  380. pkgvar = pkgvar[:-12]
  381. Package.all_ignored_cves[pkgvar] = value.split()
  382. elif pkgvar.endswith("_CPE_ID"):
  383. pkgvar = pkgvar[:-7]
  384. Package.all_cpeids[pkgvar] = value
  385. check_url_count = 0
  386. async def check_url_status(session, pkg, npkgs, retry=True):
  387. global check_url_count
  388. try:
  389. async with session.get(pkg.url) as resp:
  390. if resp.status >= 400:
  391. pkg.status['url'] = ("error", "invalid {}".format(resp.status))
  392. check_url_count += 1
  393. print("[%04d/%04d] %s" % (check_url_count, npkgs, pkg.name))
  394. return
  395. except (aiohttp.ClientError, asyncio.TimeoutError):
  396. if retry:
  397. return await check_url_status(session, pkg, npkgs, retry=False)
  398. else:
  399. pkg.status['url'] = ("error", "invalid (err)")
  400. check_url_count += 1
  401. print("[%04d/%04d] %s" % (check_url_count, npkgs, pkg.name))
  402. return
  403. pkg.status['url'] = ("ok", "valid")
  404. check_url_count += 1
  405. print("[%04d/%04d] %s" % (check_url_count, npkgs, pkg.name))
  406. async def check_package_urls(packages):
  407. tasks = []
  408. connector = aiohttp.TCPConnector(limit_per_host=5)
  409. async with aiohttp.ClientSession(connector=connector, trust_env=True,
  410. timeout=aiohttp.ClientTimeout(total=15)) as sess:
  411. packages = [p for p in packages if p.status['url'][0] == 'ok']
  412. for pkg in packages:
  413. tasks.append(asyncio.ensure_future(check_url_status(sess, pkg, len(packages))))
  414. await asyncio.wait(tasks)
  415. def check_package_latest_version_set_status(pkg, status, version, identifier):
  416. pkg.latest_version = {
  417. "status": status,
  418. "version": version,
  419. "id": identifier,
  420. }
  421. if pkg.latest_version['status'] == RM_API_STATUS_ERROR:
  422. pkg.status['version'] = ('warning', "Release Monitoring API error")
  423. elif pkg.latest_version['status'] == RM_API_STATUS_NOT_FOUND:
  424. pkg.status['version'] = ('warning', "Package not found on Release Monitoring")
  425. if pkg.latest_version['version'] is None:
  426. pkg.status['version'] = ('warning', "No upstream version available on Release Monitoring")
  427. elif pkg.latest_version['version'] != pkg.current_version:
  428. pkg.status['version'] = ('error', "The newer version {} is available upstream".format(pkg.latest_version['version']))
  429. else:
  430. pkg.status['version'] = ('ok', 'up-to-date')
  431. async def check_package_get_latest_version_by_distro(session, pkg, retry=True):
  432. url = "https://release-monitoring.org//api/project/Buildroot/%s" % pkg.name
  433. try:
  434. async with session.get(url) as resp:
  435. if resp.status != 200:
  436. return False
  437. data = await resp.json()
  438. if 'stable_versions' in data and data['stable_versions']:
  439. version = data['stable_versions'][0]
  440. elif 'version' in data:
  441. version = data['version']
  442. else:
  443. version = None
  444. check_package_latest_version_set_status(pkg,
  445. RM_API_STATUS_FOUND_BY_DISTRO,
  446. version,
  447. data['id'])
  448. return True
  449. except (aiohttp.ClientError, asyncio.TimeoutError):
  450. if retry:
  451. return await check_package_get_latest_version_by_distro(session, pkg, retry=False)
  452. else:
  453. return False
  454. async def check_package_get_latest_version_by_guess(session, pkg, retry=True):
  455. url = "https://release-monitoring.org/api/projects/?pattern=%s" % pkg.name
  456. try:
  457. async with session.get(url) as resp:
  458. if resp.status != 200:
  459. return False
  460. data = await resp.json()
  461. # filter projects that have the right name and a version defined
  462. projects = [p for p in data['projects'] if p['name'] == pkg.name and 'stable_versions' in p]
  463. projects.sort(key=lambda x: x['id'])
  464. if len(projects) > 0:
  465. check_package_latest_version_set_status(pkg,
  466. RM_API_STATUS_FOUND_BY_PATTERN,
  467. projects[0]['stable_versions'][0],
  468. projects[0]['id'])
  469. return True
  470. except (aiohttp.ClientError, asyncio.TimeoutError):
  471. if retry:
  472. return await check_package_get_latest_version_by_guess(session, pkg, retry=False)
  473. else:
  474. return False
  475. check_latest_count = 0
  476. async def check_package_latest_version_get(session, pkg, npkgs):
  477. global check_latest_count
  478. if await check_package_get_latest_version_by_distro(session, pkg):
  479. check_latest_count += 1
  480. print("[%04d/%04d] %s" % (check_latest_count, npkgs, pkg.name))
  481. return
  482. if await check_package_get_latest_version_by_guess(session, pkg):
  483. check_latest_count += 1
  484. print("[%04d/%04d] %s" % (check_latest_count, npkgs, pkg.name))
  485. return
  486. check_package_latest_version_set_status(pkg,
  487. RM_API_STATUS_NOT_FOUND,
  488. None, None)
  489. check_latest_count += 1
  490. print("[%04d/%04d] %s" % (check_latest_count, npkgs, pkg.name))
  491. async def check_package_latest_version(packages):
  492. """
  493. Fills in the .latest_version field of all Package objects
  494. This field is a dict and has the following keys:
  495. - status: one of RM_API_STATUS_ERROR,
  496. RM_API_STATUS_FOUND_BY_DISTRO, RM_API_STATUS_FOUND_BY_PATTERN,
  497. RM_API_STATUS_NOT_FOUND
  498. - version: string containing the latest version known by
  499. release-monitoring.org for this package
  500. - id: string containing the id of the project corresponding to this
  501. package, as known by release-monitoring.org
  502. """
  503. for pkg in [p for p in packages if not p.is_actual_package]:
  504. pkg.status['version'] = ("na", "no valid package infra")
  505. tasks = []
  506. connector = aiohttp.TCPConnector(limit_per_host=5)
  507. async with aiohttp.ClientSession(connector=connector, trust_env=True) as sess:
  508. packages = [p for p in packages if p.is_actual_package]
  509. for pkg in packages:
  510. tasks.append(asyncio.ensure_future(check_package_latest_version_get(sess, pkg, len(packages))))
  511. await asyncio.wait(tasks)
  512. def check_package_cve_affects(cve, cpe_product_pkgs):
  513. for product in cve.affected_products:
  514. if product not in cpe_product_pkgs:
  515. continue
  516. for pkg in cpe_product_pkgs[product]:
  517. cve_status = cve.affects(pkg.name, pkg.current_version, pkg.ignored_cves, pkg.cpeid)
  518. if cve_status == cve.CVE_AFFECTS:
  519. pkg.cves.append(cve.identifier)
  520. elif cve_status == cve.CVE_UNKNOWN:
  521. pkg.unsure_cves.append(cve.identifier)
  522. def check_package_cves(nvd_path, packages):
  523. if not os.path.isdir(nvd_path):
  524. os.makedirs(nvd_path)
  525. cpe_product_pkgs = defaultdict(list)
  526. for pkg in packages:
  527. if not pkg.is_actual_package:
  528. pkg.status['cve'] = ("na", "N/A")
  529. continue
  530. if not pkg.current_version:
  531. pkg.status['cve'] = ("na", "no version information available")
  532. continue
  533. if pkg.cpeid:
  534. cpe_product = cvecheck.cpe_product(pkg.cpeid)
  535. cpe_product_pkgs[cpe_product].append(pkg)
  536. else:
  537. cpe_product_pkgs[pkg.name].append(pkg)
  538. for cve in cvecheck.CVE.read_nvd_dir(nvd_path):
  539. check_package_cve_affects(cve, cpe_product_pkgs)
  540. for pkg in packages:
  541. if 'cve' not in pkg.status:
  542. if pkg.cves or pkg.unsure_cves:
  543. pkg.status['cve'] = ("error", "affected by CVEs")
  544. else:
  545. pkg.status['cve'] = ("ok", "not affected by CVEs")
  546. def check_package_cpes(nvd_path, packages):
  547. class CpeXmlParser:
  548. cpes = []
  549. def start(self, tag, attrib):
  550. if tag == "{http://scap.nist.gov/schema/cpe-extension/2.3}cpe23-item":
  551. self.cpes.append(attrib['name'])
  552. def close(self):
  553. return self.cpes
  554. print("CPE: Setting up NIST dictionary")
  555. if not os.path.exists(os.path.join(nvd_path, "cpe")):
  556. os.makedirs(os.path.join(nvd_path, "cpe"))
  557. cpe_dict_local = os.path.join(nvd_path, "cpe", os.path.basename(CPEDB_URL))
  558. if not os.path.exists(cpe_dict_local) or os.stat(cpe_dict_local).st_mtime < time.time() - 86400:
  559. print("CPE: Fetching xml manifest from [" + CPEDB_URL + "]")
  560. cpe_dict = requests.get(CPEDB_URL)
  561. open(cpe_dict_local, "wb").write(cpe_dict.content)
  562. print("CPE: Unzipping xml manifest...")
  563. nist_cpe_file = gzip.GzipFile(fileobj=open(cpe_dict_local, 'rb'))
  564. parser = xml.etree.ElementTree.XMLParser(target=CpeXmlParser())
  565. while True:
  566. c = nist_cpe_file.read(1024*1024)
  567. if not c:
  568. break
  569. parser.feed(c)
  570. cpes = parser.close()
  571. for p in packages:
  572. if not p.cpeid:
  573. continue
  574. if p.cpeid in cpes:
  575. p.status['cpe'] = ("ok", "verified CPE identifier")
  576. else:
  577. p.status['cpe'] = ("error", "CPE version unknown in CPE database")
  578. def calculate_stats(packages):
  579. stats = defaultdict(int)
  580. stats['packages'] = len(packages)
  581. for pkg in packages:
  582. # If packages have multiple infra, take the first one. For the
  583. # vast majority of packages, the target and host infra are the
  584. # same. There are very few packages that use a different infra
  585. # for the host and target variants.
  586. if len(pkg.infras) > 0:
  587. infra = pkg.infras[0][1]
  588. stats["infra-%s" % infra] += 1
  589. else:
  590. stats["infra-unknown"] += 1
  591. if pkg.is_status_ok('license'):
  592. stats["license"] += 1
  593. else:
  594. stats["no-license"] += 1
  595. if pkg.is_status_ok('license-files'):
  596. stats["license-files"] += 1
  597. else:
  598. stats["no-license-files"] += 1
  599. if pkg.is_status_ok('hash'):
  600. stats["hash"] += 1
  601. else:
  602. stats["no-hash"] += 1
  603. if pkg.latest_version['status'] == RM_API_STATUS_FOUND_BY_DISTRO:
  604. stats["rmo-mapping"] += 1
  605. else:
  606. stats["rmo-no-mapping"] += 1
  607. if not pkg.latest_version['version']:
  608. stats["version-unknown"] += 1
  609. elif pkg.latest_version['version'] == pkg.current_version:
  610. stats["version-uptodate"] += 1
  611. else:
  612. stats["version-not-uptodate"] += 1
  613. stats["patches"] += pkg.patch_count
  614. stats["total-cves"] += len(pkg.cves)
  615. stats["total-unsure-cves"] += len(pkg.unsure_cves)
  616. if len(pkg.cves) != 0:
  617. stats["pkg-cves"] += 1
  618. if len(pkg.unsure_cves) != 0:
  619. stats["pkg-unsure-cves"] += 1
  620. if pkg.cpeid:
  621. stats["cpe-id"] += 1
  622. else:
  623. stats["no-cpe-id"] += 1
  624. return stats
  625. html_header = """
  626. <!DOCTYPE html>
  627. <html lang="en">
  628. <head>
  629. <meta charset="UTF-8">
  630. <meta name="viewport" content="width=device-width, initial-scale=1">
  631. <script>
  632. function sortGrid(sortLabel){
  633. let pkgSortArray = [], sortedPkgArray = [], pkgStringSortArray = [], pkgNumSortArray = [];
  634. let columnValues = Array.from(document.getElementsByClassName(sortLabel));
  635. columnValues.shift();
  636. columnValues.forEach((listing) => {
  637. let sortArr = [];
  638. sortArr[0] = listing.id.replace(sortLabel+"_", "");
  639. if (!listing.innerText){
  640. sortArr[1] = -1;
  641. } else {
  642. sortArr[1] = listing.innerText;
  643. };
  644. pkgSortArray.push(sortArr);
  645. })
  646. pkgSortArray.forEach((listing) => {
  647. if ( isNaN(parseInt(listing[1], 10)) ){
  648. pkgStringSortArray.push(listing);
  649. } else {
  650. listing[1] = parseFloat(listing[1]);
  651. pkgNumSortArray.push(listing);
  652. };
  653. })
  654. sortedStringPkgArray = pkgStringSortArray.sort(function(a, b) {
  655. const nameA = a[1].toUpperCase(); // ignore upper and lowercase
  656. const nameB = b[1].toUpperCase(); // ignore upper and lowercase
  657. if (nameA < nameB) { return -1; };
  658. if (nameA > nameB) { return 1; };
  659. return 0; // names must be equal
  660. });
  661. sortedNumPkgArray = pkgNumSortArray.sort(function(a, b) {
  662. return a[1] - b[1];
  663. });
  664. let triangleUp = String.fromCodePoint(32, 9652);
  665. let triangleDown = String.fromCodePoint(32, 9662);
  666. let columnName = document.getElementById(sortLabel);
  667. if (columnName.lastElementChild.innerText == triangleDown) {
  668. columnName.lastElementChild.innerText = triangleUp;
  669. sortedStringPkgArray.reverse();
  670. sortedNumPkgArray.reverse();
  671. sortedPkgArray = sortedNumPkgArray.concat(sortedStringPkgArray)
  672. } else {
  673. columnName.lastElementChild.innerText = triangleDown;
  674. sortedPkgArray = sortedStringPkgArray.concat(sortedNumPkgArray)
  675. }
  676. sortedPkgArray.forEach((listing) => {
  677. let row = Array.from(document.getElementsByClassName(listing[0]));
  678. let packageGrid = document.getElementById("package-grid");
  679. row.forEach((element) => { packageGrid.append(element)});
  680. })
  681. }
  682. </script>
  683. <style>
  684. .label {
  685. position: sticky;
  686. top: 1px;
  687. }
  688. .label{
  689. background: white;
  690. padding: 10px 2px 10px 2px;
  691. }
  692. #package-grid, #results-grid {
  693. display: grid;
  694. grid-gap: 2px;
  695. grid-template-columns: 1fr repeat(12, min-content);
  696. }
  697. #results-grid {
  698. grid-template-columns: 3fr 1fr;
  699. }
  700. .data {
  701. border: solid 1px gray;
  702. }
  703. .centered {
  704. text-align: center;
  705. }
  706. .wrong, .lotsofpatches, .invalid_url, .version-needs-update, .cpe-nok, .cve-nok {
  707. background: #ff9a69;
  708. }
  709. .correct, .nopatches, .good_url, .version-good, .cpe-ok, .cve-ok {
  710. background: #d2ffc4;
  711. }
  712. .somepatches, .missing_url, .version-unknown, .cpe-unknown, .cve-unknown {
  713. background: #ffd870;
  714. }
  715. .cve_ignored, .version-error {
  716. background: #ccc;
  717. }
  718. </style>
  719. <title>Statistics of Buildroot packages</title>
  720. </head>
  721. <body>
  722. <a href=\"#results\">Results</a><br/>
  723. <p id=\"sortable_hint\"></p>
  724. """ # noqa - tabs and spaces
  725. html_footer = """
  726. <script>
  727. if (typeof sortGrid === "function") {
  728. document.getElementById("sortable_hint").innerHTML =
  729. "hint: the table can be sorted by clicking the column headers"
  730. }
  731. </script>
  732. </body>
  733. </html>
  734. """
  735. def infra_str(infra_list):
  736. if not infra_list:
  737. return "Unknown"
  738. elif len(infra_list) == 1:
  739. return "<b>%s</b><br/>%s" % (infra_list[0][1], infra_list[0][0])
  740. elif infra_list[0][1] == infra_list[1][1]:
  741. return "<b>%s</b><br/>%s + %s" % \
  742. (infra_list[0][1], infra_list[0][0], infra_list[1][0])
  743. else:
  744. return "<b>%s</b> (%s)<br/><b>%s</b> (%s)" % \
  745. (infra_list[0][1], infra_list[0][0],
  746. infra_list[1][1], infra_list[1][0])
  747. def boolean_str(b):
  748. if b:
  749. return "Yes"
  750. else:
  751. return "No"
  752. def dump_html_pkg(f, pkg):
  753. f.write(f'<div id=\"package_{pkg.name}\" \
  754. class=\"package data {pkg.name}\">{pkg.path}</div>\n')
  755. # Patch count
  756. data_field_id = f'patch_count_{pkg.name}'
  757. div_class = ["centered patch_count data"]
  758. div_class.append(pkg.name)
  759. if pkg.patch_count == 0:
  760. div_class.append("nopatches")
  761. elif pkg.patch_count < 5:
  762. div_class.append("somepatches")
  763. else:
  764. div_class.append("lotsofpatches")
  765. f.write(f' <div id=\"{data_field_id}\" class=\"{" ".join(div_class)} \
  766. \">{str(pkg.patch_count)}</div>\n')
  767. # Infrastructure
  768. data_field_id = f'infrastructure_{pkg.name}'
  769. infra = infra_str(pkg.infras)
  770. div_class = ["centered infrastructure data"]
  771. div_class.append(pkg.name)
  772. if infra == "Unknown":
  773. div_class.append("wrong")
  774. else:
  775. div_class.append("correct")
  776. f.write(f' <div id=\"{data_field_id}\" class=\"{" ".join(div_class)} \
  777. \">{infra_str(pkg.infras)}</div>\n')
  778. # License
  779. data_field_id = f'license_{pkg.name}'
  780. div_class = ["centered license data"]
  781. div_class.append(pkg.name)
  782. if pkg.is_status_ok('license'):
  783. div_class.append("correct")
  784. else:
  785. div_class.append("wrong")
  786. f.write(f' <div id=\"{data_field_id}\" class=\"{" ".join(div_class)} \
  787. \">{boolean_str(pkg.is_status_ok("license"))}</div>\n')
  788. # License files
  789. data_field_id = f'license_files_{pkg.name}'
  790. div_class = ["centered license_files data"]
  791. div_class.append(pkg.name)
  792. if pkg.is_status_ok('license-files'):
  793. div_class.append("correct")
  794. else:
  795. div_class.append("wrong")
  796. f.write(f' <div id=\"{data_field_id}\" class=\"{" ".join(div_class)} \
  797. \">{boolean_str(pkg.is_status_ok("license-files"))}</div>\n')
  798. # Hash
  799. data_field_id = f'hash_file_{pkg.name}'
  800. div_class = ["centered hash_file data"]
  801. div_class.append(pkg.name)
  802. if pkg.is_status_ok('hash'):
  803. div_class.append("correct")
  804. else:
  805. div_class.append("wrong")
  806. f.write(f' <div id=\"{data_field_id}\" class=\"{" ".join(div_class)} \
  807. \">{boolean_str(pkg.is_status_ok("hash"))}</div>\n')
  808. # Current version
  809. data_field_id = f'current_version_{pkg.name}'
  810. if len(pkg.current_version) > 20:
  811. current_version = pkg.current_version[:20] + "..."
  812. else:
  813. current_version = pkg.current_version
  814. f.write(f' <div id=\"{data_field_id}\" \
  815. class=\"centered current_version data {pkg.name}\">{current_version}</div>\n')
  816. # Latest version
  817. data_field_id = f'latest_version_{pkg.name}'
  818. div_class.append(pkg.name)
  819. div_class.append("latest_version data")
  820. if pkg.latest_version['status'] == RM_API_STATUS_ERROR:
  821. div_class.append("version-error")
  822. if pkg.latest_version['version'] is None:
  823. div_class.append("version-unknown")
  824. elif pkg.latest_version['version'] != pkg.current_version:
  825. div_class.append("version-needs-update")
  826. else:
  827. div_class.append("version-good")
  828. if pkg.latest_version['status'] == RM_API_STATUS_ERROR:
  829. latest_version_text = "<b>Error</b>"
  830. elif pkg.latest_version['status'] == RM_API_STATUS_NOT_FOUND:
  831. latest_version_text = "<b>Not found</b>"
  832. else:
  833. if pkg.latest_version['version'] is None:
  834. latest_version_text = "<b>Found, but no version</b>"
  835. else:
  836. latest_version_text = "<a href=\"https://release-monitoring.org/project/%s\"><b>%s</b></a>" % \
  837. (pkg.latest_version['id'], str(pkg.latest_version['version']))
  838. latest_version_text += "<br/>"
  839. if pkg.latest_version['status'] == RM_API_STATUS_FOUND_BY_DISTRO:
  840. latest_version_text += "found by <a href=\"https://release-monitoring.org/distro/Buildroot/\">distro</a>"
  841. else:
  842. latest_version_text += "found by guess"
  843. f.write(f' <div id=\"{data_field_id}\" class=\"{" ".join(div_class)}\">{latest_version_text}</div>\n')
  844. # Warnings
  845. data_field_id = f'warnings_{pkg.name}'
  846. div_class = ["centered warnings data"]
  847. div_class.append(pkg.name)
  848. if pkg.warnings == 0:
  849. div_class.append("correct")
  850. else:
  851. div_class.append("wrong")
  852. f.write(f' <div id=\"{data_field_id}\" class=\"{" ".join(div_class)}\">{pkg.warnings}</div>\n')
  853. # URL status
  854. data_field_id = f'upstream_url_{pkg.name}'
  855. div_class = ["centered upstream_url data"]
  856. div_class.append(pkg.name)
  857. url_str = pkg.status['url'][1]
  858. if pkg.status['url'][0] in ("error", "warning"):
  859. div_class.append("missing_url")
  860. if pkg.status['url'][0] == "error":
  861. div_class.append("invalid_url")
  862. url_str = "<a href=\"%s\">%s</a>" % (pkg.url, pkg.status['url'][1])
  863. else:
  864. div_class.append("good_url")
  865. url_str = "<a href=\"%s\">Link</a>" % pkg.url
  866. f.write(f' <div id=\"{data_field_id}\" class=\"{" ".join(div_class)}\">{url_str}</div>\n')
  867. # CVEs
  868. data_field_id = f'cves_{pkg.name}'
  869. div_class = ["centered cves data"]
  870. div_class.append(pkg.name)
  871. if pkg.is_status_ok("cve"):
  872. div_class.append("cve-ok")
  873. elif pkg.is_status_error("cve"):
  874. div_class.append("cve-nok")
  875. elif pkg.is_status_na("cve") and not pkg.is_actual_package:
  876. div_class.append("cve-ok")
  877. else:
  878. div_class.append("cve-unknown")
  879. f.write(f' <div id=\"{data_field_id}\" class=\"{" ".join(div_class)}\">\n')
  880. if pkg.is_status_error("cve"):
  881. for cve in pkg.cves:
  882. f.write(" <a href=\"https://security-tracker.debian.org/tracker/%s\">%s</a><br/>\n" % (cve, cve))
  883. for cve in pkg.unsure_cves:
  884. f.write(" <a href=\"https://security-tracker.debian.org/tracker/%s\">%s <i>(unsure)</i></a><br/>\n" % (cve, cve))
  885. elif pkg.is_status_na("cve"):
  886. f.write(" %s" % pkg.status['cve'][1])
  887. else:
  888. f.write(" N/A\n")
  889. f.write(" </div>\n")
  890. # CVEs Ignored
  891. data_field_id = f'ignored_cves_{pkg.name}'
  892. div_class = ["centered data ignored_cves"]
  893. div_class.append(pkg.name)
  894. if pkg.ignored_cves:
  895. div_class.append("cve_ignored")
  896. f.write(f' <div id=\"{data_field_id}\" class=\"{" ".join(div_class)}\">\n')
  897. for ignored_cve in pkg.ignored_cves:
  898. f.write(" <a href=\"https://security-tracker.debian.org/tracker/%s\">%s</a><br/>\n" % (ignored_cve, ignored_cve))
  899. f.write(" </div>\n")
  900. # CPE ID
  901. data_field_id = f'cpe_id_{pkg.name}'
  902. div_class = ["left cpe_id data"]
  903. div_class.append(pkg.name)
  904. if pkg.is_status_ok("cpe"):
  905. div_class.append("cpe-ok")
  906. elif pkg.is_status_error("cpe"):
  907. div_class.append("cpe-nok")
  908. elif pkg.is_status_na("cpe") and not pkg.is_actual_package:
  909. div_class.append("cpe-ok")
  910. else:
  911. div_class.append("cpe-unknown")
  912. f.write(f' <div id=\"{data_field_id}\" class=\"{" ".join(div_class)}\">\n')
  913. if pkg.cpeid:
  914. f.write(" <code>%s</code>\n" % pkg.cpeid)
  915. if not pkg.is_status_ok("cpe"):
  916. if pkg.is_actual_package and pkg.current_version:
  917. if pkg.cpeid:
  918. f.write(" <br/>%s <a href=\"https://nvd.nist.gov/products/cpe/search/results?namingFormat=2.3&keyword=%s\">(Search)</a>\n" % # noqa: E501
  919. (pkg.status['cpe'][1], ":".join(pkg.cpeid.split(":")[0:5])))
  920. else:
  921. f.write(" %s <a href=\"https://nvd.nist.gov/products/cpe/search/results?namingFormat=2.3&keyword=%s\">(Search)</a>\n" % # noqa: E501
  922. (pkg.status['cpe'][1], pkg.name))
  923. else:
  924. f.write(" %s\n" % pkg.status['cpe'][1])
  925. f.write(" </div>\n")
  926. def dump_html_all_pkgs(f, packages):
  927. f.write("""
  928. <div id=\"package-grid\">
  929. <div style="grid-column: 1;" onclick="sortGrid(this.id)" id=\"package\"
  930. class=\"package data label\"><span>Package</span><span></span></div>
  931. <div style="grid-column: 2;" onclick="sortGrid(this.id)" id=\"patch_count\"
  932. class=\"centered patch_count data label\"><span>Patch count</span><span></span></div>
  933. <div style="grid-column: 3;" onclick="sortGrid(this.id)" id=\"infrastructure\"
  934. class=\"centered infrastructure data label\">Infrastructure<span></span></div>
  935. <div style="grid-column: 4;" onclick="sortGrid(this.id)" id=\"license\"
  936. class=\"centered license data label\"><span>License</span><span></span></div>
  937. <div style="grid-column: 5;" onclick="sortGrid(this.id)" id=\"license_files\"
  938. class=\"centered license_files data label\"><span>License files</span><span></span></div>
  939. <div style="grid-column: 6;" onclick="sortGrid(this.id)" id=\"hash_file\"
  940. class=\"centered hash_file data label\"><span>Hash file</span><span></span></div>
  941. <div style="grid-column: 7;" onclick="sortGrid(this.id)" id=\"current_version\"
  942. class=\"centered current_version data label\"><span>Current version</span><span></span></div>
  943. <div style="grid-column: 8;" onclick="sortGrid(this.id)" id=\"latest_version\"
  944. class=\"centered latest_version data label\"><span>Latest version</span><span></span></div>
  945. <div style="grid-column: 9;" onclick="sortGrid(this.id)" id=\"warnings\"
  946. class=\"centered warnings data label\"><span>Warnings</span><span></span></div>
  947. <div style="grid-column: 10;" onclick="sortGrid(this.id)" id=\"upstream_url\"
  948. class=\"centered upstream_url data label\"><span>Upstream URL</span><span></span></div>
  949. <div style="grid-column: 11;" onclick="sortGrid(this.id)" id=\"cves\"
  950. class=\"centered cves data label\"><span>CVEs</span><span></span></div>
  951. <div style="grid-column: 12;" onclick="sortGrid(this.id)" id=\"ignored_cves\"
  952. class=\"centered ignored_cves data label\"><span>CVEs Ignored</span><span></span></div>
  953. <div style="grid-column: 13;" onclick="sortGrid(this.id)" id=\"cpe_id\"
  954. class=\"centered cpe_id data label\"><span>CPE ID</span><span></span></div>
  955. """)
  956. for pkg in sorted(packages):
  957. dump_html_pkg(f, pkg)
  958. f.write("</div>")
  959. def dump_html_stats(f, stats):
  960. f.write("<a id=\"results\"></a>\n")
  961. f.write("<div class=\"data\" id=\"results-grid\">\n")
  962. infras = [infra[6:] for infra in stats.keys() if infra.startswith("infra-")]
  963. for infra in infras:
  964. f.write(" <div class=\"data\">Packages using the <i>%s</i> infrastructure</div><div class=\"data\">%s</div>\n" %
  965. (infra, stats["infra-%s" % infra]))
  966. f.write(" <div class=\"data\">Packages having license information</div><div class=\"data\">%s</div>\n" %
  967. stats["license"])
  968. f.write(" <div class=\"data\">Packages not having license information</div><div class=\"data\">%s</div>\n" %
  969. stats["no-license"])
  970. f.write(" <div class=\"data\">Packages having license files information</div><div class=\"data\">%s</div>\n" %
  971. stats["license-files"])
  972. f.write(" <div class=\"data\">Packages not having license files information</div><div class=\"data\">%s</div>\n" %
  973. stats["no-license-files"])
  974. f.write(" <div class=\"data\">Packages having a hash file</div><div class=\"data\">%s</div>\n" %
  975. stats["hash"])
  976. f.write(" <div class=\"data\">Packages not having a hash file</div><div class=\"data\">%s</div>\n" %
  977. stats["no-hash"])
  978. f.write(" <div class=\"data\">Total number of patches</div><div class=\"data\">%s</div>\n" %
  979. stats["patches"])
  980. f.write("<div class=\"data\">Packages having a mapping on <i>release-monitoring.org</i></div><div class=\"data\">%s</div>\n" %
  981. stats["rmo-mapping"])
  982. f.write("<div class=\"data\">Packages lacking a mapping on <i>release-monitoring.org</i></div><div class=\"data\">%s</div>\n" %
  983. stats["rmo-no-mapping"])
  984. f.write("<div class=\"data\">Packages that are up-to-date</div><div class=\"data\">%s</div>\n" %
  985. stats["version-uptodate"])
  986. f.write("<div class=\"data\">Packages that are not up-to-date</div><div class=\"data\">%s</div>\n" %
  987. stats["version-not-uptodate"])
  988. f.write("<div class=\"data\">Packages with no known upstream version</div><div class=\"data\">%s</div>\n" %
  989. stats["version-unknown"])
  990. f.write("<div class=\"data\">Packages affected by CVEs</div><div class=\"data\">%s</div>\n" %
  991. stats["pkg-cves"])
  992. f.write("<div class=\"data\">Total number of CVEs affecting all packages</div><div class=\"data\">%s</div>\n" %
  993. stats["total-cves"])
  994. f.write("<div class=\"data\">Packages affected by unsure CVEs</div><div class=\"data\">%s</div>\n" %
  995. stats["pkg-unsure-cves"])
  996. f.write("<div class=\"data\">Total number of unsure CVEs affecting all packages</div><div class=\"data\">%s</div>\n" %
  997. stats["total-unsure-cves"])
  998. f.write("<div class=\"data\">Packages with CPE ID</div><div class=\"data\">%s</div>\n" %
  999. stats["cpe-id"])
  1000. f.write("<div class=\"data\">Packages without CPE ID</div><div class=\"data\">%s</div>\n" %
  1001. stats["no-cpe-id"])
  1002. f.write("</div>\n")
  1003. def dump_html_gen_info(f, date, commit):
  1004. # Updated on Mon Feb 19 08:12:08 CET 2018, Git commit aa77030b8f5e41f1c53eb1c1ad664b8c814ba032
  1005. f.write("<p><i>Updated on %s, git commit %s</i></p>\n" % (str(date), commit))
  1006. def dump_html(packages, stats, date, commit, output):
  1007. with open(output, 'w') as f:
  1008. f.write(html_header)
  1009. dump_html_all_pkgs(f, packages)
  1010. dump_html_stats(f, stats)
  1011. dump_html_gen_info(f, date, commit)
  1012. f.write(html_footer)
  1013. def dump_json(packages, defconfigs, stats, date, commit, output):
  1014. # Format packages as a dictionnary instead of a list
  1015. # Exclude local field that does not contains real date
  1016. excluded_fields = ['url_worker', 'name']
  1017. pkgs = {
  1018. pkg.name: {
  1019. k: v
  1020. for k, v in pkg.__dict__.items()
  1021. if k not in excluded_fields
  1022. } for pkg in packages
  1023. }
  1024. defconfigs = {
  1025. d.name: {
  1026. k: v
  1027. for k, v in d.__dict__.items()
  1028. } for d in defconfigs
  1029. }
  1030. # Aggregate infrastructures into a single dict entry
  1031. statistics = {
  1032. k: v
  1033. for k, v in stats.items()
  1034. if not k.startswith('infra-')
  1035. }
  1036. statistics['infra'] = {k[6:]: v for k, v in stats.items() if k.startswith('infra-')}
  1037. # The actual structure to dump, add commit and date to it
  1038. final = {'packages': pkgs,
  1039. 'stats': statistics,
  1040. 'defconfigs': defconfigs,
  1041. 'package_status_checks': Package.status_checks,
  1042. 'commit': commit,
  1043. 'date': str(date)}
  1044. with open(output, 'w') as f:
  1045. json.dump(final, f, indent=2, separators=(',', ': '))
  1046. f.write('\n')
  1047. def resolvepath(path):
  1048. return os.path.abspath(os.path.expanduser(path))
  1049. def list_str(values):
  1050. return values.split(',')
  1051. def parse_args():
  1052. parser = argparse.ArgumentParser()
  1053. output = parser.add_argument_group('output', 'Output file(s)')
  1054. output.add_argument('--html', dest='html', type=resolvepath,
  1055. help='HTML output file')
  1056. output.add_argument('--json', dest='json', type=resolvepath,
  1057. help='JSON output file')
  1058. packages = parser.add_mutually_exclusive_group()
  1059. packages.add_argument('-c', dest='configpackages', action='store_true',
  1060. help='Apply to packages enabled in current configuration')
  1061. packages.add_argument('-n', dest='npackages', type=int, action='store',
  1062. help='Number of packages')
  1063. packages.add_argument('-p', dest='packages', action='store',
  1064. help='List of packages (comma separated)')
  1065. parser.add_argument('--nvd-path', dest='nvd_path',
  1066. help='Path to the local NVD database', type=resolvepath)
  1067. parser.add_argument('--disable', type=list_str,
  1068. help='Features to disable, comma-separated (cve, upstream, url, cpe, warning)',
  1069. default=[])
  1070. args = parser.parse_args()
  1071. if not args.html and not args.json:
  1072. parser.error('at least one of --html or --json (or both) is required')
  1073. return args
  1074. def __main__():
  1075. global cvecheck
  1076. args = parse_args()
  1077. if args.nvd_path:
  1078. import cve as cvecheck
  1079. show_info_js = None
  1080. if args.packages:
  1081. package_list = args.packages.split(",")
  1082. elif args.configpackages:
  1083. show_info_js = get_show_info_js()
  1084. package_list = set([v["name"] for v in show_info_js.values() if 'name' in v])
  1085. else:
  1086. package_list = None
  1087. date = datetime.datetime.utcnow()
  1088. commit = subprocess.check_output(['git', '-C', brpath,
  1089. 'rev-parse',
  1090. 'HEAD']).splitlines()[0].decode()
  1091. print("Build package list ...")
  1092. packages = get_pkglist(args.npackages, package_list)
  1093. print("Getting developers ...")
  1094. developers = parse_developers()
  1095. print("Build defconfig list ...")
  1096. defconfigs = get_defconfig_list()
  1097. for d in defconfigs:
  1098. d.set_developers(developers)
  1099. print("Getting package make info ...")
  1100. package_init_make_info()
  1101. print("Getting package details ...")
  1102. for pkg in packages:
  1103. pkg.set_infra(show_info_js)
  1104. pkg.set_license()
  1105. pkg.set_hash_info()
  1106. pkg.set_patch_count()
  1107. if "warnings" not in args.disable:
  1108. pkg.set_check_package_warnings()
  1109. pkg.set_current_version()
  1110. pkg.set_cpeid()
  1111. pkg.set_url()
  1112. pkg.set_ignored_cves()
  1113. pkg.set_developers(developers)
  1114. if "url" not in args.disable:
  1115. print("Checking URL status")
  1116. loop = asyncio.get_event_loop()
  1117. loop.run_until_complete(check_package_urls(packages))
  1118. if "upstream" not in args.disable:
  1119. print("Getting latest versions ...")
  1120. loop = asyncio.get_event_loop()
  1121. loop.run_until_complete(check_package_latest_version(packages))
  1122. if "cve" not in args.disable and args.nvd_path:
  1123. print("Checking packages CVEs")
  1124. check_package_cves(args.nvd_path, packages)
  1125. if "cpe" not in args.disable and args.nvd_path:
  1126. print("Checking packages CPEs")
  1127. check_package_cpes(args.nvd_path, packages)
  1128. print("Calculate stats")
  1129. stats = calculate_stats(packages)
  1130. if args.html:
  1131. print("Write HTML")
  1132. dump_html(packages, stats, date, commit, args.html)
  1133. if args.json:
  1134. print("Write JSON")
  1135. dump_json(packages, defconfigs, stats, date, commit, args.json)
  1136. __main__()