cve.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342
  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 distutils.version
  21. import json
  22. import subprocess
  23. import sys
  24. import operator
  25. sys.path.append('utils/')
  26. NVD_START_YEAR = 1999
  27. NVD_BASE_URL = "https://github.com/fkie-cad/nvd-json-data-feeds/"
  28. ops = {
  29. '>=': operator.ge,
  30. '>': operator.gt,
  31. '<=': operator.le,
  32. '<': operator.lt,
  33. '=': operator.eq
  34. }
  35. class CPE:
  36. DISJOINT = 0
  37. SUBSET = 1
  38. SUPERSET = 2
  39. EQUAL = 3
  40. ANY = '*'
  41. NA = '-'
  42. @staticmethod
  43. def compareAttribute(left, right):
  44. """
  45. This static method compare two single attributes part of two CPE.
  46. This is an implementation of table 6-2 of [1].
  47. Attribute that are empty will be matched to the '*' (ANY) attribute.
  48. According to [2] section 6.1.2.1.1 the empty attribute is inherited
  49. from CPE22 and now bind to ANY.
  50. The hyphen '-' bind to the NA attribute (see [2]).
  51. [1] https://nvlpubs.nist.gov/nistpubs/Legacy/IR/nistir7696.pdf
  52. [2] https://nvlpubs.nist.gov/nistpubs/Legacy/IR/nistir7695.pdf
  53. """
  54. if left == '':
  55. left = CPE.ANY
  56. if right == '':
  57. right = CPE.ANY
  58. if left == right:
  59. # 1 6 9 - equals
  60. return CPE.EQUAL
  61. elif left == CPE.ANY:
  62. # 2 3 4 - superset
  63. return CPE.SUPERSET
  64. elif left == CPE.NA and right == CPE.ANY:
  65. # 5 - subset
  66. return CPE.SUBSET
  67. elif left == CPE.NA:
  68. # 12 16 - disjoint
  69. return CPE.DISJOINT
  70. elif right == CPE.ANY:
  71. # 13 15 - subset
  72. return CPE.SUBSET
  73. return CPE.DISJOINT
  74. def matches(self, target) -> bool:
  75. """
  76. As an example let's take the example of CVE-2023-... for syslog-ng.
  77. One of the node as the following CPE criteria matched with the Buildroot CPE:
  78. cpe:2.3:a:oneidentitty:syslog-ng:*:*:*:*:-:*:*:*
  79. cpe:2.3:a:oneidentitty:syslog-ng:4.71:*:*:*:*:*:*:*
  80. vendor: EQUAL (3)
  81. product: EQUAL (3)
  82. version: SUPERSET (2)
  83. update: EQUAL (3)
  84. edition: EQUAL (3)
  85. language: EQUAL (3)
  86. sw_edition: SUBSET (1)
  87. ...
  88. This operation results in the two CPE matching.
  89. """
  90. if not isinstance(target, CPE):
  91. target = CPE(target)
  92. for selfAttribute, targetAttribute in zip(self.parts, target.parts):
  93. if CPE.compareAttribute(selfAttribute, targetAttribute) == CPE.DISJOINT:
  94. return False
  95. return True
  96. def __str__(self):
  97. return self.cpe
  98. def __init__(self, cpe):
  99. self.cpe = cpe
  100. self.parts = cpe.split(':')
  101. self.vendor = self.parts[3]
  102. self.product = self.parts[4]
  103. self.version = self.parts[5]
  104. self.update = self.parts[6]
  105. self.edition = self.parts[7]
  106. self.language = self.parts[8]
  107. self.sw_edition = self.parts[9]
  108. self.target_sw = self.parts[10]
  109. self.target_hw = self.parts[11]
  110. self.other = self.parts[12]
  111. class CVE:
  112. """An accessor class for CVE Items in NVD files"""
  113. CVE_AFFECTS = 1
  114. CVE_DOESNT_AFFECT = 2
  115. CVE_UNKNOWN = 3
  116. def __init__(self, nvd_cve):
  117. """Initialize a CVE from its NVD JSON representation"""
  118. self.nvd_cve = nvd_cve
  119. @staticmethod
  120. def download_nvd(nvd_dir):
  121. nvd_git_dir = os.path.join(nvd_dir, "git")
  122. if os.path.exists(nvd_git_dir):
  123. subprocess.check_call(
  124. ["git", "pull"],
  125. cwd=nvd_git_dir,
  126. stdout=subprocess.DEVNULL,
  127. stderr=subprocess.DEVNULL,
  128. )
  129. else:
  130. # Create the directory and its parents; git
  131. # happily clones into an empty directory.
  132. os.makedirs(nvd_git_dir)
  133. subprocess.check_call(
  134. ["git", "clone", NVD_BASE_URL, nvd_git_dir],
  135. stdout=subprocess.DEVNULL,
  136. stderr=subprocess.DEVNULL,
  137. )
  138. @staticmethod
  139. def sort_id(cve_ids):
  140. def cve_key(cve_id):
  141. year, id_ = cve_id.split('-')[1:]
  142. return (int(year), int(id_))
  143. return sorted(cve_ids, key=cve_key)
  144. @classmethod
  145. def read_nvd_dir(cls, nvd_dir):
  146. """
  147. Iterate over all the CVEs contained in NIST Vulnerability Database
  148. feeds since NVD_START_YEAR. If the files are missing or outdated in
  149. nvd_dir, a fresh copy will be downloaded, and kept in .json.gz
  150. """
  151. nvd_git_dir = os.path.join(nvd_dir, "git")
  152. for year in range(NVD_START_YEAR, datetime.datetime.now().year + 1):
  153. for dirpath, _, filenames in os.walk(os.path.join(nvd_git_dir, f"CVE-{year}")):
  154. for filename in filenames:
  155. if filename[-5:] != ".json":
  156. continue
  157. with open(os.path.join(dirpath, filename), "rb") as f:
  158. yield cls(json.load(f))
  159. @classmethod
  160. def read_nvd_entry(cls, nvd_dir, cve_id):
  161. """
  162. Retrieve a single CVE entry contained in NIST Vulnerability Database
  163. feeds.
  164. If the CVE entry doesn't exist 'None' is returned.
  165. """
  166. nvd_git_dir = os.path.join(nvd_dir, "git")
  167. _, year, minor = cve_id.split("-")
  168. cve_subpath = f"CVE-{year}/CVE-{year}-{minor[:-2] + 'xx'}/{cve_id.upper()}.json"
  169. path = os.path.join(nvd_git_dir, cve_subpath)
  170. ret = None
  171. if os.path.exists(path):
  172. with open(path, "rb") as f:
  173. ret = cls(json.load(f))
  174. return ret
  175. def parse_node(self, node):
  176. """
  177. Parse the node inside the configurations section to extract the
  178. cpe information useful to know if a product is affected by
  179. the CVE. Actually only the product name and the version
  180. descriptor are needed, but we also provide the vendor name.
  181. """
  182. # The node containing the cpe entries matching the CVE can also
  183. # contain sub-nodes, so we need to manage it.
  184. for child in node.get('children', ()):
  185. for parsed_node in self.parse_node(child):
  186. yield parsed_node
  187. for cpe in node.get('cpeMatch', ()):
  188. if not cpe['vulnerable']:
  189. return
  190. cpeId = CPE(cpe['criteria'])
  191. product = cpeId.product
  192. version = cpeId.version
  193. # ignore when product is '-', which means N/A
  194. if product == '-':
  195. return
  196. op_start = ''
  197. op_end = ''
  198. v_start = ''
  199. v_end = ''
  200. if version != '*' and version != '-':
  201. # Version is defined, this is a '=' match
  202. op_start = '='
  203. v_start = version
  204. else:
  205. # Parse start version, end version and operators
  206. if 'versionStartIncluding' in cpe:
  207. op_start = '>='
  208. v_start = cpe['versionStartIncluding']
  209. if 'versionStartExcluding' in cpe:
  210. op_start = '>'
  211. v_start = cpe['versionStartExcluding']
  212. if 'versionEndIncluding' in cpe:
  213. op_end = '<='
  214. v_end = cpe['versionEndIncluding']
  215. if 'versionEndExcluding' in cpe:
  216. op_end = '<'
  217. v_end = cpe['versionEndExcluding']
  218. yield {
  219. 'id': cpeId,
  220. 'v_start': v_start,
  221. 'op_start': op_start,
  222. 'v_end': v_end,
  223. 'op_end': op_end
  224. }
  225. def each_cpe(self):
  226. for nodes in self.nvd_cve.get('configurations', []):
  227. for node in nodes.get('nodes', []):
  228. for cpe in self.parse_node(node):
  229. yield cpe
  230. @property
  231. def identifier(self):
  232. """The CVE unique identifier"""
  233. return self.nvd_cve['id']
  234. @property
  235. def affected_products(self):
  236. """The set of CPE products referred by this CVE definition"""
  237. return set(p['id'].product for p in self.each_cpe())
  238. def affects(self, name, version, cpeid=None):
  239. """
  240. True if the Buildroot Package object passed as argument is affected
  241. by this CVE.
  242. """
  243. if cpeid is None:
  244. # if we don't have a cpeid, build one based on name and version
  245. cpeid = CPE("cpe:2.3:*:*:%s:%s:*:*:*:*:*:*:*" % (name, version))
  246. elif not isinstance(cpeid, CPE):
  247. cpeid = CPE(cpeid)
  248. # Always prefer the package version of the CPE ID.
  249. pkg_version = distutils.version.LooseVersion(cpeid.version)
  250. if not hasattr(pkg_version, "version"):
  251. print("Cannot parse package '%s' version '%s'" % (name, version), file=sys.stderr)
  252. pkg_version = None
  253. for cpe in self.each_cpe():
  254. if not cpe['id'].matches(cpeid):
  255. # If the node CPE id is not a subset of the target package we
  256. # don't check for affect
  257. continue
  258. if not cpe['v_start'] and not cpe['v_end']:
  259. return self.CVE_AFFECTS
  260. if not pkg_version:
  261. continue
  262. if cpe['v_start']:
  263. try:
  264. cve_affected_version = distutils.version.LooseVersion(cpe['v_start'])
  265. inrange = ops.get(cpe['op_start'])(pkg_version, cve_affected_version)
  266. except TypeError:
  267. return self.CVE_UNKNOWN
  268. # current package version is before v_start, so we're
  269. # not affected by the CVE
  270. if not inrange:
  271. continue
  272. if cpe['v_end']:
  273. try:
  274. cve_affected_version = distutils.version.LooseVersion(cpe['v_end'])
  275. inrange = ops.get(cpe['op_end'])(pkg_version, cve_affected_version)
  276. except TypeError:
  277. return self.CVE_UNKNOWN
  278. # current package version is after v_end, so we're
  279. # not affected by the CVE
  280. if not inrange:
  281. continue
  282. # We're in the version range affected by this CVE
  283. return self.CVE_AFFECTS
  284. return self.CVE_DOESNT_AFFECT