-
Notifications
You must be signed in to change notification settings - Fork 0
/
webhook_handler.py
223 lines (182 loc) · 8.54 KB
/
webhook_handler.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
# Copyright 2023 HCL America
#
# 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.
from datetime import datetime
import requests
import time
import logging
import json
import importlib
logger = logging.getLogger('asco_webhook_proxy')
class WebhookHandler:
asoc = None
config = None
def __init__(self, asoc, config):
self.config = config
self.asoc = asoc
def collectSubjectData(subjectId):
if(not self.asoc.checkAuth()):
if(not self.asoc.login()):
logger.error("Cannot login, check network or credentials")
return None
scanExec = asoc.scanSummary(execId, True)
if(not scanExec):
logger.error(f"Error getting scan execution summary: {execId}")
return None
scanId = scanExec["ScanId"]
scan = asoc.scanSummary(scanId)
if(not scan):
logger.error(f"Error getting scan summary: {scanId}")
return None
data = {
"scan": scan,
"scan_execution": scanExec
}
return data
def saveReport(self, id, reportConfig, fullPath, type = "ScanExecutionCompleted"):
if(not self.asoc.checkAuth()):
if(not self.asoc.login()):
logger.error("Cannot login, check network or credentials")
return False
reportId = self.asoc.startReport(id, reportConfig, type)
if(not reportId):
logger.error("Error starting report for scan execution {id}")
return False
waiting = self.asoc.waitForReport(reportId)
if(not waiting):
logger.error("Problem occurred waiting for report")
return False
if(not self.asoc.downloadReport(reportId, fullPath)):
logger.error("Problem occurred downloading report")
return False
return True
def applyTemplate(self, template, data):
now = datetime.now()
time_stamp = now.strftime("%Y-%m-%dT%H:%M:%SZ")
app = data["scan"]["AppName"]
scanFinishedRaw = data["scan_execution"]["ScanEndTime"]
scanFinishedRaw = scanFinishedRaw[:26]
scanFinishedDt = datetime.strptime(scanFinishedRaw,"%Y-%m-%dT%H:%M:%S.%f")
scanFinished = scanFinishedDt.strftime("%Y-%m-%d %H:%M:%S")
duration_secs = data["scan_execution"]["ExecutionDurationSec"]
duration_str = time.strftime('%Hh %Mm %Ss', time.gmtime(duration_secs))
createdBy = data["scan_execution"]["CreatedBy"]["FirstName"]+" "
createdBy += data["scan_execution"]["CreatedBy"]["LastName"]+" <"
createdBy += data["scan_execution"]["CreatedBy"]["Email"]+">"
scanName = data["scan"]["Name"]
report_url = None
if(data["report_url"]):
report_url = data["report_url"]
NIssuesFound = data["scan_execution"]["NIssuesFound"]
NHighIssues = data["scan_execution"]["NHighIssues"]
NMediumIssues = data["scan_execution"]["NMediumIssues"]
NLowIssues = data["scan_execution"]["NLowIssues"]
templateStr = ""
try:
with open(template, "r") as f:
templateStr = f.read()
except Exception as e:
logger.error(f"Error reading template file {template}")
logger.error(e)
return None
templateStr = templateStr.replace("{app}", app)
templateStr = templateStr.replace("{scan_finished_time}", scanFinished)
templateStr = templateStr.replace("{time_stamp}", time_stamp)
templateStr = templateStr.replace("{duration_str}", duration_str)
templateStr = templateStr.replace("{createdBy}", createdBy)
templateStr = templateStr.replace("{scanName}", scanName)
if(report_url is None):
templateStr = templateStr.replace("{report_url}", "")
else:
templateStr = templateStr.replace("{report_url}", report_url)
templateStr = templateStr.replace("{NIssuesFound}", str(NIssuesFound))
templateStr = templateStr.replace("{NHighIssues}", str(NHighIssues))
templateStr = templateStr.replace("{NMediumIssues}", str(NMediumIssues))
templateStr = templateStr.replace("{NLowIssues}", str(NLowIssues))
templateJson = None
try:
templateJson = json.loads(templateStr)
except Exception as e:
logger.error("Error parsing templateStr to Python Dict")
logger.error(e)
print(templateStr)
return None
return templateJson
"""
Function to make the post request to the webhook
"""
def postWebhook(self, webhookUrl, data):
resp = requests.post(webhookUrl, json=data)
return resp.status_code
def handleCustom(self, webhookObj, data):
moduleName = webhookObj["handler"]
try:
logger.info(f"Loading custom handler for [{moduleName}]")
handler = importlib.import_module(f"handlers.{moduleName}")
logger.info(f"Custom handler for [{moduleName}] Loaded")
logger.info(f"Calling handle function in {moduleName}")
handler.handle(webhookObj, data)
except ModuleNotFoundError as e:
logger.error("Error importing custom handler code {moduleName}")
logger.error(e)
def handle(self, webhookObj, subjectId, type="json_post"):
webhookName = webhookObj["name"]
logger.info(f"Handling Webhook Call {webhookName} {subjectId}")
scanExec = None
scanData = None
appData = None
reportUrl = None
logger.info("Collecting Data from ASoC")
trigger = webhookObj["trigger"]
reportTargetId = subjectId
#Webhook exists and has matched to a configured webhook
if(trigger == "ScanExecutionCompleted"):
logger.info("Getting Scan Summary from ASoC")
scanExec = self.asoc.scanSummary(subjectId, True)
if(not scanExec):
logger.error(f"Error getting scan execution summary {subjectId}")
return None
scanData = self.asoc.scanSummary(scanExec["ScanId"])
if(not scanData):
scanId = scanExec["ScanId"]
logger.error(f"Error getting scan summary {scanId}")
return None
appId = scanData["AppId"]
elif(trigger == "ApplicationUpdated"):
appId = subjectId
reportTargetId = appId
else:
logger.error(f"Unknown Webhook Trigger [{trigger}]")
return False
logger.info("Getting App Data from ASoC")
appData = self.asoc.getApplication(appId)
reportData = None
if(webhookObj["report_config"]):
logger.info("Downloading Report")
ext = webhookObj["report_config"]["Configuration"]["ReportFileType"].lower()
reportUrl = self.config["hostname"]+":"+str(self.config["port"])+"/reports/"+subjectId+"."+ext
path = "reports/"+subjectId+"."+ext
if(not self.saveReport(reportTargetId, webhookObj["report_config"], path, trigger)):
reportUrl = None
data = {
"scan_execution": scanExec,
"scan": scanData,
"app": appData,
"report_url": reportUrl
}
if(type=="json_post"):
logger.info("Processing template")
templateJson = self.applyTemplate("templates/"+webhookObj["template"], data)
logger.info("Submitting Webhook Json Post")
status = self.postWebhook(webhookObj["url"], templateJson)
logger.info(f"Submitted Json to Webhook - Response Code {status}")