-
Notifications
You must be signed in to change notification settings - Fork 202
/
models.py
1396 lines (1136 loc) · 44.2 KB
/
models.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#
# Copyright (c) nexB Inc. and others. All rights reserved.
# VulnerableCode is a trademark of nexB Inc.
# SPDX-License-Identifier: Apache-2.0
# See http://www.apache.org/licenses/LICENSE-2.0 for the license text.
# See https://github.com/nexB/vulnerablecode for support or download.
# See https://aboutcode.org for more information about nexB OSS projects.
#
import hashlib
import json
import logging
from contextlib import suppress
from functools import cached_property
from typing import Optional
from typing import Union
from cwe2.database import Database
from django.contrib.auth import get_user_model
from django.contrib.auth.models import UserManager
from django.core import exceptions
from django.core.exceptions import ValidationError
from django.core.paginator import Paginator
from django.core.validators import MaxValueValidator
from django.core.validators import MinValueValidator
from django.db import models
from django.db import transaction
from django.db.models import Count
from django.db.models import Exists
from django.db.models import OuterRef
from django.db.models import Prefetch
from django.db.models import Q
from django.db.models.functions import Length
from django.db.models.functions import Trim
from django.urls import reverse
from django.utils import timezone
from packageurl import PackageURL
from packageurl.contrib.django.models import PackageURLMixin
from packageurl.contrib.django.models import PackageURLQuerySet
from rest_framework.authtoken.models import Token
from univers.version_range import RANGE_CLASS_BY_SCHEMES
from univers.version_range import AlpineLinuxVersionRange
from univers.versions import Version
from vulnerabilities import utils
from vulnerabilities.severity_systems import SCORING_SYSTEMS
from vulnerabilities.utils import normalize_purl
from vulnerabilities.utils import purl_to_dict
from vulnerablecode import __version__ as VULNERABLECODE_VERSION
logger = logging.getLogger(__name__)
models.CharField.register_lookup(Length)
models.CharField.register_lookup(Trim)
# patch univers for missing entry
RANGE_CLASS_BY_SCHEMES["alpine"] = AlpineLinuxVersionRange
class BaseQuerySet(models.QuerySet):
def get_or_none(self, *args, **kwargs):
"""
Returns a single object matching the given keyword arguments, `None` otherwise.
"""
with suppress(self.model.DoesNotExist, ValidationError):
return self.get(*args, **kwargs)
def paginated(self, per_page=5000):
"""
Iterate over a (large) QuerySet by chunks of ``per_page`` items.
This technique is essential for preventing memory issues when iterating
See these links for inspiration:
https://nextlinklabs.com/resources/insights/django-big-data-iteration
https://stackoverflow.com/questions/4222176/why-is-iterating-through-a-large-django-queryset-consuming-massive-amounts-of-me/
"""
paginator = Paginator(self, per_page=per_page)
for page_number in paginator.page_range:
page = paginator.page(page_number)
for obj in page.object_list:
yield obj
class VulnerabilityQuerySet(BaseQuerySet):
def affecting_vulnerabilities(self):
"""
Return a queryset of Vulnerability that affect a package.
"""
return self.filter(packagerelatedvulnerability__fix=False)
def with_cpes(self):
"""
Return a queryset of Vulnerability that have one or more NVD CPE references.
"""
return self.filter(vulnerabilityreference__reference_id__startswith="cpe")
def for_cpe(self, cpe):
"""
Return a queryset of Vulnerability that have the ``cpe`` as an NVD CPE reference.
"""
return self.filter(vulnerabilityreference__reference_id__exact=cpe)
def with_cves(self):
"""
Return a queryset of Vulnerability that have one or more NVD CVE aliases.
"""
return self.filter(aliases__alias__startswith="CVE")
def for_cve(self, cve):
"""
Return a queryset of Vulnerability that have the the NVD CVE ``cve`` as an alias.
"""
return self.filter(vulnerabilityreference__reference_id__exact=cve)
def with_packages(self):
"""
Return a queryset of Vulnerability that have one or more related packages.
"""
return self.filter(packages__isnull=False)
def search(self, query: str = None):
"""
Return a Vulnerability queryset searching for the ``query``.
Make a best effort approach to search a vulnerability using various heuristics.
"""
query = query and query.strip()
if not query:
return self.none()
qs = self
# middle ground, exact on vulnerability_id
qssearch = qs.filter(vulnerability_id=query)
if not qssearch.exists():
# middle ground, exact on alias
qssearch = qs.filter(aliases__alias=query)
if not qssearch.exists():
# middle ground, slow enough
qssearch = qs.filter(
Q(vulnerability_id__icontains=query) | Q(aliases__alias__icontains=query)
)
if not qssearch.exists():
# last resort super slow
qssearch = qs.filter(
Q(references__id__icontains=query) | Q(summary__icontains=query)
)
return qssearch.order_by("vulnerability_id")
def with_package_counts(self):
return self.annotate(
vulnerable_package_count=Count(
"packages", filter=Q(packagerelatedvulnerability__fix=False), distinct=True
),
patched_package_count=Count(
"packages", filter=Q(packagerelatedvulnerability__fix=True), distinct=True
),
)
class VulnerabilityStatusType(models.IntegerChoices):
"""List of vulnerability statuses."""
PUBLISHED = 1, "Published"
DISPUTED = 2, "Disputed"
INVALID = 3, "Invalid"
class Vulnerability(models.Model):
"""
A software vulnerability with a unique identifier and alternate ``aliases``.
"""
vulnerability_id = models.CharField(
unique=True,
blank=True,
max_length=20,
default=utils.build_vcid,
help_text="Unique identifier for a vulnerability in the external representation. "
"It is prefixed with VCID-",
)
summary = models.TextField(
help_text="Summary of the vulnerability",
blank=True,
)
references = models.ManyToManyField(
to="VulnerabilityReference", through="VulnerabilityRelatedReference"
)
packages = models.ManyToManyField(
to="Package",
through="PackageRelatedVulnerability",
)
status = models.IntegerField(
choices=VulnerabilityStatusType.choices, default=VulnerabilityStatusType.PUBLISHED
)
objects = VulnerabilityQuerySet.as_manager()
class Meta:
verbose_name_plural = "Vulnerabilities"
ordering = ["vulnerability_id"]
def __str__(self):
return self.vulnerability_id
@property
def vcid(self):
return self.vulnerability_id
@property
def severities(self):
"""
Return a queryset of VulnerabilitySeverity for this vulnerability.
"""
return VulnerabilitySeverity.objects.filter(reference__in=self.references.all())
@property
def affected_packages(self):
"""
Return a queryset of packages that are affected by this vulnerability.
"""
return self.packages.affected()
# legacy aliases
vulnerable_packages = affected_packages
@property
def fixed_by_packages(self):
"""
Return a queryset of packages that are fixing this vulnerability.
"""
return self.packages.fixing()
# legacy alias
patched_packages = fixed_by_packages
@property
def get_aliases(self):
"""
Return a queryset of all Aliases for this vulnerability.
"""
return self.aliases.all()
alias = get_aliases
@property
def get_status_label(self):
label_by_status = {choice[0]: choice[1] for choice in VulnerabilityStatusType.choices}
return label_by_status.get(self.status) or VulnerabilityStatusType.PUBLISHED.label
@property
def history(self):
return self.changelog.all()
def get_absolute_url(self):
"""
Return this Vulnerability details absolute URL.
"""
return reverse("vulnerability_details", args=[self.vulnerability_id])
def get_details_url(self, request):
"""
Return this Package details URL.
"""
from rest_framework.reverse import reverse
return reverse(
"vulnerability_details",
kwargs={"vulnerability_id": self.vulnerability_id},
request=request,
)
def get_related_cpes(self):
"""
Return a list of CPE strings of this vulnerability.
"""
return list(self.references.for_cpe().values_list("reference_id", flat=True).distinct())
def get_related_cves(self):
"""
Return a list of aliases CVE strings of this vulnerability.
"""
return list(self.aliases.for_cve().values_list("alias", flat=True).distinct())
def get_affected_purls(self):
"""
Return a list of purl strings affected by this vulnerability.
"""
return [p.package_url for p in self.affected_packages.all()]
def get_fixing_purls(self):
"""
Return a list of purl strings fixing this vulnerability.
"""
return [p.package_url for p in self.fixed_by_packages.all()]
def get_related_purls(self):
"""
Return a list of purl strings related to this vulnerability.
"""
return [p.package_url for p in self.packages.distinct().all()]
class Weakness(models.Model):
"""
A Common Weakness Enumeration model
"""
cwe_id = models.IntegerField(help_text="CWE id")
vulnerabilities = models.ManyToManyField(Vulnerability, related_name="weaknesses")
db = Database()
@property
def weakness(self):
"""
Return a queryset of Weakness for this vulnerability.
"""
try:
weakness = self.db.get(self.cwe_id)
return weakness
except Exception as e:
logger.warning(f"Could not find CWE {self.cwe_id}: {e}")
@property
def name(self):
"""Return the weakness's name."""
return self.weakness.name if self.weakness else ""
@property
def description(self):
"""Return the weakness's description."""
return self.weakness.description if self.weakness else ""
def to_dict(self):
return {"cwe_id": self.cwe_id, "name": self.name, "description": self.description}
class VulnerabilityReferenceQuerySet(BaseQuerySet):
def for_cpe(self):
"""
Return a queryset of VulnerabilityReferences that are for a CPE.
"""
return self.filter(reference_id__startswith="cpe")
class VulnerabilityReference(models.Model):
"""
A reference to a vulnerability such as a security advisory from a Linux distribution or language
package manager.
"""
vulnerabilities = models.ManyToManyField(
to="Vulnerability",
through="VulnerabilityRelatedReference",
)
url = models.URLField(
max_length=1024,
help_text="URL to the vulnerability reference",
unique=True,
)
ADVISORY = "advisory"
EXPLOIT = "exploit"
MAILING_LIST = "mailing_list"
BUG = "bug"
OTHER = "other"
REFERENCE_TYPES = [
(ADVISORY, "Advisory"),
(EXPLOIT, "Exploit"),
(MAILING_LIST, "Mailing List"),
(BUG, "Bug"),
(OTHER, "Other"),
]
reference_type = models.CharField(max_length=20, choices=REFERENCE_TYPES, blank=True)
reference_id = models.CharField(
max_length=200,
help_text="An optional reference ID, such as DSA-4465-1 when available",
blank=True,
)
objects = VulnerabilityReferenceQuerySet.as_manager()
class Meta:
ordering = ["reference_id", "url", "reference_type"]
def __str__(self):
reference_id = f" {self.reference_id}" if self.reference_id else ""
return f"{self.url}{reference_id}"
@property
def is_cpe(self):
"""
Return Trueis this is a CPE reference.
"""
return self.reference_id.startswith("cpe")
class VulnerabilityRelatedReference(models.Model):
"""
A reference related to a vulnerability.
"""
vulnerability = models.ForeignKey(
Vulnerability,
on_delete=models.CASCADE,
)
reference = models.ForeignKey(
VulnerabilityReference,
on_delete=models.CASCADE,
)
class Meta:
unique_together = ["vulnerability", "reference"]
ordering = ["vulnerability", "reference"]
class PackageQuerySet(BaseQuerySet, PackageURLQuerySet):
def get_fixed_by_package_versions(self, purl: PackageURL, fix=True):
"""
Return a queryset of all the package versions of this `package` that fix any vulnerability.
If `fix` is False, return all package versions whether or not they fix a vulnerability.
"""
filter_dict = {
"name": purl.name,
"namespace": purl.namespace,
"type": purl.type,
"qualifiers": purl.qualifiers,
"subpath": purl.subpath,
}
if fix:
filter_dict["packagerelatedvulnerability__fix"] = True
return Package.objects.filter(**filter_dict).distinct()
def get_or_create_from_purl(self, purl: Union[PackageURL, str]):
"""
Return a new or existing Package given a ``purl`` PackageURL object or PURL string.
"""
package, is_created = Package.objects.get_or_create(**purl_to_dict(purl=purl))
return package, is_created
def from_purl(self, purl: Union[PackageURL, str]):
"""
Return a new Package given a ``purl`` PackageURL object or PURL string.
"""
return Package.objects.create(**purl_to_dict(purl=purl))
def affected(self):
"""
Return only packages affected by a vulnerability.
"""
return self.filter(packagerelatedvulnerability__fix=False)
vulnerable = affected
def fixing(self):
"""
Return only packages fixing a vulnerability .
"""
return self.filter(packagerelatedvulnerability__fix=True)
def with_vulnerability_counts(self):
return self.annotate(
vulnerability_count=Count(
"vulnerabilities",
filter=Q(packagerelatedvulnerability__fix=False),
),
patched_vulnerability_count=Count(
"vulnerabilities",
filter=Q(packagerelatedvulnerability__fix=True),
),
)
def fixing_packages(self, package, with_qualifiers_and_subpath=True):
"""
Return a queryset of packages that are fixing the vulnerability of
``package``.
"""
return self.match_purl(
purl=package.purl,
with_qualifiers_and_subpath=with_qualifiers_and_subpath,
).fixing()
def search(self, query: str = None):
"""
Return a Package queryset searching for the ``query``.
Make a best effort approach to find matching packages either based
on exact purl, partial purl or just name and namespace.
"""
query = query and query.strip()
if not query:
return self.none()
qs = self
try:
# if it's a valid purl, try to parse it and use it as is
purl = str(utils.plain_purl(query))
qs = qs.filter(package_url__istartswith=purl)
except ValueError:
# otherwise use query as a plain string
qs = qs.filter(package_url__icontains=query)
return qs.order_by("package_url")
def for_purl(self, purl):
"""
Return a queryset matching the ``purl`` Package URL.
"""
return self.filter(**purl_to_dict(purl))
def with_cpes(self):
"""
Return a queryset of Package that a vulnerability with one or more NVD CPE references.
"""
return self.filter(vulnerabilities__vulnerabilityreference__reference_id__startswith="cpe")
def for_cpe(self, cpe):
"""
Return a queryset of Vulnerability that have the ``cpe`` as an NVD CPE reference.
"""
return self.filter(vulnerabilities__vulnerabilityreference__reference_id__exact=cpe)
def with_cves(self):
"""
Return a queryset of Vulnerability that have one or more NVD CVE aliases.
"""
return self.filter(vulnerabilities__aliases__alias__startswith="CVE")
def for_cve(self, cve):
"""
Return a queryset of Vulnerability that have the the NVD CVE ``cve`` as an alias.
"""
return self.filter(vulnerabilities__vulnerabilityreference__reference_id__exact=cve)
def for_purls(self, purls=[]):
return Package.objects.filter(package_url__in=purls).distinct()
def with_is_vulnerable(self):
"""
Annotate Package with ``with_is_vulnerable`` boolean attribute.
"""
return self.annotate(
is_vulnerable=Exists(
PackageRelatedVulnerability.objects.filter(
package=OuterRef("pk"),
fix=False,
)
)
)
def only_vulnerable(self):
return self._vulnerable(True)
def only_non_vulnerable(self):
return self._vulnerable(False)
def _vulnerable(self, vulnerable=True):
"""
Filter to select only vulnerable or non-vulnearble packages.
"""
return self.with_is_vulnerable().filter(is_vulnerable=vulnerable)
def get_purl_query_lookups(purl):
"""
Return a dictionary of non-empty plain purl fields
Do not reference all the possible qualifiers and relax the
purl matching to only lookup the type, namespace, name and version fields.
"""
plain_purl = utils.plain_purl(purl=purl)
return purl_to_dict(plain_purl, with_empty=False)
class Package(PackageURLMixin):
"""
A software package with related vulnerabilities.
"""
# Remove the `qualifers` and `set_package_url` overrides after
# https://github.com/package-url/packageurl-python/pull/35
# https://github.com/package-url/packageurl-python/pull/67
# gets merged
vulnerabilities = models.ManyToManyField(
to="Vulnerability", through="PackageRelatedVulnerability"
)
package_url = models.CharField(
max_length=1000,
null=False,
help_text="The Package URL for this package.",
db_index=True,
)
plain_package_url = models.CharField(
max_length=1000,
null=False,
help_text="The Package URL for this package without qualifiers and subpath.",
db_index=True,
)
objects = PackageQuerySet.as_manager()
def save(self, *args, **kwargs):
"""
Save, normalizing PURL fields.
"""
purl = PackageURL(
type=self.type,
namespace=self.namespace,
name=self.name,
version=self.version,
qualifiers=self.qualifiers,
subpath=self.subpath,
)
# We re-parse the purl to ensure name and namespace
# are set correctly
normalized = normalize_purl(purl=purl)
for name, value in purl_to_dict(normalized).items():
setattr(self, name, value)
self.package_url = str(normalized)
plain_purl = utils.plain_purl(normalized)
self.plain_package_url = str(plain_purl)
super().save(*args, **kwargs)
@property
def purl(self):
return self.package_url
class Meta:
unique_together = ["type", "namespace", "name", "version", "qualifiers", "subpath"]
ordering = ["type", "namespace", "name", "version", "qualifiers", "subpath"]
def __str__(self):
return self.package_url
@property
def affected_by(self):
"""
Return a queryset of vulnerabilities affecting this package.
"""
return self.vulnerabilities.filter(packagerelatedvulnerability__fix=False)
# legacy aliases
vulnerable_to = affected_by
@property
# TODO: consider renaming to "fixes" or "fixing" ? (TBD) and updating the docstring
def fixing(self):
"""
Return a queryset of vulnerabilities fixed by this package.
"""
return self.vulnerabilities.filter(packagerelatedvulnerability__fix=True)
# legacy aliases
resolved_to = fixing
@property
def fixed_packages(self):
"""
Return a queryset of packages that are fixed.
"""
return Package.objects.fixing_packages(package=self).distinct()
@property
def history(self):
return self.changelog.all()
def get_absolute_url(self):
"""
Return this Package details URL.
"""
return reverse("package_details", args=[self.purl])
def get_details_url(self, request):
"""
Return this Package details URL.
"""
from rest_framework.reverse import reverse
return reverse("package_details", kwargs={"purl": self.purl}, request=request)
def sort_by_version(self, packages):
"""
Return a sequence of `packages` sorted by version.
"""
if not packages:
return []
return sorted(packages, key=lambda x: self.version_class(x.version))
@cached_property
def version_class(self):
range_class = RANGE_CLASS_BY_SCHEMES.get(self.type)
return range_class.version_class if range_class else Version
@cached_property
def current_version(self):
return self.version_class(self.version)
@property
def fixed_package_details(self):
"""
Return a mapping of vulnerabilities that affect this package and the next and
latest non-vulnerable versions.
"""
package_details = {}
package_details["purl"] = PackageURL.from_string(self.purl)
next_non_vulnerable, latest_non_vulnerable = self.get_non_vulnerable_versions()
package_details["next_non_vulnerable"] = next_non_vulnerable
package_details["latest_non_vulnerable"] = latest_non_vulnerable
package_details["vulnerabilities"] = self.get_affecting_vulnerabilities()
return package_details
def get_non_vulnerable_versions(self):
"""
Return a tuple of the next and latest non-vulnerable versions as PackageURLs. Return a tuple of
(None, None) if there is no non-vulnerable version.
"""
non_vulnerable_versions = Package.objects.get_fixed_by_package_versions(
self, fix=False
).only_non_vulnerable()
sorted_versions = self.sort_by_version(non_vulnerable_versions)
later_non_vulnerable_versions = []
for non_vuln_ver in sorted_versions:
if self.version_class(non_vuln_ver.version) > self.current_version:
later_non_vulnerable_versions.append(non_vuln_ver)
if later_non_vulnerable_versions:
sorted_versions = self.sort_by_version(later_non_vulnerable_versions)
next_non_vulnerable_version = sorted_versions[0]
latest_non_vulnerable_version = sorted_versions[-1]
next_non_vulnerable = PackageURL.from_string(next_non_vulnerable_version.purl)
latest_non_vulnerable = PackageURL.from_string(latest_non_vulnerable_version.purl)
return next_non_vulnerable, latest_non_vulnerable
return None, None
def get_affecting_vulnerabilities(self):
"""
Return a list of vulnerabilities that affect this package together with information regarding
the versions that fix the vulnerabilities.
"""
package_details_vulns = []
fixed_by_packages = Package.objects.get_fixed_by_package_versions(self, fix=True)
package_vulnerabilities = self.vulnerabilities.affecting_vulnerabilities().prefetch_related(
Prefetch(
"packages",
queryset=fixed_by_packages,
to_attr="fixed_packages",
)
)
for vuln in package_vulnerabilities:
package_details_vulns.append({"vulnerability": vuln})
later_fixed_packages = []
for fixed_pkg in vuln.fixed_packages:
if fixed_pkg not in fixed_by_packages:
continue
fixed_version = self.version_class(fixed_pkg.version)
if fixed_version > self.current_version:
later_fixed_packages.append(fixed_pkg)
next_fixed_package = None
next_fixed_package_vulns = []
sort_fixed_by_packages_by_version = []
if later_fixed_packages:
sort_fixed_by_packages_by_version = self.sort_by_version(later_fixed_packages)
fixed_by_pkgs = []
for vuln_details in package_details_vulns:
if vuln_details["vulnerability"] != vuln:
continue
vuln_details["fixed_by_purl"] = []
vuln_details["fixed_by_purl_vulnerabilities"] = []
for fixed_by_pkg in sort_fixed_by_packages_by_version:
fixed_by_package_details = {}
fixed_by_purl = PackageURL.from_string(fixed_by_pkg.purl)
next_fixed_package_vulns = list(fixed_by_pkg.affected_by)
fixed_by_package_details["fixed_by_purl"] = fixed_by_purl
fixed_by_package_details[
"fixed_by_purl_vulnerabilities"
] = next_fixed_package_vulns
fixed_by_pkgs.append(fixed_by_package_details)
vuln_details["fixed_by_package_details"] = fixed_by_pkgs
return package_details_vulns
@property
def fixing_vulnerabilities(self):
"""
Return a queryset of Vulnerabilities that are fixed by this `package`.
"""
return self.vulnerabilities.filter(packagerelatedvulnerability__fix=True)
@property
def affecting_vulnerabilities(self):
"""
Return a queryset of Vulnerabilities that affect this `package`.
"""
return self.vulnerabilities.filter(packagerelatedvulnerability__fix=False)
class PackageRelatedVulnerability(models.Model):
"""
Track the relationship between a Package and Vulnerability.
"""
# TODO: Fix related_name
package = models.ForeignKey(
Package,
on_delete=models.CASCADE,
)
vulnerability = models.ForeignKey(
Vulnerability,
on_delete=models.CASCADE,
)
created_by = models.CharField(
max_length=100,
blank=True,
help_text="Fully qualified name of the improver prefixed with the"
"module name responsible for creating this relation. Eg:"
"vulnerabilities.importers.nginx.NginxBasicImprover",
)
from vulnerabilities.improver import MAX_CONFIDENCE
confidence = models.PositiveIntegerField(
default=MAX_CONFIDENCE,
validators=[MinValueValidator(0), MaxValueValidator(MAX_CONFIDENCE)],
help_text="Confidence score for this relation",
)
fix = models.BooleanField(
default=False,
db_index=True,
help_text="Does this relation fix the specified vulnerability ?",
)
class Meta:
unique_together = ["package", "vulnerability"]
verbose_name_plural = "PackageRelatedVulnerabilities"
indexes = [models.Index(fields=["fix"])]
ordering = ["package", "vulnerability"]
def __str__(self):
return f"{self.package.package_url} {self.vulnerability.vulnerability_id}"
def update_or_create(self, advisory):
"""
Update if supplied record has more confidence than existing record
Create if doesn't exist
"""
try:
existing = PackageRelatedVulnerability.objects.get(
vulnerability=self.vulnerability, package=self.package
)
if self.confidence > existing.confidence:
existing.created_by = self.created_by
existing.confidence = self.confidence
existing.fix = self.fix
existing.save()
# TODO: later we want these to be part of a log field in the DB
logger.info(
f"Confidence improved for {self.package} R {self.vulnerability}, "
f"new confidence: {self.confidence}"
)
self.add_package_vulnerability_changelog(advisory=advisory)
except self.DoesNotExist:
PackageRelatedVulnerability.objects.create(
vulnerability=self.vulnerability,
created_by=self.created_by,
package=self.package,
confidence=self.confidence,
fix=self.fix,
)
logger.info(
f"New relationship {self.package} R {self.vulnerability}, "
f"fix: {self.fix}, confidence: {self.confidence}"
)
self.add_package_vulnerability_changelog(advisory=advisory)
@transaction.atomic
def add_package_vulnerability_changelog(self, advisory):
from vulnerabilities.utils import get_importer_name
importer_name = get_importer_name(advisory)
if self.fix:
change_logger = PackageChangeLog.log_fixing
else:
change_logger = PackageChangeLog.log_affected_by
change_logger(
package=self.package,
importer=importer_name,
source_url=advisory.url or None,
related_vulnerability=str(self.vulnerability),
)
class VulnerabilitySeverity(models.Model):
reference = models.ForeignKey(VulnerabilityReference, on_delete=models.CASCADE)
scoring_system_choices = tuple(
(system.identifier, system.name) for system in SCORING_SYSTEMS.values()
)
scoring_system = models.CharField(
max_length=50,
choices=scoring_system_choices,
help_text="Identifier for the scoring system used. Available choices are: {} ".format(
",\n".join(f"{sid}: {sname}" for sid, sname in scoring_system_choices)
),
)
value = models.CharField(max_length=50, help_text="Example: 9.0, Important, High")
scoring_elements = models.CharField(
max_length=150,
null=True,
help_text="Supporting scoring elements used to compute the score values. "
"For example a CVSS vector string as used to compute a CVSS score.",
)
published_at = models.DateTimeField(
blank=True, null=True, help_text="UTC Date of publication of the vulnerability severity"
)
class Meta:
unique_together = ["reference", "scoring_system", "value"]
ordering = ["reference", "scoring_system", "value"]
class AliasQuerySet(BaseQuerySet):
def for_cve(self):
"""
Return a queryset of Aliases that are for a CVE.
"""
return self.filter(alias__startswith="CVE")
class Alias(models.Model):
"""
An alias is a unique vulnerability identifier in some database, such as
the NVD, PYSEC, CVE or similar. These databases guarantee that these
identifiers are unique within their namespace.
An alias may also be used as a Reference. But in contrast with some
Reference may not be an identifier for a single vulnerability, for instance,
security advisories such as Debian security advisory reference various
vulnerabilities.
"""
alias = models.CharField(
max_length=50,
unique=True,
blank=False,
null=False,
help_text="An alias is a unique vulnerability identifier in some database, "
"such as CVE-2020-2233",
)
vulnerability = models.ForeignKey(
Vulnerability,
on_delete=models.CASCADE,
related_name="aliases",
)
objects = AliasQuerySet.as_manager()