-
Notifications
You must be signed in to change notification settings - Fork 5
/
custom-socfortress.py
267 lines (252 loc) · 9.98 KB
/
custom-socfortress.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
#!/var/ossec/framework/python/bin/python3
# Copyright (C) 2023, SOCFortress, LLP.
import json
import sys
import time
import os
import ipaddress
import re
from socket import socket, AF_UNIX, SOCK_DGRAM
try:
import requests
from requests.auth import HTTPBasicAuth
except Exception as e:
print("No module 'requests' found. Install: pip install requests")
sys.exit(1)
# Global vars
debug_enabled = False
pwd = os.path.dirname(os.path.dirname(os.path.realpath(__file__)))
json_alert = {}
now = time.strftime("%a %b %d %H:%M:%S %Z %Y")
# Set paths
log_file = '{0}/logs/integrations.log'.format(pwd)
socket_addr = '{0}/queue/sockets/queue'.format(pwd)
def main(args):
debug("# Starting")
# Read args
alert_file_location = args[1]
apikey = args[2]
debug("# API Key")
debug(apikey)
debug("# File location")
debug(alert_file_location)
# Load alert. Parse JSON object.
with open(alert_file_location) as alert_file:
json_alert = json.load(alert_file)
debug("# Processing alert")
debug(json_alert)
# Request SOCFortress info
msg = request_socfortress_api(json_alert,apikey)
# If positive match, send event to Wazuh Manager
if msg:
send_event(msg, json_alert["agent"])
def debug(msg):
if debug_enabled:
msg = "{0}: {1}\n".format(now, msg)
print(msg)
f = open(log_file,"a")
f.write(msg)
f.close()
def collect_source_1(data):
comment = data['comment']
value = data['value']
timestamp = data['timestamp']
if timestamp is None:
timestamp = '1679526769'
category = data['category']
type = data['type']
virustotal_url = data['virustotal_url']
return comment, value, timestamp, category, type, virustotal_url
def collect_source_2(data):
comment = data['comment']
value = data['value']
type = data['type']
last_seen = data['last_seen']
report_id = data['report_id']
report_url = data['report_url']
virustotal_url = data['virustotal_url']
return comment, value, type, last_seen, report_id, report_url, virustotal_url
def collect_source_3(data):
comment = data['comment']
value = data['value']
type = data['type']
last_seen = data['last_seen']
virustotal_url = data['virustotal_url']
return comment, value, type, last_seen, virustotal_url
def is_ipv4(value):
try:
ipaddress.IPv4Address(value)
debug(f"{value} is a valid IPv4 address.")
return True
except ipaddress.AddressValueError:
debug(f"{value} is not a valid IPv4 address.")
return False
def is_domain(value):
try:
domain_regex = re.compile(r"^([a-z0-9]+(-[a-z0-9]+)*\.)+[a-z]{2,}$", re.IGNORECASE)
if domain_regex.match(value):
debug(f"{value} is a valid domain name.")
return True
else:
debug(f"{value} is not a valid domain name.")
return False
except Exception as e:
debug(f"Error: {e}")
return False
def ioc_source(data, ioc_value):
result = data['ioc_source']
if result == '1':
return True
return False
def has_report(data, ioc_value):
if 'report_found' in data:
return True
return False
def query_api(ioc_value, apikey):
params = {'value': ioc_value,}
headers = {
'Accept': 'application/json',
'Content-Type': 'application/json',
"x-api-key": apikey,
"module-version": "1.0",
}
response = requests.get('https://intel.socfortress.co/search', params=params, headers=headers)
if response.status_code == 200:
json_response = response.json()
data = json_response.get('data')
return data
elif response.status_code == 403 or response.status_code == 429:
json_response = response.json()
data = json_response
alert_output = {}
alert_output["socfortress"] = {}
alert_output["integration"] = "custom-socfortress"
alert_output["socfortress"]["status_code"] = response.status_code
alert_output["socfortress"]["message"] = json_response['message']
send_event(alert_output)
exit(0)
else:
alert_output = {}
alert_output["socfortress"] = {}
alert_output["integration"] = "custom-socfortress"
json_response = response.json()
debug("# Error: The SOCFortress integration encountered an error")
alert_output["socfortress"]["status_code"] = response.status_code
alert_output["socfortress"]["message"] = json_response['error']
send_event(alert_output)
exit(0)
def request_socfortress_api(alert, apikey):
alert_output = {}
# Collect the IoC Type - Currently only Supports SYSMON For Windows
event_source = alert["rule"]["groups"][0]
if 'windows' in event_source.lower():
if 'hashes' in alert["data"]["win"]["eventdata"]:
## Regex Pattern used based on SHA256 lenght (64 characters)
regex_file_hash = re.compile('\w{64}')
ioc_value = regex_file_hash.search(alert["data"]["win"]["eventdata"]["hashes"]).group(0)
data = query_api(ioc_value, apikey)
elif 'destinationIp' in alert["data"]["win"]["eventdata"]:
ioc_value = alert["data"]["win"]["eventdata"]["destinationIp"]
ipv4 = is_ipv4(ioc_value)
if ipv4 and ipaddress.ip_address(ioc_value).is_global:
data = query_api(ioc_value, apikey)
else:
return(0)
elif 'queryName' in alert["data"]["win"]["eventdata"]:
ioc_value = alert["data"]["win"]["eventdata"]["queryName"]
domain = is_domain(ioc_value)
if domain:
data = query_api(ioc_value, apikey)
else:
return(0)
else:
return(0)
else:
return(0)
# Create alert
alert_output["socfortress"] = {}
alert_output["integration"] = "custom-socfortress"
alert_output["socfortress"]["found"] = 0
alert_output["socfortress"]["source"] = {}
alert_output["socfortress"]["source"]["alert_id"] = alert["id"]
alert_output["socfortress"]["source"]["agent_name"] = alert["agent"]["name"]
alert_output["socfortress"]["source"]["rule"] = alert["rule"]["id"]
alert_output["socfortress"]["source"]["description"] = alert["rule"]["description"]
alert_output["socfortress"]["source"]["processGuid"] = alert["data"]["win"]["eventdata"]["processGuid"]
alert_output["socfortress"]["source"]["ioc_value"] = ioc_value
ioc_value = ioc_value
# Check if SOCFortress has any info about the IoC
if ioc_source(data, ioc_value):
alert_output["socfortress"]["ioc_source"] = 1
else:
alert_output["socfortress"]["ioc_source"] = 2
# Check if SOCFortress has any reports about the IoC
report_found = has_report(data, ioc_value)
if report_found:
alert_output["socfortress"]["report_found"] = 1
else:
alert_output["socfortress"]["report_found"] = 0
if alert_output["socfortress"]["ioc_source"] == 2 and alert_output["socfortress"]["report_found"] == 1:
comment, value, type, last_seen, report_id, report_url, virustotal_url = collect_source_2(data)
# Populate JSON Output with SOCFortress results
alert_output["socfortress"]["status_code"] = 200
alert_output["socfortress"]["comment"] = comment
alert_output["socfortress"]["value"] = value
alert_output["socfortress"]["last_seen"] = last_seen
alert_output["socfortress"]["type"] = type
alert_output["socfortress"]["report_id"] = report_id
alert_output["socfortress"]["report_url"] = report_url
alert_output["socfortress"]["virustotal_url"] = virustotal_url
if alert_output["socfortress"]["ioc_source"] == 2 and alert_output["socfortress"]["report_found"] == 0:
comment, value, type, last_seen, virustotal_url = collect_source_3(data)
alert_output["socfortress"]["status_code"] = 200
alert_output["socfortress"]["comment"] = comment
alert_output["socfortress"]["value"] = value
alert_output["socfortress"]["last_seen"] = last_seen
alert_output["socfortress"]["type"] = type
alert_output["socfortress"]["virustotal_url"] = virustotal_url
# Info about the IoC found in SOCFortress
if alert_output["socfortress"]["ioc_source"] == 1:
comment, value, timestamp, category, type, virustotal_url = collect_source_1(data)
# Populate JSON Output object with SOCFortress results
alert_output["socfortress"]["status_code"] = 200
alert_output["socfortress"]["comment"] = comment
alert_output["socfortress"]["value"] = value
alert_output["socfortress"]["timestamp"] = timestamp
alert_output["socfortress"]["category"] = category
alert_output["socfortress"]["type"] = type
alert_output["socfortress"]["virustotal_url"] = virustotal_url
debug(alert_output)
return(alert_output)
def send_event(msg, agent = None):
if not agent or agent["id"] == "000":
string = '1:socfortress:{0}'.format(json.dumps(msg))
else:
string = '1:[{0}] ({1}) {2}->socfortress:{3}'.format(agent["id"], agent["name"], agent["ip"] if "ip" in agent else "any", json.dumps(msg))
debug(string)
sock = socket(AF_UNIX, SOCK_DGRAM)
sock.connect(socket_addr)
sock.send(string.encode())
sock.close()
if __name__ == "__main__":
try:
# Read arguments
bad_arguments = False
if len(sys.argv) >= 4:
msg = '{0} {1} {2} {3} {4}'.format(now, sys.argv[1], sys.argv[2], sys.argv[3], sys.argv[4] if len(sys.argv) > 4 else '')
debug_enabled = (len(sys.argv) > 4 and sys.argv[4] == 'debug')
else:
msg = '{0} Wrong arguments'.format(now)
bad_arguments = True
# Logging the call
f = open(log_file, 'a')
f.write(msg +'\n')
f.close()
if bad_arguments:
debug("# Exiting: Bad arguments.")
sys.exit(1)
# Main function
main(sys.argv)
except Exception as e:
debug(str(e))
raise