-
Notifications
You must be signed in to change notification settings - Fork 6
/
nessus2wazuh.py
348 lines (301 loc) · 14.6 KB
/
nessus2wazuh.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
#This takes as input a .nessus scan file with either vulnerability or compliance info (or both)
#and dumps the data into elasticsearc into wazuh index
#
#autor: @Ar0xA / ar0xa@tldr.nu
#
#note: assumes timezone on nessus scanner and this script are the same!
from bs4 import BeautifulSoup
import argparse
import sys
import os
import io
import json
import configparser
import urllib3
import time
urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)
from objdict import ObjDict
from dateutil.parser import parse
from datetime import timedelta
#check if index exists
def ES_index_check (args):
#what index to we need to post to?
#can we reach the server?
es_server = args.elasticsearchserver
es_port = args.elasticsearchport
es_index = args.elasticsearchindex
es_url = "http://" + es_server + ":" + str(es_port) + "/"
#construct indexname
year, month, day, hour, minute = time.strftime("%Y,%m,%d,%H,%M").split(',')
es_index = es_index + "-" + year + "." + month +"."+ day
#test if index esists
http = urllib3.PoolManager()
r = http.request('HEAD', es_url+es_index)
#we need the existing index
if r.status == 404:
print ("Index %s does not exist, sorry. quitting." % (es_index))
sys.exit(1)
elif r.status == 200:
print ("Index already exists. Lets insert our data!")
elif not r.status == 200:
print ("Something is wrong with the index, but i have no idea what. I give up!")
print (r.status)
sys.exit(1)
#we retreive the agent.id from the /var/ossec/etc/client.keys
def get_id_from_keys(args, hostip):
try:
with open(args.ossec,'r') as keysfile:
filedata = keysfile.readlines()
for line in filedata:
if hostip in line:
#if we find it, we need the first number
return line.split(" ",1)[0]
except:
print ("Cant open %s. am I in the correct group or on the right system?" % (args.ossec))
sys.exit(1)
return False
#post data to elastic
def post_to_ES(json_data,args, task_id):
#what index to we need to post to?
#can we reach the server?
es_server = args.elasticsearchserver
es_port = args.elasticsearchport
es_index = args.elasticsearchindex
es_url = "http://" + es_server + ":" + str(es_port) + "/"
#construct indexname
year, month, day, hour, minute = time.strftime("%Y,%m,%d,%H,%M").split(',')
es_index = es_index + "-" + year + "." + month +"."+ day
http = urllib3.PoolManager()
#index exists, lets post the data #yolo
r = http.request('POST', es_url+es_index+"/wazuh", headers={'Content-Type':'application/json'}, body=json_data)
if not r.status == 201:
print ("well, something went wrong, thats embarrasing")
print (r.status)
print (r.reason)
sys.exit(1)
#here we parse results from the nessus file, we extract the vulnerabiltiy information
# we create a host, where we have general data and findings.
# General date is always there, findings can be none, one or many
# Some items in teh findings are always there, some are optional.
# The optional ones have some which can be arrays
def parse_to_json(nessus_xml_data, args):
#some quick report checking
data =ObjDict()
tmp_scanname = nessus_xml_data.report['name']
if len(tmp_scanname) == 0:
print ('Didn\'t find report name in file. is this a valid nessus file?')
sys.exit(1)
else:
data.scanname = tmp_scanname
#policyused
data.scanpolicy = nessus_xml_data.policyname.get_text()
# see if there are any hosts that are reported on
hosts = nessus_xml_data.findAll('reporthost')
if len(hosts) == 0:
print ('Didn\'t find any hosts in file. Is this a valid nessus file?')
sys.exit(1)
else:
print ('Found %i hosts' % (len(hosts)))
#find the Task ID for uniqueness checking
#test: is this unique per RUN..or per task?
task_id = ""
tmp_prefs = nessus_xml_data.findAll('preference')
for pref in tmp_prefs:
if "report_task_id" in str(pref):
task_id = pref.value.get_text()
#Lets see if the index already exists or not
if not args.fake:
ES_index_check (args)
print ("Checking for results and posting to ElasticSearch. This might take a while...")
for host in hosts:
#lets iterate through the reportItem, here the compliance items will be
reportItems = host.findAll('reportitem')
for rItem in reportItems:
host_info = ObjDict()
host_info.agent = ObjDict()
host_info.rule = ObjDict()
host_info.data = ObjDict()
host_info.manager = ObjDict()
#TODO make configurable to OSSEC server
host_info.manager.name = "debian"
#lets get the host information
#host_info.hostname = host['name']
host_info.agent.ip = host.find('tag', attrs={'name': 'host-ip'}).get_text()
#we got the IP...from here we need the agent.id
agent_id = get_id_from_keys(args,host_info.agent.ip)
host_info.agent.id = agent_id
if agent_id:
#default fields to make wazuh work
#host_info.rule.groups = "oscap, oscap-result"
host_info.rule.groups = "oscap"
host_info.location = "nessus_CIS-benchmark"
timeoffset = int((time.localtime().tm_gmtoff)/3600)
hostscanend = host.find('tag', attrs={'name': 'HOST_END'}).get_text()
hostscanend = parse(hostscanend)
hostscanend = hostscanend - timedelta(hours=timeoffset)
host_info["@timestamp"] = hostscanend.strftime("%Y-%m-%dT%H:%M:%S")
#fqdn might be optional
host_fqdn = host.find('tag', attrs={'name': 'host-fqdn'})
host_info.predecoder = ObjDict()
if host_fqdn:
host_info.predecoder.hostname = host_fqdn.get_text()
else:
host_info.predecoder.hostname = host_info.agent.ip
#get all report findings info
host_info.data.oscap = ObjDict()
host_info.data.oscap.check = ObjDict()
host_info.data.oscap.scan = ObjDict()
host_info.data.oscap.check.oval = ObjDict()
host_info.data.oscap.scan.benchmark = ObjDict()
host_info.data.oscap.scan.profile = ObjDict()
#a limitation of nessus is how severity is done in CIS benchmarking compared to oscap
#a benchmark scan in NEssus is always a severity 3,
#a missing warning because of wrong OS is 2
try:
severity = rItem['severity']
if severity == "0":
host_info.data.oscap.check.severity = "informational"
host_info.rule.level = 3
elif severity == "1":
print ("Severity 1 shouldn't happen with CIS benchmark scans!")
sys.exit(1)
# host_info.data.oscap.check.severity = "low"
# host_info.rule.level = 5
elif severity == "2": #warnings
host_info.data.oscap.check.severity = "low"
host_info.rule.level = 7
elif severity == "3":
host_info.data.oscap.check.severity = "medium"
host_info.rule.level = 10
else:
print ("unknown severity: %s" % (severity))
sys.exit(1)
host_info.data.oscap.scan.id = task_id
#these fields should always be present
host_info.data.oscap.check.oval.id = rItem['pluginid']
#host_info.data.oscap.scan.benchmark.id = rItem['pluginname'] #not needed for wazuh report screen
host_info.data.oscap.scan.profile.title = rItem['pluginname']
compliance_item = rItem.find('compliance')
#we're only interested in compliance items, really
if compliance_item:
#this stuff only around when its a compliance scan anyway
comaudit = rItem.find('cm:compliance-audit-file')
if comaudit:
#host_info.data.oscap.check.id = comaudit.get_text()
#host_info.data.oscap.scan.profile.id = comaudit.get_text()
host_info.data.oscap.scan.content = comaudit.get_text()
else:
#host_info.data.oscap.check.id = None
#host_info.data.oscap.scan.profile.id = None
host_info.data.oscap.scan.content = None
comcheck = rItem.find('cm:compliance-check-name')
if comcheck:
#host_info.data.oscap.check.description = comcheck.get_text()
host_info.data.oscap.check.title = comcheck.get_text()
else:
#host_info.data.oscap.check.description = comcheck.get_text()
host_info.data.oscap.check.title = comcheck.get_text()
cominfo = rItem.find('cm:compliance-info')
if cominfo:
host_info.data.oscap.check.rationale = cominfo.get_text().replace("\n","")
else:
host_info.data.oscap.check.rationale = None
comref = rItem.find('cm:compliance-reference')
if comref:
host_info.data.oscap.check.references = comref.get_text()
else:
host_info.data.oscap.check.references = None
comres = rItem.find('cm:compliance-result')
if comres:
complianceresult = comres.get_text()
if complianceresult == "PASSED":
host_info.data.oscap.check.result = "pass"
elif complianceresult == "FAILED":
host_info.data.oscap.check.result = "fail"
elif complianceresult == "WARNING":
host_info.data.oscap.check.result = "informational"
else:
print ("unknown compliance result:")
print (complianceresult)
sys.exit(1)
else:
host_info.complianceresult = None
#both compliance and vuln scan
descrip = rItem.find('description')
if descrip:
host_info.full_log = descrip.get_text()
else:
host_info.full_log = None
#we have all data in host_info, why not send that instead?
#print ("Finding for %s complete, sending to ES" % (host_info.hostname))
json_data = host_info.dumps()
#print (json_data)
if not args.fake:
post_to_ES(json_data, args, task_id)
#sys.exit(1)
except Exception as e:
print ("Error:")
print (e)
print (rItem)
sys.exit(1)
def parse_args():
parser = argparse.ArgumentParser(description = 'Push data into elasticsearch from a .nessus result file.')
group = parser.add_mutually_exclusive_group(required=True)
group.add_argument('-i', '--input', help = 'Input file in .nessus format',
default = None)
parser.add_argument('-o', '--ossec', help = 'Ossec key file',
default = '/var/ossec/etc/client.keys')
parser.add_argument('-es', '--elasticsearchserver', help = 'elasticsearch server',
default = '127.0.0.1')
parser.add_argument('-ep', '--elasticsearchport', help = 'elasticsearch port',
default = 9200)
parser.add_argument('-ei','--elasticsearchindex', help='What index to post the report data to',
default = 'wazuh-alerts-3.x')
parser.add_argument('-t', '--type', help = 'What type of result to parse the file for.', choices = ['both', 'vulnerability','compliance' ],
default = 'both')
parser.add_argument('-f','--fake', help = 'Do everything but actually send data to elasticsearch', action = 'store_true')
group.add_argument('-c', '--config', help = 'Config file for script to read settings from. Overwrites all other cli parameters', default = None)
args = parser.parse_args()
return args
#replace args from config file instead
def replace_args(args):
if os.path.isfile(args.config):
print ("Reading configuration from config file")
Config = ConfigParser.ConfigParser()
try:
Config.read(args.config)
args.input = Config.get("General","Input")
args.type = Config.get("General","Type")
args.fake = Config.getboolean("General","Fake")
args.ossec = Config.get("General", "OSSEC")
args.elasticsearchserver = Config.get("elasticsearch","elasticsearchServer")
args.elasticsearchport = Config.getint("elasticsearch","elasticsearchPort")
except IOError:
print('could not read config file "' + args.config + '".')
sys.exit(1)
else:
print('"' + args.config + '" is not a valid file.')
sys.exit(1)
return args
def main():
args = parse_args()
#do we have a config file instead of cli?
if args.config:
args = replace_args(args)
#ok, if not
if (not args.input) and (not args.nessusscanname):
print('Need input file to export. Specify one in the configuation file, with -i (file) or -rn (reportname)\n See -h for more info')
sys.exit(1)
if args.input:
nessus_scan_file = args.input
else:
nessus_scan_file = args.nessustmp + "/" + args.nessusscanname
print ("Nessus file to parse is %s" % (nessus_scan_file))
# read the file..might be big though...
with open(nessus_scan_file, 'r') as f:
print ('Parsing file %s as xml into memory, hold on...' % (args.input))
nessus_xml_data = BeautifulSoup(f.read(), 'lxml')
parse_to_json(nessus_xml_data, args)
if __name__ == "__main__":
main()
print ("Done.")