contentctl 4.0.4__py3-none-any.whl → 4.1.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- contentctl/actions/inspect.py +1 -1
- contentctl/actions/new_content.py +18 -7
- contentctl/actions/validate.py +1 -0
- contentctl/api.py +137 -0
- contentctl/contentctl.py +28 -24
- contentctl/enrichments/cve_enrichment.py +43 -78
- contentctl/input/director.py +72 -72
- contentctl/input/new_content_questions.py +0 -5
- contentctl/objects/abstract_security_content_objects/detection_abstract.py +77 -13
- contentctl/objects/abstract_security_content_objects/security_content_object_abstract.py +17 -0
- contentctl/objects/baseline.py +0 -1
- contentctl/objects/config.py +4 -8
- contentctl/objects/detection_tags.py +1 -1
- contentctl/objects/macro.py +8 -7
- contentctl/objects/story_tags.py +2 -0
- contentctl/output/yml_writer.py +39 -1
- contentctl/templates/detections/application/.gitkeep +0 -0
- contentctl/templates/detections/cloud/.gitkeep +0 -0
- contentctl/templates/detections/network/.gitkeep +0 -0
- contentctl/templates/detections/web/.gitkeep +0 -0
- {contentctl-4.0.4.dist-info → contentctl-4.1.0.dist-info}/METADATA +7 -8
- {contentctl-4.0.4.dist-info → contentctl-4.1.0.dist-info}/RECORD +27 -25
- contentctl/actions/apav_deploy.py +0 -98
- contentctl/actions/api_deploy.py +0 -151
- contentctl/templates/app_template/default/distsearch.conf +0 -5
- /contentctl/actions/{acs_deploy.py → deploy_acs.py} +0 -0
- /contentctl/templates/detections/{anomalous_usage_of_7zip.yml → endpoint/anomalous_usage_of_7zip.yml} +0 -0
- {contentctl-4.0.4.dist-info → contentctl-4.1.0.dist-info}/LICENSE.md +0 -0
- {contentctl-4.0.4.dist-info → contentctl-4.1.0.dist-info}/WHEEL +0 -0
- {contentctl-4.0.4.dist-info → contentctl-4.1.0.dist-info}/entry_points.txt +0 -0
contentctl/actions/inspect.py
CHANGED
|
@@ -61,7 +61,7 @@ class Inspect:
|
|
|
61
61
|
if not package_path.is_file():
|
|
62
62
|
raise Exception(f"Cannot run Appinspect API on App '{config.app.title}' - "
|
|
63
63
|
f"no package exists as expected path '{package_path}'.\nAre you "
|
|
64
|
-
"trying to 'contentctl
|
|
64
|
+
"trying to 'contentctl deploy_acs' the package BEFORE running 'contentctl build'?")
|
|
65
65
|
|
|
66
66
|
files = {
|
|
67
67
|
"app_package": open(package_path,"rb"),
|
|
@@ -19,16 +19,22 @@ class NewContent:
|
|
|
19
19
|
answers = questionary.prompt(questions)
|
|
20
20
|
answers.update(answers)
|
|
21
21
|
answers['name'] = answers['detection_name']
|
|
22
|
+
del answers['detection_name']
|
|
22
23
|
answers['id'] = str(uuid.uuid4())
|
|
23
24
|
answers['version'] = 1
|
|
24
25
|
answers['date'] = datetime.today().strftime('%Y-%m-%d')
|
|
25
26
|
answers['author'] = answers['detection_author']
|
|
26
|
-
|
|
27
|
+
del answers['detection_author']
|
|
28
|
+
answers['data_sources'] = answers['data_source']
|
|
29
|
+
del answers['data_source']
|
|
27
30
|
answers['type'] = answers['detection_type']
|
|
31
|
+
del answers['detection_type']
|
|
28
32
|
answers['status'] = "production" #start everything as production since that's what we INTEND the content to become
|
|
29
33
|
answers['description'] = 'UPDATE_DESCRIPTION'
|
|
30
34
|
file_name = answers['name'].replace(' ', '_').replace('-','_').replace('.','_').replace('/','_').lower()
|
|
35
|
+
answers['kind'] = answers['detection_kind']
|
|
31
36
|
answers['search'] = answers['detection_search'] + ' | `' + file_name + '_filter`'
|
|
37
|
+
del answers['detection_search']
|
|
32
38
|
answers['how_to_implement'] = 'UPDATE_HOW_TO_IMPLEMENT'
|
|
33
39
|
answers['known_false_positives'] = 'UPDATE_KNOWN_FALSE_POSITIVES'
|
|
34
40
|
answers['references'] = ['REFERENCE']
|
|
@@ -44,6 +50,7 @@ class NewContent:
|
|
|
44
50
|
answers['tags']['required_fields'] = ['UPDATE']
|
|
45
51
|
answers['tags']['risk_score'] = 'UPDATE (impact * confidence)/100'
|
|
46
52
|
answers['tags']['security_domain'] = answers['security_domain']
|
|
53
|
+
del answers["security_domain"]
|
|
47
54
|
answers['tags']['cve'] = ['UPDATE WITH CVE(S) IF APPLICABLE']
|
|
48
55
|
|
|
49
56
|
#generate the tests section
|
|
@@ -52,31 +59,35 @@ class NewContent:
|
|
|
52
59
|
'name': "True Positive Test",
|
|
53
60
|
'attack_data': [
|
|
54
61
|
{
|
|
55
|
-
'data': "
|
|
62
|
+
'data': "https://github.com/splunk/contentctl/wiki",
|
|
56
63
|
"sourcetype": "UPDATE SOURCETYPE",
|
|
57
64
|
"source": "UPDATE SOURCE"
|
|
58
65
|
}
|
|
59
66
|
]
|
|
60
67
|
}
|
|
61
68
|
]
|
|
69
|
+
del answers["mitre_attack_ids"]
|
|
62
70
|
return answers
|
|
63
71
|
|
|
64
72
|
def buildStory(self)->dict[str,Any]:
|
|
65
73
|
questions = NewContentQuestions.get_questions_story()
|
|
66
74
|
answers = questionary.prompt(questions)
|
|
67
75
|
answers['name'] = answers['story_name']
|
|
76
|
+
del answers['story_name']
|
|
68
77
|
answers['id'] = str(uuid.uuid4())
|
|
69
78
|
answers['version'] = 1
|
|
70
79
|
answers['date'] = datetime.today().strftime('%Y-%m-%d')
|
|
71
80
|
answers['author'] = answers['story_author']
|
|
81
|
+
del answers['story_author']
|
|
72
82
|
answers['description'] = 'UPDATE_DESCRIPTION'
|
|
73
83
|
answers['narrative'] = 'UPDATE_NARRATIVE'
|
|
74
84
|
answers['references'] = []
|
|
75
85
|
answers['tags'] = dict()
|
|
76
|
-
answers['tags']['analytic_story'] = answers['name']
|
|
77
86
|
answers['tags']['category'] = answers['category']
|
|
87
|
+
del answers['category']
|
|
78
88
|
answers['tags']['product'] = ['Splunk Enterprise','Splunk Enterprise Security','Splunk Cloud']
|
|
79
89
|
answers['tags']['usecase'] = answers['usecase']
|
|
90
|
+
del answers['usecase']
|
|
80
91
|
answers['tags']['cve'] = ['UPDATE WITH CVE(S) IF APPLICABLE']
|
|
81
92
|
return answers
|
|
82
93
|
|
|
@@ -84,13 +95,13 @@ class NewContent:
|
|
|
84
95
|
def execute(self, input_dto: new) -> None:
|
|
85
96
|
if input_dto.type == NewContentType.detection:
|
|
86
97
|
content_dict = self.buildDetection()
|
|
87
|
-
subdirectory = pathlib.Path('detections') / content_dict.
|
|
98
|
+
subdirectory = pathlib.Path('detections') / content_dict.pop('detection_kind')
|
|
88
99
|
elif input_dto.type == NewContentType.story:
|
|
89
100
|
content_dict = self.buildStory()
|
|
90
101
|
subdirectory = pathlib.Path('stories')
|
|
91
102
|
else:
|
|
92
103
|
raise Exception(f"Unsupported new content type: [{input_dto.type}]")
|
|
93
|
-
|
|
104
|
+
|
|
94
105
|
full_output_path = input_dto.path / subdirectory / SecurityContentObject_Abstract.contentNameToFileName(content_dict.get('name'))
|
|
95
106
|
YmlWriter.writeYmlFile(str(full_output_path), content_dict)
|
|
96
107
|
|
|
@@ -103,12 +114,12 @@ class NewContent:
|
|
|
103
114
|
#make sure the output folder exists for this detection
|
|
104
115
|
output_folder.mkdir(exist_ok=True)
|
|
105
116
|
|
|
106
|
-
YmlWriter.
|
|
117
|
+
YmlWriter.writeDetection(file_path, object)
|
|
107
118
|
print("Successfully created detection " + file_path)
|
|
108
119
|
|
|
109
120
|
elif type == NewContentType.story:
|
|
110
121
|
file_path = os.path.join(self.output_path, 'stories', self.convertNameToFileName(object['name'], object['tags']['product']))
|
|
111
|
-
YmlWriter.
|
|
122
|
+
YmlWriter.writeStory(file_path, object)
|
|
112
123
|
print("Successfully created story " + file_path)
|
|
113
124
|
|
|
114
125
|
else:
|
contentctl/actions/validate.py
CHANGED
|
@@ -23,6 +23,7 @@ class Validate:
|
|
|
23
23
|
director_output_dto = DirectorOutputDto(AtomicTest.getAtomicTestsFromArtRepo(repo_path=input_dto.getAtomicRedTeamRepoPath(),
|
|
24
24
|
enabled=input_dto.enrichments),
|
|
25
25
|
AttackEnrichment.getAttackEnrichment(input_dto),
|
|
26
|
+
CveEnrichment.getCveEnrichment(input_dto),
|
|
26
27
|
[],[],[],[],[],[],[],[],[])
|
|
27
28
|
|
|
28
29
|
|
contentctl/api.py
ADDED
|
@@ -0,0 +1,137 @@
|
|
|
1
|
+
from pathlib import Path
|
|
2
|
+
from typing import Any, Union, Type
|
|
3
|
+
from contentctl.input.yml_reader import YmlReader
|
|
4
|
+
from contentctl.objects.config import test_common, test, test_servers
|
|
5
|
+
from contentctl.objects.security_content_object import SecurityContentObject
|
|
6
|
+
from contentctl.input.director import DirectorOutputDto
|
|
7
|
+
|
|
8
|
+
def config_from_file(path:Path=Path("contentctl.yml"), config: dict[str,Any]={},
|
|
9
|
+
configType:Type[Union[test,test_servers]]=test)->test_common:
|
|
10
|
+
|
|
11
|
+
"""
|
|
12
|
+
Fetch a configuration object that can be used for a number of different contentctl
|
|
13
|
+
operations including validate, build, inspect, test, and test_servers. A file will
|
|
14
|
+
be used as the basis for constructing the configuration.
|
|
15
|
+
|
|
16
|
+
Args:
|
|
17
|
+
path (Path, optional): Relative or absolute path to a contentctl config file.
|
|
18
|
+
Defaults to Path("contentctl.yml"), which is the default name and location (in the current directory)
|
|
19
|
+
of the configuration files which are automatically generated for contentctl.
|
|
20
|
+
config (dict[], optional): Dictionary of values to override values read from the YML
|
|
21
|
+
path passed as the first argument. Defaults to {}, an empty dict meaning that nothing
|
|
22
|
+
will be overwritten
|
|
23
|
+
configType (Type[Union[test,test_servers]], optional): The Config Class to instantiate.
|
|
24
|
+
This may be a test or test_servers object. Note that this is NOT an instance of the class. Defaults to test.
|
|
25
|
+
Returns:
|
|
26
|
+
test_common: Returns a complete contentctl test_common configuration. Note that this configuration
|
|
27
|
+
will have all applicable field for validate and build as well, but can also be used for easily
|
|
28
|
+
construction a test or test_servers object.
|
|
29
|
+
"""
|
|
30
|
+
|
|
31
|
+
try:
|
|
32
|
+
yml_dict = YmlReader.load_file(path, add_fields=False)
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
except Exception as e:
|
|
36
|
+
raise Exception(f"Failed to load contentctl configuration from file '{path}': {str(e)}")
|
|
37
|
+
|
|
38
|
+
# Apply settings that have been overridden from the ones in the file
|
|
39
|
+
try:
|
|
40
|
+
yml_dict.update(config)
|
|
41
|
+
except Exception as e:
|
|
42
|
+
raise Exception(f"Failed updating dictionary of values read from file '{path}'"
|
|
43
|
+
f" with the dictionary of arguments passed: {str(e)}")
|
|
44
|
+
|
|
45
|
+
# The function below will throw its own descriptive exception if it fails
|
|
46
|
+
configObject = config_from_dict(yml_dict, configType=configType)
|
|
47
|
+
|
|
48
|
+
return configObject
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
def config_from_dict(config: dict[str,Any]={},
|
|
54
|
+
configType:Type[Union[test,test_servers]]=test)->test_common:
|
|
55
|
+
"""
|
|
56
|
+
Fetch a configuration object that can be used for a number of different contentctl
|
|
57
|
+
operations including validate, build, inspect, test, and test_servers. A dict will
|
|
58
|
+
be used as the basis for constructing the configuration.
|
|
59
|
+
|
|
60
|
+
Args:
|
|
61
|
+
config (dict[str,Any],Optional): If a dictionary is not explicitly passed, then
|
|
62
|
+
an empty dict will be used to create a configuration, if possible, from default
|
|
63
|
+
values. Note that based on default values in the contentctl/objects/config.py
|
|
64
|
+
file, this may raise an exception. If so, please set appropriate default values
|
|
65
|
+
in the file above or supply those values via this argument.
|
|
66
|
+
configType (Type[Union[test,test_servers]], optional): The Config Class to instantiate.
|
|
67
|
+
This may be a test or test_servers object. Note that this is NOT an instance of the class. Defaults to test.
|
|
68
|
+
Returns:
|
|
69
|
+
test_common: Returns a complete contentctl test_common configuration. Note that this configuration
|
|
70
|
+
will have all applicable field for validate and build as well, but can also be used for easily
|
|
71
|
+
construction a test or test_servers object.
|
|
72
|
+
"""
|
|
73
|
+
try:
|
|
74
|
+
test_object = configType.model_validate(config)
|
|
75
|
+
except Exception as e:
|
|
76
|
+
raise Exception(f"Failed to load contentctl configuration from dict:\n{str(e)}")
|
|
77
|
+
|
|
78
|
+
return test_object
|
|
79
|
+
|
|
80
|
+
|
|
81
|
+
def update_config(config:Union[test,test_servers], **key_value_updates:dict[str,Any])->test_common:
|
|
82
|
+
|
|
83
|
+
"""Update any relevant keys in a config file with the specified values.
|
|
84
|
+
Full validation will be performed after this update and descriptive errors
|
|
85
|
+
will be produced
|
|
86
|
+
|
|
87
|
+
Args:
|
|
88
|
+
config (test_common): A previously-constructed test_common object. This can be
|
|
89
|
+
build using the configFromDict or configFromFile functions.
|
|
90
|
+
key_value_updates (kwargs, optional): Additional keyword/argument pairs to update
|
|
91
|
+
arbitrary fields in the configuration.
|
|
92
|
+
|
|
93
|
+
Returns:
|
|
94
|
+
test_common: A validated object which has had the relevant fields updated.
|
|
95
|
+
Note that descriptive Exceptions will be generated if updated values are either
|
|
96
|
+
invalid (have the wrong type, or disallowed values) or you attempt to update
|
|
97
|
+
fields that do not exist
|
|
98
|
+
"""
|
|
99
|
+
# Create a copy so we don't change the underlying model
|
|
100
|
+
config_copy = config.model_copy(deep=True)
|
|
101
|
+
|
|
102
|
+
# Force validation of assignment since doing so via arbitrary dict can be error prone
|
|
103
|
+
# Also, ensure that we do not try to add fields that are not part of the model
|
|
104
|
+
config_copy.model_config.update({'validate_assignment': True, 'extra': 'forbid'})
|
|
105
|
+
|
|
106
|
+
|
|
107
|
+
|
|
108
|
+
# Collect any errors that may occur
|
|
109
|
+
errors:list[Exception] = []
|
|
110
|
+
|
|
111
|
+
# We need to do this one by one because the extra:forbid argument does not appear to
|
|
112
|
+
# be respected at this time.
|
|
113
|
+
for key, value in key_value_updates.items():
|
|
114
|
+
try:
|
|
115
|
+
setattr(config_copy,key,value)
|
|
116
|
+
except Exception as e:
|
|
117
|
+
errors.append(e)
|
|
118
|
+
if len(errors) > 0:
|
|
119
|
+
errors_string = '\n'.join([str(e) for e in errors])
|
|
120
|
+
raise Exception(f"Error(s) updaitng configuration:\n{errors_string}")
|
|
121
|
+
|
|
122
|
+
return config_copy
|
|
123
|
+
|
|
124
|
+
|
|
125
|
+
|
|
126
|
+
def content_to_dict(director:DirectorOutputDto)->dict[str,list[dict[str,Any]]]:
|
|
127
|
+
output_dict:dict[str,list[dict[str,Any]]] = {}
|
|
128
|
+
for contentType in ['detections','stories','baselines','investigations',
|
|
129
|
+
'playbooks','macros','lookups','deployments','ssa_detections']:
|
|
130
|
+
|
|
131
|
+
output_dict[contentType] = []
|
|
132
|
+
t:list[SecurityContentObject] = getattr(director,contentType)
|
|
133
|
+
|
|
134
|
+
for item in t:
|
|
135
|
+
output_dict[contentType].append(item.model_dump())
|
|
136
|
+
return output_dict
|
|
137
|
+
|
contentctl/contentctl.py
CHANGED
|
@@ -1,6 +1,11 @@
|
|
|
1
|
-
|
|
1
|
+
import traceback
|
|
2
|
+
import sys
|
|
3
|
+
import warnings
|
|
4
|
+
import pathlib
|
|
2
5
|
import tyro
|
|
3
|
-
|
|
6
|
+
|
|
7
|
+
from contentctl.actions.initialize import Initialize
|
|
8
|
+
from contentctl.objects.config import init, validate, build, new, deploy_acs, test, test_servers, inspect, report, test_common, release_notes
|
|
4
9
|
from contentctl.actions.validate import Validate
|
|
5
10
|
from contentctl.actions.new_content import NewContent
|
|
6
11
|
from contentctl.actions.detection_testing.GitService import GitService
|
|
@@ -9,14 +14,10 @@ from contentctl.actions.build import (
|
|
|
9
14
|
DirectorOutputDto,
|
|
10
15
|
Build,
|
|
11
16
|
)
|
|
12
|
-
|
|
13
17
|
from contentctl.actions.test import Test
|
|
14
18
|
from contentctl.actions.test import TestInputDto
|
|
15
19
|
from contentctl.actions.reporting import ReportingInputDto, Reporting
|
|
16
20
|
from contentctl.actions.inspect import Inspect
|
|
17
|
-
import sys
|
|
18
|
-
import warnings
|
|
19
|
-
import pathlib
|
|
20
21
|
from contentctl.input.yml_reader import YmlReader
|
|
21
22
|
from contentctl.actions.release_notes import ReleaseNotes
|
|
22
23
|
|
|
@@ -95,13 +96,14 @@ def new_func(config:new):
|
|
|
95
96
|
|
|
96
97
|
def deploy_acs_func(config:deploy_acs):
|
|
97
98
|
#This is a bit challenging to get to work with the default values.
|
|
98
|
-
raise Exception("deploy acs not yet implemented")
|
|
99
|
-
|
|
100
|
-
def deploy_rest_func(config:deploy_rest):
|
|
101
|
-
raise Exception("deploy rest not yet implemented")
|
|
102
|
-
|
|
99
|
+
raise Exception("deploy acs not yet implemented")
|
|
103
100
|
|
|
104
101
|
def test_common_func(config:test_common):
|
|
102
|
+
if type(config) == test:
|
|
103
|
+
#construct the container Infrastructure objects
|
|
104
|
+
config.getContainerInfrastructureObjects()
|
|
105
|
+
#otherwise, they have already been passed as servers
|
|
106
|
+
|
|
105
107
|
director_output_dto = build_func(config)
|
|
106
108
|
gitServer = GitService(director=director_output_dto,config=config)
|
|
107
109
|
detections_to_test = gitServer.getContent()
|
|
@@ -175,15 +177,14 @@ def main():
|
|
|
175
177
|
"test":test.model_validate(config_obj),
|
|
176
178
|
"test_servers":test_servers.model_construct(**t.__dict__),
|
|
177
179
|
"release_notes": release_notes.model_construct(**config_obj),
|
|
178
|
-
"deploy_acs": deploy_acs.model_construct(**t.__dict__)
|
|
179
|
-
#"deploy_rest":deploy_rest()
|
|
180
|
+
"deploy_acs": deploy_acs.model_construct(**t.__dict__)
|
|
180
181
|
}
|
|
181
182
|
)
|
|
182
183
|
|
|
183
184
|
|
|
184
185
|
|
|
185
186
|
|
|
186
|
-
|
|
187
|
+
config = None
|
|
187
188
|
try:
|
|
188
189
|
# Since some model(s) were constructed and not model_validated, we have to catch
|
|
189
190
|
# warnings again when creating the cli
|
|
@@ -209,20 +210,23 @@ def main():
|
|
|
209
210
|
elif type(config) == deploy_acs:
|
|
210
211
|
updated_config = deploy_acs.model_validate(config)
|
|
211
212
|
deploy_acs_func(updated_config)
|
|
212
|
-
elif type(config) == deploy_rest:
|
|
213
|
-
deploy_rest_func(config)
|
|
214
213
|
elif type(config) == test or type(config) == test_servers:
|
|
215
|
-
if type(config) == test:
|
|
216
|
-
#construct the container Infrastructure objects
|
|
217
|
-
config.getContainerInfrastructureObjects()
|
|
218
|
-
#otherwise, they have already been passed as servers
|
|
219
214
|
test_common_func(config)
|
|
220
215
|
else:
|
|
221
216
|
raise Exception(f"Unknown command line type '{type(config).__name__}'")
|
|
222
217
|
except Exception as e:
|
|
223
|
-
|
|
224
|
-
|
|
225
|
-
|
|
226
|
-
|
|
218
|
+
if config is None:
|
|
219
|
+
print("There was a serious issue where the config file could not be created.\n"
|
|
220
|
+
"The entire stack trace is provided below (please include it if filing a bug report).\n")
|
|
221
|
+
traceback.print_exc()
|
|
222
|
+
elif config.verbose:
|
|
223
|
+
print("Verbose error logging is ENABLED.\n"
|
|
224
|
+
"The entire stack trace has been provided below (please include it if filing a bug report):\n")
|
|
225
|
+
traceback.print_exc()
|
|
226
|
+
else:
|
|
227
|
+
print("Verbose error logging is DISABLED.\n"
|
|
228
|
+
"Please use the --verbose command line argument if you need more context for your error or file a bug report.")
|
|
229
|
+
print(e)
|
|
230
|
+
|
|
227
231
|
sys.exit(1)
|
|
228
232
|
|
|
@@ -4,97 +4,62 @@ import functools
|
|
|
4
4
|
import os
|
|
5
5
|
import shelve
|
|
6
6
|
import time
|
|
7
|
-
from typing import Annotated
|
|
8
|
-
from pydantic import BaseModel,Field,
|
|
9
|
-
|
|
7
|
+
from typing import Annotated, Any, Union, TYPE_CHECKING
|
|
8
|
+
from pydantic import BaseModel,Field, computed_field
|
|
10
9
|
from decimal import Decimal
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
CVE_CACHE_FILENAME = "lookups/CVE_CACHE.db"
|
|
14
|
-
|
|
15
|
-
NON_PERSISTENT_CACHE = {}
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
''''''
|
|
19
|
-
@functools.cache
|
|
20
|
-
def cvesearch_helper(url:str, cve_id:str, force_cached_or_offline:bool=False, max_api_attempts:int=3, retry_sleep_seconds:int=5):
|
|
21
|
-
if max_api_attempts < 1:
|
|
22
|
-
raise(Exception(f"The minimum number of CVESearch API attempts is 1. You have passed {max_api_attempts}"))
|
|
23
|
-
|
|
24
|
-
if force_cached_or_offline:
|
|
25
|
-
if not os.path.exists(CVE_CACHE_FILENAME):
|
|
26
|
-
print(f"Cache at {CVE_CACHE_FILENAME} not found - Creating it.")
|
|
27
|
-
cache = shelve.open(CVE_CACHE_FILENAME, flag='c', writeback=True)
|
|
28
|
-
else:
|
|
29
|
-
cache = NON_PERSISTENT_CACHE
|
|
30
|
-
if cve_id in cache:
|
|
31
|
-
result = cache[cve_id]
|
|
32
|
-
#print(f"hit cve_enrichment: {time.time() - start:.2f}")
|
|
33
|
-
else:
|
|
34
|
-
api_attempts_remaining = max_api_attempts
|
|
35
|
-
result = None
|
|
36
|
-
while api_attempts_remaining > 0:
|
|
37
|
-
api_attempts_remaining -= 1
|
|
38
|
-
try:
|
|
39
|
-
cve = cvesearch_id_helper(url)
|
|
40
|
-
result = cve.id(cve_id)
|
|
41
|
-
break
|
|
42
|
-
except Exception as e:
|
|
43
|
-
if api_attempts_remaining > 0:
|
|
44
|
-
print(f"The option 'force_cached_or_offline' was used, but {cve_id} not found in {CVE_CACHE_FILENAME} and unable to connect to {CVESSEARCH_API_URL}: {str(e)}")
|
|
45
|
-
print(f"Retrying the CVESearch API up to {api_attempts_remaining} more times after a sleep of {retry_sleep_seconds} seconds...")
|
|
46
|
-
time.sleep(retry_sleep_seconds)
|
|
47
|
-
else:
|
|
48
|
-
raise(Exception(f"The option 'force_cached_or_offline' was used, but {cve_id} not found in {CVE_CACHE_FILENAME} and unable to connect to {CVESSEARCH_API_URL} after {max_api_attempts} attempts: {str(e)}"))
|
|
49
|
-
|
|
50
|
-
if result is None:
|
|
51
|
-
raise(Exception(f'CveEnrichment for [ {cve_id} ] failed - CVE does not exist'))
|
|
52
|
-
cache[cve_id] = result
|
|
53
|
-
|
|
54
|
-
if isinstance(cache, shelve.Shelf):
|
|
55
|
-
#close the cache if it was a shelf
|
|
56
|
-
cache.close()
|
|
10
|
+
from requests.exceptions import ReadTimeout
|
|
57
11
|
|
|
58
|
-
|
|
12
|
+
if TYPE_CHECKING:
|
|
13
|
+
from contentctl.objects.config import validate
|
|
59
14
|
|
|
60
|
-
@functools.cache
|
|
61
|
-
def cvesearch_id_helper(url:str):
|
|
62
|
-
#The initial CVESearch call takes some time.
|
|
63
|
-
#We cache it to avoid making this call each time we need to do a lookup
|
|
64
|
-
cve = CVESearch(CVESSEARCH_API_URL)
|
|
65
|
-
return cve
|
|
66
15
|
|
|
67
16
|
|
|
17
|
+
CVESSEARCH_API_URL = 'https://cve.circl.lu'
|
|
68
18
|
|
|
69
19
|
|
|
70
20
|
class CveEnrichmentObj(BaseModel):
|
|
71
21
|
id:Annotated[str, "^CVE-[1|2][0-9]{3}-[0-9]+$"]
|
|
72
22
|
cvss:Annotated[Decimal, Field(ge=.1, le=10, decimal_places=1)]
|
|
73
23
|
summary:str
|
|
24
|
+
|
|
25
|
+
@computed_field
|
|
26
|
+
@property
|
|
27
|
+
def url(self)->str:
|
|
28
|
+
BASE_NVD_URL = "https://nvd.nist.gov/vuln/detail/"
|
|
29
|
+
return f"{BASE_NVD_URL}{self.id}"
|
|
74
30
|
|
|
75
31
|
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
return CveEnrichmentObj(id=id, cvss=Decimal(5.0), summary=message)
|
|
32
|
+
class CveEnrichment(BaseModel):
|
|
33
|
+
use_enrichment: bool = True
|
|
34
|
+
cve_api_obj: Union[CVESearch,None] = None
|
|
35
|
+
|
|
81
36
|
|
|
82
|
-
class
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
except Exception as e:
|
|
93
|
-
message = f"issue enriching {cve_id}, with error: {str(e)}"
|
|
94
|
-
if treat_failures_as_warnings:
|
|
95
|
-
return CveEnrichmentObj.buildEnrichmentOnFailure(id = cve_id, errorMessage=f"WARNING, {message}")
|
|
96
|
-
else:
|
|
97
|
-
raise ValueError(f"ERROR, {message}")
|
|
37
|
+
class Config:
|
|
38
|
+
# Arbitrary_types are allowed to let us use the CVESearch Object
|
|
39
|
+
arbitrary_types_allowed = True
|
|
40
|
+
frozen = True
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
@staticmethod
|
|
44
|
+
def getCveEnrichment(config:validate, timeout_seconds:int=10, force_disable_enrichment:bool=True)->CveEnrichment:
|
|
45
|
+
if force_disable_enrichment:
|
|
46
|
+
return CveEnrichment(use_enrichment=False, cve_api_obj=None)
|
|
98
47
|
|
|
99
|
-
|
|
48
|
+
if config.enrichments:
|
|
49
|
+
try:
|
|
50
|
+
cve_api_obj = CVESearch(CVESSEARCH_API_URL, timeout=timeout_seconds)
|
|
51
|
+
return CveEnrichment(use_enrichment=True, cve_api_obj=cve_api_obj)
|
|
52
|
+
except Exception as e:
|
|
53
|
+
raise Exception(f"Error setting CVE_SEARCH API to: {CVESSEARCH_API_URL}: {str(e)}")
|
|
100
54
|
|
|
55
|
+
return CveEnrichment(use_enrichment=False, cve_api_obj=None)
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
def enrich_cve(self, cve_id:str, raise_exception_on_failure:bool=True)->CveEnrichmentObj:
|
|
59
|
+
|
|
60
|
+
if not self.use_enrichment:
|
|
61
|
+
return CveEnrichmentObj(id=cve_id,cvss=Decimal(5.0),summary="SUMMARY NOT AVAILABLE! ONLY THE LINK WILL BE USED AT THIS TIME")
|
|
62
|
+
else:
|
|
63
|
+
print("WARNING - Dynamic enrichment not supported at this time.")
|
|
64
|
+
return CveEnrichmentObj(id=cve_id,cvss=Decimal(5.0),summary="SUMMARY NOT AVAILABLE! ONLY THE LINK WILL BE USED AT THIS TIME")
|
|
65
|
+
# Depending on needs, we may add dynamic enrichment functionality back to the tool
|