Skip to content

Commit cd0c865

Browse files
committed
Faster Weakness Lookup
Signed-off-by: Tushar Goel <tushar.goel.dav@gmail.com>
1 parent 1589949 commit cd0c865

File tree

1 file changed

+29
-3
lines changed

1 file changed

+29
-3
lines changed

vulnerabilities/models.py

Lines changed: 29 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@
77
# See https://aboutcode.org for more information about nexB OSS projects.
88
#
99

10+
import csv
1011
import hashlib
1112
import json
1213
import logging
@@ -46,13 +47,15 @@
4647
from univers.version_range import AlpineLinuxVersionRange
4748
from univers.versions import Version
4849

49-
from aboutcode import hashid
5050
from vulnerabilities import utils
5151
from vulnerabilities.severity_systems import EPSS
5252
from vulnerabilities.severity_systems import SCORING_SYSTEMS
5353
from vulnerabilities.utils import normalize_purl
5454
from vulnerabilities.utils import purl_to_dict
5555
from vulnerablecode import __version__ as VULNERABLECODE_VERSION
56+
from cwe2.weakness import Weakness as DBWeakness
57+
from cwe2.mappings import xml_database_path
58+
import xml.etree.ElementTree as ET
5659

5760
logger = logging.getLogger(__name__)
5861

@@ -466,6 +469,21 @@ def get_severity_vectors_and_values(self):
466469

467470
return severity_vectors, severity_values
468471

472+
def get_cwes(self):
473+
"""Yield CWE Weakness objects"""
474+
for cwe_category in self.cwe_files:
475+
cwe_category.seek(0)
476+
reader = csv.DictReader(cwe_category)
477+
for row in reader:
478+
yield DBWeakness(*list(row.values())[0:-1])
479+
tree = ET.parse(xml_database_path)
480+
root = tree.getroot()
481+
for tag_num in [1, 2]: # Categories , Views
482+
tag = root[tag_num]
483+
for child in tag:
484+
yield DBWeakness(*[child.attrib["ID"], child.attrib.get("Name"),None,child.attrib.get("Status"),child[0].text])
485+
486+
Database.get_cwes = get_cwes
469487

470488
class Weakness(models.Model):
471489
"""
@@ -474,7 +492,15 @@ class Weakness(models.Model):
474492

475493
cwe_id = models.IntegerField(help_text="CWE id")
476494
vulnerabilities = models.ManyToManyField(Vulnerability, related_name="weaknesses")
477-
db = Database()
495+
496+
cwe_by_id = {}
497+
498+
def get_cwe(self, cwe_id):
499+
if not self.cwe_by_id:
500+
db = Database()
501+
for weakness in db.get_cwes():
502+
self.cwe_by_id[str(weakness.cwe_id)] = weakness
503+
return self.cwe_by_id[cwe_id]
478504

479505
@property
480506
def cwe(self):
@@ -486,7 +512,7 @@ def weakness(self):
486512
Return a queryset of Weakness for this vulnerability.
487513
"""
488514
try:
489-
weakness = self.db.get(self.cwe_id)
515+
weakness = self.get_cwe(str(self.cwe_id))
490516
return weakness
491517
except Exception as e:
492518
logger.warning(f"Could not find CWE {self.cwe_id}: {e}")

0 commit comments

Comments
 (0)