pkg-stats 50 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364
  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. INFRA_RE = re.compile(r"\$\(eval \$\(([a-z-]*)-package\)\)")
  37. URL_RE = re.compile(r"\s*https?://\S*\s*$")
  38. CPEDB_URL = "https://static.nvd.nist.gov/feeds/xml/cpe/dictionary/official-cpe-dictionary_v2.3.xml.gz"
  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-processes 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 dictionary")
  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. 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/barebox/barebox.mk",
  297. "boot/common.mk",
  298. "linux/linux-ext-.*.mk",
  299. "package/fftw/fftw.mk",
  300. "package/freescale-imx/freescale-imx.mk",
  301. "package/gcc/gcc.mk",
  302. "package/gstreamer/gstreamer.mk",
  303. "package/gstreamer1/gstreamer1.mk",
  304. "package/gtk2-themes/gtk2-themes.mk",
  305. "package/kf5/kf5.mk",
  306. "package/llvm-project/llvm-project.mk",
  307. "package/matchbox/matchbox.mk",
  308. "package/opengl/opengl.mk",
  309. "package/qt5/qt5.mk",
  310. "package/qt6/qt6.mk",
  311. "package/x11r7/x11r7.mk",
  312. "package/doc-asciidoc.mk",
  313. "package/pkg-.*.mk",
  314. "toolchain/toolchain-external/pkg-toolchain-external.mk",
  315. "toolchain/toolchain-external/toolchain-external.mk",
  316. "toolchain/toolchain.mk",
  317. "toolchain/helpers.mk",
  318. "toolchain/toolchain-wrapper.mk"]
  319. packages = list()
  320. count = 0
  321. for root, dirs, files in os.walk(brpath):
  322. root = os.path.relpath(root, brpath)
  323. rootdir = root.split("/")
  324. if len(rootdir) < 1:
  325. continue
  326. if rootdir[0] not in WALK_USEFUL_SUBDIRS:
  327. continue
  328. for f in files:
  329. if not f.endswith(".mk"):
  330. continue
  331. # Strip ending ".mk"
  332. pkgname = f[:-3]
  333. if package_list and pkgname not in package_list:
  334. continue
  335. pkgpath = os.path.join(root, f)
  336. skip = False
  337. for exclude in WALK_EXCLUDES:
  338. if re.match(exclude, pkgpath):
  339. skip = True
  340. continue
  341. if skip:
  342. continue
  343. p = Package(pkgname, pkgpath)
  344. packages.append(p)
  345. count += 1
  346. if npackages and count == npackages:
  347. return packages
  348. return packages
  349. def get_show_info_js():
  350. cmd = ["make", "--no-print-directory", "show-info"]
  351. return json.loads(subprocess.check_output(cmd))
  352. def package_init_make_info():
  353. # Fetch all variables at once
  354. variables = subprocess.check_output(["make", "--no-print-directory", "-s",
  355. "BR2_HAVE_DOT_CONFIG=y", "printvars",
  356. "VARS=%_LICENSE %_LICENSE_FILES %_VERSION %_IGNORE_CVES %_CPE_ID"])
  357. variable_list = variables.decode().splitlines()
  358. # We process first the host package VERSION, and then the target
  359. # package VERSION. This means that if a package exists in both
  360. # target and host variants, with different values (eg. version
  361. # numbers (unlikely)), we'll report the target one.
  362. variable_list = [x[5:] for x in variable_list if x.startswith("HOST_")] + \
  363. [x for x in variable_list if not x.startswith("HOST_")]
  364. for item in variable_list:
  365. # Get variable name and value
  366. pkgvar, value = item.split("=", maxsplit=1)
  367. # Strip the suffix according to the variable
  368. if pkgvar.endswith("_LICENSE"):
  369. # If value is "unknown", no license details available
  370. if value == "unknown":
  371. continue
  372. pkgvar = pkgvar[:-8]
  373. Package.all_licenses[pkgvar] = value
  374. elif pkgvar.endswith("_LICENSE_FILES"):
  375. if pkgvar.endswith("_MANIFEST_LICENSE_FILES"):
  376. continue
  377. pkgvar = pkgvar[:-14]
  378. Package.all_license_files.append(pkgvar)
  379. elif pkgvar.endswith("_VERSION"):
  380. if pkgvar.endswith("_DL_VERSION"):
  381. continue
  382. pkgvar = pkgvar[:-8]
  383. Package.all_versions[pkgvar] = value
  384. elif pkgvar.endswith("_IGNORE_CVES"):
  385. pkgvar = pkgvar[:-12]
  386. Package.all_ignored_cves[pkgvar] = value.split()
  387. elif pkgvar.endswith("_CPE_ID"):
  388. pkgvar = pkgvar[:-7]
  389. Package.all_cpeids[pkgvar] = value
  390. check_url_count = 0
  391. async def check_url_status(session, pkg, npkgs, retry=True):
  392. global check_url_count
  393. try:
  394. async with session.get(pkg.url) as resp:
  395. if resp.status >= 400:
  396. pkg.status['url'] = ("error", "invalid {}".format(resp.status))
  397. check_url_count += 1
  398. print("[%04d/%04d] %s" % (check_url_count, npkgs, pkg.name))
  399. return
  400. except (aiohttp.ClientError, asyncio.TimeoutError):
  401. if retry:
  402. return await check_url_status(session, pkg, npkgs, retry=False)
  403. else:
  404. pkg.status['url'] = ("error", "invalid (err)")
  405. check_url_count += 1
  406. print("[%04d/%04d] %s" % (check_url_count, npkgs, pkg.name))
  407. return
  408. pkg.status['url'] = ("ok", "valid")
  409. check_url_count += 1
  410. print("[%04d/%04d] %s" % (check_url_count, npkgs, pkg.name))
  411. async def check_package_urls(packages):
  412. tasks = []
  413. connector = aiohttp.TCPConnector(limit_per_host=5)
  414. async with aiohttp.ClientSession(connector=connector, trust_env=True,
  415. timeout=aiohttp.ClientTimeout(total=15)) as sess:
  416. packages = [p for p in packages if p.status['url'][0] == 'ok']
  417. for pkg in packages:
  418. tasks.append(asyncio.ensure_future(check_url_status(sess, pkg, len(packages))))
  419. await asyncio.wait(tasks)
  420. def check_package_latest_version_set_status(pkg, status, version, identifier):
  421. pkg.latest_version = {
  422. "status": status,
  423. "version": version,
  424. "id": identifier,
  425. }
  426. if pkg.latest_version['status'] == RM_API_STATUS_ERROR:
  427. pkg.status['version'] = ('warning', "Release Monitoring API error")
  428. elif pkg.latest_version['status'] == RM_API_STATUS_NOT_FOUND:
  429. pkg.status['version'] = ('warning', "Package not found on Release Monitoring")
  430. if pkg.latest_version['version'] is None:
  431. pkg.status['version'] = ('warning', "No upstream version available on Release Monitoring")
  432. elif pkg.latest_version['version'] != pkg.current_version:
  433. pkg.status['version'] = ('error', "The newer version {} is available upstream".format(pkg.latest_version['version']))
  434. else:
  435. pkg.status['version'] = ('ok', 'up-to-date')
  436. async def check_package_get_latest_version_by_distro(session, pkg, retry=True):
  437. url = "https://release-monitoring.org/api/project/Buildroot/%s" % pkg.name
  438. try:
  439. async with session.get(url) as resp:
  440. if resp.status != 200:
  441. return False
  442. data = await resp.json()
  443. if 'stable_versions' in data and data['stable_versions']:
  444. version = data['stable_versions'][0]
  445. elif 'version' in data:
  446. version = data['version']
  447. else:
  448. version = None
  449. check_package_latest_version_set_status(pkg,
  450. RM_API_STATUS_FOUND_BY_DISTRO,
  451. version,
  452. data['id'])
  453. return True
  454. except (aiohttp.ClientError, asyncio.TimeoutError):
  455. if retry:
  456. return await check_package_get_latest_version_by_distro(session, pkg, retry=False)
  457. else:
  458. return False
  459. async def check_package_get_latest_version_by_guess(session, pkg, retry=True):
  460. url = "https://release-monitoring.org/api/projects/?pattern=%s" % pkg.name
  461. try:
  462. async with session.get(url) as resp:
  463. if resp.status != 200:
  464. return False
  465. data = await resp.json()
  466. # filter projects that have the right name and a version defined
  467. projects = [p for p in data['projects'] if p['name'] == pkg.name and 'stable_versions' in p]
  468. projects.sort(key=lambda x: x['id'])
  469. if len(projects) == 0:
  470. return False
  471. if len(projects[0]['stable_versions']) == 0:
  472. return False
  473. check_package_latest_version_set_status(pkg,
  474. RM_API_STATUS_FOUND_BY_PATTERN,
  475. projects[0]['stable_versions'][0],
  476. projects[0]['id'])
  477. return True
  478. except (aiohttp.ClientError, asyncio.TimeoutError):
  479. if retry:
  480. return await check_package_get_latest_version_by_guess(session, pkg, retry=False)
  481. else:
  482. return False
  483. check_latest_count = 0
  484. async def check_package_latest_version_get(session, pkg, npkgs):
  485. global check_latest_count
  486. if await check_package_get_latest_version_by_distro(session, pkg):
  487. check_latest_count += 1
  488. print("[%04d/%04d] %s" % (check_latest_count, npkgs, pkg.name))
  489. return
  490. if await check_package_get_latest_version_by_guess(session, pkg):
  491. check_latest_count += 1
  492. print("[%04d/%04d] %s" % (check_latest_count, npkgs, pkg.name))
  493. return
  494. check_package_latest_version_set_status(pkg,
  495. RM_API_STATUS_NOT_FOUND,
  496. None, None)
  497. check_latest_count += 1
  498. print("[%04d/%04d] %s" % (check_latest_count, npkgs, pkg.name))
  499. async def check_package_latest_version(packages):
  500. """
  501. Fills in the .latest_version field of all Package objects
  502. This field is a dict and has the following keys:
  503. - status: one of RM_API_STATUS_ERROR,
  504. RM_API_STATUS_FOUND_BY_DISTRO, RM_API_STATUS_FOUND_BY_PATTERN,
  505. RM_API_STATUS_NOT_FOUND
  506. - version: string containing the latest version known by
  507. release-monitoring.org for this package
  508. - id: string containing the id of the project corresponding to this
  509. package, as known by release-monitoring.org
  510. """
  511. for pkg in [p for p in packages if not p.is_actual_package]:
  512. pkg.status['version'] = ("na", "no valid package infra")
  513. tasks = []
  514. connector = aiohttp.TCPConnector(limit_per_host=5)
  515. async with aiohttp.ClientSession(connector=connector, trust_env=True) as sess:
  516. packages = [p for p in packages if p.is_actual_package]
  517. for pkg in packages:
  518. tasks.append(asyncio.ensure_future(check_package_latest_version_get(sess, pkg, len(packages))))
  519. await asyncio.wait(tasks)
  520. def check_package_cve_affects(cve, cpe_product_pkgs):
  521. for product in cve.affected_products:
  522. if product not in cpe_product_pkgs:
  523. continue
  524. for pkg in cpe_product_pkgs[product]:
  525. cve_status = cve.affects(pkg.name, pkg.current_version, pkg.ignored_cves, pkg.cpeid)
  526. if cve_status == cve.CVE_AFFECTS:
  527. pkg.cves.append(cve.identifier)
  528. elif cve_status == cve.CVE_UNKNOWN:
  529. pkg.unsure_cves.append(cve.identifier)
  530. def check_package_cves(nvd_path, packages):
  531. if not os.path.isdir(nvd_path):
  532. os.makedirs(nvd_path)
  533. cpe_product_pkgs = defaultdict(list)
  534. for pkg in packages:
  535. if not pkg.is_actual_package:
  536. pkg.status['cve'] = ("na", "N/A")
  537. continue
  538. if not pkg.current_version:
  539. pkg.status['cve'] = ("na", "no version information available")
  540. continue
  541. if pkg.cpeid:
  542. cpe_product = cvecheck.cpe_product(pkg.cpeid)
  543. cpe_product_pkgs[cpe_product].append(pkg)
  544. else:
  545. cpe_product_pkgs[pkg.name].append(pkg)
  546. for cve in cvecheck.CVE.read_nvd_dir(nvd_path):
  547. check_package_cve_affects(cve, cpe_product_pkgs)
  548. for pkg in packages:
  549. if 'cve' not in pkg.status:
  550. if pkg.cves or pkg.unsure_cves:
  551. pkg.status['cve'] = ("error", "affected by CVEs")
  552. else:
  553. pkg.status['cve'] = ("ok", "not affected by CVEs")
  554. def check_package_cpes(nvd_path, packages):
  555. class CpeXmlParser:
  556. cpes = []
  557. def start(self, tag, attrib):
  558. if tag == "{http://scap.nist.gov/schema/cpe-extension/2.3}cpe23-item":
  559. self.cpes.append(attrib['name'])
  560. def close(self):
  561. return self.cpes
  562. print("CPE: Setting up NIST dictionary")
  563. if not os.path.exists(os.path.join(nvd_path, "cpe")):
  564. os.makedirs(os.path.join(nvd_path, "cpe"))
  565. cpe_dict_local = os.path.join(nvd_path, "cpe", os.path.basename(CPEDB_URL))
  566. if not os.path.exists(cpe_dict_local) or os.stat(cpe_dict_local).st_mtime < time.time() - 86400:
  567. print("CPE: Fetching xml manifest from [" + CPEDB_URL + "]")
  568. cpe_dict = requests.get(CPEDB_URL)
  569. open(cpe_dict_local, "wb").write(cpe_dict.content)
  570. print("CPE: Unzipping xml manifest...")
  571. nist_cpe_file = gzip.GzipFile(fileobj=open(cpe_dict_local, 'rb'))
  572. parser = xml.etree.ElementTree.XMLParser(target=CpeXmlParser())
  573. while True:
  574. c = nist_cpe_file.read(1024*1024)
  575. if not c:
  576. break
  577. parser.feed(c)
  578. cpes = parser.close()
  579. for p in packages:
  580. if not p.cpeid:
  581. continue
  582. if p.cpeid in cpes:
  583. p.status['cpe'] = ("ok", "verified CPE identifier")
  584. else:
  585. p.status['cpe'] = ("error", "CPE version unknown in CPE database")
  586. def calculate_stats(packages):
  587. stats = defaultdict(int)
  588. stats['packages'] = len(packages)
  589. for pkg in packages:
  590. # If packages have multiple infra, take the first one. For the
  591. # vast majority of packages, the target and host infra are the
  592. # same. There are very few packages that use a different infra
  593. # for the host and target variants.
  594. if len(pkg.infras) > 0:
  595. infra = pkg.infras[0][1]
  596. stats["infra-%s" % infra] += 1
  597. else:
  598. stats["infra-unknown"] += 1
  599. if pkg.is_status_ok('license'):
  600. stats["license"] += 1
  601. else:
  602. stats["no-license"] += 1
  603. if pkg.is_status_ok('license-files'):
  604. stats["license-files"] += 1
  605. else:
  606. stats["no-license-files"] += 1
  607. if pkg.is_status_ok('hash'):
  608. stats["hash"] += 1
  609. else:
  610. stats["no-hash"] += 1
  611. if pkg.latest_version['status'] == RM_API_STATUS_FOUND_BY_DISTRO:
  612. stats["rmo-mapping"] += 1
  613. else:
  614. stats["rmo-no-mapping"] += 1
  615. if not pkg.latest_version['version']:
  616. stats["version-unknown"] += 1
  617. elif pkg.latest_version['version'] == pkg.current_version:
  618. stats["version-uptodate"] += 1
  619. else:
  620. stats["version-not-uptodate"] += 1
  621. stats["patches"] += pkg.patch_count
  622. stats["total-cves"] += len(pkg.cves)
  623. stats["total-unsure-cves"] += len(pkg.unsure_cves)
  624. if len(pkg.cves) != 0:
  625. stats["pkg-cves"] += 1
  626. if len(pkg.unsure_cves) != 0:
  627. stats["pkg-unsure-cves"] += 1
  628. if pkg.cpeid:
  629. stats["cpe-id"] += 1
  630. else:
  631. stats["no-cpe-id"] += 1
  632. return stats
  633. html_header = """
  634. <!DOCTYPE html>
  635. <html lang="en">
  636. <head>
  637. <meta charset="UTF-8">
  638. <meta name="viewport" content="width=device-width, initial-scale=1">
  639. <script>
  640. const triangleUp = String.fromCodePoint(32, 9652);
  641. const triangleDown = String.fromCodePoint(32, 9662);
  642. var lastColumnName = false;
  643. const styleElement = document.createElement('style');
  644. document.head.insertAdjacentElement("afterend", styleElement);
  645. const styleSheet = styleElement.sheet;
  646. addedCSSRules = [
  647. ".collapse{ height: 200px; overflow: hidden scroll;}",
  648. ".see-more{ display: block;}",
  649. ".label:hover,.see-more:hover { cursor: pointer; background: #d2ffc4;}"
  650. ];
  651. addedCSSRules.forEach(rule => styleSheet.insertRule(rule));
  652. function sortGrid(sortLabel){
  653. let i = 0;
  654. let pkgSortArray = [], sortedPkgArray = [], pkgStringSortArray = [], pkgNumSortArray = [];
  655. const columnValues = Array.from(document.getElementsByClassName(sortLabel));
  656. const columnName = document.getElementById(sortLabel);
  657. let lastStyle = document.getElementById("sort-css");
  658. if (lastStyle){
  659. lastStyle.disable = true;
  660. lastStyle.remove();
  661. };
  662. styleElement.id = "sort-css";
  663. document.head.appendChild(styleElement);
  664. const styleSheet = styleElement.sheet;
  665. columnValues.shift();
  666. columnValues.forEach((listing) => {
  667. let sortArr = [];
  668. sortArr[0] = listing.id.replace(sortLabel+"_", "");
  669. if (!listing.innerText){
  670. sortArr[1] = -1;
  671. } else {
  672. sortArr[1] = listing.innerText;
  673. };
  674. pkgSortArray.push(sortArr);
  675. });
  676. pkgSortArray.forEach((listing) => {
  677. if ( isNaN(parseInt(listing[1], 10)) ){
  678. pkgStringSortArray.push(listing);
  679. } else {
  680. listing[1] = parseFloat(listing[1]);
  681. pkgNumSortArray.push(listing);
  682. };
  683. });
  684. let sortedStringPkgArray = pkgStringSortArray.sort((a, b) => {
  685. if (a[1].toUpperCase() < b[1].toUpperCase()) { return -1; };
  686. if (a[1].toUpperCase() > b[1].toUpperCase()) { return 1; };
  687. return 0;
  688. });
  689. let sortedNumPkgArray = pkgNumSortArray.sort((a, b) => a[1] - b[1]);
  690. if (columnName.lastElementChild.innerText == triangleDown) {
  691. columnName.lastElementChild.innerText = triangleUp;
  692. sortedStringPkgArray.reverse();
  693. sortedNumPkgArray.reverse();
  694. sortedPkgArray = sortedNumPkgArray.concat(sortedStringPkgArray);
  695. } else {
  696. columnName.lastElementChild.innerText = triangleDown;
  697. sortedPkgArray = sortedStringPkgArray.concat(sortedNumPkgArray);
  698. };
  699. if (lastColumnName && lastColumnName != columnName){lastColumnName.lastElementChild.innerText = ""};
  700. lastColumnName = columnName;
  701. sortedPkgArray.unshift(["label"]);
  702. sortedPkgArray.forEach((listing) => {
  703. i++;
  704. let rule = "." + listing[0] + " { grid-row: " + i + "; }";
  705. styleSheet.insertRule(rule);
  706. });
  707. addedCSSRules.forEach(rule => styleSheet.insertRule(rule));
  708. };
  709. function expandField(fieldId){
  710. const field = document.getElementById(fieldId);
  711. const fieldText = field.firstElementChild.innerText;
  712. const fieldTotal = fieldText.split(' ')[2];
  713. if (fieldText == "see all " + fieldTotal + triangleDown){
  714. field.firstElementChild.innerText = "see less " + fieldTotal + triangleUp;
  715. field.style.height = "auto";
  716. } else {
  717. field.firstElementChild.innerText = "see all " + fieldTotal + triangleDown;
  718. field.style.height = "200px";
  719. }
  720. };
  721. </script>
  722. <style>
  723. .see-more{
  724. display: none;
  725. }
  726. .label, .see-more {
  727. position: sticky;
  728. top: 1px;
  729. }
  730. .label{
  731. z-index: 1;
  732. background: white;
  733. padding: 10px 2px 10px 2px;
  734. }
  735. #package-grid, #results-grid {
  736. display: grid;
  737. grid-gap: 2px;
  738. grid-template-columns: 1fr repeat(12, min-content);
  739. }
  740. #results-grid {
  741. grid-template-columns: 3fr 1fr;
  742. }
  743. .data {
  744. border: solid 1px gray;
  745. }
  746. .centered {
  747. text-align: center;
  748. }
  749. .current_version {
  750. overflow: scroll;
  751. width: 21ch;
  752. padding: 10px 2px 10px 2px;
  753. }
  754. .correct, .nopatches, .good_url, .version-good, .cpe-ok, .cve-ok {
  755. background: #d2ffc4;
  756. }
  757. .wrong, .lotsofpatches, .invalid_url, .version-needs-update, .cpe-nok, .cve-nok {
  758. background: #ff9a69;
  759. }
  760. .somepatches, .somewarnings, .missing_url, .version-unknown, .cpe-unknown, .cve-unknown {
  761. background: #ffd870;
  762. }
  763. .cve_ignored, .version-error {
  764. background: #ccc;
  765. }
  766. </style>
  767. <title>Statistics of Buildroot packages</title>
  768. </head>
  769. <body>
  770. <a href="#results">Results</a><br/>
  771. """ # noqa - tabs and spaces
  772. html_footer = """
  773. </body>
  774. </html>
  775. """
  776. def infra_str(infra_list):
  777. if not infra_list:
  778. return "Unknown"
  779. elif len(infra_list) == 1:
  780. return "<b>%s</b><br/>%s" % (infra_list[0][1], infra_list[0][0])
  781. elif infra_list[0][1] == infra_list[1][1]:
  782. return "<b>%s</b><br/>%s + %s" % \
  783. (infra_list[0][1], infra_list[0][0], infra_list[1][0])
  784. else:
  785. return "<b>%s</b> (%s)<br/><b>%s</b> (%s)" % \
  786. (infra_list[0][1], infra_list[0][0],
  787. infra_list[1][1], infra_list[1][0])
  788. def boolean_str(b):
  789. if b:
  790. return "Yes"
  791. else:
  792. return "No"
  793. def dump_html_pkg(f, pkg):
  794. pkg_css_class = pkg.path.replace("/", "_")[:-3]
  795. f.write(f'<div id="package__{pkg_css_class}" \
  796. class="package data _{pkg_css_class}">{pkg.path}</div>\n')
  797. # Patch count
  798. data_field_id = f'patch_count__{pkg_css_class}'
  799. div_class = ["centered patch_count data"]
  800. div_class.append(f'_{pkg_css_class}')
  801. if pkg.patch_count == 0:
  802. div_class.append("nopatches")
  803. elif pkg.patch_count < 5:
  804. div_class.append("somepatches")
  805. else:
  806. div_class.append("lotsofpatches")
  807. f.write(f' <div id="{data_field_id}" class="{" ".join(div_class)} \
  808. ">{str(pkg.patch_count)}</div>\n')
  809. # Infrastructure
  810. data_field_id = f'infrastructure__{pkg_css_class}'
  811. infra = infra_str(pkg.infras)
  812. div_class = ["centered infrastructure data"]
  813. div_class.append(f'_{pkg_css_class}')
  814. if infra == "Unknown":
  815. div_class.append("wrong")
  816. else:
  817. div_class.append("correct")
  818. f.write(f' <div id="{data_field_id}" class="{" ".join(div_class)} \
  819. ">{infra_str(pkg.infras)}</div>\n')
  820. # License
  821. data_field_id = f'license__{pkg_css_class}'
  822. div_class = ["centered license data"]
  823. div_class.append(f'_{pkg_css_class}')
  824. if pkg.is_status_ok('license'):
  825. div_class.append("correct")
  826. else:
  827. div_class.append("wrong")
  828. f.write(f' <div id="{data_field_id}" class="{" ".join(div_class)} \
  829. ">{boolean_str(pkg.is_status_ok("license"))}</div>\n')
  830. # License files
  831. data_field_id = f'license_files__{pkg_css_class}'
  832. div_class = ["centered license_files data"]
  833. div_class.append(f'_{pkg_css_class}')
  834. if pkg.is_status_ok('license-files'):
  835. div_class.append("correct")
  836. else:
  837. div_class.append("wrong")
  838. f.write(f' <div id="{data_field_id}" class="{" ".join(div_class)} \
  839. ">{boolean_str(pkg.is_status_ok("license-files"))}</div>\n')
  840. # Hash
  841. data_field_id = f'hash_file__{pkg_css_class}'
  842. div_class = ["centered hash_file data"]
  843. div_class.append(f'_{pkg_css_class}')
  844. if pkg.is_status_ok('hash'):
  845. div_class.append("correct")
  846. else:
  847. div_class.append("wrong")
  848. f.write(f' <div id="{data_field_id}" class="{" ".join(div_class)} \
  849. ">{boolean_str(pkg.is_status_ok("hash"))}</div>\n')
  850. # Current version
  851. data_field_id = f'current_version__{pkg_css_class}'
  852. current_version = pkg.current_version
  853. f.write(f' <div id="{data_field_id}" \
  854. class="centered current_version data _{pkg_css_class}">{current_version}</div>\n')
  855. # Latest version
  856. data_field_id = f'latest_version__{pkg_css_class}'
  857. div_class.append(f'_{pkg_css_class}')
  858. div_class.append("latest_version data")
  859. if pkg.latest_version['status'] == RM_API_STATUS_ERROR:
  860. div_class.append("version-error")
  861. if pkg.latest_version['version'] is None:
  862. div_class.append("version-unknown")
  863. elif pkg.latest_version['version'] != pkg.current_version:
  864. div_class.append("version-needs-update")
  865. else:
  866. div_class.append("version-good")
  867. if pkg.latest_version['status'] == RM_API_STATUS_ERROR:
  868. latest_version_text = "<b>Error</b>"
  869. elif pkg.latest_version['status'] == RM_API_STATUS_NOT_FOUND:
  870. latest_version_text = "<b>Not found</b>"
  871. else:
  872. if pkg.latest_version['version'] is None:
  873. latest_version_text = "<b>Found, but no version</b>"
  874. else:
  875. latest_version_text = f"""<a href="https://release-monitoring.org/project/{pkg.latest_version['id']}">""" \
  876. f"""<b>{str(pkg.latest_version['version'])}</b></a>"""
  877. latest_version_text += "<br/>"
  878. if pkg.latest_version['status'] == RM_API_STATUS_FOUND_BY_DISTRO:
  879. latest_version_text += 'found by <a href="https://release-monitoring.org/distro/Buildroot/">distro</a>'
  880. else:
  881. latest_version_text += "found by guess"
  882. f.write(f' <div id="{data_field_id}" class="{" ".join(div_class)}">{latest_version_text}</div>\n')
  883. # Warnings
  884. data_field_id = f'warnings__{pkg_css_class}'
  885. div_class = ["centered warnings data"]
  886. div_class.append(f'_{pkg_css_class}')
  887. if pkg.warnings == 0:
  888. div_class.append("correct")
  889. elif pkg.warnings < 5:
  890. div_class.append("somewarnings")
  891. else:
  892. div_class.append("wrong")
  893. f.write(f' <div id="{data_field_id}" class="{" ".join(div_class)}">{pkg.warnings}</div>\n')
  894. # URL status
  895. data_field_id = f'upstream_url__{pkg_css_class}'
  896. div_class = ["centered upstream_url data"]
  897. div_class.append(f'_{pkg_css_class}')
  898. url_str = pkg.status['url'][1]
  899. if pkg.status['url'][0] in ("error", "warning"):
  900. div_class.append("missing_url")
  901. if pkg.status['url'][0] == "error":
  902. div_class.append("invalid_url")
  903. url_str = f"""<a href="{pkg.url}">{pkg.status['url'][1]}</a>"""
  904. else:
  905. div_class.append("good_url")
  906. url_str = f'<a href="{pkg.url}">Link</a>'
  907. f.write(f' <div id="{data_field_id}" class="{" ".join(div_class)}">{url_str}</div>\n')
  908. # CVEs
  909. data_field_id = f'cves__{pkg_css_class}'
  910. div_class = ["centered cves data"]
  911. div_class.append(f'_{pkg_css_class}')
  912. if len(pkg.cves) > 10:
  913. div_class.append("collapse")
  914. if pkg.is_status_ok("cve"):
  915. div_class.append("cve-ok")
  916. elif pkg.is_status_error("cve"):
  917. div_class.append("cve-nok")
  918. elif pkg.is_status_na("cve") and not pkg.is_actual_package:
  919. div_class.append("cve-ok")
  920. else:
  921. div_class.append("cve-unknown")
  922. f.write(f' <div id="{data_field_id}" class="{" ".join(div_class)}">\n')
  923. if len(pkg.cves) > 10:
  924. cve_total = len(pkg.cves) + 1
  925. f.write(f' <div onclick="expandField(\'{data_field_id}\')" \
  926. class="see-more centered cve_ignored">see all ({cve_total}) &#9662;</div>\n')
  927. if pkg.is_status_error("cve"):
  928. for cve in pkg.cves:
  929. f.write(f' <a href="https://security-tracker.debian.org/tracker/{cve}">{cve}</a><br/>\n')
  930. for cve in pkg.unsure_cves:
  931. f.write(f' <a href="https://security-tracker.debian.org/tracker/{cve}">{cve} <i>(unsure)</i></a><br/>\n')
  932. elif pkg.is_status_na("cve"):
  933. f.write(f""" {pkg.status['cve'][1]}""")
  934. else:
  935. f.write(" N/A\n")
  936. f.write(" </div>\n")
  937. # CVEs Ignored
  938. data_field_id = f'ignored_cves__{pkg_css_class}'
  939. div_class = ["centered data ignored_cves"]
  940. div_class.append(f'_{pkg_css_class}')
  941. if pkg.ignored_cves:
  942. div_class.append("cve_ignored")
  943. f.write(f' <div id="{data_field_id}" class="{" ".join(div_class)}">\n')
  944. for ignored_cve in pkg.ignored_cves:
  945. f.write(f' <a href="https://security-tracker.debian.org/tracker/{ignored_cve}">{ignored_cve}</a><br/>\n')
  946. f.write(" </div>\n")
  947. # CPE ID
  948. data_field_id = f'cpe_id__{pkg_css_class}'
  949. div_class = ["left cpe_id data"]
  950. div_class.append(f'_{pkg_css_class}')
  951. if pkg.is_status_ok("cpe"):
  952. div_class.append("cpe-ok")
  953. elif pkg.is_status_error("cpe"):
  954. div_class.append("cpe-nok")
  955. elif pkg.is_status_na("cpe") and not pkg.is_actual_package:
  956. div_class.append("cpe-ok")
  957. else:
  958. div_class.append("cpe-unknown")
  959. f.write(f' <div id="{data_field_id}" class="{" ".join(div_class)}">\n')
  960. if pkg.cpeid:
  961. cpeid_begin = ":".join(pkg.cpeid.split(":")[0:4]) + ":"
  962. cpeid_formatted = pkg.cpeid.replace(cpeid_begin, cpeid_begin + "<wbr>")
  963. f.write(" <code>%s</code>\n" % cpeid_formatted)
  964. if not pkg.is_status_ok("cpe"):
  965. if pkg.is_actual_package and pkg.current_version:
  966. if pkg.cpeid:
  967. f.write(f""" <br/>{pkg.status['cpe'][1]} <a href="https://nvd.nist.gov/products/cpe/search/results?"""
  968. f"""namingFormat=2.3&keyword={":".join(pkg.cpeid.split(":")[0:5])}">(Search)</a>\n""")
  969. else:
  970. f.write(f""" {pkg.status['cpe'][1]} <a href="https://nvd.nist.gov/products/cpe/search/results?"""
  971. f"""namingFormat=2.3&keyword={pkg.name}">(Search)</a>\n""")
  972. else:
  973. f.write(" %s\n" % pkg.status['cpe'][1])
  974. f.write(" </div>\n")
  975. def dump_html_all_pkgs(f, packages):
  976. f.write("""
  977. <div id="package-grid">
  978. <div style="grid-column: 1;" onclick="sortGrid(this.id)" id="package"
  979. class="package data label"><span>Package</span><span></span></div>
  980. <div style="grid-column: 2;" onclick="sortGrid(this.id)" id="patch_count"
  981. class="centered patch_count data label"><span>Patch count</span><span></span></div>
  982. <div style="grid-column: 3;" onclick="sortGrid(this.id)" id="infrastructure"
  983. class="centered infrastructure data label">Infrastructure<span></span></div>
  984. <div style="grid-column: 4;" onclick="sortGrid(this.id)" id="license"
  985. class="centered license data label"><span>License</span><span></span></div>
  986. <div style="grid-column: 5;" onclick="sortGrid(this.id)" id="license_files"
  987. class="centered license_files data label"><span>License files</span><span></span></div>
  988. <div style="grid-column: 6;" onclick="sortGrid(this.id)" id="hash_file"
  989. class="centered hash_file data label"><span>Hash file</span><span></span></div>
  990. <div style="grid-column: 7;" onclick="sortGrid(this.id)" id="current_version"
  991. class="centered current_version data label"><span>Current version</span><span></span></div>
  992. <div style="grid-column: 8;" onclick="sortGrid(this.id)" id="latest_version"
  993. class="centered latest_version data label"><span>Latest version</span><span></span></div>
  994. <div style="grid-column: 9;" onclick="sortGrid(this.id)" id="warnings"
  995. class="centered warnings data label"><span>Warnings</span><span></span></div>
  996. <div style="grid-column: 10;" onclick="sortGrid(this.id)" id="upstream_url"
  997. class="centered upstream_url data label"><span>Upstream URL</span><span></span></div>
  998. <div style="grid-column: 11;" onclick="sortGrid(this.id)" id="cves"
  999. class="centered cves data label"><span>CVEs</span><span></span></div>
  1000. <div style="grid-column: 12;" onclick="sortGrid(this.id)" id="ignored_cves"
  1001. class="centered ignored_cves data label"><span>CVEs Ignored</span><span></span></div>
  1002. <div style="grid-column: 13;" onclick="sortGrid(this.id)" id="cpe_id"
  1003. class="centered cpe_id data label"><span>CPE ID</span><span></span></div>
  1004. """)
  1005. for pkg in sorted(packages):
  1006. dump_html_pkg(f, pkg)
  1007. f.write("</div>")
  1008. def dump_html_stats(f, stats):
  1009. f.write('<a id="results"></a>\n')
  1010. f.write('<div class="data" id="results-grid">\n')
  1011. infras = [infra[6:] for infra in stats.keys() if infra.startswith("infra-")]
  1012. for infra in infras:
  1013. f.write(' <div class="data">Packages using the <i>%s</i> infrastructure</div><div class="data">%s</div>\n' %
  1014. (infra, stats["infra-%s" % infra]))
  1015. f.write(' <div class="data">Packages having license information</div><div class="data">%s</div>\n' %
  1016. stats["license"])
  1017. f.write(' <div class="data">Packages not having license information</div><div class="data">%s</div>\n' %
  1018. stats["no-license"])
  1019. f.write(' <div class="data">Packages having license files information</div><div class="data">%s</div>\n' %
  1020. stats["license-files"])
  1021. f.write(' <div class="data">Packages not having license files information</div><div class="data">%s</div>\n' %
  1022. stats["no-license-files"])
  1023. f.write(' <div class="data">Packages having a hash file</div><div class="data">%s</div>\n' %
  1024. stats["hash"])
  1025. f.write(' <div class="data">Packages not having a hash file</div><div class="data">%s</div>\n' %
  1026. stats["no-hash"])
  1027. f.write(' <div class="data">Total number of patches</div><div class="data">%s</div>\n' %
  1028. stats["patches"])
  1029. f.write('<div class="data">Packages having a mapping on <i>release-monitoring.org</i></div><div class="data">%s</div>\n' %
  1030. stats["rmo-mapping"])
  1031. f.write('<div class="data">Packages lacking a mapping on <i>release-monitoring.org</i></div><div class="data">%s</div>\n' %
  1032. stats["rmo-no-mapping"])
  1033. f.write('<div class="data">Packages that are up-to-date</div><div class="data">%s</div>\n' %
  1034. stats["version-uptodate"])
  1035. f.write('<div class="data">Packages that are not up-to-date</div><div class="data">%s</div>\n' %
  1036. stats["version-not-uptodate"])
  1037. f.write('<div class="data">Packages with no known upstream version</div><div class="data">%s</div>\n' %
  1038. stats["version-unknown"])
  1039. f.write('<div class="data">Packages affected by CVEs</div><div class="data">%s</div>\n' %
  1040. stats["pkg-cves"])
  1041. f.write('<div class="data">Total number of CVEs affecting all packages</div><div class="data">%s</div>\n' %
  1042. stats["total-cves"])
  1043. f.write('<div class="data">Packages affected by unsure CVEs</div><div class="data">%s</div>\n' %
  1044. stats["pkg-unsure-cves"])
  1045. f.write('<div class="data">Total number of unsure CVEs affecting all packages</div><div class="data">%s</div>\n' %
  1046. stats["total-unsure-cves"])
  1047. f.write('<div class="data">Packages with CPE ID</div><div class="data">%s</div>\n' %
  1048. stats["cpe-id"])
  1049. f.write('<div class="data">Packages without CPE ID</div><div class="data">%s</div>\n' %
  1050. stats["no-cpe-id"])
  1051. f.write('</div>\n')
  1052. def dump_html_gen_info(f, date, commit):
  1053. # Updated on Mon Feb 19 08:12:08 CET 2018, Git commit aa77030b8f5e41f1c53eb1c1ad664b8c814ba032
  1054. f.write("<p><i>Updated on %s, git commit %s</i></p>\n" % (str(date), commit))
  1055. def dump_html(packages, stats, date, commit, output):
  1056. with open(output, 'w') as f:
  1057. f.write(html_header)
  1058. dump_html_all_pkgs(f, packages)
  1059. dump_html_stats(f, stats)
  1060. dump_html_gen_info(f, date, commit)
  1061. f.write(html_footer)
  1062. def dump_json(packages, defconfigs, stats, date, commit, output):
  1063. # Format packages as a dictionnary instead of a list
  1064. # Exclude local field that does not contains real date
  1065. excluded_fields = ['url_worker', 'name']
  1066. pkgs = {
  1067. pkg.name: {
  1068. k: v
  1069. for k, v in pkg.__dict__.items()
  1070. if k not in excluded_fields
  1071. } for pkg in packages
  1072. }
  1073. defconfigs = {
  1074. d.name: {
  1075. k: v
  1076. for k, v in d.__dict__.items()
  1077. } for d in defconfigs
  1078. }
  1079. # Aggregate infrastructures into a single dict entry
  1080. statistics = {
  1081. k: v
  1082. for k, v in stats.items()
  1083. if not k.startswith('infra-')
  1084. }
  1085. statistics['infra'] = {k[6:]: v for k, v in stats.items() if k.startswith('infra-')}
  1086. # The actual structure to dump, add commit and date to it
  1087. final = {'packages': pkgs,
  1088. 'stats': statistics,
  1089. 'defconfigs': defconfigs,
  1090. 'package_status_checks': Package.status_checks,
  1091. 'commit': commit,
  1092. 'date': str(date)}
  1093. with open(output, 'w') as f:
  1094. json.dump(final, f, indent=2, separators=(',', ': '))
  1095. f.write('\n')
  1096. def resolvepath(path):
  1097. return os.path.abspath(os.path.expanduser(path))
  1098. def list_str(values):
  1099. return values.split(',')
  1100. def parse_args():
  1101. parser = argparse.ArgumentParser()
  1102. output = parser.add_argument_group('output', 'Output file(s)')
  1103. output.add_argument('--html', dest='html', type=resolvepath,
  1104. help='HTML output file')
  1105. output.add_argument('--json', dest='json', type=resolvepath,
  1106. help='JSON output file')
  1107. packages = parser.add_mutually_exclusive_group()
  1108. packages.add_argument('-c', dest='configpackages', action='store_true',
  1109. help='Apply to packages enabled in current configuration')
  1110. packages.add_argument('-n', dest='npackages', type=int, action='store',
  1111. help='Number of packages')
  1112. packages.add_argument('-p', dest='packages', action='store',
  1113. help='List of packages (comma separated)')
  1114. parser.add_argument('--nvd-path', dest='nvd_path',
  1115. help='Path to the local NVD database', type=resolvepath)
  1116. parser.add_argument('--disable', type=list_str,
  1117. help='Features to disable, comma-separated (cve, upstream, url, cpe, warning)',
  1118. default=[])
  1119. args = parser.parse_args()
  1120. if not args.html and not args.json:
  1121. parser.error('at least one of --html or --json (or both) is required')
  1122. return args
  1123. def __main__():
  1124. global cvecheck
  1125. args = parse_args()
  1126. if args.nvd_path:
  1127. import cve as cvecheck
  1128. show_info_js = None
  1129. if args.packages:
  1130. package_list = args.packages.split(",")
  1131. elif args.configpackages:
  1132. show_info_js = get_show_info_js()
  1133. package_list = set([v["name"] for v in show_info_js.values() if 'name' in v])
  1134. else:
  1135. package_list = None
  1136. date = datetime.datetime.utcnow()
  1137. commit = subprocess.check_output(['git', '-C', brpath,
  1138. 'rev-parse',
  1139. 'HEAD']).splitlines()[0].decode()
  1140. print("Build package list ...")
  1141. packages = get_pkglist(args.npackages, package_list)
  1142. print("Getting developers ...")
  1143. developers = parse_developers()
  1144. print("Build defconfig list ...")
  1145. defconfigs = get_defconfig_list()
  1146. for d in defconfigs:
  1147. d.set_developers(developers)
  1148. print("Getting package make info ...")
  1149. package_init_make_info()
  1150. print("Getting package details ...")
  1151. for pkg in packages:
  1152. pkg.set_infra(show_info_js)
  1153. pkg.set_license()
  1154. pkg.set_hash_info()
  1155. pkg.set_patch_count()
  1156. if "warnings" not in args.disable:
  1157. pkg.set_check_package_warnings()
  1158. pkg.set_current_version()
  1159. pkg.set_cpeid()
  1160. pkg.set_url()
  1161. pkg.set_ignored_cves()
  1162. pkg.set_developers(developers)
  1163. if "url" not in args.disable:
  1164. print("Checking URL status")
  1165. loop = asyncio.get_event_loop()
  1166. loop.run_until_complete(check_package_urls(packages))
  1167. if "upstream" not in args.disable:
  1168. print("Getting latest versions ...")
  1169. loop = asyncio.get_event_loop()
  1170. loop.run_until_complete(check_package_latest_version(packages))
  1171. if "cve" not in args.disable and args.nvd_path:
  1172. print("Checking packages CVEs")
  1173. check_package_cves(args.nvd_path, packages)
  1174. if "cpe" not in args.disable and args.nvd_path:
  1175. print("Checking packages CPEs")
  1176. check_package_cpes(args.nvd_path, packages)
  1177. print("Calculate stats")
  1178. stats = calculate_stats(packages)
  1179. if args.html:
  1180. print("Write HTML")
  1181. dump_html(packages, stats, date, commit, args.html)
  1182. if args.json:
  1183. print("Write JSON")
  1184. dump_json(packages, defconfigs, stats, date, commit, args.json)
  1185. __main__()