cve.py 9.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273
  1. #!/usr/bin/env python3
  2. # Copyright (C) 2009 by Thomas Petazzoni <thomas.petazzoni@free-electrons.com>
  3. # Copyright (C) 2020 by Gregory CLEMENT <gregory.clement@bootlin.com>
  4. #
  5. # This program is free software; you can redistribute it and/or modify
  6. # it under the terms of the GNU General Public License as published by
  7. # the Free Software Foundation; either version 2 of the License, or
  8. # (at your option) any later version.
  9. #
  10. # This program is distributed in the hope that it will be useful,
  11. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  12. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  13. # General Public License for more details.
  14. #
  15. # You should have received a copy of the GNU General Public License
  16. # along with this program; if not, write to the Free Software
  17. # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
  18. import datetime
  19. import os
  20. import requests # URL checking
  21. import distutils.version
  22. import time
  23. import gzip
  24. import sys
  25. import operator
  26. try:
  27. import ijson
  28. # backend is a module in < 2.5, a string in >= 2.5
  29. if 'python' in getattr(ijson.backend, '__name__', ijson.backend):
  30. try:
  31. import ijson.backends.yajl2_cffi as ijson
  32. except ImportError:
  33. sys.stderr.write('Warning: Using slow ijson python backend\n')
  34. except ImportError:
  35. sys.stderr.write("You need ijson to parse NVD for CVE check\n")
  36. exit(1)
  37. sys.path.append('utils/')
  38. NVD_START_YEAR = 2002
  39. NVD_JSON_VERSION = "1.1"
  40. NVD_BASE_URL = "https://nvd.nist.gov/feeds/json/cve/" + NVD_JSON_VERSION
  41. ops = {
  42. '>=': operator.ge,
  43. '>': operator.gt,
  44. '<=': operator.le,
  45. '<': operator.lt,
  46. '=': operator.eq
  47. }
  48. # Check if two CPE IDs match each other
  49. def cpe_matches(cpe1, cpe2):
  50. cpe1_elems = cpe1.split(":")
  51. cpe2_elems = cpe2.split(":")
  52. remains = filter(lambda x: x[0] not in ["*", "-"] and x[1] not in ["*", "-"] and x[0] != x[1],
  53. zip(cpe1_elems, cpe2_elems))
  54. return len(list(remains)) == 0
  55. def cpe_product(cpe):
  56. return cpe.split(':')[4]
  57. def cpe_version(cpe):
  58. return cpe.split(':')[5]
  59. class CVE:
  60. """An accessor class for CVE Items in NVD files"""
  61. CVE_AFFECTS = 1
  62. CVE_DOESNT_AFFECT = 2
  63. CVE_UNKNOWN = 3
  64. def __init__(self, nvd_cve):
  65. """Initialize a CVE from its NVD JSON representation"""
  66. self.nvd_cve = nvd_cve
  67. @staticmethod
  68. def download_nvd_year(nvd_path, year):
  69. metaf = "nvdcve-%s-%s.meta" % (NVD_JSON_VERSION, year)
  70. path_metaf = os.path.join(nvd_path, metaf)
  71. jsonf_gz = "nvdcve-%s-%s.json.gz" % (NVD_JSON_VERSION, year)
  72. path_jsonf_gz = os.path.join(nvd_path, jsonf_gz)
  73. # If the database file is less than a day old, we assume the NVD data
  74. # locally available is recent enough.
  75. if os.path.exists(path_jsonf_gz) and os.stat(path_jsonf_gz).st_mtime >= time.time() - 86400:
  76. return path_jsonf_gz
  77. # If not, we download the meta file
  78. url = "%s/%s" % (NVD_BASE_URL, metaf)
  79. print("Getting %s" % url)
  80. page_meta = requests.get(url)
  81. page_meta.raise_for_status()
  82. # If the meta file already existed, we compare the existing
  83. # one with the data newly downloaded. If they are different,
  84. # we need to re-download the database.
  85. # If the database does not exist locally, we need to redownload it in
  86. # any case.
  87. if os.path.exists(path_metaf) and os.path.exists(path_jsonf_gz):
  88. meta_known = open(path_metaf, "r").read()
  89. if page_meta.text == meta_known:
  90. return path_jsonf_gz
  91. # Grab the compressed JSON NVD, and write files to disk
  92. url = "%s/%s" % (NVD_BASE_URL, jsonf_gz)
  93. print("Getting %s" % url)
  94. page_json = requests.get(url)
  95. page_json.raise_for_status()
  96. open(path_jsonf_gz, "wb").write(page_json.content)
  97. open(path_metaf, "w").write(page_meta.text)
  98. return path_jsonf_gz
  99. @classmethod
  100. def read_nvd_dir(cls, nvd_dir):
  101. """
  102. Iterate over all the CVEs contained in NIST Vulnerability Database
  103. feeds since NVD_START_YEAR. If the files are missing or outdated in
  104. nvd_dir, a fresh copy will be downloaded, and kept in .json.gz
  105. """
  106. for year in range(NVD_START_YEAR, datetime.datetime.now().year + 1):
  107. filename = CVE.download_nvd_year(nvd_dir, year)
  108. try:
  109. content = ijson.items(gzip.GzipFile(filename), 'CVE_Items.item')
  110. except: # noqa: E722
  111. print("ERROR: cannot read %s. Please remove the file then rerun this script" % filename)
  112. raise
  113. for cve in content:
  114. yield cls(cve)
  115. def each_product(self):
  116. """Iterate over each product section of this cve"""
  117. for vendor in self.nvd_cve['cve']['affects']['vendor']['vendor_data']:
  118. for product in vendor['product']['product_data']:
  119. yield product
  120. def parse_node(self, node):
  121. """
  122. Parse the node inside the configurations section to extract the
  123. cpe information usefull to know if a product is affected by
  124. the CVE. Actually only the product name and the version
  125. descriptor are needed, but we also provide the vendor name.
  126. """
  127. # The node containing the cpe entries matching the CVE can also
  128. # contain sub-nodes, so we need to manage it.
  129. for child in node.get('children', ()):
  130. for parsed_node in self.parse_node(child):
  131. yield parsed_node
  132. for cpe in node.get('cpe_match', ()):
  133. if not cpe['vulnerable']:
  134. return
  135. product = cpe_product(cpe['cpe23Uri'])
  136. version = cpe_version(cpe['cpe23Uri'])
  137. # ignore when product is '-', which means N/A
  138. if product == '-':
  139. return
  140. op_start = ''
  141. op_end = ''
  142. v_start = ''
  143. v_end = ''
  144. if version != '*' and version != '-':
  145. # Version is defined, this is a '=' match
  146. op_start = '='
  147. v_start = version
  148. else:
  149. # Parse start version, end version and operators
  150. if 'versionStartIncluding' in cpe:
  151. op_start = '>='
  152. v_start = cpe['versionStartIncluding']
  153. if 'versionStartExcluding' in cpe:
  154. op_start = '>'
  155. v_start = cpe['versionStartExcluding']
  156. if 'versionEndIncluding' in cpe:
  157. op_end = '<='
  158. v_end = cpe['versionEndIncluding']
  159. if 'versionEndExcluding' in cpe:
  160. op_end = '<'
  161. v_end = cpe['versionEndExcluding']
  162. yield {
  163. 'id': cpe['cpe23Uri'],
  164. 'v_start': v_start,
  165. 'op_start': op_start,
  166. 'v_end': v_end,
  167. 'op_end': op_end
  168. }
  169. def each_cpe(self):
  170. for node in self.nvd_cve['configurations']['nodes']:
  171. for cpe in self.parse_node(node):
  172. yield cpe
  173. @property
  174. def identifier(self):
  175. """The CVE unique identifier"""
  176. return self.nvd_cve['cve']['CVE_data_meta']['ID']
  177. @property
  178. def affected_products(self):
  179. """The set of CPE products referred by this CVE definition"""
  180. return set(cpe_product(p['id']) for p in self.each_cpe())
  181. def affects(self, name, version, cve_ignore_list, cpeid=None):
  182. """
  183. True if the Buildroot Package object passed as argument is affected
  184. by this CVE.
  185. """
  186. if self.identifier in cve_ignore_list:
  187. return self.CVE_DOESNT_AFFECT
  188. pkg_version = distutils.version.LooseVersion(version)
  189. if not hasattr(pkg_version, "version"):
  190. print("Cannot parse package '%s' version '%s'" % (name, version))
  191. pkg_version = None
  192. # if we don't have a cpeid, build one based on name and version
  193. if not cpeid:
  194. cpeid = "cpe:2.3:*:*:%s:%s:*:*:*:*:*:*:*" % (name, version)
  195. # if we have a cpeid, use its version instead of the package
  196. # version, as they might be different due to
  197. # <pkg>_CPE_ID_VERSION
  198. else:
  199. pkg_version = distutils.version.LooseVersion(cpe_version(cpeid))
  200. for cpe in self.each_cpe():
  201. if not cpe_matches(cpe['id'], cpeid):
  202. continue
  203. if not cpe['v_start'] and not cpe['v_end']:
  204. return self.CVE_AFFECTS
  205. if not pkg_version:
  206. continue
  207. if cpe['v_start']:
  208. try:
  209. cve_affected_version = distutils.version.LooseVersion(cpe['v_start'])
  210. inrange = ops.get(cpe['op_start'])(pkg_version, cve_affected_version)
  211. except TypeError:
  212. return self.CVE_UNKNOWN
  213. # current package version is before v_start, so we're
  214. # not affected by the CVE
  215. if not inrange:
  216. continue
  217. if cpe['v_end']:
  218. try:
  219. cve_affected_version = distutils.version.LooseVersion(cpe['v_end'])
  220. inrange = ops.get(cpe['op_end'])(pkg_version, cve_affected_version)
  221. except TypeError:
  222. return self.CVE_UNKNOWN
  223. # current package version is after v_end, so we're
  224. # not affected by the CVE
  225. if not inrange:
  226. continue
  227. # We're in the version range affected by this CVE
  228. return self.CVE_AFFECTS
  229. return self.CVE_DOESNT_AFFECT