pkg-stats 38 KB

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