xref: /OK3568_Linux_fs/yocto/poky/meta/classes/cve-check.bbclass (revision 4882a59341e53eb6f0b4789bf948001014eff981)
1*4882a593Smuzhiyun# This class is used to check recipes against public CVEs.
2*4882a593Smuzhiyun#
3*4882a593Smuzhiyun# In order to use this class just inherit the class in the
4*4882a593Smuzhiyun# local.conf file and it will add the cve_check task for
5*4882a593Smuzhiyun# every recipe. The task can be used per recipe, per image,
6*4882a593Smuzhiyun# or using the special cases "world" and "universe". The
7*4882a593Smuzhiyun# cve_check task will print a warning for every unpatched
8*4882a593Smuzhiyun# CVE found and generate a file in the recipe WORKDIR/cve
9*4882a593Smuzhiyun# directory. If an image is build it will generate a report
10*4882a593Smuzhiyun# in DEPLOY_DIR_IMAGE for all the packages used.
11*4882a593Smuzhiyun#
12*4882a593Smuzhiyun# Example:
13*4882a593Smuzhiyun#   bitbake -c cve_check openssl
14*4882a593Smuzhiyun#   bitbake core-image-sato
15*4882a593Smuzhiyun#   bitbake -k -c cve_check universe
16*4882a593Smuzhiyun#
17*4882a593Smuzhiyun# DISCLAIMER
18*4882a593Smuzhiyun#
19*4882a593Smuzhiyun# This class/tool is meant to be used as support and not
20*4882a593Smuzhiyun# the only method to check against CVEs. Running this tool
21*4882a593Smuzhiyun# doesn't guarantee your packages are free of CVEs.
22*4882a593Smuzhiyun
23*4882a593Smuzhiyun# The product name that the CVE database uses defaults to BPN, but may need to
24*4882a593Smuzhiyun# be overriden per recipe (for example tiff.bb sets CVE_PRODUCT=libtiff).
25*4882a593SmuzhiyunCVE_PRODUCT ??= "${BPN}"
26*4882a593SmuzhiyunCVE_VERSION ??= "${PV}"
27*4882a593Smuzhiyun
28*4882a593SmuzhiyunCVE_CHECK_DB_DIR ?= "${DL_DIR}/CVE_CHECK"
29*4882a593SmuzhiyunCVE_CHECK_DB_FILE ?= "${CVE_CHECK_DB_DIR}/nvdcve_1.1.db"
30*4882a593SmuzhiyunCVE_CHECK_DB_FILE_LOCK ?= "${CVE_CHECK_DB_FILE}.lock"
31*4882a593Smuzhiyun
32*4882a593SmuzhiyunCVE_CHECK_LOG ?= "${T}/cve.log"
33*4882a593SmuzhiyunCVE_CHECK_TMP_FILE ?= "${TMPDIR}/cve_check"
34*4882a593SmuzhiyunCVE_CHECK_SUMMARY_DIR ?= "${LOG_DIR}/cve"
35*4882a593SmuzhiyunCVE_CHECK_SUMMARY_FILE_NAME ?= "cve-summary"
36*4882a593SmuzhiyunCVE_CHECK_SUMMARY_FILE ?= "${CVE_CHECK_SUMMARY_DIR}/${CVE_CHECK_SUMMARY_FILE_NAME}"
37*4882a593SmuzhiyunCVE_CHECK_SUMMARY_FILE_NAME_JSON = "cve-summary.json"
38*4882a593SmuzhiyunCVE_CHECK_SUMMARY_INDEX_PATH = "${CVE_CHECK_SUMMARY_DIR}/cve-summary-index.txt"
39*4882a593Smuzhiyun
40*4882a593SmuzhiyunCVE_CHECK_LOG_JSON ?= "${T}/cve.json"
41*4882a593Smuzhiyun
42*4882a593SmuzhiyunCVE_CHECK_DIR ??= "${DEPLOY_DIR}/cve"
43*4882a593SmuzhiyunCVE_CHECK_RECIPE_FILE ?= "${CVE_CHECK_DIR}/${PN}"
44*4882a593SmuzhiyunCVE_CHECK_RECIPE_FILE_JSON ?= "${CVE_CHECK_DIR}/${PN}_cve.json"
45*4882a593SmuzhiyunCVE_CHECK_MANIFEST ?= "${IMGDEPLOYDIR}/${IMAGE_NAME}${IMAGE_NAME_SUFFIX}.cve"
46*4882a593SmuzhiyunCVE_CHECK_MANIFEST_JSON ?= "${IMGDEPLOYDIR}/${IMAGE_NAME}${IMAGE_NAME_SUFFIX}.json"
47*4882a593SmuzhiyunCVE_CHECK_COPY_FILES ??= "1"
48*4882a593SmuzhiyunCVE_CHECK_CREATE_MANIFEST ??= "1"
49*4882a593Smuzhiyun
50*4882a593Smuzhiyun# Report Patched or Ignored CVEs
51*4882a593SmuzhiyunCVE_CHECK_REPORT_PATCHED ??= "1"
52*4882a593Smuzhiyun
53*4882a593SmuzhiyunCVE_CHECK_SHOW_WARNINGS ??= "1"
54*4882a593Smuzhiyun
55*4882a593Smuzhiyun# Provide text output
56*4882a593SmuzhiyunCVE_CHECK_FORMAT_TEXT ??= "1"
57*4882a593Smuzhiyun
58*4882a593Smuzhiyun# Provide JSON output
59*4882a593SmuzhiyunCVE_CHECK_FORMAT_JSON ??= "1"
60*4882a593Smuzhiyun
61*4882a593Smuzhiyun# Check for packages without CVEs (no issues or missing product name)
62*4882a593SmuzhiyunCVE_CHECK_COVERAGE ??= "1"
63*4882a593Smuzhiyun
64*4882a593Smuzhiyun# Skip CVE Check for packages (PN)
65*4882a593SmuzhiyunCVE_CHECK_SKIP_RECIPE ?= ""
66*4882a593Smuzhiyun
67*4882a593Smuzhiyun# Ingore the check for a given list of CVEs. If a CVE is found,
68*4882a593Smuzhiyun# then it is considered patched. The value is a string containing
69*4882a593Smuzhiyun# space separated CVE values:
70*4882a593Smuzhiyun#
71*4882a593Smuzhiyun# CVE_CHECK_IGNORE = 'CVE-2014-2524 CVE-2018-1234'
72*4882a593Smuzhiyun#
73*4882a593SmuzhiyunCVE_CHECK_IGNORE ?= ""
74*4882a593Smuzhiyun
75*4882a593Smuzhiyun# Layers to be excluded
76*4882a593SmuzhiyunCVE_CHECK_LAYER_EXCLUDELIST ??= ""
77*4882a593Smuzhiyun
78*4882a593Smuzhiyun# Layers to be included
79*4882a593SmuzhiyunCVE_CHECK_LAYER_INCLUDELIST ??= ""
80*4882a593Smuzhiyun
81*4882a593Smuzhiyun
82*4882a593Smuzhiyun# set to "alphabetical" for version using single alphabetical character as increment release
83*4882a593SmuzhiyunCVE_VERSION_SUFFIX ??= ""
84*4882a593Smuzhiyun
85*4882a593Smuzhiyundef generate_json_report(d, out_path, link_path):
86*4882a593Smuzhiyun    if os.path.exists(d.getVar("CVE_CHECK_SUMMARY_INDEX_PATH")):
87*4882a593Smuzhiyun        import json
88*4882a593Smuzhiyun        from oe.cve_check import cve_check_merge_jsons, update_symlinks
89*4882a593Smuzhiyun
90*4882a593Smuzhiyun        bb.note("Generating JSON CVE summary")
91*4882a593Smuzhiyun        index_file = d.getVar("CVE_CHECK_SUMMARY_INDEX_PATH")
92*4882a593Smuzhiyun        summary = {"version":"1", "package": []}
93*4882a593Smuzhiyun        with open(index_file) as f:
94*4882a593Smuzhiyun            filename = f.readline()
95*4882a593Smuzhiyun            while filename:
96*4882a593Smuzhiyun                with open(filename.rstrip()) as j:
97*4882a593Smuzhiyun                    data = json.load(j)
98*4882a593Smuzhiyun                    cve_check_merge_jsons(summary, data)
99*4882a593Smuzhiyun                filename = f.readline()
100*4882a593Smuzhiyun
101*4882a593Smuzhiyun        with open(out_path, "w") as f:
102*4882a593Smuzhiyun            json.dump(summary, f, indent=2)
103*4882a593Smuzhiyun
104*4882a593Smuzhiyun        update_symlinks(out_path, link_path)
105*4882a593Smuzhiyun
106*4882a593Smuzhiyunpython cve_save_summary_handler () {
107*4882a593Smuzhiyun    import shutil
108*4882a593Smuzhiyun    import datetime
109*4882a593Smuzhiyun    from oe.cve_check import update_symlinks
110*4882a593Smuzhiyun
111*4882a593Smuzhiyun    cve_tmp_file = d.getVar("CVE_CHECK_TMP_FILE")
112*4882a593Smuzhiyun
113*4882a593Smuzhiyun    cve_summary_name = d.getVar("CVE_CHECK_SUMMARY_FILE_NAME")
114*4882a593Smuzhiyun    cvelogpath = d.getVar("CVE_CHECK_SUMMARY_DIR")
115*4882a593Smuzhiyun    bb.utils.mkdirhier(cvelogpath)
116*4882a593Smuzhiyun
117*4882a593Smuzhiyun    timestamp = datetime.datetime.now().strftime('%Y%m%d%H%M%S')
118*4882a593Smuzhiyun    cve_summary_file = os.path.join(cvelogpath, "%s-%s.txt" % (cve_summary_name, timestamp))
119*4882a593Smuzhiyun
120*4882a593Smuzhiyun    if os.path.exists(cve_tmp_file):
121*4882a593Smuzhiyun        shutil.copyfile(cve_tmp_file, cve_summary_file)
122*4882a593Smuzhiyun        cvefile_link = os.path.join(cvelogpath, cve_summary_name)
123*4882a593Smuzhiyun        update_symlinks(cve_summary_file, cvefile_link)
124*4882a593Smuzhiyun        bb.plain("Complete CVE report summary created at: %s" % cvefile_link)
125*4882a593Smuzhiyun
126*4882a593Smuzhiyun    if d.getVar("CVE_CHECK_FORMAT_JSON") == "1":
127*4882a593Smuzhiyun        json_summary_link_name = os.path.join(cvelogpath, d.getVar("CVE_CHECK_SUMMARY_FILE_NAME_JSON"))
128*4882a593Smuzhiyun        json_summary_name = os.path.join(cvelogpath, "%s-%s.json" % (cve_summary_name, timestamp))
129*4882a593Smuzhiyun        generate_json_report(d, json_summary_name, json_summary_link_name)
130*4882a593Smuzhiyun        bb.plain("Complete CVE JSON report summary created at: %s" % json_summary_link_name)
131*4882a593Smuzhiyun}
132*4882a593Smuzhiyun
133*4882a593Smuzhiyunaddhandler cve_save_summary_handler
134*4882a593Smuzhiyuncve_save_summary_handler[eventmask] = "bb.event.BuildCompleted"
135*4882a593Smuzhiyun
136*4882a593Smuzhiyunpython do_cve_check () {
137*4882a593Smuzhiyun    """
138*4882a593Smuzhiyun    Check recipe for patched and unpatched CVEs
139*4882a593Smuzhiyun    """
140*4882a593Smuzhiyun    from oe.cve_check import get_patched_cves
141*4882a593Smuzhiyun
142*4882a593Smuzhiyun    with bb.utils.fileslocked([d.getVar("CVE_CHECK_DB_FILE_LOCK")], shared=True):
143*4882a593Smuzhiyun        if os.path.exists(d.getVar("CVE_CHECK_DB_FILE")):
144*4882a593Smuzhiyun            try:
145*4882a593Smuzhiyun                patched_cves = get_patched_cves(d)
146*4882a593Smuzhiyun            except FileNotFoundError:
147*4882a593Smuzhiyun                bb.fatal("Failure in searching patches")
148*4882a593Smuzhiyun            ignored, patched, unpatched, status = check_cves(d, patched_cves)
149*4882a593Smuzhiyun            if patched or unpatched or (d.getVar("CVE_CHECK_COVERAGE") == "1" and status):
150*4882a593Smuzhiyun                cve_data = get_cve_info(d, patched + unpatched + ignored)
151*4882a593Smuzhiyun                cve_write_data(d, patched, unpatched, ignored, cve_data, status)
152*4882a593Smuzhiyun        else:
153*4882a593Smuzhiyun            bb.note("No CVE database found, skipping CVE check")
154*4882a593Smuzhiyun
155*4882a593Smuzhiyun}
156*4882a593Smuzhiyun
157*4882a593Smuzhiyunaddtask cve_check before do_build
158*4882a593Smuzhiyundo_cve_check[depends] = "cve-update-db-native:do_fetch"
159*4882a593Smuzhiyundo_cve_check[nostamp] = "1"
160*4882a593Smuzhiyun
161*4882a593Smuzhiyunpython cve_check_cleanup () {
162*4882a593Smuzhiyun    """
163*4882a593Smuzhiyun    Delete the file used to gather all the CVE information.
164*4882a593Smuzhiyun    """
165*4882a593Smuzhiyun    bb.utils.remove(e.data.getVar("CVE_CHECK_TMP_FILE"))
166*4882a593Smuzhiyun    bb.utils.remove(e.data.getVar("CVE_CHECK_SUMMARY_INDEX_PATH"))
167*4882a593Smuzhiyun}
168*4882a593Smuzhiyun
169*4882a593Smuzhiyunaddhandler cve_check_cleanup
170*4882a593Smuzhiyuncve_check_cleanup[eventmask] = "bb.event.BuildCompleted"
171*4882a593Smuzhiyun
172*4882a593Smuzhiyunpython cve_check_write_rootfs_manifest () {
173*4882a593Smuzhiyun    """
174*4882a593Smuzhiyun    Create CVE manifest when building an image
175*4882a593Smuzhiyun    """
176*4882a593Smuzhiyun
177*4882a593Smuzhiyun    import shutil
178*4882a593Smuzhiyun    import json
179*4882a593Smuzhiyun    from oe.rootfs import image_list_installed_packages
180*4882a593Smuzhiyun    from oe.cve_check import cve_check_merge_jsons, update_symlinks
181*4882a593Smuzhiyun
182*4882a593Smuzhiyun    if d.getVar("CVE_CHECK_COPY_FILES") == "1":
183*4882a593Smuzhiyun        deploy_file = d.getVar("CVE_CHECK_RECIPE_FILE")
184*4882a593Smuzhiyun        if os.path.exists(deploy_file):
185*4882a593Smuzhiyun            bb.utils.remove(deploy_file)
186*4882a593Smuzhiyun        deploy_file_json = d.getVar("CVE_CHECK_RECIPE_FILE_JSON")
187*4882a593Smuzhiyun        if os.path.exists(deploy_file_json):
188*4882a593Smuzhiyun            bb.utils.remove(deploy_file_json)
189*4882a593Smuzhiyun
190*4882a593Smuzhiyun    # Create a list of relevant recipies
191*4882a593Smuzhiyun    recipies = set()
192*4882a593Smuzhiyun    for pkg in list(image_list_installed_packages(d)):
193*4882a593Smuzhiyun        pkg_info = os.path.join(d.getVar('PKGDATA_DIR'),
194*4882a593Smuzhiyun                                'runtime-reverse', pkg)
195*4882a593Smuzhiyun        pkg_data = oe.packagedata.read_pkgdatafile(pkg_info)
196*4882a593Smuzhiyun        recipies.add(pkg_data["PN"])
197*4882a593Smuzhiyun
198*4882a593Smuzhiyun    bb.note("Writing rootfs CVE manifest")
199*4882a593Smuzhiyun    deploy_dir = d.getVar("IMGDEPLOYDIR")
200*4882a593Smuzhiyun    link_name = d.getVar("IMAGE_LINK_NAME")
201*4882a593Smuzhiyun
202*4882a593Smuzhiyun    json_data = {"version":"1", "package": []}
203*4882a593Smuzhiyun    text_data = ""
204*4882a593Smuzhiyun    enable_json = d.getVar("CVE_CHECK_FORMAT_JSON") == "1"
205*4882a593Smuzhiyun    enable_text = d.getVar("CVE_CHECK_FORMAT_TEXT") == "1"
206*4882a593Smuzhiyun
207*4882a593Smuzhiyun    save_pn = d.getVar("PN")
208*4882a593Smuzhiyun
209*4882a593Smuzhiyun    for pkg in recipies:
210*4882a593Smuzhiyun        # To be able to use the CVE_CHECK_RECIPE_FILE variable we have to evaluate
211*4882a593Smuzhiyun        # it with the different PN names set each time.
212*4882a593Smuzhiyun        d.setVar("PN", pkg)
213*4882a593Smuzhiyun        if enable_text:
214*4882a593Smuzhiyun            pkgfilepath = d.getVar("CVE_CHECK_RECIPE_FILE")
215*4882a593Smuzhiyun            if os.path.exists(pkgfilepath):
216*4882a593Smuzhiyun                with open(pkgfilepath) as pfile:
217*4882a593Smuzhiyun                    text_data += pfile.read()
218*4882a593Smuzhiyun
219*4882a593Smuzhiyun        if enable_json:
220*4882a593Smuzhiyun            pkgfilepath = d.getVar("CVE_CHECK_RECIPE_FILE_JSON")
221*4882a593Smuzhiyun            if os.path.exists(pkgfilepath):
222*4882a593Smuzhiyun                with open(pkgfilepath) as j:
223*4882a593Smuzhiyun                    data = json.load(j)
224*4882a593Smuzhiyun                    cve_check_merge_jsons(json_data, data)
225*4882a593Smuzhiyun
226*4882a593Smuzhiyun    d.setVar("PN", save_pn)
227*4882a593Smuzhiyun
228*4882a593Smuzhiyun    if enable_text:
229*4882a593Smuzhiyun        link_path = os.path.join(deploy_dir, "%s.cve" % link_name)
230*4882a593Smuzhiyun        manifest_name = d.getVar("CVE_CHECK_MANIFEST")
231*4882a593Smuzhiyun
232*4882a593Smuzhiyun        with open(manifest_name, "w") as f:
233*4882a593Smuzhiyun            f.write(text_data)
234*4882a593Smuzhiyun
235*4882a593Smuzhiyun        update_symlinks(manifest_name, link_path)
236*4882a593Smuzhiyun        bb.plain("Image CVE report stored in: %s" % manifest_name)
237*4882a593Smuzhiyun
238*4882a593Smuzhiyun    if enable_json:
239*4882a593Smuzhiyun        link_path = os.path.join(deploy_dir, "%s.json" % link_name)
240*4882a593Smuzhiyun        manifest_name = d.getVar("CVE_CHECK_MANIFEST_JSON")
241*4882a593Smuzhiyun
242*4882a593Smuzhiyun        with open(manifest_name, "w") as f:
243*4882a593Smuzhiyun            json.dump(json_data, f, indent=2)
244*4882a593Smuzhiyun
245*4882a593Smuzhiyun        update_symlinks(manifest_name, link_path)
246*4882a593Smuzhiyun        bb.plain("Image CVE JSON report stored in: %s" % manifest_name)
247*4882a593Smuzhiyun}
248*4882a593Smuzhiyun
249*4882a593SmuzhiyunROOTFS_POSTPROCESS_COMMAND:prepend = "${@'cve_check_write_rootfs_manifest; ' if d.getVar('CVE_CHECK_CREATE_MANIFEST') == '1' else ''}"
250*4882a593Smuzhiyundo_rootfs[recrdeptask] += "${@'do_cve_check' if d.getVar('CVE_CHECK_CREATE_MANIFEST') == '1' else ''}"
251*4882a593Smuzhiyundo_populate_sdk[recrdeptask] += "${@'do_cve_check' if d.getVar('CVE_CHECK_CREATE_MANIFEST') == '1' else ''}"
252*4882a593Smuzhiyun
253*4882a593Smuzhiyundef check_cves(d, patched_cves):
254*4882a593Smuzhiyun    """
255*4882a593Smuzhiyun    Connect to the NVD database and find unpatched cves.
256*4882a593Smuzhiyun    """
257*4882a593Smuzhiyun    from oe.cve_check import Version, convert_cve_version
258*4882a593Smuzhiyun
259*4882a593Smuzhiyun    pn = d.getVar("PN")
260*4882a593Smuzhiyun    real_pv = d.getVar("PV")
261*4882a593Smuzhiyun    suffix = d.getVar("CVE_VERSION_SUFFIX")
262*4882a593Smuzhiyun
263*4882a593Smuzhiyun    cves_unpatched = []
264*4882a593Smuzhiyun    cves_ignored = []
265*4882a593Smuzhiyun    cves_status = []
266*4882a593Smuzhiyun    cves_in_recipe = False
267*4882a593Smuzhiyun    # CVE_PRODUCT can contain more than one product (eg. curl/libcurl)
268*4882a593Smuzhiyun    products = d.getVar("CVE_PRODUCT").split()
269*4882a593Smuzhiyun    # If this has been unset then we're not scanning for CVEs here (for example, image recipes)
270*4882a593Smuzhiyun    if not products:
271*4882a593Smuzhiyun        return ([], [], [], [])
272*4882a593Smuzhiyun    pv = d.getVar("CVE_VERSION").split("+git")[0]
273*4882a593Smuzhiyun
274*4882a593Smuzhiyun    # If the recipe has been skipped/ignored we return empty lists
275*4882a593Smuzhiyun    if pn in d.getVar("CVE_CHECK_SKIP_RECIPE").split():
276*4882a593Smuzhiyun        bb.note("Recipe has been skipped by cve-check")
277*4882a593Smuzhiyun        return ([], [], [], [])
278*4882a593Smuzhiyun
279*4882a593Smuzhiyun    cve_ignore = d.getVar("CVE_CHECK_IGNORE").split()
280*4882a593Smuzhiyun
281*4882a593Smuzhiyun    import sqlite3
282*4882a593Smuzhiyun    db_file = d.expand("file:${CVE_CHECK_DB_FILE}?mode=ro")
283*4882a593Smuzhiyun    conn = sqlite3.connect(db_file, uri=True)
284*4882a593Smuzhiyun
285*4882a593Smuzhiyun    # For each of the known product names (e.g. curl has CPEs using curl and libcurl)...
286*4882a593Smuzhiyun    for product in products:
287*4882a593Smuzhiyun        cves_in_product = False
288*4882a593Smuzhiyun        if ":" in product:
289*4882a593Smuzhiyun            vendor, product = product.split(":", 1)
290*4882a593Smuzhiyun        else:
291*4882a593Smuzhiyun            vendor = "%"
292*4882a593Smuzhiyun
293*4882a593Smuzhiyun        # Find all relevant CVE IDs.
294*4882a593Smuzhiyun        cve_cursor = conn.execute("SELECT DISTINCT ID FROM PRODUCTS WHERE PRODUCT IS ? AND VENDOR LIKE ?", (product, vendor))
295*4882a593Smuzhiyun        for cverow in cve_cursor:
296*4882a593Smuzhiyun            cve = cverow[0]
297*4882a593Smuzhiyun
298*4882a593Smuzhiyun            if cve in cve_ignore:
299*4882a593Smuzhiyun                bb.note("%s-%s ignores %s" % (product, pv, cve))
300*4882a593Smuzhiyun                cves_ignored.append(cve)
301*4882a593Smuzhiyun                continue
302*4882a593Smuzhiyun            elif cve in patched_cves:
303*4882a593Smuzhiyun                bb.note("%s has been patched" % (cve))
304*4882a593Smuzhiyun                continue
305*4882a593Smuzhiyun            # Write status once only for each product
306*4882a593Smuzhiyun            if not cves_in_product:
307*4882a593Smuzhiyun                cves_status.append([product, True])
308*4882a593Smuzhiyun                cves_in_product = True
309*4882a593Smuzhiyun                cves_in_recipe = True
310*4882a593Smuzhiyun
311*4882a593Smuzhiyun            vulnerable = False
312*4882a593Smuzhiyun            ignored = False
313*4882a593Smuzhiyun
314*4882a593Smuzhiyun            product_cursor = conn.execute("SELECT * FROM PRODUCTS WHERE ID IS ? AND PRODUCT IS ? AND VENDOR LIKE ?", (cve, product, vendor))
315*4882a593Smuzhiyun            for row in product_cursor:
316*4882a593Smuzhiyun                (_, _, _, version_start, operator_start, version_end, operator_end) = row
317*4882a593Smuzhiyun                #bb.debug(2, "Evaluating row " + str(row))
318*4882a593Smuzhiyun                if cve in cve_ignore:
319*4882a593Smuzhiyun                    ignored = True
320*4882a593Smuzhiyun
321*4882a593Smuzhiyun                version_start = convert_cve_version(version_start)
322*4882a593Smuzhiyun                version_end = convert_cve_version(version_end)
323*4882a593Smuzhiyun
324*4882a593Smuzhiyun                if (operator_start == '=' and pv == version_start) or version_start == '-':
325*4882a593Smuzhiyun                    vulnerable = True
326*4882a593Smuzhiyun                else:
327*4882a593Smuzhiyun                    if operator_start:
328*4882a593Smuzhiyun                        try:
329*4882a593Smuzhiyun                            vulnerable_start =  (operator_start == '>=' and Version(pv,suffix) >= Version(version_start,suffix))
330*4882a593Smuzhiyun                            vulnerable_start |= (operator_start == '>' and Version(pv,suffix) > Version(version_start,suffix))
331*4882a593Smuzhiyun                        except:
332*4882a593Smuzhiyun                            bb.warn("%s: Failed to compare %s %s %s for %s" %
333*4882a593Smuzhiyun                                    (product, pv, operator_start, version_start, cve))
334*4882a593Smuzhiyun                            vulnerable_start = False
335*4882a593Smuzhiyun                    else:
336*4882a593Smuzhiyun                        vulnerable_start = False
337*4882a593Smuzhiyun
338*4882a593Smuzhiyun                    if operator_end:
339*4882a593Smuzhiyun                        try:
340*4882a593Smuzhiyun                            vulnerable_end  = (operator_end == '<=' and Version(pv,suffix) <= Version(version_end,suffix) )
341*4882a593Smuzhiyun                            vulnerable_end |= (operator_end == '<' and Version(pv,suffix) < Version(version_end,suffix) )
342*4882a593Smuzhiyun                        except:
343*4882a593Smuzhiyun                            bb.warn("%s: Failed to compare %s %s %s for %s" %
344*4882a593Smuzhiyun                                    (product, pv, operator_end, version_end, cve))
345*4882a593Smuzhiyun                            vulnerable_end = False
346*4882a593Smuzhiyun                    else:
347*4882a593Smuzhiyun                        vulnerable_end = False
348*4882a593Smuzhiyun
349*4882a593Smuzhiyun                    if operator_start and operator_end:
350*4882a593Smuzhiyun                        vulnerable = vulnerable_start and vulnerable_end
351*4882a593Smuzhiyun                    else:
352*4882a593Smuzhiyun                        vulnerable = vulnerable_start or vulnerable_end
353*4882a593Smuzhiyun
354*4882a593Smuzhiyun                if vulnerable:
355*4882a593Smuzhiyun                    if ignored:
356*4882a593Smuzhiyun                        bb.note("%s is ignored in %s-%s" % (cve, pn, real_pv))
357*4882a593Smuzhiyun                        cves_ignored.append(cve)
358*4882a593Smuzhiyun                    else:
359*4882a593Smuzhiyun                        bb.note("%s-%s is vulnerable to %s" % (pn, real_pv, cve))
360*4882a593Smuzhiyun                        cves_unpatched.append(cve)
361*4882a593Smuzhiyun                    break
362*4882a593Smuzhiyun            product_cursor.close()
363*4882a593Smuzhiyun
364*4882a593Smuzhiyun            if not vulnerable:
365*4882a593Smuzhiyun                bb.note("%s-%s is not vulnerable to %s" % (pn, real_pv, cve))
366*4882a593Smuzhiyun                patched_cves.add(cve)
367*4882a593Smuzhiyun        cve_cursor.close()
368*4882a593Smuzhiyun
369*4882a593Smuzhiyun        if not cves_in_product:
370*4882a593Smuzhiyun            bb.note("No CVE records found for product %s, pn %s" % (product, pn))
371*4882a593Smuzhiyun            cves_status.append([product, False])
372*4882a593Smuzhiyun
373*4882a593Smuzhiyun    conn.close()
374*4882a593Smuzhiyun
375*4882a593Smuzhiyun    if not cves_in_recipe:
376*4882a593Smuzhiyun        bb.note("No CVE records for products in recipe %s" % (pn))
377*4882a593Smuzhiyun
378*4882a593Smuzhiyun    return (list(cves_ignored), list(patched_cves), cves_unpatched, cves_status)
379*4882a593Smuzhiyun
380*4882a593Smuzhiyundef get_cve_info(d, cves):
381*4882a593Smuzhiyun    """
382*4882a593Smuzhiyun    Get CVE information from the database.
383*4882a593Smuzhiyun    """
384*4882a593Smuzhiyun
385*4882a593Smuzhiyun    import sqlite3
386*4882a593Smuzhiyun
387*4882a593Smuzhiyun    cve_data = {}
388*4882a593Smuzhiyun    db_file = d.expand("file:${CVE_CHECK_DB_FILE}?mode=ro")
389*4882a593Smuzhiyun    conn = sqlite3.connect(db_file, uri=True)
390*4882a593Smuzhiyun
391*4882a593Smuzhiyun    for cve in cves:
392*4882a593Smuzhiyun        cursor = conn.execute("SELECT * FROM NVD WHERE ID IS ?", (cve,))
393*4882a593Smuzhiyun        for row in cursor:
394*4882a593Smuzhiyun            cve_data[row[0]] = {}
395*4882a593Smuzhiyun            cve_data[row[0]]["summary"] = row[1]
396*4882a593Smuzhiyun            cve_data[row[0]]["scorev2"] = row[2]
397*4882a593Smuzhiyun            cve_data[row[0]]["scorev3"] = row[3]
398*4882a593Smuzhiyun            cve_data[row[0]]["modified"] = row[4]
399*4882a593Smuzhiyun            cve_data[row[0]]["vector"] = row[5]
400*4882a593Smuzhiyun        cursor.close()
401*4882a593Smuzhiyun    conn.close()
402*4882a593Smuzhiyun    return cve_data
403*4882a593Smuzhiyun
404*4882a593Smuzhiyundef cve_write_data_text(d, patched, unpatched, ignored, cve_data):
405*4882a593Smuzhiyun    """
406*4882a593Smuzhiyun    Write CVE information in WORKDIR; and to CVE_CHECK_DIR, and
407*4882a593Smuzhiyun    CVE manifest if enabled.
408*4882a593Smuzhiyun    """
409*4882a593Smuzhiyun
410*4882a593Smuzhiyun    cve_file = d.getVar("CVE_CHECK_LOG")
411*4882a593Smuzhiyun    fdir_name  = d.getVar("FILE_DIRNAME")
412*4882a593Smuzhiyun    layer = fdir_name.split("/")[-3]
413*4882a593Smuzhiyun
414*4882a593Smuzhiyun    include_layers = d.getVar("CVE_CHECK_LAYER_INCLUDELIST").split()
415*4882a593Smuzhiyun    exclude_layers = d.getVar("CVE_CHECK_LAYER_EXCLUDELIST").split()
416*4882a593Smuzhiyun
417*4882a593Smuzhiyun    report_all = d.getVar("CVE_CHECK_REPORT_PATCHED") == "1"
418*4882a593Smuzhiyun
419*4882a593Smuzhiyun    if exclude_layers and layer in exclude_layers:
420*4882a593Smuzhiyun        return
421*4882a593Smuzhiyun
422*4882a593Smuzhiyun    if include_layers and layer not in include_layers:
423*4882a593Smuzhiyun        return
424*4882a593Smuzhiyun
425*4882a593Smuzhiyun    # Early exit, the text format does not report packages without CVEs
426*4882a593Smuzhiyun    if not patched+unpatched+ignored:
427*4882a593Smuzhiyun        return
428*4882a593Smuzhiyun
429*4882a593Smuzhiyun    nvd_link = "https://nvd.nist.gov/vuln/detail/"
430*4882a593Smuzhiyun    write_string = ""
431*4882a593Smuzhiyun    unpatched_cves = []
432*4882a593Smuzhiyun    bb.utils.mkdirhier(os.path.dirname(cve_file))
433*4882a593Smuzhiyun
434*4882a593Smuzhiyun    for cve in sorted(cve_data):
435*4882a593Smuzhiyun        is_patched = cve in patched
436*4882a593Smuzhiyun        is_ignored = cve in ignored
437*4882a593Smuzhiyun
438*4882a593Smuzhiyun        if (is_patched or is_ignored) and not report_all:
439*4882a593Smuzhiyun            continue
440*4882a593Smuzhiyun
441*4882a593Smuzhiyun        write_string += "LAYER: %s\n" % layer
442*4882a593Smuzhiyun        write_string += "PACKAGE NAME: %s\n" % d.getVar("PN")
443*4882a593Smuzhiyun        write_string += "PACKAGE VERSION: %s%s\n" % (d.getVar("EXTENDPE"), d.getVar("PV"))
444*4882a593Smuzhiyun        write_string += "CVE: %s\n" % cve
445*4882a593Smuzhiyun        if is_ignored:
446*4882a593Smuzhiyun            write_string += "CVE STATUS: Ignored\n"
447*4882a593Smuzhiyun        elif is_patched:
448*4882a593Smuzhiyun            write_string += "CVE STATUS: Patched\n"
449*4882a593Smuzhiyun        else:
450*4882a593Smuzhiyun            unpatched_cves.append(cve)
451*4882a593Smuzhiyun            write_string += "CVE STATUS: Unpatched\n"
452*4882a593Smuzhiyun        write_string += "CVE SUMMARY: %s\n" % cve_data[cve]["summary"]
453*4882a593Smuzhiyun        write_string += "CVSS v2 BASE SCORE: %s\n" % cve_data[cve]["scorev2"]
454*4882a593Smuzhiyun        write_string += "CVSS v3 BASE SCORE: %s\n" % cve_data[cve]["scorev3"]
455*4882a593Smuzhiyun        write_string += "VECTOR: %s\n" % cve_data[cve]["vector"]
456*4882a593Smuzhiyun        write_string += "MORE INFORMATION: %s%s\n\n" % (nvd_link, cve)
457*4882a593Smuzhiyun
458*4882a593Smuzhiyun    if unpatched_cves and d.getVar("CVE_CHECK_SHOW_WARNINGS") == "1":
459*4882a593Smuzhiyun        bb.warn("Found unpatched CVE (%s), for more information check %s" % (" ".join(unpatched_cves),cve_file))
460*4882a593Smuzhiyun
461*4882a593Smuzhiyun    with open(cve_file, "w") as f:
462*4882a593Smuzhiyun        bb.note("Writing file %s with CVE information" % cve_file)
463*4882a593Smuzhiyun        f.write(write_string)
464*4882a593Smuzhiyun
465*4882a593Smuzhiyun    if d.getVar("CVE_CHECK_COPY_FILES") == "1":
466*4882a593Smuzhiyun        deploy_file = d.getVar("CVE_CHECK_RECIPE_FILE")
467*4882a593Smuzhiyun        bb.utils.mkdirhier(os.path.dirname(deploy_file))
468*4882a593Smuzhiyun        with open(deploy_file, "w") as f:
469*4882a593Smuzhiyun            f.write(write_string)
470*4882a593Smuzhiyun
471*4882a593Smuzhiyun    if d.getVar("CVE_CHECK_CREATE_MANIFEST") == "1":
472*4882a593Smuzhiyun        cvelogpath = d.getVar("CVE_CHECK_SUMMARY_DIR")
473*4882a593Smuzhiyun        bb.utils.mkdirhier(cvelogpath)
474*4882a593Smuzhiyun
475*4882a593Smuzhiyun        with open(d.getVar("CVE_CHECK_TMP_FILE"), "a") as f:
476*4882a593Smuzhiyun            f.write("%s" % write_string)
477*4882a593Smuzhiyun
478*4882a593Smuzhiyundef cve_check_write_json_output(d, output, direct_file, deploy_file, manifest_file):
479*4882a593Smuzhiyun    """
480*4882a593Smuzhiyun    Write CVE information in the JSON format: to WORKDIR; and to
481*4882a593Smuzhiyun    CVE_CHECK_DIR, if CVE manifest if enabled, write fragment
482*4882a593Smuzhiyun    files that will be assembled at the end in cve_check_write_rootfs_manifest.
483*4882a593Smuzhiyun    """
484*4882a593Smuzhiyun
485*4882a593Smuzhiyun    import json
486*4882a593Smuzhiyun
487*4882a593Smuzhiyun    write_string = json.dumps(output, indent=2)
488*4882a593Smuzhiyun    with open(direct_file, "w") as f:
489*4882a593Smuzhiyun        bb.note("Writing file %s with CVE information" % direct_file)
490*4882a593Smuzhiyun        f.write(write_string)
491*4882a593Smuzhiyun
492*4882a593Smuzhiyun    if d.getVar("CVE_CHECK_COPY_FILES") == "1":
493*4882a593Smuzhiyun        bb.utils.mkdirhier(os.path.dirname(deploy_file))
494*4882a593Smuzhiyun        with open(deploy_file, "w") as f:
495*4882a593Smuzhiyun            f.write(write_string)
496*4882a593Smuzhiyun
497*4882a593Smuzhiyun    if d.getVar("CVE_CHECK_CREATE_MANIFEST") == "1":
498*4882a593Smuzhiyun        cvelogpath = d.getVar("CVE_CHECK_SUMMARY_DIR")
499*4882a593Smuzhiyun        index_path = d.getVar("CVE_CHECK_SUMMARY_INDEX_PATH")
500*4882a593Smuzhiyun        bb.utils.mkdirhier(cvelogpath)
501*4882a593Smuzhiyun        fragment_file = os.path.basename(deploy_file)
502*4882a593Smuzhiyun        fragment_path = os.path.join(cvelogpath, fragment_file)
503*4882a593Smuzhiyun        with open(fragment_path, "w") as f:
504*4882a593Smuzhiyun            f.write(write_string)
505*4882a593Smuzhiyun        with open(index_path, "a+") as f:
506*4882a593Smuzhiyun            f.write("%s\n" % fragment_path)
507*4882a593Smuzhiyun
508*4882a593Smuzhiyundef cve_write_data_json(d, patched, unpatched, ignored, cve_data, cve_status):
509*4882a593Smuzhiyun    """
510*4882a593Smuzhiyun    Prepare CVE data for the JSON format, then write it.
511*4882a593Smuzhiyun    """
512*4882a593Smuzhiyun
513*4882a593Smuzhiyun    output = {"version":"1", "package": []}
514*4882a593Smuzhiyun    nvd_link = "https://nvd.nist.gov/vuln/detail/"
515*4882a593Smuzhiyun
516*4882a593Smuzhiyun    fdir_name  = d.getVar("FILE_DIRNAME")
517*4882a593Smuzhiyun    layer = fdir_name.split("/")[-3]
518*4882a593Smuzhiyun
519*4882a593Smuzhiyun    include_layers = d.getVar("CVE_CHECK_LAYER_INCLUDELIST").split()
520*4882a593Smuzhiyun    exclude_layers = d.getVar("CVE_CHECK_LAYER_EXCLUDELIST").split()
521*4882a593Smuzhiyun
522*4882a593Smuzhiyun    report_all = d.getVar("CVE_CHECK_REPORT_PATCHED") == "1"
523*4882a593Smuzhiyun
524*4882a593Smuzhiyun    if exclude_layers and layer in exclude_layers:
525*4882a593Smuzhiyun        return
526*4882a593Smuzhiyun
527*4882a593Smuzhiyun    if include_layers and layer not in include_layers:
528*4882a593Smuzhiyun        return
529*4882a593Smuzhiyun
530*4882a593Smuzhiyun    unpatched_cves = []
531*4882a593Smuzhiyun
532*4882a593Smuzhiyun    product_data = []
533*4882a593Smuzhiyun    for s in cve_status:
534*4882a593Smuzhiyun        p = {"product": s[0], "cvesInRecord": "Yes"}
535*4882a593Smuzhiyun        if s[1] == False:
536*4882a593Smuzhiyun            p["cvesInRecord"] = "No"
537*4882a593Smuzhiyun        product_data.append(p)
538*4882a593Smuzhiyun
539*4882a593Smuzhiyun    package_version = "%s%s" % (d.getVar("EXTENDPE"), d.getVar("PV"))
540*4882a593Smuzhiyun    package_data = {
541*4882a593Smuzhiyun        "name" : d.getVar("PN"),
542*4882a593Smuzhiyun        "layer" : layer,
543*4882a593Smuzhiyun        "version" : package_version,
544*4882a593Smuzhiyun        "products": product_data
545*4882a593Smuzhiyun    }
546*4882a593Smuzhiyun    cve_list = []
547*4882a593Smuzhiyun
548*4882a593Smuzhiyun    for cve in sorted(cve_data):
549*4882a593Smuzhiyun        is_patched = cve in patched
550*4882a593Smuzhiyun        is_ignored = cve in ignored
551*4882a593Smuzhiyun        status = "Unpatched"
552*4882a593Smuzhiyun        if (is_patched or is_ignored) and not report_all:
553*4882a593Smuzhiyun            continue
554*4882a593Smuzhiyun        if is_ignored:
555*4882a593Smuzhiyun            status = "Ignored"
556*4882a593Smuzhiyun        elif is_patched:
557*4882a593Smuzhiyun            status = "Patched"
558*4882a593Smuzhiyun        else:
559*4882a593Smuzhiyun            # default value of status is Unpatched
560*4882a593Smuzhiyun            unpatched_cves.append(cve)
561*4882a593Smuzhiyun
562*4882a593Smuzhiyun        issue_link = "%s%s" % (nvd_link, cve)
563*4882a593Smuzhiyun
564*4882a593Smuzhiyun        cve_item = {
565*4882a593Smuzhiyun            "id" : cve,
566*4882a593Smuzhiyun            "summary" : cve_data[cve]["summary"],
567*4882a593Smuzhiyun            "scorev2" : cve_data[cve]["scorev2"],
568*4882a593Smuzhiyun            "scorev3" : cve_data[cve]["scorev3"],
569*4882a593Smuzhiyun            "vector" : cve_data[cve]["vector"],
570*4882a593Smuzhiyun            "status" : status,
571*4882a593Smuzhiyun            "link": issue_link
572*4882a593Smuzhiyun        }
573*4882a593Smuzhiyun        cve_list.append(cve_item)
574*4882a593Smuzhiyun
575*4882a593Smuzhiyun    package_data["issue"] = cve_list
576*4882a593Smuzhiyun    output["package"].append(package_data)
577*4882a593Smuzhiyun
578*4882a593Smuzhiyun    direct_file = d.getVar("CVE_CHECK_LOG_JSON")
579*4882a593Smuzhiyun    deploy_file = d.getVar("CVE_CHECK_RECIPE_FILE_JSON")
580*4882a593Smuzhiyun    manifest_file = d.getVar("CVE_CHECK_SUMMARY_FILE_NAME_JSON")
581*4882a593Smuzhiyun
582*4882a593Smuzhiyun    cve_check_write_json_output(d, output, direct_file, deploy_file, manifest_file)
583*4882a593Smuzhiyun
584*4882a593Smuzhiyundef cve_write_data(d, patched, unpatched, ignored, cve_data, status):
585*4882a593Smuzhiyun    """
586*4882a593Smuzhiyun    Write CVE data in each enabled format.
587*4882a593Smuzhiyun    """
588*4882a593Smuzhiyun
589*4882a593Smuzhiyun    if d.getVar("CVE_CHECK_FORMAT_TEXT") == "1":
590*4882a593Smuzhiyun        cve_write_data_text(d, patched, unpatched, ignored, cve_data)
591*4882a593Smuzhiyun    if d.getVar("CVE_CHECK_FORMAT_JSON") == "1":
592*4882a593Smuzhiyun        cve_write_data_json(d, patched, unpatched, ignored, cve_data, status)
593