pkg-stats 31 KB

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