-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathchallengeapi.py
More file actions
496 lines (433 loc) · 17.4 KB
/
Copy pathchallengeapi.py
File metadata and controls
496 lines (433 loc) · 17.4 KB
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
from typing import List # noqa: I001
from flask import abort, render_template, request, url_for
from flask_restx import Namespace, Resource
from sqlalchemy.sql import and_
from CTFd.api.v1.helpers.request import validate_args
from CTFd.api.v1.helpers.schemas import sqlalchemy_to_pydantic
from CTFd.api.v1.schemas import APIDetailedSuccessResponse, APIListSuccessResponse
from CTFd.cache import clear_challenges, clear_standings
from CTFd.constants import RawEnum
from CTFd.exceptions.challenges import (
ChallengeCreateException,
ChallengeUpdateException,
)
from CTFd.models import ChallengeFiles as ChallengeFilesModel
from CTFd.models import Challenges
from CTFd.models import ChallengeTopics as ChallengeTopicsModel
from CTFd.models import Fails, Flags, Hints, HintUnlocks, Solves, Submissions, Tags, db
from CTFd.plugins.challenges import CHALLENGE_CLASSES, get_chal_class
from CTFd.schemas.challenges import ChallengeSchema
from CTFd.schemas.tags import TagSchema
from CTFd.utils import config
from CTFd.utils import user as current_user
from CTFd.utils.challenges import (
get_solve_counts_for_challenges,
get_solve_ids_for_user_id,
)
from CTFd.utils.config.visibility import (
accounts_visible,
challenges_visible,
scores_visible,
)
from CTFd.utils.dates import ctf_ended
from CTFd.utils.decorators import (
admins_only,
during_ctf_time_only,
require_verified_emails,
)
from CTFd.utils.decorators.visibility import (
check_challenge_visibility,
)
from CTFd.utils.security.signing import serialize
from CTFd.utils.user import (
authed,
get_current_team,
get_current_team_attrs,
get_current_user,
get_current_user_attrs,
is_admin,
)
from .utils import get_all_challenges
challenges_namespace = Namespace(
"challenges", description="Endpoint to retrieve Challenges"
)
ChallengeModel = sqlalchemy_to_pydantic(
Challenges, include={"solves": int, "solved_by_me": bool}
)
TransientChallengeModel = sqlalchemy_to_pydantic(Challenges, exclude=["id"])
class ChallengeDetailedSuccessResponse(APIDetailedSuccessResponse):
data: ChallengeModel
class ChallengeListSuccessResponse(APIListSuccessResponse):
data: List[ChallengeModel]
challenges_namespace.schema_model(
"ChallengeDetailedSuccessResponse", ChallengeDetailedSuccessResponse.apidoc()
)
challenges_namespace.schema_model(
"ChallengeListSuccessResponse", ChallengeListSuccessResponse.apidoc()
)
@challenges_namespace.route("")
class ChallengeList(Resource):
@check_challenge_visibility
@during_ctf_time_only
@require_verified_emails
@challenges_namespace.doc(
description="Endpoint to get Challenge objects in bulk",
responses={
200: ("Success", "ChallengeListSuccessResponse"),
400: (
"An error occured processing the provided or stored data",
"APISimpleErrorResponse",
),
},
)
@validate_args(
{
"name": (str, None),
"max_attempts": (int, None),
"value": (int, None),
"category": (str, None),
"type": (str, None),
"state": (str, None),
"q": (str, None),
"field": (
RawEnum(
"ChallengeFields",
{
"name": "name",
"description": "description",
"category": "category",
"type": "type",
"state": "state",
},
),
None,
),
},
location="query",
)
def get(self, query_args):
# Require a team if in teams mode
# TODO: Convert this into a re-useable decorator
# TODO: The require_team decorator doesnt work because of no admin passthru
if get_current_user_attrs():
if is_admin():
pass
else:
if config.is_teams_mode() and get_current_team_attrs() is None:
abort(403)
# Build filtering queries
q = query_args.pop("q", None)
field = str(query_args.pop("field", None))
# Admins get a shortcut to see all challenges despite pre-requisites
admin_view = is_admin() and request.args.get("view") == "admin"
# Get a cached mapping of challenge_id to solve_count
solve_counts = get_solve_counts_for_challenges(admin=admin_view)
# Get list of solve_ids for current user
if authed():
user = get_current_user()
user_solves = get_solve_ids_for_user_id(user_id=user.id)
user_subscription = user.subscription_level
else:
user = None
user_solves = set()
user_subscription = "freemium"
# Aggregate the query results into the hashes defined at the top of
# this block for later use
if scores_visible() and accounts_visible():
solve_count_dfl = 0
else:
# Empty out the solves_count if we're hiding scores/accounts
solve_counts = {}
# This is necessary to match the challenge detail API which returns
# `None` for the solve count if visiblity checks fail
solve_count_dfl = None
chal_q = get_all_challenges(admin=admin_view, field=field, q=q, sub=user_subscription, **query_args)
# Iterate through the list of challenges, adding to the object which
# will be JSONified back to the client
response = []
tag_schema = TagSchema(view="user", many=True)
# Gather all challenge IDs so that we can determine invalid challenge prereqs
all_challenge_ids = {
c.id for c in Challenges.query.with_entities(Challenges.id).all()
}
for challenge in chal_q:
if challenge.requirements:
requirements = challenge.requirements.get("prerequisites", [])
anonymize = challenge.requirements.get("anonymize")
prereqs = set(requirements).intersection(all_challenge_ids)
if user_solves >= prereqs or admin_view:
pass
else:
if anonymize:
response.append(
{
"id": challenge.id,
"type": "hidden",
"name": "???",
"value": 0,
"solves": None,
"solved_by_me": False,
"category": "???",
"tags": [],
"template": "",
"script": "",
}
)
# Fallthrough to continue
continue
try:
challenge_type = get_chal_class(challenge.type)
except KeyError:
# Challenge type does not exist. Fall through to next challenge.
continue
# Challenge passes all checks, add it to response
response.append(
{
"id": challenge.id,
"type": challenge_type.name,
"name": challenge.name,
"value": challenge.value,
"solves": solve_counts.get(challenge.id, solve_count_dfl),
"solved_by_me": challenge.id in user_solves,
"category": challenge.category,
"tags": tag_schema.dump(challenge.tags).data,
"template": challenge_type.templates["view"],
"script": challenge_type.scripts["view"],
}
)
db.session.close()
return {"success": True, "data": response}
@admins_only
@challenges_namespace.doc(
description="Endpoint to create a Challenge object",
responses={
200: ("Success", "ChallengeDetailedSuccessResponse"),
400: (
"An error occured processing the provided or stored data",
"APISimpleErrorResponse",
),
},
)
def post(self):
data = request.form or request.get_json()
# Load data through schema for validation but not for insertion
schema = ChallengeSchema()
response = schema.load(data)
if response.errors:
return {"success": False, "errors": response.errors}, 400
challenge_type = data.get("type", "standard")
challenge_class = get_chal_class(challenge_type)
try:
challenge = challenge_class.create(request)
except ChallengeCreateException as e:
return {"success": False, "errors": {"": [str(e)]}}, 500
response = challenge_class.read(challenge)
clear_challenges()
return {"success": True, "data": response}
@challenges_namespace.route("/<challenge_id>")
class Challenge(Resource):
@check_challenge_visibility
@during_ctf_time_only
@require_verified_emails
@challenges_namespace.doc(
description="Endpoint to get a specific Challenge object",
responses={
200: ("Success", "ChallengeDetailedSuccessResponse"),
400: (
"An error occured processing the provided or stored data",
"APISimpleErrorResponse",
),
},
)
def get(self, challenge_id):
user = get_current_user()
if is_admin():
chal = Challenges.query.filter(Challenges.id == challenge_id).first_or_404()
else:
# Get the challenge first
chal = Challenges.query.filter(
Challenges.id == challenge_id,
and_(Challenges.state != "hidden", Challenges.state != "locked"),
).first_or_404()
# Check subscription requirements using the new method
required_subscription = chal.get_subscription_required()
user_subscription = user.subscription_level if user else "freemium"
# Check if user has access based on subscription level
if required_subscription == "premium" and user_subscription == "freemium":
abort(404) # Challenge not accessible to freemium users
elif required_subscription == "all-in" and user_subscription in ["freemium", "premium"]:
abort(404) # Challenge not accessible to non-all-in users
elif required_subscription == "beta" and user_subscription != "beta":
abort(404)
try:
chal_class = get_chal_class(chal.type)
except KeyError:
abort(
500,
f"The underlying challenge type ({chal.type}) is not installed. This challenge can not be loaded.",
)
if chal.requirements:
requirements = chal.requirements.get("prerequisites", [])
anonymize = chal.requirements.get("anonymize")
# Gather all challenge IDs so that we can determine invalid challenge prereqs
all_challenge_ids = {
c.id for c in Challenges.query.with_entities(Challenges.id).all()
}
if challenges_visible():
user = get_current_user()
if user:
solve_ids = (
Solves.query.with_entities(Solves.challenge_id)
.filter_by(account_id=user.account_id)
.order_by(Solves.challenge_id.asc())
.all()
)
else:
# We need to handle the case where a user is viewing challenges anonymously
solve_ids = []
solve_ids = {value for value, in solve_ids}
prereqs = set(requirements).intersection(all_challenge_ids)
if solve_ids >= prereqs or is_admin():
pass
else:
if anonymize:
return {
"success": True,
"data": {
"id": chal.id,
"type": "hidden",
"name": "???",
"value": 0,
"solves": None,
"solved_by_me": False,
"category": "???",
"tags": [],
"template": "",
"script": "",
},
}
abort(403)
else:
abort(403)
tags = [
tag["value"] for tag in TagSchema("user", many=True).dump(chal.tags).data
]
unlocked_hints = set()
hints = []
if authed():
user = get_current_user()
team = get_current_team()
# TODO: Convert this into a re-useable decorator
if is_admin():
pass
else:
if config.is_teams_mode() and team is None:
abort(403)
unlocked_hints = {
u.target
for u in HintUnlocks.query.filter_by(
type="hints", account_id=user.account_id
)
}
files = []
for f in chal.files:
token = {
"user_id": user.id,
"team_id": team.id if team else None,
"file_id": f.id,
}
files.append(
url_for("views.files", path=f.location, token=serialize(token))
)
else:
files = [url_for("views.files", path=f.location) for f in chal.files]
for hint in Hints.query.filter_by(challenge_id=chal.id).all():
if hint.id in unlocked_hints or ctf_ended():
hints.append(
{"id": hint.id, "cost": hint.cost, "content": hint.content}
)
else:
hints.append({"id": hint.id, "cost": hint.cost})
response = chal_class.read(challenge=chal)
# Get list of solve_ids for current user
if authed():
user = get_current_user()
user_solves = get_solve_ids_for_user_id(user_id=user.id)
else:
user_solves = []
solves_count = get_solve_counts_for_challenges(challenge_id=chal.id)
if solves_count:
challenge_id = chal.id
solve_count = solves_count.get(chal.id)
solved_by_user = challenge_id in user_solves
else:
solve_count, solved_by_user = 0, False
# Hide solve counts if we are hiding solves/accounts
if scores_visible() is False or accounts_visible() is False:
solve_count = None
if authed():
# Get current attempts for the user
attempts = Submissions.query.filter_by(
account_id=user.account_id, challenge_id=challenge_id
).count()
else:
attempts = 0
response["solves"] = solve_count
response["solved_by_me"] = solved_by_user
response["attempts"] = attempts
response["files"] = files
response["tags"] = tags
response["hints"] = hints
response["view"] = render_template(
chal_class.templates["view"].lstrip("/"),
solves=solve_count,
solved_by_me=solved_by_user,
files=files,
tags=tags,
hints=[Hints(**h) for h in hints],
max_attempts=chal.max_attempts,
attempts=attempts,
challenge=chal,
)
db.session.close()
return {"success": True, "data": response}
@admins_only
@challenges_namespace.doc(
description="Endpoint to edit a specific Challenge object",
responses={
200: ("Success", "ChallengeDetailedSuccessResponse"),
400: (
"An error occured processing the provided or stored data",
"APISimpleErrorResponse",
),
},
)
def patch(self, challenge_id):
data = request.get_json()
# Load data through schema for validation but not for insertion
schema = ChallengeSchema()
response = schema.load(data)
if response.errors:
return {"success": False, "errors": response.errors}, 400
challenge = Challenges.query.filter_by(id=challenge_id).first_or_404()
challenge_class = get_chal_class(challenge.type)
try:
challenge = challenge_class.update(challenge, request)
except ChallengeUpdateException as e:
return {"success": False, "errors": {"": [str(e)]}}, 500
response = challenge_class.read(challenge)
clear_standings()
clear_challenges()
return {"success": True, "data": response}
@admins_only
@challenges_namespace.doc(
description="Endpoint to delete a specific Challenge object",
responses={200: ("Success", "APISimpleSuccessResponse")},
)
def delete(self, challenge_id):
challenge = Challenges.query.filter_by(id=challenge_id).first_or_404()
chal_class = get_chal_class(challenge.type)
chal_class.delete(challenge)
clear_standings()
clear_challenges()
return {"success": True}