Skip to contentSkip to conversation

support/scripts/pkg-stats: ignore more makefiles that aren't packages

PATCH Applied Daniel Lang 2 participants 13 messages Sep 1, 2023 – Jan 30, 2024

lore
Share & tools
lore
#0 lore raw

PATCH v4 1/6 support/scripts/pkg-stats: ignore more makefiles that aren't packages

Some packages are grouped and have a general makefile that defines reusable variables. These makefiles have no relevant information for pkg-stats and should be excluded.

---
v3 -> v4:
- Added more packages to ignore list, not just llvm-project

---
 support/scripts/pkg-stats | 7 ++++++-
 1 file changed, 6 insertions(+), 1 deletion(-)
support/scripts/pkg-stats +6 -1
index 28f5a0789c..eca638f396 100755
@@ -338,16 +338,21 @@ def get_pkglist(npackages, package_list):
     package_list: limit to those packages in this list
     """
     WALK_USEFUL_SUBDIRS = ["boot", "linux", "package", "toolchain"]
-    WALK_EXCLUDES = ["boot/common.mk",
+    WALK_EXCLUDES = ["boot/barebox/barebox.mk",
+                     "boot/common.mk",
                      "linux/linux-ext-.*.mk",
+                     "package/fftw/fftw.mk",
                      "package/freescale-imx/freescale-imx.mk",
                      "package/gcc/gcc.mk",
                      "package/gstreamer/gstreamer.mk",
                      "package/gstreamer1/gstreamer1.mk",
                      "package/gtk2-themes/gtk2-themes.mk",
+                     "package/kf5/kf5.mk",
+                     "package/llvm-project/llvm-project.mk",
                      "package/matchbox/matchbox.mk",
                      "package/opengl/opengl.mk",
                      "package/qt5/qt5.mk",
+                     "package/qt6/qt6.mk",
                      "package/x11r7/x11r7.mk",
                      "package/doc-asciidoc.mk",
                      "package/pkg-.*.mk",
Signature · 6 lines
2.42.0

_______________________________________________
buildroot mailing list
[email protected]
https://lists.buildroot.org/mailman/listinfo/buildroot
#1 lore raw

PATCH v4 2/6 support/scripts/pkg-stats: check all files for warnings

Instead of only checking .mk and Config.in{,.host}, check all files in a package directory.
.checkpackageignore isn't considered here, therefore the shown number includes ignored warnings as well.
Add another css class to signal some warning, compared to a lot (>5), similar to patches.

---
v3 -> v4:
- use yellowish bachground for "some" warnings
v2 -> v3:
- new patch

---
 support/scripts/pkg-stats | 7 ++++---
 1 file changed, 4 insertions(+), 3 deletions(-)
support/scripts/pkg-stats +4 -3
index eca638f396..9349a0df57 100755
@@ -272,8 +272,7 @@ class Package:
         self.status['pkg-check'] = ("error", "Missing")
         for root, dirs, files in os.walk(pkgdir):
             for f in files:
-                if f.endswith(".mk") or f.endswith(".hash") or f == "Config.in" or f == "Config.in.host":
-                    cmd.append(os.path.join(root, f))
+                cmd.append(os.path.join(root, f))
         o = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE).communicate()[1]
         lines = o.splitlines()
         for line in lines:
@@ -876,7 +875,7 @@ function expandField(fieldId){
  .wrong, .lotsofpatches, .invalid_url, .version-needs-update, .cpe-nok, .cve-nok {
    background: #ff9a69;
  }
- .somepatches, .missing_url, .version-unknown, .cpe-unknown, .cve-unknown {
+ .somepatches, .somewarnings, .missing_url, .version-unknown, .cpe-unknown, .cve-unknown {
    background: #ffd870;
  }
  .cve_ignored, .version-error {
@@ -1033,6 +1032,8 @@ def dump_html_pkg(f, pkg):
     div_class.append(f'_{pkg_css_class}')
     if pkg.warnings == 0:
         div_class.append("correct")
+    elif pkg.warnings < 5:
+        div_class.append("somewarnings")
     else:
         div_class.append("wrong")
     f.write(f'  <div id="{data_field_id}" class="{" ".join(div_class)}">{pkg.warnings}</div>\n')
Signature · 6 lines
2.42.0

_______________________________________________
buildroot mailing list
[email protected]
https://lists.buildroot.org/mailman/listinfo/buildroot
#2 lore raw

Re: [Buildroot] [PATCH v4 2/6] support/scripts/pkg-stats: check all files for warnings

Quoted 7 lines · On Fri, 1 Sep 2023 21:27:10 +0200 Daniel Lang <[email protected]> wrote:

Instead of only checking .mk and Config.in{,.host}, check all files in a package directory.
.checkpackageignore isn't considered here, therefore the shown number includes ignored warnings as well.
Add another css class to signal some warning, compared to a lot (>5), similar to patches.

Quoted 6 lines

---
v3 -> v4:
- use yellowish bachground for "some" warnings
v2 -> v3:
- new patch

Applied to master, thanks.

Thomas

Signature · 7 lines
Thomas Petazzoni, CTO, Bootlin
Embedded Linux and Kernel engineering
https://bootlin.com
_______________________________________________
buildroot mailing list
[email protected]
https://lists.buildroot.org/mailman/listinfo/buildroot
#3 lore raw

PATCH v4 3/6 support/scripts/nvd_api_v2.py: new helper class

In reply to Daniel Lang

The current NVD data feeds used for CVE and CPE checking will be retired by 2023-12-05 [0]. Both have to be switched to the new v2 API. Since fetching data from both sources workes the same, a common base class is used to handle the API interaction.
With the new API JSON pages are downloaded, meaning that we have to come up with a storage solution ourselves. Therefore nvd_api_v2.py manages a generic set of methods to initialize and update a sqlite database.

[0]: https://nvd.nist.gov/General/News/change-timeline

---
v3 -> v4:
- use f-strings
- add meta table instead of tmp file
- drop error handling

---
 DEVELOPERS                    |   1 +
 support/scripts/nvd_api_v2.py | 137 ++++++++++++++++++++++++++++++++++
 2 files changed, 138 insertions(+)
 create mode 100755 support/scripts/nvd_api_v2.py
DEVELOPERS +1 -0
index 9b500f3701..046a022fc9 100644
@@ -668,6 +668,7 @@ F:	package/paho-mqtt-cpp/
 F:	package/pangomm/
 F:	package/pangomm2_46/
 F:	package/sam-ba/
+F:	support/scripts/nvd_api_v2.py
 
 N:	Damien Lanson <[email protected]>
 F:	package/libvdpau/
support/scripts/nvd_api_v2.py new file +137 -0

137 lines not on this page · raw message

Signature · 6 lines
2.42.0

_______________________________________________
buildroot mailing list
[email protected]
https://lists.buildroot.org/mailman/listinfo/buildroot
#4 lore raw

Re: [Buildroot] [PATCH v4 3/6] support/scripts/nvd_api_v2.py: new helper class

Hello Daniel,

Quoted 11 lines · On Fri, 1 Sep 2023 21:27:11 +0200 Daniel Lang <[email protected]> wrote:

The current NVD data feeds used for CVE and CPE checking will be retired by 2023-12-05 [0]. Both have to be switched to the new v2 API. Since fetching data from both sources workes the same, a common base class is used to handle the API interaction.
With the new API JSON pages are downloaded, meaning that we have to come up with a storage solution ourselves. Therefore nvd_api_v2.py manages a generic set of methods to initialize and update a sqlite database.

[0]: https://nvd.nist.gov/General/News/change-timeline

Thanks for working into this. I wanted to merge this, but taking a fresh look at this, I don't quite understand the SW design choices you've made when it comes to splitting between the NVD_API class and the CVE_API class.

The NVD_API class implements
- An actual init_db_meta() method
- A dummy init_db() method
- A dummy save_to_db() method
- An actual download() method
- An actual check_for_updates() method

Then the CVE_API class inherits from NVD_API, which provides the actual implementation of init_db(), save_to_db() among others.

What is the reasoning behind this? One could think that the NVD_API class was only related to calling the NVD HTTP API, but it does have knowledge of the local sqlite database.

So I'm really not clear on this design. Could you provide some details?

Now I see that the CPE_API class also inherits from NVD_API, but I'm still confused.

Thomas

Signature · 7 lines
Thomas Petazzoni, co-owner and CEO, Bootlin
Embedded Linux and Kernel engineering and training
https://bootlin.com
_______________________________________________
buildroot mailing list
[email protected]
https://lists.buildroot.org/mailman/listinfo/buildroot
#5 lore raw

Re: [Buildroot] [PATCH v4 3/6] support/scripts/nvd_api_v2.py: new helper class

Hello Thomas,

sorry for the long silence.

Quoted 13 lines · Thomas Petazzoni

Hello Daniel,

Quoted 8 lines · On Fri, 1 Sep 2023 21:27:11 +0200 Daniel Lang <[email protected]> wrote:

The current NVD data feeds used for CVE and CPE checking will be retired by 2023-12-05 [0]. Both have to be switched to the new v2 API. Since fetching data from both sources workes the same, a common base class is used to handle the API interaction.
With the new API JSON pages are downloaded, meaning that we have to come up with a storage solution ourselves. Therefore nvd_api_v2.py manages a generic set of methods to initialize and update a sqlite database.

Quoted 8 lines
Quoted 3 lines

[0]: https://nvd.nist.gov/General/News/change-timeline

Thanks for working into this. I wanted to merge this, but taking a fresh look at this, I don't quite understand the SW design choices you've made when it comes to splitting between the NVD_API class and the CVE_API class.

My idea was to move code that is needed for CVEs and CPEs into a common file since with the new API both endpoints are quit similar.

Therefore NVD_API contains code for querying the API, handling pagination, querying meta information from the database. Additionally downloaded information is passed to CVE_API or CPE_API via save_to_db().

Not sure, if that makes it clearer.

Quoted 8 lines

The NVD_API class implements
- An actual init_db_meta() method
- A dummy init_db() method
- A dummy save_to_db() method
- An actual download() method
- An actual check_for_updates() method

Quoted 6 lines

Then the CVE_API class inherits from NVD_API, which provides the actual implementation of init_db(), save_to_db() among others.

What is the reasoning behind this? One could think that the NVD_API class was only related to calling the NVD HTTP API, but it does have knowledge of the local sqlite database.

Yes, it has knowledge of the local database to load and save meta information, which is currently only "when was the last run".

Quoted 5 lines

So I'm really not clear on this design. Could you provide some details?

Now I see that the CPE_API class also inherits from NVD_API, but I'm still confused.

While implementing this I was going back and forth on whether to use a database.
This version of the patch does, but I have since moved the code to GitLab to try out GitLab Package Repositories for hosting the archives for each year. During this move I switched back to using JSON files.
This makes it possible to query the data once for all buildroot users and filter the data for the needed fields.
This means, that we end up with a couple of MB per year instead of a 400MB sqlite database.
This approach could either be part of sources.buildroot.org or via GitLab.

Quoted 2 lines

Thomas

Regards,
Daniel

_______________________________________________
buildroot mailing list
[email protected]
https://lists.buildroot.org/mailman/listinfo/buildroot

#6 lore raw

PATCH v4 4/6 support/scripts/cve.py: switch to NVD API v2

In reply to Daniel Lang

The currently used feed will be retired in December 2023 [0]. The only alternative is the new v2 API [1]. The API allows downloading sets of CVEs (2k at a time) that were modified after a given UTC timestamp. Rate limiting of 5 requests in a sliding 30 seconds window is used [2].
nvd_api_v2.py is used to store the data in a local sqlite database. Only a subset of fields get stored to keep the db smaller (still ~400MB currently).

[0]: https://nvd.nist.gov/General/News/change-timeline
[1]: https://nvd.nist.gov/developers/vulnerabilities
[2]: https://nvd.nist.gov/developers/start-here

---
v3 -> v4:
- progress output moved to nvd_api_v2
- self.connection was renamed to self.db_connection
v1 -> v2:
- switch to sqlite database for a more future proof storage
- CPE_ID class has been moved to a laster patch, therefore not used here

---
 DEVELOPERS                |   1 +
 support/scripts/cve.py    | 413 ++++++++++++++++++++------------------
 support/scripts/pkg-stats |  31 ++-
 3 files changed, 236 insertions(+), 209 deletions(-)
DEVELOPERS +1 -0
index 046a022fc9..87f5e816f2 100644
@@ -668,6 +668,7 @@ F:	package/paho-mqtt-cpp/
 F:	package/pangomm/
 F:	package/pangomm2_46/
 F:	package/sam-ba/
+F:	support/scripts/cve.py
 F:	support/scripts/nvd_api_v2.py
 
 N:	Damien Lanson <[email protected]>
support/scripts/cve.py +220 -193

440 lines not on this page · raw message

support/scripts/pkg-stats +15 -16
index 9349a0df57..b1f02c15b8 100755
@@ -32,6 +32,7 @@ import time
 import gzip
 import xml.etree.ElementTree
 import requests
+from cve import CVE_API, cpe_product
 
 brpath = os.path.normpath(os.path.join(os.path.dirname(__file__), "..", ".."))
 
@@ -611,15 +612,17 @@ async def check_package_latest_version(packages):
 
 
 def check_package_cve_affects(cve, cpe_product_pkgs):
-    for product in cve.affected_products:
-        if product not in cpe_product_pkgs:
+    product = cve.affected_product
+    if product not in cpe_product_pkgs:
+        return
+    for pkg in cpe_product_pkgs[product]:
+        if cve.identifier in pkg.cves or cve.identifier in pkg.unsure_cves:
             continue
-        for pkg in cpe_product_pkgs[product]:
-            cve_status = cve.affects(pkg.name, pkg.current_version, pkg.ignored_cves, pkg.cpeid)
-            if cve_status == cve.CVE_AFFECTS:
-                pkg.cves.append(cve.identifier)
-            elif cve_status == cve.CVE_UNKNOWN:
-                pkg.unsure_cves.append(cve.identifier)
+        cve_status = cve.affects(pkg.name, pkg.current_version, pkg.ignored_cves, pkg.cpeid)
+        if cve_status == cve.CVE_AFFECTS:
+            pkg.cves.append(cve.identifier)
+        elif cve_status == cve.CVE_UNKNOWN:
+            pkg.unsure_cves.append(cve.identifier)
 
 
 def check_package_cves(nvd_path, packages):
@@ -635,12 +638,13 @@ def check_package_cves(nvd_path, packages):
             pkg.status['cve'] = ("na", "no version information available")
             continue
         if pkg.cpeid:
-            cpe_product = cvecheck.cpe_product(pkg.cpeid)
-            cpe_product_pkgs[cpe_product].append(pkg)
+            product = cpe_product(pkg.cpeid)
+            cpe_product_pkgs[product].append(pkg)
         else:
             cpe_product_pkgs[pkg.name].append(pkg)
 
-    for cve in cvecheck.CVE.read_nvd_dir(nvd_path):
+    cve_api = CVE_API(nvd_path)
+    for cve in cve_api.load_all():
         check_package_cve_affects(cve, cpe_product_pkgs)
 
     for pkg in packages:
@@ -1291,13 +1295,8 @@ def parse_args():
 
 
 def __main__():
-    global cvecheck
-
     args = parse_args()
 
-    if args.nvd_path:
-        import cve as cvecheck
-
     show_info_js = None
     if args.packages:
         package_list = args.packages.split(",")
Signature · 6 lines
2.42.0

_______________________________________________
buildroot mailing list
[email protected]
https://lists.buildroot.org/mailman/listinfo/buildroot
#7 lore raw

Re: [Buildroot] [PATCH v4 4/6] support/scripts/cve.py: switch to NVD API v2

Hi Daniel,

I'm finally getting around to this patch series... I have one little question
(and a lot of little changes that I'm doing while applying).

Quoted 12 lines · Daniel Lang
support/scripts/cve.py +12 -0
+            for config in vul['cve'].get('configurations', ()):
+                for node in config['nodes']:
+                    for cpe_match in node['cpeMatch']:
+                        if not cpe_match['vulnerable']:
+                            continue
+                        match_data = self.extract_cpe_match_data(cpe_match)
+                        if not match_data:
+                            continue
+                        cpe_matches.append(match_data)
+                        configurations.append([vul['cve']['id'], match_data[0]])
+
+        cursor = self.db_connection.cursor()

support/scripts/cve.py class CVE: · line 273

Quoted 10 lines
support/scripts/cve.py +10 -0
+
+        # Drop all CVEs that are rejected, status might have changed
+        cursor.executemany('DELETE FROM cves WHERE id = ?', cve_ids_dropped)
+
+        # Delete configuration mapping for included CVEs, otherwise we can't detect
+        # upstream dropping configurations.
+        cursor.executemany('DELETE FROM configurations WHERE cve_id = ?', cve_ids_changed)
+        cursor.executemany('INSERT OR REPLACE INTO cves VALUES (?, ?, ?, ?, ?)', cves)
+        cursor.executemany('INSERT OR REPLACE INTO cpe_matches VALUES (?, ?, ?, ?, ?, ?)', cpe_matches)
+        cursor.executemany('INSERT OR REPLACE INTO configurations VALUES (?, ?)', configurations)

AFAIU, the configurations table is there to make an M-N relationship between
CVEs and CPE_matches. However, I don't understand why this is needed or even possible - i.e., it necessarily has to be a 1-N relationship. Indeed, the code above always creates both a CPE_match line and a configuration line; the ID of the CPE_match line is UNIQUE, so the same match line cannot be reused for another CVE.

So, I think this configurations table is entirely redundant, and instead the
cpe_matches table should just contain a reference to the CVE ID.

(Don't change and resend this patch, I've made a whole lot of changes myself
and I can remove this configurations table too.)

Regards,
Arnout
_______________________________________________
buildroot mailing list
[email protected]
https://lists.buildroot.org/mailman/listinfo/buildroot

#8 lore raw

Re: [Buildroot] [PATCH v4 4/6] support/scripts/cve.py: switch to NVD API v2

Hi Arnout,

Quoted 3 lines · Arnout Vandecappelle

 Hi Daniel,

 I'm finally getting around to this patch series... I have one little question (and a lot of little changes that I'm doing while applying).

As I mentioned in my last email to Thomas [0], I have since moved away from the database approach back to json files. Additionally I toyed with the idea of using GitLab for fetching and optimizing the data because passing it on to buildroot users. A quick prove of concept can be found found here [1].

Quoted 18 lines · Daniel Lang
Quoted 16 lines

+            for config in vul['cve'].get('configurations', ()):
+                for node in config['nodes']:
+                    for cpe_match in node['cpeMatch']:
+                        if not cpe_match['vulnerable']:
+                            continue
+                        match_data = self.extract_cpe_match_data(cpe_match) +                        if not match_data:
+                            continue
+                        cpe_matches.append(match_data)
+                        configurations.append([vul['cve']['id'], match_data[0]])

support/scripts/cve.py +6 -0
+
+        cursor = self.db_connection.cursor()
+
+        # Drop all CVEs that are rejected, status might have changed
+        cursor.executemany('DELETE FROM cves WHERE id = ?', cve_ids_dropped)
+
Quoted 8 lines
Quoted 6 lines

+        # Delete configuration mapping for included CVEs, otherwise we can't detect
+        # upstream dropping configurations.
+        cursor.executemany('DELETE FROM configurations WHERE cve_id = ?', cve_ids_changed) +        cursor.executemany('INSERT OR REPLACE INTO cves VALUES (?, ?, ?, ?, ?)', cves) +        cursor.executemany('INSERT OR REPLACE INTO cpe_matches VALUES (?, ?, ?, ?, ?, ?)', cpe_matches) +        cursor.executemany('INSERT OR REPLACE INTO configurations VALUES (?, ?)', configurations)

 AFAIU, the configurations table is there to make an M-N relationship between CVEs and CPE_matches. However, I don't understand why this is needed or even possible - i.e., it necessarily has to be a 1-N relationship. Indeed, the code above always creates both a CPE_match line and a configuration line; the ID of the CPE_match line is UNIQUE, so the same match line cannot be reused for another CVE.

Looking at the database when I last ran this version in September of 2023, the counts in the three tables looked like this:
- cves: 211066 rows
- cve_matches: 398178 rows
- configurations: 1971459 rows

So it seems that the same cve_matches ID is used for multiple cves.

Quoted 7 lines

 So, I think this configurations table is entirely redundant, and instead the cpe_matches table should just contain a reference to the CVE ID.

 (Don't change and resend this patch, I've made a whole lot of changes myself and I can remove this configurations table too.)

 Regards,
 Arnout

Regards,
Daniel

[0]: https://lists.buildroot.org/pipermail/buildroot/2023-December/681888.html
[1]: https://gitlab.com/daniellang/nvd-v2.0/
_______________________________________________
buildroot mailing list
[email protected]
https://lists.buildroot.org/mailman/listinfo/buildroot

#9 lore raw

Re: [Buildroot] [PATCH v4 4/6] support/scripts/cve.py: switch to NVD API v2

Hi Daniel,

Quoted 8 lines · Daniel Lang

Hi Arnout,

Quoted 3 lines · Arnout Vandecappelle

 Hi Daniel,

 I'm finally getting around to this patch series... I have one little question (and a lot of little changes that I'm doing while applying).

As I mentioned in my last email to Thomas [0], I have since moved away from the database approach back to json files.

Oh, I wasn't aware of that. But now you mention it, I vaguely remember someone
suggested to use json files instead of sqlite, indeed.

Quoted 1 line

Additionally I toyed with the idea of using GitLab for fetching and optimizing the data because passing it on to buildroot users.

I think it makes more sense to use BR2_PRIMARY_SITE to store a cached version.
However, if we do that, it should have a hash and everything, so it's perhaps not super practical...

Quoted 1 line

A quick prove of concept can be found found here [1].

I'll take a look at it some time :-)

Quoted 28 lines
Quoted 19 lines · Daniel Lang
Quoted 16 lines

+            for config in vul['cve'].get('configurations', ()):
+                for node in config['nodes']:
+                    for cpe_match in node['cpeMatch']:
+                        if not cpe_match['vulnerable']:
+                            continue
+                        match_data = self.extract_cpe_match_data(cpe_match) +                        if not match_data:
+                            continue
+                        cpe_matches.append(match_data)
+                        configurations.append([vul['cve']['id'], match_data[0]])

support/scripts/cve.py +6 -0
+
+        cursor = self.db_connection.cursor()
+
+        # Drop all CVEs that are rejected, status might have changed
+        cursor.executemany('DELETE FROM cves WHERE id = ?', cve_ids_dropped)
+
Quoted 8 lines
Quoted 6 lines

+        # Delete configuration mapping for included CVEs, otherwise we can't detect
+        # upstream dropping configurations.
+        cursor.executemany('DELETE FROM configurations WHERE cve_id = ?', cve_ids_changed) +        cursor.executemany('INSERT OR REPLACE INTO cves VALUES (?, ?, ?, ?, ?)', cves) +        cursor.executemany('INSERT OR REPLACE INTO cpe_matches VALUES (?, ?, ?, ?, ?, ?)', cpe_matches) +        cursor.executemany('INSERT OR REPLACE INTO configurations VALUES (?, ?)', configurations)

 AFAIU, the configurations table is there to make an M-N relationship between CVEs and CPE_matches. However, I don't understand why this is needed or even possible - i.e., it necessarily has to be a 1-N relationship. Indeed, the code above always creates both a CPE_match line and a configuration line; the ID of the CPE_match line is UNIQUE, so the same match line cannot be reused for another CVE.

Quoted 6 lines

Looking at the database when I last ran this version in September of 2023, the counts in the three tables looked like this:
- cves: 211066 rows
- cve_matches: 398178 rows
- configurations: 1971459 rows

So it seems that the same cve_matches ID is used for multiple cves.

Right! I'm not sure though if the additional configurations table really saves
space - since we only save a subset of the criteria, it's possible that duplicating the cpe_matches doesn't take (much) more space than the additional configurations table. Unfortunately I didn't implement it like that (I incorrectly overwrite the cpe_match's CVEID when the same one occurs several times), so I don't have the numbers to be sure.

Anyway, as you say: if we go for storing JSON files after all, the point is
probably moot.

Regards,
Arnout

Quoted 6 lines
Quoted 6 lines

 So, I think this configurations table is entirely redundant, and instead the cpe_matches table should just contain a reference to the CVE ID.

 (Don't change and resend this patch, I've made a whole lot of changes myself and I can remove this configurations table too.)

Quoted 8 lines
Quoted 2 lines

 Regards,
 Arnout

Regards,
Daniel

[0]: https://lists.buildroot.org/pipermail/buildroot/2023-December/681888.html
[1]: https://gitlab.com/daniellang/nvd-v2.0/

_______________________________________________
buildroot mailing list
[email protected]
https://lists.buildroot.org/mailman/listinfo/buildroot

#10 lore raw

PATCH v4 5/6 support/scripts/pkg-stats: switch CPEs to NVD API v2

In reply to Daniel Lang

The currently used feed will be retired in December 2023 [0]. As an alternative the new v2 API [1]. The new API allows downloading sets of CPEs (10k at a time) that were modified after a given UTC timestamp. Rate limiting of 5 requests in a sliding 30 seconds window is used [2].
nvd_api_v2.py is used to store the data in a local sqlite database. Only a subset of fields is stored to keep the database "smaller" (still ~200MB).

[0]: https://nvd.nist.gov/General/News/change-timeline
[1]: https://nvd.nist.gov/developers/products
[2]: https://nvd.nist.gov/developers/start-here

---
v3 -> v4:
- progress output moved to nvd_api_v2
- self.connection was renamed to self.db_connection v2 -> v3:
- drop XML handling for gen-missing-cpe
- Move creation of CPE_ID class into this patch

---
 support/scripts/cpe.py    | 89 +++++++++++++++++++++++++++++++++++++++
 support/scripts/cve.py    | 29 +++----------
 support/scripts/pkg-stats | 42 +++---------------
 3 files changed, 100 insertions(+), 60 deletions(-)
 create mode 100755 support/scripts/cpe.py
support/scripts/cpe.py new file +89 -0
new file mode 100755
index 0000000000..671923ebff
@@ -0,0 +1,89 @@
+#!/usr/bin/env python3
+
+from nvd_api_v2 import NVD_API
+
+
+class CPE_ID:
+    @staticmethod
+    def matches(cpe1, cpe2):
+        """Check if two CPE IDs match each other"""
+        cpe1_elems = cpe1.split(":")
+        cpe2_elems = cpe2.split(":")
+
+        remains = filter(lambda x: x[0] not in ["*", "-"] and x[1] not in ["*", "-"] and x[0] != x[1],
+                         zip(cpe1_elems, cpe2_elems))
+        return len(list(remains)) == 0
+
+    @staticmethod
+    def product(cpe):
+        return cpe.split(':')[4]
+
+    @staticmethod
+    def version(cpe):
+        return cpe.split(':')[5]
+
+    @staticmethod
+    def no_version(cpe):
+        return ":".join(cpe.split(":")[:5])
+
+
+class CPE_API(NVD_API):
+    def __init__(self, nvd_path):
+        NVD_API.__init__(self, nvd_path, 'CPEs', 'nvdcpe')
+        self.cpes = list()
+        self.cpes_without_version = dict()
+
+    def init_db(self):
+        cursor = self.db_connection.cursor()
+
+        cursor.execute('CREATE TABLE IF NOT EXISTS products ( \
+            id TEXT UNIQUE, \
+            name TEXT)')
+
+        cursor.close()
+
+    def save_to_db(self, content):
+        cpe_ids_dropped = list()
+        products = list()
+
+        for product in content['products']:
+            if product['cpe']['deprecated']:
+                cpe_ids_dropped.append((product['cpe']['cpeNameId'],))
+                continue
+
+            cpe = product['cpe']
+
+            products.append([cpe['cpeNameId'], cpe['cpeName']])
+
+        cursor = self.db_connection.cursor()
+
+        # Drop all CPEs that are deprecated, status might have changed
+        cursor.executemany('DELETE FROM products WHERE id = ?', cpe_ids_dropped)
+        cursor.executemany('INSERT OR REPLACE INTO products VALUES (?, ?)', products)
+
+        return True
+
+    def load_ids(self):
+        self.check_for_updates()
+
+        cursor = self.db_connection.cursor()
+
+        ids = list()
+        for row in cursor.execute('SELECT name FROM products'):
+            ids.append(row[0])
+
+        cursor.close()
+        self.db_connection.close()
+
+        self.cpes = ids
+        return ids
+
+    def generate_partials(self):
+        self.cpes_without_version = dict()
+        for cpe in self.cpes:
+            self.cpes_without_version[CPE_ID.no_version(cpe)] = cpe
+
+    def find_partial(self, cpe_id):
+        cpe_id_without_version = CPE_ID.no_version(cpe_id)
+        if cpe_id_without_version in self.cpes_without_version.keys():
+            return self.cpes_without_version[cpe_id_without_version]
support/scripts/cve.py +6 -23
index b09ac64c81..ce951d60f6 100755
@@ -20,24 +20,7 @@
 import distutils.version
 import operator
 from nvd_api_v2 import NVD_API
-
-
-# Check if two CPE IDs match each other
-def cpe_matches(cpe1, cpe2):
-    cpe1_elems = cpe1.split(":")
-    cpe2_elems = cpe2.split(":")
-
-    remains = filter(lambda x: x[0] not in ["*", "-"] and x[1] not in ["*", "-"] and x[0] != x[1],
-                     zip(cpe1_elems, cpe2_elems))
-    return len(list(remains)) == 0
-
-
-def cpe_product(cpe):
-    return cpe.split(':')[4]
-
-
-def cpe_version(cpe):
-    return cpe.split(':')[5]
+from cpe import CPE_ID
 
 
 class CVE:
@@ -71,7 +54,7 @@ class CVE:
     @property
     def affected_product(self):
         """Name of the affected product"""
-        return cpe_product(self.match_criteria)
+        return CPE_ID.product(self.match_criteria)
 
     def affects(self, name, version, cve_ignore_list, cpeid=None):
         """
