-
Notifications
You must be signed in to change notification settings - Fork 2
/
database.py
1667 lines (1336 loc) · 52.9 KB
/
database.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
import binascii
from collections import Counter
import hashlib
import random
from requests.sessions import session
from settings import SETTINGS
import json
import toml
import uuid
from nacl.public import PrivateKey, PublicKey
from Crypto.PublicKey import RSA
import requests
from requests.exceptions import ConnectTimeout
from loguru import logger
logger.add(SETTINGS.get("_logfile"))
from datetime import datetime
from pony.orm import *
from pony.orm.core import BindingError
# https://editor.ponyorm.com/user/shyft/byoctf/designer
# this is probably a bit of an overcomplicated db architecture.
# this is because I was learning the relationships and how they worked in pony.
# things also changed in the project and I left some things in order to not break stuff.
db = Database()
class Flag(db.Entity):
id = PrimaryKey(int, auto=True)
challenges = Set("Challenge")
description = Optional(str)
solves = Set("Solve")
flag = Required(str)
value = Required(float)
unsolved = Optional(bool, default=True)
bonus = Optional(bool, default=False)
flag_type = Optional(str, default="normal")
tags = Set("Tag")
author = Required("User")
byoc = Optional(bool)
transaction = Optional("Transaction")
reward_capped = Optional(bool, default=False)
class Challenge(db.Entity):
id = PrimaryKey(int, auto=True)
title = Required(str)
flags = Set(Flag)
author = Required("User")
description = Optional(str)
parent = Set("Challenge", reverse="children")
children = Set("Challenge", reverse="parent")
tags = Set("Tag")
release_time = Optional(datetime, default=lambda: datetime.now())
visible = Optional(bool, default=True)
hints = Set("Hint")
byoc = Optional(bool, default=False)
byoc_ext_url = Optional(str, nullable=True, default=None)
unsolved = Optional(bool, default=True)
byoc_ext_value = Optional(float)
solve = Set("Solve")
transaction = Set("Transaction")
ratings = Set("Rating")
uuid = Optional(str, unique=True, default=lambda: str(uuid.uuid4()))
class User(db.Entity):
id = PrimaryKey(int, auto=True)
name = Required(str, unique=True)
challenges = Set(Challenge)
solves = Set("Solve")
team = Optional("Team")
sent_transactions = Set("Transaction", reverse="sender")
recipient_transactions = Set("Transaction", reverse="recipient")
authored_flags = Set(Flag)
ratings = Set("Rating")
api_key = Required(str, default=lambda: str(uuid.uuid4()))
is_admin = Required(bool, default=False)
public_key = Optional(str)
private_key = Optional(str)
class Solve(db.Entity):
id = PrimaryKey(int, auto=True)
time = Optional(datetime, default=lambda: datetime.now())
flag = Optional(Flag)
user = Required(User)
value = Required(float)
transaction = Optional("Transaction")
challenge = Optional(Challenge)
flag_text = Optional(str)
class DelayedSolve(Solve):
pass
class Team(db.Entity):
id = PrimaryKey(int, auto=True)
members = Set(User)
name = Required(str)
password = Required(str)
uuid = Required(str, default=lambda: str(uuid.uuid4()))
public_key = Optional(str, default="")
private_key = Optional(str, default="")
class Tag(db.Entity):
id = PrimaryKey(int, auto=True)
name = Optional(str)
challenges = Set(Challenge)
flags = Set(Flag)
class Transaction(db.Entity):
id = PrimaryKey(int, auto=True)
value = Optional(float)
sender = Required(User, reverse="sent_transactions")
recipient = Required(User, reverse="recipient_transactions")
type = Required(str)
message = Optional(str)
time = Optional(datetime, default=lambda: datetime.now())
solve = Optional(Solve)
flag = Optional(Flag)
challenge = Optional(Challenge)
hint = Optional("Hint")
class Hint(db.Entity):
id = PrimaryKey(int, auto=True)
text = Required(str)
cost = Optional(float)
challenge = Required(Challenge)
transactions = Set(Transaction)
class Rating(db.Entity):
id = PrimaryKey(int, auto=True)
user = Required(User)
challenge = Required(Challenge)
value = Optional(int, default=0) # 1-5
note = Optional(str)
time = Optional(datetime, default=lambda: datetime.now())
def generateMapping():
# https://docs.ponyorm.org/database.html
try:
if SETTINGS["_db_type"] == "sqlite":
db.bind(
provider="sqlite", filename=SETTINGS["_db_database"], create_db=True
)
elif SETTINGS["_db_type"] == "postgres":
print("postgres is tested less than sqlite... good luck...")
db.bind(
provider="postgres",
user=SETTINGS["_db_user"],
password=SETTINGS["_db_pass"],
host=SETTINGS["_db_host"],
database=SETTINGS["_db_database"],
port=SETTINGS["_db_port"],
)
elif SETTINGS["_db_type"] == "mysql":
print("mysql is untested... good luck...")
db.bind(
provider="mysql",
user=SETTINGS["_db_user"],
password=SETTINGS["_db_pass"],
host=SETTINGS["_db_host"],
database=SETTINGS["_db_database"],
)
# elif SETTINGS['_db_type'] == 'cockroach':
# print('using cockroachdb')
# db.bind(
# provider='cockroach',
# user=SETTINGS["_db_user"],
# password=SETTINGS["_db_pass"],
# host=SETTINGS["_db_host"],
# database=SETTINGS["_db_database"],
# sslmode='require'
# )
# db.create_tables()
db.generate_mapping(create_tables=True)
except BindingError as e:
print(e)
def set_custom_methods():
def get_chall_value(self):
flags = list(select(c.flags for c in Challenge if c.id == self.id))
return sum([flag.value for flag in flags])
setattr(Challenge, "get_value", get_chall_value)
def get_chall_rating(self):
return int(avg(r.value for r in Rating if r.challenge == self) or 0)
setattr(Challenge, "get_rating", get_chall_rating)
generateMapping()
set_custom_methods()
#########
@db_session
def get_or_create_user_by_email(email):
username = email.split('@')[0]
user = User.get(name=username)
if user == None:
unaffiliated_team = Team.get(name="__unaffiliated__")
user = User(name=username, team=unaffiliated_team)
rotate_player_keys(user)
return user
@db_session
def register_team(teamname: str, password: str, username: str) -> Team|str:
print(teamname, password, username)
teamname = teamname.strip()
password = password.strip()
if len(password) < 8:
return "min password length is 8"
hashed_pass = hashlib.sha256(password.encode()).hexdigest()
team = Team.get(name=teamname)
unaffiliated = Team.get(name="__unaffiliated__")
user = User.get(name=username)
if user == None:
logger.debug("User not yet created. Assigning to team \"__unaffiliated__\" for now")
user = User(name=username, team=unaffiliated)
rotate_player_keys(user)
db.commit()
if not user.team:
user.team = unaffiliated
db.commit()
if user.team.name != "__unaffiliated__":
msg = f"already registered as `{username}` on team `{user.team.name}`. talk to an admin to have your team changed..."
if SETTINGS["_debug"]:
logger.debug(msg)
return msg
# does the team exist?
if team == None:
team = Team(name=teamname, password=hashed_pass)
pub, priv = generate_keys()
team.public_key = pub
team.private_key = priv
db.commit()
if len(team.members) == SETTINGS["_team_size"]:
msg = f"No room on the team... currently limited to {SETTINGS['_team_size']} members per team."
if SETTINGS["_debug"]:
logger.debug(msg)
return msg
if (hashed_pass != team.password): # if it's a new team, these should match automatically..
msg = f"Password incorrect for team {team.name}"
if SETTINGS["_debug"]:
logger.debug(
f"{username} failed registration; Team {teamname} pass {password} hashed {hashed_pass}"
)
return msg
user.team = team
if team.private_key == "":
pub, priv = generate_keys()
team.public_key = pub
team.private_key = priv
db.commit()
return team
@db_session
def average_score() -> float:
all_scores = [getScore(u) for u in User.select(lambda u: u.id != 0)[:]]
return sum(all_scores) / len(all_scores)
def generate_keys(keysize: int = 2048):
"""returns pub,private keys in PKCS8 PEM format"""
key = RSA.generate(keysize)
priv = key.export_key("PEM", pkcs=8).decode()
pub = key.publickey().export_key().decode()
return pub, priv
@db_session
def rotate_player_keys(user: User):
user.api_key = str(uuid.uuid4())
pub, priv = generate_keys()
# priv = PrivateKey.generate()
# pub = priv.public_key
# user.private_key = priv._private_key.hex()
# user.public_key = pub._public_key.hex()
user.private_key = priv
user.public_key = pub
@db_session
def rotate_team_keys(team: Team):
pub, priv = generate_keys()
# priv = PrivateKey.generate()
# pub = priv.public_key
# user.private_key = priv._private_key.hex()
# user.public_key = pub._public_key.hex()
team.private_key = priv
team.public_key = pub
@db_session
def render_variables(user: User, msg: str) -> str:
"""this will replace the variables '{{PLAYERNAME}}' '{{TEAMNAME}}' AND '{{TEAMUUID}}' with appropriate values for a given player. This is mainly used in challenge descriptions."""
variables = {
"{{PLAYERNAME}}": user.name,
"{{TEAMNAME}}": user.team.name,
"{{TEAMUUID}}": user.team.uuid,
}
for k, v in variables.items():
msg = msg.replace(k, v)
return msg
def ensure_bot_acct():
# ensure the built in accounts for bot an botteam exist; remove from populateTestdata.py
with db_session:
unaffiliated = db.Team.get(name="__unaffiliated__")
if unaffiliated == None:
unaffiliated = db.Team(name="__unaffiliated__", password="__unaffiliated__")
botteam = db.Team.get(name="__botteam__")
if botteam == None:
botteam = db.Team(name="__botteam__", password="__botteam__")
bot = db.User.get(id=0)
if bot == None:
bot = db.User(id=0, name=SETTINGS["_botusername"], team=botteam)
rotate_player_keys(bot)
commit()
def is_valid_uuid(val):
try:
uuid.UUID(str(val))
return True
except ValueError:
logger.debug(f"invalid uuid {val}")
return False
@db_session # TODO 02sep23 this isn't working...
def get_team_by_id(target: str | int) -> User:
if is_valid_uuid(target):
return select(t for t in db.Team if t.uuid == target).first()
else:
return select(t for t in db.Team if t.id == target).first()
@db_session
def get_user_by_id(target: str | int) -> User:
if is_valid_uuid(target):
return select(u for u in db.User if u.api_key == target).first()
else:
return select(u for u in db.User if u.id == target).first()
@db_session
def grant_points(
requested_user: str,
admin_user: db.User = None,
amount: float = 0,
msg: str = "admin granted points",
):
# logger.debug('granting', amount, requested_user, admin_user, msg)
botuser = db.User.get(name=SETTINGS["_botusername"])
if admin_user == None:
admin_user = botuser
# logger.debug(admin_user.name)
user = db.User.get(name=requested_user)
if user != None:
t = db.Transaction(
sender=botuser,
recipient=user,
value=amount,
type="admin grant",
message=f"{admin_user.name}: {msg}",
)
db.commit()
logger.debug(f"granted {amount} points to {user.name}")
return True
else:
logger.debug("invalid user", requested_user)
return False
@db_session
def get_user_by_api_key(target: str) -> User:
if is_valid_uuid(target):
return select(u for u in db.User if u.api_key == target).first()
else:
return None
@db_session
def update_user_api_key(user: User, new_uuid: str = None):
"""create or set an new api_key for a user. Must be a uuid in str form"""
if new_uuid != None:
if is_valid_uuid(new_uuid):
user.api_key = new_uuid
return
else: # generate a new random one
user.api_key = str(uuid.uuid4())
print(user.api_key)
@db_session
def getTeammates(user: User):
"""this includes the user in the list of teammates..."""
res = list(select(member for member in User if member.team.name == user.team.name))
return res
@db_session
def getSubmittedChallFlags(chall: Challenge, user: User):
teammates = getTeammates(user)
flags = list()
for tm in teammates:
for solve in tm.solves:
if solve.challenge == chall:
flags.append(solve.flag)
# print(flags)
return flags
@db_session
def getScore(user: User) -> float:
if type(user) == str: # for use via cmdline in ctrl_ctf.py
# logger.debug(f'looking for user {user}')
user = User.get(name=user)
if user == None:
return "User is None... "
# https://docs.ponyorm.org/queries.html#automatic-distinct
# hence the without_distint()
received = sum(
select(t.value for t in Transaction if t.recipient == user).without_distinct()
)
sent = sum(
select(t.value for t in Transaction if t.sender == user).without_distinct()
)
if SETTINGS["_debug"] == True and SETTINGS["_debug_level"] > 1:
logger.debug(
f"{user.name} has received {received}, - sent {sent} = {received - sent}"
)
return received - sent
@db_session
def getTeammateScores(user: User):
teammates = list(
select(member for member in User if member.team.name == user.team.name)
)
res = [(tm.name, getScore(tm)) for tm in teammates]
return res
@db_session
def challValue(challenge: Challenge):
if challenge.byoc_ext_value != None:
return challenge.byoc_ext_value
if challenge.id == 0:
return 0
flags = list(select(c.flags for c in Challenge if c.id == challenge.id))
# if SETTINGS['_debug']:
if SETTINGS["_debug"] and SETTINGS["_debug_level"] > 1:
logger.debug(f"flags{flags}")
val = sum([flag.value for flag in flags])
# logger.debug(f'challenge {challenge.title} is worth {val} points')
return val
@db_session()
def topPlayers(num: int = 10):
all_users = select(u for u in User if u.name != SETTINGS["_botusername"])
topN = [(u, getScore(u)) for u in all_users]
if SETTINGS["_debug"] and SETTINGS["_debug_level"] > 1:
logger.debug(f"topN: {topN}")
if len(topN) > num:
return sorted(topN, key=lambda x: x[1], reverse=True)[:num]
else:
return sorted(topN, key=lambda x: x[1], reverse=True)
@db_session()
def getTopTeams(num: int = 3):
all_users = select(u for u in User if u.name != SETTINGS["_botusername"])
all_scores = [(u, getScore(u)) for u in all_users]
# logger.debug(f'all_scores: {all_scores}')
scores = {}
for user, score in all_scores:
scores[user.team.name] = scores.get(user.team.name, 0) + score
sorted_scores = sorted(scores.items(), key=lambda x: x[1], reverse=True)
if num <= len(sorted_scores):
res = sorted_scores[:num]
else:
res = sorted_scores
if SETTINGS["_debug"] and SETTINGS["_debug_level"] > 1:
logger.debug(f"sorted scores: {res}")
return res
@db_session()
def challegeUnlocked(user: User, chall):
"""returns true if all the dependencies for a given challenge have been met by the specified user"""
# logger.debug(f'{user.name} wants to access {chall.title}')
# get all solves for this user and their teammates.
teammates = getTeammates(user) # including self
# logger.debug(f'players {[x.name for x in teammates]}')
# logger.debug(user.team.name)
flags_subbed_by_team = list()
flags_subbed_by_team = select(
solve.flag
for solve in Solve
if solve.user in teammates and solve.flag in chall.parent.flags
)[:] # optimized query
# for tm in teammates:
# flags_subbed_by_team.append(
# select(solve.flag for solve in Solve if tm == solve.user)[:]
# )
# print(chall, team_solves)
# logger.debug(f'team_solves {team_solves}')
# logger.debug(f'"{chall.title}" has a parent "{chall.parent.title}" challenge dependencies {chall.children}')
parent_flags = set(
chall.parent.flags
) # use set to deduplicate flags. chall.parent.flags is the flags from ALL parent challenges (possibly more than one challenge). might need to think about that when randomly linking challenges.
if len(parent_flags) == 0:
return True
flag_capture_percent = len(flags_subbed_by_team) / len(parent_flags)
if SETTINGS["_debug"] and SETTINGS["_debug_level"] >= 2:
logger.debug(f"team_solves: {flags_subbed_by_team}")
logger.debug(f"parent_flags: {parent_flags}")
logger.debug(f"flag_capture_percent { flag_capture_percent}")
# consider making this a tunable setting?
if flag_capture_percent >= SETTINGS["percent_solved_to_unlock"]: # 50% by default
return True
return False
@db_session()
def get_challs_by_player(player: User) -> list[Challenge]:
if player == None:
return list()
challs = list(select(c for c in Challenge if c.author.name == player.name))
return challs
@db_session()
def rate(user: User, chall: Challenge, user_rating: int | float):
if chall == None or challegeUnlocked(user, chall) == False:
return -1
# is the rating within the bounds
if user_rating < SETTINGS["rating_min"]:
user_rating = SETTINGS["rating_min"]
elif user_rating > SETTINGS["rating_max"]:
user_rating = SETTINGS["rating_max"]
user_rating = int(user_rating)
prev_rating = Rating.get(user=user, challenge=chall)
if prev_rating:
# update your previous rating
prev_rating.value = user_rating
else:
try:
# breakpoint()
new_rating = Rating(user=user, challenge=chall, value=user_rating)
except TypeError:
return prev_rating
return user_rating
@db_session()
def get_unlocked_challenges(user: User):
# show only challenges which are not hidden (dependencies resolved and released)
teammates = getTeammates(user)
solvable = list(
select(c for c in Challenge if c.visible == True and c.author not in teammates)
) # type: ignore ; # visible means GMs want it to be solved...
visible_and_unlocked = [
c for c in solvable if challegeUnlocked(user, c)
] # means the user has met the prereqs for viewing the challenge
return visible_and_unlocked
@db_session()
def issolved(chall: Challenge, user: User):
teammates = getTeammates(user)
sol = select(
sol for sol in Solve if sol.challenge == chall and sol.user in teammates
).first()
if sol != None:
return True
return False
@db_session()
def get_completed_challenges(user: User):
teammates = getTeammates(user)
flags_subbed_by_team = list()
unlocked_challs = get_unlocked_challenges(user)
completed = set()
for chall in unlocked_challs:
if len(chall.flags) == 0: # this shouldn't occur
continue
flags_subbed_by_team = select(
solve.flag
for solve in Solve
if solve.user in teammates and solve.flag in chall.flags
)[:] # optimized query
chall_percent = len(flags_subbed_by_team) / len(chall.flags)
if chall_percent == 1:
completed.add(chall)
return completed
@db_session()
def get_untouched_challenges(user: User):
challs = get_unlocked_challenges(
user
) # this is all unlocked challs / visible challs
teammates = getTeammates(user)
untouched = list()
@db_session()
def get_incomplete_challenges(
user: User,
): # TODO: how is this different than get_all_unlocked_challenges() ? around line 423
"""show only challenges which are not hidden AND unsolved by a user/team"""
challs = get_unlocked_challenges(
user
) # this is all unlocked challs / visible challs
teammates = getTeammates(user)
ret = list()
for chall in challs:
if SETTINGS["_debug"] and SETTINGS["_debug_level"] > 1:
logger.debug("flags", list(chall.flags))
for flag in list(chall.flags):
# solve = Solve.get(user=user, flag=flag.flag)
solves = list(
select(
s for s in Solve if s.user in teammates and s.flag.flag == flag.flag
) # type: ignore
)
if SETTINGS["_debug"] and SETTINGS["_debug_level"] > 1:
logger.debug(solves)
if len(solves) == 0:
if chall not in ret:
ret.append(chall)
return ret
@db_session()
def getMostCommonFlagSolves(num=3):
solves = Counter(select(solve.flag for solve in Solve))
if SETTINGS["_debug"] and SETTINGS["_debug_level"] > 2:
logger.debug(solves)
# for solve
return solves.most_common(num)
@db_session
def get_byoc_rewards(user: User):
if isinstance(user, str):
user = User.get(name=user)
if user == None:
return 0
teammates = getTeammates(user)
total = sum(
select(
sum(t.value)
for t in db.Transaction
if (t.type == "byoc reward" or t.type == "byoc hint reward")
and t.recipient in teammates
)
)
return total
@db_session
def getHintTransactions(user: User) -> list[Transaction]:
res = select(
t for t in Transaction if t.sender.name == user.name and t.type == "hint buy"
)[:]
return res
@db_session
def get_team_purchased_hints(user: User, chall_id=-1):
hint_transactions = getHintTransactions(user)
# msg = f"Team {user.team.name}'s hints:\n"
data = list()
teammates = getTeammates(user)
for tm in teammates:
tm_hints = sorted(getHintTransactions(tm))
if chall_id == -1:
data += [
(
ht.hint.challenge.uuid,
ht.hint.challenge.title,
ht.hint.text,
ht.hint.cost,
ht.sender.name,
)
for ht in tm_hints if ht.hint
]
else:
data += [
(
ht.hint.challenge.id,
ht.hint.challenge.title,
ht.hint.text,
ht.hint.cost,
ht.sender.name,
)
for ht in tm_hints
if ht.hint and ht.hint.challenge.id == chall_id
]
return data
@db_session()
def get_team_byoc_stats(user: User):
teammates = getTeammates(user)
team_challs = db.Challenge.select(lambda c: c.author in teammates)[:] # type: ignore
# num solves per challenge
byoc_solves = list()
for chall in team_challs:
num_solves = db.Solve.select(lambda s: s.challenge == chall)[:] # type: ignore
total_rewards_for_chall = 0
# total_rewards_for_chall = sum(
# db.select( sum(t.value) for t in db.Transaction if t.type == "byoc reward" and t.recipient in teammates and t.challenge == chall).without_distinct()
# )
ts = db.Transaction.select(
lambda t: t.type == "byoc reward"
and t.recipient in teammates
and t.challenge == chall
)[:]
for t in ts:
total_rewards_for_chall += t.value
line = [chall, len(num_solves), total_rewards_for_chall]
byoc_solves.append(line)
return byoc_solves
@db_session()
def get_team_transactions(user: User):
teammates = getTeammates(user) # throws an error about db session is over
ts = db.Transaction.select(
lambda t: t.sender in teammates or t.recipient in teammates
)[:]
return ts
@db_session
def getHintCost(user: User, challenge_id: int = 0) -> int | float:
# this is to abstract away some of the issues with populating test data
# see around line 970 in buy_hint in byoctf_discord.py
# does challenge have hints
chall = Challenge.get(id=challenge_id)
if chall == None:
return -1
hints_for_this_chall = list(chall.hints)
purchasable_hints = list()
teammates = getTeammates(user)
for hint in hints_for_this_chall:
hint_transaction = select(
t for t in Transaction if t.sender in teammates and t.hint == hint
).first()
# print(hint_transaction)
if hint_transaction != None:
if SETTINGS["_debug"] == True and SETTINGS["_debug_level"] > 0:
logger.debug("already bough hint in transaction", hint_transaction)
# a purchase exists (not None); no need to buy it again
continue # so try the next hint in the list of challenge hints
else:
purchasable_hints.append(hint)
if len(purchasable_hints) < 1:
if SETTINGS["_debug"] == True and SETTINGS["_debug_level"] > 0:
logger.debug(
f"{user.name} has no more hints for challenge id {challenge_id}"
)
# return "There are no more hints available to purchase for this challenge.", None
return -1
purchasable_hints = sorted(purchasable_hints, key=lambda x: x.cost, reverse=False)
# print(f'hints available to purchase: {purchasable_hints}')
cheapest_hint = purchasable_hints[0]
# print(cheapest_hint.to_dict())
return cheapest_hint.cost
@db_session
def buyHint(user: User, challenge_id: int = 0):
# this is to abstract away some of the issues with populating test data
# see around line 400 in buy_hint in byoctf_discord.py
# does challenge have hints
chall = Challenge.get(id=challenge_id)
if chall == None:
return f"invalid challenge id: {challenge_id}", None
teammates = getTeammates(user)
if chall.author in teammates:
return "You shouldn't have to buy your own hints...", None
if SETTINGS["_debug"]:
logger.debug(
f"Trying to buy hint for challenge_id {challenge_id} and user {user.name}"
)
# has user purchased these hints
# hint_transactions = list()
hints_for_this_chall = list(chall.hints)
purchasable_hints = list()
# teammates collected above
for hint in hints_for_this_chall:
hint_transaction = select(
t for t in Transaction if t.sender in teammates and t.hint == hint
).first()
# print(hint_transaction)
if hint_transaction != None:
print("already bough hint in transaction", hint_transaction)
# a purchase exists (not None); no need to buy it again
continue # so try the next hint in the list of challenge hints
else:
purchasable_hints.append(hint)
if len(purchasable_hints) < 1:
if SETTINGS["_debug"] == True and SETTINGS["_debug_level"] > 0:
logger.debug(
f"{user.name} has no more hints for challenge id {challenge_id}"
)
return "There are no more hints available to purchase for this challenge.", None
purchasable_hints = sorted(purchasable_hints, key=lambda x: x.cost, reverse=False)
# print(f'hints available to purchase: {purchasable_hints}')
cheapest_hint = purchasable_hints[0]
print(cheapest_hint.to_dict())
# does user have enough funds
funds = getScore(user)
if funds >= cheapest_hint.cost:
botuser = User.get(name=SETTINGS["_botusername"])
hint_buy = Transaction(
sender=user,
recipient=botuser,
value=cheapest_hint.cost,
challenge=chall,
hint=cheapest_hint,
type="hint buy",
message=f"bought hint ID {cheapest_hint.id} for challenge ID {chall.id}",
)
if (
"byoc" in [t.name for t in chall.tags]
and SETTINGS["_byoc_hint_reward_rate"] > 0
):
botuser = db.User.get(id=0)
reward = cheapest_hint.cost * SETTINGS["_byoc_hint_reward_rate"]
byoc_hint = Transaction(
sender=botuser,
recipient=chall.author,
value=reward,
challenge=chall,
hint=cheapest_hint,
type="byoc hint reward",
message=f"hint buy from {user.name}",
)
return "ok", cheapest_hint
return "insufficient funds", None
@db_session
def createExtSolve(user: User, chall: Challenge, submitted_flag: str):
if chall.byoc_ext_url == None:
msg = f"Challenge id {chall.id} is not an externally validated challenge."
if SETTINGS["_debug"]:
logger.debug(msg)
return msg
if user in getTeammates(chall.author):
msg = f"You can't submit a challenge from a teammate or yourself... "
if SETTINGS["_debug"]:
logger.debug(msg)
return msg
payload = {"challenge_id": chall.id, "flag": submitted_flag, "user": user.name}
resp = requests.post(chall.byoc_ext_url, data=payload)
# breakpoint()
if resp.status_code != 200:
msg = f"Challenge id {chall.id} external validation server isn't responding correctly. talk to the author..."
if SETTINGS["_debug"]:
logger.debug(msg)
return msg
data = json.loads(resp.text)
if data.get("msg") == "correct":
botuser = User.get(name=SETTINGS["_botusername"])
reward = chall.byoc_ext_value
# first blood
if chall.unsolved == True: