-
Notifications
You must be signed in to change notification settings - Fork 2
/
byoctf_discord.py
executable file
·1710 lines (1407 loc) · 57.2 KB
/
byoctf_discord.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3
og_print = print
import random
from rich import print
from fileinput import filename
from logging import log
from pony.orm.core import args2str
from settings import SETTINGS, init_config, is_initialized
import datetime
import time
import json
import pyfiglet
import math
from typing import Union
import hashlib
from loguru import logger
logger.add(SETTINGS["_logfile"])
import requests
from terminaltables import AsciiTable, GithubFlavoredMarkdownTable
import discord
from discord.ext import commands
import asyncio
import database as db
import toml
FIRST_PLACE_TEAM = ""
def banner():
ret = _spray(msg="byoctf")
msg = f"""
{ret}
by fs2600 / SOTB crew
"""
og_print(msg)
# should be handled in settings now.
# if is_initialized() == False: # basically the ./byoctf_diskcache/cache.db has data in it. rm to reset
# init_config()
bot = commands.Bot(command_prefix="!", intents=discord.Intents.all())
async def newLeader() -> bool:
global FIRST_PLACE_TEAM
ctf_chan = bot.get_channel(SETTINGS["_ctf_channel_id"])
leader = db.getTopTeams(num=1)[0]
if leader[0] != FIRST_PLACE_TEAM:
FIRST_PLACE_TEAM = leader[0]
await ctf_chan.send(
f"There's a new Leader!!! `{leader[0]}` with `{leader[1]}` points"
)
# this is a hook point for calling the lights api to do something on leader change...
return True
return False
@db.db_session
def getDecayChallengeValue(chall_id: id) -> tuple[int, int, float]:
raise NotImplementedError
chall = db.Challenge[chall_id]
solve_count = db.count(
db.select(t for t in db.Transaction if t.flag == flag).without_distinct()
)
team_count = (
db.count(db.select(t for t in db.Team)) - 1
) # don't count discordbot's team
solve_percent = solve_count / team_count
reward *= max(
[1 - solve_percent, SETTINGS["_decay_minimum"]]
) # don't go below the minimum established
return solve_count, team_count, reward
@bot.event
async def on_ready():
logger.debug(f"{bot.user.name} is online and awaiting your command!")
def username(obj):
if hasattr(obj, "author"):
return f"{obj.author.name}"
elif type(obj) == discord.User or type(obj) == discord.user.ClientUser:
return f"{obj.name}"
return "__NONE__"
def ctfRunning():
the_time = datetime.datetime.utcnow()
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
async def getDiscordUser(ctx, target_user: str):
# this is only for the gui representation of the recipient
# https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.UserConverter
logger.debug(f"looking up user {target_user}")
uc = discord.ext.commands.UserConverter()
try:
res = await uc.convert(ctx, target_user)
except BaseException as e:
logger.debug(e)
res = target_user
logger.debug(f"{res=}, {type(res)}")
return res
async def sendBigMessage(ctx, content, wrap=True):
"""this should split a long message across multiple sends if it exceeds the 2000 char limit of discord. requires newlines in the message. Set wrap=False to omit the code blocks for your message"""
lines = content.splitlines(keepends=True)
if SETTINGS["_debug"] == True and SETTINGS["_debug_level"] > 1:
logger.debug(content)
chunk = ""
for line in lines:
if len(chunk) + len(line) < 1800:
chunk = chunk + line
else:
if wrap:
await ctx.send(f"```{chunk}```")
else:
await ctx.send(f"{chunk}")
chunk = line
# send final chunk
if wrap:
await ctx.send(f"```{chunk}```")
else:
await ctx.send(f"{chunk}")
@bot.event
async def on_command_error(ctx, error):
if isinstance(error, commands.errors.CommandNotFound):
await ctx.send(
f"Command `{ctx.message.content}` not found... \n\nTry `!help` or `!help <command>`"
)
# elif isinstance(error, commands.errors.BadArgument):
# await ctx.send(f'Invalid argument to command')
elif isinstance(error, commands.errors.CommandOnCooldown):
msg = f"***Whoa... Slow down... Please try again in {error.retry_after:.2f}s***"
await ctx.send(msg)
logger.debug(f"Brute forcing for flags? - {username(ctx)}: {msg}")
elif isinstance(error, commands.errors.MissingRequiredArgument):
await ctx.send(f"Missing argument to command")
else:
logger.debug(f"{error}")
# if SETTINGS["_debug"]:
raise error
async def inPublicChannel(
ctx, msg="this command should only be done in a private message (a DM) to the bot"
):
if ctx.channel.type.name == "text":
# we're in public
await ctx.message.delete()
await ctx.send(msg)
return True
return False
async def isRegistered(
ctx, msg="It doesn't look like you're registered yet. `!reg <teamname> <teampass>`"
):
with db.db_session:
user = db.User.get(name=username(ctx))
if user == None:
await ctx.send(msg)
return False
return True
def renderChallenge(result: dict, preview=False):
"""returns the string to be sent to the user via discord. preview is mostly for BYOC challenges to validate that flags came through correctly."""
msg = ""
# preview is for the rendering of the validator for byoc challenges
if preview == True:
if result.get("valid"):
msg = f"Challenge **valid**. 😎😎😎 \n\n"
else:
msg = f"Challenge ***INVALID***. ❌❌❌ \n\n **failed because**: {result['fail_reason']}\n\n"
byoc_rate = SETTINGS.get("_byoc_reward_rate", 0)
break_even_solves = (result["cost"] / byoc_rate) // 100
logger.debug(result)
avg_flag_val = "invalid challenge"
try:
avg_flag_val = sum([f["flag_value"] for f in result["flags"]]) / len(
result["flags"]
)
flag_vals = [f["flag_value"] for f in result["flags"]]
num_flags = len(flag_vals)
flag_vals.sort()
least_middle_most = flag_vals[num_flags // 2 - 1]
# break_even_solves = result["cost"] / avg_flag_val
# In [28]: vals = [100, 225, 250, 350, 400, 475, 600]
# In [29]: vals.sort();vals[len(vals)//2 - 1]
# Out[29]: 250
# This is the minimum number of solves of a obtainable flag to recoup cost.
break_even_solves = result["cost"] / least_middle_most
except ZeroDivisionError as e:
logger.debug(e)
except BaseException as e:
logger.debug(e)
# break_even_solves = result['cost'] / (avg_flag_val * byoc_rate)
msg += f"{'-'*25}\n\n"
msg += "Here's a preview:\n\n"
msg += f"It will cost `{result['cost']}` points to post with `!byoc_commit`\n"
# normal challenge rendering
# print(result)
msg += "-" * 40 + "\n"
msg += f"**Title**: `{result['challenge_title']}`\n\n"
msg += f"**Total Challenge Value**: `{result['value']}` points\n\n"
msg += f'**Challenge_uuid**: `{result.get("uuid")}`\n\n'
# byoc validation rendering
if preview == True:
msg += f"Average flag value `{avg_flag_val}`\n\nReward rate is currently `{byoc_rate}` of flag value which means about `{break_even_solves}` solves will be required to break even. _It's possible to break even or profit with enough of partial solves._\n\n"
# normal rendering
msg += f"**Description**:\n{result['challenge_description']}\n\n"
msg += f"**Tags**: ` {', '.join(result.get('tags',list()))} ` \n\n"
msg += f"**Unlocked By Challenges**: `{result.get('parent_ids', list())}`\n\n"
msg += "-" * 40 + "\n\n"
msg += f'**Number of Flags**: {result.get("num_flags",0)}\n\n'
msg += f"**Total Hints**: {len(result.get('hints',list()))}\n\n"
for idx, hint in enumerate(result.get("hints_purchased", list()), 1):
msg += f"**Hint** {idx}: {hint.text}\n"
msg += "-" * 40 + "\n\n"
if result.get("byoc_ext_url") != None:
msg += f"**This is an externally validated flag:** Players must submit it with `!byoc_ext <chall_id> <flag>` "
# more byoc validation rendering
if preview == True:
msg += f"\n**Hints**\n\n"
for idx, hint in enumerate(result.get("hints", list()), 1):
msg += (
f" - Hint {idx}: `{hint['hint_text']}` Cost: `{hint['hint_cost']}` \n"
)
msg += f"\n\n"
msg += "-" * 40 + "\n"
msg += f"\n**Flags**\n\n"
for idx, flag in enumerate(result["flags"], 1):
msg += f" - Flag {idx}: `{flag['flag_flag']}` value: `{flag['flag_value']}` title: `{flag['flag_title']}` \n"
# finally send it back.
return msg
# TODO this might be a problem; disable team unregistration...
# user1 joins team A
# user1 joins team A
# user2 joins team A
# user1 creates a challenge X
# user2 leaves team A
# user2 joins team B (a burner team)
# user2 solves challenge X
# user2 leaves team B
# user2 joins team A
@db.db_session()
@bot.command(
name="unregister",
help="Leave a team... you still exist as a player but without a team... no fun.",
aliases=["unreg", "leave"],
)
@commands.dm_only()
async def unregister(ctx: discord.ext.commands.Context):
if await isRegistered(ctx) == False:
return
if await inPublicChannel(
ctx, msg=f"Hey, <@{ctx.author.id}>, don't leave a team in public channels..."
):
return
await ctx.send("unregistration is disabled... you pesky hackers ruined it..")
return # this may be deprecated or removed in the future...
if SETTINGS["registration"] == "disabled":
await ctx.send("registration is disabled")
return
with db.db_session:
user = db.User.get(name=username(ctx))
if user == None:
logger.debug(f"user {username(ctx)} not registered to play.")
await ctx.send("You weren't registered")
return
if SETTINGS["_debug"] and SETTINGS["_debug_level"] > 0:
logger.debug(f"{user.name} left team {user.team.name}")
await ctx.send(f"Leaving team {user.team.name}... bye.")
unaffiliated = db.Team.get(name="__unaffilliated__")
user.team = unaffiliated
db.commit()
def _spray(msg: str = "BYOCTF \nby fs2600 ") -> str:
fonts = [
"3-d",
"3x5",
"5lineoblique",
"slant",
"5lineoblique",
"alphabet",
"banner3-D",
"doh",
"isometric1",
"letters",
"alligator",
"bubble",
]
return pyfiglet.figlet_format(msg, font=random.choice(fonts))
@bot.command(name="spray", help="show a random byoctf banner")
async def spray(ctx: discord.ext.commands.Context, msg: str = "BYOCTF \nby fs2600 "):
ret = _spray(msg=msg)
count = 0
while len(ret) > 2000:
ret = _spray(msg=msg)
if count > 4:
await ctx.send("message may be too long... try something else")
return
await ctx.send(f"```{ret}```")
@db.db_session()
@bot.command(
name="register",
help="register on the scoreboard. !register <teamname> <password>; wrap team name in quotes if you need a space",
aliases=["reg", "join"],
)
@commands.dm_only()
async def register(
ctx: discord.ext.commands.Context, teamname: str = "", password: str = ""
):
# if await isRegistered(ctx, msg="Looks like you're already registered.... try `!unreg`") == False:
# return
if await inPublicChannel(
ctx,
msg=f"Hey, <@{ctx.author.id}>, don't register or join a team in public channels...",
):
return
if SETTINGS["registration"] == "disabled":
await ctx.send("registration is disabled")
return
if teamname == "" or password == "":
await ctx.send(
"I know it looks like the teamname and password are optional parameters, but they aren't... sorry. wrap the team name in quotes if it has spaces. "
)
return
# db.register_team(teamname, password, username(ctx))
# # TODO move over to using this function to separate discord from business logic 16SEP23
with db.db_session:
teamname = teamname.strip()
password = password.strip()
hashed_pass = hashlib.sha256(password.encode()).hexdigest()
team = db.Team.get(name=teamname)
unaffiliated = db.Team.get(name="__unaffiliated__")
user = db.User.get(name=username(ctx))
if user == None:
logger.debug("User not yet created. Assigning to team \"__unaffiliated__\" for now")
user = db.User(name=username(ctx), team=unaffiliated)
db.rotate_player_keys(user)
if not user.team:
user.team = unaffiliated
if user.team.name != "__unaffiliated__":
msg = f"already registered as `{username(ctx)}` on team `{user.team.name}`. talk to an admin to have your team changed..."
await ctx.send(msg)
if SETTINGS["_debug"]:
logger.debug(msg)
return
# does the team exist?
if team == None:
team = db.Team(name=teamname, password=hashed_pass)
pub, priv = db.generate_keys()
team.public_key = pub
team.private_key = priv
if len(team.members) == SETTINGS["_team_size"]:
msg = f"No room on the team... currently limited to {SETTINGS['_team_size']} members per team."
await ctx.send(msg)
if SETTINGS["_debug"]:
logger.debug(msg)
return
if (
hashed_pass != team.password
): # if it's a new team, these should match automatically..
msg = f"Password incorrect for team {team.name}"
await ctx.send(msg)
if SETTINGS["_debug"]:
logger.debug(
f"{username(ctx)} failed registration; Team {teamname} pass {password} hashed {hashed_pass}"
)
return
user.team = team
if team.private_key == "":
pub, priv = db.generate_keys()
team.public_key = pub
team.private_key = priv
db.commit()
# give them the 'byoctf' channel on Arkansas hackers
# add them to the appropriate channels on your server.
guild: discord.Guild = bot.get_guild(SETTINGS["_ctf_guild_id"])
role = guild.get_role(SETTINGS["_ctf_channel_role_id"])
channel = bot.get_channel(SETTINGS["_ctf_channel_id"])
member = guild.get_member(ctx.author.id)
if member == None:
msg = f"Error {member=}"
logger.debug(msg)
# await ctx.send(msg)
return None
await member.add_roles(role)
if SETTINGS["_debug"] and SETTINGS["_debug_level"] > 0:
logger.debug(f"{member} on {guild} got role {role}")
msg = f"Registered as `{username(ctx)}` on team `{teamname}`. Check the {channel.mention} channel"
await ctx.send(msg)
@bot.command(
name="ctfstatus",
help="shows status information about the CTF",
aliases=["ctfstat", "ctfstats"],
)
async def ctfstatus(ctx):
if await isRegistered(ctx) == False:
return
if await inPublicChannel(
ctx,
msg=f"Hey, <@{ctx.author.id}>, don't view ctf status info in public channels...",
):
return
data = [
(k, SETTINGS[k]) for k in SETTINGS.iterkeys() if k[0] != "_"
] # filter out the private settings; see settings.py config object
data.insert(0, ["Setting", "Value"])
table = GithubFlavoredMarkdownTable(data)
await ctx.send(f"CTF Status ```{table.table}```")
@bot.command(
name="scores",
help="shows your indivivually earned points, your teams collective points, and the top N teams without their scores.",
aliases=["score", "points", "top"],
)
# @commands.dm_only()
async def scores(ctx):
if await isRegistered(ctx) == False:
return
if await inPublicChannel(
ctx,
msg=f"Hey, <@{ctx.author.id}>, don't show your scores in public channels...",
):
return
if ctfRunning() == False:
await ctx.send("CTF isn't running yet")
return
if await newLeader() == True:
# another hook for doing intersting stuff with lights and sound when there is a new score leader
pass
# individual score
msg = ""
with db.db_session:
user = db.User.get(name=username(ctx)) # simpler
individual_points = db.getScore(user)
if SETTINGS["_debug"] == True and SETTINGS["_debug_level"] == 2:
logger.debug(f"{user.name} individual points {individual_points}")
# teammates scores
teammates = db.getTeammateScores(user)
teammates = sorted(teammates, key=lambda x: x[1], reverse=True)
teammates.insert(0, ["Teammate", "Score"])
table = GithubFlavoredMarkdownTable(teammates)
team_points = sum([v for k, v in teammates[1:]]) # skip header
msg += f"Your score is `{individual_points}`\n"
msg += f"\nTeam `{user.team.name}` has `{team_points}` ```{table.table}```"
if SETTINGS["scoreboard"] == "public":
# top 3 team scores
scores = db.getTopTeams(
num=SETTINGS["_scoreboard_size"]
) # private settings with _
scores.insert(0, ["Team Name", "Score"])
table = GithubFlavoredMarkdownTable(scores)
msg += (
f'Top {SETTINGS["_scoreboard_size"]} Team scores \n```{table.table}```'
)
else:
msg += f"Scoreboard is set to private\n"
if SETTINGS["_show_mvp"] == True:
# top players in the game
topPlayers = db.topPlayers(num=SETTINGS["_mvp_size"])
data = [(p.name, p.team.name, v) for p, v in topPlayers]
data.insert(0, ["Player", "Team", "Score"])
table = GithubFlavoredMarkdownTable(data)
msg += f'Top {SETTINGS["_mvp_size"]} Players\n```{table.table}```'
else:
msg += f"MVP is set to False "
await ctx.send(msg)
@bot.command(
name="whoami", help="Show username,api_key, and teamname", aliases=["w"]
) # shows authorid, name, teamname
async def byoc_stats(ctx):
if await isRegistered(ctx) == False:
return
if await inPublicChannel(ctx, msg=f"<@{ctx.author.id}>, dm this command to CTFBot"):
return
msg = ""
with db.db_session:
user = db.User.get(name=username(ctx))
teammates = db.getTeammates(user)
await ctx.send(
f"AuthorID: <@{ctx.author.id}>\nUserName: {user.name}\napi key: {user.api_key}\nHUD Link: {SETTINGS['scoreboard_url']}/login/{user.api_key}\nTeamName: {user.team.name}\nTeammates: {[t.name for t in teammates]}\n\nuse `!mykeys` to see your pub/priv keys or `!rotate_keys` to generate new ones."
)
@bot.command(name="mykeys", help="Show public and private keys")
async def my_keys(ctx):
with db.db_session:
user = db.User.get(name=username(ctx))
await ctx.send(f"```Public Key:\n{user.public_key}```")
await ctx.send(f"```Private Key:\n{user.private_key}```")
@bot.command(
name="submit", help="submit a flag e.g. !submit FLAG{some_flag}", aliases=["sub"]
)
@commands.cooldown(
1, SETTINGS["_rate_limit_window"], type=discord.ext.commands.BucketType.user
) # one submission per second per user
async def submit(ctx: discord.ext.commands.Context, submitted_flag: str = None):
if await isRegistered(ctx) == False:
return
if await inPublicChannel(
ctx, msg=f"Hey, <@{ctx.author.id}>, don't submit flags in public channels..."
):
return
if ctfRunning() == False:
await ctx.send("CTF isn't running yet")
return
if SETTINGS["_debug"] == True and SETTINGS["_debug_level"] == 1:
logger.debug(f"{username(ctx)} is attempting to submit '{submitted_flag}'")
with db.db_session:
# is this a valid flag
flag = db.Flag.get(flag=submitted_flag)
user = db.User.get(name=username(ctx))
if flag == None:
msg = f'incorrect: we got "{submitted_flag}"'
logger.debug(msg)
await ctx.send(msg)
return
# have I already submitted this flag?
solves = list(
db.select( # type: ignore
solve
for solve in db.Solve # type: ignore
if submitted_flag == solve.flag.flag
and username(ctx) == solve.user.name
)
) # should be an empty list
if len(solves) > 0: # if prev_solve != None:
msg = f"You've already submitted `{submitted_flag}` at {solves[0].time} "
logger.debug(msg)
await ctx.send(msg)
return
# has a teammate submitted this flag?
teammates = db.getTeammates(user)
solved = list()
for teammate in teammates:
res = list(
db.select( # type: ignore
solve
for solve in db.Solve # type: ignore
if submitted_flag == solve.flag.flag
and teammate.name == solve.user.name
)
) # see above regarding simpler looking query
if len(res) > 0: # already submitted by a teammate
msg = f"{res[0].user.name} already submitted `{submitted_flag}` at {res[0].time} "
if SETTINGS["_debug"] == True and SETTINGS["_debug_level"] == 1:
logger.debug(msg)
await ctx.send(msg)
return
# did this user author the flag?
if flag.author.name == user.name:
await ctx.send("You can't submit a flag from your own challenges...")
return
# did someone else on their team author this flag?
for teammate in teammates:
if flag.author.name == teammate.name:
await ctx.send(
"You can't submit a flag created by someone on your own team..."
)
return
# if I get this far, it has not been solved by any of my teammates
# is this challenge unlocked?
# get parent challenges.
flag_challs = list(flag.challenges)
# incomplete_challs = list()
for chall in flag_challs:
for p_chall in list(chall.parent):
print(p_chall.title, p_chall.id)
# is the parent complete?
# if db.challegeUnlocked(user, chall) == False:
if db.challengeComplete(p_chall, user) == False:
# incomplete_challs.append(p_chall)
await ctx.send(
f"This flag is for a challenge that is not unlocked yet... good job? Look at `{p_chall.title}` and unlock it (50% or more flags captured) then try again?"
)
# return
msg = "Correct!\n"
reward = flag.value
challenge: db.Challenge = db.select( # type: ignore
c for c in db.Challenge if flag in c.flags
).first()
if challenge: # was this flag part of a challenge?
msg += f"You submitted a flag for challenge `{challenge.title}`.\n"
if flag.unsolved == True:
ctf_chan = bot.get_channel(SETTINGS["_ctf_channel_id"])
discord_user = await getDiscordUser(ctx, user.name)
logger.debug(f"{discord_user=} {type(discord_user)}")
await ctf_chan.send(f"<@{discord_user.id}> drew First Blood!")
msg += f'**First blood!** \nYou are the first to submit `{flag.flag}` and have earned a bonus {SETTINGS["_firstblood_rate"] * 100 }% \nTotal reward `{flag.value * (1 + SETTINGS["_firstblood_rate"])}` rather than `{flag.value}`\n'
elif SETTINGS["_decay_solves"] == True:
# solve_count, team_count, decay_value = getDecayValue(challenge.id)
solve_count = db.count(
db.select( # type: ignore
t for t in db.Transaction if t.flag == flag
).without_distinct()
)
team_count = (
db.count(db.select(t for t in db.Team)) - 1
) # don't count discordbot's team
solve_percent = solve_count / team_count
reward *= max(
[1 - solve_percent, SETTINGS["_decay_minimum"]]
) # don't go below the minimum established
if SETTINGS["_debug"] == True:
logger.debug(
f"decay solves {solve_count} team count{team_count} ; solve percent {solve_percent} reward is {reward}"
)
msg += f"{solve_count} teams have solved this challenge... Your reward is reduced based on that fact... reward is {reward} rather than {flag.value}\n"
# firstblood and decay points/award/reductions logic is now in create solve. above is for display only
db.createSolve(
user=user,
flag=flag,
challenge=challenge,
msg="\n".join([c.title for c in flag.challenges]),
)
msg += f"Challenge is {db.percentComplete(challenge, user)}% complete.\n"
msg += f"Your score is now `{db.getScore(user)}`"
# logger.debug(msg)
await ctx.send(msg)
@bot.command(
name="rotate_keys",
help="generate new api_key, public_key, and private_key",
)
@commands.cooldown(
1, SETTINGS["_rate_limit_window"], type=discord.ext.commands.BucketType.user
) # one submission per second per user
async def rotate_keys(ctx):
if await isRegistered(ctx) == False:
return
if await inPublicChannel(
ctx,
msg=f"Hey, <@{ctx.author.id}>, send that command in a DM to the bot...",
):
return
def check(msg):
return msg.content == "confirm" and msg.channel == ctx.channel
# TODO https://discordpy.readthedocs.io/en/latest/api.html#discord.Client.wait_for
await ctx.send(
"\n\n\n***Reply with `confirm` in the next 20 seconds to rotate your api, pub/priv keys***"
)
with db.db_session:
user = db.User.get(name=username(ctx))
if user == None:
await ctx.send("invalid user somehow...")
return
resp = None
try:
resp = await ctx.bot.wait_for("message", check=check, timeout=20)
except asyncio.exceptions.TimeoutError as e:
await ctx.send("**Cancelling...**")
return
if resp.content == "confirm":
db.rotate_player_keys(user)
await ctx.send("Keys updated. use `!whoami` to see them... ")
return
await ctx.send("invalid response")
@bot.command(
name="tip",
help="send a tip (points) to another player; msg has 100 char limit e.g. !tip @user <some_points> ['some message here']",
)
@commands.cooldown(
1, SETTINGS["_rate_limit_window"], type=discord.ext.commands.BucketType.user
) # one submission per second per user
async def tip(
ctx,
target_user: Union[discord.User, str],
tip_amount: float,
msg: str | None = None,
):
if await isRegistered(ctx) == False:
return
if tip_amount <= 0:
await ctx.send("nice try... ")
return
with db.db_session:
sender = db.User.get(name=username(ctx))
recipient = db.User.get(name=username(target_user))
if sender == recipient:
await ctx.send("nice try... ")
return
if recipient == None:
await ctx.send(
f"invalid recipient...`{target_user}`. Are they registered for the ctf using the `!reg` command?"
)
return
result, points = db.send_tip(sender, recipient, tip_amount=tip_amount, msg=msg)
if result == False:
await ctx.send(
f"You only have {points} points and can't send {tip_amount}... math is hard... "
)
return
# tip = db.Transaction(
# sender=sender,
# recipient=recipient,
# value=tip_amount,
# type="tip",
# message=msg,
# )
# db.commit()
recipient_discord_user = await getDiscordUser(ctx, username(target_user))
message = f"<@{ctx.author.id}> is sending a tip of `{tip_amount}` points to <@{recipient_discord_user.id}> with message ```{msg}```"
await ctx.send(message)
if SETTINGS["_debug"] == True and SETTINGS["_debug_level"] == 1:
logger.debug(f"tip from {username(ctx)} - {message}")
@bot.command(
name="unsolved",
help="list only the challenges that your team HASN'T solved",
aliases=["usol", "un", "unsol"],
)
async def list_unsolved(ctx):
if await isRegistered(ctx) == False:
return
if await inPublicChannel(
ctx, msg=f"Hey, <@{ctx.author.id}>, don't view challenges in public channels..."
):
return
if ctfRunning() == False:
await ctx.send("CTF isn't running yet")
return
with db.db_session:
user = db.User.get(name=username(ctx))
challs = db.get_incomplete_challenges(user)
# logger.debug(challs)
res = list()
for c in challs:
if c.author not in db.getTeammates(
user
): # you can't solve your teammates challenges, so don't show them.
res.append(
[c.id, c.author.name, c.title, ", ".join([t.name for t in c.tags])]
)
res.insert(0, ["ID", "Author", "Title", "Tags"])
table = GithubFlavoredMarkdownTable(res)
# logger.debug("discord",challs)\
msg = f"Showing all unsolved challenges```{table.table}```"
await sendBigMessage(ctx, msg)
# await ctx.send(msg)
def anyIn(list1, list2):
return any(elem in list1 for elem in list2)
def allIn(list1, list2):
return all(elem in list1 for elem in list2)
@bot.command(
name="all_challenges",
help="list all visible challenges. solved or not. ",
aliases=["all", "allc", "ac"],
)
async def list_all(ctx, *, tags=None):
if await isRegistered(ctx) == False:
return
if await inPublicChannel(
ctx, msg=f"Hey, <@{ctx.author.id}>, don't view challenges in public channels..."
):
return
if ctfRunning() == False:
await ctx.send("CTF isn't running yet")
return
with db.db_session:
user = db.User.get(name=username(ctx))
challs = db.get_unlocked_challenges(user)
# It'd be nice to show a percentage complete as well...
#
# don't show teammates challenges or your own challenges. !bstat to see yours. helps prevent a teammate working on your challenges when they couldn't submit it anyway.
res = list()
if tags == None:
res = [
(
c.id,
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 challs
if c.id > 0 and c.author not in db.getTeammates(user)
]
else:
tags = tags.split(" ")
includes = [x for x in tags if x.startswith("!") == False]
excludes = [x[1:] for x in tags if x.startswith("!")]
if SETTINGS["_debug"] and SETTINGS["_debug_level"] >= 1:
logger.debug(
f"tags: {tags}; filter including {includes}; excluding {excludes}"
)
for chall in challs:
chall_tags = [t.name for t in chall.tags]
if anyIn(
excludes, chall_tags
): # kick it back if any of the excludes are in the chall_tags
continue
if (
len(includes) > 0 and anyIn(includes, chall_tags) == False
): # if it doesn't have any of the includes, skip it.
continue
if chall.id < 1 or chall.author in db.getTeammates(
user
): # other reasons to skip this challenge...
continue
res += [
[
chall.id,
chall.author.name,
chall.title,
db.challValue(chall),
f"{db.percentComplete(chall, user)}%",
"*"
* int(
db.avg(r.value for r in db.Rating if r.challenge == chall)
or 0
),
", ".join(chall_tags),
]
]
res.insert(0, ["ID", "Author", "Title", "Total Value", "Done", "Rating", "Tags"])
table = GithubFlavoredMarkdownTable(res)
# logger.debug("discord",challs)
msg = f"Showing all unlocked challenges"
await ctx.send(msg)
await sendBigMessage(ctx, table.table)
#
@bot.command(
name="view",