2
1

pkg-stats 36 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062
  1. #!/usr/bin/env python
  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 argparse
  18. import datetime
  19. import fnmatch
  20. import os
  21. from collections import defaultdict
  22. import re
  23. import subprocess
  24. import requests # URL checking
  25. import json
  26. import ijson
  27. import certifi
  28. import distutils.version
  29. import time
  30. import gzip
  31. import sys
  32. from urllib3 import HTTPSConnectionPool
  33. from urllib3.exceptions import HTTPError
  34. from multiprocessing import Pool
  35. sys.path.append('utils/')
  36. from getdeveloperlib import parse_developers # noqa: E402
  37. NVD_START_YEAR = 2002
  38. NVD_JSON_VERSION = "1.0"
  39. NVD_BASE_URL = "https://nvd.nist.gov/feeds/json/cve/" + NVD_JSON_VERSION
  40. INFRA_RE = re.compile(r"\$\(eval \$\(([a-z-]*)-package\)\)")
  41. URL_RE = re.compile(r"\s*https?://\S*\s*$")
  42. RM_API_STATUS_ERROR = 1
  43. RM_API_STATUS_FOUND_BY_DISTRO = 2
  44. RM_API_STATUS_FOUND_BY_PATTERN = 3
  45. RM_API_STATUS_NOT_FOUND = 4
  46. # Used to make multiple requests to the same host. It is global
  47. # because it's used by sub-processes.
  48. http_pool = None
  49. class Defconfig:
  50. def __init__(self, name, path):
  51. self.name = name
  52. self.path = path
  53. self.developers = None
  54. def set_developers(self, developers):
  55. """
  56. Fills in the .developers field
  57. """
  58. self.developers = [
  59. developer.name
  60. for developer in developers
  61. if developer.hasfile(self.path)
  62. ]
  63. def get_defconfig_list():
  64. """
  65. Builds the list of Buildroot defconfigs, returning a list of Defconfig
  66. objects.
  67. """
  68. return [
  69. Defconfig(name[:-len('_defconfig')], os.path.join('configs', name))
  70. for name in os.listdir('configs')
  71. if name.endswith('_defconfig')
  72. ]
  73. class Package:
  74. all_licenses = dict()
  75. all_license_files = list()
  76. all_versions = dict()
  77. all_ignored_cves = dict()
  78. # This is the list of all possible checks. Add new checks to this list so
  79. # a tool that post-processeds the json output knows the checks before
  80. # iterating over the packages.
  81. status_checks = ['cve', 'developers', 'hash', 'license',
  82. 'license-files', 'patches', 'pkg-check', 'url', 'version']
  83. def __init__(self, name, path):
  84. self.name = name
  85. self.path = path
  86. self.pkg_path = os.path.dirname(path)
  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.cves = list()
  98. self.latest_version = {'status': RM_API_STATUS_ERROR, 'version': None, 'id': None}
  99. self.status = {}
  100. def pkgvar(self):
  101. return self.name.upper().replace("-", "_")
  102. def set_url(self):
  103. """
  104. Fills in the .url field
  105. """
  106. self.status['url'] = ("warning", "no Config.in")
  107. for filename in os.listdir(os.path.dirname(self.path)):
  108. if fnmatch.fnmatch(filename, 'Config.*'):
  109. fp = open(os.path.join(os.path.dirname(self.path), filename), "r")
  110. for config_line in fp:
  111. if URL_RE.match(config_line):
  112. self.url = config_line.strip()
  113. self.status['url'] = ("ok", "found")
  114. fp.close()
  115. return
  116. self.status['url'] = ("error", "missing")
  117. fp.close()
  118. @property
  119. def patch_count(self):
  120. return len(self.patch_files)
  121. @property
  122. def has_valid_infra(self):
  123. try:
  124. if self.infras[0][1] == 'virtual':
  125. return False
  126. except IndexError:
  127. return False
  128. return True
  129. def set_infra(self):
  130. """
  131. Fills in the .infras field
  132. """
  133. self.infras = list()
  134. with open(self.path, 'r') as f:
  135. lines = f.readlines()
  136. for l in lines:
  137. match = INFRA_RE.match(l)
  138. if not match:
  139. continue
  140. infra = match.group(1)
  141. if infra.startswith("host-"):
  142. self.infras.append(("host", infra[5:]))
  143. else:
  144. self.infras.append(("target", infra))
  145. def set_license(self):
  146. """
  147. Fills in the .status['license'] and .status['license-files'] fields
  148. """
  149. if not self.has_valid_infra:
  150. self.status['license'] = ("na", "no valid package infra")
  151. self.status['license-files'] = ("na", "no valid package infra")
  152. return
  153. var = self.pkgvar()
  154. self.status['license'] = ("error", "missing")
  155. self.status['license-files'] = ("error", "missing")
  156. if var in self.all_licenses:
  157. self.license = self.all_licenses[var]
  158. self.status['license'] = ("ok", "found")
  159. if var in self.all_license_files:
  160. self.status['license-files'] = ("ok", "found")
  161. def set_hash_info(self):
  162. """
  163. Fills in the .status['hash'] field
  164. """
  165. if not self.has_valid_infra:
  166. self.status['hash'] = ("na", "no valid package infra")
  167. self.status['hash-license'] = ("na", "no valid package infra")
  168. return
  169. hashpath = self.path.replace(".mk", ".hash")
  170. if os.path.exists(hashpath):
  171. self.status['hash'] = ("ok", "found")
  172. else:
  173. self.status['hash'] = ("error", "missing")
  174. def set_patch_count(self):
  175. """
  176. Fills in the .patch_count, .patch_files and .status['patches'] fields
  177. """
  178. if not self.has_valid_infra:
  179. self.status['patches'] = ("na", "no valid package infra")
  180. return
  181. pkgdir = os.path.dirname(self.path)
  182. for subdir, _, _ in os.walk(pkgdir):
  183. self.patch_files = fnmatch.filter(os.listdir(subdir), '*.patch')
  184. if self.patch_count == 0:
  185. self.status['patches'] = ("ok", "no patches")
  186. elif self.patch_count < 5:
  187. self.status['patches'] = ("warning", "some patches")
  188. else:
  189. self.status['patches'] = ("error", "lots of patches")
  190. def set_current_version(self):
  191. """
  192. Fills in the .current_version field
  193. """
  194. var = self.pkgvar()
  195. if var in self.all_versions:
  196. self.current_version = self.all_versions[var]
  197. def set_check_package_warnings(self):
  198. """
  199. Fills in the .warnings and .status['pkg-check'] fields
  200. """
  201. cmd = ["./utils/check-package"]
  202. pkgdir = os.path.dirname(self.path)
  203. self.status['pkg-check'] = ("error", "Missing")
  204. for root, dirs, files in os.walk(pkgdir):
  205. for f in files:
  206. if f.endswith(".mk") or f.endswith(".hash") or f == "Config.in" or f == "Config.in.host":
  207. cmd.append(os.path.join(root, f))
  208. o = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE).communicate()[1]
  209. lines = o.splitlines()
  210. for line in lines:
  211. m = re.match("^([0-9]*) warnings generated", line.decode())
  212. if m:
  213. self.warnings = int(m.group(1))
  214. if self.warnings == 0:
  215. self.status['pkg-check'] = ("ok", "no warnings")
  216. else:
  217. self.status['pkg-check'] = ("error", "{} warnings".format(self.warnings))
  218. return
  219. def is_cve_ignored(self, cve):
  220. """
  221. Tells if the CVE is ignored by the package
  222. """
  223. return cve in self.all_ignored_cves.get(self.pkgvar(), [])
  224. def set_developers(self, developers):
  225. """
  226. Fills in the .developers and .status['developers'] field
  227. """
  228. self.developers = [
  229. dev.name
  230. for dev in developers
  231. if dev.hasfile(self.path)
  232. ]
  233. if self.developers:
  234. self.status['developers'] = ("ok", "{} developers".format(len(self.developers)))
  235. else:
  236. self.status['developers'] = ("warning", "no developers")
  237. def is_status_ok(self, name):
  238. return self.status[name][0] == 'ok'
  239. def __eq__(self, other):
  240. return self.path == other.path
  241. def __lt__(self, other):
  242. return self.path < other.path
  243. def __str__(self):
  244. return "%s (path='%s', license='%s', license_files='%s', hash='%s', patches=%d)" % \
  245. (self.name, self.path, self.is_status_ok('license'),
  246. self.is_status_ok('license-files'), self.status['hash'], self.patch_count)
  247. class CVE:
  248. """An accessor class for CVE Items in NVD files"""
  249. def __init__(self, nvd_cve):
  250. """Initialize a CVE from its NVD JSON representation"""
  251. self.nvd_cve = nvd_cve
  252. @staticmethod
  253. def download_nvd_year(nvd_path, year):
  254. metaf = "nvdcve-%s-%s.meta" % (NVD_JSON_VERSION, year)
  255. path_metaf = os.path.join(nvd_path, metaf)
  256. jsonf_gz = "nvdcve-%s-%s.json.gz" % (NVD_JSON_VERSION, year)
  257. path_jsonf_gz = os.path.join(nvd_path, jsonf_gz)
  258. # If the database file is less than a day old, we assume the NVD data
  259. # locally available is recent enough.
  260. if os.path.exists(path_jsonf_gz) and os.stat(path_jsonf_gz).st_mtime >= time.time() - 86400:
  261. return path_jsonf_gz
  262. # If not, we download the meta file
  263. url = "%s/%s" % (NVD_BASE_URL, metaf)
  264. print("Getting %s" % url)
  265. page_meta = requests.get(url)
  266. page_meta.raise_for_status()
  267. # If the meta file already existed, we compare the existing
  268. # one with the data newly downloaded. If they are different,
  269. # we need to re-download the database.
  270. # If the database does not exist locally, we need to redownload it in
  271. # any case.
  272. if os.path.exists(path_metaf) and os.path.exists(path_jsonf_gz):
  273. meta_known = open(path_metaf, "r").read()
  274. if page_meta.text == meta_known:
  275. return path_jsonf_gz
  276. # Grab the compressed JSON NVD, and write files to disk
  277. url = "%s/%s" % (NVD_BASE_URL, jsonf_gz)
  278. print("Getting %s" % url)
  279. page_json = requests.get(url)
  280. page_json.raise_for_status()
  281. open(path_jsonf_gz, "wb").write(page_json.content)
  282. open(path_metaf, "w").write(page_meta.text)
  283. return path_jsonf_gz
  284. @classmethod
  285. def read_nvd_dir(cls, nvd_dir):
  286. """
  287. Iterate over all the CVEs contained in NIST Vulnerability Database
  288. feeds since NVD_START_YEAR. If the files are missing or outdated in
  289. nvd_dir, a fresh copy will be downloaded, and kept in .json.gz
  290. """
  291. for year in range(NVD_START_YEAR, datetime.datetime.now().year + 1):
  292. filename = CVE.download_nvd_year(nvd_dir, year)
  293. try:
  294. content = ijson.items(gzip.GzipFile(filename), 'CVE_Items.item')
  295. except: # noqa: E722
  296. print("ERROR: cannot read %s. Please remove the file then rerun this script" % filename)
  297. raise
  298. for cve in content:
  299. yield cls(cve['cve'])
  300. def each_product(self):
  301. """Iterate over each product section of this cve"""
  302. for vendor in self.nvd_cve['affects']['vendor']['vendor_data']:
  303. for product in vendor['product']['product_data']:
  304. yield product
  305. @property
  306. def identifier(self):
  307. """The CVE unique identifier"""
  308. return self.nvd_cve['CVE_data_meta']['ID']
  309. @property
  310. def pkg_names(self):
  311. """The set of package names referred by this CVE definition"""
  312. return set(p['product_name'] for p in self.each_product())
  313. def affects(self, br_pkg):
  314. """
  315. True if the Buildroot Package object passed as argument is affected
  316. by this CVE.
  317. """
  318. if br_pkg.is_cve_ignored(self.identifier):
  319. return False
  320. for product in self.each_product():
  321. if product['product_name'] != br_pkg.name:
  322. continue
  323. for v in product['version']['version_data']:
  324. if v["version_affected"] == "=":
  325. if br_pkg.current_version == v["version_value"]:
  326. return True
  327. elif v["version_affected"] == "<=":
  328. pkg_version = distutils.version.LooseVersion(br_pkg.current_version)
  329. if not hasattr(pkg_version, "version"):
  330. print("Cannot parse package '%s' version '%s'" % (br_pkg.name, br_pkg.current_version))
  331. continue
  332. cve_affected_version = distutils.version.LooseVersion(v["version_value"])
  333. if not hasattr(cve_affected_version, "version"):
  334. print("Cannot parse CVE affected version '%s'" % v["version_value"])
  335. continue
  336. return pkg_version <= cve_affected_version
  337. else:
  338. print("version_affected: %s" % v['version_affected'])
  339. return False
  340. def get_pkglist(npackages, package_list):
  341. """
  342. Builds the list of Buildroot packages, returning a list of Package
  343. objects. Only the .name and .path fields of the Package object are
  344. initialized.
  345. npackages: limit to N packages
  346. package_list: limit to those packages in this list
  347. """
  348. WALK_USEFUL_SUBDIRS = ["boot", "linux", "package", "toolchain"]
  349. WALK_EXCLUDES = ["boot/common.mk",
  350. "linux/linux-ext-.*.mk",
  351. "package/freescale-imx/freescale-imx.mk",
  352. "package/gcc/gcc.mk",
  353. "package/gstreamer/gstreamer.mk",
  354. "package/gstreamer1/gstreamer1.mk",
  355. "package/gtk2-themes/gtk2-themes.mk",
  356. "package/matchbox/matchbox.mk",
  357. "package/opengl/opengl.mk",
  358. "package/qt5/qt5.mk",
  359. "package/x11r7/x11r7.mk",
  360. "package/doc-asciidoc.mk",
  361. "package/pkg-.*.mk",
  362. "package/nvidia-tegra23/nvidia-tegra23.mk",
  363. "toolchain/toolchain-external/pkg-toolchain-external.mk",
  364. "toolchain/toolchain-external/toolchain-external.mk",
  365. "toolchain/toolchain.mk",
  366. "toolchain/helpers.mk",
  367. "toolchain/toolchain-wrapper.mk"]
  368. packages = list()
  369. count = 0
  370. for root, dirs, files in os.walk("."):
  371. rootdir = root.split("/")
  372. if len(rootdir) < 2:
  373. continue
  374. if rootdir[1] not in WALK_USEFUL_SUBDIRS:
  375. continue
  376. for f in files:
  377. if not f.endswith(".mk"):
  378. continue
  379. # Strip ending ".mk"
  380. pkgname = f[:-3]
  381. if package_list and pkgname not in package_list:
  382. continue
  383. pkgpath = os.path.join(root, f)
  384. skip = False
  385. for exclude in WALK_EXCLUDES:
  386. # pkgpath[2:] strips the initial './'
  387. if re.match(exclude, pkgpath[2:]):
  388. skip = True
  389. continue
  390. if skip:
  391. continue
  392. p = Package(pkgname, pkgpath)
  393. packages.append(p)
  394. count += 1
  395. if npackages and count == npackages:
  396. return packages
  397. return packages
  398. def package_init_make_info():
  399. # Fetch all variables at once
  400. variables = subprocess.check_output(["make", "BR2_HAVE_DOT_CONFIG=y", "-s", "printvars",
  401. "VARS=%_LICENSE %_LICENSE_FILES %_VERSION %_IGNORE_CVES"])
  402. variable_list = variables.decode().splitlines()
  403. # We process first the host package VERSION, and then the target
  404. # package VERSION. This means that if a package exists in both
  405. # target and host variants, with different values (eg. version
  406. # numbers (unlikely)), we'll report the target one.
  407. variable_list = [x[5:] for x in variable_list if x.startswith("HOST_")] + \
  408. [x for x in variable_list if not x.startswith("HOST_")]
  409. for l in variable_list:
  410. # Get variable name and value
  411. pkgvar, value = l.split("=")
  412. # Strip the suffix according to the variable
  413. if pkgvar.endswith("_LICENSE"):
  414. # If value is "unknown", no license details available
  415. if value == "unknown":
  416. continue
  417. pkgvar = pkgvar[:-8]
  418. Package.all_licenses[pkgvar] = value
  419. elif pkgvar.endswith("_LICENSE_FILES"):
  420. if pkgvar.endswith("_MANIFEST_LICENSE_FILES"):
  421. continue
  422. pkgvar = pkgvar[:-14]
  423. Package.all_license_files.append(pkgvar)
  424. elif pkgvar.endswith("_VERSION"):
  425. if pkgvar.endswith("_DL_VERSION"):
  426. continue
  427. pkgvar = pkgvar[:-8]
  428. Package.all_versions[pkgvar] = value
  429. elif pkgvar.endswith("_IGNORE_CVES"):
  430. pkgvar = pkgvar[:-12]
  431. Package.all_ignored_cves[pkgvar] = value.split()
  432. def check_url_status_worker(url, url_status):
  433. if url_status[0] == 'ok':
  434. try:
  435. url_status_code = requests.head(url, timeout=30).status_code
  436. if url_status_code >= 400:
  437. return ("error", "invalid {}".format(url_status_code))
  438. except requests.exceptions.RequestException:
  439. return ("error", "invalid (err)")
  440. return ("ok", "valid")
  441. return url_status
  442. def check_package_urls(packages):
  443. pool = Pool(processes=64)
  444. for pkg in packages:
  445. pkg.url_worker = pool.apply_async(check_url_status_worker, (pkg.url, pkg.status['url']))
  446. for pkg in packages:
  447. pkg.status['url'] = pkg.url_worker.get(timeout=3600)
  448. del pkg.url_worker
  449. pool.terminate()
  450. def release_monitoring_get_latest_version_by_distro(pool, name):
  451. try:
  452. req = pool.request('GET', "/api/project/Buildroot/%s" % name)
  453. except HTTPError:
  454. return (RM_API_STATUS_ERROR, None, None)
  455. if req.status != 200:
  456. return (RM_API_STATUS_NOT_FOUND, None, None)
  457. data = json.loads(req.data)
  458. if 'version' in data:
  459. return (RM_API_STATUS_FOUND_BY_DISTRO, data['version'], data['id'])
  460. else:
  461. return (RM_API_STATUS_FOUND_BY_DISTRO, None, data['id'])
  462. def release_monitoring_get_latest_version_by_guess(pool, name):
  463. try:
  464. req = pool.request('GET', "/api/projects/?pattern=%s" % name)
  465. except HTTPError:
  466. return (RM_API_STATUS_ERROR, None, None)
  467. if req.status != 200:
  468. return (RM_API_STATUS_NOT_FOUND, None, None)
  469. data = json.loads(req.data)
  470. projects = data['projects']
  471. projects.sort(key=lambda x: x['id'])
  472. for p in projects:
  473. if p['name'] == name and 'version' in p:
  474. return (RM_API_STATUS_FOUND_BY_PATTERN, p['version'], p['id'])
  475. return (RM_API_STATUS_NOT_FOUND, None, None)
  476. def check_package_latest_version_worker(name):
  477. """Wrapper to try both by name then by guess"""
  478. print(name)
  479. res = release_monitoring_get_latest_version_by_distro(http_pool, name)
  480. if res[0] == RM_API_STATUS_NOT_FOUND:
  481. res = release_monitoring_get_latest_version_by_guess(http_pool, name)
  482. return res
  483. def check_package_latest_version(packages):
  484. """
  485. Fills in the .latest_version field of all Package objects
  486. This field is a dict and has the following keys:
  487. - status: one of RM_API_STATUS_ERROR,
  488. RM_API_STATUS_FOUND_BY_DISTRO, RM_API_STATUS_FOUND_BY_PATTERN,
  489. RM_API_STATUS_NOT_FOUND
  490. - version: string containing the latest version known by
  491. release-monitoring.org for this package
  492. - id: string containing the id of the project corresponding to this
  493. package, as known by release-monitoring.org
  494. """
  495. global http_pool
  496. http_pool = HTTPSConnectionPool('release-monitoring.org', port=443,
  497. cert_reqs='CERT_REQUIRED', ca_certs=certifi.where(),
  498. timeout=30)
  499. worker_pool = Pool(processes=64)
  500. results = worker_pool.map(check_package_latest_version_worker, (pkg.name for pkg in packages))
  501. for pkg, r in zip(packages, results):
  502. pkg.latest_version = dict(zip(['status', 'version', 'id'], r))
  503. if not pkg.has_valid_infra:
  504. pkg.status['version'] = ("na", "no valid package infra")
  505. continue
  506. if pkg.latest_version['status'] == RM_API_STATUS_ERROR:
  507. pkg.status['version'] = ('warning', "Release Monitoring API error")
  508. elif pkg.latest_version['status'] == RM_API_STATUS_NOT_FOUND:
  509. pkg.status['version'] = ('warning', "Package not found on Release Monitoring")
  510. if pkg.latest_version['version'] is None:
  511. pkg.status['version'] = ('warning', "No upstream version available on Release Monitoring")
  512. elif pkg.latest_version['version'] != pkg.current_version:
  513. pkg.status['version'] = ('error', "The newer version {} is available upstream".format(pkg.latest_version['version']))
  514. else:
  515. pkg.status['version'] = ('ok', 'up-to-date')
  516. worker_pool.terminate()
  517. del http_pool
  518. def check_package_cves(nvd_path, packages):
  519. if not os.path.isdir(nvd_path):
  520. os.makedirs(nvd_path)
  521. for cve in CVE.read_nvd_dir(nvd_path):
  522. for pkg_name in cve.pkg_names:
  523. if pkg_name in packages and cve.affects(packages[pkg_name]):
  524. packages[pkg_name].cves.append(cve.identifier)
  525. def calculate_stats(packages):
  526. stats = defaultdict(int)
  527. stats['packages'] = len(packages)
  528. for pkg in packages:
  529. # If packages have multiple infra, take the first one. For the
  530. # vast majority of packages, the target and host infra are the
  531. # same. There are very few packages that use a different infra
  532. # for the host and target variants.
  533. if len(pkg.infras) > 0:
  534. infra = pkg.infras[0][1]
  535. stats["infra-%s" % infra] += 1
  536. else:
  537. stats["infra-unknown"] += 1
  538. if pkg.is_status_ok('license'):
  539. stats["license"] += 1
  540. else:
  541. stats["no-license"] += 1
  542. if pkg.is_status_ok('license-files'):
  543. stats["license-files"] += 1
  544. else:
  545. stats["no-license-files"] += 1
  546. if pkg.is_status_ok('hash'):
  547. stats["hash"] += 1
  548. else:
  549. stats["no-hash"] += 1
  550. if pkg.latest_version['status'] == RM_API_STATUS_FOUND_BY_DISTRO:
  551. stats["rmo-mapping"] += 1
  552. else:
  553. stats["rmo-no-mapping"] += 1
  554. if not pkg.latest_version['version']:
  555. stats["version-unknown"] += 1
  556. elif pkg.latest_version['version'] == pkg.current_version:
  557. stats["version-uptodate"] += 1
  558. else:
  559. stats["version-not-uptodate"] += 1
  560. stats["patches"] += pkg.patch_count
  561. stats["total-cves"] += len(pkg.cves)
  562. if len(pkg.cves) != 0:
  563. stats["pkg-cves"] += 1
  564. return stats
  565. html_header = """
  566. <head>
  567. <script src=\"https://www.kryogenix.org/code/browser/sorttable/sorttable.js\"></script>
  568. <style type=\"text/css\">
  569. table {
  570. width: 100%;
  571. }
  572. td {
  573. border: 1px solid black;
  574. }
  575. td.centered {
  576. text-align: center;
  577. }
  578. td.wrong {
  579. background: #ff9a69;
  580. }
  581. td.correct {
  582. background: #d2ffc4;
  583. }
  584. td.nopatches {
  585. background: #d2ffc4;
  586. }
  587. td.somepatches {
  588. background: #ffd870;
  589. }
  590. td.lotsofpatches {
  591. background: #ff9a69;
  592. }
  593. td.good_url {
  594. background: #d2ffc4;
  595. }
  596. td.missing_url {
  597. background: #ffd870;
  598. }
  599. td.invalid_url {
  600. background: #ff9a69;
  601. }
  602. td.version-good {
  603. background: #d2ffc4;
  604. }
  605. td.version-needs-update {
  606. background: #ff9a69;
  607. }
  608. td.version-unknown {
  609. background: #ffd870;
  610. }
  611. td.version-error {
  612. background: #ccc;
  613. }
  614. </style>
  615. <title>Statistics of Buildroot packages</title>
  616. </head>
  617. <a href=\"#results\">Results</a><br/>
  618. <p id=\"sortable_hint\"></p>
  619. """
  620. html_footer = """
  621. </body>
  622. <script>
  623. if (typeof sorttable === \"object\") {
  624. document.getElementById(\"sortable_hint\").innerHTML =
  625. \"hint: the table can be sorted by clicking the column headers\"
  626. }
  627. </script>
  628. </html>
  629. """
  630. def infra_str(infra_list):
  631. if not infra_list:
  632. return "Unknown"
  633. elif len(infra_list) == 1:
  634. return "<b>%s</b><br/>%s" % (infra_list[0][1], infra_list[0][0])
  635. elif infra_list[0][1] == infra_list[1][1]:
  636. return "<b>%s</b><br/>%s + %s" % \
  637. (infra_list[0][1], infra_list[0][0], infra_list[1][0])
  638. else:
  639. return "<b>%s</b> (%s)<br/><b>%s</b> (%s)" % \
  640. (infra_list[0][1], infra_list[0][0],
  641. infra_list[1][1], infra_list[1][0])
  642. def boolean_str(b):
  643. if b:
  644. return "Yes"
  645. else:
  646. return "No"
  647. def dump_html_pkg(f, pkg):
  648. f.write(" <tr>\n")
  649. f.write(" <td>%s</td>\n" % pkg.path[2:])
  650. # Patch count
  651. td_class = ["centered"]
  652. if pkg.patch_count == 0:
  653. td_class.append("nopatches")
  654. elif pkg.patch_count < 5:
  655. td_class.append("somepatches")
  656. else:
  657. td_class.append("lotsofpatches")
  658. f.write(" <td class=\"%s\">%s</td>\n" %
  659. (" ".join(td_class), str(pkg.patch_count)))
  660. # Infrastructure
  661. infra = infra_str(pkg.infras)
  662. td_class = ["centered"]
  663. if infra == "Unknown":
  664. td_class.append("wrong")
  665. else:
  666. td_class.append("correct")
  667. f.write(" <td class=\"%s\">%s</td>\n" %
  668. (" ".join(td_class), infra_str(pkg.infras)))
  669. # License
  670. td_class = ["centered"]
  671. if pkg.is_status_ok('license'):
  672. td_class.append("correct")
  673. else:
  674. td_class.append("wrong")
  675. f.write(" <td class=\"%s\">%s</td>\n" %
  676. (" ".join(td_class), boolean_str(pkg.is_status_ok('license'))))
  677. # License files
  678. td_class = ["centered"]
  679. if pkg.is_status_ok('license-files'):
  680. td_class.append("correct")
  681. else:
  682. td_class.append("wrong")
  683. f.write(" <td class=\"%s\">%s</td>\n" %
  684. (" ".join(td_class), boolean_str(pkg.is_status_ok('license-files'))))
  685. # Hash
  686. td_class = ["centered"]
  687. if pkg.is_status_ok('hash'):
  688. td_class.append("correct")
  689. else:
  690. td_class.append("wrong")
  691. f.write(" <td class=\"%s\">%s</td>\n" %
  692. (" ".join(td_class), boolean_str(pkg.is_status_ok('hash'))))
  693. # Current version
  694. if len(pkg.current_version) > 20:
  695. current_version = pkg.current_version[:20] + "..."
  696. else:
  697. current_version = pkg.current_version
  698. f.write(" <td class=\"centered\">%s</td>\n" % current_version)
  699. # Latest version
  700. if pkg.latest_version['status'] == RM_API_STATUS_ERROR:
  701. td_class.append("version-error")
  702. if pkg.latest_version['version'] is None:
  703. td_class.append("version-unknown")
  704. elif pkg.latest_version['version'] != pkg.current_version:
  705. td_class.append("version-needs-update")
  706. else:
  707. td_class.append("version-good")
  708. if pkg.latest_version['status'] == RM_API_STATUS_ERROR:
  709. latest_version_text = "<b>Error</b>"
  710. elif pkg.latest_version['status'] == RM_API_STATUS_NOT_FOUND:
  711. latest_version_text = "<b>Not found</b>"
  712. else:
  713. if pkg.latest_version['version'] is None:
  714. latest_version_text = "<b>Found, but no version</b>"
  715. else:
  716. latest_version_text = "<a href=\"https://release-monitoring.org/project/%s\"><b>%s</b></a>" % \
  717. (pkg.latest_version['id'], str(pkg.latest_version['version']))
  718. latest_version_text += "<br/>"
  719. if pkg.latest_version['status'] == RM_API_STATUS_FOUND_BY_DISTRO:
  720. latest_version_text += "found by <a href=\"https://release-monitoring.org/distro/Buildroot/\">distro</a>"
  721. else:
  722. latest_version_text += "found by guess"
  723. f.write(" <td class=\"%s\">%s</td>\n" %
  724. (" ".join(td_class), latest_version_text))
  725. # Warnings
  726. td_class = ["centered"]
  727. if pkg.warnings == 0:
  728. td_class.append("correct")
  729. else:
  730. td_class.append("wrong")
  731. f.write(" <td class=\"%s\">%d</td>\n" %
  732. (" ".join(td_class), pkg.warnings))
  733. # URL status
  734. td_class = ["centered"]
  735. url_str = pkg.status['url'][1]
  736. if pkg.status['url'][0] in ("error", "warning"):
  737. td_class.append("missing_url")
  738. if pkg.status['url'][0] == "error":
  739. td_class.append("invalid_url")
  740. url_str = "<a href=%s>%s</a>" % (pkg.url, pkg.status['url'][1])
  741. else:
  742. td_class.append("good_url")
  743. url_str = "<a href=%s>Link</a>" % pkg.url
  744. f.write(" <td class=\"%s\">%s</td>\n" %
  745. (" ".join(td_class), url_str))
  746. # CVEs
  747. td_class = ["centered"]
  748. if len(pkg.cves) == 0:
  749. td_class.append("correct")
  750. else:
  751. td_class.append("wrong")
  752. f.write(" <td class=\"%s\">\n" % " ".join(td_class))
  753. for cve in pkg.cves:
  754. f.write(" <a href=\"https://security-tracker.debian.org/tracker/%s\">%s<br/>\n" % (cve, cve))
  755. f.write(" </td>\n")
  756. f.write(" </tr>\n")
  757. def dump_html_all_pkgs(f, packages):
  758. f.write("""
  759. <table class=\"sortable\">
  760. <tr>
  761. <td>Package</td>
  762. <td class=\"centered\">Patch count</td>
  763. <td class=\"centered\">Infrastructure</td>
  764. <td class=\"centered\">License</td>
  765. <td class=\"centered\">License files</td>
  766. <td class=\"centered\">Hash file</td>
  767. <td class=\"centered\">Current version</td>
  768. <td class=\"centered\">Latest version</td>
  769. <td class=\"centered\">Warnings</td>
  770. <td class=\"centered\">Upstream URL</td>
  771. <td class=\"centered\">CVEs</td>
  772. </tr>
  773. """)
  774. for pkg in sorted(packages):
  775. dump_html_pkg(f, pkg)
  776. f.write("</table>")
  777. def dump_html_stats(f, stats):
  778. f.write("<a id=\"results\"></a>\n")
  779. f.write("<table>\n")
  780. infras = [infra[6:] for infra in stats.keys() if infra.startswith("infra-")]
  781. for infra in infras:
  782. f.write(" <tr><td>Packages using the <i>%s</i> infrastructure</td><td>%s</td></tr>\n" %
  783. (infra, stats["infra-%s" % infra]))
  784. f.write(" <tr><td>Packages having license information</td><td>%s</td></tr>\n" %
  785. stats["license"])
  786. f.write(" <tr><td>Packages not having license information</td><td>%s</td></tr>\n" %
  787. stats["no-license"])
  788. f.write(" <tr><td>Packages having license files information</td><td>%s</td></tr>\n" %
  789. stats["license-files"])
  790. f.write(" <tr><td>Packages not having license files information</td><td>%s</td></tr>\n" %
  791. stats["no-license-files"])
  792. f.write(" <tr><td>Packages having a hash file</td><td>%s</td></tr>\n" %
  793. stats["hash"])
  794. f.write(" <tr><td>Packages not having a hash file</td><td>%s</td></tr>\n" %
  795. stats["no-hash"])
  796. f.write(" <tr><td>Total number of patches</td><td>%s</td></tr>\n" %
  797. stats["patches"])
  798. f.write("<tr><td>Packages having a mapping on <i>release-monitoring.org</i></td><td>%s</td></tr>\n" %
  799. stats["rmo-mapping"])
  800. f.write("<tr><td>Packages lacking a mapping on <i>release-monitoring.org</i></td><td>%s</td></tr>\n" %
  801. stats["rmo-no-mapping"])
  802. f.write("<tr><td>Packages that are up-to-date</td><td>%s</td></tr>\n" %
  803. stats["version-uptodate"])
  804. f.write("<tr><td>Packages that are not up-to-date</td><td>%s</td></tr>\n" %
  805. stats["version-not-uptodate"])
  806. f.write("<tr><td>Packages with no known upstream version</td><td>%s</td></tr>\n" %
  807. stats["version-unknown"])
  808. f.write("<tr><td>Packages affected by CVEs</td><td>%s</td></tr>\n" %
  809. stats["pkg-cves"])
  810. f.write("<tr><td>Total number of CVEs affecting all packages</td><td>%s</td></tr>\n" %
  811. stats["total-cves"])
  812. f.write("</table>\n")
  813. def dump_html_gen_info(f, date, commit):
  814. # Updated on Mon Feb 19 08:12:08 CET 2018, Git commit aa77030b8f5e41f1c53eb1c1ad664b8c814ba032
  815. f.write("<p><i>Updated on %s, git commit %s</i></p>\n" % (str(date), commit))
  816. def dump_html(packages, stats, date, commit, output):
  817. with open(output, 'w') as f:
  818. f.write(html_header)
  819. dump_html_all_pkgs(f, packages)
  820. dump_html_stats(f, stats)
  821. dump_html_gen_info(f, date, commit)
  822. f.write(html_footer)
  823. def dump_json(packages, defconfigs, stats, date, commit, output):
  824. # Format packages as a dictionnary instead of a list
  825. # Exclude local field that does not contains real date
  826. excluded_fields = ['url_worker', 'name']
  827. pkgs = {
  828. pkg.name: {
  829. k: v
  830. for k, v in pkg.__dict__.items()
  831. if k not in excluded_fields
  832. } for pkg in packages
  833. }
  834. defconfigs = {
  835. d.name: {
  836. k: v
  837. for k, v in d.__dict__.items()
  838. } for d in defconfigs
  839. }
  840. # Aggregate infrastructures into a single dict entry
  841. statistics = {
  842. k: v
  843. for k, v in stats.items()
  844. if not k.startswith('infra-')
  845. }
  846. statistics['infra'] = {k[6:]: v for k, v in stats.items() if k.startswith('infra-')}
  847. # The actual structure to dump, add commit and date to it
  848. final = {'packages': pkgs,
  849. 'stats': statistics,
  850. 'defconfigs': defconfigs,
  851. 'package_status_checks': Package.status_checks,
  852. 'commit': commit,
  853. 'date': str(date)}
  854. with open(output, 'w') as f:
  855. json.dump(final, f, indent=2, separators=(',', ': '))
  856. f.write('\n')
  857. def resolvepath(path):
  858. return os.path.abspath(os.path.expanduser(path))
  859. def parse_args():
  860. parser = argparse.ArgumentParser()
  861. output = parser.add_argument_group('output', 'Output file(s)')
  862. output.add_argument('--html', dest='html', type=resolvepath,
  863. help='HTML output file')
  864. output.add_argument('--json', dest='json', type=resolvepath,
  865. help='JSON output file')
  866. packages = parser.add_mutually_exclusive_group()
  867. packages.add_argument('-n', dest='npackages', type=int, action='store',
  868. help='Number of packages')
  869. packages.add_argument('-p', dest='packages', action='store',
  870. help='List of packages (comma separated)')
  871. parser.add_argument('--nvd-path', dest='nvd_path',
  872. help='Path to the local NVD database', type=resolvepath)
  873. args = parser.parse_args()
  874. if not args.html and not args.json:
  875. parser.error('at least one of --html or --json (or both) is required')
  876. return args
  877. def __main__():
  878. args = parse_args()
  879. if args.packages:
  880. package_list = args.packages.split(",")
  881. else:
  882. package_list = None
  883. date = datetime.datetime.utcnow()
  884. commit = subprocess.check_output(['git', 'rev-parse',
  885. 'HEAD']).splitlines()[0].decode()
  886. print("Build package list ...")
  887. packages = get_pkglist(args.npackages, package_list)
  888. print("Getting developers ...")
  889. developers = parse_developers()
  890. print("Build defconfig list ...")
  891. defconfigs = get_defconfig_list()
  892. for d in defconfigs:
  893. d.set_developers(developers)
  894. print("Getting package make info ...")
  895. package_init_make_info()
  896. print("Getting package details ...")
  897. for pkg in packages:
  898. pkg.set_infra()
  899. pkg.set_license()
  900. pkg.set_hash_info()
  901. pkg.set_patch_count()
  902. pkg.set_check_package_warnings()
  903. pkg.set_current_version()
  904. pkg.set_url()
  905. pkg.set_developers(developers)
  906. print("Checking URL status")
  907. check_package_urls(packages)
  908. print("Getting latest versions ...")
  909. check_package_latest_version(packages)
  910. if args.nvd_path:
  911. print("Checking packages CVEs")
  912. check_package_cves(args.nvd_path, {p.name: p for p in packages})
  913. print("Calculate stats")
  914. stats = calculate_stats(packages)
  915. if args.html:
  916. print("Write HTML")
  917. dump_html(packages, stats, date, commit, args.html)
  918. if args.json:
  919. print("Write JSON")
  920. dump_json(packages, defconfigs, stats, date, commit, args.json)
  921. __main__()