pkg-stats 36 KB

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