@@ -93,9 +76,9 @@ class CVE:
         # version, as they might be different due to
         # <pkg>_CPE_ID_VERSION
         else:
-            pkg_version = distutils.version.LooseVersion(cpe_version(cpeid))
+            pkg_version = distutils.version.LooseVersion(CPE_ID.version(cpeid))
 
-        if not cpe_matches(self.match_criteria, cpeid):
+        if not CPE_ID.matches(self.match_criteria, cpeid):
             return self.CVE_DOESNT_AFFECT
         if not self.v_start and not self.v_end:
             return self.CVE_AFFECTS
@@ -189,8 +172,8 @@ class CVE_API(NVD_API):
 
     def extract_cpe_match_data(self, cpe_match):
         """Map CPE match information to database fields."""
-        product = cpe_product(cpe_match['criteria'])
-        version = cpe_version(cpe_match['criteria'])
+        product = CPE_ID.product(cpe_match['criteria'])
+        version = CPE_ID.version(cpe_match['criteria'])
         # ignore when product is '-', which means N/A
         if product == '-':
             return
support/scripts/pkg-stats +5 -37

60 lines not on this page · raw message

Signature · 6 lines
2.42.0

_______________________________________________
buildroot mailing list
[email protected]
https://lists.buildroot.org/mailman/listinfo/buildroot
#11 lore raw

