cve.py 8.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244
  1. #!/usr/bin/env python
  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. except ImportError:
  29. sys.stderr.write("You need ijson to parse NVD for CVE check\n")
  30. exit(1)
  31. sys.path.append('utils/')
  32. NVD_START_YEAR = 2002
  33. NVD_JSON_VERSION = "1.1"
  34. NVD_BASE_URL = "https://nvd.nist.gov/feeds/json/cve/" + NVD_JSON_VERSION
  35. ops = {
  36. '>=': operator.ge,
  37. '>': operator.gt,
  38. '<=': operator.le,
  39. '<': operator.lt,
  40. '=': operator.eq
  41. }
  42. class CVE:
  43. """An accessor class for CVE Items in NVD files"""
  44. CVE_AFFECTS = 1
  45. CVE_DOESNT_AFFECT = 2
  46. CVE_UNKNOWN = 3
  47. def __init__(self, nvd_cve):
  48. """Initialize a CVE from its NVD JSON representation"""
  49. self.nvd_cve = nvd_cve
  50. @staticmethod
  51. def download_nvd_year(nvd_path, year):
  52. metaf = "nvdcve-%s-%s.meta" % (NVD_JSON_VERSION, year)
  53. path_metaf = os.path.join(nvd_path, metaf)
  54. jsonf_gz = "nvdcve-%s-%s.json.gz" % (NVD_JSON_VERSION, year)
  55. path_jsonf_gz = os.path.join(nvd_path, jsonf_gz)
  56. # If the database file is less than a day old, we assume the NVD data
  57. # locally available is recent enough.
  58. if os.path.exists(path_jsonf_gz) and os.stat(path_jsonf_gz).st_mtime >= time.time() - 86400:
  59. return path_jsonf_gz
  60. # If not, we download the meta file
  61. url = "%s/%s" % (NVD_BASE_URL, metaf)
  62. print("Getting %s" % url)
  63. page_meta = requests.get(url)
  64. page_meta.raise_for_status()
  65. # If the meta file already existed, we compare the existing
  66. # one with the data newly downloaded. If they are different,
  67. # we need to re-download the database.
  68. # If the database does not exist locally, we need to redownload it in
  69. # any case.
  70. if os.path.exists(path_metaf) and os.path.exists(path_jsonf_gz):
  71. meta_known = open(path_metaf, "r").read()
  72. if page_meta.text == meta_known:
  73. return path_jsonf_gz
  74. # Grab the compressed JSON NVD, and write files to disk
  75. url = "%s/%s" % (NVD_BASE_URL, jsonf_gz)
  76. print("Getting %s" % url)
  77. page_json = requests.get(url)
  78. page_json.raise_for_status()
  79. open(path_jsonf_gz, "wb").write(page_json.content)
  80. open(path_metaf, "w").write(page_meta.text)
  81. return path_jsonf_gz
  82. @classmethod
  83. def read_nvd_dir(cls, nvd_dir):
  84. """
  85. Iterate over all the CVEs contained in NIST Vulnerability Database
  86. feeds since NVD_START_YEAR. If the files are missing or outdated in
  87. nvd_dir, a fresh copy will be downloaded, and kept in .json.gz
  88. """
  89. for year in range(NVD_START_YEAR, datetime.datetime.now().year + 1):
  90. filename = CVE.download_nvd_year(nvd_dir, year)
  91. try:
  92. content = ijson.items(gzip.GzipFile(filename), 'CVE_Items.item')
  93. except: # noqa: E722
  94. print("ERROR: cannot read %s. Please remove the file then rerun this script" % filename)
  95. raise
  96. for cve in content:
  97. yield cls(cve)
  98. def each_product(self):
  99. """Iterate over each product section of this cve"""
  100. for vendor in self.nvd_cve['cve']['affects']['vendor']['vendor_data']:
  101. for product in vendor['product']['product_data']:
  102. yield product
  103. def parse_node(self, node):
  104. """
  105. Parse the node inside the configurations section to extract the
  106. cpe information usefull to know if a product is affected by
  107. the CVE. Actually only the product name and the version
  108. descriptor are needed, but we also provide the vendor name.
  109. """
  110. # The node containing the cpe entries matching the CVE can also
  111. # contain sub-nodes, so we need to manage it.
  112. for child in node.get('children', ()):
  113. for parsed_node in self.parse_node(child):
  114. yield parsed_node
  115. for cpe in node.get('cpe_match', ()):
  116. if not cpe['vulnerable']:
  117. return
  118. vendor, product, version = cpe['cpe23Uri'].split(':')[3:6]
  119. op_start = ''
  120. op_end = ''
  121. v_start = ''
  122. v_end = ''
  123. if version != '*' and version != '-':
  124. # Version is defined, this is a '=' match
  125. op_start = '='
  126. v_start = version
  127. elif version == '-':
  128. # no version information is available
  129. op_start = '='
  130. v_start = version
  131. else:
  132. # Parse start version, end version and operators
  133. if 'versionStartIncluding' in cpe:
  134. op_start = '>='
  135. v_start = cpe['versionStartIncluding']
  136. if 'versionStartExcluding' in cpe:
  137. op_start = '>'
  138. v_start = cpe['versionStartExcluding']
  139. if 'versionEndIncluding' in cpe:
  140. op_end = '<='
  141. v_end = cpe['versionEndIncluding']
  142. if 'versionEndExcluding' in cpe:
  143. op_end = '<'
  144. v_end = cpe['versionEndExcluding']
  145. yield {
  146. 'vendor': vendor,
  147. 'product': product,
  148. 'v_start': v_start,
  149. 'op_start': op_start,
  150. 'v_end': v_end,
  151. 'op_end': op_end
  152. }
  153. def each_cpe(self):
  154. for node in self.nvd_cve['configurations']['nodes']:
  155. for cpe in self.parse_node(node):
  156. yield cpe
  157. @property
  158. def identifier(self):
  159. """The CVE unique identifier"""
  160. return self.nvd_cve['cve']['CVE_data_meta']['ID']
  161. @property
  162. def pkg_names(self):
  163. """The set of package names referred by this CVE definition"""
  164. return set(p['product'] for p in self.each_cpe())
  165. def affects(self, name, version, cve_ignore_list):
  166. """
  167. True if the Buildroot Package object passed as argument is affected
  168. by this CVE.
  169. """
  170. if self.identifier in cve_ignore_list:
  171. return self.CVE_DOESNT_AFFECT
  172. pkg_version = distutils.version.LooseVersion(version)
  173. if not hasattr(pkg_version, "version"):
  174. print("Cannot parse package '%s' version '%s'" % (name, version))
  175. pkg_version = None
  176. for cpe in self.each_cpe():
  177. if cpe['product'] != name:
  178. continue
  179. if cpe['v_start'] == '-':
  180. return self.CVE_AFFECTS
  181. if not cpe['v_start'] and not cpe['v_end']:
  182. print("No CVE affected version")
  183. continue
  184. if not pkg_version:
  185. continue
  186. if cpe['v_start']:
  187. try:
  188. cve_affected_version = distutils.version.LooseVersion(cpe['v_start'])
  189. inrange = ops.get(cpe['op_start'])(pkg_version, cve_affected_version)
  190. except TypeError:
  191. return self.CVE_UNKNOWN
  192. # current package version is before v_start, so we're
  193. # not affected by the CVE
  194. if not inrange:
  195. continue
  196. if cpe['v_end']:
  197. try:
  198. cve_affected_version = distutils.version.LooseVersion(cpe['v_end'])
  199. inrange = ops.get(cpe['op_end'])(pkg_version, cve_affected_version)
  200. except TypeError:
  201. return self.CVE_UNKNOWN
  202. # current package version is after v_end, so we're
  203. # not affected by the CVE
  204. if not inrange:
  205. continue
  206. # We're in the version range affected by this CVE
  207. return self.CVE_AFFECTS
  208. return self.CVE_DOESNT_AFFECT