pkg-stats 50 KB

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