pkg-stats 40 KB

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