-
Notifications
You must be signed in to change notification settings - Fork 296
/
rootthebox.py
1247 lines (1046 loc) · 30.2 KB
/
rootthebox.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
"""
Copyright 2012 Root the Box
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
----------------------------------------------------------------------------
This file is the main starting point for the application, based on the
command line arguments it calls various components setup/start/etc.
"""
# pylint: disable=unused-wildcard-import,unused-variable
from __future__ import print_function
import logging
import os
import random
import sys
from builtins import input, str
from datetime import datetime
import nose
from tornado.options import define, options
from libs.ConfigHelpers import save_config, save_config_image
from libs.ConsoleColors import *
from libs.StringCoding import set_type
from setup import __version__
def current_time():
"""Nicely formatted current time as a string"""
return str(datetime.now()).split(" ")[1].split(".")[0]
def start():
"""Update the database schema"""
try:
from handlers import update_db
update_db()
except Exception as error:
logging.error("Error: %s" % error)
if "Can't locate revision identified" not in str(error):
# Skipped if alembic record ahead for branch compatibility
os._exit(1)
""" Starts the application """
from handlers import start_server
prefix = "https://" if options.ssl else "http://"
# TODO For docker, it would be nice to grab the mapped docker port
listenport = C + "%slocalhost:%s" % (prefix, str(options.listen_port)) + W
sys.stdout.flush()
try:
print(INFO + bold + R + "Starting RTB on %s" % listenport, flush=True)
except TypeError:
print(INFO + bold + R + "Starting RTB on %s" % listenport)
if len(options.mail_host) > 0 and "localhost" in options.origin:
logging.warning(
"%sWARNING:%s Invalid 'origin' configuration (localhost) for Email support %s"
% (WARN + bold + R, W, WARN)
)
result = start_server()
if result == "restart":
restart()
def setup():
"""
Creates/bootstraps the database.
If you're a real developer you'll figure out how to remove the
warning yourself. Don't merge any code the removes it.
"""
is_devel = options.setup.startswith("dev")
if is_devel:
print("%sWARNING:%s Setup is in development mode %s" % (WARN + bold, W, WARN))
message = "I know what the fuck I am doing"
resp = input(PROMPT + 'Please type "%s": ' % message)
if resp.replace('"', "").lower().strip() != message.lower():
os._exit(1)
else:
is_devel = options.setup.startswith("docker")
print(INFO + "%s : Creating the database ..." % current_time())
from setup.create_database import create_tables, engine, metadata
create_tables(engine, metadata, options.log_sql)
sys.stdout.flush()
from models.Theme import Theme
themes = Theme.all()
if len(themes) > 0:
print(INFO + "It looks like database has already been set up.")
return
print(INFO + "%s : Bootstrapping the database ..." % current_time())
import setup.bootstrap
# Display Details
if is_devel:
environ = bold + R + "Development bootstrap:"
details = C + "Admin Username: admin, Password: rootthebox" + W
else:
environ = bold + "Production bootstrap" + W
details = ""
from handlers import update_db
update_db(False)
sys.stdout.flush()
try:
print(INFO + "%s %s" % (environ, details), flush=True)
except:
print(INFO + "%s %s" % (environ, details))
def recovery():
"""Starts the recovery console"""
from setup.recovery import RecoveryConsole
print(INFO + "%s : Starting recovery console ..." % current_time())
console = RecoveryConsole()
try:
console.cmdloop()
except KeyboardInterrupt:
print(INFO + "Have a nice day!")
def setup_xml(xml_params):
"""Imports XML file(s)"""
from setup.xmlsetup import import_xml
for index, xml_param in enumerate(xml_params):
print(
INFO + "Processing %d of %d .xml file(s) ..." % (index + 1, len(xml_params))
)
import_xml(xml_param)
print(INFO + "%s : Completed processing of all .xml file(s)" % (current_time()))
def generate_teams(num_teams):
"""Generates teams by number"""
from models import Team, dbsession
for i in range(0, num_teams):
team = Team()
team.name = "Team " + str(i + 1)
dbsession.add(team)
dbsession.flush()
dbsession.commit()
def generate_teams_by_name(team_names):
"""Generates teams by their names"""
from models import Team, dbsession
for i in range(0, len(team_names)):
team = Team()
team.name = team_names[i]
dbsession.add(team)
dbsession.flush()
dbsession.commit()
def generate_admins(admin_names):
"""Creates admin users with the syntax '<handle> <email> <password>'"""
from models import Permission, User, dbsession
from models.User import ADMIN_PERMISSION
for i in range(0, len(admin_names)):
admin_detail = admin_names[i].split()
user = User(
handle=admin_detail[0],
name=admin_detail[0],
email=admin_detail[1],
password=admin_detail[2],
)
dbsession.add(user)
dbsession.flush()
admin_permission = Permission(name=ADMIN_PERMISSION, user_id=user.id)
dbsession.add(admin_permission)
dbsession.flush()
dbsession.commit()
def tests():
"""Creates a temporary sqlite database and runs the unit tests"""
print(INFO + "%s : Running unit tests ..." % current_time())
from tests import setup_database, teardown_database
db_name = "test-%04s" % random.randint(0, 9999)
setup_database(db_name)
nose.run(module="tests", argv=[os.getcwd() + "/tests"])
teardown_database(db_name)
def restart():
"""
Shutdown the actual process and restart the service.
Useful for rootthebox.cfg changes.
"""
pid = os.getpid()
print(INFO + "%s : Restarting the service (%i)..." % (current_time(), pid))
os.execl("./setup/restart.sh", "./setup/restart.sh")
def update():
"""Update RTB to the latest repository code."""
os.system("git pull")
def version():
from sqlalchemy import __version__ as orm_version
from tornado import version as tornado_version
print(bold + "Root the Box%s v%s" % (W, __version__))
print(bold + " SQL Alchemy%s v%s" % (W, orm_version))
print(bold + " Torando%s v%s" % (W, tornado_version))
def check_cwd():
"""Checks to make sure the cwd is the application root directory"""
app_root = os.path.dirname(os.path.abspath(__file__))
if app_root != os.getcwd():
print(INFO + "Switching CWD to '%s'" % app_root)
os.chdir(app_root)
def options_parse_environment():
# Used for defining vars in cloud environment
# Takes priority over rootthebox.cfg variables
if os.environ.get("PORT", None) is not None:
# Heroku uses $PORT to define listen_port
options.listen_port = int(os.environ.get("PORT"))
logging.info("Environment Configuration (PORT): %d" % options.listen_port)
images = ["ctf_logo", "story_character", "scoreboard_right_image"]
for item in options.as_dict():
config = os.environ.get(item.upper(), os.environ.get(item, None))
if config is not None:
if item in images:
value = save_config_image(config)
else:
value = config
value = set_type(value, options[item])
if isinstance(value, type(options[item])):
logging.info(
"Environment Configuration (%s): %s" % (item.upper(), value)
)
options[item] = value
else:
logging.error(
"Environment Configuration (%s): unable to convert type %s to %s for %s"
% (item.upper(), type(value), type(options[item]), value)
)
def help():
help_response = [
"\tNo options specified. Examples: 'rootthebox.py --setup=prod' or 'rootthebox.py --start'"
]
help_response.append("\t\t--recovery\tstart the recovery console")
help_response.append(
"\t\t--reset\tkeeps teams / players and resets the game to start"
)
help_response.append(
"\t\t--reset-delete\tdeletes teams / players and resets the game to start"
)
help_response.append("\t\t--restart\trestart the server")
help_response.append("\t\t--save\t\tsave the current configuration to file")
help_response.append("\t\t--setup\t\tsetup a database (prod|devel|docker)")
help_response.append("\t\t--start\t\tstart the server")
help_response.append("\t\t--tests\t\trun the unit tests")
help_response.append("\t\t--update\tpull the latest code via github")
help_response.append("\t\t--version\tdisplay version information and exit")
help_response.append("\t\t--xml\t\timport xml file(s)")
help_response.append(
"\t\t--config\tconfiguration file location (default: files/rootthebox.cfg)"
)
return "\n".join(help_response)
########################################################################
# Application Settings
########################################################################
# HTTP Server Settings
define(
"origin",
default="ws://localhost:8888",
group="server",
help="validate websocket connections against this origin",
)
define(
"listen_port",
default=8888,
group="server",
help="run instances starting the given port",
type=int,
)
define(
"listen_interface",
default="0.0.0.0",
group="server",
help="attach to which interface. 0.0.0.0 implies all available.",
)
define(
"session_age",
default=int(48 * 60),
group="server",
help="max session age (minutes) of inactivity",
type=int,
)
define(
"x_headers",
default=False,
group="server",
help="honor the `X-FORWARDED-FOR` and `X-REAL-IP` http headers",
type=bool,
)
define(
"ssl", default=False, group="server", help="enable the use of ssl/tls", type=bool
)
define(
"certfile",
default="",
group="server",
help="the certificate file path (for ssl/tls)",
)
define("keyfile", default="", group="server", help="the key file path (for ssl/tls)")
define(
"admin_ips",
multiple=True,
default=["127.0.0.1", "::1"],
group="server",
help="whitelist of ip addresses that can access the admin ui (use empty list to allow all ip addresses)",
)
define(
"autoreload_source",
default=True,
group="server",
help="automatically restart the server if a change is detected in source (debuggers will not follow)",
)
define(
"webhook_url",
default=None,
group="server",
help="url to receive webhook callbacks when certain game actions occur, such as flag capture",
)
define(
"api_keys",
multiple=True,
default=[],
group="server",
help="keys to use for api access",
)
# Mail Server
define("mail_host", default="", group="mail", help="SMTP server")
define("mail_port", default=587, group="mail", help="SMTP server port", type=int)
define(
"mail_username", default="", group="mail", help="User account for the smtp server"
)
define("mail_password", default="", group="mail", help="Password for the smtp server")
define(
"mail_sender",
default="[email protected]",
group="mail",
help="Email for the sender (FROM)",
)
# Application Settings
define(
"debug",
default=False,
group="application",
help="start the application in debugging mode",
type=bool,
)
define(
"autostart_game",
default=False,
group="application",
help="start the game automatically",
type=bool,
)
define(
"suspend_registration",
default=False,
group="application",
help="suspend the registration automatically",
type=bool,
)
define(
"auth",
default="db",
group="application",
help="The authentication mechanism, db (default) or Azure AD",
)
define(
"avatar_dir",
default="./files/avatars",
group="application",
help="the directory to store avatar files",
)
define(
"share_dir",
default="./files/shares",
group="application",
help="the directory to store shared files",
)
define(
"flag_attachment_dir",
default="./files/flag_attachments",
group="application",
help="the directory to store flag attachment files",
)
define(
"source_code_market_dir",
default="./files/source_code_market",
group="application",
help="the directory to store source code market files",
)
define(
"game_materials_dir",
default="./files/game_materials",
group="application",
help="the directory to store applications, docs, and other materials for the game",
)
define(
"game_materials_on_stop",
default=True,
group="application",
help="show game materials when game stopped",
type=bool,
)
define(
"use_box_materials_dir",
default=True,
group="application",
help="show files belonging to a box in the box page",
type=bool,
)
define(
"force_download_game_materials",
default=True,
group="application",
help="force the browser to download game materials (instead of just viewing them)",
type=bool,
)
define(
"force_locale",
default="",
group="application",
help="force the application to use this locale instead of the browser's locale.",
)
define(
"tool_links",
multiple=True,
type=dict,
default=[{"name": "CyberChef", "url": "/cyberchef/", "target": "_blank"}],
group="application",
help="links to add to the tool menu",
)
define(
"show_organizor_help",
default=False,
group="application",
help="show an info text on the user's home page about organizor help",
type=bool,
)
define(
"disable_hijack_protection",
default=False,
group="application",
help="Disable the hijack protection when the session ip doesn't equal the request ip",
type=bool,
)
# Azure AD
define("client_id", default="", group="azuread")
define("tenant_id", default="common", group="azuread")
define("client_secret", default="", group="azuread")
define("redirect_url", default="http://localhost:8888/oidc", group="azuread")
# ReCAPTCHA
define(
"use_recaptcha",
default=False,
help="enable the use of recaptcha for bank passwords",
group="recaptcha",
type=bool,
)
define(
"recaptcha_site_key",
default="",
group="recaptcha",
help="recaptcha site client api key",
)
define(
"recaptcha_secret_key",
default="",
group="recaptcha",
help="recaptcha secret server key",
)
# Database settings
define(
"sql_dialect",
default="mysql",
group="database",
help="define the type of database (mysql|postgres|sqlite)",
)
define(
"sql_database", default="rootthebox", group="database", help="the sql database name"
)
define(
"sql_host", default="127.0.0.1", group="database", help="database sever hostname"
)
define("sql_port", default=3306, group="database", help="database tcp port", type=int)
define("sql_user", default="rtb", group="database", help="database username")
define(
"sql_sslca", default="", group="database", help="SSL CA Cert for database server."
)
define(
"sql_password",
default="rtb",
group="database",
help="database password, if applicable",
)
define("log_sql", default=False, group="database", help="Log SQL queries for debugging")
# Memcached settings
define(
"memcached",
default="127.0.0.1:11211",
group="cache",
help="memcached servers comma separated - hostname:port",
)
define(
"memcached_user", default="", group="cache", help="memcached SASL server username"
)
define(
"memcached_password",
default="",
group="cache",
help="memcached SASL server password",
)
# Game Settings
try:
# python2
game_type = basestring
except NameError:
# python 3
game_type = str
define(
"game_name",
default="Root the Box",
group="game",
help="the name of the current game",
type=game_type,
)
define(
"game_version",
default="1.0",
group="game",
help="optional version for this game",
type=game_type,
)
define(
"ctf_logo",
default="/static/images/rtb2.png",
group="game",
help="the image displayed on the welcome page",
type=game_type,
)
define(
"ctf_tagline",
default="A Game of Hackers",
group="game",
help="the tagline displayed on the welcome page",
type=game_type,
)
define(
"org_footer",
default="",
group="game",
help="Organization footer - righthand text / html",
type=game_type,
)
define(
"privacy_policy_link",
default="",
group="game",
help="Link to the privacy policy",
type=game_type,
)
define(
"story_character",
default="/static/images/morris.jpg",
group="game",
help="the character image displayed on the communication dialog",
type=game_type,
)
define(
"story_signature",
multiple=True,
default=[" ", "Good hunting,\n -Morris"],
group="game",
help="the ending at the end of the communication dialog",
type=game_type,
)
define(
"story_firstlogin",
multiple=True,
default=[
"Hello [[b;;]$user],\n",
"I am your new employer. You may call me [[b;;]Morris].",
" ",
"I hope you're well rested. We have a lot of work to do.",
"I have several assignments which require your... special skill set.",
" ",
'You may view your current assignments by selecting \n"Missions" from the Game menu.',
],
group="game",
help="the dialog displayed at first login",
type=game_type,
)
define(
"story_banking",
multiple=True,
default=[
" ",
"I've taken the liberty of depositing some seed money in your team's bank account.",
"See that it's put to good use.",
],
group="game",
help="additional dialog displayed at first login if banking is enabled",
type=game_type,
)
define(
"story_bots",
multiple=True,
default=[" ", "I will also be glad to rent your botnet for $$reward per bot."],
group="game",
help="additional dialog displayed at first login if bots are enabled",
type=game_type,
)
define(
"restrict_registration",
default=False,
group="game",
help="require registration tokens",
type=bool,
)
define(
"require_email",
default=True,
group="game",
help="require email for registration",
type=bool,
)
define(
"validate_email",
default=False,
group="game",
help="validate email for registration",
type=bool,
)
define(
"public_teams",
default=True,
group="game",
help="allow anyone to create a new team",
type=bool,
)
define(
"show_mvp",
default=True,
group="game",
help="display the mvp list on scoreboard",
type=bool,
)
define("mvp_max", default=10, group="game", help="display the top N players", type=int)
define(
"scoreboard_right_image",
default="",
group="game",
help="display image to right of scoreboard (can fade with show_mvp)",
type=game_type,
)
define(
"show_captured_flag",
default=False,
group="game",
help="allow player to see the flag token after capture",
type=bool,
)
define(
"hints_taken",
default=False,
group="game",
help="display number of hints taken on scoreboard",
type=bool,
)
define(
"global_notification",
default=False,
group="game",
help="notify all players of flag captures and level unlocks",
type=bool,
)
define(
"teams",
default=True,
group="game",
help="turn off teams - individual playstyle",
type=bool,
)
define(
"player_use_handle",
default=True,
group="game",
help="when in individual playstyle, use handle or playername",
type=bool,
)
define(
"max_team_size",
default=4,
group="game",
help="max number of players on any one team",
type=int,
)
define(
"team_sharing",
default=True,
group="game",
help="team sharing - pastebin and file share",
type=bool,
)
define(
"min_user_password_length",
default=7,
group="game",
help="min user password length",
type=int,
)
define(
"banking",
default=False,
group="game",
help="turn off bank scoring - point scoreboard",
type=bool,
)
define(
"max_password_length",
default=7,
group="game",
help="max bank password length",
type=int,
)
define(
"use_bots", default=False, group="game", help="enable the use of botnets", type=bool
)
define(
"botnet_db", default="files/botnet.db", group="game", help="botnet database path"
)
define(
"bot_reward",
default=50,
group="game",
help="the reward per-interval for a single bot",
type=int,
)
define(
"use_black_market",
default=False,
group="game",
help="enable the use of the black market",
type=bool,
)
define(
"allowed_market_items",
default=["Source Code Market", "Password Security", "Federal Reserve", "SWAT"],
group="game",
help="if black market is enabled only allow these market items",
multiple=True,
)
define(
"show_source_code_description",
default=False,
group="game",
help="show description of a source code file to users",
type=bool,
)
define(
"password_upgrade_cost",
default=1000,
group="game",
help="price to upgrade a password hash algorithm",
type=int,
)
define(
"bribe_cost",
default=2500,
group="game",
help="the base bribe cost to swat another player",
type=int,
)
define(
"starting_team_money",
default=500,
group="game",
help="the starting money for a new team when using banking",
type=int,
)
define(
"whitelist_box_ips",
default=False,
group="game",
help="whitelist box ip addresses (for botnets)",
type=bool,
)
define(
"story_mode",
default=False,
group="game",
help="Morris story with secure communique dialog screen after capture success",
type=bool,
)
define(
"scoreboard_visibility",
default="public",
group="game",
help="Visibility of the Scoreboard - public, players, admins",
type=game_type,
)
define(
"scoreboard_lazy_update",
default=False,
group="game",
help="Skips aggressive gamestate update on scoreboard refresh",
type=bool,
)
define(
"dynamic_flag_value",
default=False,
group="game",
help="decrease reward for flags based on captures",
type=bool,
)
define(
"dynamic_flag_type",
default="decay_future",
group="game",
help="determines the type of dynamic scoring used",
)
define(
"max_flag_attempts",
default=100,
group="game",
help="limits the number of attempts to capture a flag",
type=int,
)
define(
"flag_value_decrease",
default=10,
group="game",
help="decrease flag reward by this percent per capture until minimum",
type=int,
)
define(
"flag_value_minimum",
default=1,
group="game",
help="minimum value for flag decay",
type=int,
)
define(
"penalize_flag_value",
default=False,
group="game",
help="penalize score for incorrect capture attempts",
type=bool,
)
define(
"flag_penalty_cost",
default=20,
group="game",
help="penalty as a percentage of flag value",
type=int,
)
define(
"flag_start_penalty",
default=2,