PATCH v4 6/6 support/scripts/pkg-stats: Only match CPE vendor and product

In reply to Daniel Lang

Instead of checking if the whole CPE string is known in the database, only check if a string with the same vendor and product exists.

---
v1 -> v2:
- patch added

---
 support/scripts/pkg-stats | 5 +++--
 1 file changed, 3 insertions(+), 2 deletions(-)
support/scripts/pkg-stats +3 -2
index 3d6c53a353..d48582ea3b 100755
@@ -654,11 +654,12 @@ def check_package_cves(nvd_path, packages):
 
 def check_package_cpes(nvd_path, packages):
     cpe_api = CPE_API(nvd_path)
-    cpes = cpe_api.load_ids()
+    cpe_api.load_ids()
+    cpe_api.generate_partials()
     for p in packages:
         if not p.cpeid:
             continue
-        if p.cpeid in cpes:
+        if cpe_api.find_partial(p.cpeid):
             p.status['cpe'] = ("ok", "verified CPE identifier")
         else:
             p.status['cpe'] = ("error", "CPE version unknown in CPE database")
Signature · 6 lines
2.42.0

_______________________________________________
buildroot mailing list
[email protected]
https://lists.buildroot.org/mailman/listinfo/buildroot
#12 lore raw
In reply to Daniel Lang
Quoted 11 lines · On Fri, 1 Sep 2023 21:27:09 +0200 Daniel Lang <[email protected]> wrote:

Some packages are grouped and have a general makefile that defines reusable variables. These makefiles have no relevant information for pkg-stats and should be excluded.

---
v3 -> v4:
- Added more packages to ignore list, not just llvm-project

---
 support/scripts/pkg-stats | 7 ++++++-
 1 file changed, 6 insertions(+), 1 deletion(-)

Applied to master, thanks.

Thomas

Signature · 7 lines
Thomas Petazzoni, CTO, Bootlin
Embedded Linux and Kernel engineering
https://bootlin.com
_______________________________________________
buildroot mailing list
[email protected]
https://lists.buildroot.org/mailman/listinfo/buildroot