-
Notifications
You must be signed in to change notification settings - Fork 0
/
openc2
341 lines (324 loc) · 14.2 KB
/
openc2
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
#!/usr/bin/env python3
#
# The MIT License (MIT)
#
# Copyright 2018 University of North Carolina at Chapel Hill. All other rights reserved.
#
# Permission is hereby granted, free of charge, to any person obtaining a copy of this software
# and associated documentation files (the "Software"), to deal in the Software without
# restriction, including without limitation the rights to use, copy, modify, merge, publish,
# distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the
# Software is furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in all copies or
# substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
# FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
# COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN
# AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
# WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
#
import subprocess
import json
import os
import sys
import signal
TIMEOUT=10
# top-level subroutine or function takes no arguments
# code for OpenC2 consumer
def main():
# handle HTTP requests within 10s for UNIX/LINUX
signal.signal(signal.SIGALRM, handler)
signal.alarm(TIMEOUT)
# call function that will handle incoming requests from an OpenC2 producer
request_handler()
signal.alarm(0)
# alarm function to timeout requests
def handler(signum, frame):
server_error();
raise IOError("Couldn't open device!")
#function to handle GET, POST, cli request and make calls to other functions to execute commands
#figure out exactly what we want this function to do as far as parsing
def request_handler():
conformance=0
openc2_actions=['query', 'deny', 'allow', 'update', 'delete']
openc2_targets=['file', 'ipv4_net', 'ipv6_net', 'ipv4_connection', 'ipv6_connection', 'features', 'slpf:rulenumber']
openc2_query=['versions','profiles','pairs','rate_limit']
openc2_response_requested=['none','ack','status','complete']
complete_response="complete"
openc2_query_versions=['1.0']
the_action=""
the_target=""
#attempt to read request passed from CLI or HTTPd
request=sys.stdin.read()
#attempt to parse request as JSON
try:
parsed_json = json.loads(request)
except:
not_parseable()
#was no response requested
try:
resp_req=parsed_json.get("args").get("response_requested")
except:
#response_requested was not set, assume requestor desires complete response
resp_req=openc2_response_requested[3]
if resp_req==None:
resp_req=openc2_response_requested[3]
elif resp_req==openc2_response_requested[0]:
# no response is requested, so just return a blank 200 OK
complete_response="none"
elif resp_req==openc2_response_requested[1]:
complete_response="status_only"
elif resp_req==openc2_response_requested[2]:
complete_response="status_only"
elif resp_req==openc2_response_requested[3]:
complete_response="complete"
else:
not_parseable('resp_req')
#try to parse the actuator id:
queried_asset="myself"
try:
queried_asset=parsed_json.get("actuator").get("slpf").get("named_group")
except:
#response_requested was not set, assume requestor desires complete response
queried_asset="myself"
if (queried_asset=="cloud" or queried_asset=="myself" or queried_asset=="iptables"):
queried_asset="myself"
else:
queried_asset="myself"
#server_204()
#do we have an actions var
# try:
# the_action=parsed_json.get("action")
# except:
# the_action="not specified"
# for alpha in openc2_actions:
# if alpha==the_action:
# conformance += 1
# if conformance!=1:
# not_parseable()
#do we have a targets var
conformance=0
tempA=None
tempB=None
tempC=None
tempD=None
tempE=None
tempF=None
try:
tempA=parsed_json.get("target").get("ipv4_net")
except:
conformance=0
try:
tempB=parsed_json.get("target").get("features")
except:
conformance=0
try:
tempC=parsed_json.get("target").get("file")
except:
conformance=0
try:
tempD=parsed_json.get("target").get("ipv4_connection")
except:
conformance=0
try:
tempE=parsed_json.get("target").get("ipv6_net")
except:
conformance=0
try:
tempF=parsed_json.get("target").get("ipv6_connection")
except:
conformance=0
if True:
# we have a request with an action and a target
conformance=0
# check for query features
feature_count=0
feature_power=0
feature_total=0
#check for query action
if parsed_json.get("action")==openc2_actions[0]:
if openc2_targets[5] in parsed_json.get("target"):
for charlie in parsed_json.get("target").get("features"):
if charlie==0:
feature_total=feature_total
elif charlie==openc2_query[0]:
feature_total=1
elif charlie==openc2_query[1]:
feature_total=feature_total+2
elif charlie==openc2_query[2]:
feature_total=feature_total+4
elif charlie==openc2_query[3]:
feature_total=feature_total+8
else:
not_parseable('query')
if feature_total==0:
server_200(complete_response,json.loads('{"status":200}'))
elif feature_total==1:
server_200(complete_response,json.loads('{"status":200,"results":{"versions":["1.0"]}}'))
elif feature_total==2:
server_200(complete_response,json.loads('{"status":200,"results":{"profiles":["slpf"]}}'))
elif feature_total==3:
server_200(complete_response,json.loads('{"status":200,"results":{"versions":["1.0"],"profiles":["slpf"]}}'))
elif feature_total==4:
server_200(complete_response,json.loads('{"status":200,"results":{"pairs":{"allow":["ipv4_net","ipv4_connection","ipv6_net","ipv6_connection"],"deny":["ipv4_net","ipv4_connection","ipv6_net","ipv6_connection"],"query":["features"]}}}'))
elif feature_total==5:
server_200(complete_response,json.loads('{"status":200,"results":{"versions":["1.0"],"pairs":{"allow":["ipv4_net"],"deny":["ipv4_net"],"query":["features"]}}}'))
elif feature_total==6:
server_200(complete_response,json.loads('{"status":200,"results":{"profiles":["slpf"],"pairs":{"allow":["ipv4_net"],"deny":["ipv4_net"],"query":["features"]}}}'))
elif feature_total==7:
server_200(complete_response,json.loads('{"status":200,"results":{"versions":["1.0"],"profiles":["slpf"],"pairs":{"allow":["ipv4_net"],"deny":["ipv4_net"],"query":["features"]}}}'))
elif feature_total==8:
server_200(complete_response,json.loads('{"status":200,"results":{"rate_limit":10}}'))
elif feature_total==9:
server_200(complete_response,json.loads('{"status":200,"results":{"versions":["1.0"],"rate_limit":10}}'))
elif feature_total==10:
server_200(complete_response,json.loads('{"status":200,"results":{"profiles":["slpf"],"rate_limit":10}}'))
elif feature_total==11:
server_200(complete_response,json.loads('{"status":200,"results":{"versions":["1.0"],"profiles":["slpf"],"rate_limit":10}}'))
elif feature_total==12:
server_200(complete_response,json.loads('{"status":200,"results":{"pairs":{"allow":["ipv4_net"],"deny":["ipv4_net"],"query":["features"]},"rate_limit":10}}'))
elif feature_total==13:
server_200(complete_response,json.loads('{"status":200,"results":{"versions":["1.0"],"pairs":{"allow":["ipv4_net"],"deny":["ipv4_net"],"query":["features"]},"rate_limit":10}}'))
elif feature_total==14:
server_200(complete_response,json.loads('{"status":200,"results":{"profiles":["slpf"],"pairs":{"allow":["ipv4_net"],"deny":["ipv4_net"],"query":["features"]},"rate_limit":10}}'))
elif feature_total==15:
server_200(complete_response,json.loads('{"status":200,"results":{"versions":["1.0"],"profiles":["slpf"],"pairs":{"allow":["ipv4_net"],"deny":["ipv4_net"],"query":["features"]},"rate_limit":10}}'))
else:
not_parseable('query2')
# action is either deny, allow, update, or delete
elif parsed_json.get("action")==openc2_actions[3]:
not_implemented()
elif parsed_json.get("action")==openc2_actions[4]:
not_implemented()
# action is either allow or deny
elif (parsed_json.get("action")==openc2_actions[1]) or (parsed_json.get("action")==openc2_actions[2]):
# we are dealing with an eny or allow action
requested_action=parsed_json.get("action")
directionality="ingress"
net=""
try:
directionality=parsed_json.get("args").get("slpf").get("direction")
except:
directionality="ingress"
try:
net=parsed_json.get("target").get("ipv4_net")
except:
net=""
try:
netsix=parsed_json.get("target").get("ipv6_net")
except:
netsix=""
if net is None:
sanitize(netsix)
execute_iptables(requested_action,netsix,directionality,complete_response)
else:
sanitize(net)
execute_iptables(requested_action,net,directionality,complete_response)
# action not found, return error
else:
server_error()
# tell producer we do not implement or support the request or command
def not_implemented():
print('Status: 501 Internal Server Error')
print('Content-Type: application/openc2-rsp+json;version=1.0')
print('')
print(json.dumps({'status': (501), 'status_text': 'Server error, not implemented'}, sort_keys=True, indent=4))
print('')
exit()
# basically do not respond to producer, no Message/Response sent
def server_204():
print('Status: 204 No Content')
print('Content-Type: application/openc2-rsp+json;version=1.0')
print('')
print('')
exit()
# tell producer something went wrong
def server_error():
print('Status: 500 Internal Server Error')
print('Content-Type: application/openc2-rsp+json;version=1.0')
print('')
print(json.dumps({'status': (500), 'status_text': 'Server error'}, sort_keys=True, indent=4))
print('')
exit()
# tell producer we could not interpret request
def not_parseable(comment):
print('Status: 400 Bad Request')
print('Content-Type: application/openc2-rsp+json;version=1.0')
print('')
print(json.dumps(['response', {'status': (400), 'status_text': 'unable to parse request near '+comment}], sort_keys=True, indent=4))
print('')
exit()
# tell producer things were ok
def server_200(complete,resultant):
print('Content-Type: application/openc2-rsp+json;version=1.0')
print('')
if complete=="complete":
print(json.dumps(resultant, sort_keys=True, indent=4))
elif complete=="none":
print('')
else:
print('{"status":200}')
exit()
# function to sanitize untrusted input
def sanitize(ip_network):
semi=ip_network.find(';')
if semi>=0:
not_parseable()
if len(ip_network)>48:
not_parseable()
elif len(ip_network)<7:
not_parseable()
else:
sanitized=1
# function to run iptables or ip6tables
# presently only supports denying or allowing a source IP
def execute_iptables(action,network,direction,expected_response):
if action=="deny":
action_cli="DROP"
elif action=="allow":
action_cli="ACCEPT"
elif action=="delete":
action_cli="-D"
else:
server_error()
if direction=="ingress":
chain="INPUT"
elif direction=="egress":
chain="OUTPUT"
else:
chain="BOTH"
# test for ipv6
ipvsix = network.find(':')
# iptables command to review source IP and either allow or deny it
if chain=="BOTH":
#need to execute two iptables commands
#command_line_args=f"/sbin/iptables --append INPUT --source {source} --jump {action_cli}"
if ipvsix==-1:
result=subprocess.run(['sudo','/sbin/iptables','--append','INPUT','--source',network,'--jump',action_cli], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
result=subprocess.run(['sudo','/sbin/iptables','--append','OUTPUT','--destination',network,'--jump',action_cli], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
server_200(expected_response,json.loads('{"status":200, "status_text":"new rule appended"}'))
else:
result=subprocess.run(['sudo','/sbin/ip6tables','--append','INPUT','--source',network,'--jump',action_cli], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
result=subprocess.run(['sudo','/sbin/ip6tables','--append','OUTPUT','--destination',network,'--jump',action_cli], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
server_200(expected_response,json.loads('{"status":200, "status_text":"new rule appended"}'))
#one command for ingress
elif chain=="INPUT":
if ipvsix==-1:
result=subprocess.run(['sudo','/sbin/iptables','--append','INPUT','--source',network,'--jump',action_cli], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
server_200(expected_response,json.loads('{"status":200}'))
else:
result=subprocess.run(['sudo','/sbin/ip6tables','--append','INPUT','--source',network,'--jump',action_cli], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
server_200(expected_response,json.loads('{"status":200}'))
#must have been an egress request
else:
if ipvsix==-1:
result=subprocess.run(['sudo','/sbin/iptables','--append','OUTPUT','--destination',network,'--jump',action_cli], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
server_200(expected_response,json.loads('{"status":200}'))
else:
result=subprocess.run(['sudo','/sbin/ip6tables','--append','OUTPUT','--destination',network,'--jump',action_cli], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
server_200(expected_response,json.loads('{"status":200}'))
if __name__ == "__main__":
main()