-
-
Notifications
You must be signed in to change notification settings - Fork 47
/
Copy pathvulnerability.py
1099 lines (886 loc) · 37.2 KB
/
vulnerability.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
# encoding: utf-8
# This file is part of CycloneDX Python Lib
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
# SPDX-License-Identifier: Apache-2.0
# Copyright (c) OWASP Foundation. All Rights Reserved.
import re
import warnings
from datetime import datetime
from decimal import Decimal
from enum import Enum
from typing import List, Optional, Tuple, Union
from urllib.parse import ParseResult, urlparse
from uuid import uuid4
from . import OrganizationalContact, OrganizationalEntity, Tool, XsUri
from .impact_analysis import ImpactAnalysisAffectedStatus, ImpactAnalysisJustification, ImpactAnalysisResponse, \
ImpactAnalysisState
from ..exception.model import MutuallyExclusivePropertiesException, NoPropertiesProvidedException
"""
This set of classes represents the data that is possible about known Vulnerabilities.
Prior to CycloneDX schema version 1.4, vulnerabilities were possible in XML versions ONLY of the standard through
a schema extension: https://cyclonedx.org/ext/vulnerability.
Since CycloneDX schema version 1.4, this has become part of the core schema.
.. note::
See the CycloneDX Schema extension definition https://cyclonedx.org/docs/1.4/#type_vulnerabilitiesType
"""
class BomTargetVersionRange:
"""
Class that represents either a version or version range and its affected status.
`version` and `version_range` are mutually exclusive.
.. note::
See the CycloneDX schema: https://cyclonedx.org/docs/1.4/#type_vulnerabilityType
"""
def __init__(self, version: Optional[str] = None, version_range: Optional[str] = None,
status: Optional[ImpactAnalysisAffectedStatus] = None) -> None:
if not version and not version_range:
raise NoPropertiesProvidedException(
'One of version or version_range must be provided for BomTargetVersionRange - neither provided.'
)
if version and version_range:
raise MutuallyExclusivePropertiesException(
'Either version or version_range should be provided for BomTargetVersionRange - both provided.'
)
self.version = version
self.range = version_range
self.status = status
@property
def version(self) -> Optional[str]:
"""
A single version of a component or service.
"""
return self._version
@version.setter
def version(self, version: Optional[str]) -> None:
self._version = version
@property
def range(self) -> Optional[str]:
"""
A version range specified in Package URL Version Range syntax (vers) which is defined at
https://github.com/package-url/purl-spec/VERSION-RANGE-SPEC.rst
.. note::
The VERSION-RANGE-SPEC from Package URL is not a formalised standard at the time of writing and this no
validation of conformance with this draft standard is performed.
"""
return self._range
@range.setter
def range(self, version_range: Optional[str]) -> None:
self._range = version_range
@property
def status(self) -> Optional[ImpactAnalysisAffectedStatus]:
"""
The vulnerability status for the version or range of versions.
"""""
return self._status
@status.setter
def status(self, status: Optional[ImpactAnalysisAffectedStatus]) -> None:
self._status = status
def __eq__(self, other: object) -> bool:
if isinstance(other, BomTargetVersionRange):
return hash(other) == hash(self)
return False
def __hash__(self) -> int:
return hash((self.version, self.range, hash(self.status)))
def __repr__(self) -> str:
return f'<BomTargetVersionRange version={self.version}, version_range={self.range}, status={self.status}>'
class BomTarget:
"""
Class that represents referencing a Component or Service in a BOM.
Aims to represent the sub-element `target` of the complex type `vulnerabilityType`.
You can either create a `cyclonedx.model.bom.Bom` yourself programmatically, or generate a `cyclonedx.model.bom.Bom`
from a `cyclonedx.parser.BaseParser` implementation.
.. note::
See the CycloneDX schema: https://cyclonedx.org/docs/1.4/#type_vulnerabilityType
"""
def __init__(self, ref: str, versions: Optional[List[BomTargetVersionRange]] = None) -> None:
self.ref = ref
self.versions = versions
@property
def ref(self) -> str:
"""
Reference to a component or service by the objects `bom-ref`.
"""
return self._ref
@ref.setter
def ref(self, ref: str) -> None:
self._ref = ref
@property
def versions(self) -> Optional[List[BomTargetVersionRange]]:
"""
Zero or more individual versions or range of versions.
"""
return self._versions
@versions.setter
def versions(self, versions: Optional[List[BomTargetVersionRange]]) -> None:
self._versions = versions
def __eq__(self, other: object) -> bool:
if isinstance(other, BomTarget):
return hash(other) == hash(self)
return False
def __hash__(self) -> int:
return hash((
self.ref,
tuple([hash(version) for version in set(sorted(self.versions, key=hash))]) if self.versions else None
))
def __repr__(self) -> str:
return f'<BomTarget ref={self.ref}>'
class VulnerabilityAnalysis:
"""
Class that models the `analysis` sub-element of the `vulnerabilityType` complex type.
.. note::
See the CycloneDX schema: https://cyclonedx.org/docs/1.4/#type_vulnerabilityType
"""
def __init__(self, state: Optional[ImpactAnalysisState] = None,
justification: Optional[ImpactAnalysisJustification] = None,
responses: Optional[List[ImpactAnalysisResponse]] = None,
detail: Optional[str] = None) -> None:
if not state and not justification and not responses and not detail:
raise NoPropertiesProvidedException(
'At least one of state, justification, responses or detail must be provided for VulnerabilityAnalysis '
'- none supplied'
)
self.state = state
self.justification = justification
self.response = responses
self.detail = detail
@property
def state(self) -> Optional[ImpactAnalysisState]:
"""
The declared current state of an occurrence of a vulnerability, after automated or manual analysis.
"""
return self._state
@state.setter
def state(self, state: Optional[ImpactAnalysisState]) -> None:
self._state = state
@property
def justification(self) -> Optional[ImpactAnalysisJustification]:
"""
The rationale of why the impact analysis state was asserted.
"""
return self._justification
@justification.setter
def justification(self, justification: Optional[ImpactAnalysisJustification]) -> None:
self._justification = justification
@property
def response(self) -> Optional[List[ImpactAnalysisResponse]]:
"""
A list of responses to the vulnerability by the manufacturer, supplier, or project responsible for the
affected component or service. More than one response is allowed. Responses are strongly encouraged for
vulnerabilities where the analysis state is exploitable.
"""
return self._response
@response.setter
def response(self, responses: Optional[List[ImpactAnalysisResponse]]) -> None:
self._response = responses
@property
def detail(self) -> Optional[str]:
"""
A detailed description of the impact including methods used during assessment. If a vulnerability is not
exploitable, this field should include specific details on why the component or service is not impacted by this
vulnerability.
:return:
"""
return self._detail
@detail.setter
def detail(self, detail: Optional[str]) -> None:
self._detail = detail
def __eq__(self, other: object) -> bool:
if isinstance(other, VulnerabilityAnalysis):
return hash(other) == hash(self)
return False
def __hash__(self) -> int:
return hash((
self.state, self.justification,
tuple([hash(r) for r in set(sorted(self.response, key=hash))]) if self.response else None,
self.detail
))
def __repr__(self) -> str:
return f'<VulnerabilityAnalysis state={self.state}, justification={self.justification}>'
class VulnerabilityAdvisory:
"""
Class that models the `advisoryType` complex type.
.. note::
See the CycloneDX schema: https://cyclonedx.org/docs/1.4/#type_advisoryType
"""
def __init__(self, url: XsUri, title: Optional[str] = None) -> None:
self.title = title
self.url = url
@property
def title(self) -> Optional[str]:
"""
The title of this advisory.
"""
return self._title
@title.setter
def title(self, title: Optional[str]) -> None:
self._title = title
@property
def url(self) -> XsUri:
"""
The url of this advisory.
"""
return self._url
@url.setter
def url(self, url: XsUri) -> None:
self._url = url
def __eq__(self, other: object) -> bool:
if isinstance(other, VulnerabilityAdvisory):
return hash(other) == hash(self)
return False
def __hash__(self) -> int:
return hash((self.title, self.url))
def __repr__(self) -> str:
return f'<VulnerabilityAdvisory url={self.url}, title={self.title}>'
class VulnerabilitySource:
"""
Class that models the `vulnerabilitySourceType` complex type.
This type is used for multiple purposes in the CycloneDX schema.
.. note::
See the CycloneDX schema: https://cyclonedx.org/docs/1.4/#type_vulnerabilitySourceType
"""
def __init__(self, name: Optional[str] = None, url: Optional[XsUri] = None) -> None:
if not name and not url:
raise NoPropertiesProvidedException(
'Either name or url must be provided for a VulnerabilitySource - neither provided'
)
self.name = name
self.url = url
@property
def name(self) -> Optional[str]:
"""
Name of this Source.
"""
return self._name
@name.setter
def name(self, name: Optional[str]) -> None:
self._name = name
@property
def url(self) -> Optional[XsUri]:
"""
The url of this Source.
"""
return self._url
@url.setter
def url(self, url: Optional[XsUri]) -> None:
self._url = url
def __eq__(self, other: object) -> bool:
if isinstance(other, VulnerabilitySource):
return hash(other) == hash(self)
return False
def __hash__(self) -> int:
return hash((self.name, self.url))
def __repr__(self) -> str:
return f'<VulnerabilityAdvisory name={self.name}, url={self.url}>'
class VulnerabilityReference:
"""
Class that models the nested `reference` within the `vulnerabilityType` complex type.
Vulnerabilities may benefit from pointers to vulnerabilities that are the equivalent of the vulnerability specified.
Often times, the same vulnerability may exist in multiple sources of vulnerability intelligence, but have different
identifiers. These references provide a way to correlate vulnerabilities across multiple sources of vulnerability
intelligence.
.. note::
See the CycloneDX schema: https://cyclonedx.org/docs/1.4/#type_vulnerabilityType
"""
def __init__(self, id: Optional[str] = None, source: Optional[VulnerabilitySource] = None) -> None:
if not id and not source:
raise NoPropertiesProvidedException(
'Either id or source must be provided for a VulnerabilityReference - neither provided'
)
self.id = id
self.source = source
@property
def id(self) -> Optional[str]:
"""
The identifier that uniquely identifies the vulnerability in the associated Source. For example: CVE-2021-39182.
"""
return self._id
@id.setter
def id(self, id: Optional[str]) -> None:
self._id = id
@property
def source(self) -> Optional[VulnerabilitySource]:
"""
The source that published the vulnerability.
"""
return self._source
@source.setter
def source(self, source: Optional[VulnerabilitySource]) -> None:
self._source = source
def __eq__(self, other: object) -> bool:
if isinstance(other, VulnerabilityReference):
return hash(other) == hash(self)
return False
def __hash__(self) -> int:
return hash((self.id, hash(self.source)))
def __repr__(self) -> str:
return f'<VulnerabilityReference id={self.id}, source={self.source}>'
class VulnerabilityScoreSource(Enum):
"""
Enum object that defines the permissible source types for a Vulnerability's score.
.. note::
See the CycloneDX Schema definition: https://cyclonedx.org/docs/1.4/#type_scoreSourceType
"""
CVSS_V2 = 'CVSSv2'
CVSS_V3 = 'CVSSv3'
CVSS_V3_1 = 'CVSSv31'
OWASP = 'OWASP' # Name change in 1.4
OPEN_FAIR = 'Open FAIR' # Only < 1.4
OTHER = 'other'
@staticmethod
def get_from_vector(vector: str) -> 'VulnerabilityScoreSource':
"""
Attempt to derive the correct SourceType from an attack vector.
For example, often attack vector strings are prefixed with the scheme in question - such
that __CVSS:3.0/AV:L/AC:L/PR:N/UI:R/S:C/C:L/I:N/A:N__ would be the vector
__AV:L/AC:L/PR:N/UI:R/S:C/C:L/I:N/A:N__ under the __CVSS 3__ scheme.
Returns:
Always returns an instance of `VulnerabilityScoreSource`. `VulnerabilityScoreSource.OTHER` is
returned if the scheme is not obvious or known to us.
"""
if vector.startswith('CVSS:3.'):
return VulnerabilityScoreSource.CVSS_V3
elif vector.startswith('CVSS:2.'):
return VulnerabilityScoreSource.CVSS_V2
elif vector.startswith('OWASP'):
return VulnerabilityScoreSource.OWASP
else:
return VulnerabilityScoreSource.OTHER
def get_localised_vector(self, vector: str) -> str:
"""
This method will remove any Source Scheme type from the supplied vector, returning just the vector.
.. Note::
Currently supports CVSS 3.x, CVSS 2.x and OWASP schemes.
Returns:
The vector without any scheme prefix as a `str`.
"""
if self == VulnerabilityScoreSource.CVSS_V3 and vector.startswith('CVSS:3.'):
return re.sub('^CVSS:3\\.\\d/?', '', vector)
if self == VulnerabilityScoreSource.CVSS_V2 and vector.startswith('CVSS:2.'):
return re.sub('^CVSS:2\\.\\d/?', '', vector)
if self == VulnerabilityScoreSource.OWASP and vector.startswith('OWASP'):
return re.sub('^OWASP/?', '', vector)
return vector
def get_value_pre_1_4(self) -> str:
"""
Some of the enum values changed in 1.4 of the CycloneDX spec. This method allows us to
backport some of the changes for pre-1.4.
Returns:
`str`
"""
if self == VulnerabilityScoreSource.OWASP:
return 'OWASP Risk'
return self.value
class VulnerabilitySeverity(Enum):
"""
Class that defines the permissible severities for a Vulnerability.
.. note::
See the CycloneDX schema: https://cyclonedx.org/docs/1.4/#type_severityType
"""
NONE = 'none'
INFO = 'info' # Only >= 1.4
LOW = 'low'
MEDIUM = 'medium'
HIGH = 'high'
CRITICAL = 'critical'
UNKNOWN = 'unknown'
@staticmethod
def get_from_cvss_scores(scores: Union[Tuple[float], float, None]) -> 'VulnerabilitySeverity':
"""
Derives the Severity of a Vulnerability from it's declared CVSS scores.
Args:
scores: A `tuple` of CVSS scores. CVSS scoring system allows for up to three separate scores.
Returns:
Always returns an instance of `VulnerabilitySeverity`.
"""
if type(scores) is float:
scores = (scores,)
if scores is None:
return VulnerabilitySeverity.UNKNOWN
max_cvss_score: float
if isinstance(scores, tuple):
max_cvss_score = max(scores)
else:
max_cvss_score = float(scores)
if max_cvss_score >= 9.0:
return VulnerabilitySeverity.CRITICAL
elif max_cvss_score >= 7.0:
return VulnerabilitySeverity.HIGH
elif max_cvss_score >= 4.0:
return VulnerabilitySeverity.MEDIUM
elif max_cvss_score > 0.0:
return VulnerabilitySeverity.LOW
else:
return VulnerabilitySeverity.NONE
class VulnerabilityRating:
"""
Class that models the `ratingType` complex element CycloneDX core schema.
This class previously modelled the `scoreType` complexe type in the schema extension used prior to schema version
1.4 - see https://github.com/CycloneDX/specification/blob/master/schema/ext/vulnerability-1.0.xsd.
.. note::
See `ratingType` in https://cyclonedx.org/docs/1.4/#ratingType
.. warning::
As part of implementing support for CycloneDX schema version 1.4, the three score types defined in the schema
externsion used prior to 1.4 have been deprecated. The deprecated `score_base` should loosely be equivalent to
the new `score` in 1.4 schema. Both `score_impact` and `score_exploitability` are deprecated and removed as
they are redundant if you have the vector (the vector allows you to calculate the scores).
"""
def __init__(self, source: Optional[VulnerabilitySource] = None, score: Optional[Decimal] = None,
severity: Optional[VulnerabilitySeverity] = None,
method: Optional[VulnerabilityScoreSource] = None, vector: Optional[str] = None,
justification: Optional[str] = None,
# Deprecated parameters follow that are left to aid backwards compatability
score_base: Optional[float] = None) -> None:
if not source and not score and not severity and not method and not vector and not justification:
raise NoPropertiesProvidedException(
'At least one property must be provided when creating a VulnerabilityRating - none supplied.'
)
self.source = source
self.score = score
self.severity = severity
self.method = method
self.vector = vector
self.justification = justification
if score_base:
warnings.warn('`score_base` is deprecated - use `score`', DeprecationWarning)
if score:
warnings.warn('Both `score` and `score_base` supplied - the deprecated `score_base` will be discarded',
DeprecationWarning)
else:
self.score = Decimal(score_base)
if vector and method:
self.vector = method.get_localised_vector(vector=vector)
@property
def source(self) -> Optional[VulnerabilitySource]:
"""
The source that published the vulnerability.
"""
return self._source
@source.setter
def source(self, source: Optional[VulnerabilitySource]) -> None:
self._source = source
@property
def score(self) -> Optional[Decimal]:
"""
The numerical score of the rating.
"""
return self._score
@score.setter
def score(self, score: Optional[Decimal]) -> None:
self._score = score
@property
def severity(self) -> Optional[VulnerabilitySeverity]:
"""
The textual representation of the severity that corresponds to the numerical score of the rating.
"""
return self._severity
@severity.setter
def severity(self, severity: Optional[VulnerabilitySeverity]) -> None:
self._severity = severity
@property
def method(self) -> Optional[VulnerabilityScoreSource]:
"""
The risk scoring methodology/standard used.
"""
return self._method
@method.setter
def method(self, score_source: Optional[VulnerabilityScoreSource]) -> None:
self._method = score_source
@property
def vector(self) -> Optional[str]:
"""
The textual representation of the metric values used to score the vulnerability - also known as the vector.
"""
return self._vector
@vector.setter
def vector(self, vector: Optional[str]) -> None:
self._vector = vector
@property
def justification(self) -> Optional[str]:
"""
An optional reason for rating the vulnerability as it was.
"""
return self._justification
@justification.setter
def justification(self, justification: Optional[str]) -> None:
self._justification = justification
def __eq__(self, other: object) -> bool:
if isinstance(other, VulnerabilityRating):
return hash(other) == hash(self)
return False
def __hash__(self) -> int:
return hash((
hash(self.source), self.score, self.severity, self.method, self.vector, self.justification
))
def __repr__(self) -> str:
return f'<VulnerabilityRating score={self.score}, source={self.source}>'
class VulnerabilityCredits:
"""
Class that models the `credits` of `vulnerabilityType` complex type in the CycloneDX schema (version >= 1.4).
This class also provides data support for schema versions < 1.4 where Vulnerabilites were possible through a schema
extension (in XML only).
.. note::
See the CycloneDX schema: https://cyclonedx.org/docs/1.4/#type_vulnerabilityType
"""
def __init__(self, organizations: Optional[List[OrganizationalEntity]] = None,
individuals: Optional[List[OrganizationalContact]] = None) -> None:
if not organizations and not individuals:
raise NoPropertiesProvidedException(
'One of `organizations` or `individuals` must be populated - neither were'
)
self.organizations = organizations
self.individuals = individuals
@property
def organizations(self) -> Optional[List[OrganizationalEntity]]:
"""
The organizations credited with vulnerability discovery.
Returns:
List of `OrganizationalEntity` or `None`
"""
return self._organizations
@organizations.setter
def organizations(self, organizations: Optional[List[OrganizationalEntity]]) -> None:
self._organizations = organizations
@property
def individuals(self) -> Optional[List[OrganizationalContact]]:
"""
The individuals, not associated with organizations, that are credited with vulnerability discovery.
Returns:
List of `OrganizationalContact` or `None`
"""
return self._individuals
@individuals.setter
def individuals(self, individuals: Optional[List[OrganizationalContact]]) -> None:
self._individuals = individuals
def __eq__(self, other: object) -> bool:
if isinstance(other, VulnerabilityCredits):
return hash(other) == hash(self)
return False
def __hash__(self) -> int:
return hash((
tuple([hash(org) for org in set(sorted(self.organizations, key=hash))]) if self.organizations else None,
tuple([hash(person) for person in set(sorted(self.individuals, key=hash))]) if self.individuals else None
))
def __repr__(self) -> str:
return f'<VulnerabilityCredits id={id(self)}>'
class Vulnerability:
"""
Class that models the `vulnerabilityType` complex type in the CycloneDX schema (version >= 1.4).
This class also provides data support for schema versions < 1.4 where Vulnerabilites were possible through a schema
extension (in XML only).
.. note::
See the CycloneDX schema: https://cyclonedx.org/docs/1.4/#type_vulnerabilityType
"""
def __init__(self, bom_ref: Optional[str] = None, id: Optional[str] = None,
source: Optional[VulnerabilitySource] = None,
references: Optional[List[VulnerabilityReference]] = None,
ratings: Optional[List[VulnerabilityRating]] = None, cwes: Optional[List[int]] = None,
description: Optional[str] = None, detail: Optional[str] = None, recommendation: Optional[str] = None,
advisories: Optional[List[VulnerabilityAdvisory]] = None, created: Optional[datetime] = None,
published: Optional[datetime] = None, updated: Optional[datetime] = None,
credits: Optional[VulnerabilityCredits] = None,
tools: Optional[List[Tool]] = None, analysis: Optional[VulnerabilityAnalysis] = None,
affects_targets: Optional[List[BomTarget]] = None,
# Deprecated Parameters kept for backwards compatibility
source_name: Optional[str] = None, source_url: Optional[str] = None,
recommendations: Optional[List[str]] = None) -> None:
self.bom_ref = bom_ref or str(uuid4())
self.id = id
self.source = source
self.references = references or []
self.ratings = ratings or []
self.cwes = cwes or []
self.description = description
self.detail = detail
self.recommendation = recommendation
self.advisories = advisories or []
self.created = created
self.published = published
self.updated = updated
self.credits = credits
self.tools = tools or []
self.analysis = analysis
self.affects = affects_targets or []
if source_name or source_url:
warnings.warn('`source_name` and `source_url` are deprecated - use `source`', DeprecationWarning)
if not source:
self.source = VulnerabilitySource(name=source_name, url=XsUri(source_url) if source_url else None)
if recommendations:
warnings.warn('`recommendations` is deprecated - use `recommendation`', DeprecationWarning)
if not recommendation:
self.recommendation = recommendations.pop()
@property
def bom_ref(self) -> Optional[str]:
"""
Get the unique reference for this Vulnerability in this BOM.
If a value was not provided in the constructor, a UUIDv4 will have been assigned.
Returns:
`str` unique identifier for this Vulnerability
"""
return self._bom_ref
@bom_ref.setter
def bom_ref(self, bom_ref: Optional[str]) -> None:
self._bom_ref = bom_ref
@property
def id(self) -> Optional[str]:
"""
The identifier that uniquely identifies the vulnerability. For example: CVE-2021-39182.
"""
return self._id
@id.setter
def id(self, id: Optional[str]) -> None:
self._id = id
@property
def source(self) -> Optional[VulnerabilitySource]:
"""
The source that published the vulnerability.
"""
return self._source
@source.setter
def source(self, source: Optional[VulnerabilitySource]) -> None:
self._source = source
@property
def references(self) -> List[VulnerabilityReference]:
"""
Zero or more pointers to vulnerabilities that are the equivalent of the vulnerability specified. Often times,
the same vulnerability may exist in multiple sources of vulnerability intelligence, but have different
identifiers. References provides a way to correlate vulnerabilities across multiple sources of vulnerability
intelligence.
"""
return self._references
@references.setter
def references(self, references: List[VulnerabilityReference]) -> None:
self._references = references
def add_reference(self, reference: VulnerabilityReference) -> None:
"""
Add an additional reference for this Vulnerability.
Vulnerabilities may benefit from pointers to vulnerabilities that are the equivalent of the vulnerability
specified. Often times, the same vulnerability may exist in multiple sources of vulnerability intelligence, but
have different identifiers. These references provide a way to correlate vulnerabilities across multiple sources
of vulnerability intelligence.
Args:
reference:
`VulnerabilityReference` reference to add
"""
self.references = self.references + [reference]
@property
def ratings(self) -> List[VulnerabilityRating]:
"""
List of vulnerability ratings.
"""
return self._ratings
@ratings.setter
def ratings(self, ratings: List[VulnerabilityRating]) -> None:
self._ratings = ratings
def add_rating(self, rating: VulnerabilityRating) -> None:
"""
Add a vulnerability rating.
Args:
rating:
`VulnerabilityRating`
"""
self.ratings = self.ratings + [rating]
@property
def cwes(self) -> List[int]:
"""
A list of CWE (Common Weakness Enumeration) identifiers.
.. note::
See https://cwe.mitre.org/
"""
return self._cwes
@cwes.setter
def cwes(self, cwes: List[int]) -> None:
self._cwes = cwes
def add_cwe(self, cwe: int) -> None:
"""
Add a CWE identifier.
Args:
cwe:
`int` identifier for the CWE
"""
self.cwes = self.cwes + [cwe]
@property
def description(self) -> Optional[str]:
"""
A description of the vulnerability as provided by the source.
"""
return self._description
@description.setter
def description(self, description: Optional[str]) -> None:
self._description = description
@property
def detail(self) -> Optional[str]:
"""
If available, an in-depth description of the vulnerability as provided by the source organization. Details
often include examples, proof-of-concepts, and other information useful in understanding root cause.
"""
return self._detail
@detail.setter
def detail(self, detail: Optional[str]) -> None:
self._detail = detail
@property
def recommendation(self) -> Optional[str]:
"""
Recommendations of how the vulnerability can be remediated or mitigated.
"""
return self._recommendation
@recommendation.setter
def recommendation(self, recommendation: Optional[str]) -> None:
self._recommendation = recommendation
@property
def advisories(self) -> List[VulnerabilityAdvisory]:
"""
Advisories relating to the Vulnerability.
"""
return self._advisories
@advisories.setter
def advisories(self, advisories: List[VulnerabilityAdvisory]) -> None:
self._advisories = advisories
def add_advisory(self, advisory: VulnerabilityAdvisory) -> None:
"""
Add a advisory.
Args:
advisory:
`VulnerabilityAdvisory`
"""
self.advisories = self.advisories + [advisory]
@property
def created(self) -> Optional[datetime]:
return self._created
@created.setter
def created(self, created: Optional[datetime]) -> None:
self._created = created
@property
def published(self) -> Optional[datetime]:
return self._published
@published.setter
def published(self, published: Optional[datetime]) -> None:
self._published = published
@property
def updated(self) -> Optional[datetime]:
return self._updated
@updated.setter
def updated(self, updated: Optional[datetime]) -> None:
self._updated = updated
@property
def credits(self) -> Optional[VulnerabilityCredits]:
"""
Individuals or organizations credited with the discovery of the vulnerability.
"""
return self._credits
@credits.setter
def credits(self, credits: Optional[VulnerabilityCredits]) -> None:
self._credits = credits
@property
def tools(self) -> List[Tool]:
"""
The tool(s) used to identify, confirm, or score the vulnerability.
"""
return self._tools
@tools.setter
def tools(self, tools: List[Tool]) -> None:
self._tools = tools
def add_tool(self, tool: Tool) -> None:
"""
Add a tool used to identify, confirm, or score the vulnerability.
Args:
tool:
`Tool`
"""
self.tools = self.tools + [tool]
@property
def analysis(self) -> Optional[VulnerabilityAnalysis]: