-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathscoreboard.py
More file actions
978 lines (800 loc) · 29.7 KB
/
Copy pathscoreboard.py
File metadata and controls
978 lines (800 loc) · 29.7 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
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
import uuid
from functools import wraps
import hashlib
import markdown2
import time
import toml
from flask import (
Flask,
flash,
make_response,
redirect,
render_template,
request,
url_for,
session,
)
from flask_cors import CORS
from flask_limiter import Limiter
from flask_limiter.util import get_remote_address
from loguru import logger
from rich import print
from terminaltables import AsciiTable, GithubFlavoredMarkdownTable
import database
import database as db
from byoctf_discord import renderChallenge
from settings import SETTINGS
from vis import challs, players, trans
from flask_oauthlib.client import OAuth
from custom_secrets import flask_secret_key, google_client_id, google_client_secret
app = Flask(__name__)
oauth = OAuth(app)
limiter = Limiter(
get_remote_address,
app=app,
default_limits=["50 per second"],
storage_uri="memory://",
)
CORS(app)
app.secret_key = flask_secret_key
google = oauth.remote_app(
'google',
consumer_key=google_client_id,
consumer_secret=google_client_secret,
request_token_params={
'scope': 'email'
},
base_url='https://www.googleapis.com/oauth2/v1/',
request_token_url=None,
access_token_method='POST',
access_token_url='https://accounts.google.com/o/oauth2/token',
authorize_url='https://accounts.google.com/o/oauth2/auth',
)
@app.route('/logout')
def logout():
session.clear()
resp = make_response(redirect(url_for("scoreboard_index")))
resp.set_cookie('api_key', '', expires=0)
return resp
@app.route('/register')
def register():
# maybe add more social logins like mastadon, matrix, facebook or something in the future. now just google.
return render_template('scoreboard/register.html')
@app.post('/quickreg')
@limiter.limit("10/minute")
@db.db_session
def quickreg():
"""Register with nothing but a handle.
Exists because the Google button is not a usable front door for every
audience: Google accounts require 13+, Discord's ToS is 13+, and plenty of
people would rather not tie a con identity to either. Youth events need a
path that asks for nothing.
The new player gets their own team, so they can solve everyone else's
challenges immediately (you can't submit a flag authored by a teammate).
"""
handle = request.form.get("handle", "")
result = db.create_solo_player(handle)
if isinstance(result, str):
flash(result, "error")
return redirect(url_for("register"))
resp = make_response(redirect(url_for("hud")))
resp.set_cookie("api_key", result.api_key)
return resp
@app.route('/google_login')
def google_login():
# uri_mismatch solution; adding authorized uris to the secrets-> https://simplyscheduleappointments.com/guides/400-redirect_uri_mismatch-error/
return google.authorize(callback=url_for('google_authorized', _external=True))
@app.route('/login/authorized')
@db.db_session
def google_authorized():
response = google.authorized_response()
if response is None or response.get('access_token') is None:
return 'Access denied: reason={} error={}'.format(
request.args['error_reason'],
request.args['error_description']
)
session['google_token'] = (response['access_token'], '')
user_info = google.get('userinfo')
user:db.User = db.get_or_create_user_by_email(user_info.data['email'])
print('google user ', user.name, 'exists')
# log the user in
resp = make_response(redirect(url_for('hud')))
resp.set_cookie('api_key', user.api_key)
return resp
@google.tokengetter
def get_google_oauth_token():
return session.get('google_token')
def ctfRunning():
if SETTINGS["ctf_paused"]:
return False
if (SETTINGS["ctf_start"] == -1 or SETTINGS["ctf_start"] <= time.time()) and (
SETTINGS["ctf_end"] == -1 or SETTINGS["ctf_end"] >= time.time()
):
return True
return False
def get_admin_api_key(func):
@wraps(func)
def check(*args, **kwargs):
api_key = request.cookies.get("api_key")
if api_key == None:
api_key = request.cookies.get("admin_api_key")
if api_key == None:
return "api_key not set; visit HUD first...", 403
with db.db_session:
user = db.get_user_by_api_key(api_key)
if user == None or user.is_admin == False:
return "user not found or is not admin", 403
return func(*args, **kwargs)
return check
def get_api_key(func):
@wraps(func)
def check(*args, **kwargs):
api_key = request.cookies.get("api_key")
if api_key == None:
return "api_key not set; visit HUD first...", 403
with db.db_session:
user = db.get_user_by_api_key(api_key)
if user == None:
return "user not found", 403
return func(*args, **kwargs)
return check
@app.post('/send_tip')
@limiter.limit("100/second", override_defaults=False)
@db.db_session
def send_tip():
print('send_tip', request.form)
sender = db.User.get(api_key=request.cookies.get("api_key",None))
if sender == None:
return "api_key invalid", 404
if SETTINGS['disable_custom_tips']:
return "custom tips are disabled for this game", 403
recipient = db.User.get(name=request.form.get('recipient',None))
if recipient == None:
return "recipient name not found", 404
amount = float(request.form.get('amount',-1))
# sender_points = db.getScore(sender)
# if amount < 0 or amount > sender_points :
# return 'invalid tip amount; too much or too little', 403
res = db.send_tip(sender, recipient, tip_amount=amount, msg=request.form.get('msg'))
print('db.send_tip returned', res)
if res[0] == True:
return f"ok, {res}"
return str(res)
@app.get("/tip")
@limiter.limit("100/second", override_defaults=False)
@db.db_session
def tip():
if SETTINGS['disable_custom_tips']:
return "custom tips are disabled for this game", 403
if ctfRunning() == False:
return "ctf not running", 403
user = db.User.get(api_key=request.cookies.get("api_key",'__invalid_api_key__'))
if user == None:
return "user not found", 404
usernames = db.select(u.name for u in db.User if u.name != SETTINGS['_botusername'])[:]
return render_template('scoreboard/tip.html', users=usernames)
@app.route('/me')
@db.db_session
def my_profile():
return "my profile"
@app.route('/join', methods=['GET', 'POST'])
# Was the only write route with no limiter. A wrong team password leaves the
# player on their solo team, so the gate re-admits them -- unlimited guesses
# against single-round sha256 of an 8-char password chosen by a teenager.
@limiter.limit("5 per minute", methods=["POST"])
@db.db_session
@get_api_key
def join_team():
api_key = request.cookies.get("api_key")
if api_key == None:
return "api_key not set; login first", 400
user = db.get_user_by_api_key(api_key)
if user == None:
return "invalid api key; login first.", 403
# Players sitting on the solo team signup gave them still get to form or
# join a real one; only members of an actual team are held here.
if user.team.name != '__unaffiliated__' and not db.is_own_solo_team(user):
# Used to redirect with no explanation, which just looked broken.
flash(f"You're already on team `{user.team.name}`. Talk to an admin to switch.", 'error')
return redirect(url_for("hud"))
if request.method == "POST":
# Do not print the raw form; it carries team_password in cleartext.
if SETTINGS["_debug"]:
print("join_team fields:", sorted(request.form.keys()))
target_team = (request.form.get('target_team') or '').strip()
team_password = request.form.get('team_password') or ''
# '' used to pass this check and reach pony as a Required attribute,
# raising ValueError -> unhandled 500 from a single request.
if not target_team or target_team == '__invalid_team__' or not team_password:
flash("Pick or type a team name, and enter the team password.", 'error')
return redirect(url_for('hud'))
result = db.register_team(target_team, team_password, user.name)
if type(result) == str:
flash(f'team registration failed:{result}', 'error')
return redirect(url_for('hud'))
elif request.method == "GET":
teams = db.joinable_teams()
return render_template('scoreboard/join.html', teams=teams,
current_team=user.team.name,
team_size=SETTINGS["_team_size"])
return 'bad request', 400
# @app.post('/me/set_team')
# @db.db_session
# @get_api_key
# def set_team(a_request=None):
# if a_request != None:
# request = a_request
# api_key = request.cookies.get("api_key")
# if api_key == None:
# return "api_key not set; login first", 400
# user = db.get_user_by_api_key(api_key)
# if user == None:
# return "invalid api key; login first.", 403
# if user.team.name != '__unaffiliated__':
# return "can't change teams on your own. talk to an admin about switching teams", 403
# target_team = request.form.get('target_team', None)
# team_password = request.form.get('team_password', None)
# if target_team == None or team_password == None:
# return "target_team or password missing", 400
# team:db.Team = db.Team.get(name=target_team)
# if team == None:
# team = db.register_team(team, team_password, user.name)
# else:
# if team.password == hashlib.sha256(team_password.strip().encode()).hexdigest():
# user.team = team
# else:
# return "check password", 401
# return redirect(url_for('hud'))
@app.get("/scores")
@limiter.limit("100/second", override_defaults=False)
@db.db_session
def scoreboard():
msg = ""
team_scores = list()
top_players = list()
if SETTINGS["scoreboard"] == "public":
# top 3 team scores by default
team_scores = db.getTopTeams(num=SETTINGS["_scoreboard_size"])
else:
return {"error_msg": "Scoreboard is set to private"}
if SETTINGS["_show_mvp"] == True:
# top players in the game
topPlayers = db.topPlayers(num=SETTINGS["_mvp_size"])
top_players = [(p.name, p.team.name, v) for p, v in topPlayers]
else:
msg += f"MVP is set to False "
if request.args.get("json") != None:
ret = {"top_teams": team_scores, "top_players": top_players}
return ret
else:
# return markdown2.markdown(msg)
show_team_scores = SETTINGS["_team_size"] > 1
return render_template(
"scoreboard/scores.html",
msg=msg,
team_scores=team_scores,
top_players=top_players,
show_team_scores=show_team_scores
)
@app.get("/player/<id>")
@limiter.limit("1/second")
@db.db_session
def get_player(id):
try:
player = db.User.get(id=int(id))
except ValueError as e:
return e, 405
if player == None:
return "player not found", 404
player_challs = db.get_challs_by_player(player)
return render_template(
"scoreboard/player.html", player=player, player_challs=player_challs
)
# @app.get('/api/all_info')
# @limiter.limit('6/min')
# @db.db_session
@app.get("/admin/net/challenges")
@get_admin_api_key
def net_challenges():
return challs()
@app.get("/admin/net/players")
@get_admin_api_key
def net_players():
return players()
@app.get("/admin/net/transactions")
@get_admin_api_key
def net_trans():
user = request.args.get("user")
trans_type = request.args.get("trans_type", "tip")
print(f"getting transactions types {trans_type} for user", user)
return trans(trans_type=trans_type, user=user)
@app.post("/api/sub_as")
@limiter.limit("1/second")
@db.db_session
def create_solve():
"""
see database.py createSolve
The createSolve function attempts to create the transaction that awards points and fails if certain criteria aren't met. Its core purpose was to prevent players from submitting their own flags, their teammates flags, or flags they've already captured. It's also how the decaying points and first blood bonus and BYOC payouts are awarded (if applicable).
points_override is to allow admins to manually specify points when creating the solve.
this is the json payload to create a solve by submitting a flag on their behalf.
{
"target_user": "shyft_xero",
"flag": "FLAG{abc_xyz}",
"points": 1337.0,
"message": "for solving xyz",
"admin_api_key": "your_api_key"
"follow_points_rules": true
}"""
payload = request.get_json()
# print([x for x in payload.items()])
target_user = payload.get(
"target_user", "__invalid username here__"
) # you can't have a user name with spaces on discord, thus you couldn't have registered one.
target_user = db.User.get(name=target_user)
if target_user == None:
return f"Invalid target_user in payload; {payload.get('target_user')}"
flag = payload.get("flag", "__not a flag__")
flag = db.Flag.get(flag=flag)
if flag == None:
return f"Invalid flag in payload; {payload.get('flag')}"
points = payload.get("points")
if points == None:
return f"points missing from payload"
points = float(points)
message = payload.get("message")
if message == None:
return "message missing from payload"
# did they present anything for the api key?
api_key = payload.get("admin_api_key")
if api_key == None:
return f"admin_api_key missing from payload: {api_key}"
# does the api key belong to a user?
admin_user: db.User = db.get_user_by_api_key(api_key)
if admin_user == None:
return f"invalid admin api key: {api_key} ;did it change?"
if admin_user.is_admin == False:
return {"error": "not an admin"}
follow_points_rules = payload.get("follow_points_rules", True)
res = db.createSolve(
user=target_user,
flag=flag,
points_override=points,
msg=message,
follow_points_rules=follow_points_rules,
)
return {"status": res}
@app.post("/api/manual_reg")
@get_admin_api_key
@limiter.limit("100/second")
@db.db_session
def manual_register():
"""
register a user manually
this is the json payload to create a user.
{
"username": "TestUser",
"teamname": "TeamAwesome",
"teampass": "$0m3L33tPa55",
}"""
api_key = request.cookies.get("api_key")
current_user = db.User.get(api_key=api_key)
if not current_user:
msg = "No valid token provided."
logger.debug(msg)
return { "status": False, "msg": msg}
payload = request.get_json()
username = payload.get("username")
teamname = payload.get("teamname")
teampass = payload.get("teampass")
if not username:
return { "status": False, "msg": f"username not set" }
if not teamname:
return { "status": False, "msg": f"teamname not set" }
if not teampass:
return { "status": False, "msg": f"teampass not set" }
hashed_teampass = hashlib.sha256(teampass.encode()).hexdigest()
user = db.User.get(name=username)
if user:
msg = f"Target user=({user}) already exists!"
logger.debug(msg)
return { "status": False, "msg": msg }
# does the team exist?
team = db.Team.get(name=teamname)
if team == None:
team = db.Team(name=teamname, password=hashed_teampass)
pub, priv = db.generate_keys()
team.public_key = pub
team.private_key = priv
# >= not ==: with ==, lowering _team_size below a team's current size
# silently disabled the cap and the team grew unbounded.
if len(team.members) >= SETTINGS["_team_size"]:
msg = f"No room on the team... currently limited to {SETTINGS['_team_size']} members per team."
logger.debug(msg)
return { "status": False, "msg": msg}
if (hashed_teampass != team.password): # if it's a new team, these should match automatically..
msg = f"Password incorrect for team {team.name}"
logger.debug(f"{username} failed registration; Team {teamname} pass {teampass} hashed {hashed_teampass}")
return { "status": False, "msg": msg}
user = db.User(name=username, team=team)
if team.private_key == "":
pub, priv = db.generate_keys()
team.public_key = pub
team.private_key = priv
db.commit()
logger.debug(f"New user=({user.name}) added!")
with db.db_session:
user = db.User.get(name=username)
login_link = f"{SETTINGS['scoreboard_url']}/login/{user.api_key}"
return {"status": True, "msg": login_link}
@app.get("/api/buy_hint/<hint_uuid>")
@db.db_session
@get_api_key
def buy_hint(hint_uuid):
""""""
user = db.get_user_by_api_key(request.cookies.get("api_key",''))
if user == None:
return "user api_key not found", 403
chall = db.Challenge.get(uuid=hint_uuid)
if chall == None:
return 'challenge not found', 404
db.buyHint(user, chall.id)
# resp = make_response(redirect(f'/chall/{hint_uuid}'))
resp = make_response()
resp.headers['HX-Refresh'] = 'true'
return resp
@app.post("/api/grant_points")
@db.db_session
@get_admin_api_key
def grant_points():
"""
{
"target_user": "shyft_xero",
"points": 1337.0,
"message": "for solving xyz",
"admin_api_key": "your_api_key"
}"""
# authed_user = db.get_user_by_api_key("bot")
payload = request.form
target_user = payload.get("target_user")
if target_user == None:
return "Invalid target_user in payload", 405
points = payload.get("points")
if points == None:
return "points missing from payload", 405
points = float(points)
message = payload.get("message")
if message == None:
return "message missing from payload", 405
# did they present one?
api_key = payload.get("admin_api_key")
if api_key == None:
return "admin_api_key missing from payload", 405
# did they present the correct one?
admin_user = db.get_user_by_api_key(api_key)
if admin_user == None:
return "invalid admin api key", 403
if admin_user.is_admin == False:
return "user is not an admin", 403
# seems legit...
res = db.grant_points(
requested_user=target_user, admin_user=admin_user, amount=points, msg=message
)
if res:
return {"status": "sucess", "orig_request": payload}
else:
return {"status": "db error", "orig_request": payload}, 400
@app.get("/api/get_team/<target>")
@limiter.limit("1/second")
@db.db_session
def get_team(target):
if db.is_valid_uuid(target):
target = uuid.UUID(target)
else:
try:
target = int(target)
except ValueError:
return {"error": "invalid id"}
team: db.Team = db.get_team_by_id(target)
if team == None:
return "invalid team id", 403
ret = {
"id": team.id,
"uuid": team.uuid,
"teamname": team.name,
# 'teammembers': [ tm.name for tm in db.getTeammates(team)],
"public_key": team.public_key,
}
return ret
@app.get("/api/all_pub_keys")
@limiter.limit("100/second")
@db.db_session
def all_user_pub_keys():
users = db.select((u.name, u.public_key) for u in db.User)[:]
teams = db.select((t.name, t.uuid, t.public_key) for t in db.Team)[:]
ret = {
"users": [u for u in users],
"teams": [t for t in teams],
}
return ret
@app.get("/api/get_username/<target>")
@limiter.limit("1/second")
@db.db_session
def get_user(target):
if db.is_valid_uuid(target):
target = uuid.UUID(target)
else:
try:
target = int(target)
except ValueError:
return {"error": "invalid id"}
user: db.User = db.get_user_by_id(target)
if user == None:
return "invalid user id", 403
ret = {
"username": user.name,
"teammates": [tm.name for tm in db.getTeammates(user)],
"teamname": user.team.name,
"id": user.id,
"public_key": user.public_key,
}
return ret
@app.get("/login/<api_key>")
@limiter.limit("1/second")
@db.db_session
def login(api_key):
user = db.get_user_by_api_key(api_key)
logger.debug(f"api_key:{api_key}, user:{user}")
if user == None:
return "invalid api key", 403
resp = make_response(redirect(url_for("hud")))
resp.set_cookie("api_key", api_key)
# resp.set_cookie("api_key", api_key, domain=SETTINGS['ctf_base_domain'])
return resp
@app.get("/transactions")
@limiter.limit("100/second")
@db.db_session
def get_public_transactions():
public_transactions = (
db.select(t for t in db.Transaction)
.sort_by(lambda t: db.desc(t.time))
.limit(500)[:]
)
return render_template(
"scoreboard/public_transactions.html", public_transactions=public_transactions
)
@app.get("/hud")
@app.get("/hud/")
@limiter.limit("100/second", override_defaults=False)
@db.db_session
def hud():
api_key = request.cookies.get("api_key")
if api_key == None:
return "api_key cookie not present; try creating an account with discord or google or something; visit <a href='/register'>/register</a>", 400
user = db.get_user_by_api_key(api_key)
if user == None:
return "invalid api key; try creating an account with discord or google or something; visit <a href='/register'>/register</a>", 403
teamname = user.team.name
solved_challs: list[db.Challenge] = sorted(
db.get_completed_challenges(user), key=lambda c: c.title
)
unsolved_challs = sorted(db.get_incomplete_challenges(user), key=lambda c: c.title)
purchased_hints = db.get_team_purchased_hints(user)
total_byoc_rewards = db.get_byoc_rewards(user)
# ret = f'{solved_challs}<br>{unsolved_challs}<br>{purchased_hints}'
scores = db.getTeammateScores(user)
total = sum([x[1] for x in scores])
team_byoc_stats = db.get_team_byoc_stats(user)
usernames = db.select(u.name for u in db.User if u.name != SETTINGS['_botusername'])[:]
resp = make_response(
render_template(
"scoreboard/hud.html",
teamname=teamname,
team_scores=scores,
total=total,
total_byoc_rewards=total_byoc_rewards,
solved_challs=solved_challs,
unsolved_challs=unsolved_challs,
purchased_hints=purchased_hints,
api_key=api_key,
is_admin=user.is_admin,
is_tipping_enabled= not SETTINGS["disable_custom_tips"],
team_byoc_stats=team_byoc_stats,
users=usernames,
)
)
return resp
@app.get("/hud/transactions")
@app.get("/hud/transactions/")
@db.db_session
def transactions():
api_key = request.cookies.get("api_key")
if api_key == None:
return "api_key not set; login first", 400
user = db.get_user_by_api_key(api_key)
if user == None:
return "invalid api key; login first.", 403
teamname = user.team.name
transactions = sorted(
db.get_team_transactions(user), key=lambda t: t.time, reverse=True
)
return render_template(
"scoreboard/transactions.html",
api_key=api_key,
transactions=transactions,
teamname=teamname,
)
@app.get("/challenges")
@limiter.limit("100/second", override_defaults=False)
@db.db_session
def challenges():
if not ctfRunning():
return render_template(
"scoreboard/challenges.html",
parsed=[],
available_challenges=[],
)
api_key = request.cookies.get("api_key")
if api_key == None:
return "api_key not set; visit HUD first...", 403
user = db.User.get(api_key=api_key)
if user == None:
return "invalid user api_key", 403
available_challenges = db.get_unlocked_challenges(user)
teammates = db.getTeammates(user)
parsed = [
(
c.id,
c.uuid,
c.author.name,
c.title,
db.challValue(c),
f"{db.percentComplete(c, user)}%",
"*" * int(db.avg(r.value for r in db.Rating if r.challenge == c) or 0),
", ".join([t.name for t in c.tags]),
)
for c in available_challenges
if c.id > 0 and c.author not in teammates and c.title != "__bonus__"
]
return render_template(
"scoreboard/challenges.html",
parsed=parsed,
available_challenges=available_challenges,
)
@app.get("/chall/<chall_uuid>")
@limiter.limit("100/second", override_defaults=False)
@db.db_session
def chall(chall_uuid):
chall = db.Challenge.get(uuid=chall_uuid)
if chall == None:
return "invalid challenge uuid", 404
api_key = request.cookies.get("api_key")
if api_key == None:
return "api_key not set; visit HUD first..."
# user = db.get_user_by_api_key(api_key)
user = db.User.get(api_key=api_key)
if user == None:
return "invalid api key", 403
purchased_hints = db.get_team_purchased_hints(user, chall_id=chall.id)
chall_value = db.challValue(chall)
captured_flags = sorted(
db.getSubmittedChallFlags(chall, user), key=lambda f: f.value
)
solves = db.getSolves(chall)
teammates = db.getTeammates(user)
if chall.author in teammates:
team_owned_challenge = True
else:
team_owned_challenge = False
rendered_chall_description = db.render_variables(user, chall.description)
next_hint_cost = db.getHintCost(user, chall.id)
return render_template(
"scoreboard/chall.html",
api_key=api_key,
chall=chall,
team_owned_challenge=team_owned_challenge,
chall_value=chall_value,
captured_flags=captured_flags,
purchased_hints=purchased_hints,
next_hint_cost=next_hint_cost,
solves=solves,
rendered_chall_description=rendered_chall_description,
)
@app.route("/sub", methods=["GET", "POST"])
@limiter.limit("100/second", override_defaults=False)
@db.db_session
@get_api_key
def submit_flag():
if not ctfRunning():
return "ctf not running."
if request.method == "POST":
user: db.User = db.get_user_by_api_key(request.cookies.get("api_key"))
flag = request.form.get("flag")
if flag == None or user == None:
return "flag or user missing from request; try setting api_key cookie", 405
submisssion_result = db.submit_flag(user_str=user.name, flag_str=flag)
if submisssion_result == False:
return "incorrect flag", 404
if submisssion_result == "":
submisssion_result = "invalid submission"
return f"{submisssion_result}"
return render_template("scoreboard/submit.html")
@app.get("/")
def scoreboard_index():
return render_template(
"scoreboard/index.html",
custom_logo_url=SETTINGS["custom_logo_url"]
)
@app.get("/create")
def create():
return render_template("creator/creator.html")
def parse_chall(chall):
try:
return toml.loads(chall)
except toml.TomlDecodeError as e:
print(f"error decoding toml: {e}")
return f"error decoding toml: {e}", 500
except TypeError as e:
print(f"error parsing toml: {e}")
return f"error parsing toml: {e}", 500
except BaseException as e:
print(e)
return f"{e}", 500
@app.post("/validate")
# @limiter.limit("4/second", override_defaults=False)
def validate():
print("before")
logger.debug(request.form)
chall = request.form.get("toml")
print(chall)
print("after")
challenge_object = parse_chall(chall)
if type(challenge_object) != dict:
return challenge_object
result = database.validateChallenge(challenge_object)
ret = renderChallenge(result, preview=True)
return markdown2.markdown(ret)
@app.post("/commit_challenge")
@limiter.limit("4/second", override_defaults=False)
def commit_chall():
logger.debug(request.form)
chall = request.form.get("toml")
api_key = request.cookies.get("api_key")
if api_key == None:
return "api_key not set; set it in the form field", 401
submitting_user = database.get_user_by_api_key(api_key)
if submitting_user == None:
return "user/api_key association not found", 404
submitting_user = submitting_user.name
challenge_object = parse_chall(chall)
if type(challenge_object) != dict:
return challenge_object
if submitting_user != challenge_object.get("author"):
return (
"Not authorized to submit a challenge on behalf of another user; api_key and username don't match",
403,
)
result = database.validateChallenge(challenge_object)
if result.get('valid') == False:
return f"invalid challenge_object; {result}", 400
chall_id = database.buildChallenge(result, is_byoc_challenge=True)
if chall_id == -3:
msg = f"Insufficient funds for {submitting_user}..."
return msg, 403
elif chall_id == -2:
msg = f'author does not exist: {submitting_user}' # shouldn't ever get here because of line 575
elif chall_id == -1:
msg = f'challenge itself not valid for somereason; {result}'
if SETTINGS["_debug"] and SETTINGS["_debug_level"] > 1:
logger.debug(msg)
if SETTINGS["_debug"] and SETTINGS["_debug_level"] > 1:
logger.debug(f"{submitting_user} created chall id {chall_id}")
with database.db_session:
chall_uuid = (database.Challenge[chall_id]).uuid
chall_url = f"/chall/{chall_uuid}"
ret = f"cool. here's your challenge -> <a href='{chall_url}'>{chall_uuid}</a>"
return ret
@app.get("/validator")
def validator_index():
return render_template("validator/index.html")
if __name__ == "__main__":
app.run(debug=True, port=4000)