forked from gl4ssesbo1/Nebula
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathteamserver.py
463 lines (406 loc) · 18 KB
/
teamserver.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
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
import json
import multiprocessing
import os
import pathlib
import random
import re
import socket
import string
from getpass import getpass
import botocore
import argparse
import docker
import mongoengine
# import termcolor
from flask import Flask
from flask_bcrypt import Bcrypt
from flask_bcrypt import generate_password_hash
from flask_jwt_extended import JWTManager
from termcolor import colored
from waitress import serve
from core.Listeners.WebSocket.server import start_websocket_listener
from core.database.db import initialize_db
from core.database.models import Cosmonaut
from core.database.models import WebsocketListener
from core.models.AWSCredentials import awscredentials_blueprint
from core.models.AWSIAM import awsusers_blueprint
from core.models.AZURECredentials import azurecredentials_blueprint
from core.models.ClientCommands import clientcommands_blueprint
from core.models.Cosmonaut import cosmonaut_blueprint
from core.models.DigitalOceanCredentials import digitaloceancredentials_blueprint
from core.models.Domains import domains_blueprint
from core.models.Listeners import listener_blueprint
from core.models.Modules import module_blueprint
from core.models.AWSS3Buckets import awsbuckets_blueprint
parser = argparse.ArgumentParser(description='------ Nebula Teamserver Options ------')
#parser.add_argument('-ah', '--apiHost', type=str, help='The API Server Host. (Default: 127.0.0.1)', default='127.0.0.1')
parser.add_argument('-ap', '--apiPort', type=int, help='The API Server Port. (Default: 5000)', default=5000)
parser.add_argument('-dH', '--databaseHost', type=str, help='The MongoDB Database Server Host. (Default: localhost)', default='localhost')
parser.add_argument('-dP', '--databasePort', type=int, help='The MongoDB Database Server Port. (Default: 27017)', default=27017)
parser.add_argument('-dn', '--databaseName', type=str, help='The MongoDB Database Name. (Required)')
parser.add_argument('-du', '--databaseUser', type=str, help='The MongoDB Database User Name.')
parser.add_argument('-dp', '--databasePassword', type=str, help='The MongoDB Database Password.')
parser.add_argument('-p', '--password', type=str, help='The password for user \'cosmonaut\'. (Required)')
parser.add_argument('-y', '--yes', action="store_true", help='If this is set, the check for the database port will be skipped.')
#parser.add_argument('-c', '--config-file', type=str, help='The config file path with the configs.')
args = parser.parse_args()
IPv4_REGEX = "^[0-9]{1,3}[.]{1}[0-9]{1,3}[.]{1}[0-9]{1,3}[.]{1}[0-9]{1,3}$"
IPv6_REGEX = "^([0-9a-fA-F]{1,4}[:]{0,2}){1,8}$"
if not args.databaseName:
print("Provide DB Name using -dn (database name)")
exit()
if args.password is not None:
password = args.password
else:
password = getpass("Password: ")
while password == "":
password = getpass("Password: ")
host = args.databaseHost
port = str(args.databasePort)
database = args.databaseName
if args.databaseUser is not None:
databaseUser = args.databaseUser
else:
databaseUser = None
if args.databasePassword is not None:
databasePassword = args.databasePassword
else:
databasePassword = None
all_count = 0
show = [
'cleanup',
'detection',
'detectionbypass',
'enum',
'exploit',
'lateralmovement',
'listeners',
'persistence',
'privesc',
'reconnaissance',
'stager',
'misc',
'postexploitation'
]
nr_of_modules = {
'cleanup':"",
'detection':"",
'detectionbypass':"",
'enum':"",
'exploit':"",
'lateralmovement':"",
'listeners':"",
'persistence':"",
'privesc':"",
'reconnaissance':"",
'stager':"",
'misc':"",
'postexploitation': ""
}
for module in show:
module_count = 0
arr = os.listdir(f"{pathlib.Path(__file__).parent.resolve()}/core/module/" + module)
for x in arr:
if "__" in x:
continue
elif ".git" in x:
continue
else:
module_count += 1
all_count += 1
if module_count == 0:
nr_of_modules[module] = "0"
else:
nr_of_modules[module] = module_count
nr_of_cloud_modules = {
"aws":0,
"gcp":0,
"azure":0,
"o365":0,
"docker":0,
"kube":0,
"misc":0,
"azuread": 0,
"digitalocean": 0
}
clouds = [
"aws",
"gcp",
"azure",
"o365",
"docker",
"kube",
"azuread",
"misc",
"digitalocean"
]
for cloud in clouds:
module_count = 0
for module in show:
arr = os.listdir(f"{pathlib.Path(__file__).parent.resolve()}/core/module/{module}")
for x in arr:
if "__" in x:
continue
elif ".git" in x:
continue
else:
if x.split("_")[0] == cloud:
module_count += 1
nr_of_cloud_modules[cloud] = module_count
input_text = colored('------------------------------------------------------------\n', "green")
input_text += colored(''' _ _ _ _
| \ | | | | | |
| \| | ___| |__ _ _| | __ _
| . ` |/ _ \ '_ \| | | | |/ _` |
_______ | |\ | __/ |_) | |_| | | (_| |
|__ __||_| \_|\___|_.__/ \__,_|_|\__,_|
| | ___ __ _ _ __ ___ ___ ___ _ ____ _____ _ __
| |/ _ \/ _` | '_ ` _ \/ __|/ _ \ '__\ \ / / _ \ '__|
| | __/ (_| | | | | | \__ \ __/ | \ V / __/ |
|_|\___|\__,_|_| |_| |_|___/\___|_| \_/ \___|_|
''', 'blue')
input_text += (colored('-------------------------------------------------------------\n', "green"))
input_text += ("{} aws\t\t{} gcp\t\t{} azure\t\t{} office365\n".format(nr_of_cloud_modules['aws'], nr_of_cloud_modules['gcp'],
nr_of_cloud_modules['azure'], nr_of_cloud_modules['o365']))
input_text += (
"{} docker\t{} kubernetes\t{} misc\t\t{} azuread\n".format(nr_of_cloud_modules['docker'], nr_of_cloud_modules['kube'],
nr_of_cloud_modules['misc'],
nr_of_cloud_modules['azuread']))
input_text += (
"{} digitalocean\n".format(nr_of_cloud_modules['digitalocean']))
input_text += (colored("-------------------------------------------------------------\n", "green"))
input_text += ("{} modules\t{} cleanup\t\t{} detection\n".format(all_count, nr_of_modules['cleanup'], nr_of_modules['detection']))
input_text += ("{} enum\t\t{} exploit\t\t{} persistence\n".format(nr_of_modules['enum'], nr_of_modules['exploit'],
nr_of_modules['persistence']))
input_text += ("{} listeners\t{} lateral movement\t{} detection bypass\n".format(nr_of_modules['listeners'],
nr_of_modules['lateralmovement'],
nr_of_modules['detectionbypass']))
input_text += ("{} privesc\t{} reconnaissance\t{} stager\t{}postexploitation\n".format(nr_of_modules['privesc'], nr_of_modules['reconnaissance'],
nr_of_modules['stager'], nr_of_modules['postexploitation']))
input_text += ("{} misc\n".format(nr_of_modules['misc']))
print (input_text)
app = Flask(__name__)
bcrypt = Bcrypt(app)
jwt = JWTManager(app)
jwt_token = ''.join(random.choice(string.ascii_lowercase + string.ascii_uppercase + string.digits) for _ in range(32))
app.config['JWT_SECRET_KEY'] = jwt_token
#app.config['MONGODB_SETTINGS'] = {
# 'host': 'mongodb://{}:{}/{}'.format(host, port, database),
#}
"""if os.environ.get("VIRTUAL_ENV"):
sessionfile = f"{os.environ.get('VIRTUAL_ENV')}/lib/python3.10/site-packages/botocore/session.py"
useragentfile = f"{os.environ.get('VIRTUAL_ENV')}/lib/python3.10/site-packages/botocore/.user-agent"
else:
if os.path.exists(f"/usr/lib/python{sys.version.split('.')[0]}.{sys.version.split('.')[1]}/dist-packages/botocore/session.py"):
sessionfile = f"/usr/lib/python{sys.version.split('.')[0]}.{sys.version.split('.')[1]}/dist-packages/botocore/session.py"
useragentfile = f"/usr/lib/python{sys.version.split('.')[0]}.{sys.version.split('.')[1]}/dist-packages/botocore/.user-agent"
else:
sessionfile = f"/usr/local/lib/python3.10/site-packages/botocore/session.py"
useragentfile = f"/usr/local/lib/python3.10/site-packages/botocore/.user-agent"
"""
sessionfile = f"{botocore.__path__[0]}/session.py"
useragentfile = f"{botocore.__path__[0]}/.user-agent"
with open(sessionfile, "r") as botocoresessionfile:
botocorecheck = 0
botocoresessionfilelines = botocoresessionfile.readlines()
for line in botocoresessionfilelines:
if 'site-packages/botocore/.user-agent' in line:
botocorecheck = 1
if botocorecheck == 0:
with open(sessionfile, "w") as botocoresessiontemp:
for bline in botocoresessionfilelines:
if 'return base' in bline:
botocoresessiontemp.write('\t\timport sys\n'.expandtabs(4))
botocoresessiontemp.write(f'\t\tif os.path.exists(f"{useragentfile}"):\n'.expandtabs(4))
botocoresessiontemp.write(f'\t\t\twith open(f"{useragentfile}") as uafile:\n'.expandtabs(4))
botocoresessiontemp.write('\t\t\t\tbase = uafile.read().replace("\\n", "").strip()\n'.expandtabs(4))
botocoresessiontemp.write('\n')
botocoresessiontemp.write(bline)
else:
botocoresessiontemp.write(bline)
try:
#a_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
#location = (host, port)
#result_of_check = a_socket.connect_ex(location)
result_of_check = 0
if result_of_check == 0 and not args.yes:
mongo_instance_verify = input(colored("[*] Port is busy. Is a MongoDB instance running there? [y/N] ", "red"))
if not mongo_instance_verify.strip().replace("\n", "") == 'y' and not mongo_instance_verify.strip().replace(
"\n", "") == 'Y':
print(colored("[*] Choose another port or stop the other service!", "red"))
exit()
else:
'''
print(colored("[*] Pulling MongoDB Image...", "green"))
client = docker.from_env()
client.images.pull('mongo')
print(colored("[*] MongoDB Image Pulled!", "green"))
'''
workspace_directory = "/home/testdocker/datafolder"
if not os.path.exists("{}/workspaces/".format(os.getcwd())):
os.mkdir("{}/workspaces/".format(os.getcwd()))
if not os. path.exists("./workspaces/{}".format(database)):
os.mkdir("{}/workspaces/{}".format(os.getcwd(), database))
'''
container = client.containers.run(
'mongo',
ports={
#port:('127.0.0.1',port)
port:('0.0.0.0',port)
},
volumes={
workspace_directory: {
'bind': "/data/db",
'mode': 'rw'
}
},
detach=True
)
print("{} '{}'".format(
colored("[*] MongoDB started on container ID", "green"),
colored(container.id, "blue")
))
'''
if databaseUser is not None:
if re.match(IPv4_REGEX, host) or re.match(IPv6_REGEX, host):
app.config['MONGODB_SETTINGS'] = {
'host': f'mongodb://{databaseUser}:{databasePassword}@{host}:{port}/{database}'
#'host': 'mongodb://{0}:{1},{0}:{2},{0}:{3}/{4}?replicaSet=mongodb-replicaset'.format(host, port, port+1, port+2, database)
}
else:
app.config['MONGODB_SETTINGS'] = {
'host': f'mongodb+srv://{databaseUser}:{databasePassword}@{host}/{database}'
#'host': 'mongodb://{0}:{1},{0}:{2},{0}:{3}/{4}?replicaSet=mongodb-replicaset'.format(host, port, port+1, port+2, database)
}
else:
if re.match(IPv4_REGEX, host) or re.match(IPv6_REGEX, host):
app.config['MONGODB_SETTINGS'] = {
'host': f'mongodb://{host}:{port}/{database}'
# 'host': 'mongodb://{0}:{1},{0}:{2},{0}:{3}/{4}?replicaSet=mongodb-replicaset'.format(host, port, port+1, port+2, database)
}
else:
app.config['MONGODB_SETTINGS'] = {
'host': f'mongodb+srv://{host}/{database}'
# 'host': 'mongodb://{0}:{1},{0}:{2},{0}:{3}/{4}?replicaSet=mongodb-replicaset'.format(host, port, port+1, port+2, database)
}
#app.config['MONGODB_DB'] = database
#app.config['MONGODB_HOST'] = host
#app.config['MONGODB_PORT'] = port
#app.config['MONGODB_CONNECT'] = False
print(colored('------------------------------------------------------------', "green"))
print("{} '{}'".format(
colored("[*] JWT Secret Key set to:", "green"),
colored(jwt_token, "blue")
))
print("{} '{}:{}'".format(
colored("[*] Database Server set to:", "green"),
colored(host, "blue"),
colored(port, "blue")
))
print("{} '{}'".format(
colored("[*] Database set to:", "green"),
colored(database, "blue")
))
# I am not using these on Nebula. So it's not an information disclosure. It's just sth I plan to use latter.
#app.config['MONGODB_USERNAME'] = 'user'
#app.config['MONGODB_PASSWORD'] = 'pass'
initialize_db(app)
try:
body = {
"cosmonaut_name": "cosmonaut",
"cosmonaut_pass": password
}
cosmonaut = Cosmonaut(**body)
cosmonaut.hash_password()
cosmonaut.save()
except mongoengine.errors.NotUniqueError as ex:
cosmonaut = Cosmonaut.objects.get(cosmonaut_name=body['cosmonaut_name'])
body['cosmonaut_pass'] = generate_password_hash(password).decode('utf8')
cosmonaut.update(**body)
#import socket
sIP = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
sIP.connect(("8.8.8.8", 80))
print('{}{}{}'.format(
colored("[*] Teamserver IP address is '", "green"),
colored(sIP.getsockname()[0], "blue"),
colored("'", "green"))
)
sIP.close()
print('{}{}{}'.format(
colored("[*] User '", "green"),
colored("cosmonaut", "blue"),
colored("' was created!", "green")
)
)
app.register_blueprint(listener_blueprint)
app.register_blueprint(cosmonaut_blueprint)
app.register_blueprint(module_blueprint)
app.register_blueprint(awscredentials_blueprint)
app.register_blueprint(awsusers_blueprint)
app.register_blueprint(azurecredentials_blueprint)
app.register_blueprint(digitaloceancredentials_blueprint)
app.register_blueprint(domains_blueprint)
app.register_blueprint(clientcommands_blueprint)
app.register_blueprint(awsbuckets_blueprint)
except SystemExit:
exit()
except docker.errors.DockerException as ex:
print(colored("[*] Please start the docker service. (service docker start)", "red"))
exit()
except Exception as e:
if e == None or e == "":
exit()
else:
print(colored("[*] {}".format(e), "red"))
exit()
def startWebsocketListeners():
try:
websocket_listeners = json.loads(WebsocketListener.objects().to_json())
if len(websocket_listeners) > 0:
for wslistener in websocket_listeners:
if wslistener['listener_status'] == "running":
wsbody = {
"listener_name": wslistener['listener_name'],
"listener_host": wslistener['listener_host'],
"listener_port": wslistener['listener_port'],
"listener_protocol": "WebSocket"
}
try:
p = multiprocessing.Process(target=start_websocket_listener,
args=(wslistener['listener_port'], None, None,))
p.start()
print(colored("[*] Listener '{}' started on host '{}' and port '{}'".format(
wslistener['listener_name'],
wslistener['listener_host'],
str(wslistener['listener_port'])
), "green"))
except Exception as e:
wslistener['listener_status'] = "dead"
try:
WebsocketListener.objects.get_or_404(listener_name=wslistener['listener_name']).update(
**wsbody)
except mongoengine.DoesNotExist:
WebsocketListener.save(**wsbody)
except Exception as e:
print(colored("[*] Listener '{}' on host '{}' and port '{}' did not start".format(
wslistener['listener_name'],
wslistener['listener_host'],
str(wslistener['listener_port'])
), "red"))
except Exception as e:
if e == None or e == "":
exit()
else:
print(colored("[*] {}".format(e), "red"))
exit()
if __name__ == "__main__":
apihost = "0.0.0.0"
apiport = args.apiPort
print("{} '{}:{}'".format(
colored("[*] API Server set to:", "green"),
colored(apihost, "blue"),
colored(apiport, "blue")
))
print(colored('------------------------------------------------------------', "green"))
startWebsocketListeners()
serve(app, host=apihost, port=apiport)