blob: 1425a405542d46cddb257ebc149192606cb95bdb [file] [log] [blame]
Patrick Williamsc0f7c042017-02-23 20:41:17 -06001# This class is used to check recipes against public CVEs.
2#
3# In order to use this class just inherit the class in the
4# local.conf file and it will add the cve_check task for
5# every recipe. The task can be used per recipe, per image,
6# or using the special cases "world" and "universe". The
7# cve_check task will print a warning for every unpatched
8# CVE found and generate a file in the recipe WORKDIR/cve
9# directory. If an image is build it will generate a report
10# in DEPLOY_DIR_IMAGE for all the packages used.
11#
12# Example:
13# bitbake -c cve_check openssl
14# bitbake core-image-sato
15# bitbake -k -c cve_check universe
16#
17# DISCLAIMER
18#
19# This class/tool is meant to be used as support and not
20# the only method to check against CVEs. Running this tool
21# doesn't guarantee your packages are free of CVEs.
22
23CVE_CHECK_DB_DIR ?= "${DL_DIR}/CVE_CHECK"
24CVE_CHECK_DB_FILE ?= "${CVE_CHECK_DB_DIR}/nvd.db"
25
26CVE_CHECK_LOCAL_DIR ?= "${WORKDIR}/cve"
27CVE_CHECK_LOCAL_FILE ?= "${CVE_CHECK_LOCAL_DIR}/cve.log"
28CVE_CHECK_TMP_FILE ?= "${TMPDIR}/cve_check"
29
30CVE_CHECK_DIR ??= "${DEPLOY_DIR}/cve"
31CVE_CHECK_MANIFEST ?= "${DEPLOY_DIR_IMAGE}/${IMAGE_NAME}${IMAGE_NAME_SUFFIX}.cve"
32CVE_CHECK_COPY_FILES ??= "1"
33CVE_CHECK_CREATE_MANIFEST ??= "1"
34
35# Whitelist for packages (PN)
36CVE_CHECK_PN_WHITELIST = "\
37 glibc-locale \
38"
39
40# Whitelist for CVE and version of package
41CVE_CHECK_CVE_WHITELIST = "{\
42 'CVE-2014-2524': ('6.3',), \
43}"
44
45python do_cve_check () {
46 """
47 Check recipe for patched and unpatched CVEs
48 """
49
50 if os.path.exists(d.getVar("CVE_CHECK_TMP_FILE", True)):
51 patched_cves = get_patches_cves(d)
52 patched, unpatched = check_cves(d, patched_cves)
53 if patched or unpatched:
54 cve_data = get_cve_info(d, patched + unpatched)
55 cve_write_data(d, patched, unpatched, cve_data)
56 else:
57 bb.note("Failed to update CVE database, skipping CVE check")
58}
59
60addtask cve_check after do_unpack before do_build
61do_cve_check[depends] = "cve-check-tool-native:do_populate_cve_db"
62do_cve_check[nostamp] = "1"
63
64python cve_check_cleanup () {
65 """
66 Delete the file used to gather all the CVE information.
67 """
68
69 bb.utils.remove(e.data.getVar("CVE_CHECK_TMP_FILE", True))
70}
71
72addhandler cve_check_cleanup
73cve_check_cleanup[eventmask] = "bb.cooker.CookerExit"
74
75python cve_check_write_rootfs_manifest () {
76 """
77 Create CVE manifest when building an image
78 """
79
80 import shutil
81
82 if os.path.exists(d.getVar("CVE_CHECK_TMP_FILE", True)):
83 bb.note("Writing rootfs CVE manifest")
84 deploy_dir = d.getVar("DEPLOY_DIR_IMAGE", True)
85 link_name = d.getVar("IMAGE_LINK_NAME", True)
86 manifest_name = d.getVar("CVE_CHECK_MANIFEST", True)
87 cve_tmp_file = d.getVar("CVE_CHECK_TMP_FILE", True)
88
89 shutil.copyfile(cve_tmp_file, manifest_name)
90
91 if manifest_name and os.path.exists(manifest_name):
92 manifest_link = os.path.join(deploy_dir, "%s.cve" % link_name)
93 # If we already have another manifest, update symlinks
94 if os.path.exists(os.path.realpath(manifest_link)):
95 os.remove(manifest_link)
96 os.symlink(os.path.basename(manifest_name), manifest_link)
97 bb.plain("Image CVE report stored in: %s" % manifest_name)
98}
99
100ROOTFS_POSTPROCESS_COMMAND_prepend = "${@'cve_check_write_rootfs_manifest; ' if d.getVar('CVE_CHECK_CREATE_MANIFEST', True) == '1' else ''}"
101
102def get_patches_cves(d):
103 """
104 Get patches that solve CVEs using the "CVE: " tag.
105 """
106
107 import re
108
109 pn = d.getVar("PN", True)
110 cve_match = re.compile("CVE:( CVE\-\d{4}\-\d+)+")
111 patched_cves = set()
112 bb.debug(2, "Looking for patches that solves CVEs for %s" % pn)
113 for url in src_patches(d):
114 patch_file = bb.fetch.decodeurl(url)[2]
115 with open(patch_file, "r", encoding="utf-8") as f:
116 try:
117 patch_text = f.read()
118 except UnicodeDecodeError:
119 bb.debug(1, "Failed to read patch %s using UTF-8 encoding"
120 " trying with iso8859-1" % patch_file)
121 f.close()
122 with open(patch_file, "r", encoding="iso8859-1") as f:
123 patch_text = f.read()
124
125 # Search for the "CVE: " line
126 match = cve_match.search(patch_text)
127 if match:
128 # Get only the CVEs without the "CVE: " tag
129 cves = patch_text[match.start()+5:match.end()]
130 for cve in cves.split():
131 bb.debug(2, "Patch %s solves %s" % (patch_file, cve))
132 patched_cves.add(cve)
133 else:
134 bb.debug(2, "Patch %s doesn't solve CVEs" % patch_file)
135
136 return patched_cves
137
138def check_cves(d, patched_cves):
139 """
140 Run cve-check-tool looking for patched and unpatched CVEs.
141 """
142
143 import ast, csv, tempfile, subprocess, io
144
145 cves_patched = []
146 cves_unpatched = []
147 bpn = d.getVar("BPN", True)
148 pv = d.getVar("PV", True).split("git+")[0]
149 cves = " ".join(patched_cves)
150 cve_db_dir = d.getVar("CVE_CHECK_DB_DIR", True)
151 cve_whitelist = ast.literal_eval(d.getVar("CVE_CHECK_CVE_WHITELIST", True))
152 cve_cmd = "cve-check-tool"
153 cmd = [cve_cmd, "--no-html", "--csv", "--not-affected", "-t", "faux", "-d", cve_db_dir]
154
155 # If the recipe has been whitlisted we return empty lists
156 if d.getVar("PN", True) in d.getVar("CVE_CHECK_PN_WHITELIST", True).split():
157 bb.note("Recipe has been whitelisted, skipping check")
158 return ([], [])
159
160 # It is needed to export the proxies to download the database using HTTP
161 bb.utils.export_proxies(d)
162
163 try:
164 # Write the faux CSV file to be used with cve-check-tool
165 fd, faux = tempfile.mkstemp(prefix="cve-faux-")
166 with os.fdopen(fd, "w") as f:
167 f.write("%s,%s,%s," % (bpn, pv, cves))
168 cmd.append(faux)
169
170 output = subprocess.check_output(cmd, stderr=subprocess.STDOUT).decode("utf-8")
171 bb.debug(2, "Output of command %s:\n%s" % ("\n".join(cmd), output))
172 except subprocess.CalledProcessError as e:
173 bb.warn("Couldn't check for CVEs: %s (output %s)" % (e, e.output))
174 finally:
175 os.remove(faux)
176
177 for row in csv.reader(io.StringIO(output)):
178 # Third row has the unpatched CVEs
179 if row[2]:
180 for cve in row[2].split():
181 # Skip if the CVE has been whitlisted for the current version
182 if pv in cve_whitelist.get(cve,[]):
183 bb.note("%s-%s has been whitelisted for %s" % (bpn, pv, cve))
184 else:
185 cves_unpatched.append(cve)
186 bb.debug(2, "%s-%s is not patched for %s" % (bpn, pv, cve))
187 # Fourth row has patched CVEs
188 if row[3]:
189 for cve in row[3].split():
190 cves_patched.append(cve)
191 bb.debug(2, "%s-%s is patched for %s" % (bpn, pv, cve))
192
193 return (cves_patched, cves_unpatched)
194
195def get_cve_info(d, cves):
196 """
197 Get CVE information from the database used by cve-check-tool.
198
199 Unfortunately the only way to get CVE info is set the output to
200 html (hard to parse) or query directly the database.
201 """
202
203 try:
204 import sqlite3
205 except ImportError:
206 from pysqlite2 import dbapi2 as sqlite3
207
208 cve_data = {}
209 db_file = d.getVar("CVE_CHECK_DB_FILE", True)
210 placeholder = ",".join("?" * len(cves))
211 query = "SELECT * FROM NVD WHERE id IN (%s)" % placeholder
212 conn = sqlite3.connect(db_file)
213 cur = conn.cursor()
214 for row in cur.execute(query, tuple(cves)):
215 cve_data[row[0]] = {}
216 cve_data[row[0]]["summary"] = row[1]
217 cve_data[row[0]]["score"] = row[2]
218 cve_data[row[0]]["modified"] = row[3]
219 cve_data[row[0]]["vector"] = row[4]
220 conn.close()
221
222 return cve_data
223
224def cve_write_data(d, patched, unpatched, cve_data):
225 """
226 Write CVE information in WORKDIR; and to CVE_CHECK_DIR, and
227 CVE manifest if enabled.
228 """
229
230 cve_file = d.getVar("CVE_CHECK_LOCAL_FILE", True)
231 nvd_link = "https://web.nvd.nist.gov/view/vuln/detail?vulnId="
232 write_string = ""
233 first_alert = True
234 bb.utils.mkdirhier(d.getVar("CVE_CHECK_LOCAL_DIR", True))
235
236 for cve in sorted(cve_data):
237 write_string += "PACKAGE NAME: %s\n" % d.getVar("PN", True)
238 write_string += "PACKAGE VERSION: %s\n" % d.getVar("PV", True)
239 write_string += "CVE: %s\n" % cve
240 if cve in patched:
241 write_string += "CVE STATUS: Patched\n"
242 else:
243 write_string += "CVE STATUS: Unpatched\n"
244 if first_alert:
245 bb.warn("Found unpatched CVE, for more information check %s" % cve_file)
246 first_alert = False
247 write_string += "CVE SUMMARY: %s\n" % cve_data[cve]["summary"]
248 write_string += "CVSS v2 BASE SCORE: %s\n" % cve_data[cve]["score"]
249 write_string += "VECTOR: %s\n" % cve_data[cve]["vector"]
250 write_string += "MORE INFORMATION: %s%s\n\n" % (nvd_link, cve)
251
252 with open(cve_file, "w") as f:
253 bb.note("Writing file %s with CVE information" % cve_file)
254 f.write(write_string)
255
256 if d.getVar("CVE_CHECK_COPY_FILES", True) == "1":
257 cve_dir = d.getVar("CVE_CHECK_DIR", True)
258 bb.utils.mkdirhier(cve_dir)
259 deploy_file = os.path.join(cve_dir, d.getVar("PN", True))
260 with open(deploy_file, "w") as f:
261 f.write(write_string)
262
263 if d.getVar("CVE_CHECK_CREATE_MANIFEST", True) == "1":
264 with open(d.getVar("CVE_CHECK_TMP_FILE", True), "a") as f:
265 f.write("%s" % write_string)