forked from andyjsmith/CTFd-Docker-Plugin
-
Notifications
You must be signed in to change notification settings - Fork 8
/
__init__.py
755 lines (623 loc) · 28.2 KB
/
__init__.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
from __future__ import division
import time
import json
import datetime
import math
from flask import Blueprint, request, Flask, render_template, url_for, redirect, flash
from CTFd.models import db, Solves
from CTFd.plugins import register_plugin_assets_directory
from CTFd.plugins.challenges import CHALLENGE_CLASSES, BaseChallenge
from CTFd.utils.decorators import authed_only, admins_only, during_ctf_time_only, ratelimit, require_verified_emails
from CTFd.utils.user import get_current_user
from CTFd.utils.modes import get_model
from CTFd.utils import get_config
from .models import ContainerChallengeModel, ContainerInfoModel, ContainerSettingsModel
from .container_manager import ContainerManager, ContainerException
USERS_MODE = "users"
TEAMS_MODE = "teams"
class ContainerChallenge(BaseChallenge):
id = "container" # Unique identifier used to register challenges
name = "container" # Name of a challenge type
templates = { # Handlebars templates used for each aspect of challenge editing & viewing
"create": "/plugins/containers/assets/create.html",
"update": "/plugins/containers/assets/update.html",
"view": "/plugins/containers/assets/view.html",
}
scripts = { # Scripts that are loaded when a template is loaded
"create": "/plugins/containers/assets/create.js",
"update": "/plugins/containers/assets/update.js",
"view": "/plugins/containers/assets/view.js",
}
# Route at which files are accessible. This must be registered using register_plugin_assets_directory()
route = "/plugins/containers/assets/"
challenge_model = ContainerChallengeModel
@classmethod
def read(cls, challenge):
"""
This method is in used to access the data of a challenge in a format processable by the front end.
:param challenge:
:return: Challenge object, data dictionary to be returned to the user
"""
data = {
"id": challenge.id,
"name": challenge.name,
"value": challenge.value,
"image": challenge.image,
"port": challenge.port,
"command": challenge.command,
"ctype": challenge.ctype,
"initial": challenge.initial,
"decay": challenge.decay,
"minimum": challenge.minimum,
"description": challenge.description,
"connection_info": challenge.connection_info,
"category": challenge.category,
"state": challenge.state,
"max_attempts": challenge.max_attempts,
"type": challenge.type,
"type_data": {
"id": cls.id,
"name": cls.name,
"templates": cls.templates,
"scripts": cls.scripts,
},
}
return data
@classmethod
def calculate_value(cls, challenge):
Model = get_model()
solve_count = (
Solves.query.join(Model, Solves.account_id == Model.id)
.filter(
Solves.challenge_id == challenge.id,
Model.hidden == False,
Model.banned == False,
)
.count()
)
# If the solve count is 0 we shouldn't manipulate the solve count to
# let the math update back to normal
if solve_count != 0:
# We subtract -1 to allow the first solver to get max point value
solve_count -= 1
# It is important that this calculation takes into account floats.
# Hence this file uses from __future__ import division
value = (
((challenge.minimum - challenge.initial) / (challenge.decay ** 2))
* (solve_count ** 2)
) + challenge.initial
value = math.ceil(value)
if value < challenge.minimum:
value = challenge.minimum
challenge.value = value
db.session.commit()
return challenge
@classmethod
def update(cls, challenge, request):
"""
This method is used to update the information associated with a challenge. This should be kept strictly to the
Challenges table and any child tables.
:param challenge:
:param request:
:return:
"""
data = request.form or request.get_json()
for attr, value in data.items():
# We need to set these to floats so that the next operations don't operate on strings
if attr in ("initial", "minimum", "decay"):
value = float(value)
setattr(challenge, attr, value)
return ContainerChallenge.calculate_value(challenge)
@classmethod
def solve(cls, user, team, challenge, request):
super().solve(user, team, challenge, request)
ContainerChallenge.calculate_value(challenge)
def settings_to_dict(settings):
return {
setting.key: setting.value for setting in settings
}
def is_team_mode():
mode = get_config("user_mode")
if mode == TEAMS_MODE:
return True
elif mode == USERS_MODE:
return False
else:
return None
def load(app: Flask):
app.db.create_all()
CHALLENGE_CLASSES["container"] = ContainerChallenge
register_plugin_assets_directory(
app, base_path="/plugins/containers/assets/"
)
container_settings = settings_to_dict(ContainerSettingsModel.query.all())
container_manager = ContainerManager(container_settings, app)
containers_bp = Blueprint(
'containers', __name__, template_folder='templates', static_folder='assets', url_prefix='/containers')
@containers_bp.app_template_filter("format_time")
def format_time_filter(unix_seconds):
dt = datetime.datetime.fromtimestamp(unix_seconds, tz=datetime.datetime.now(
datetime.timezone.utc).astimezone().tzinfo)
return dt.strftime("%H:%M:%S %d/%m/%Y")
def kill_container(container_id):
container: ContainerInfoModel = ContainerInfoModel.query.filter_by(
container_id=container_id).first()
try:
container_manager.kill_container(container_id)
except ContainerException:
return {"error": "Docker is not initialized. Please check your settings."}
db.session.delete(container)
db.session.commit()
return {"success": "Container killed"}
def renew_container(chal_id, xid, is_team):
# Get the requested challenge
challenge = ContainerChallenge.challenge_model.query.filter_by(
id=chal_id).first()
# Make sure the challenge exists and is a container challenge
if challenge is None:
return {"error": "Challenge not found"}, 400
if is_team is True:
running_containers = ContainerInfoModel.query.filter_by(
challenge_id=challenge.id, team_id=xid)
else:
running_containers = ContainerInfoModel.query.filter_by(
challenge_id=challenge.id, user_id=xid)
running_container = running_containers.first()
if running_container is None:
return {"error": "Container not found, try resetting the container."}
try:
running_container.expires = int(
time.time() + container_manager.expiration_seconds)
db.session.commit()
except ContainerException:
return {"error": "Database error occurred, please try again."}
return {"success": "Container renewed", "expires": running_container.expires, "hostname": container_manager.settings.get("docker_hostname", ""), "port": running_container.port, "connect": challenge.ctype}
def create_container(chal_id, xid, is_team):
# Get the requested challenge
challenge = ContainerChallenge.challenge_model.query.filter_by(
id=chal_id).first()
# Make sure the challenge exists and is a container challenge
if challenge is None:
return {"error": "Challenge not found"}, 400
# Check for any existing containers for the team
if is_team is True:
running_containers = ContainerInfoModel.query.filter_by(
challenge_id=challenge.id, team_id=xid)
else:
running_containers = ContainerInfoModel.query.filter_by(
challenge_id=challenge.id, user_id=xid)
running_container = running_containers.first()
# If a container is already running for the team, return it
if running_container:
# Check if Docker says the container is still running before returning it
try:
if container_manager.is_container_running(
running_container.container_id):
return json.dumps({
"status": "already_running",
"hostname": container_manager.settings.get("docker_hostname", ""),
"port": running_container.port,
"connect": challenge.ctype,
"expires": running_container.expires
})
else:
# Container is not running, it must have died or been killed,
# remove it from the database and create a new one
running_containers.delete()
db.session.commit()
except ContainerException as err:
return {"error": str(err)}, 500
# TODO: Should insert before creating container, then update. That would avoid a TOCTOU issue
# Run a new Docker container
try:
created_container = container_manager.create_container(
challenge.image, challenge.port, challenge.command, challenge.volumes)
except ContainerException as err:
return {"error": str(err)}
# Fetch the random port Docker assigned
port = container_manager.get_container_port(created_container.id)
# Port may be blank if the container failed to start
if port is None:
return json.dumps({
"status": "error",
"error": "Could not get port"
})
expires = int(time.time() + container_manager.expiration_seconds)
# Insert the new container into the database
if is_team is True:
new_container = ContainerInfoModel(
container_id=created_container.id,
challenge_id=challenge.id,
team_id=xid,
port=port,
timestamp=int(time.time()),
expires=expires
)
else:
new_container = ContainerInfoModel(
container_id=created_container.id,
challenge_id=challenge.id,
user_id=xid,
port=port,
timestamp=int(time.time()),
expires=expires
)
db.session.add(new_container)
db.session.commit()
return json.dumps({
"status": "created",
"hostname": container_manager.settings.get("docker_hostname", ""),
"port": port,
"connect": challenge.ctype,
"expires": expires
})
def view_container_info(chal_id, xid, is_team):
# Get the requested challenge
challenge = ContainerChallenge.challenge_model.query.filter_by(
id=chal_id).first()
# Make sure the challenge exists and is a container challenge
if challenge is None:
return {"error": "Challenge not found"}, 400
# Check for any existing containers for the team
if is_team is True:
running_containers = ContainerInfoModel.query.filter_by(
challenge_id=challenge.id, team_id=xid)
else:
running_containers = ContainerInfoModel.query.filter_by(
challenge_id=challenge.id, user_id=xid)
running_container = running_containers.first()
# If a container is already running for the team, return it
if running_container:
# Check if Docker says the container is still running before returning it
try:
if container_manager.is_container_running(
running_container.container_id):
return json.dumps({
"status": "already_running",
"hostname": container_manager.settings.get("docker_hostname", ""),
"port": running_container.port,
"connect": challenge.ctype,
"expires": running_container.expires
})
else:
# Container is not running, it must have died or been killed,
# remove it from the database and create a new one
running_containers.delete()
db.session.commit()
except ContainerException as err:
return {"error": str(err)}, 500
else:
return {"status": "Challenge not started"}
def connect_type(chal_id):
# Get the requested challenge
challenge = ContainerChallenge.challenge_model.query.filter_by(
id=chal_id).first()
# Make sure the challenge exists and is a container challenge
if challenge is None:
return {"error": "Challenge not found"}, 400
return json.dumps({
"status": "Ok",
"connect": challenge.ctype
})
@containers_bp.route('/api/get_connect_type/<int:challenge_id>', methods=['GET'])
@authed_only
@during_ctf_time_only
@require_verified_emails
@ratelimit(method="GET", limit=15, interval=60)
def get_connect_type(challenge_id):
try:
return connect_type(challenge_id)
except ContainerException as err:
return {"error": str(err)}, 500
@containers_bp.route('/api/view_info', methods=['POST'])
@authed_only
@during_ctf_time_only
@require_verified_emails
@ratelimit(method="POST", limit=15, interval=60)
def route_view_info():
user = get_current_user()
# Validate the request
if request.json is None:
return {"error": "Invalid request"}, 400
if request.json.get("chal_id", None) is None:
return {"error": "No chal_id specified"}, 400
if user is None:
return {"error": "User not found"}, 400
if user.team is None and is_team_mode() is True:
return {"error": "User not a member of a team"}, 400
try:
if is_team_mode() is True:
return view_container_info(request.json.get("chal_id"), user.team.id, True)
elif is_team_mode() is False:
return view_container_info(request.json.get("chal_id"), user.id, False)
except ContainerException as err:
return {"error": str(err)}, 500
@containers_bp.route('/api/request', methods=['POST'])
@authed_only
@during_ctf_time_only
@require_verified_emails
@ratelimit(method="POST", limit=6, interval=60)
def route_request_container():
user = get_current_user()
# Validate the request
if request.json is None:
return {"error": "Invalid request"}, 400
if request.json.get("chal_id", None) is None:
return {"error": "No chal_id specified"}, 400
if user is None:
return {"error": "User not found"}, 400
if user.team is None and is_team_mode() is True:
return {"error": "User not a member of a team"}, 400
try:
if is_team_mode() is True:
return create_container(request.json.get("chal_id"), user.team.id,True)
elif is_team_mode() is False:
return create_container(request.json.get("chal_id"), user.id, False)
except ContainerException as err:
return {"error": str(err)}, 500
@containers_bp.route('/api/renew', methods=['POST'])
@authed_only
@during_ctf_time_only
@require_verified_emails
@ratelimit(method="POST", limit=6, interval=60)
def route_renew_container():
user = get_current_user()
# Validate the request
if request.json is None:
return {"error": "Invalid request"}, 400
if request.json.get("chal_id", None) is None:
return {"error": "No chal_id specified"}, 400
if user is None:
return {"error": "User not found"}, 400
if user.team is None and is_team_mode() is True:
return {"error": "User not a member of a team"}, 400
try:
if is_team_mode() is True:
return renew_container(request.json.get("chal_id"), user.team.id, True)
elif is_team_mode() is False:
return renew_container(request.json.get("chal_id"), user.id, False)
except ContainerException as err:
return {"error": str(err)}, 500
user = get_current_user()
# Validate the request
if request.json is None:
return {"error": "Invalid request"}, 400
if request.json.get("chal_id", None) is None:
return {"error": "No chal_id specified"}, 400
if user is None:
return {"error": "User not found"}, 400
if user.team is None and is_team_mode() is True:
return {"error": "User not a member of a team"}, 400
if is_team_mode() is True:
running_container: ContainerInfoModel = ContainerInfoModel.query.filter_by(
challenge_id=request.json.get("chal_id"), team_id=user.team.id).first()
if running_container:
kill_container(running_container.container_id)
return create_container(request.json.get("chal_id"), user.team.id)
elif is_team_mode() is False:
running_container: ContainerInfoModel = ContainerInfoModel.query.filter_by(
challenge_id=request.json.get("chal_id"), team_id=user.id).first()
if running_container:
kill_container(running_container.container_id)
return create_container(request.json.get("chal_id"), user.id)
@containers_bp.route('/api/stop', methods=['POST'])
@authed_only
@during_ctf_time_only
@require_verified_emails
@ratelimit(method="POST", limit=10, interval=60)
def route_stop_container():
user = get_current_user()
# Validate the request
if request.json is None:
return {"error": "Invalid request"}, 400
if request.json.get("chal_id", None) is None:
return {"error": "No chal_id specified"}, 400
if user is None:
return {"error": "User not found"}, 400
if user.team is None and is_team_mode() is True:
return {"error": "User not a member of a team"}, 400
if is_team_mode() is True:
running_container: ContainerInfoModel = ContainerInfoModel.query.filter_by(
challenge_id=request.json.get("chal_id"), team_id=user.team.id).first()
if running_container:
return kill_container(running_container.container_id)
return {"error": "No container found"}, 400
elif is_team_mode() is False:
running_container: ContainerInfoModel = ContainerInfoModel.query.filter_by(
challenge_id=request.json.get("chal_id"), user_id=user.id).first()
if running_container:
return kill_container(running_container.container_id)
return {"error": "No container found"}, 400
@containers_bp.route('/api/kill', methods=['POST'])
@admins_only
def route_kill_container():
if request.json is None:
return {"error": "Invalid request"}, 400
if request.json.get("container_id", None) is None:
return {"error": "No container_id specified"}, 400
return kill_container(request.json.get("container_id"))
@containers_bp.route('/api/purge', methods=['POST'])
@admins_only
def route_purge_containers():
containers: "list[ContainerInfoModel]" = ContainerInfoModel.query.all()
for container in containers:
try:
kill_container(container.container_id)
except ContainerException:
pass
return {"success": "Purged all containers"}, 200
@containers_bp.route('/api/images', methods=['GET'])
@admins_only
def route_get_images():
try:
images = container_manager.get_images()
except ContainerException as err:
return {"error": str(err)}
return {"images": images}
@containers_bp.route('/api/settings/update', methods=['POST'])
@admins_only
def route_update_settings():
if request.form.get("docker_base_url") is None:
return {"error": "Invalid request"}, 400
if request.form.get("docker_hostname") is None:
return {"error": "Invalid request"}, 400
if request.form.get("container_expiration") is None:
return {"error": "Invalid request"}, 400
if request.form.get("container_maxmemory") is None:
return {"error": "Invalid request"}, 400
if request.form.get("container_maxcpu") is None:
return {"error": "Invalid request"}, 400
docker_base_url = ContainerSettingsModel.query.filter_by(
key="docker_base_url").first()
docker_hostname = ContainerSettingsModel.query.filter_by(
key="docker_hostname").first()
container_expiration = ContainerSettingsModel.query.filter_by(
key="container_expiration").first()
container_maxmemory = ContainerSettingsModel.query.filter_by(
key="container_maxmemory").first()
container_maxcpu = ContainerSettingsModel.query.filter_by(
key="container_maxcpu").first()
# Create or update
if docker_base_url is None:
# Create
docker_base_url = ContainerSettingsModel(
key="docker_base_url", value=request.form.get("docker_base_url"))
db.session.add(docker_base_url)
else:
# Update
docker_base_url.value = request.form.get("docker_base_url")
# Create or update
if docker_hostname is None:
# Create
docker_hostname = ContainerSettingsModel(
key="docker_hostname", value=request.form.get("docker_hostname"))
db.session.add(docker_hostname)
else:
# Update
docker_hostname.value = request.form.get("docker_hostname")
# Create or update
if container_expiration is None:
# Create
container_expiration = ContainerSettingsModel(
key="container_expiration", value=request.form.get("container_expiration"))
db.session.add(container_expiration)
else:
# Update
container_expiration.value = request.form.get(
"container_expiration")
# Create or update
if container_maxmemory is None:
# Create
container_maxmemory = ContainerSettingsModel(
key="container_maxmemory", value=request.form.get("container_maxmemory"))
db.session.add(container_maxmemory)
else:
# Update
container_maxmemory.value = request.form.get("container_maxmemory")
# Create or update
if container_maxcpu is None:
# Create
container_maxcpu = ContainerSettingsModel(
key="container_maxcpu", value=request.form.get("container_maxcpu"))
db.session.add(container_maxcpu)
else:
# Update
container_maxcpu.value = request.form.get("container_maxcpu")
db.session.commit()
container_manager.settings = settings_to_dict(
ContainerSettingsModel.query.all())
if container_manager.settings.get("docker_base_url") is not None:
try:
container_manager.initialize_connection(
container_manager.settings, app)
except ContainerException as err:
flash(str(err), "error")
return redirect(url_for(".route_containers_settings"))
return redirect(url_for(".route_containers_dashboard"))
@containers_bp.route('/dashboard', methods=['GET'])
@admins_only
def route_containers_dashboard():
running_containers = ContainerInfoModel.query.order_by(
ContainerInfoModel.timestamp.desc()).all()
connected = False
try:
connected = container_manager.is_connected()
except ContainerException:
pass
for i, container in enumerate(running_containers):
try:
running_containers[i].is_running = container_manager.is_container_running(
container.container_id)
except ContainerException:
running_containers[i].is_running = False
return render_template('container_dashboard.html', containers=running_containers, connected=connected)
@containers_bp.route('/api/running_containers', methods=['GET'])
@admins_only
def route_get_running_containers():
running_containers = ContainerInfoModel.query.order_by(
ContainerInfoModel.timestamp.desc()).all()
connected = False
try:
connected = container_manager.is_connected()
except ContainerException:
pass
# Create lists to store unique teams and challenges
unique_teams = set()
unique_challenges = set()
for i, container in enumerate(running_containers):
try:
running_containers[i].is_running = container_manager.is_container_running(
container.container_id)
except ContainerException:
running_containers[i].is_running = False
# Add team and challenge to the unique sets
if is_team_mode() is True:
unique_teams.add(f"{container.team.name} [{container.team_id}]")
else:
unique_teams.add(f"{container.user.name} [{container.user_id}]")
unique_challenges.add(f"{container.challenge.name} [{container.challenge_id}]")
# Convert unique sets to lists
unique_teams_list = list(unique_teams)
unique_challenges_list = list(unique_challenges)
# Create a list of dictionaries containing running_containers data
running_containers_data = []
for container in running_containers:
if is_team_mode() is True:
container_data = {
"container_id": container.container_id,
"image": container.challenge.image,
"challenge": f"{container.challenge.name} [{container.challenge_id}]",
"team": f"{container.team.name} [{container.team_id}]",
"port": container.port,
"created": container.timestamp,
"expires": container.expires,
"is_running": container.is_running
}
else:
container_data = {
"container_id": container.container_id,
"image": container.challenge.image,
"challenge": f"{container.challenge.name} [{container.challenge_id}]",
"user": f"{container.user.name} [{container.user_id}]",
"port": container.port,
"created": container.timestamp,
"expires": container.expires,
"is_running": container.is_running
}
running_containers_data.append(container_data)
# Create a JSON response containing running_containers_data, unique teams, and unique challenges
response_data = {
"containers": running_containers_data,
"connected": connected,
"teams": unique_teams_list,
"challenges": unique_challenges_list
}
# Return the JSON response
return json.dumps(response_data)
@containers_bp.route('/settings', methods=['GET'])
@admins_only
def route_containers_settings():
running_containers = ContainerInfoModel.query.order_by(
ContainerInfoModel.timestamp.desc()).all()
return render_template('container_settings.html', settings=container_manager.settings)
app.register_blueprint(containers_bp)