repo stringlengths 7 90 | file_url stringlengths 81 315 | file_path stringlengths 4 228 | content stringlengths 0 32.8k | language stringclasses 1 value | license stringclasses 7 values | commit_sha stringlengths 40 40 | retrieved_at stringdate 2026-01-04 14:38:15 2026-01-05 02:33:18 | truncated bool 2 classes |
|---|---|---|---|---|---|---|---|---|
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/MapleCTF/2023/misc/Maple_Island/server.py | ctfs/MapleCTF/2023/misc/Maple_Island/server.py | import os
import time
import random
from secrets import SECRET_FLAG_TEXT, create_a_perfect_world
CONTESTANTS_PER_SIDE = 20
def generate_contestants():
ones = []
zeroes = []
oprefs = []
zprefs = []
while len(ones) < CONTESTANTS_PER_SIDE or len(zeroes) < CONTESTANTS_PER_SIDE:
contestant = os.urandom(4);
if contestant[-1] % 2 == 0 and len(zeroes) < CONTESTANTS_PER_SIDE:
zeroes.append(contestant)
elif contestant[-1] % 2 == 1 and len(ones) < CONTESTANTS_PER_SIDE:
ones.append(contestant)
for i in range(CONTESTANTS_PER_SIDE):
oprefs.append(random.sample(zeroes, len(zeroes)))
zprefs.append(random.sample(ones, len(ones)))
return (ones, zeroes, oprefs, zprefs)
def xor_streams(otp, flag):
assert len(otp) == len(flag)
return b"".join([int.to_bytes(x ^ y) for x, y in zip(otp, flag)])
print("""
WELCOME TO MAPLE ISLAND <3
---------------------------------
The name of the game is simple. It's love. They say opposites attract.
You know like North and South, Hot and Cold, etc. The same is said to
be true for parity too, the odd (the ones) and even DWORDS (the zeroes)
have always had quite steamy and passionate relationships.
Historically speaking, tradition was paramount for this species. The
zeroes scour the world in hopes of find their special One. (Where do
you think the saying comes from? duh.) However, we are in the 21st
century and must adapt to the new.
So, we made an entire reality TV show about it. The premise is simple:
Screw tradition, in this show, only the Ones are allowed to court the
zeroes.
Stay tuned for the most drama-filled season of Maple Island as of yet
with even more tears, arguments, and passionate moments than ever before.
Will every match made in Maple heaven be stable?
Maple Island streaming next month on MapleTV!
But wait, lucky viewers have a chance to catch exclusive early-access content
if they can solve the following puzzle below and text the answer to 1-800-MAPLE-1337.
""")
# just for readability on terminal
time.sleep(2)
ones, zeroes, oprefs, zprefs = generate_contestants()
otp = b''
for couple in create_a_perfect_world(ones, zeroes, oprefs, zprefs):
otp += couple
ctext = xor_streams(otp, SECRET_FLAG_TEXT)
print(f"""
ones: {ones}
zeroes: {zeroes}
oprefs: {oprefs}
zprefs: {zprefs}
ctext: {ctext}
""")
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/MapleCTF/2023/misc/cjail/jail.py | ctfs/MapleCTF/2023/misc/cjail/jail.py | import os, re
lines = input("input c: ")
while True:
line = input()
lines += "\n"
lines += line
if line == "": break
if re.search(r'[{][^}]', lines) or re.search(r'[^{][}]', lines):
quit() # disallow function declarations
elif re.search(r';', lines):
quit() # disallow function calls
elif re.search(r'#', lines):
quit() # disallow includes
elif re.search(r'%', lines) or re.search(r'\?', lines) or re.search(r'<', lines):
quit() # disallow digraphs and trigraphs
elif re.search(r'_', lines):
quit()
elif re.search(r'system', lines):
quit() # a little more pain
else:
with open("safe.c", "w") as file:
file.write(lines)
os.system("cc safe.c")
os.system("./a.out")
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/MapleCTF/2023/misc/A_Quantum_Symphony/server.py | ctfs/MapleCTF/2023/misc/A_Quantum_Symphony/server.py | #!/usr/bin/env python3
from qiskit import QuantumCircuit
import qiskit.quantum_info as qi
from base64 import b64decode
from secret import CHORD_PROGRESSION, FLAG, LORE
QUBITS = 4
# No flat notes because they're just enharmonic to the sharps
NOTE_MAP = {
'0000': 'C',
'0001': 'C#',
'0010': 'D',
'0011': 'D#',
'0100': 'E',
'0101': 'F',
'0110': 'F#',
'0111': 'G',
'1000': 'G#',
'1001': 'A',
'1010': 'A#',
'1011': 'B',
'1100': 'X', # misc note (aka ignore these)
'1101': 'X',
'1110': 'X',
'1111': 'X',
}
# legend says that one only requires the major and minor chords to unlock the secret gates
CHORD_MAP = {
'Cmaj' : {'C', 'E', 'G'},
'C#maj': {'C#', 'E#', 'G#'},
'Dmaj' : {'D', 'F#', 'A'},
'D#maj': {'D#', 'G', 'A#'},
'Emaj' : {'E', 'G#', 'B'},
'Fmaj' : {'F', 'A', 'C'},
'Gmaj' : {'G', 'B', 'D'},
'G#maj': {'G#', 'C', 'D#'},
'Amaj' : {'A', 'C#', 'E'},
'A#maj': {'A#', 'D', 'F'},
'Bmaj' : {'N', 'D', 'F#'},
'Cmin' : {'C', 'D#', 'G'},
'C#min': {'C#', 'E', 'G#'},
'Dmin' : {'D', 'F', 'A'},
'D#min': {'D#', 'F#', 'A#'},
'Emin' : {'E', 'G', 'B'},
'Fmin' : {'F', 'G#', 'C'},
'F#min': {'F#', 'A', 'C#'},
'Gmin' : {'G', 'A#', 'D'},
'G#min': {'G#', 'B', 'D#'},
'Amin' : {'A', 'C', 'E'},
'A#min': {'A#', 'C#', 'F'},
'Bmin' : {'B', 'D', 'F#'}
}
def get_chord_from_sv(state_vector) -> str:
'''
Returns the correct chord from the CHORD_MAP corresponding to the superposition of the
'''
state_to_probability_map = [(bin(i)[2:].rjust(QUBITS, '0'), state_vector[i].real ** 2) for i in range(len(state_vector))]
state_to_probability_map.sort(key=lambda pair: pair[1], reverse=True)
notes = set()
for i in range(3):
qubit_state, probability = state_to_probability_map[i]
notes.add(NOTE_MAP[qubit_state])
if notes in CHORD_MAP.values():
for chord in CHORD_MAP.keys():
if notes == CHORD_MAP[chord]:
return chord
return 'INVALID_CHORD'
def get_circuit():
try:
qasm_str = b64decode(input("\nThe device demands an OpenQASM string encoded in base 64 from you: ")).decode()
except:
print("The device makes some angry noises. Perhaps there was an error decoding b64!")
exit(0)
try:
circ = QuantumCircuit.from_qasm_str(qasm_str)
circ.remove_final_measurements(inplace=True)
except:
print("The device looks sick from your Circuit. It advises you to use the Qiskit Transpiler in order to decompose your circuit into the basis gates (Rx. Ry, Rz, CNOT)")
exit(0)
if circ.num_qubits != QUBITS:
print(f"Your quantum circuit acts on {circ.num_qubits} instead of {QUBITS} qubits!")
exit(0)
return circ
def main():
print(LORE)
for chord in CHORD_PROGRESSION:
circ = get_circuit()
sv = qi.Statevector.from_instruction(circ)
# Note from an anonymous NSA cryptanalyst:
# I wish there was some way I could convert a zero state vector to any arbitrary state vector of my choosing,,, I feel like I'm so close.
input_chord = get_chord_from_sv(sv)
if input_chord != chord:
print("You entered the wrong chord")
print(f"the chord you entered: {input_chord}")
print('Good bye!')
exit(0)
print("Gears start shifting...")
print("I think you entered the correct chord!")
print("Woah... The device is shaking..,")
print("The device has been unlocked.")
print("you see a piece of paper hidden away inside, securely between the gears.")
print("You pick it up and begin to read it:")
print(FLAG)
if __name__ == "__main__":
main()
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/MapleCTF/2023/misc/AaaS/server.py | ctfs/MapleCTF/2023/misc/AaaS/server.py | import socketserver, string
def check_safe(line):
return all(c in (string.ascii_letters + string.digits + string.whitespace + '+=#').encode() for c in line)
class AaaSHandler(socketserver.BaseRequestHandler):
def handle(self):
conn = self.request
try:
buf, env = bytearray(), {}
while data := conn.recv(1024):
buf += data
if b'\n' in buf:
line, buf = buf.split(b'\n', 2)
if check_safe(line):
exec(line, {}, env)
conn.send(str(env).encode() + b'\n')
else:
conn.send(b"This is just an adder, what are you trying to do :'(\n")
conn.close()
break
except Exception as e:
print(e)
conn.send(b'Do math properly dumbo >:(\n')
conn.close()
server = socketserver.ThreadingTCPServer(('0.0.0.0', 1337), AaaSHandler)
server.serve_forever() | python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/MapleCTF/2023/misc/Coinflip/server.py | ctfs/MapleCTF/2023/misc/Coinflip/server.py | from random import Random
from secret import FLAG
import signal
class Coin:
def __init__(self, coin_id):
self.random = Random(coin_id)
self.flips_left = 0
self.buffer = None
def flip(self):
if self.flips_left == 0:
self.buffer = self.random.getrandbits(32)
self.flips_left = 32
res = self.buffer & 1
self.buffer >>= 1
self.flips_left -= 1
return res
if __name__ == "__main__":
signal.alarm(60)
print("Welcome to Maple Betting!")
print("We'll be betting on the outcome of a fair coin flip.")
print("You'll start with $1 - try to make lots of money and you'll get flags!")
game_id = input("Which coin would you like to use? ")
num_rounds = input("How many rounds do you want to go for? ")
num_rounds = int(num_rounds)
if num_rounds > 20_000_000:
print("Can't play that long, I'm afraid.")
exit(1)
print("Alright, let's go!")
coin = Coin(int(game_id, 0))
money = 1
for nr in range(num_rounds):
money += [1, -1][coin.flip()]
if money <= 0:
print(f"Oops, you went broke at round {nr+1}!")
exit(1)
print(f"You finished with ${money} in the pot.")
if money < 18_000:
print("At least you didn't go broke!")
elif money < 7_000_000:
print(f"Pretty good!")
else:
print(f"What the hell?! You bankrupted the casino! Take your spoils: {FLAG}")
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/MapleCTF/2023/pwn/db/dist/web.py | ctfs/MapleCTF/2023/pwn/db/dist/web.py | import functools
import bottle
from bottle import abort, request, response, route, run, template, view
from db import Db
db = Db('film.db')
@route('/')
@view('index.html')
def index():
offset = int(request.query.skip or 0)
term = request.query.term or ''
films = db.execute(
b"select tconst, title, year from title\
where title like '%"+term.encode('latin1')+b"%'\
limit 50 offset "+str(offset).encode('latin1')+b";"
)
return dict(term=term, films=films)
@route('/film/<id:int>')
@view('film.html')
def film(id):
results = db.execute(b"select title, year from title where tconst="+str(id).encode('latin1')+b";")
if len(results) == 0:
abort(404, 'Film not found')
title, year = results[0]
names = db.execute(
b"select name.nconst, name.name, category.name from principal\
join name on principal.nconst=name.nconst\
join category on id=category\
where tconst="+str(id).encode('latin1')+b";"
)
return dict(title=title, year=year, names=names)
@route('/person/<id:int>')
@view('person.html')
def film(id):
results = db.execute(b"select name, birth_year from name where nconst="+str(id).encode('latin1')+b";")
if len(results) == 0:
abort(404, 'Person not found')
name, birth_year = results[0]
films = db.execute(
b"select title.tconst, title, year from principal\
join title on principal.tconst=title.tconst\
where nconst="+str(id).encode('latin1')+b";"
)
return dict(name=name, birth_year=birth_year, films=films)
bottle.FormsDict.input_encoding = 'latin1'
run(host='0.0.0.0', port=8080)
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/MapleCTF/2023/pwn/db/dist/db.py | ctfs/MapleCTF/2023/pwn/db/dist/db.py | import sys
from struct import pack, unpack
from subprocess import PIPE, Popen
from threading import Thread
from collections import defaultdict
DB_TIMEOUT = 5.0
class DbException(Exception):
def __init__(self, msg):
super().__init__(msg)
class Db:
def __init__(self, db_file):
self.db_file = db_file
self.proc = None
self.rows = None
self.exception = None
self.done = False
self.open()
def __enter__(self):
return self
def __exit__(self, ty, val, tb):
self.proc.stdin.close()
self.proc.wait(timeout=1)
self.proc.terminate()
def open(self):
if self.proc is not None and self.proc.poll() is not None:
self.proc.kill()
self.proc = Popen(['./db', self.db_file], stdin=PIPE, stdout=PIPE)
def execute(self, cmd):
try:
self.proc.stdin.write(pack('H', len(cmd)) + cmd)
self.proc.stdin.flush()
except BrokenPipeError:
print('reopening database')
self.open()
return self.execute(cmd)
self.rows = []
self.exception = None
self.done = False
t = Thread(target=self.read_rows_timeout)
t.start()
t.join(DB_TIMEOUT)
if self.exception is not None:
raise self.exception
return self.rows
def read_rows_timeout(self):
try:
for row in self.read_rows():
self.rows.append(row)
self.done = True
except DbException as e:
self.exception = e
def read_resp(self):
ty = self.proc.stdout.read(1)
match ty:
case b'':
return None
case b'D':
return self.read_row()
case b'X':
l, = unpack('H', self.proc.stdout.read(2))
return DbException(self.proc.stdout.read(l))
case b'I':
l, = unpack('H', self.proc.stdout.read(2))
data = self.proc.stdout.read(l)
return [b'db returned info:', data, len(self.rows)]
case b'E':
return None
case _:
return [b'db returned other:', ty, len(self.rows)]
def read_rows(self):
e = None
while (r := self.read_resp()) is not None:
if isinstance(r, Exception):
e = r
elif isinstance(r, bytes):
yield r.decode('latin1')
else:
yield r
if e is not None:
raise e
def read_row(self):
data = []
cols = self.proc.stdout.read(1)[0]
for i in range(cols):
match self.proc.stdout.read(1):
case b'i':
data.append(unpack('i', self.proc.stdout.read(4))[0])
case b'b':
l, = unpack('H', self.proc.stdout.read(2))
s = self.proc.stdout.read(l).decode('utf8', 'backslashreplace')
data.append(s)
return tuple(data)
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/MapleCTF/2023/rev/mostly_harmless/src/output.py | ctfs/MapleCTF/2023/rev/mostly_harmless/src/output.py | from typing import TypeVar, Generic
T = TypeVar("T", contravariant=True)
class Z: ...
class N(Generic[T]): ...
class ML(Generic[T]): ...
class MR(Generic[T]): ...
class L_a(Generic[T]): ...
class L_b(Generic[T]): ...
class L_c(Generic[T]): ...
class L_d(Generic[T]): ...
class L_e(Generic[T]): ...
class L_f(Generic[T]): ...
class L_g(Generic[T]): ...
class L_h(Generic[T]): ...
class L_i(Generic[T]): ...
class L_j(Generic[T]): ...
class L_k(Generic[T]): ...
class L_l(Generic[T]): ...
class L_m(Generic[T]): ...
class L_n(Generic[T]): ...
class L_o(Generic[T]): ...
class L_p(Generic[T]): ...
class L_q(Generic[T]): ...
class L_r(Generic[T]): ...
class L_s(Generic[T]): ...
class L_t(Generic[T]): ...
class L_u(Generic[T]): ...
class L_v(Generic[T]): ...
class L_w(Generic[T]): ...
class L_x(Generic[T]): ...
class L_y(Generic[T]): ...
class L_z(Generic[T]): ...
class L__(Generic[T]): ...
class L___TAPE_END__(Generic[T]): ...
class QLR_s01(Generic[T]): ...
class QLR_s02(Generic[T]): ...
class QLR_s03(Generic[T]): ...
class QLR_s04(Generic[T]): ...
class QLR_s05(Generic[T]): ...
class QLR_s06(Generic[T]): ...
class QLR_s07(Generic[T]): ...
class QLR_s08(Generic[T]): ...
class QLR_s09(Generic[T]): ...
class QLR_s10(Generic[T]): ...
class QLR_s11(Generic[T]): ...
class QLR_s16(Generic[T]): ...
class QLR_s12(Generic[T]): ...
class QLR_s13(Generic[T]): ...
class QLR_s14(Generic[T]): ...
class QLR_s15(Generic[T]): ...
class QLR_s17(Generic[T]): ...
class QLR_s18(Generic[T]): ...
class QLR_s19(Generic[T]): ...
class QLR_s20(Generic[T]): ...
class QLR_s21(Generic[T]): ...
class QLR_s22(Generic[T]): ...
class QLR_s23(Generic[T]): ...
class QLR_s24(Generic[T]): ...
class QLR_s25(Generic[T]): ...
class QLR_s26(Generic[T]): ...
class QLR_s27(Generic[T]): ...
class QLR_s28(Generic[T]): ...
class QLR_s29(Generic[T]): ...
class QLR_s30(Generic[T]): ...
class QLR_s31(Generic[T]): ...
class QLR_s32(Generic[T]): ...
class QLR_s33(Generic[T]): ...
class QLR_s34(Generic[T]): ...
class QLR_s35(Generic[T]): ...
class QLR_s36(Generic[T]): ...
class QLR_s37(Generic[T]): ...
class QLR_s38(Generic[T]): ...
class QLR_s39(Generic[T]): ...
class QLR_s40(Generic[T]): ...
class QLR_s41(Generic[T]): ...
class QLR_s42(Generic[T]): ...
class QLR_s43(Generic[T]): ...
class QLR_s44(Generic[T]): ...
class QLR_s45(Generic[T]): ...
class QLR_s46(Generic[T]): ...
class QLR_s47(Generic[T]): ...
class QLR_s48(Generic[T]): ...
class QLR_s49(Generic[T]): ...
class QLR_s50(Generic[T]): ...
class QLR_s51(Generic[T]): ...
class QLR_s52(Generic[T]): ...
class QLR_s53(Generic[T]): ...
class QLR_s54(Generic[T]): ...
class QLR_s55(Generic[T]): ...
class QLR_s56(Generic[T]): ...
class QLR_s57(Generic[T]): ...
class QLR_s58(Generic[T]): ...
class QLR_s59(Generic[T]): ...
class QLR_s60(Generic[T]): ...
class QLR_s61(Generic[T]): ...
class QLR_s62(Generic[T]): ...
class QLR_s63(Generic[T]): ...
class QLR_s64(Generic[T]): ...
class QLR_s65(Generic[T]): ...
class QLR_s66(Generic[T]): ...
class QLR_s67(Generic[T]): ...
class QLR_s69(Generic[T]): ...
class QLR_s68(Generic[T]): ...
class QLR_s70(Generic[T]): ...
class QLR_s71(Generic[T]): ...
class QRL_s01(Generic[T]): ...
class QRL_s02(Generic[T]): ...
class QRL_s03(Generic[T]): ...
class QRL_s04(Generic[T]): ...
class QRL_s05(Generic[T]): ...
class QRL_s06(Generic[T]): ...
class QRL_s07(Generic[T]): ...
class QRL_s08(Generic[T]): ...
class QRL_s09(Generic[T]): ...
class QRL_s10(Generic[T]): ...
class QRL_s11(Generic[T]): ...
class QRL_s16(Generic[T]): ...
class QRL_s12(Generic[T]): ...
class QRL_s13(Generic[T]): ...
class QRL_s14(Generic[T]): ...
class QRL_s15(Generic[T]): ...
class QRL_s17(Generic[T]): ...
class QRL_s18(Generic[T]): ...
class QRL_s19(Generic[T]): ...
class QRL_s20(Generic[T]): ...
class QRL_s21(Generic[T]): ...
class QRL_s22(Generic[T]): ...
class QRL_s23(Generic[T]): ...
class QRL_s24(Generic[T]): ...
class QRL_s25(Generic[T]): ...
class QRL_s26(Generic[T]): ...
class QRL_s27(Generic[T]): ...
class QRL_s28(Generic[T]): ...
class QRL_s29(Generic[T]): ...
class QRL_s30(Generic[T]): ...
class QRL_s31(Generic[T]): ...
class QRL_s32(Generic[T]): ...
class QRL_s33(Generic[T]): ...
class QRL_s34(Generic[T]): ...
class QRL_s35(Generic[T]): ...
class QRL_s36(Generic[T]): ...
class QRL_s37(Generic[T]): ...
class QRL_s38(Generic[T]): ...
class QRL_s39(Generic[T]): ...
class QRL_s40(Generic[T]): ...
class QRL_s41(Generic[T]): ...
class QRL_s42(Generic[T]): ...
class QRL_s43(Generic[T]): ...
class QRL_s44(Generic[T]): ...
class QRL_s45(Generic[T]): ...
class QRL_s46(Generic[T]): ...
class QRL_s47(Generic[T]): ...
class QRL_s48(Generic[T]): ...
class QRL_s49(Generic[T]): ...
class QRL_s50(Generic[T]): ...
class QRL_s51(Generic[T]): ...
class QRL_s52(Generic[T]): ...
class QRL_s53(Generic[T]): ...
class QRL_s54(Generic[T]): ...
class QRL_s55(Generic[T]): ...
class QRL_s56(Generic[T]): ...
class QRL_s57(Generic[T]): ...
class QRL_s58(Generic[T]): ...
class QRL_s59(Generic[T]): ...
class QRL_s60(Generic[T]): ...
class QRL_s61(Generic[T]): ...
class QRL_s62(Generic[T]): ...
class QRL_s63(Generic[T]): ...
class QRL_s64(Generic[T]): ...
class QRL_s65(Generic[T]): ...
class QRL_s66(Generic[T]): ...
class QRL_s67(Generic[T]): ...
class QRL_s69(Generic[T]): ...
class QRL_s68(Generic[T]): ...
class QRL_s70(Generic[T]): ...
class QRL_s71(Generic[T]): ...
class E(Generic[T], QLR_s29["N[QRW_s29[E[E[T]]]]"], QLR_s01["N[QRW_s01[E[E[T]]]]"], QLR_s12["N[QRW_s12[E[E[T]]]]"], QLR_s02["N[QRW_s02[E[E[T]]]]"], QLR_s30["N[QRW_s30[E[E[T]]]]"], QLR_s03["N[QRW_s03[E[E[T]]]]"], QLR_s05["N[QRW_s05[E[E[T]]]]"], QLR_s04["N[QRW_s04[E[E[T]]]]"], QLR_s16["N[QRW_s16[E[E[T]]]]"], QLR_s45["N[QRW_s45[E[E[T]]]]"], QLR_s06["N[QRW_s06[E[E[T]]]]"], QLR_s46["N[QRW_s46[E[E[T]]]]"], QLR_s07["N[QRW_s07[E[E[T]]]]"], QLR_s24["N[QRW_s24[E[E[T]]]]"], QLR_s08["N[QRW_s08[E[E[T]]]]"], QLR_s61["N[QRW_s61[E[E[T]]]]"], QLR_s09["N[QRW_s09[E[E[T]]]]"], QLR_s58["N[QRW_s58[E[E[T]]]]"], QLR_s10["N[QRW_s10[E[E[T]]]]"], QLR_s68["N[QRW_s68[E[E[T]]]]"], QLR_s11["N[QRW_s11[E[E[T]]]]"], QLR_s19["N[QRW_s19[E[E[T]]]]"], QLR_s13["N[QRW_s13[E[E[T]]]]"], QLR_s40["N[QRW_s40[E[E[T]]]]"], QLR_s14["N[QRW_s14[E[E[T]]]]"], QLR_s38["N[QRW_s38[E[E[T]]]]"], QLR_s15["N[QRW_s15[E[E[T]]]]"], QLR_s65["N[QRW_s65[E[E[T]]]]"], QLR_s67["N[QRW_s67[E[E[T]]]]"], QLR_s17["N[QRW_s17[E[E[T]]]]"], QLR_s18["N[QRW_s18[E[E[T]]]]"], QLR_s39["N[QRW_s39[E[E[T]]]]"], QLR_s20["N[QRW_s20[E[E[T]]]]"], QLR_s27["N[QRW_s27[E[E[T]]]]"], QLR_s21["N[QRW_s21[E[E[T]]]]"], QLR_s43["N[QRW_s43[E[E[T]]]]"], QLR_s22["N[QRW_s22[E[E[T]]]]"], QLR_s51["N[QRW_s51[E[E[T]]]]"], QLR_s23["N[QRW_s23[E[E[T]]]]"], QLR_s63["N[QRW_s63[E[E[T]]]]"], QLR_s59["N[QRW_s59[E[E[T]]]]"], QLR_s25["N[QRW_s25[E[E[T]]]]"], QLR_s62["N[QRW_s62[E[E[T]]]]"], QLR_s26["N[QRW_s26[E[E[T]]]]"], QLR_s53["N[QRW_s53[E[E[T]]]]"], QLR_s28["N[QRW_s28[E[E[T]]]]"], QLR_s69["N[QRW_s69[E[E[T]]]]"], QLR_s31["N[QRW_s31[E[E[T]]]]"], QLR_s57["N[QRW_s57[E[E[T]]]]"], QLR_s32["N[QRW_s32[E[E[T]]]]"], QLR_s33["N[QRW_s33[E[E[T]]]]"], QLR_s34["N[QRW_s34[E[E[T]]]]"], QLR_s66["N[QRW_s66[E[E[T]]]]"], QLR_s35["N[QRW_s35[E[E[T]]]]"], QLR_s36["N[QRW_s36[E[E[T]]]]"], QLR_s37["N[QRW_s37[E[E[T]]]]"], QLR_s70["N[QRW_s70[E[E[T]]]]"], QLR_s41["N[QRW_s41[E[E[T]]]]"], QLR_s55["N[QRW_s55[E[E[T]]]]"], QLR_s42["N[QRW_s42[E[E[T]]]]"], QLR_s52["N[QRW_s52[E[E[T]]]]"], QLR_s60["N[QRW_s60[E[E[T]]]]"], QLR_s44["N[QRW_s44[E[E[T]]]]"], QLR_s64["N[QRW_s64[E[E[T]]]]"], QLR_s71["N[QRW_s71[E[E[T]]]]"], QLR_s47["N[QRW_s47[E[E[T]]]]"], QLR_s48["N[QRW_s48[E[E[T]]]]"], QLR_s49["N[QRW_s49[E[E[T]]]]"], QLR_s56["N[QRW_s56[E[E[T]]]]"], QLR_s50["N[QRW_s50[E[E[T]]]]"], QLR_s54["N[QRW_s54[E[E[T]]]]"], QRL_s29["N[QLW_s29[E[E[T]]]]"], QRL_s01["N[QLW_s01[E[E[T]]]]"], QRL_s12["N[QLW_s12[E[E[T]]]]"], QRL_s02["N[QLW_s02[E[E[T]]]]"], QRL_s30["N[QLW_s30[E[E[T]]]]"], QRL_s03["N[QLW_s03[E[E[T]]]]"], QRL_s05["N[QLW_s05[E[E[T]]]]"], QRL_s04["N[QLW_s04[E[E[T]]]]"], QRL_s16["N[QLW_s16[E[E[T]]]]"], QRL_s45["N[QLW_s45[E[E[T]]]]"], QRL_s06["N[QLW_s06[E[E[T]]]]"], QRL_s46["N[QLW_s46[E[E[T]]]]"], QRL_s07["N[QLW_s07[E[E[T]]]]"], QRL_s24["N[QLW_s24[E[E[T]]]]"], QRL_s08["N[QLW_s08[E[E[T]]]]"], QRL_s61["N[QLW_s61[E[E[T]]]]"], QRL_s09["N[QLW_s09[E[E[T]]]]"], QRL_s58["N[QLW_s58[E[E[T]]]]"], QRL_s10["N[QLW_s10[E[E[T]]]]"], QRL_s68["N[QLW_s68[E[E[T]]]]"], QRL_s11["N[QLW_s11[E[E[T]]]]"], QRL_s19["N[QLW_s19[E[E[T]]]]"], QRL_s13["N[QLW_s13[E[E[T]]]]"], QRL_s40["N[QLW_s40[E[E[T]]]]"], QRL_s14["N[QLW_s14[E[E[T]]]]"], QRL_s38["N[QLW_s38[E[E[T]]]]"], QRL_s15["N[QLW_s15[E[E[T]]]]"], QRL_s65["N[QLW_s65[E[E[T]]]]"], QRL_s67["N[QLW_s67[E[E[T]]]]"], QRL_s17["N[QLW_s17[E[E[T]]]]"], QRL_s18["N[QLW_s18[E[E[T]]]]"], QRL_s39["N[QLW_s39[E[E[T]]]]"], QRL_s20["N[QLW_s20[E[E[T]]]]"], QRL_s27["N[QLW_s27[E[E[T]]]]"], QRL_s21["N[QLW_s21[E[E[T]]]]"], QRL_s43["N[QLW_s43[E[E[T]]]]"], QRL_s22["N[QLW_s22[E[E[T]]]]"], QRL_s51["N[QLW_s51[E[E[T]]]]"], QRL_s23["N[QLW_s23[E[E[T]]]]"], QRL_s63["N[QLW_s63[E[E[T]]]]"], QRL_s59["N[QLW_s59[E[E[T]]]]"], QRL_s25["N[QLW_s25[E[E[T]]]]"], QRL_s62["N[QLW_s62[E[E[T]]]]"], QRL_s26["N[QLW_s26[E[E[T]]]]"], QRL_s53["N[QLW_s53[E[E[T]]]]"], QRL_s28["N[QLW_s28[E[E[T]]]]"], QRL_s69["N[QLW_s69[E[E[T]]]]"], QRL_s31["N[QLW_s31[E[E[T]]]]"], QRL_s57["N[QLW_s57[E[E[T]]]]"], QRL_s32["N[QLW_s32[E[E[T]]]]"], QRL_s33["N[QLW_s33[E[E[T]]]]"], QRL_s34["N[QLW_s34[E[E[T]]]]"], QRL_s66["N[QLW_s66[E[E[T]]]]"], QRL_s35["N[QLW_s35[E[E[T]]]]"], QRL_s36["N[QLW_s36[E[E[T]]]]"], QRL_s37["N[QLW_s37[E[E[T]]]]"], QRL_s70["N[QLW_s70[E[E[T]]]]"], QRL_s41["N[QLW_s41[E[E[T]]]]"], QRL_s55["N[QLW_s55[E[E[T]]]]"], QRL_s42["N[QLW_s42[E[E[T]]]]"], QRL_s52["N[QLW_s52[E[E[T]]]]"], QRL_s60["N[QLW_s60[E[E[T]]]]"], QRL_s44["N[QLW_s44[E[E[T]]]]"], QRL_s64["N[QLW_s64[E[E[T]]]]"], QRL_s71["N[QLW_s71[E[E[T]]]]"], QRL_s47["N[QLW_s47[E[E[T]]]]"], QRL_s48["N[QLW_s48[E[E[T]]]]"], QRL_s49["N[QLW_s49[E[E[T]]]]"], QRL_s56["N[QLW_s56[E[E[T]]]]"], QRL_s50["N[QLW_s50[E[E[T]]]]"], QRL_s54["N[QLW_s54[E[E[T]]]]"]): ...
class QLW_s01(Generic[T], ML["N[QL_s01[T]]"], MR["N[QLW_s01[MR[N[T]]]]"], L_a["N[QLW_s01[L_a[N[T]]]]"], L_x["N[QLW_s01[L_x[N[T]]]]"], L_c["N[QLW_s01[L_c[N[T]]]]"], L_d["N[QLW_s01[L_d[N[T]]]]"], L_e["N[QLW_s01[L_e[N[T]]]]"], L_f["N[QLW_s01[L_f[N[T]]]]"], L_g["N[QLW_s01[L_g[N[T]]]]"], L_h["N[QLW_s01[L_h[N[T]]]]"], L_i["N[QLW_s01[L_i[N[T]]]]"], L_l["N[QLW_s01[L_l[N[T]]]]"], L_m["N[QLW_s01[L_m[N[T]]]]"], L_n["N[QLW_s01[L_n[N[T]]]]"], L_o["N[QLW_s01[L_o[N[T]]]]"], L_p["N[QLW_s01[L_p[N[T]]]]"], L_r["N[QLW_s01[L_r[N[T]]]]"], L_s["N[QLW_s01[L_s[N[T]]]]"], L_t["N[QLW_s01[L_t[N[T]]]]"], L_u["N[QLW_s01[L_u[N[T]]]]"], L_w["N[QLW_s01[L_w[N[T]]]]"], L_y["N[QLW_s01[L_y[N[T]]]]"], L__["N[QLW_s01[L__[N[T]]]]"], L___TAPE_END__["N[QLW_s01[L___TAPE_END__[N[T]]]]"], E["QLR_s01[N[T]]"]): ...
class QRW_s01(Generic[T], MR["N[QR_s01[T]]"], ML["N[QRW_s01[ML[N[T]]]]"], L_a["N[QRW_s01[L_a[N[T]]]]"], L_x["N[QRW_s01[L_x[N[T]]]]"], L_c["N[QRW_s01[L_c[N[T]]]]"], L_d["N[QRW_s01[L_d[N[T]]]]"], L_e["N[QRW_s01[L_e[N[T]]]]"], L_f["N[QRW_s01[L_f[N[T]]]]"], L_g["N[QRW_s01[L_g[N[T]]]]"], L_h["N[QRW_s01[L_h[N[T]]]]"], L_i["N[QRW_s01[L_i[N[T]]]]"], L_l["N[QRW_s01[L_l[N[T]]]]"], L_m["N[QRW_s01[L_m[N[T]]]]"], L_n["N[QRW_s01[L_n[N[T]]]]"], L_o["N[QRW_s01[L_o[N[T]]]]"], L_p["N[QRW_s01[L_p[N[T]]]]"], L_r["N[QRW_s01[L_r[N[T]]]]"], L_s["N[QRW_s01[L_s[N[T]]]]"], L_t["N[QRW_s01[L_t[N[T]]]]"], L_u["N[QRW_s01[L_u[N[T]]]]"], L_w["N[QRW_s01[L_w[N[T]]]]"], L_y["N[QRW_s01[L_y[N[T]]]]"], L__["N[QRW_s01[L__[N[T]]]]"], L___TAPE_END__["N[QRW_s01[L___TAPE_END__[N[T]]]]"], E["QRL_s01[N[T]]"]): ...
class QLW_s02(Generic[T], ML["N[QL_s02[T]]"], MR["N[QLW_s02[MR[N[T]]]]"], L_a["N[QLW_s02[L_a[N[T]]]]"], L_x["N[QLW_s02[L_x[N[T]]]]"], L_c["N[QLW_s02[L_c[N[T]]]]"], L_d["N[QLW_s02[L_d[N[T]]]]"], L_e["N[QLW_s02[L_e[N[T]]]]"], L_f["N[QLW_s02[L_f[N[T]]]]"], L_g["N[QLW_s02[L_g[N[T]]]]"], L_h["N[QLW_s02[L_h[N[T]]]]"], L_i["N[QLW_s02[L_i[N[T]]]]"], L_l["N[QLW_s02[L_l[N[T]]]]"], L_m["N[QLW_s02[L_m[N[T]]]]"], L_n["N[QLW_s02[L_n[N[T]]]]"], L_o["N[QLW_s02[L_o[N[T]]]]"], L_p["N[QLW_s02[L_p[N[T]]]]"], L_r["N[QLW_s02[L_r[N[T]]]]"], L_s["N[QLW_s02[L_s[N[T]]]]"], L_t["N[QLW_s02[L_t[N[T]]]]"], L_u["N[QLW_s02[L_u[N[T]]]]"], L_w["N[QLW_s02[L_w[N[T]]]]"], L_y["N[QLW_s02[L_y[N[T]]]]"], L__["N[QLW_s02[L__[N[T]]]]"], L___TAPE_END__["N[QLW_s02[L___TAPE_END__[N[T]]]]"], E["QLR_s02[N[T]]"]): ...
class QRW_s02(Generic[T], MR["N[QR_s02[T]]"], ML["N[QRW_s02[ML[N[T]]]]"], L_a["N[QRW_s02[L_a[N[T]]]]"], L_x["N[QRW_s02[L_x[N[T]]]]"], L_c["N[QRW_s02[L_c[N[T]]]]"], L_d["N[QRW_s02[L_d[N[T]]]]"], L_e["N[QRW_s02[L_e[N[T]]]]"], L_f["N[QRW_s02[L_f[N[T]]]]"], L_g["N[QRW_s02[L_g[N[T]]]]"], L_h["N[QRW_s02[L_h[N[T]]]]"], L_i["N[QRW_s02[L_i[N[T]]]]"], L_l["N[QRW_s02[L_l[N[T]]]]"], L_m["N[QRW_s02[L_m[N[T]]]]"], L_n["N[QRW_s02[L_n[N[T]]]]"], L_o["N[QRW_s02[L_o[N[T]]]]"], L_p["N[QRW_s02[L_p[N[T]]]]"], L_r["N[QRW_s02[L_r[N[T]]]]"], L_s["N[QRW_s02[L_s[N[T]]]]"], L_t["N[QRW_s02[L_t[N[T]]]]"], L_u["N[QRW_s02[L_u[N[T]]]]"], L_w["N[QRW_s02[L_w[N[T]]]]"], L_y["N[QRW_s02[L_y[N[T]]]]"], L__["N[QRW_s02[L__[N[T]]]]"], L___TAPE_END__["N[QRW_s02[L___TAPE_END__[N[T]]]]"], E["QRL_s02[N[T]]"]): ...
class QLW_s03(Generic[T], ML["N[QL_s03[T]]"], MR["N[QLW_s03[MR[N[T]]]]"], L_a["N[QLW_s03[L_a[N[T]]]]"], L_x["N[QLW_s03[L_x[N[T]]]]"], L_c["N[QLW_s03[L_c[N[T]]]]"], L_d["N[QLW_s03[L_d[N[T]]]]"], L_e["N[QLW_s03[L_e[N[T]]]]"], L_f["N[QLW_s03[L_f[N[T]]]]"], L_g["N[QLW_s03[L_g[N[T]]]]"], L_h["N[QLW_s03[L_h[N[T]]]]"], L_i["N[QLW_s03[L_i[N[T]]]]"], L_l["N[QLW_s03[L_l[N[T]]]]"], L_m["N[QLW_s03[L_m[N[T]]]]"], L_n["N[QLW_s03[L_n[N[T]]]]"], L_o["N[QLW_s03[L_o[N[T]]]]"], L_p["N[QLW_s03[L_p[N[T]]]]"], L_r["N[QLW_s03[L_r[N[T]]]]"], L_s["N[QLW_s03[L_s[N[T]]]]"], L_t["N[QLW_s03[L_t[N[T]]]]"], L_u["N[QLW_s03[L_u[N[T]]]]"], L_w["N[QLW_s03[L_w[N[T]]]]"], L_y["N[QLW_s03[L_y[N[T]]]]"], L__["N[QLW_s03[L__[N[T]]]]"], L___TAPE_END__["N[QLW_s03[L___TAPE_END__[N[T]]]]"], E["QLR_s03[N[T]]"]): ...
class QRW_s03(Generic[T], MR["N[QR_s03[T]]"], ML["N[QRW_s03[ML[N[T]]]]"], L_a["N[QRW_s03[L_a[N[T]]]]"], L_x["N[QRW_s03[L_x[N[T]]]]"], L_c["N[QRW_s03[L_c[N[T]]]]"], L_d["N[QRW_s03[L_d[N[T]]]]"], L_e["N[QRW_s03[L_e[N[T]]]]"], L_f["N[QRW_s03[L_f[N[T]]]]"], L_g["N[QRW_s03[L_g[N[T]]]]"], L_h["N[QRW_s03[L_h[N[T]]]]"], L_i["N[QRW_s03[L_i[N[T]]]]"], L_l["N[QRW_s03[L_l[N[T]]]]"], L_m["N[QRW_s03[L_m[N[T]]]]"], L_n["N[QRW_s03[L_n[N[T]]]]"], L_o["N[QRW_s03[L_o[N[T]]]]"], L_p["N[QRW_s03[L_p[N[T]]]]"], L_r["N[QRW_s03[L_r[N[T]]]]"], L_s["N[QRW_s03[L_s[N[T]]]]"], L_t["N[QRW_s03[L_t[N[T]]]]"], L_u["N[QRW_s03[L_u[N[T]]]]"], L_w["N[QRW_s03[L_w[N[T]]]]"], L_y["N[QRW_s03[L_y[N[T]]]]"], L__["N[QRW_s03[L__[N[T]]]]"], L___TAPE_END__["N[QRW_s03[L___TAPE_END__[N[T]]]]"], E["QRL_s03[N[T]]"]): ...
class QLW_s04(Generic[T], ML["N[QL_s04[T]]"], MR["N[QLW_s04[MR[N[T]]]]"], L_a["N[QLW_s04[L_a[N[T]]]]"], L_x["N[QLW_s04[L_x[N[T]]]]"], L_c["N[QLW_s04[L_c[N[T]]]]"], L_d["N[QLW_s04[L_d[N[T]]]]"], L_e["N[QLW_s04[L_e[N[T]]]]"], L_f["N[QLW_s04[L_f[N[T]]]]"], L_g["N[QLW_s04[L_g[N[T]]]]"], L_h["N[QLW_s04[L_h[N[T]]]]"], L_i["N[QLW_s04[L_i[N[T]]]]"], L_l["N[QLW_s04[L_l[N[T]]]]"], L_m["N[QLW_s04[L_m[N[T]]]]"], L_n["N[QLW_s04[L_n[N[T]]]]"], L_o["N[QLW_s04[L_o[N[T]]]]"], L_p["N[QLW_s04[L_p[N[T]]]]"], L_r["N[QLW_s04[L_r[N[T]]]]"], L_s["N[QLW_s04[L_s[N[T]]]]"], L_t["N[QLW_s04[L_t[N[T]]]]"], L_u["N[QLW_s04[L_u[N[T]]]]"], L_w["N[QLW_s04[L_w[N[T]]]]"], L_y["N[QLW_s04[L_y[N[T]]]]"], L__["N[QLW_s04[L__[N[T]]]]"], L___TAPE_END__["N[QLW_s04[L___TAPE_END__[N[T]]]]"], E["QLR_s04[N[T]]"]): ...
class QRW_s04(Generic[T], MR["N[QR_s04[T]]"], ML["N[QRW_s04[ML[N[T]]]]"], L_a["N[QRW_s04[L_a[N[T]]]]"], L_x["N[QRW_s04[L_x[N[T]]]]"], L_c["N[QRW_s04[L_c[N[T]]]]"], L_d["N[QRW_s04[L_d[N[T]]]]"], L_e["N[QRW_s04[L_e[N[T]]]]"], L_f["N[QRW_s04[L_f[N[T]]]]"], L_g["N[QRW_s04[L_g[N[T]]]]"], L_h["N[QRW_s04[L_h[N[T]]]]"], L_i["N[QRW_s04[L_i[N[T]]]]"], L_l["N[QRW_s04[L_l[N[T]]]]"], L_m["N[QRW_s04[L_m[N[T]]]]"], L_n["N[QRW_s04[L_n[N[T]]]]"], L_o["N[QRW_s04[L_o[N[T]]]]"], L_p["N[QRW_s04[L_p[N[T]]]]"], L_r["N[QRW_s04[L_r[N[T]]]]"], L_s["N[QRW_s04[L_s[N[T]]]]"], L_t["N[QRW_s04[L_t[N[T]]]]"], L_u["N[QRW_s04[L_u[N[T]]]]"], L_w["N[QRW_s04[L_w[N[T]]]]"], L_y["N[QRW_s04[L_y[N[T]]]]"], L__["N[QRW_s04[L__[N[T]]]]"], L___TAPE_END__["N[QRW_s04[L___TAPE_END__[N[T]]]]"], E["QRL_s04[N[T]]"]): ...
class QLW_s05(Generic[T], ML["N[QL_s05[T]]"], MR["N[QLW_s05[MR[N[T]]]]"], L_a["N[QLW_s05[L_a[N[T]]]]"], L_x["N[QLW_s05[L_x[N[T]]]]"], L_c["N[QLW_s05[L_c[N[T]]]]"], L_d["N[QLW_s05[L_d[N[T]]]]"], L_e["N[QLW_s05[L_e[N[T]]]]"], L_f["N[QLW_s05[L_f[N[T]]]]"], L_g["N[QLW_s05[L_g[N[T]]]]"], L_h["N[QLW_s05[L_h[N[T]]]]"], L_i["N[QLW_s05[L_i[N[T]]]]"], L_l["N[QLW_s05[L_l[N[T]]]]"], L_m["N[QLW_s05[L_m[N[T]]]]"], L_n["N[QLW_s05[L_n[N[T]]]]"], L_o["N[QLW_s05[L_o[N[T]]]]"], L_p["N[QLW_s05[L_p[N[T]]]]"], L_r["N[QLW_s05[L_r[N[T]]]]"], L_s["N[QLW_s05[L_s[N[T]]]]"], L_t["N[QLW_s05[L_t[N[T]]]]"], L_u["N[QLW_s05[L_u[N[T]]]]"], L_w["N[QLW_s05[L_w[N[T]]]]"], L_y["N[QLW_s05[L_y[N[T]]]]"], L__["N[QLW_s05[L__[N[T]]]]"], L___TAPE_END__["N[QLW_s05[L___TAPE_END__[N[T]]]]"], E["QLR_s05[N[T]]"]): ...
class QRW_s05(Generic[T], MR["N[QR_s05[T]]"], ML["N[QRW_s05[ML[N[T]]]]"], L_a["N[QRW_s05[L_a[N[T]]]]"], L_x["N[QRW_s05[L_x[N[T]]]]"], L_c["N[QRW_s05[L_c[N[T]]]]"], L_d["N[QRW_s05[L_d[N[T]]]]"], L_e["N[QRW_s05[L_e[N[T]]]]"], L_f["N[QRW_s05[L_f[N[T]]]]"], L_g["N[QRW_s05[L_g[N[T]]]]"], L_h["N[QRW_s05[L_h[N[T]]]]"], L_i["N[QRW_s05[L_i[N[T]]]]"], L_l["N[QRW_s05[L_l[N[T]]]]"], L_m["N[QRW_s05[L_m[N[T]]]]"], L_n["N[QRW_s05[L_n[N[T]]]]"], L_o["N[QRW_s05[L_o[N[T]]]]"], L_p["N[QRW_s05[L_p[N[T]]]]"], L_r["N[QRW_s05[L_r[N[T]]]]"], L_s["N[QRW_s05[L_s[N[T]]]]"], L_t["N[QRW_s05[L_t[N[T]]]]"], L_u["N[QRW_s05[L_u[N[T]]]]"], L_w["N[QRW_s05[L_w[N[T]]]]"], L_y["N[QRW_s05[L_y[N[T]]]]"], L__["N[QRW_s05[L__[N[T]]]]"], L___TAPE_END__["N[QRW_s05[L___TAPE_END__[N[T]]]]"], E["QRL_s05[N[T]]"]): ...
class QLW_s06(Generic[T], ML["N[QL_s06[T]]"], MR["N[QLW_s06[MR[N[T]]]]"], L_a["N[QLW_s06[L_a[N[T]]]]"], L_x["N[QLW_s06[L_x[N[T]]]]"], L_c["N[QLW_s06[L_c[N[T]]]]"], L_d["N[QLW_s06[L_d[N[T]]]]"], L_e["N[QLW_s06[L_e[N[T]]]]"], L_f["N[QLW_s06[L_f[N[T]]]]"], L_g["N[QLW_s06[L_g[N[T]]]]"], L_h["N[QLW_s06[L_h[N[T]]]]"], L_i["N[QLW_s06[L_i[N[T]]]]"], L_l["N[QLW_s06[L_l[N[T]]]]"], L_m["N[QLW_s06[L_m[N[T]]]]"], L_n["N[QLW_s06[L_n[N[T]]]]"], L_o["N[QLW_s06[L_o[N[T]]]]"], L_p["N[QLW_s06[L_p[N[T]]]]"], L_r["N[QLW_s06[L_r[N[T]]]]"], L_s["N[QLW_s06[L_s[N[T]]]]"], L_t["N[QLW_s06[L_t[N[T]]]]"], L_u["N[QLW_s06[L_u[N[T]]]]"], L_w["N[QLW_s06[L_w[N[T]]]]"], L_y["N[QLW_s06[L_y[N[T]]]]"], L__["N[QLW_s06[L__[N[T]]]]"], L___TAPE_END__["N[QLW_s06[L___TAPE_END__[N[T]]]]"], E["QLR_s06[N[T]]"]): ...
class QRW_s06(Generic[T], MR["N[QR_s06[T]]"], ML["N[QRW_s06[ML[N[T]]]]"], L_a["N[QRW_s06[L_a[N[T]]]]"], L_x["N[QRW_s06[L_x[N[T]]]]"], L_c["N[QRW_s06[L_c[N[T]]]]"], L_d["N[QRW_s06[L_d[N[T]]]]"], L_e["N[QRW_s06[L_e[N[T]]]]"], L_f["N[QRW_s06[L_f[N[T]]]]"], L_g["N[QRW_s06[L_g[N[T]]]]"], L_h["N[QRW_s06[L_h[N[T]]]]"], L_i["N[QRW_s06[L_i[N[T]]]]"], L_l["N[QRW_s06[L_l[N[T]]]]"], L_m["N[QRW_s06[L_m[N[T]]]]"], L_n["N[QRW_s06[L_n[N[T]]]]"], L_o["N[QRW_s06[L_o[N[T]]]]"], L_p["N[QRW_s06[L_p[N[T]]]]"], L_r["N[QRW_s06[L_r[N[T]]]]"], L_s["N[QRW_s06[L_s[N[T]]]]"], L_t["N[QRW_s06[L_t[N[T]]]]"], L_u["N[QRW_s06[L_u[N[T]]]]"], L_w["N[QRW_s06[L_w[N[T]]]]"], L_y["N[QRW_s06[L_y[N[T]]]]"], L__["N[QRW_s06[L__[N[T]]]]"], L___TAPE_END__["N[QRW_s06[L___TAPE_END__[N[T]]]]"], E["QRL_s06[N[T]]"]): ...
class QLW_s07(Generic[T], ML["N[QL_s07[T]]"], MR["N[QLW_s07[MR[N[T]]]]"], L_a["N[QLW_s07[L_a[N[T]]]]"], L_x["N[QLW_s07[L_x[N[T]]]]"], L_c["N[QLW_s07[L_c[N[T]]]]"], L_d["N[QLW_s07[L_d[N[T]]]]"], L_e["N[QLW_s07[L_e[N[T]]]]"], L_f["N[QLW_s07[L_f[N[T]]]]"], L_g["N[QLW_s07[L_g[N[T]]]]"], L_h["N[QLW_s07[L_h[N[T]]]]"], L_i["N[QLW_s07[L_i[N[T]]]]"], L_l["N[QLW_s07[L_l[N[T]]]]"], L_m["N[QLW_s07[L_m[N[T]]]]"], L_n["N[QLW_s07[L_n[N[T]]]]"], L_o["N[QLW_s07[L_o[N[T]]]]"], L_p["N[QLW_s07[L_p[N[T]]]]"], L_r["N[QLW_s07[L_r[N[T]]]]"], L_s["N[QLW_s07[L_s[N[T]]]]"], L_t["N[QLW_s07[L_t[N[T]]]]"], L_u["N[QLW_s07[L_u[N[T]]]]"], L_w["N[QLW_s07[L_w[N[T]]]]"], L_y["N[QLW_s07[L_y[N[T]]]]"], L__["N[QLW_s07[L__[N[T]]]]"], L___TAPE_END__["N[QLW_s07[L___TAPE_END__[N[T]]]]"], E["QLR_s07[N[T]]"]): ...
class QRW_s07(Generic[T], MR["N[QR_s07[T]]"], ML["N[QRW_s07[ML[N[T]]]]"], L_a["N[QRW_s07[L_a[N[T]]]]"], L_x["N[QRW_s07[L_x[N[T]]]]"], L_c["N[QRW_s07[L_c[N[T]]]]"], L_d["N[QRW_s07[L_d[N[T]]]]"], L_e["N[QRW_s07[L_e[N[T]]]]"], L_f["N[QRW_s07[L_f[N[T]]]]"], L_g["N[QRW_s07[L_g[N[T]]]]"], L_h["N[QRW_s07[L_h[N[T]]]]"], L_i["N[QRW_s07[L_i[N[T]]]]"], L_l["N[QRW_s07[L_l[N[T]]]]"], L_m["N[QRW_s07[L_m[N[T]]]]"], L_n["N[QRW_s07[L_n[N[T]]]]"], L_o["N[QRW_s07[L_o[N[T]]]]"], L_p["N[QRW_s07[L_p[N[T]]]]"], L_r["N[QRW_s07[L_r[N[T]]]]"], L_s["N[QRW_s07[L_s[N[T]]]]"], L_t["N[QRW_s07[L_t[N[T]]]]"], L_u["N[QRW_s07[L_u[N[T]]]]"], L_w["N[QRW_s07[L_w[N[T]]]]"], L_y["N[QRW_s07[L_y[N[T]]]]"], L__["N[QRW_s07[L__[N[T]]]]"], L___TAPE_END__["N[QRW_s07[L___TAPE_END__[N[T]]]]"], E["QRL_s07[N[T]]"]): ...
class QLW_s08(Generic[T], ML["N[QL_s08[T]]"], MR["N[QLW_s08[MR[N[T]]]]"], L_a["N[QLW_s08[L_a[N[T]]]]"], L_x["N[QLW_s08[L_x[N[T]]]]"], L_c["N[QLW_s08[L_c[N[T]]]]"], L_d["N[QLW_s08[L_d[N[T]]]]"], L_e["N[QLW_s08[L_e[N[T]]]]"], L_f["N[QLW_s08[L_f[N[T]]]]"], L_g["N[QLW_s08[L_g[N[T]]]]"], L_h["N[QLW_s08[L_h[N[T]]]]"], L_i["N[QLW_s08[L_i[N[T]]]]"], L_l["N[QLW_s08[L_l[N[T]]]]"], L_m["N[QLW_s08[L_m[N[T]]]]"], L_n["N[QLW_s08[L_n[N[T]]]]"], L_o["N[QLW_s08[L_o[N[T]]]]"], L_p["N[QLW_s08[L_p[N[T]]]]"], L_r["N[QLW_s08[L_r[N[T]]]]"], L_s["N[QLW_s08[L_s[N[T]]]]"], L_t["N[QLW_s08[L_t[N[T]]]]"], L_u["N[QLW_s08[L_u[N[T]]]]"], L_w["N[QLW_s08[L_w[N[T]]]]"], L_y["N[QLW_s08[L_y[N[T]]]]"], L__["N[QLW_s08[L__[N[T]]]]"], L___TAPE_END__["N[QLW_s08[L___TAPE_END__[N[T]]]]"], E["QLR_s08[N[T]]"]): ...
class QRW_s08(Generic[T], MR["N[QR_s08[T]]"], ML["N[QRW_s08[ML[N[T]]]]"], L_a["N[QRW_s08[L_a[N[T]]]]"], L_x["N[QRW_s08[L_x[N[T]]]]"], L_c["N[QRW_s08[L_c[N[T]]]]"], L_d["N[QRW_s08[L_d[N[T]]]]"], L_e["N[QRW_s08[L_e[N[T]]]]"], L_f["N[QRW_s08[L_f[N[T]]]]"], L_g["N[QRW_s08[L_g[N[T]]]]"], L_h["N[QRW_s08[L_h[N[T]]]]"], L_i["N[QRW_s08[L_i[N[T]]]]"], L_l["N[QRW_s08[L_l[N[T]]]]"], L_m["N[QRW_s08[L_m[N[T]]]]"], L_n["N[QRW_s08[L_n[N[T]]]]"], L_o["N[QRW_s08[L_o[N[T]]]]"], L_p["N[QRW_s08[L_p[N[T]]]]"], L_r["N[QRW_s08[L_r[N[T]]]]"], L_s["N[QRW_s08[L_s[N[T]]]]"], L_t["N[QRW_s08[L_t[N[T]]]]"], L_u["N[QRW_s08[L_u[N[T]]]]"], L_w["N[QRW_s08[L_w[N[T]]]]"], L_y["N[QRW_s08[L_y[N[T]]]]"], L__["N[QRW_s08[L__[N[T]]]]"], L___TAPE_END__["N[QRW_s08[L___TAPE_END__[N[T]]]]"], E["QRL_s08[N[T]]"]): ...
class QLW_s09(Generic[T], ML["N[QL_s09[T]]"], MR["N[QLW_s09[MR[N[T]]]]"], L_a["N[QLW_s09[L_a[N[T]]]]"], L_x["N[QLW_s09[L_x[N[T]]]]"], L_c["N[QLW_s09[L_c[N[T]]]]"], L_d["N[QLW_s09[L_d[N[T]]]]"], L_e["N[QLW_s09[L_e[N[T]]]]"], L_f["N[QLW_s09[L_f[N[T]]]]"], L_g["N[QLW_s09[L_g[N[T]]]]"], L_h["N[QLW_s09[L_h[N[T]]]]"], L_i["N[QLW_s09[L_i[N[T]]]]"], L_l["N[QLW_s09[L_l[N[T]]]]"], L_m["N[QLW_s09[L_m[N[T]]]]"], L_n["N[QLW_s09[L_n[N[T]]]]"], L_o["N[QLW_s09[L_o[N[T]]]]"], L_p["N[QLW_s09[L_p[N[T]]]]"], L_r["N[QLW_s09[L_r[N[T]]]]"], L_s["N[QLW_s09[L_s[N[T]]]]"], L_t["N[QLW_s09[L_t[N[T]]]]"], L_u["N[QLW_s09[L_u[N[T]]]]"], L_w["N[QLW_s09[L_w[N[T]]]]"], L_y["N[QLW_s09[L_y[N[T]]]]"], L__["N[QLW_s09[L__[N[T]]]]"], L___TAPE_END__["N[QLW_s09[L___TAPE_END__[N[T]]]]"], E["QLR_s09[N[T]]"]): ...
class QRW_s09(Generic[T], MR["N[QR_s09[T]]"], ML["N[QRW_s09[ML[N[T]]]]"], L_a["N[QRW_s09[L_a[N[T]]]]"], L_x["N[QRW_s09[L_x[N[T]]]]"], L_c["N[QRW_s09[L_c[N[T]]]]"], L_d["N[QRW_s09[L_d[N[T]]]]"], L_e["N[QRW_s09[L_e[N[T]]]]"], L_f["N[QRW_s09[L_f[N[T]]]]"], L_g["N[QRW_s09[L_g[N[T]]]]"], L_h["N[QRW_s09[L_h[N[T]]]]"], L_i["N[QRW_s09[L_i[N[T]]]]"], L_l["N[QRW_s09[L_l[N[T]]]]"], L_m["N[QRW_s09[L_m[N[T]]]]"], L_n["N[QRW_s09[L_n[N[T]]]]"], L_o["N[QRW_s09[L_o[N[T]]]]"], L_p["N[QRW_s09[L_p[N[T]]]]"], L_r["N[QRW_s09[L_r[N[T]]]]"], L_s["N[QRW_s09[L_s[N[T]]]]"], L_t["N[QRW_s09[L_t[N[T]]]]"], L_u["N[QRW_s09[L_u[N[T]]]]"], L_w["N[QRW_s09[L_w[N[T]]]]"], L_y["N[QRW_s09[L_y[N[T]]]]"], L__["N[QRW_s09[L__[N[T]]]]"], L___TAPE_END__["N[QRW_s09[L___TAPE_END__[N[T]]]]"], E["QRL_s09[N[T]]"]): ...
class QLW_s10(Generic[T], ML["N[QL_s10[T]]"], MR["N[QLW_s10[MR[N[T]]]]"], L_a["N[QLW_s10[L_a[N[T]]]]"], L_x["N[QLW_s10[L_x[N[T]]]]"], L_c["N[QLW_s10[L_c[N[T]]]]"], L_d["N[QLW_s10[L_d[N[T]]]]"], L_e["N[QLW_s10[L_e[N[T]]]]"], L_f["N[QLW_s10[L_f[N[T]]]]"], L_g["N[QLW_s10[L_g[N[T]]]]"], L_h["N[QLW_s10[L_h[N[T]]]]"], L_i["N[QLW_s10[L_i[N[T]]]]"], L_l["N[QLW_s10[L_l[N[T]]]]"], L_m["N[QLW_s10[L_m[N[T]]]]"], L_n["N[QLW_s10[L_n[N[T]]]]"], L_o["N[QLW_s10[L_o[N[T]]]]"], L_p["N[QLW_s10[L_p[N[T]]]]"], L_r["N[QLW_s10[L_r[N[T]]]]"], L_s["N[QLW_s10[L_s[N[T]]]]"], L_t["N[QLW_s10[L_t[N[T]]]]"], L_u["N[QLW_s10[L_u[N[T]]]]"], L_w["N[QLW_s10[L_w[N[T]]]]"], L_y["N[QLW_s10[L_y[N[T]]]]"], L__["N[QLW_s10[L__[N[T]]]]"], L___TAPE_END__["N[QLW_s10[L___TAPE_END__[N[T]]]]"], E["QLR_s10[N[T]]"]): ...
class QRW_s10(Generic[T], MR["N[QR_s10[T]]"], ML["N[QRW_s10[ML[N[T]]]]"], L_a["N[QRW_s10[L_a[N[T]]]]"], L_x["N[QRW_s10[L_x[N[T]]]]"], L_c["N[QRW_s10[L_c[N[T]]]]"], L_d["N[QRW_s10[L_d[N[T]]]]"], L_e["N[QRW_s10[L_e[N[T]]]]"], L_f["N[QRW_s10[L_f[N[T]]]]"], L_g["N[QRW_s10[L_g[N[T]]]]"], L_h["N[QRW_s10[L_h[N[T]]]]"], L_i["N[QRW_s10[L_i[N[T]]]]"], L_l["N[QRW_s10[L_l[N[T]]]]"], L_m["N[QRW_s10[L_m[N[T]]]]"], L_n["N[QRW_s10[L_n[N[T]]]]"], L_o["N[QRW_s10[L_o[N[T]]]]"], L_p["N[QRW_s10[L_p[N[T]]]]"], L_r["N[QRW_s10[L_r[N[T]]]]"], L_s["N[QRW_s10[L_s[N[T]]]]"], L_t["N[QRW_s10[L_t[N[T]]]]"], L_u["N[QRW_s10[L_u[N[T]]]]"], L_w["N[QRW_s10[L_w[N[T]]]]"], L_y["N[QRW_s10[L_y[N[T]]]]"], L__["N[QRW_s10[L__[N[T]]]]"], L___TAPE_END__["N[QRW_s10[L___TAPE_END__[N[T]]]]"], E["QRL_s10[N[T]]"]): ...
class QLW_s11(Generic[T], ML["N[QL_s11[T]]"], MR["N[QLW_s11[MR[N[T]]]]"], L_a["N[QLW_s11[L_a[N[T]]]]"], L_x["N[QLW_s11[L_x[N[T]]]]"], L_c["N[QLW_s11[L_c[N[T]]]]"], L_d["N[QLW_s11[L_d[N[T]]]]"], L_e["N[QLW_s11[L_e[N[T]]]]"], L_f["N[QLW_s11[L_f[N[T]]]]"], L_g["N[QLW_s11[L_g[N[T]]]]"], L_h["N[QLW_s11[L_h[N[T]]]]"], L_i["N[QLW_s11[L_i[N[T]]]]"], L_l["N[QLW_s11[L_l[N[T]]]]"], L_m["N[QLW_s11[L_m[N[T]]]]"], L_n["N[QLW_s11[L_n[N[T]]]]"], L_o["N[QLW_s11[L_o[N[T]]]]"], L_p["N[QLW_s11[L_p[N[T]]]]"], L_r["N[QLW_s11[L_r[N[T]]]]"], L_s["N[QLW_s11[L_s[N[T]]]]"], L_t["N[QLW_s11[L_t[N[T]]]]"], L_u["N[QLW_s11[L_u[N[T]]]]"], L_w["N[QLW_s11[L_w[N[T]]]]"], L_y["N[QLW_s11[L_y[N[T]]]]"], L__["N[QLW_s11[L__[N[T]]]]"], L___TAPE_END__["N[QLW_s11[L___TAPE_END__[N[T]]]]"], E["QLR_s11[N[T]]"]): ...
class QRW_s11(Generic[T], MR["N[QR_s11[T]]"], ML["N[QRW_s11[ML[N[T]]]]"], L_a["N[QRW_s11[L_a[N[T]]]]"], L_x["N[QRW_s11[L_x[N[T]]]]"], L_c["N[QRW_s11[L_c[N[T]]]]"], L_d["N[QRW_s11[L_d[N[T]]]]"], L_e["N[QRW_s11[L_e[N[T]]]]"], L_f["N[QRW_s11[L_f[N[T]]]]"], L_g["N[QRW_s11[L_g[N[T]]]]"], L_h["N[QRW_s11[L_h[N[T]]]]"], L_i["N[QRW_s11[L_i[N[T]]]]"], L_l["N[QRW_s11[L_l[N[T]]]]"], L_m["N[QRW_s11[L_m[N[T]]]]"], L_n["N[QRW_s11[L_n[N[T]]]]"], L_o["N[QRW_s11[L_o[N[T]]]]"], L_p["N[QRW_s11[L_p[N[T]]]]"], L_r["N[QRW_s11[L_r[N[T]]]]"], L_s["N[QRW_s11[L_s[N[T]]]]"], L_t["N[QRW_s11[L_t[N[T]]]]"], L_u["N[QRW_s11[L_u[N[T]]]]"], L_w["N[QRW_s11[L_w[N[T]]]]"], L_y["N[QRW_s11[L_y[N[T]]]]"], L__["N[QRW_s11[L__[N[T]]]]"], L___TAPE_END__["N[QRW_s11[L___TAPE_END__[N[T]]]]"], E["QRL_s11[N[T]]"]): ...
class QLW_s12(Generic[T], ML["N[QL_s12[T]]"], MR["N[QLW_s12[MR[N[T]]]]"], L_a["N[QLW_s12[L_a[N[T]]]]"], L_x["N[QLW_s12[L_x[N[T]]]]"], L_c["N[QLW_s12[L_c[N[T]]]]"], L_d["N[QLW_s12[L_d[N[T]]]]"], L_e["N[QLW_s12[L_e[N[T]]]]"], L_f["N[QLW_s12[L_f[N[T]]]]"], L_g["N[QLW_s12[L_g[N[T]]]]"], L_h["N[QLW_s12[L_h[N[T]]]]"], L_i["N[QLW_s12[L_i[N[T]]]]"], L_l["N[QLW_s12[L_l[N[T]]]]"], L_m["N[QLW_s12[L_m[N[T]]]]"], L_n["N[QLW_s12[L_n[N[T]]]]"], L_o["N[QLW_s12[L_o[N[T]]]]"], L_p["N[QLW_s12[L_p[N[T]]]]"], L_r["N[QLW_s12[L_r[N[T]]]]"], L_s["N[QLW_s12[L_s[N[T]]]]"], L_t["N[QLW_s12[L_t[N[T]]]]"], L_u["N[QLW_s12[L_u[N[T]]]]"], L_w["N[QLW_s12[L_w[N[T]]]]"], L_y["N[QLW_s12[L_y[N[T]]]]"], L__["N[QLW_s12[L__[N[T]]]]"], L___TAPE_END__["N[QLW_s12[L___TAPE_END__[N[T]]]]"], E["QLR_s12[N[T]]"]): ...
class QRW_s12(Generic[T], MR["N[QR_s12[T]]"], ML["N[QRW_s12[ML[N[T]]]]"], L_a["N[QRW_s12[L_a[N[T]]]]"], L_x["N[QRW_s12[L_x[N[T]]]]"], L_c["N[QRW_s12[L_c[N[T]]]]"], L_d["N[QRW_s12[L_d[N[T]]]]"], L_e["N[QRW_s12[L_e[N[T]]]]"], L_f["N[QRW_s12[L_f[N[T]]]]"], L_g["N[QRW_s12[L_g[N[T]]]]"], L_h["N[QRW_s12[L_h[N[T]]]]"], L_i["N[QRW_s12[L_i[N[T]]]]"], L_l["N[QRW_s12[L_l[N[T]]]]"], L_m["N[QRW_s12[L_m[N[T]]]]"], L_n["N[QRW_s12[L_n[N[T]]]]"], L_o["N[QRW_s12[L_o[N[T]]]]"], L_p["N[QRW_s12[L_p[N[T]]]]"], L_r["N[QRW_s12[L_r[N[T]]]]"], L_s["N[QRW_s12[L_s[N[T]]]]"], L_t["N[QRW_s12[L_t[N[T]]]]"], L_u["N[QRW_s12[L_u[N[T]]]]"], L_w["N[QRW_s12[L_w[N[T]]]]"], L_y["N[QRW_s12[L_y[N[T]]]]"], L__["N[QRW_s12[L__[N[T]]]]"], L___TAPE_END__["N[QRW_s12[L___TAPE_END__[N[T]]]]"], E["QRL_s12[N[T]]"]): ...
class QLW_s13(Generic[T], ML["N[QL_s13[T]]"], MR["N[QLW_s13[MR[N[T]]]]"], L_a["N[QLW_s13[L_a[N[T]]]]"], L_x["N[QLW_s13[L_x[N[T]]]]"], L_c["N[QLW_s13[L_c[N[T]]]]"], L_d["N[QLW_s13[L_d[N[T]]]]"], L_e["N[QLW_s13[L_e[N[T]]]]"], L_f["N[QLW_s13[L_f[N[T]]]]"], L_g["N[QLW_s13[L_g[N[T]]]]"], L_h["N[QLW_s13[L_h[N[T]]]]"], L_i["N[QLW_s13[L_i[N[T]]]]"], L_l["N[QLW_s13[L_l[N[T]]]]"], L_m["N[QLW_s13[L_m[N[T]]]]"], L_n["N[QLW_s13[L_n[N[T]]]]"], L_o["N[QLW_s13[L_o[N[T]]]]"], L_p["N[QLW_s13[L_p[N[T]]]]"], L_r["N[QLW_s13[L_r[N[T]]]]"], L_s["N[QLW_s13[L_s[N[T]]]]"], L_t["N[QLW_s13[L_t[N[T]]]]"], L_u["N[QLW_s13[L_u[N[T]]]]"], L_w["N[QLW_s13[L_w[N[T]]]]"], L_y["N[QLW_s13[L_y[N[T]]]]"], L__["N[QLW_s13[L__[N[T]]]]"], L___TAPE_END__["N[QLW_s13[L___TAPE_END__[N[T]]]]"], E["QLR_s13[N[T]]"]): ...
class QRW_s13(Generic[T], MR["N[QR_s13[T]]"], ML["N[QRW_s13[ML[N[T]]]]"], L_a["N[QRW_s13[L_a[N[T]]]]"], L_x["N[QRW_s13[L_x[N[T]]]]"], L_c["N[QRW_s13[L_c[N[T]]]]"], L_d["N[QRW_s13[L_d[N[T]]]]"], L_e["N[QRW_s13[L_e[N[T]]]]"], L_f["N[QRW_s13[L_f[N[T]]]]"], L_g["N[QRW_s13[L_g[N[T]]]]"], L_h["N[QRW_s13[L_h[N[T]]]]"], L_i["N[QRW_s13[L_i[N[T]]]]"], L_l["N[QRW_s13[L_l[N[T]]]]"], L_m["N[QRW_s13[L_m[N[T]]]]"], L_n["N[QRW_s13[L_n[N[T]]]]"], L_o["N[QRW_s13[L_o[N[T]]]]"], L_p["N[QRW_s13[L_p[N[T]]]]"], L_r["N[QRW_s13[L_r[N[T]]]]"], L_s["N[QRW_s13[L_s[N[T]]]]"], L_t["N[QRW_s13[L_t[N[T]]]]"], L_u["N[QRW_s13[L_u[N[T]]]]"], L_w["N[QRW_s13[L_w[N[T]]]]"], L_y["N[QRW_s13[L_y[N[T]]]]"], L__["N[QRW_s13[L__[N[T]]]]"], L___TAPE_END__["N[QRW_s13[L___TAPE_END__[N[T]]]]"], E["QRL_s13[N[T]]"]): ...
class QLW_s14(Generic[T], ML["N[QL_s14[T]]"], MR["N[QLW_s14[MR[N[T]]]]"], L_a["N[QLW_s14[L_a[N[T]]]]"], L_x["N[QLW_s14[L_x[N[T]]]]"], L_c["N[QLW_s14[L_c[N[T]]]]"], L_d["N[QLW_s14[L_d[N[T]]]]"], L_e["N[QLW_s14[L_e[N[T]]]]"], L_f["N[QLW_s14[L_f[N[T]]]]"], L_g["N[QLW_s14[L_g[N[T]]]]"], L_h["N[QLW_s14[L_h[N[T]]]]"], L_i["N[QLW_s14[L_i[N[T]]]]"], L_l["N[QLW_s14[L_l[N[T]]]]"], L_m["N[QLW_s14[L_m[N[T]]]]"], L_n["N[QLW_s14[L_n[N[T]]]]"], L_o["N[QLW_s14[L_o[N[T]]]]"], L_p["N[QLW_s14[L_p[N[T]]]]"], L_r["N[QLW_s14[L_r[N[T]]]]"], L_s["N[QLW_s14[L_s[N[T]]]]"], L_t["N[QLW_s14[L_t[N[T]]]]"], L_u["N[QLW_s14[L_u[N[T]]]]"], L_w["N[QLW_s14[L_w[N[T]]]]"], L_y["N[QLW_s14[L_y[N[T]]]]"], L__["N[QLW_s14[L__[N[T]]]]"], L___TAPE_END__["N[QLW_s14[L___TAPE_END__[N[T]]]]"], E["QLR_s14[N[T]]"]): ...
class QRW_s14(Generic[T], MR["N[QR_s14[T]]"], ML["N[QRW_s14[ML[N[T]]]]"], L_a["N[QRW_s14[L_a[N[T]]]]"], L_x["N[QRW_s14[L_x[N[T]]]]"], L_c["N[QRW_s14[L_c[N[T]]]]"], L_d["N[QRW_s14[L_d[N[T]]]]"], L_e["N[QRW_s14[L_e[N[T]]]]"], L_f["N[QRW_s14[L_f[N[T]]]]"], L_g["N[QRW_s14[L_g[N[T]]]]"], L_h["N[QRW_s14[L_h[N[T]]]]"], L_i["N[QRW_s14[L_i[N[T]]]]"], L_l["N[QRW_s14[L_l[N[T]]]]"], L_m["N[QRW_s14[L_m[N[T]]]]"], L_n["N[QRW_s14[L_n[N[T]]]]"], L_o["N[QRW_s14[L_o[N[T]]]]"], L_p["N[QRW_s14[L_p[N[T]]]]"], L_r["N[QRW_s14[L_r[N[T]]]]"], L_s["N[QRW_s14[L_s[N[T]]]]"], L_t["N[QRW_s14[L_t[N[T]]]]"], L_u["N[QRW_s14[L_u[N[T]]]]"], L_w["N[QRW_s14[L_w[N[T]]]]"], L_y["N[QRW_s14[L_y[N[T]]]]"], L__["N[QRW_s14[L__[N[T]]]]"], L___TAPE_END__["N[QRW_s14[L___TAPE_END__[N[T]]]]"], E["QRL_s14[N[T]]"]): ...
class QLW_s15(Generic[T], ML["N[QL_s15[T]]"], MR["N[QLW_s15[MR[N[T]]]]"], L_a["N[QLW_s15[L_a[N[T]]]]"], L_x["N[QLW_s15[L_x[N[T]]]]"], L_c["N[QLW_s15[L_c[N[T]]]]"], L_d["N[QLW_s15[L_d[N[T]]]]"], L_e["N[QLW_s15[L_e[N[T]]]]"], L_f["N[QLW_s15[L_f[N[T]]]]"], L_g["N[QLW_s15[L_g[N[T]]]]"], L_h["N[QLW_s15[L_h[N[T]]]]"], L_i["N[QLW_s15[L_i[N[T]]]]"], L_l["N[QLW_s15[L_l[N[T]]]]"], L_m["N[QLW_s15[L_m[N[T]]]]"], L_n["N[QLW_s15[L_n[N[T]]]]"], L_o["N[QLW_s15[L_o[N[T]]]]"], L_p["N[QLW_s15[L_p[N[T]]]]"], L_r["N[QLW_s15[L_r[N[T]]]]"], L_s["N[QLW_s15[L_s[N[T]]]]"], L_t["N[QLW_s15[L_t[N[T]]]]"], L_u["N[QLW_s15[L_u[N[T]]]]"], L_w["N[QLW_s15[L_w[N[T]]]]"], L_y["N[QLW_s15[L_y[N[T]]]]"], L__["N[QLW_s15[L__[N[T]]]]"], L___TAPE_END__["N[QLW_s15[L___TAPE_END__[N[T]]]]"], E["QLR_s15[N[T]]"]): ...
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | true |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/MapleCTF/2023/rev/mostly_harmless/src/app.py | ctfs/MapleCTF/2023/rev/mostly_harmless/src/app.py | import subprocess
flag = list(input("input flag: "))
flag = flag[6:-1]
flag = list(flag)
def convertify(flag):
INPUT = ""
LENGTH = ""
for c in flag:
INPUT = "[L_" + c + "[N" + INPUT
LENGTH += "]]"
return "_: E[E[Z]] = QRW_s29[L___TAPE_END__[N" + INPUT + "[MR[N[L___TAPE_END__[N[E[E[Z]]]]]]]]]" + LENGTH + "()"
with open("/app/output.py", 'r') as file:
lines = file.readlines()
lines[461] = convertify(flag)
with open("/app/output.py", 'w') as file:
file.writelines(lines)
with subprocess.Popen(["mypy", "/app/output.py"]) as mypy:
success = mypy.wait(timeout=10)
if success == 0:
print("correct!")
else:
print("incorrect!")
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/MapleCTF/2023/crypto/Merkle/server.py | ctfs/MapleCTF/2023/crypto/Merkle/server.py | from secret import flag
import hashlib
import random
import os
import ast
DIGEST_SIZE = 256
HEIGHT = 6
def hash(m):
return hashlib.sha256(m).digest()
class Node:
def __init__(self, left, right, parent=None):
self.left = left
self.right = right
self.parent = parent
self.hash = self.compute_hash()
def compute_hash(self):
return hash(self.left.hash + self.right.hash)
def __repr__(self):
return self.hash.hex()
class Leaf(Node):
def __init__(self, value, parent=None):
self.hash = hash(value)
self.left = None
self.right = None
self.parent = parent
def __repr__(self):
return self.hash.hex()
class MerkleTree:
def __init__(self, values):
self.leaves = [Leaf(value) for value in values]
self.root = self.build_tree(self.leaves)
self.pubkey = self.root.hash
def build_tree(self, leaves):
if len(leaves) == 1:
return leaves[0]
parents = []
for i in range(0, len(leaves), 2):
left = leaves[i]
if i + 1 < len(leaves):
right = leaves[i + 1]
else:
right = left
parent = Node(left, right)
left.parent = parent
right.parent = parent
parents.append(parent)
return self.build_tree(parents)
def print_tree(self, node=None, level=0):
if node is None:
node = self.root
if node is not None:
if node.left is not None or node.right is not None:
self.print_tree(node.right, level + 1)
print(' ' * 4 * level + '->', node.hash.hex())
if node.left is not None:
self.print_tree(node.left, level + 1)
class MerkleSignature:
def __init__(self, h):
self.h = h
self.keypairs = [MerkleSignature._generate_keypair() for _ in range(2 ** self.h)]
self.tree = MerkleTree([MerkleSignature._serialize_pubkey(keypair[0]) for keypair in self.keypairs])
@staticmethod
def _serialize_pubkey(key):
# reduce the 2-dimensional pubkey into a bytearray for hashing
return b''.join(key[0] + key[1])
@staticmethod
def _generate_keypair():
priv = [[os.urandom(32) for j in range(DIGEST_SIZE)] for i in range(2)]
pub = [[hash(priv[i][j]) for j in range(DIGEST_SIZE)] for i in range(2)]
return pub, priv
@staticmethod
def _sign_ots(msg, priv):
msg_bin = bin(int.from_bytes(hash(msg), 'big'))[2:].zfill(DIGEST_SIZE)
return [priv[m == "1"][i] for i, m in enumerate(msg_bin)]
@staticmethod
def _verify_ots(msg, sig, pub):
msg_bin = bin(int.from_bytes(hash(msg), 'big'))[2:].zfill(DIGEST_SIZE)
return all(hash(priv) == pub[m == "1"][i] for i, (m, priv) in enumerate(zip(msg_bin, sig)))
def sign(self, msg):
idx = random.randint(0, 2 ** self.h - 1)
pub, priv = self.keypairs[idx]
current = self.tree.leaves[idx]
signature_path = []
msg_sig = MerkleSignature._sign_ots(msg, priv)
while current != self.tree.root:
if current == current.parent.left:
signature_path.append((current.parent.right.hash, True))
else:
signature_path.append((current.parent.left.hash, False))
current = current.parent
return (signature_path, msg_sig, pub)
def verify(self, msg, signature):
signature_path, sig, pub = signature
assert MerkleSignature._verify_ots(msg, sig, pub), f"Invalid signature for {msg}!"
current_hash = hash(MerkleSignature._serialize_pubkey(pub))
for h, left in signature_path:
if left:
current_hash = hash(current_hash + h)
else:
current_hash = hash(h + current_hash)
return current_hash == self.tree.root.hash
if __name__ == "__main__":
s = MerkleSignature(HEIGHT)
print("""Welcome! To win, please submit a valid signature containing "flag".
1. Sign a message
2. Verify a message
3. Get root hash""")
for _ in range(500):
option = int(input("> "))
if option == 1:
msg = input("> ").encode()
if b'flag' in msg:
print("No cheating!")
exit()
signature_path, msg_sig, pub = s.sign(msg)
assert s.verify(msg, (signature_path, msg_sig, pub))
hint = random.sample([node[0].hex() for node in signature_path], HEIGHT // 2)
random.shuffle(hint)
print(",".join(hint))
print(",".join([k.hex() for k in msg_sig]))
elif option == 2:
msg = input("> ").encode()
signature_path = ast.literal_eval(input("> "))
msg_sig = ast.literal_eval(input("> "))
pub = ast.literal_eval(input("> "))
'''
signature_path: [(bytes, True), (bytes, False), ...]
msg_sig: [bytes, bytes, bytes, ]
pub (2, 256) = [[bytes, bytes, ...], [bytes, bytes]]
'''
assert isinstance(signature_path, list) and all([isinstance(node[0], bytes) and isinstance(node[1], bool) for node in signature_path])
assert isinstance(msg_sig, list) and all(isinstance(i, bytes) for i in msg_sig)
assert isinstance(pub, list) and all(isinstance(i, list) for i in pub) and all(isinstance(j, bytes) for i in pub for j in i)
assert s.verify(msg, (signature_path, msg_sig, pub)), "Invalid signature!"
# Check lengths
assert len(signature_path) == HEIGHT
assert len(pub) == 2 and len(pub[0]) == 256 and len(pub[1]) == 256
assert len(msg_sig) == 256
if b'flag' in msg:
print("Well done! Here's your flag:", flag)
else:
print("Valid signature!")
elif option == 3:
print(s.tree.root.hash.hex())
else:
print("Invalid option, try again.")
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/MapleCTF/2023/crypto/RNG/server.py | ctfs/MapleCTF/2023/crypto/RNG/server.py | from Crypto.Util.number import getPrime
from secret import flag
import random
class RNG:
def __init__(self, s, a):
self.s = s
self.a = a
def next(self):
self.s = (self.s * self.a) % (2 ** 128)
return self.s >> 96
if __name__ == "__main__":
rng1 = RNG(getPrime(128), getPrime(64))
rng2 = RNG(getPrime(128), getPrime(64))
assert flag.startswith("maple{") and flag.endswith("}")
flag = flag[len("maple{"):-1]
enc_flag = []
for i in range(0, len(flag), 4):
enc_flag.append(int.from_bytes(flag[i:i+4].encode(), 'big') ^ rng1.next() ^ rng2.next())
outputs = []
for _ in range(42):
if random.choice([True, False]):
rng1.next()
if random.choice([True, False]):
rng2.next()
if random.choice([True, False]):
outputs.append(rng1.next())
else:
outputs.append(rng2.next())
print("RNG 1:", rng1.a)
print("RNG 2:", rng2.a)
print("Encrypted flag:", enc_flag)
print("Outputs:", outputs)
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/MapleCTF/2023/crypto/Fraudulent/client.py | ctfs/MapleCTF/2023/crypto/Fraudulent/client.py | from Crypto.Util.number import getPrime, long_to_bytes, bytes_to_long
from random import randint
from hashlib import sha256
p = 81561774084914804116542793383590610809004606518687125749737444881352531178029
g = 2
q = p - 1
x = 1 # Your private key
X = pow(g, x, p)
def hash(values):
h = sha256()
for v in values:
h.update(long_to_bytes(v))
return bytes_to_long(h.digest())
def create_proof(encrypted_vote, r):
R, S = encrypted_vote
c_0 = randint(0, q - 1)
f_0 = randint(0, q - 1)
a_1 = randint(0, q - 1)
A_0 = pow(g, f_0, p) * pow(R, -c_0, p) % p
B_0 = pow(X, f_0, p) * pow(S, -c_0, p) % p
A_1 = pow(g, a_1, p)
B_1 = pow(X, a_1, p)
print([A_0, B_0, A_1, B_1])
c = hash([A_0, B_0, A_1, B_1])
c_1 = c - c_0
f_1 = a_1 + c_1 * r
return (c_0, c_1, f_0, f_1)
def encrypt(m):
# Encrypt message
y = randint(0, q - 1)
s = pow(X, y, p)
c_1 = pow(g, y, p)
c_2 = pow(g, m, p) * s % p
R, S = c_1, c_2
# Generate proof that encrypted message is either 0 or 1
if m == 0:
c_1 = randint(0, q - 1)
f_1 = randint(0, q - 1)
a_0 = randint(0, q - 1)
S_p = S * pow(g, -1, p) % p
A_1 = pow(g, f_1, p) * pow(R, -c_1, p) % p
B_1 = pow(X, f_1, p) * pow(S_p, -c_1, p) % p
A_0 = pow(g, a_0, p)
B_0 = pow(X, a_0, p)
c = hash([A_0, B_0, A_1, B_1])
c_0 = c - c_1
f_0 = a_0 + c_0 * y
return (R, S), (c_0, c_1, f_0, f_1)
elif m == 1:
c_0 = randint(0, q - 1)
f_0 = randint(0, q - 1)
a_1 = randint(0, q - 1)
A_0 = pow(g, f_0, p) * pow(R, -c_0, p) % p
B_0 = pow(X, f_0, p) * pow(S, -c_0, p) % p
A_1 = pow(g, a_1, p)
B_1 = pow(X, a_1, p)
c = hash([A_0, B_0, A_1, B_1])
c_1 = c - c_0
f_1 = a_1 + c_1 * y
return (R, S), (c_0, c_1, f_0, f_1)
else:
raise Exception(f"Cannot encrypt message {m}!")
def verify_vote(encrypted_vote, proof):
R, S = encrypted_vote
c_0, c_1, f_0, f_1 = proof
values = [
pow(g, f_0, p) * pow(R, -c_0, p) % p,
pow(X, f_0, p) * pow(S, -c_0, p) % p,
pow(g, f_1, p) * pow(R, -c_1, p) % p,
pow(X, f_1, p) * pow(S, -c_1, p) * pow(g, c_1, p) % p,
]
return c_0 + c_1 == hash(values)
encrypted_vote, proof = encrypt(1)
print("(R, S):", encrypted_vote)
print("(C0, C1, F0, F1):", proof)
assert verify_vote(encrypted_vote, proof) | python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/MapleCTF/2023/crypto/Fraudulent/server.py | ctfs/MapleCTF/2023/crypto/Fraudulent/server.py | from Crypto.Util.number import getPrime, long_to_bytes, bytes_to_long
from secret import flag
from random import randint
from hashlib import sha256
import ast
def hash(values):
h = sha256()
for v in values:
h.update(long_to_bytes(v))
return bytes_to_long(h.digest())
def encrypt(m):
assert 0 <= m < q
y = randint(0, q - 1)
s = pow(X, y, p)
c_1 = pow(g, y, p)
c_2 = pow(g, m, p) * s % p
return (c_1, c_2)
def decrypt(c_1, c_2):
s = pow(c_1, x, p)
return c_2 * pow(s, -1, p) % p
# Return a count of votes for A
def get_votes():
c_1 = 1
c_2 = 1
for vote in encrypted_votes_for_A:
c_1 *= vote[0]
c_2 *= vote[1]
vote = decrypt(c_1, c_2)
for i in range(10**4):
if pow(g, i, p) == vote:
return i
return -1
# Verify that the encrypted_vote corresponds to either 0 or 1
def verify_vote(encrypted_vote, proof):
R, S = encrypted_vote
c_0, c_1, f_0, f_1 = proof
values = [
pow(g, f_0, p) * pow(R, -c_0, p) % p,
pow(X, f_0, p) * pow(S, -c_0, p) % p,
pow(g, f_1, p) * pow(R, -c_1, p) % p,
pow(X, f_1, p) * pow(S, -c_1, p) * pow(g, c_1, p) % p,
]
return c_0 + c_1 == hash(values)
p = 81561774084914804116542793383590610809004606518687125749737444881352531178029
g = 2
q = p - 1
# 1. Take in private key from user
x = int(input("Private key: "))
X = pow(g, x, p)
encrypted_votes_for_A = []
# 2. The server will encrypt 200 A votes and 150 B votes, then tally them
for i in range(200):
encrypted_votes_for_A.append(encrypt(1))
for i in range(100):
encrypted_votes_for_A.append(encrypt(0))
# 3. Now, you send a single ciphertext representing your vote
# Must also provide proof that your vote is either 0 or 1
encrypted_vote = ast.literal_eval(input("Vote (R, S): "))
proof = ast.literal_eval(input("Proof (C0, C1, F0, F1): "))
assert len(encrypted_vote) == 2 and len(proof) == 4
assert all([isinstance(k, int) for k in encrypted_vote])
assert all([isinstance(k, int) for k in proof])
assert verify_vote(encrypted_vote, proof), "Please vote for either 0 or 1."
# Tally all votes. If B has more votes, then you win
encrypted_votes_for_A.append(encrypted_vote)
votes_for_A = get_votes()
votes_for_B = 301 - votes_for_A
print("Votes for A:", votes_for_A)
print("Votes for B:", votes_for_B)
if votes_for_B > votes_for_A:
print("You win!")
print(flag)
else:
print("So close! Next time.")
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/MapleCTF/2023/crypto/Pen_and_Paper/source.py | ctfs/MapleCTF/2023/crypto/Pen_and_Paper/source.py | import string
import random
ALPHABET = string.ascii_uppercase
def generate_key():
return [random.randint(0, 26) for _ in range(13)]
def generate_keystream(key, length):
keystream = []
while len(keystream) < length:
keystream.extend(key)
key = key[1:] + key[:1]
return keystream
def encrypt(message, key):
indices = [ALPHABET.index(c) if c in ALPHABET else c for c in message.upper()]
keystream = generate_keystream(key, len(message))
encrypted = []
for i in range(len(indices)):
if isinstance(indices[i], int):
encrypted.append(ALPHABET[(keystream[i] + indices[i]) % 26])
else:
encrypted.append(indices[i])
return "".join(encrypted)
with open("plaintext.txt", "r") as f:
plaintext = f.read()
key = generate_key()
ciphertext = encrypt(plaintext, key)
with open("ciphertext.txt", "w") as f:
f.write(ciphertext)
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/MapleCTF/2023/crypto/Handshake/server.py | ctfs/MapleCTF/2023/crypto/Handshake/server.py | from abc import abstractmethod
from secret import flag
from Crypto.Cipher import DES
from Crypto.Util.Padding import pad
import random
import os
import string
import hashlib
def bxor(a, b):
return bytes([i ^ j for i, j in zip(a, b)])
def expand_key(key, n):
if len(key) >= n:
return key[:n]
out = key + b"\x00" * (n - len(key))
for i in range(1, n - len(key) + 1):
out = bxor(out, b"\x00" * i + key + b"\x00" * (n - len(key) - i))
return out
traffic = []
class AuthClass:
def __init__(self, username, password):
self.username = username
self.password = password
self.challenge = None
def generate_challenge_response(self, challenge_hash):
password_hash = hashlib.md5(password.encode()).digest()
challenge_response = DES.new(
expand_key(password_hash[0:3], 8), DES.MODE_ECB
).encrypt(pad(challenge_hash, 16))
challenge_response += DES.new(
expand_key(password_hash[7:10], 8), DES.MODE_ECB
).encrypt(pad(challenge_hash, 16))
challenge_response += DES.new(
expand_key(password_hash[13:16], 8), DES.MODE_ECB
).encrypt(pad(challenge_hash, 16))
return challenge_response
def generate_auth_response(self, challenge_response, challenge_hash):
password_hash_hash = hashlib.md5(
hashlib.md5(self.password.encode()).digest()
).digest()
digest = hashlib.sha1(
password_hash_hash
+ challenge_response
+ b"Magic server to client signing constant"
).digest()
auth_response = hashlib.sha1(
digest + challenge_hash + b"Pad to make it do one more iteration"
).digest()
return auth_response
def generate_challenge(self):
self.challenge = os.urandom(16)
return self.challenge
@abstractmethod
def send(self, message):
pass
class Server(AuthClass):
def __init__(self, username, password):
super().__init__(username, password)
def send(self, message):
traffic.append(("Server", message))
class Client(AuthClass):
def __init__(self, username, password):
super().__init__(username, password)
def generate_client_response(self, server_challenge):
challenge_hash = hashlib.sha1(
self.challenge + server_challenge + username.encode()
).digest()[:8]
return (
self.generate_challenge_response(challenge_hash),
challenge_hash,
username,
)
def send(self, message):
traffic.append(("Client", message))
if __name__ == "__main__":
username = "admin"
password = "".join(
random.choice(string.ascii_letters + string.digits) for _ in range(40)
)
server = Server(username, password)
client = Client(username, password)
client.send("Hello")
server.generate_challenge()
server.send(server.challenge)
client.generate_challenge()
client_response = client.generate_client_response(server.challenge)
client.send(client_response)
challenge_response, challenge_hash, _ = client_response
assert challenge_response == server.generate_challenge_response(
challenge_hash
), "Error in authenticating client"
server_auth = server.generate_auth_response(challenge_response, challenge_hash)
server.send(server_auth)
assert server_auth == client.generate_auth_response(
challenge_response, challenge_hash
), "Error in authenticating server"
print("Traffic")
print(traffic)
print("Now, your turn!")
server.generate_challenge()
print("Server challenge:", server.challenge)
challenge_response, new_challenge_hash, _username = input(
"Client response: "
).split(" ")
challenge_response = bytes.fromhex(challenge_response)
new_challenge_hash = bytes.fromhex(new_challenge_hash)
assert _username == username
assert challenge_hash != new_challenge_hash, "No cheating!"
assert challenge_response == server.generate_challenge_response(
new_challenge_hash
), "Error in authenticating client"
print("Successfully authenticated!")
print("Here's your flag", flag)
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/MapleCTF/2023/web/JUJUTSU_KAISEN_2/app/configuration.py | ctfs/MapleCTF/2023/web/JUJUTSU_KAISEN_2/app/configuration.py | import os
PORT = os.environ.get('PORT', 9080)
GRAPHQL_ENDPOINT = "http://jjk_db:9090"
ADMIN_NAME = os.environ.get('ADMIN_NAME', 'via')
ADMIN_PASSWORD = os.environ.get('ADMIN_PASSWORD', 'via')
QUERY = '''
{
getCharacters {
edges {
node {
name,
occupation,
cursedTechnique,
notes
}
}
}
}
'''
MUTATION = '''
mutation {{
addNewCharacter (input:{{
name:"{name}"
occupation: "{occupation}",
notes: "{notes}"
cursedTechnique: "{ct}"
}}) {{
status
}}
}}
'''
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/MapleCTF/2023/web/JUJUTSU_KAISEN_2/app/app.py | ctfs/MapleCTF/2023/web/JUJUTSU_KAISEN_2/app/app.py | from flask import Flask, request, render_template, redirect, session, send_from_directory
from functools import wraps
import redis
from werkzeug.utils import secure_filename
import requests
import urllib.parse
from configuration import *
app = Flask(__name__, static_folder='static/', static_url_path='/')
app.secret_key = os.urandom(128)
app.config.update(
SESSION_COOKIE_SECURE=True,
SESSION_COOKIE_HTTPONLY=True, # default flask behavior just does this
SESSION_COOKIE_SAMESITE='None',
)
## redis is used for rate-limiting on the bot. Not intended part of solution, you can ignore.
r = redis.Redis(host='redis')
# Authentication decorator
def vie_auth(f):
@wraps(f)
def decorator(*args, **kwargs):
if not session.get('auth', False):
return render_template("error.html", error="Sorry, you need to be logged in to access this.")
return f(*args, **kwargs)
return decorator
@app.route("/")
def base():
if session.get('auth'):
return render_template("admin.html")
return render_template("index.html")
@app.route("/visit", methods=["GET", "POST"])
def visit_handler():
if request.method == "GET":
return render_template("visit.html")
elif request.method == "POST":
url = request.form.get('url')
if url == '':
return render_template("error.html", error="The URL cannot be blank!")
elif url.startswith(('http://', 'https://')):
r.rpush('submissions', url)
return "Submitted"
else:
return render_template("error.html", error="The URL can only be HTTP(S)!")
@app.route("/login", methods=["GET", "POST"])
def login_handler():
if request.method == "GET":
if session.get('auth'):
return redirect('/')
return render_template("login.html")
elif request.method == "POST":
username = request.form.get('username', None)
password = request.form.get('password', None)
if username == ADMIN_NAME and password == ADMIN_PASSWORD:
session['auth'] = True
return redirect("/")
else:
return render_template("error.html", error="You're not Vie.")
@app.route("/characters")
@vie_auth
def character_handler():
r = requests.get(GRAPHQL_ENDPOINT + "?query={query}".format(query=urllib.parse.quote(QUERY)))
# TODO: PARSE better
return r.json()['data']['getCharacters']['edges']
@app.route("/view/<string:img>")
@vie_auth
def img_handler(img):
return send_from_directory('uploads', img)
@app.route("/newchar", methods=["GET", "POST"])
@vie_auth
def upload_handler():
if request.method == "GET":
return render_template("newchar.html")
elif request.method == "POST":
name = request.form.get('name')
occupation = request.form.get('occupation')
cursed_technique = request.form.get('cursed_technique')
notes = request.form.get('notes')
upload = request.files.get('file')
if upload is None:
return render_template("error.html", error="You can't upload an empty file!")
ext = upload.filename.split(".")[-1]
if ext != "png":
return render_template("error.html", error="I see what you're trying to do.")
filename = secure_filename(os.urandom(42).hex())
mutation = MUTATION.format(name=name, occupation=occupation, cursed_technique=cursed_technique, notes=notes, ct=cursed_technique)
r = requests.post(GRAPHQL_ENDPOINT, json={"query": mutation, "variables": None})
if (r.json()["data"]["addNewCharacter"]['status'] == True):
upload.save(f"uploads/{filename}.{ext}")
return redirect(f"/view/{filename}.{ext}")
else:
return render_template("error.html", error="Something went wrong when trying to upload through graphql!")
def main():
app.run(port=PORT, debug=False, host='0.0.0.0')
if __name__ == "__main__":
main()
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/MapleCTF/2023/web/JUJUTSU_KAISEN_2/db/configuration.py | ctfs/MapleCTF/2023/web/JUJUTSU_KAISEN_2/db/configuration.py | import os
PORT = os.environ.get("port", 9090) | python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/MapleCTF/2023/web/JUJUTSU_KAISEN_2/db/schema.py | ctfs/MapleCTF/2023/web/JUJUTSU_KAISEN_2/db/schema.py | from typedefs import CharactersTypeDef, CharactersFilter, AddCharacterFields
from models import CharactersModel
from database import db
import graphene
from graphene import relay
from graphene_sqlalchemy_filter import FilterableConnectionField
class Query(graphene.ObjectType):
node = relay.Node.Field()
get_characters = FilterableConnectionField(CharactersTypeDef.connection, filters=CharactersFilter())
class AddNewCharacter(graphene.Mutation):
character = graphene.Field(lambda: CharactersTypeDef)
status = graphene.Boolean()
class Arguments:
input = AddCharacterFields(required=True)
@staticmethod
def mutate(self, info, input):
character = CharactersModel(**input)
# db.session.add(character)
# db.session.commit()
status = True
return AddNewCharacter(character=character, status=status)
class Mutation(graphene.ObjectType):
addNewCharacter = AddNewCharacter.Field()
schema = graphene.Schema(
query=Query, mutation=Mutation
)
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/MapleCTF/2023/web/JUJUTSU_KAISEN_2/db/models.py | ctfs/MapleCTF/2023/web/JUJUTSU_KAISEN_2/db/models.py | from database import db
class CharactersModel(db.Model):
__tablename__ = "characters"
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String)
occupation = db.Column(db.String)
cursed_technique = db.Column(db.String)
img_file = db.Column(db.String)
notes = db.Column(db.String)
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/MapleCTF/2023/web/JUJUTSU_KAISEN_2/db/typedefs.py | ctfs/MapleCTF/2023/web/JUJUTSU_KAISEN_2/db/typedefs.py | import graphene
from graphene import relay
from graphene_sqlalchemy import SQLAlchemyObjectType
from graphene_sqlalchemy_filter import FilterSet
from models import CharactersModel
class CharactersFilter(FilterSet):
class Meta:
model = CharactersModel
fields = {
'name': [...],
'cursed_technique': [...],
'occupation': [...],
'notes': [...],
}
class CharactersTypeDef(SQLAlchemyObjectType):
class Meta:
model = CharactersModel
interfaces = (relay.Node,)
## For mutations
class CharacterFields:
id = graphene.Int()
name = graphene.String()
occupation = graphene.String()
cursed_technique = graphene.String()
img_file = graphene.String()
notes = graphene.String()
class AddCharacterFields(graphene.InputObjectType, CharacterFields):
pass
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/MapleCTF/2023/web/JUJUTSU_KAISEN_2/db/database.py | ctfs/MapleCTF/2023/web/JUJUTSU_KAISEN_2/db/database.py | from flask_sqlalchemy import SQLAlchemy
db = SQLAlchemy()
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/MapleCTF/2023/web/JUJUTSU_KAISEN_2/db/app.py | ctfs/MapleCTF/2023/web/JUJUTSU_KAISEN_2/db/app.py | from flask import Flask
from flask_graphql import GraphQLView as View
from schema import schema
from database import db
from configuration import PORT
app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///jjk_db.sqlite3'
app.add_url_rule("/", view_func=View.as_view("graphql", graphiql=False, schema=schema))
db.init_app(app)
with app.app_context():
db.create_all()
with open("init.sql", "r") as f:
init_script = f.read()
conn = db.engine
statements = init_script.split(";")
for statement in statements:
conn.execute(statement)
@app.teardown_appcontext
def shutdown_session(Error=None):
db.session.remove()
def main():
app.run(port=PORT, debug=False, host='0.0.0.0')
if __name__ == "__main__":
main()
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/MapleCTF/2023/web/JUJUTSU_KAISEN/app/configuration.py | ctfs/MapleCTF/2023/web/JUJUTSU_KAISEN/app/configuration.py | import os
PORT = os.environ.get('PORT', 9080)
GRAPHQL_ENDPOINT = "http://jjk_db:9090"
ADMIN_NAME = os.environ.get('ADMIN_NAME', 'via')
ADMIN_PASSWORD = os.environ.get('ADMIN_PASSWORD', 'via')
QUERY = '''
{
getCharacters {
edges {
node {
name,
occupation,
cursedTechnique,
notes
}
}
}
}
'''
MUTATION = '''
mutation {{
addNewCharacter (input:{{
name:"{name}"
occupation: "{occupation}",
notes: "{notes}"
cursedTechnique: "{ct}"
}}) {{
status
}}
}}
'''
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/MapleCTF/2023/web/JUJUTSU_KAISEN/app/app.py | ctfs/MapleCTF/2023/web/JUJUTSU_KAISEN/app/app.py | from flask import Flask, request, render_template, redirect, session, send_from_directory
from functools import wraps
import redis
from werkzeug.utils import secure_filename
import requests
import urllib.parse
from configuration import *
app = Flask(__name__, static_folder='static/', static_url_path='/')
app.secret_key = os.urandom(128)
app.config.update(
SESSION_COOKIE_SECURE=True,
SESSION_COOKIE_HTTPONLY=True, # default flask behavior just does this
SESSION_COOKIE_SAMESITE='None',
)
## redis is used for rate-limiting on the bot. Not intended part of solution, you can ignore.
r = redis.Redis(host='redis')
# Authentication decorator
def vie_auth(f):
@wraps(f)
def decorator(*args, **kwargs):
if not session.get('auth', False):
return render_template("error.html", error="Sorry, you need to be logged in to access this.")
return f(*args, **kwargs)
return decorator
@app.route("/")
def base():
if session.get('auth'):
return render_template("admin.html")
return render_template("index.html")
@app.route("/visit", methods=["GET", "POST"])
def visit_handler():
if request.method == "GET":
return render_template("visit.html")
elif request.method == "POST":
url = request.form.get('url')
if url == '':
return render_template("error.html", error="The URL cannot be blank!")
elif url.startswith(('http://', 'https://')):
r.rpush('submissions', url)
return "Submitted"
else:
return render_template("error.html", error="The URL can only be HTTP(S)!")
@app.route("/login", methods=["GET", "POST"])
def login_handler():
if request.method == "GET":
if session.get('auth'):
return redirect('/')
return render_template("login.html")
elif request.method == "POST":
username = request.form.get('username', None)
password = request.form.get('password', None)
if username == ADMIN_NAME and password == ADMIN_PASSWORD:
session['auth'] = True
return redirect("/")
else:
return render_template("error.html", error="You're not Vie.")
@app.route("/characters")
@vie_auth
def character_handler():
r = requests.get(GRAPHQL_ENDPOINT + "?query={query}".format(query=urllib.parse.quote(QUERY)))
# TODO: PARSE better
return r.json()['data']['getCharacters']['edges']
@app.route("/view/<string:img>")
@vie_auth
def img_handler(img):
return send_from_directory('uploads', img)
@app.route("/newchar", methods=["GET", "POST"])
@vie_auth
def upload_handler():
if request.method == "GET":
return render_template("newchar.html")
elif request.method == "POST":
name = request.form.get('name')
occupation = request.form.get('occupation')
cursed_technique = request.form.get('cursed_technique')
notes = request.form.get('notes')
upload = request.files.get('file')
if upload is None:
return render_template("error.html", error="You can't upload an empty file!")
ext = upload.filename.split(".")[-1]
if ext != "png":
return render_template("error.html", error="I see what you're trying to do.")
filename = secure_filename(os.urandom(42).hex())
mutation = MUTATION.format(name=name, occupation=occupation, cursed_technique=cursed_technique, notes=notes, ct=cursed_technique)
r = requests.post(GRAPHQL_ENDPOINT, json={"query": mutation, "variables": None})
if (r.json()["data"]["addNewCharacter"]['status'] == True):
upload.save(f"uploads/{filename}.{ext}")
return redirect(f"/view/{filename}.{ext}")
else:
return render_template("error.html", error="Something went wrong when trying to upload through graphql!")
def main():
app.run(port=PORT, debug=False, host='0.0.0.0')
if __name__ == "__main__":
main()
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/MapleCTF/2023/web/JUJUTSU_KAISEN/db/configuration.py | ctfs/MapleCTF/2023/web/JUJUTSU_KAISEN/db/configuration.py | import os
PORT = os.environ.get("port", 9090) | python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/MapleCTF/2023/web/JUJUTSU_KAISEN/db/schema.py | ctfs/MapleCTF/2023/web/JUJUTSU_KAISEN/db/schema.py | from typedefs import CharactersTypeDef, CharactersFilter, AddCharacterFields
from models import CharactersModel
from database import db
import graphene
from graphene import relay
from graphene_sqlalchemy_filter import FilterableConnectionField
class Query(graphene.ObjectType):
node = relay.Node.Field()
get_characters = FilterableConnectionField(CharactersTypeDef.connection, filters=CharactersFilter())
class AddNewCharacter(graphene.Mutation):
character = graphene.Field(lambda: CharactersTypeDef)
status = graphene.Boolean()
class Arguments:
input = AddCharacterFields(required=True)
@staticmethod
def mutate(self, info, input):
character = CharactersModel(**input)
# db.session.add(character)
# db.session.commit()
status = True
return AddNewCharacter(character=character, status=status)
class Mutation(graphene.ObjectType):
addNewCharacter = AddNewCharacter.Field()
schema = graphene.Schema(
query=Query, mutation=Mutation
)
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/MapleCTF/2023/web/JUJUTSU_KAISEN/db/models.py | ctfs/MapleCTF/2023/web/JUJUTSU_KAISEN/db/models.py | from database import db
class CharactersModel(db.Model):
__tablename__ = "characters"
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String)
occupation = db.Column(db.String)
cursed_technique = db.Column(db.String)
img_file = db.Column(db.String)
notes = db.Column(db.String)
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/MapleCTF/2023/web/JUJUTSU_KAISEN/db/typedefs.py | ctfs/MapleCTF/2023/web/JUJUTSU_KAISEN/db/typedefs.py | import graphene
from graphene import relay
from graphene_sqlalchemy import SQLAlchemyObjectType
from graphene_sqlalchemy_filter import FilterSet
from models import CharactersModel
class CharactersFilter(FilterSet):
class Meta:
model = CharactersModel
fields = {
'name': [...],
'cursed_technique': [...],
'occupation': [...],
'notes': [...],
}
class CharactersTypeDef(SQLAlchemyObjectType):
class Meta:
model = CharactersModel
interfaces = (relay.Node,)
## For mutations
class CharacterFields:
id = graphene.Int()
name = graphene.String()
occupation = graphene.String()
cursed_technique = graphene.String()
img_file = graphene.String()
notes = graphene.String()
class AddCharacterFields(graphene.InputObjectType, CharacterFields):
pass
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/MapleCTF/2023/web/JUJUTSU_KAISEN/db/database.py | ctfs/MapleCTF/2023/web/JUJUTSU_KAISEN/db/database.py | from flask_sqlalchemy import SQLAlchemy
db = SQLAlchemy()
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/MapleCTF/2023/web/JUJUTSU_KAISEN/db/app.py | ctfs/MapleCTF/2023/web/JUJUTSU_KAISEN/db/app.py | from flask import Flask
from flask_graphql import GraphQLView as View
from schema import schema
from database import db
from configuration import PORT
app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///jjk_db.sqlite3'
app.add_url_rule("/", view_func=View.as_view("graphql", graphiql=False, schema=schema))
db.init_app(app)
with app.app_context():
db.create_all()
with open("init.sql", "r") as f:
init_script = f.read()
conn = db.engine
statements = init_script.split(";")
for statement in statements:
conn.execute(statement)
@app.teardown_appcontext
def shutdown_session(Error=None):
db.session.remove()
def main():
app.run(port=PORT, debug=False, host='0.0.0.0')
if __name__ == "__main__":
main()
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/MapleCTF/2023/web/Data_Explorer/src/server.py | ctfs/MapleCTF/2023/web/Data_Explorer/src/server.py | import codecs
import csv
import os
import sqlite3
import time
import threading
import traceback
import uuid
from collections import deque
from dataclasses import dataclass
from io import TextIOWrapper
from typing import Any
from flask import Flask, flash, redirect, render_template, request, url_for
app = Flask(__name__)
app.secret_key = os.urandom(32).hex()
app.config["MAX_CONTENT_LENGTH"] = 64 * 1024
DATABASE_EXPIRY_TIME = 5 * 60
DEMO_QUERY_LIMIT = 2
DEMO_ROW_LIMIT = 200
def quote_identifier(s, errors="strict"):
# https://stackoverflow.com/questions/6514274/how-do-you-escape-strings-for-sqlite-table-column-names-in-python
encodable = s.encode("utf-8", errors).decode("utf-8")
nul_index = encodable.find("\x00")
if nul_index >= 0:
error = UnicodeEncodeError(
"NUL-terminated utf-8",
encodable,
nul_index,
nul_index + 1,
"NUL not allowed",
)
error_handler = codecs.lookup_error(errors)
replacement, _ = error_handler(error)
encodable = encodable.replace("\x00", replacement)
return '"' + encodable.replace('"', '""') + '"'
def convert_value(v: str) -> Any:
try:
return int(v)
except Exception:
pass
try:
return float(v)
except Exception:
pass
return v
def format_filter(filt: tuple[str, str, str]) -> str:
col_name, operator, _ = filt
assert operator.upper() in (
"<",
">",
"<=",
">=",
"=",
"==",
"<>",
"!=",
"IS",
"IS NOT",
"LIKE",
"NOT LIKE",
)
return "%s %s ?" % (quote_identifier(col_name), operator)
def format_order(order: tuple[str, str]) -> str:
col_name, direction = order
assert direction.upper() in ["ASC", "DESC"]
return "%s %s" % (quote_identifier(col_name), direction)
class Database:
def __init__(self):
self.db = sqlite3.connect(":memory:")
def create_table(self, table_name: str, column_names: list[str]) -> None:
self.db.execute(
"CREATE TABLE %s (%s)"
% (
quote_identifier(table_name),
", ".join(quote_identifier(col) for col in column_names),
)
)
def insert_row(self, table_name: str, values: list[str]) -> None:
self.db.execute(
"INSERT INTO %s VALUES (%s)" % (quote_identifier(table_name), ", ".join(["?"] * len(values))),
values,
)
def select_from(
self,
table_name: str,
filters: list[tuple[str, str, str]],
orders: list[tuple[str, str]],
) -> list[tuple[Any, ...]]:
query = "SELECT * FROM %s" % quote_identifier(table_name)
params = []
if filters:
query += " WHERE %s" % " AND ".join(format_filter(f) for f in filters)
params = [convert_value(f[2]) for f in filters]
if orders:
query += " ORDER BY %s" % ", ".join(format_order(f) for f in orders)
return self.db.execute(query, params).fetchall()
@dataclass
class Table:
expiry_time: float
queries_left: int
col_names: str
database: Database
lock: threading.Lock
table_list: list[str] = deque()
tables: dict[str, Table] = {}
@app.route("/upgrade/<uuid:table_id>", methods=["POST"])
def upgrade(table_id: str):
if "key" not in request.form or not request.form["key"]:
flash("No license key provided")
return redirect(url_for("view", table_id=table_id))
table = tables.get(table_id, None)
if not table:
flash("Table expired or does not exist")
return redirect(url_for("index"))
with table.lock:
keys = table.database.select_from("license", [("key", "==", request.form["key"])], [])
if not keys:
flash("Invalid license key")
return redirect(url_for("view", table_id=table_id))
return render_template("upgrade.html", flag=os.environ.get("FLAG", "no flag found - contact admin!"))
@app.route("/view/<uuid:table_id>", methods=["GET", "POST"])
def view(table_id: str):
table = tables.get(table_id, None)
if not table:
flash("Table expired or does not exist")
return redirect(url_for("index"))
operations = {
# value: (html, sql)
"eq": ("=", "="),
"ne": ("≠", "!="),
"lt": ("<", "<"),
"gt": (">", ">"),
"le": ("≤", "<="),
"ge": ("≥", ">="),
"like": ("like", "LIKE"),
"unlike": ("unlike", "NOT LIKE"),
}
if request.method == "POST":
filters = list(
zip(
request.form.getlist("filter-col"),
request.form.getlist("filter-op"),
request.form.getlist("filter-val"),
)
)
db_filters = [(col_name, operations[op][1], value) for col_name, op, value in filters]
orders = list(zip(request.form.getlist("order-col"), request.form.getlist("order-od")))
db_orders = [(col_name, od) for col_name, od in orders]
else:
filters = db_filters = []
orders = db_orders = []
with table.lock:
if table.queries_left > 0:
table.queries_left -= 1
try:
data = table.database.select_from("data", db_filters, db_orders)
except Exception as e:
flash("Database query failed")
data = []
else:
flash("Your demo has expired!")
data = []
return render_template("view.html", **locals())
@app.route("/create", methods=["POST"])
def create():
if "file" not in request.files:
flash("No file submitted")
return redirect(url_for("index"))
database = Database()
try:
file = request.files["file"]
reader = csv.reader(TextIOWrapper(file))
fieldnames = next(reader)
database.create_table("data", fieldnames)
database.col_names = fieldnames
for i, row in zip(range(DEMO_ROW_LIMIT), reader):
database.insert_row("data", [convert_value(v) for v in row[: len(fieldnames)]])
database.create_table("license", ["key"])
key = os.urandom(128).hex()
database.insert_row("license", [key])
except Exception:
flash("Unable to parse your input!")
return redirect(url_for("index"))
table_id = uuid.uuid4()
table_list.append(table_id)
tables[table_id] = Table(
expiry_time=time.time() + DATABASE_EXPIRY_TIME,
queries_left=DEMO_QUERY_LIMIT,
col_names=fieldnames,
database=database,
lock=threading.Lock(),
)
return redirect(url_for("view", table_id=table_id))
@app.get("/")
def index():
return render_template("index.html")
def cleanup_thread():
while 1:
time.sleep(10)
try:
while table_list:
table_id = table_list[0]
table = tables.get(table_id, None)
if table and table.expiry_time > time.time():
break
tables.pop(table_id, None)
table_list.popleft()
except Exception:
traceback.print_exc()
if __name__ == "__main__":
threading.Thread(target=cleanup_thread, daemon=True).start()
app.run()
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/MapleCTF/2022/pwn/EBCSIC/chal.py | ctfs/MapleCTF/2022/pwn/EBCSIC/chal.py | #!/usr/bin/env python3
import string
import ctypes
import os
import sys
import subprocess
ok_chars = string.ascii_uppercase + string.digits
elf_header = bytes.fromhex("7F454C46010101000000000000000000020003000100000000800408340000000000000000000000340020000200280000000000010000000010000000800408008004080010000000000100070000000000000051E5746400000000000000000000000000000000000000000600000004000000")
print("Welcome to EBCSIC!")
sc = input("Enter your alphanumeric shellcode: ")
try:
assert all(c in ok_chars for c in sc)
sc_raw = sc.encode("cp037")
assert len(sc_raw) <= 4096
except Exception as e:
print("Sorry, that shellcode is not acceptable.")
exit(1)
print("Looks good! Let's try your shellcode...")
sys.stdout.flush()
memfd_create = ctypes.CDLL("libc.so.6").memfd_create
memfd_create.argtypes = [ctypes.c_char_p, ctypes.c_int]
memfd_create.restype = ctypes.c_int
fd = memfd_create(b"prog", 0)
os.write(fd, elf_header)
os.lseek(fd, 4096, 0)
os.write(fd, sc_raw.ljust(4096, b"\xf4"))
os.execle("/proc/self/fd/%d" % fd, "prog", {})
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/MapleCTF/2022/crypto/jwt/jwt.py | ctfs/MapleCTF/2022/crypto/jwt/jwt.py | from Crypto.Util.number import bytes_to_long as bl, inverse
from fastecdsa.curve import secp256k1
from base64 import urlsafe_b64decode, urlsafe_b64encode
from hashlib import sha256
from json import loads, dumps
from secret import private
def b64decode(msg: str) -> bytes:
if len(msg) % 4 != 0:
msg += "=" * (4 - len(msg) % 4)
return urlsafe_b64decode(msg.encode())
def b64encode(msg: bytes) -> str:
return urlsafe_b64encode(msg).decode().rstrip("=")
class ES256:
def __init__(self):
self.G = secp256k1.G
self.order = secp256k1.q
self.private = private
self.public = self.G * self.private
def _sign(self, msg):
z = sha256(msg.encode()).digest()
k = self.private
z = bl(z)
r = (k * self.G).x
s = inverse(k, self.order) * (z + r * self.private) % self.order
return r, s
def _verify(self, r, s, msg):
if not (1 <= r < self.order and 1 <= s < self.order):
return False
z = sha256(msg.encode()).digest()
z = bl(z)
u1 = z * inverse(s, self.order) % self.order
u2 = r * inverse(s, self.order) % self.order
p = u1 * self.G + u2 * self.public
return r == p.x
# return true if the token signature matches the data
def verify(self, data, signature):
r = int.from_bytes(signature[:32], "little")
s = int.from_bytes(signature[32:], "little")
return self._verify(r, s, data)
# return the signed message and update private/public
def sign(self, data):
header = b64encode(
dumps({"alg": "ES256", "typ": "JWT"}).replace(" ", "").encode()
)
data = b64encode(dumps(data).replace(" ", "").encode())
r, s = self._sign(header + "." + data)
signature = r.to_bytes(32, "little") + s.to_bytes(32, "little")
return header + "." + data + "." + b64encode(signature)
# return the decoded token as a JSON object
def decode(self, token):
_header, _data, _signature = token.split(".")
header = loads(b64decode(_header))
data = loads(b64decode(_data))
signature = b64decode(_signature)
if header["alg"] != "ES256":
raise Exception("Algorithm not supported!")
if not self.verify(_header + "." + _data, signature):
raise Exception("Invalid signature")
return {"user": data["user"]}
jwt = ES256()
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/MapleCTF/2022/crypto/jwt/models.py | ctfs/MapleCTF/2022/crypto/jwt/models.py | from flask_sqlalchemy import SQLAlchemy
db = SQLAlchemy()
class User(db.Model):
id = db.Column(db.Integer, primary_key=True)
username = db.Column(db.String, nullable=False)
password = db.Column(db.String, nullable=False)
def __repr__(self):
return f"<User id={self.id} username={self.username}>"
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/MapleCTF/2022/crypto/jwt/app.py | ctfs/MapleCTF/2022/crypto/jwt/app.py | from flask import Flask, request, render_template, flash, url_for, redirect, g
from flask_cors import CORS
from models import User, db
from secret import flag
from jwt import jwt
import os
def create_app():
app = Flask(__name__)
CORS(app)
app.config["SQLALCHEMY_DATABASE_URI"] = "sqlite:////tmp/jwt.db"
app.config["SQLALCHEMY_TRACK_MODIFICATIONS"] = True
app.config["SECRET_KEY"] = os.urandom(32).hex()
db.init_app(app)
with app.app_context():
db.drop_all()
db.create_all()
user = User(username="admin", password=os.urandom(32).hex())
db.session.add(user)
db.session.commit()
return app
app = create_app()
@app.route("/")
def index():
return redirect("login")
@app.route("/register", methods=["GET", "POST"])
def register():
if request.method == "POST":
username = request.form.get("username")
password = request.form.get("password")
error = None
if not username or not password:
error = "Missing username or password"
if User.query.filter(User.username == username).first() is not None:
error = "User already exists"
if not error:
user = User(username=username, password=password)
db.session.add(user)
db.session.commit()
return redirect(url_for("login"))
flash(error)
return render_template("register.html")
@app.route("/login", methods=["GET", "POST"])
def login():
if request.method == "POST":
username = request.form.get("username")
password = request.form.get("password")
user = User.query.filter(
User.username == username, User.password == password
).one_or_none()
if user:
token = jwt.sign({"user": username})
resp = redirect(url_for("home"))
resp.set_cookie("token", token)
return resp
flash("Invalid username or password")
return render_template("login.html")
@app.before_request
def load_user():
if not (token := request.cookies.get("token")):
return
try:
user = jwt.decode(token)["user"]
g.user = user
except Exception as e:
return
@app.route("/logout", methods=["GET", "POST"])
def logout():
if hasattr(g, "user"):
resp = redirect(url_for("login"))
resp.set_cookie("token", "", expires=0)
return resp
return redirect(url_for("login"))
@app.route("/home", methods=["GET"])
def home():
if hasattr(g, "user"):
if g.user == "admin":
message = f"Welcome back! Here's your flag {flag}"
else:
message = f"Welcome back {g.user}!"
return render_template("home.html", message=message)
flash("An error occurred - please login again")
return redirect(url_for("login"))
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/MapleCTF/2022/crypto/brsaby/script.py | ctfs/MapleCTF/2022/crypto/brsaby/script.py | from Crypto.Util.number import getPrime, bytes_to_long
from secret import FLAG
msg = bytes_to_long(FLAG)
p = getPrime(512)
q = getPrime(512)
N = p*q
e = 0x10001
enc = pow(msg, e, N)
hint = p**4 - q**3
print(f"{N = }")
print(f"{e = }")
print(f"{enc = }")
print(f"{hint = }")
'''
N = 134049493752540418773065530143076126635445393203564220282068096099004424462500237164471467694656029850418188898633676218589793310992660499303428013844428562884017060683631593831476483842609871002334562252352992475614866865974358629573630911411844296034168928705543095499675521713617474013653359243644060206273
e = 65537
enc = 110102068225857249266317472106969433365215711224747391469423595211113736904624336819727052620230568210114877696850912188601083627767033947343144894754967713943008865252845680364312307500261885582194931443807130970738278351511194280306132200450370953028936210150584164591049215506801271155664701637982648648103
hint = 20172108941900018394284473561352944005622395962339433571299361593905788672168045532232800087202397752219344139121724243795336720758440190310585711170413893436453612554118877290447992615675653923905848685604450760355869000618609981902108252359560311702189784994512308860998406787788757988995958832480986292341328962694760728098818022660328680140765730787944534645101122046301434298592063643437213380371824613660631584008711686240103416385845390125711005079231226631612790119628517438076962856020578250598417110996970171029663545716229258911304933901864735285384197017662727621049720992964441567484821110407612560423282
'''
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/MapleCTF/2022/crypto/Spiral/main.py | ctfs/MapleCTF/2022/crypto/Spiral/main.py | from spiral import Spiral
from secret import flag
from os import urandom
menu = """Options:
1. Get encrypted flag
2. Encrypt message"""
key = urandom(16)
cipher = Spiral(key, rounds=4)
def main():
print(menu)
while True:
try:
option = int(input(">>> "))
if option == 1:
ciphertext = cipher.encrypt(flag)
print(ciphertext.hex())
elif option == 2:
plaintext = bytes.fromhex(input())
ciphertext = cipher.encrypt(plaintext)
print(ciphertext.hex())
else:
print("Please select a valid option")
except Exception:
print("Something went wrong, please try again.")
if __name__ == "__main__":
main()
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/MapleCTF/2022/crypto/Spiral/utils.py | ctfs/MapleCTF/2022/crypto/Spiral/utils.py | # rotate a 4x4 matrix clockwise
def spiralRight(matrix):
right = []
for j in range(4):
for i in range(3, -1, -1):
right.append(matrix[i][j])
return bytes2matrix(right)
# rotate a 4x4 matrix counterclockwise
def spiralLeft(matrix):
left = []
for j in range(3, -1, -1):
for i in range(4):
left.append(matrix[i][j])
return bytes2matrix(left)
# convert bytes to 4x4 matrix
def bytes2matrix(bytes):
return [list(bytes[i : i + 4]) for i in range(0, len(bytes), 4)]
# convert 4x4 matrix to bytes
def matrix2bytes(matrix):
return bytes(sum(matrix, []))
SBOX = [184, 79, 76, 49, 237, 28, 54, 183, 106, 24, 192, 7, 43, 111, 175, 44, 46, 199, 182, 115, 83, 227, 61, 230, 6, 57, 165, 137, 58, 14, 94, 217, 66, 120, 53, 142, 29, 150, 103, 75, 186, 39, 31, 196, 18, 207, 244, 16, 213, 243, 114, 251, 96, 4, 138, 197, 10, 176, 157, 91, 238, 155, 254, 71, 86, 37, 130, 12, 52, 162, 220, 56, 88, 188, 27, 208, 25, 51, 172, 141, 168, 253, 85, 193, 90, 35, 95, 105, 200, 127, 247, 21, 93, 67, 13, 235, 84, 190, 225, 119, 189, 81, 250, 117, 231, 50, 179, 22, 223, 26, 228, 132, 139, 166, 210, 23, 64, 108, 212, 201, 99, 218, 160, 240, 129, 224, 233, 242, 159, 47, 126, 125, 146, 229, 0, 252, 161, 98, 30, 63, 239, 164, 36, 80, 151, 245, 38, 107, 3, 65, 73, 204, 8, 205, 82, 78, 173, 112, 219, 136, 123, 149, 118, 32, 215, 163, 74, 134, 248, 68, 110, 45, 59, 145, 178, 156, 100, 177, 221, 2, 92, 20, 40, 144, 101, 140, 169, 116, 143, 202, 1, 113, 209, 104, 133, 128, 70, 89, 216, 147, 122, 131, 9, 249, 121, 109, 191, 77, 124, 246, 55, 198, 187, 185, 17, 60, 180, 203, 19, 158, 97, 206, 148, 5, 87, 170, 236, 222, 194, 15, 214, 241, 211, 234, 42, 41, 153, 62, 102, 152, 69, 181, 34, 48, 226, 11, 195, 154, 174, 167, 135, 232, 72, 171, 33]
SPIRAL = [
[1, 19, 22, 23],
[166, 169, 173, 31],
[149, 212, 176, 38],
[134, 94, 59, 47],
]
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/MapleCTF/2022/crypto/Spiral/spiral.py | ctfs/MapleCTF/2022/crypto/Spiral/spiral.py | from utils import *
class Spiral:
def __init__(self, key, rounds=4):
self.rounds = rounds
self.keys = [bytes2matrix(key)]
self.BLOCK_SIZE = 16
for i in range(rounds):
self.keys.append(spiralLeft(self.keys[-1]))
def encrypt(self, plaintext):
if len(plaintext) % self.BLOCK_SIZE != 0:
padding = self.BLOCK_SIZE - len(plaintext) % self.BLOCK_SIZE
plaintext += bytes([padding] * padding)
ciphertext = b""
for i in range(0, len(plaintext), 16):
ciphertext += self.encrypt_block(plaintext[i : i + 16])
return ciphertext
def encrypt_block(self, plaintext):
self.state = bytes2matrix(plaintext)
self.add_key(0)
for i in range(1, self.rounds):
self.substitute()
self.rotate()
self.mix()
self.add_key(i)
self.substitute()
self.rotate()
self.add_key(self.rounds)
return matrix2bytes(self.state)
def add_key(self, idx):
for i in range(4):
for j in range(4):
self.state[i][j] = (self.state[i][j] + self.keys[idx][i][j]) % 255
def substitute(self):
for i in range(4):
for j in range(4):
self.state[i][j] = SBOX[self.state[i][j]]
def rotate(self):
self.state = spiralRight(self.state)
def mix(self):
out = [[0 for _ in range(4)] for _ in range(4)]
for i in range(4):
for j in range(4):
for k in range(4):
out[i][j] += SPIRAL[i][k] * self.state[k][j]
out[i][j] %= 255
self.state = out
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/MapleCTF/2022/crypto/qotp-real/server.py | ctfs/MapleCTF/2022/crypto/qotp-real/server.py | from random import uniform
from math import sin, cos, tan, pi
from signal import alarm
from secret import FLAG
EPS = 1e-9
class Qstate:
def __init__(self, x: float, y: float):
assert(abs(x * x + y * y - 1.0) < EPS)
self.x = x
self.y = y
def __mul__(self, other):
return self.x * other.x + self.y * other.y
class Base:
def __init__(self, q1: Qstate, q2: Qstate):
assert(abs(q1 * q2) < EPS)
self.q1 = q1
self.q2 = q2
def measure(self, q: Qstate):
alpha = (self.q1 * q)**2
return int(uniform(0, 1) >= alpha)
def get_random_bases(n: int):
angles = [pi / 4 * uniform(-pi, pi) + pi / 4 for _ in range(n)]
bases = [Base(Qstate(cos(angle), sin(angle)), Qstate(-sin(angle), cos(angle))) for angle in angles]
return bases
def binify(s: str):
return ''.join(format(ord(c), '08b') for c in s)
def decode(enc, bases):
return ''.join(str(b.measure(q)) for q, b in zip(enc, bases))
def encode(msg, bases):
enc = [b.q1 if x == '0' else b.q2 for x, b in zip(msg, bases)]
assert decode(enc, bases) == msg
return enc
def print_menu():
print('''
What would you like to do?
(1) Encrypt message
(2) Decrypt message
(3) Decrypt flag
''')
def read_base():
baseq1x = float(input("Enter base.q1.x: "))
baseq1y = float(input("Enter base.q1.y: "))
baseq2x = float(input("Enter base.q2.x: "))
baseq2y = float(input("Enter base.q2.y: "))
return Base(Qstate(baseq1x, baseq1y), Qstate(baseq2x, baseq2y))
if __name__ == '__main__':
alarm(60)
FLAG = binify(FLAG)
enc = encode(FLAG, get_random_bases(len(FLAG)))
msg = ""
print("Welcome to my REAL quantum encryption service!")
print("Only real numbers allowed!")
while True:
print_menu()
response = int(input("Enter choice: "))
if response == 1:
msg = input("Enter message: ")
msg = binify(msg)
bases = [read_base()] * len(msg)
msg = encode(msg, bases)
print("Message stored!")
elif response == 2:
bases = [read_base()] * len(msg)
print(decode(msg, bases))
elif response == 3:
bases = [read_base()] * len(FLAG)
print(decode(enc, bases))
enc = encode(FLAG, get_random_bases(len(FLAG)))
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/MapleCTF/2022/crypto/e000p/script.py | ctfs/MapleCTF/2022/crypto/e000p/script.py | from secret import FLAG
# Implementation of Edwards Curve41417
# x ** 2 + y ** 2 = 1 + 3617 * x ** 2 * y ** 2
# Formulas from http://hyperelliptic.org/EFD/g1p/auto-edwards.html
P = 2 ** 414 - 17
d = 3617
def on_curve(p):
x, y = p
return (x * x + y * y) % P == (1 + d * x * x * y * y) % P
def inv(x):
return pow(x, -1, P)
def add(p1, p2):
x1, y1 = p1
x2, y2 = p2
x = (x1 * y2 + y1 * x2) * inv(1 + d * x1 * x2 * y1 * y2)
y = (y1 * y2 - x1 * x2) * inv(1 - d * x1 * x2 * y1 * y2)
return (x % P, y % P)
def mul(x: int, base):
ans = (0,1)
cur = base
while x > 0:
if x & 1:
ans = add(cur, ans)
x >>= 1
cur = add(cur, cur)
return ans
base = (17319886477121189177719202498822615443556957307604340815256226171904769976866975908866528699294134494857887698432266169206165, 34)
assert(on_curve(base))
order = 2 ** 411 - 33364140863755142520810177694098385178984727200411208589594759
msg = int.from_bytes(FLAG, 'big')
assert(msg < 2 ** 410)
enc = mul(pow(msg, -1, order), base)
print(f"{enc = }")
# Have a hint!
bm = (1 << 412) - 1
bm ^= ((1 << 22) -1) << 313
bm ^= ((1 << 22) -1) << 13
bm ^= 1 << 196
hint = bm & pow(msg, -1, order)
print(f"{hint = }")
'''
enc = (29389900956614406804195679733048238721927197300216785144586024378999988819550861039522005309555174206184334563744077143526515, 35393890305755889860162885313105764163711685229222879079392595581125504924571957049674311023316022028491019878405896203357959)
hint = 323811241263249292936728039512527915123919581362694022248295847200852329370976362254362732891461683020125008591836401372097
'''
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/MapleCTF/2022/crypto/Spiral-baby/main.py | ctfs/MapleCTF/2022/crypto/Spiral-baby/main.py | from spiral import Spiral
from secret import flag
from os import urandom
menu = """Options:
1. Get encrypted flag
2. Encrypt message"""
key = urandom(16)
cipher = Spiral(key, rounds=1)
def main():
print(menu)
while True:
try:
option = int(input(">>> "))
if option == 1:
ciphertext = cipher.encrypt(flag)
print(ciphertext.hex())
elif option == 2:
plaintext = bytes.fromhex(input())
ciphertext = cipher.encrypt(plaintext)
print(ciphertext.hex())
else:
print("Please select a valid option")
except Exception:
print("Something went wrong, please try again.")
if __name__ == "__main__":
main()
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/MapleCTF/2022/crypto/Spiral-baby/utils.py | ctfs/MapleCTF/2022/crypto/Spiral-baby/utils.py | # rotate a 4x4 matrix clockwise
def spiralRight(matrix):
right = []
for j in range(4):
for i in range(3, -1, -1):
right.append(matrix[i][j])
return bytes2matrix(right)
# rotate a 4x4 matrix counterclockwise
def spiralLeft(matrix):
left = []
for j in range(3, -1, -1):
for i in range(4):
left.append(matrix[i][j])
return bytes2matrix(left)
# convert bytes to 4x4 matrix
def bytes2matrix(bytes):
return [list(bytes[i : i + 4]) for i in range(0, len(bytes), 4)]
# convert 4x4 matrix to bytes
def matrix2bytes(matrix):
return bytes(sum(matrix, []))
SBOX = [184, 79, 76, 49, 237, 28, 54, 183, 106, 24, 192, 7, 43, 111, 175, 44, 46, 199, 182, 115, 83, 227, 61, 230, 6, 57, 165, 137, 58, 14, 94, 217, 66, 120, 53, 142, 29, 150, 103, 75, 186, 39, 31, 196, 18, 207, 244, 16, 213, 243, 114, 251, 96, 4, 138, 197, 10, 176, 157, 91, 238, 155, 254, 71, 86, 37, 130, 12, 52, 162, 220, 56, 88, 188, 27, 208, 25, 51, 172, 141, 168, 253, 85, 193, 90, 35, 95, 105, 200, 127, 247, 21, 93, 67, 13, 235, 84, 190, 225, 119, 189, 81, 250, 117, 231, 50, 179, 22, 223, 26, 228, 132, 139, 166, 210, 23, 64, 108, 212, 201, 99, 218, 160, 240, 129, 224, 233, 242, 159, 47, 126, 125, 146, 229, 0, 252, 161, 98, 30, 63, 239, 164, 36, 80, 151, 245, 38, 107, 3, 65, 73, 204, 8, 205, 82, 78, 173, 112, 219, 136, 123, 149, 118, 32, 215, 163, 74, 134, 248, 68, 110, 45, 59, 145, 178, 156, 100, 177, 221, 2, 92, 20, 40, 144, 101, 140, 169, 116, 143, 202, 1, 113, 209, 104, 133, 128, 70, 89, 216, 147, 122, 131, 9, 249, 121, 109, 191, 77, 124, 246, 55, 198, 187, 185, 17, 60, 180, 203, 19, 158, 97, 206, 148, 5, 87, 170, 236, 222, 194, 15, 214, 241, 211, 234, 42, 41, 153, 62, 102, 152, 69, 181, 34, 48, 226, 11, 195, 154, 174, 167, 135, 232, 72, 171, 33]
SPIRAL = [
[1, 19, 22, 23],
[166, 169, 173, 31],
[149, 212, 176, 38],
[134, 94, 59, 47],
]
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/MapleCTF/2022/crypto/Spiral-baby/spiral.py | ctfs/MapleCTF/2022/crypto/Spiral-baby/spiral.py | from utils import *
class Spiral:
def __init__(self, key, rounds=4):
self.rounds = rounds
self.keys = [bytes2matrix(key)]
self.BLOCK_SIZE = 16
for i in range(rounds):
self.keys.append(spiralLeft(self.keys[-1]))
def encrypt(self, plaintext):
if len(plaintext) % self.BLOCK_SIZE != 0:
padding = self.BLOCK_SIZE - len(plaintext) % self.BLOCK_SIZE
plaintext += bytes([padding] * padding)
ciphertext = b""
for i in range(0, len(plaintext), 16):
ciphertext += self.encrypt_block(plaintext[i : i + 16])
return ciphertext
def encrypt_block(self, plaintext):
self.state = bytes2matrix(plaintext)
self.add_key(0)
for i in range(1, self.rounds):
self.substitute()
self.rotate()
self.mix()
self.add_key(i)
self.substitute()
self.rotate()
self.add_key(self.rounds)
return matrix2bytes(self.state)
def add_key(self, idx):
for i in range(4):
for j in range(4):
self.state[i][j] = (self.state[i][j] + self.keys[idx][i][j]) % 255
def substitute(self):
for i in range(4):
for j in range(4):
self.state[i][j] = SBOX[self.state[i][j]]
def rotate(self):
self.state = spiralRight(self.state)
def mix(self):
out = [[0 for _ in range(4)] for _ in range(4)]
for i in range(4):
for j in range(4):
for k in range(4):
out[i][j] += SPIRAL[i][k] * self.state[k][j]
out[i][j] %= 255
self.state = out
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/MapleCTF/2022/web/pickle-factory/hosted/app.py | ctfs/MapleCTF/2022/web/pickle-factory/hosted/app.py | import random
import json
import pickle
from http.server import BaseHTTPRequestHandler, HTTPServer
from urllib.parse import urlparse, unquote_plus
from jinja2 import Environment
pickles = {}
env = Environment()
class PickleFactoryHandler(BaseHTTPRequestHandler):
def do_GET(self):
parsed = urlparse(self.path)
if parsed.path == "/":
self.send_response(200)
self.send_header("Content-type", "text/html")
self.end_headers()
with open("templates/index.html", "r") as f:
self.wfile.write(f.read().encode())
return
elif parsed.path == "/view-pickle":
params = parsed.query.split("&")
params = [p.split("=") for p in params]
uid = None
filler = "##"
space = "__"
for p in params:
if p[0] == "uid":
uid = p[1]
elif p[0] == "filler":
filler = p[1]
elif p[0] == "space":
space = p[1]
if uid == None:
self.send_response(400)
self.send_header("Content-type", "text/html")
self.end_headers()
self.wfile.write("No uid specified".encode())
return
if uid not in pickles:
self.send_response(404)
self.send_header("Content-type", "text/html")
self.end_headers()
self.wfile.write(
"No pickle found with uid {}".format(uid).encode())
return
large_template = """
<!DOCTYPE html>
<html>
<head>
<title> Your Pickle </title>
<style>
html * {
font-size: 12px;
line-height: 1.625;
font-family: Consolas; }
</style>
</head>
<body>
<code> """ + str(pickles[uid]) + """ </code>
<h2> Sample good: </h2>
{% if True %}
{% endif %}
{{space*59}}
{% if True %}
{% endif %}
{{space*6+filler*5+space*48}}
{% if True %}
{% endif %}
{{space*4+filler*15+space*27+filler*8+space*5}}
{% if True %}
{% endif %}
{{space*3+filler*20+space*11+filler*21+space*4}}
{% if True %}
{% endif %}
{{space*3+filler*53+space*3}}
{% if True %}
{% endif %}
{{space*3+filler*54+space*2}}
{% if True %}
{% endif %}
{{space*2+filler*55+space*2}}
{% if True %}
{% endif %}
{{space*2+filler*56+space*1}}
{% if True %}
{% endif %}
{{space*3+filler*55+space*1}}
{% if True %}
{% endif %}
{{space*3+filler*55+space*1}}
{% if True %}
{% endif %}
{{space*4+filler*53+space*2}}
{% if True %}
{% endif %}
{{space*4+filler*53+space*2}}
{% if True %}
{% endif %}
{{space*5+filler*51+space*3}}
{% if True %}
{% endif %}
{{space*7+filler*48+space*4}}
{% if True %}
{% endif %}
{{space*9+filler*44+space*6}}
{% if True %}
{% endif %}
{{space*13+filler*38+space*8}}
{% if True %}
{% endif %}
{{space*16+filler*32+space*11}}
{% if True %}
{% endif %}
{{space*20+filler*24+space*15}}
{% if True %}
{% endif %}
{{space*30+filler*5+space*24}}
{% if True %}
{% endif %}
{{space*59}}
{% if True %}
{% endif %}
</body>
</html>
"""
try:
res = env.from_string(large_template).render(
filler=filler, space=space)
self.send_response(200)
self.send_header("Content-type", "text/html")
self.end_headers()
self.wfile.write(res.encode())
except Exception as e:
print(e)
self.send_response(500)
self.send_header("Content-type", "text/html")
self.end_headers()
self.wfile.write("Error rendering template".encode())
return
else:
self.send_response(404)
self.send_header("Content-type", "text/html")
self.end_headers()
self.wfile.write("Not found".encode())
return
def do_POST(self):
parsed = urlparse(self.path)
if parsed.path == "/create-pickle":
length = int(self.headers.get("content-length"))
body = self.rfile.read(length).decode()
try:
data = unquote_plus(body.split("=")[1]).strip()
data = json.loads(data)
pp = pickle.dumps(data)
uid = generate_random_hexstring(32)
pickles[uid] = pp
self.send_response(200)
self.send_header("Content-type", "text/html")
self.end_headers()
self.wfile.write(uid.encode())
return
except Exception as e:
print(e)
self.send_response(400)
self.send_header("Content-type", "text/html")
self.end_headers()
self.wfile.write("Invalid JSON".encode())
return
else:
self.send_response(404)
self.send_header("Content-type", "text/html")
self.end_headers()
self.wfile.write("Not found".encode())
return
def render_template_string_sanitized(env, template, **args):
# it works!
global_vars = ['self', 'config', 'request', 'session', 'g', 'app']
for var in global_vars:
template = "{% set " + var + " = None %}\n" + template
return env.from_string(template).render(**args)
def generate_random_hexstring(length):
return "".join(random.choice("0123456789abcdef") for _ in range(length))
if __name__ == "__main__":
PORT = 9229
with HTTPServer(("", PORT), PickleFactoryHandler) as httpd:
print(f"Listening on 0.0.0.0:{PORT}")
httpd.serve_forever()
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/TFC/2021/crypto/JAM/main.py | ctfs/TFC/2021/crypto/JAM/main.py | #!/usr/bin/env python3
import random
import re
import string
import sys
from secret import secret, flag
import hashlib
def print_trade_help():
print("----=== Trade ===----")
print("1. Flag - 6 COIN(S)")
print("2. Random String - 1 COIN(S)")
print("3. Nothing - 1 COIN(S)")
print("---------------------")
def print_help():
print("----=== Menu ===----")
print("1. Work!")
print("2. Trade!")
print("3. Recover last session!")
print("4. Check your purse!")
print("5. Print recovery token!")
print("q. Quit!")
print("--------------------")
class Console:
def __init__(self):
self.__secret = secret.encode("utf-8")
self.__hash = hashlib.md5(self.__secret + b' 0').hexdigest()
self.__coins = 0
def work(self):
if self.__coins >= 5:
print("Can't work anymore! You're too tired!")
return
self.__coins += 1
print("You've worked really hard today! Have a coin!")
print("Purse: " + str(self.__coins) + " (+1 COIN)")
self.__hash = hashlib.md5(self.__secret + b' ' + str(self.__coins).encode("utf-8")).hexdigest()
print("To recover, here's your token: " + self.__hash)
def trade(self):
options = {
"1": (6, flag),
"2": (1, ''.join(random.choice(string.ascii_uppercase + string.digits) for _ in range(10))),
"3": (1, "You receive nothing.")
}
print_trade_help()
print("What would you like to buy?")
opt = input("> ")
if opt not in options.keys():
print("Invalid option!")
return
if options[opt][0] > self.__coins:
print("You do not have enough coins!")
return
else:
self.__coins -= options[opt][0]
print(options[opt][1])
print("Purse: " + str(self.__coins) + " (-" + str(options[opt][0]) + " COIN(S))")
def recover(self):
print("In order to recover, we need two things from you.")
print("1. How many coins did you have?")
print("> ", end="")
amt_coins = sys.stdin.buffer.readline()[:-1]
print("2. What was your recovery token?")
token = input("> ")
hash_tkn = self.__secret + b" " + amt_coins
hash_for_coins = hashlib.md5(hash_tkn).hexdigest()
if hash_for_coins != token:
print("Incorrect!")
return
self.__coins = int(re.sub("[^0-9]", "", amt_coins.decode("unicode_escape")))
print(self.__coins)
self.__hash = token
print("Recovered successfully!")
def check_purse(self):
print("Purse: " + str(self.__coins))
def get_recovery_token(self):
print(self.__hash)
def start_console(self):
options = {
"1": self.work,
"2": self.trade,
"3": self.recover,
"4": self.check_purse,
"5": self.get_recovery_token,
}
while True:
print_help()
inp = input("> ")
if inp == "q":
print("Quitting.")
sys.exit(0)
if inp not in options.keys():
print("Not a valid option!")
continue
try:
options[inp]()
except Exception:
pass
if __name__ == "__main__":
console = Console()
console.start_console()
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/TFC/2021/crypto/KH5YHLZVJP/main.py | ctfs/TFC/2021/crypto/KH5YHLZVJP/main.py | import base64
import random
from pwn import xor
from secret import flag
with open("c.out", "w") as f:
for _ in range(4):
x = random.getrandbits(4096)
f.write(str(x) + "\n")
x = random.getrandbits(4096)
x = xor(flag, str(x)[:512])
secret = base64.b64encode(x).decode("utf-8")
f.write("SECRET: " + secret)
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/TFC/2023/misc/MY_FIRST_CALCULATOR/main.py | ctfs/TFC/2023/misc/MY_FIRST_CALCULATOR/main.py | import sys
print("This is a calculator")
inp = input("Formula: ")
sys.stdin.close()
blacklist = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ."
if any(x in inp for x in blacklist):
print("Nice try")
exit()
fns = {
"pow": pow
}
print(eval(inp, fns, fns)) | python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/TFC/2023/misc/MY_THIRD_CALCULATOR/third.py | ctfs/TFC/2023/misc/MY_THIRD_CALCULATOR/third.py | import sys
print("This is a safe calculator")
inp = input("Formula: ")
sys.stdin.close()
blacklist = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ."
if any(x in inp for x in blacklist):
print("Nice try")
exit()
fns = {
"__builtins__": {"setattr": setattr, "__import__": __import__, "chr": chr}
}
print(eval(inp, fns, fns))
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/TFC/2023/crypto/FERMENTATION/server.py | ctfs/TFC/2023/crypto/FERMENTATION/server.py | #!/usr/bin/env python3
import pickle
from Crypto.Cipher import AES
from Crypto.Util.Padding import pad, unpad
import os
KEY = os.urandom(16)
IV = os.urandom(16)
FLAG = 'redacted'
header = input("Header: ")
name = input("Name: ")
is_admin = False
data = header.encode() + pickle.dumps((name, is_admin))
encrypted = AES.new(KEY, AES.MODE_CBC, IV).encrypt(pad(data, 16))
print(encrypted.hex())
while True:
data = bytes.fromhex(input().strip())
try:
if pickle.loads(unpad(AES.new(KEY, AES.MODE_CBC, IV).decrypt(data),16)[len(header):])[1] == 1:
print(FLAG)
else:
print("Wait a minute, who are you?")
except:
print("Wait a minute, who are you?") | python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/TFC/2023/crypto/CYPHEREHPYC/cypherehpyc.py | ctfs/TFC/2023/crypto/CYPHEREHPYC/cypherehpyc.py | from Crypto.Cipher import AES
from Crypto.Util.Padding import pad, unpad
KEY = b"redacted" * 2
FLAG = "redacted"
initial_cipher = bytes.fromhex(input("Initial HEX: ").strip())
cipher = AES.new(KEY, AES.MODE_ECB).encrypt(pad(initial_cipher, 16))
print(cipher.hex())
cipher = AES.new(KEY, AES.MODE_ECB).encrypt(pad(cipher, 16))
print(cipher.hex())
cipher = AES.new(KEY, AES.MODE_ECB).encrypt(pad(cipher, 16))
result = bytes.fromhex(input("Result HEX: ").strip())
if cipher == result:
print(FLAG)
else:
print("Not quite...") | python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/TFC/2023/web/BABY_DUCKY_NOTES_REVENGE/src/routes.py | ctfs/TFC/2023/web/BABY_DUCKY_NOTES_REVENGE/src/routes.py | from flask import Blueprint, render_template, session, request, jsonify, abort
from database.database import db_login, db_register, db_create_post, db_get_user_posts, db_get_all_users_posts, db_delete_posts, db_delete_all_posts
import re, threading, datetime
from functools import wraps
from bot import bot
USERNAME_REGEX = re.compile('^[A-za-z0-9\.]{2,}$')
def auth_required(f):
@wraps(f)
def decorator(*args, **kwargs):
username = session.get('username')
if not username:
return abort(401, 'Not logged in!')
return f(username, *args, **kwargs)
return decorator
web = Blueprint('web', __name__)
api = Blueprint('api', __name__)
@web.route('/', methods=['GET'])
def index():
date = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
return render_template('index.html', current_date=date)
@web.route('/login')
def login():
return render_template('login.html')
@web.route('/register')
def register():
return render_template('register.html')
@web.route('/posts/', methods=['GET'])
@auth_required
def posts(username):
if username != 'admin':
return jsonify('You must be admin to see all posts!'), 401
frontend_posts = []
posts = db_get_all_users_posts()
for post in posts:
try:
frontend_posts += [{'username': post['username'],
'title': post['title'],
'content': post['content']}]
except:
raise Exception(post)
return render_template('posts.html', posts=frontend_posts)
@web.route('/posts/view/<user>', methods=['GET'])
@auth_required
def posts_view(username, user):
try:
posts = db_get_user_posts(user, username == user)
except:
raise Exception(username)
return render_template('posts.html', posts=posts)
@web.route('/posts/create', methods=['GET'])
@auth_required
def posts_create(username):
return render_template('create.html', username=username)
@api.route('/login', methods=['POST'])
def api_login():
if not request.is_json:
return jsonify('JSON is needed'), 400
data = request.get_json()
username = data.get('username', '')
password = data.get('password', '')
if not username or not password:
return jsonify('Username and password required!'), 401
if type(username) != str or type(password) != str:
return jsonify('Username or password wrong format!'), 402
user = db_login(username, password)
if user:
session['username'] = username
return jsonify('Success login'), 200
return jsonify('Invalid credentials!'), 403
@api.route('/register', methods=['POST'])
def api_register():
if not request.is_json:
return jsonify('JSON is needed'), 400
data = request.get_json()
username = data.get('username', '')
password = data.get('password', '')
if not username or not password:
return jsonify('Username and password required!'), 402
if type(username) != str or type(password) != str:
return jsonify('Username or password wrong format!'), 402
if USERNAME_REGEX.match(username) == None:
return jsonify('Can\'t create an account with that username'), 402
result = db_register(username, password)
if result:
return jsonify('Success register'), 200
return jsonify('Account already existing!'), 403
@api.route('/posts', methods=['POST'])
@auth_required
def api_create_post(username):
if not request.is_json:
return jsonify('JSON is needed'), 400
data = request.get_json()
title = data.get('title', None)
content = data.get('content', '')
hidden = data.get('hidden', None)
if not content or hidden == None:
return jsonify('Content and hidden value required!'), 401
if title and type(title) != str:
return jsonify('Title value wrong format!'), 402
if type(content) != str or type(hidden) != bool:
return jsonify('Content and hidden value wrong format!'), 402
db_create_post(username, {"title": title, "content": content, "hidden": hidden})
return jsonify('Post created successfully!'), 200
@api.route('/report', methods=['POST'])
@auth_required
def api_report(username):
thread = threading.Thread(target=bot, args=(username,))
thread.start()
return jsonify('Post reported successfully!'), 200
@api.route('/posts', methods=['DELETE'])
@auth_required
def api_delete_posts(username):
db_delete_posts(username)
return jsonify('All posts deleted successfully!'), 200
@api.route('/posts/all', methods=['DELETE'])
@auth_required
def api_delete_all_posts(username):
db_delete_all_posts()
return jsonify('All posts deleted successfully!'), 200 | python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/TFC/2023/web/BABY_DUCKY_NOTES_REVENGE/src/bot.py | ctfs/TFC/2023/web/BABY_DUCKY_NOTES_REVENGE/src/bot.py | from selenium import webdriver
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.common.by import By
import time, os
def bot(username):
options = Options()
options.add_argument('--no-sandbox')
options.add_argument('headless')
options.add_argument('ignore-certificate-errors')
options.add_argument('disable-dev-shm-usage')
options.add_argument('disable-infobars')
options.add_argument('disable-background-networking')
options.add_argument('disable-default-apps')
options.add_argument('disable-extensions')
options.add_argument('disable-gpu')
options.add_argument('disable-sync')
options.add_argument('disable-translate')
options.add_argument('hide-scrollbars')
options.add_argument('metrics-recording-only')
options.add_argument('no-first-run')
options.add_argument('safebrowsing-disable-auto-update')
options.add_argument('media-cache-size=1')
options.add_argument('disk-cache-size=1')
client = webdriver.Chrome(options=options)
client.get(f"http://localhost:1337/login")
time.sleep(3)
client.find_element(By.ID, "username").send_keys('admin')
client.find_element(By.ID, "password").send_keys(os.environ.get("ADMIN_PASSWD"))
client.execute_script("document.getElementById('login-btn').click()")
time.sleep(3)
client.get(f"http://localhost:1337/posts/view/{username}")
time.sleep(30)
client.quit()
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/TFC/2023/web/BABY_DUCKY_NOTES_REVENGE/src/app.py | ctfs/TFC/2023/web/BABY_DUCKY_NOTES_REVENGE/src/app.py | from flask import Flask, jsonify
from routes import web, api
import database.database as db
import os, datetime
app = Flask(__name__)
app.secret_key = os.urandom(30).hex()
app.config['LOG_DIR'] = './static/logs/'
db.db_init()
app.register_blueprint(web, url_prefix='/')
app.register_blueprint(api, url_prefix='/api')
@app.errorhandler(404)
def not_found(e):
return e, 404
@app.errorhandler(403)
def forbidden(e):
return e, 403
@app.errorhandler(400)
def bad_request(e):
return e, 400
@app.errorhandler(401)
def bad_request(e):
return e, 401
@app.errorhandler(Exception)
def handle_error(e):
if not e.args or "username" not in e.args[0].keys():
return e, 500
error_date = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
post = e.args[0]
log_message = f'"{error_date}" {post["username"]} {post["content"]}'
with open(f"{app.config['LOG_DIR']}{error_date}.txt", 'w') as f:
f.write(log_message)
return log_message, 500
app.run(host='0.0.0.0', port=1337, debug=False)
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/TFC/2023/web/BABY_DUCKY_NOTES_REVENGE/src/database/database.py | ctfs/TFC/2023/web/BABY_DUCKY_NOTES_REVENGE/src/database/database.py | import sqlite3, os
def query(con, query, args=(), one=False):
c = con.cursor()
c.execute(query, args)
rv = [dict((c.description[idx][0], value)
for idx, value in enumerate(row) if value != None) for row in c.fetchall()]
return (rv[0] if rv else None) if one else rv
def db_init():
con = sqlite3.connect('database/data.db')
# Create users database
query(con, '''
CREATE TABLE IF NOT EXISTS users (
id integer PRIMARY KEY,
username text NOT NULL,
password text NOT NULL
);
''')
query(con, f'''
INSERT INTO users (
username,
password
) VALUES (
'admin',
'{os.environ.get("ADMIN_PASSWD")}'
);
''')
# Create posts database
query(con, '''
CREATE TABLE IF NOT EXISTS posts (
id integer PRIMARY KEY,
user_id integer NOT NULL,
title text,
content text NOT NULL,
hidden boolean NOT NULL,
FOREIGN KEY (user_id) REFERENCES users (id)
);
''')
query(con, f'''
INSERT INTO posts (
user_id,
title,
content,
hidden
) VALUES (
1,
'Here is a ducky flag!',
'{os.environ.get("FLAG")}',
1
);
''')
con.commit()
def db_login(username, password):
con = sqlite3.connect('database/data.db')
user = query(con, 'SELECT username FROM users WHERE username = ? AND password = ?', (username, password,), True)
if user:
return True
return False
def db_register(username, password):
con = sqlite3.connect('database/data.db')
user = query(con, 'SELECT username FROM users WHERE username = ?', (username,), True)
if not user:
query(con, 'INSERT into users (username, password) VALUES (?, ?)', (username, password,))
con.commit()
return True
return False
def db_create_post(username, post):
con = sqlite3.connect('database/data.db')
user = query(con, 'SELECT id from users WHERE username = ?', (username,), True)
query(con, 'INSERT into posts (user_id, title, content, hidden) VALUES (?, ?, ?, ?)', (user['id'], post['title'], post['content'], post['hidden'],))
con.commit()
return True
def db_get_user_posts(username, hidden):
con = sqlite3.connect('database/data.db')
posts = query(con, 'SELECT users.username as username, title, content, hidden from posts INNER JOIN users ON users.id = posts.user_id WHERE users.username = ?', (username,))
return [post for post in posts if hidden or not post['hidden']]
def db_get_all_users_posts():
con = sqlite3.connect('database/data.db')
posts = query(con, 'SELECT users.username as username, title, content, hidden from posts INNER JOIN users ON users.id = posts.user_id ')
return posts
def db_delete_posts(username):
con = sqlite3.connect('database/data.db')
user = query(con, 'SELECT id from users WHERE username = ?', (username,), True)
query(con, 'DELETE FROM posts WHERE user_id = ?', (user['id'], ))
con.commit()
return True
def db_delete_all_posts():
con = sqlite3.connect('database/data.db')
query(con, 'DELETE FROM posts WHERE id != 1')
con.commit()
return True
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/TFC/2023/web/COOKIE_STORE/challenge/main.py | ctfs/TFC/2023/web/COOKIE_STORE/challenge/main.py | import os
import sqlite3
import json
from flask import Flask, render_template, request, redirect, url_for, session
from bot import bot
SECRET_KEY = os.urandom(32).hex()
app = Flask(__name__)
app.config['SECRET_KEY'] = SECRET_KEY
@app.route('/', methods=('GET',))
def index():
return redirect(url_for('form_builder'))
# Add 404 route
@app.errorhandler(404)
def page_not_found(e):
return render_template('404.html'), 404
@app.route('/form_builder', methods=('GET',))
def form_builder():
session['csrf_token'] = os.urandom(32).hex()
return render_template('form_builder.html')
@app.route('/form_builder', methods=('POST',))
def form_builder_post():
if 'csrf_token' not in session or session['csrf_token'] != request.form['csrf_token']:
return redirect(url_for('csrf_error.html'))
formdata = request.form.to_dict()
if 'csrf_token' in formdata:
del formdata["csrf_token"]
for key in formdata:
session[key] = formdata[key]
return redirect(url_for('view_form'))
@app.route('/view_data', methods=('GET',))
def view_form():
formdata = {}
for key in session:
formdata[key] = session[key]
del formdata["csrf_token"]
return render_template('view_form.html', formdata=formdata)
@app.route('/bot', methods=('GET',))
def bot_route():
return render_template('bot.html')
@app.route('/bot', methods=('POST',))
def bot_route_post():
fields = request.form['fields']
bot(fields)
return redirect('/')
app.run(host='0.0.0.0', port=1337) | python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/TFC/2023/web/COOKIE_STORE/challenge/bot.py | ctfs/TFC/2023/web/COOKIE_STORE/challenge/bot.py | from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.chrome.options import Options
import time
import urllib.parse
FLAG = "TFCCTF{fake_flag}"
def bot(fields):
chrome_options = Options()
chrome_options.add_argument('headless')
chrome_options.add_argument('no-sandbox')
chrome_options.add_argument('ignore-certificate-errors')
chrome_options.add_argument('disable-dev-shm-usage')
chrome_options.add_argument('disable-infobars')
chrome_options.add_argument('disable-background-networking')
chrome_options.add_argument('disable-default-apps')
chrome_options.add_argument('disable-extensions')
chrome_options.add_argument('disable-gpu')
chrome_options.add_argument('disable-sync')
chrome_options.add_argument('disable-translate')
chrome_options.add_argument('hide-scrollbars')
chrome_options.add_argument('metrics-recording-only')
chrome_options.add_argument('no-first-run')
chrome_options.add_argument('safebrowsing-disable-auto-update')
chrome_options.add_argument('media-cache-size=1')
chrome_options.add_argument('disk-cache-size=1')
client = webdriver.Chrome(options=chrome_options)
fields = urllib.parse.quote(fields)
time.sleep(2)
client.get(f"http://localhost:1337/form_builder?fields={fields}")
time.sleep(2)
try:
client.find_element(By.ID, "title").send_keys(FLAG)
except:
pass
client.execute_script("""document.querySelector('input[type="submit"]').click();""")
time.sleep(2)
client.quit()
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/TFC/2023/web/DUCKY_NOTES_PART_3/src/routes.py | ctfs/TFC/2023/web/DUCKY_NOTES_PART_3/src/routes.py | from flask import Blueprint, render_template, session, request, jsonify, abort
from database.database import db_login, db_register, db_create_post, db_get_user_posts, db_get_all_users_posts, db_delete_posts, db_delete_all_posts
import re, threading, datetime
from functools import wraps
from bot import bot
USERNAME_REGEX = re.compile('^[A-za-z0-9\.]{2,}$')
def auth_required(f):
@wraps(f)
def decorator(*args, **kwargs):
username = session.get('username')
if not username:
return abort(401, 'Not logged in!')
return f(username, *args, **kwargs)
return decorator
web = Blueprint('web', __name__)
api = Blueprint('api', __name__)
@web.route('/', methods=['GET'])
def index():
date = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
return render_template('index.html', current_date=date)
@web.route('/login')
def login():
return render_template('login.html')
@web.route('/register')
def register():
return render_template('register.html')
@web.route('/posts/', methods=['GET'])
@auth_required
def posts(username):
if username != 'admin':
return jsonify('You must be admin to see all posts!'), 401
frontend_posts = []
posts = db_get_all_users_posts()
for post in posts:
try:
frontend_posts += [{'username': post['username'],
'title': post['title'],
'content': post['content']}]
except:
raise Exception(post)
return render_template('posts.html', posts=frontend_posts)
@web.route('/posts/view/<user>', methods=['GET'])
@auth_required
def posts_view(username, user):
try:
posts = db_get_user_posts(user, username == user)
except:
raise Exception(username)
return render_template('posts.html', posts=posts)
@web.route('/posts/create', methods=['GET'])
@auth_required
def posts_create(username):
return render_template('create.html', username=username)
@api.route('/login', methods=['POST'])
def api_login():
if not request.is_json:
return jsonify('JSON is needed'), 400
data = request.get_json()
username = data.get('username', '')
password = data.get('password', '')
if not username or not password:
return jsonify('Username and password required!'), 401
if type(username) != str or type(password) != str:
return jsonify('Username or password wrong format!'), 402
user = db_login(username, password)
if user:
session['username'] = username
return jsonify('Success login'), 200
return jsonify('Invalid credentials!'), 403
@api.route('/register', methods=['POST'])
def api_register():
if not request.is_json:
return jsonify('JSON is needed'), 400
data = request.get_json()
username = data.get('username', '')
password = data.get('password', '')
if not username or not password:
return jsonify('Username and password required!'), 402
if type(username) != str or type(password) != str:
return jsonify('Username or password wrong format!'), 402
if USERNAME_REGEX.match(username) == None:
return jsonify('Can\'t create an account with that username'), 402
result = db_register(username, password)
if result:
return jsonify('Success register'), 200
return jsonify('Account already existing!'), 403
@api.route('/posts', methods=['POST'])
@auth_required
def api_create_post(username):
if not request.is_json:
return jsonify('JSON is needed'), 400
data = request.get_json()
title = data.get('title', None)
content = data.get('content', '')
hidden = data.get('hidden', None)
if not content or hidden == None:
return jsonify('Content and hidden value required!'), 401
if title and type(title) != str:
return jsonify('Title value wrong format!'), 402
if type(content) != str or type(hidden) != bool:
return jsonify('Content and hidden value wrong format!'), 402
db_create_post(username, {"title": title, "content": content, "hidden": hidden})
return jsonify('Post created successfully!'), 200
@api.route('/report', methods=['POST'])
@auth_required
def api_report(username):
thread = threading.Thread(target=bot, args=(username,))
thread.start()
return jsonify('Post reported successfully!'), 200
@api.route('/posts', methods=['DELETE'])
@auth_required
def api_delete_posts(username):
db_delete_posts(username)
return jsonify('All posts deleted successfully!'), 200
@api.route('/posts/all', methods=['DELETE'])
@auth_required
def api_delete_all_posts(username):
db_delete_all_posts()
return jsonify('All posts deleted successfully!'), 200 | python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/TFC/2023/web/DUCKY_NOTES_PART_3/src/bot.py | ctfs/TFC/2023/web/DUCKY_NOTES_PART_3/src/bot.py | from selenium import webdriver
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.common.by import By
import time, os
def bot(username):
options = Options()
options.add_argument('--no-sandbox')
options.add_argument('headless')
options.add_argument('ignore-certificate-errors')
options.add_argument('disable-dev-shm-usage')
options.add_argument('disable-infobars')
options.add_argument('disable-background-networking')
options.add_argument('disable-default-apps')
options.add_argument('disable-extensions')
options.add_argument('disable-gpu')
options.add_argument('disable-sync')
options.add_argument('disable-translate')
options.add_argument('hide-scrollbars')
options.add_argument('metrics-recording-only')
options.add_argument('no-first-run')
options.add_argument('safebrowsing-disable-auto-update')
options.add_argument('media-cache-size=1')
options.add_argument('disk-cache-size=1')
client = webdriver.Chrome(options=options)
client.get(f"http://localhost:1337/login")
time.sleep(3)
client.find_element(By.ID, "username").send_keys('admin')
client.find_element(By.ID, "password").send_keys(os.environ.get("ADMIN_PASSWD"))
client.execute_script("document.getElementById('login-btn').click()")
time.sleep(3)
client.get(f"http://localhost:1337/posts/view/{username}")
time.sleep(30)
client.quit()
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/TFC/2023/web/DUCKY_NOTES_PART_3/src/app.py | ctfs/TFC/2023/web/DUCKY_NOTES_PART_3/src/app.py | from flask import Flask, jsonify
from routes import web, api
import database.database as db
import os, datetime
app = Flask(__name__)
app.secret_key = os.urandom(30).hex()
app.config['LOG_DIR'] = './static/logs/'
db.db_init()
app.register_blueprint(web, url_prefix='/')
app.register_blueprint(api, url_prefix='/api')
@app.errorhandler(404)
def not_found(e):
return e, 404
@app.errorhandler(403)
def forbidden(e):
return e, 403
@app.errorhandler(400)
def bad_request(e):
return e, 400
@app.errorhandler(401)
def bad_request(e):
return e, 401
@app.errorhandler(Exception)
def handle_error(e):
if not e.args or "username" not in e.args[0].keys():
return e, 500
error_date = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
post = e.args[0]
log_message = f'"{error_date}" {post["username"]} {post["content"]}'
with open(f"{app.config['LOG_DIR']}{error_date}.txt", 'w') as f:
f.write(log_message)
return log_message, 500
app.run(host='0.0.0.0', port=1337, debug=False)
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/TFC/2023/web/DUCKY_NOTES_PART_3/src/database/database.py | ctfs/TFC/2023/web/DUCKY_NOTES_PART_3/src/database/database.py | import sqlite3, os
def query(con, query, args=(), one=False):
c = con.cursor()
c.execute(query, args)
rv = [dict((c.description[idx][0], value)
for idx, value in enumerate(row) if value != None) for row in c.fetchall()]
return (rv[0] if rv else None) if one else rv
def db_init():
con = sqlite3.connect('database/data.db')
# Create users database
query(con, '''
CREATE TABLE IF NOT EXISTS users (
id integer PRIMARY KEY,
username text NOT NULL,
password text NOT NULL
);
''')
query(con, f'''
INSERT INTO users (
username,
password
) VALUES (
'admin',
'{os.environ.get("ADMIN_PASSWD")}'
);
''')
# Create posts database
query(con, '''
CREATE TABLE IF NOT EXISTS posts (
id integer PRIMARY KEY,
user_id integer NOT NULL,
title text,
content text NOT NULL,
hidden boolean NOT NULL,
FOREIGN KEY (user_id) REFERENCES users (id)
);
''')
query(con, f'''
INSERT INTO posts (
user_id,
title,
content,
hidden
) VALUES (
1,
'Here is a ducky flag!',
'{os.environ.get("FLAG")}',
1
);
''')
con.commit()
def db_login(username, password):
con = sqlite3.connect('database/data.db')
user = query(con, 'SELECT username FROM users WHERE username = ? AND password = ?', (username, password,), True)
if user:
return True
return False
def db_register(username, password):
con = sqlite3.connect('database/data.db')
user = query(con, 'SELECT username FROM users WHERE username = ?', (username,), True)
if not user:
query(con, 'INSERT into users (username, password) VALUES (?, ?)', (username, password,))
con.commit()
return True
return False
def db_create_post(username, post):
con = sqlite3.connect('database/data.db')
user = query(con, 'SELECT id from users WHERE username = ?', (username,), True)
query(con, 'INSERT into posts (user_id, title, content, hidden) VALUES (?, ?, ?, ?)', (user['id'], post['title'], post['content'], post['hidden'],))
con.commit()
return True
def db_get_user_posts(username, hidden):
con = sqlite3.connect('database/data.db')
posts = query(con, 'SELECT users.username as username, title, content, hidden from posts INNER JOIN users ON users.id = posts.user_id WHERE users.username = ?', (username,))
return [post for post in posts if hidden or not post['hidden']]
def db_get_all_users_posts():
con = sqlite3.connect('database/data.db')
posts = query(con, 'SELECT users.username as username, title, content, hidden from posts INNER JOIN users ON users.id = posts.user_id ')
return posts
def db_delete_posts(username):
con = sqlite3.connect('database/data.db')
user = query(con, 'SELECT id from users WHERE username = ?', (username,), True)
query(con, 'DELETE FROM posts WHERE user_id = ?', (user['id'], ))
con.commit()
return True
def db_delete_all_posts():
con = sqlite3.connect('database/data.db')
query(con, 'DELETE FROM posts WHERE id != 1')
con.commit()
return True
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/TFC/2023/web/BABY_DUCKY_NOTES/src/routes.py | ctfs/TFC/2023/web/BABY_DUCKY_NOTES/src/routes.py | from flask import Blueprint, render_template, session, request, jsonify, abort
from database.database import db_login, db_register, db_create_post, db_get_user_posts, db_get_all_users_posts, db_delete_posts, db_delete_all_posts
import re, threading, datetime
from functools import wraps
from bot import bot
USERNAME_REGEX = re.compile('^[A-za-z0-9\.]{2,}$')
def auth_required(f):
@wraps(f)
def decorator(*args, **kwargs):
username = session.get('username')
if not username:
return abort(401, 'Not logged in!')
return f(username, *args, **kwargs)
return decorator
web = Blueprint('web', __name__)
api = Blueprint('api', __name__)
@web.route('/', methods=['GET'])
def index():
date = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
return render_template('index.html', current_date=date)
@web.route('/login')
def login():
return render_template('login.html')
@web.route('/register')
def register():
return render_template('register.html')
@web.route('/posts/', methods=['GET'])
@auth_required
def posts(username):
if username != 'admin':
return jsonify('You must be admin to see all posts!'), 401
frontend_posts = []
posts = db_get_all_users_posts()
for post in posts:
try:
frontend_posts += [{'username': post['username'],
'title': post['title'],
'content': post['content']}]
except:
raise Exception(post)
return render_template('posts.html', posts=frontend_posts)
@web.route('/posts/view/<user>', methods=['GET'])
@auth_required
def posts_view(username, user):
try:
posts = db_get_user_posts(user, username == user)
except:
raise Exception(username)
return render_template('posts.html', posts=posts)
@web.route('/posts/create', methods=['GET'])
@auth_required
def posts_create(username):
return render_template('create.html', username=username)
@api.route('/login', methods=['POST'])
def api_login():
if not request.is_json:
return jsonify('JSON is needed'), 400
data = request.get_json()
username = data.get('username', '')
password = data.get('password', '')
if not username or not password:
return jsonify('Username and password required!'), 401
if type(username) != str or type(password) != str:
return jsonify('Username or password wrong format!'), 402
user = db_login(username, password)
if user:
session['username'] = username
return jsonify('Success login'), 200
return jsonify('Invalid credentials!'), 403
@api.route('/register', methods=['POST'])
def api_register():
if not request.is_json:
return jsonify('JSON is needed'), 400
data = request.get_json()
username = data.get('username', '')
password = data.get('password', '')
if not username or not password:
return jsonify('Username and password required!'), 402
if type(username) != str or type(password) != str:
return jsonify('Username or password wrong format!'), 402
if USERNAME_REGEX.match(username) == None:
return jsonify('Can\'t create an account with that username'), 402
result = db_register(username, password)
if result:
return jsonify('Success register'), 200
return jsonify('Account already existing!'), 403
@api.route('/posts', methods=['POST'])
@auth_required
def api_create_post(username):
if not request.is_json:
return jsonify('JSON is needed'), 400
data = request.get_json()
title = data.get('title', None)
content = data.get('content', '')
hidden = data.get('hidden', None)
if not content or hidden == None:
return jsonify('Content and hidden value required!'), 401
if title and type(title) != str:
return jsonify('Title value wrong format!'), 402
if type(content) != str or type(hidden) != bool:
return jsonify('Content and hidden value wrong format!'), 402
db_create_post(username, {"title": title, "content": content, "hidden": hidden})
return jsonify('Post created successfully!'), 200
@api.route('/report', methods=['POST'])
@auth_required
def api_report(username):
thread = threading.Thread(target=bot, args=(username,))
thread.start()
return jsonify('Post reported successfully!'), 200
@api.route('/posts', methods=['DELETE'])
@auth_required
def api_delete_posts(username):
db_delete_posts(username)
return jsonify('All posts deleted successfully!'), 200
@api.route('/posts/all', methods=['DELETE'])
@auth_required
def api_delete_all_posts(username):
db_delete_all_posts()
return jsonify('All posts deleted successfully!'), 200 | python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/TFC/2023/web/BABY_DUCKY_NOTES/src/bot.py | ctfs/TFC/2023/web/BABY_DUCKY_NOTES/src/bot.py | from selenium import webdriver
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.common.by import By
import time, os
def bot(username):
options = Options()
options.add_argument('--no-sandbox')
options.add_argument('headless')
options.add_argument('ignore-certificate-errors')
options.add_argument('disable-dev-shm-usage')
options.add_argument('disable-infobars')
options.add_argument('disable-background-networking')
options.add_argument('disable-default-apps')
options.add_argument('disable-extensions')
options.add_argument('disable-gpu')
options.add_argument('disable-sync')
options.add_argument('disable-translate')
options.add_argument('hide-scrollbars')
options.add_argument('metrics-recording-only')
options.add_argument('no-first-run')
options.add_argument('safebrowsing-disable-auto-update')
options.add_argument('media-cache-size=1')
options.add_argument('disk-cache-size=1')
client = webdriver.Chrome(options=options)
client.get(f"http://localhost:1337/login")
time.sleep(3)
client.find_element(By.ID, "username").send_keys('admin')
client.find_element(By.ID, "password").send_keys(os.environ.get("ADMIN_PASSWD"))
client.execute_script("document.getElementById('login-btn').click()")
time.sleep(3)
client.get(f"http://localhost:1337/posts/view/{username}")
time.sleep(30)
client.quit()
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/TFC/2023/web/BABY_DUCKY_NOTES/src/app.py | ctfs/TFC/2023/web/BABY_DUCKY_NOTES/src/app.py | from flask import Flask, jsonify
from routes import web, api
import database.database as db
import os, datetime
app = Flask(__name__)
app.secret_key = os.urandom(30).hex()
app.config['LOG_DIR'] = './static/logs/'
db.db_init()
app.register_blueprint(web, url_prefix='/')
app.register_blueprint(api, url_prefix='/api')
@app.errorhandler(404)
def not_found(e):
return e, 404
@app.errorhandler(403)
def forbidden(e):
return e, 403
@app.errorhandler(400)
def bad_request(e):
return e, 400
@app.errorhandler(401)
def bad_request(e):
return e, 401
@app.errorhandler(Exception)
def handle_error(e):
if not e.args or "username" not in e.args[0].keys():
return e, 500
error_date = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
post = e.args[0]
log_message = f'"{error_date}" {post["username"]} {post["content"]}'
with open(f"{app.config['LOG_DIR']}{error_date}.txt", 'w') as f:
f.write(log_message)
return log_message, 500
app.run(host='0.0.0.0', port=1337, debug=False)
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/TFC/2023/web/BABY_DUCKY_NOTES/src/database/database.py | ctfs/TFC/2023/web/BABY_DUCKY_NOTES/src/database/database.py | import sqlite3, os
def query(con, query, args=(), one=False):
c = con.cursor()
c.execute(query, args)
rv = [dict((c.description[idx][0], value)
for idx, value in enumerate(row) if value != None) for row in c.fetchall()]
return (rv[0] if rv else None) if one else rv
def db_init():
con = sqlite3.connect('database/data.db')
# Create users database
query(con, '''
CREATE TABLE IF NOT EXISTS users (
id integer PRIMARY KEY,
username text NOT NULL,
password text NOT NULL
);
''')
query(con, f'''
INSERT INTO users (
username,
password
) VALUES (
'admin',
'{os.environ.get("ADMIN_PASSWD")}'
);
''')
# Create posts database
query(con, '''
CREATE TABLE IF NOT EXISTS posts (
id integer PRIMARY KEY,
user_id integer NOT NULL,
title text,
content text NOT NULL,
hidden boolean NOT NULL,
FOREIGN KEY (user_id) REFERENCES users (id)
);
''')
query(con, f'''
INSERT INTO posts (
user_id,
title,
content,
hidden
) VALUES (
1,
'Here is a ducky flag!',
'{os.environ.get("FLAG")}',
0
);
''')
con.commit()
def db_login(username, password):
con = sqlite3.connect('database/data.db')
user = query(con, 'SELECT username FROM users WHERE username = ? AND password = ?', (username, password,), True)
if user:
return True
return False
def db_register(username, password):
con = sqlite3.connect('database/data.db')
user = query(con, 'SELECT username FROM users WHERE username = ?', (username,), True)
if not user:
query(con, 'INSERT into users (username, password) VALUES (?, ?)', (username, password,))
con.commit()
return True
return False
def db_create_post(username, post):
con = sqlite3.connect('database/data.db')
user = query(con, 'SELECT id from users WHERE username = ?', (username,), True)
query(con, 'INSERT into posts (user_id, title, content, hidden) VALUES (?, ?, ?, ?)', (user['id'], post['title'], post['content'], post['hidden'],))
con.commit()
return True
def db_get_user_posts(username, hidden):
con = sqlite3.connect('database/data.db')
posts = query(con, 'SELECT users.username as username, title, content, hidden from posts INNER JOIN users ON users.id = posts.user_id WHERE users.username = ?', (username,))
return [post for post in posts if hidden or not post['hidden']]
def db_get_all_users_posts():
con = sqlite3.connect('database/data.db')
posts = query(con, 'SELECT users.username as username, title, content, hidden from posts INNER JOIN users ON users.id = posts.user_id ')
return posts
def db_delete_posts(username):
con = sqlite3.connect('database/data.db')
user = query(con, 'SELECT id from users WHERE username = ?', (username,), True)
query(con, 'DELETE FROM posts WHERE user_id = ?', (user['id'], ))
con.commit()
return True
def db_delete_all_posts():
con = sqlite3.connect('database/data.db')
query(con, 'DELETE FROM posts WHERE id != 1')
con.commit()
return True
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/TFC/2023/web/DUCKY_NOTES_ENDGAME/src/routes.py | ctfs/TFC/2023/web/DUCKY_NOTES_ENDGAME/src/routes.py | from flask import Blueprint, render_template, session, request, jsonify, abort
from database.database import db_login, db_register, db_create_post, db_get_user_posts, db_get_all_users_posts, db_delete_posts, db_delete_all_posts
import re, threading, datetime
from functools import wraps
from bot import bot
USERNAME_REGEX = re.compile('^[A-za-z0-9\.]{2,}$')
def auth_required(f):
@wraps(f)
def decorator(*args, **kwargs):
username = session.get('username')
if not username:
return abort(401, 'Not logged in!')
return f(username, *args, **kwargs)
return decorator
web = Blueprint('web', __name__)
api = Blueprint('api', __name__)
@web.route('/', methods=['GET'])
def index():
date = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
return render_template('index.html', current_date=date)
@web.route('/login')
def login():
return render_template('login.html')
@web.route('/register')
def register():
return render_template('register.html')
@web.route('/posts/', methods=['GET'])
@auth_required
def posts(username):
if username != 'admin':
return jsonify('You must be admin to see all posts!'), 401
frontend_posts = []
posts = db_get_all_users_posts()
for post in posts:
try:
frontend_posts += [{'username': post['username'],
'title': post['title'],
'content': post['content']}]
except:
raise Exception(post)
return render_template('posts.html', posts=frontend_posts)
@web.route('/posts/view/<user>', methods=['GET'])
@auth_required
def posts_view(username, user):
try:
posts = db_get_user_posts(user, username == user)
except:
raise Exception(username)
return render_template('posts.html', posts=posts)
@web.route('/posts/create', methods=['GET'])
@auth_required
def posts_create(username):
return render_template('create.html', username=username)
@api.route('/login', methods=['POST'])
def api_login():
if not request.is_json:
return jsonify('JSON is needed'), 400
data = request.get_json()
username = data.get('username', '')
password = data.get('password', '')
if not username or not password:
return jsonify('Username and password required!'), 401
if type(username) != str or type(password) != str:
return jsonify('Username or password wrong format!'), 402
user = db_login(username, password)
if user:
session['username'] = username
return jsonify('Success login'), 200
return jsonify('Invalid credentials!'), 403
@api.route('/register', methods=['POST'])
def api_register():
if not request.is_json:
return jsonify('JSON is needed'), 400
data = request.get_json()
username = data.get('username', '')
password = data.get('password', '')
if not username or not password:
return jsonify('Username and password required!'), 402
if type(username) != str or type(password) != str:
return jsonify('Username or password wrong format!'), 402
if USERNAME_REGEX.match(username) == None:
return jsonify('Can\'t create an account with that username'), 402
result = db_register(username, password)
if result:
return jsonify('Success register'), 200
return jsonify('Account already existing!'), 403
@api.route('/posts', methods=['POST'])
@auth_required
def api_create_post(username):
if not request.is_json:
return jsonify('JSON is needed'), 400
data = request.get_json()
title = data.get('title', None)
content = data.get('content', '')
hidden = data.get('hidden', None)
if not content or hidden == None:
return jsonify('Content and hidden value required!'), 401
if title and type(title) != str:
return jsonify('Title value wrong format!'), 402
if type(content) != str or type(hidden) != bool:
return jsonify('Content and hidden value wrong format!'), 402
db_create_post(username, {"title": title, "content": content, "hidden": hidden})
return jsonify('Post created successfully!'), 200
@api.route('/report', methods=['POST'])
@auth_required
def api_report(username):
thread = threading.Thread(target=bot, args=(username,))
thread.start()
return jsonify('Post reported successfully!'), 200
@api.route('/posts', methods=['DELETE'])
@auth_required
def api_delete_posts(username):
db_delete_posts(username)
return jsonify('All posts deleted successfully!'), 200
@api.route('/posts/all', methods=['DELETE'])
@auth_required
def api_delete_all_posts(username):
db_delete_all_posts()
return jsonify('All posts deleted successfully!'), 200 | python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/TFC/2023/web/DUCKY_NOTES_ENDGAME/src/bot.py | ctfs/TFC/2023/web/DUCKY_NOTES_ENDGAME/src/bot.py | from selenium import webdriver
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.common.by import By
import time, os
def bot(username):
options = Options()
options.add_argument('--no-sandbox')
options.add_argument('headless')
options.add_argument('ignore-certificate-errors')
options.add_argument('disable-dev-shm-usage')
options.add_argument('disable-infobars')
options.add_argument('disable-background-networking')
options.add_argument('disable-default-apps')
options.add_argument('disable-extensions')
options.add_argument('disable-gpu')
options.add_argument('disable-sync')
options.add_argument('disable-translate')
options.add_argument('hide-scrollbars')
options.add_argument('metrics-recording-only')
options.add_argument('no-first-run')
options.add_argument('safebrowsing-disable-auto-update')
options.add_argument('media-cache-size=1')
options.add_argument('disk-cache-size=1')
client = webdriver.Chrome(options=options)
client.get(f"http://localhost:1337/login")
time.sleep(3)
client.find_element(By.ID, "username").send_keys('admin')
client.find_element(By.ID, "password").send_keys(os.environ.get("ADMIN_PASSWD"))
client.execute_script("document.getElementById('login-btn').click()")
time.sleep(3)
client.get(f"http://localhost:1337/posts/view/{username}")
time.sleep(30)
client.quit()
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/TFC/2023/web/DUCKY_NOTES_ENDGAME/src/app.py | ctfs/TFC/2023/web/DUCKY_NOTES_ENDGAME/src/app.py | from flask import Flask, jsonify
from routes import web, api
import database.database as db
import os, datetime
app = Flask(__name__)
app.secret_key = os.urandom(30).hex()
app.config['LOG_DIR'] = './static/logs/'
db.db_init()
app.register_blueprint(web, url_prefix='/')
app.register_blueprint(api, url_prefix='/api')
@app.after_request
def add_header(response):
response.headers['X-Frame-Options'] = 'SAMEORIGIN'
response.headers['Content-Security-Policy'] = "default-src 'self'; object-src 'none';"
return response
@app.errorhandler(404)
def not_found(e):
return e, 404
@app.errorhandler(403)
def forbidden(e):
return e, 403
@app.errorhandler(400)
def bad_request(e):
return e, 400
@app.errorhandler(401)
def bad_request(e):
return e, 401
@app.errorhandler(Exception)
def handle_error(e):
if not e.args or "username" not in e.args[0].keys():
return e, 500
error_date = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
post = e.args[0]
log_message = f'"{error_date}" {post["username"]} {post["content"]}'
with open(f"{app.config['LOG_DIR']}{error_date}.txt", 'w') as f:
f.write(log_message)
return log_message, 500
app.run(host='0.0.0.0', port=1337, debug=False)
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/TFC/2023/web/DUCKY_NOTES_ENDGAME/src/database/database.py | ctfs/TFC/2023/web/DUCKY_NOTES_ENDGAME/src/database/database.py | import sqlite3, os
def query(con, query, args=(), one=False):
c = con.cursor()
c.execute(query, args)
rv = [dict((c.description[idx][0], value)
for idx, value in enumerate(row) if value != None) for row in c.fetchall()]
return (rv[0] if rv else None) if one else rv
def db_init():
con = sqlite3.connect('database/data.db')
# Create users database
query(con, '''
CREATE TABLE IF NOT EXISTS users (
id integer PRIMARY KEY,
username text NOT NULL,
password text NOT NULL
);
''')
query(con, f'''
INSERT INTO users (
username,
password
) VALUES (
'admin',
'{os.environ.get("ADMIN_PASSWD")}'
);
''')
# Create posts database
query(con, '''
CREATE TABLE IF NOT EXISTS posts (
id integer PRIMARY KEY,
user_id integer NOT NULL,
title text,
content text NOT NULL,
hidden boolean NOT NULL,
FOREIGN KEY (user_id) REFERENCES users (id)
);
''')
query(con, f'''
INSERT INTO posts (
user_id,
title,
content,
hidden
) VALUES (
1,
'Here is a ducky flag!',
'{os.environ.get("FLAG")}',
1
);
''')
con.commit()
def db_login(username, password):
con = sqlite3.connect('database/data.db')
user = query(con, 'SELECT username FROM users WHERE username = ? AND password = ?', (username, password,), True)
if user:
return True
return False
def db_register(username, password):
con = sqlite3.connect('database/data.db')
user = query(con, 'SELECT username FROM users WHERE username = ?', (username,), True)
if not user:
query(con, 'INSERT into users (username, password) VALUES (?, ?)', (username, password,))
con.commit()
return True
return False
def db_create_post(username, post):
con = sqlite3.connect('database/data.db')
user = query(con, 'SELECT id from users WHERE username = ?', (username,), True)
query(con, 'INSERT into posts (user_id, title, content, hidden) VALUES (?, ?, ?, ?)', (user['id'], post['title'], post['content'], post['hidden'],))
con.commit()
return True
def db_get_user_posts(username, hidden):
con = sqlite3.connect('database/data.db')
posts = query(con, 'SELECT users.username as username, title, content, hidden from posts INNER JOIN users ON users.id = posts.user_id WHERE users.username = ?', (username,))
return [post for post in posts if hidden or not post['hidden']]
def db_get_all_users_posts():
con = sqlite3.connect('database/data.db')
posts = query(con, 'SELECT users.username as username, title, content, hidden from posts INNER JOIN users ON users.id = posts.user_id ')
return posts
def db_delete_posts(username):
con = sqlite3.connect('database/data.db')
user = query(con, 'SELECT id from users WHERE username = ?', (username,), True)
query(con, 'DELETE FROM posts WHERE user_id = ?', (user['id'], ))
con.commit()
return True
def db_delete_all_posts():
con = sqlite3.connect('database/data.db')
query(con, 'DELETE FROM posts WHERE id != 1')
con.commit()
return True
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/TFC/2022/crypto/ADMIN_PANEL_BUT_HARDER_AND_FIXED/main.py | ctfs/TFC/2022/crypto/ADMIN_PANEL_BUT_HARDER_AND_FIXED/main.py | import os
import random
from Crypto.Cipher import AES
KEY = os.urandom(16)
PASSWORD = os.urandom(16)
FLAG = os.getenv('FLAG')
menu = """========================
1. Access Flag
2. Change Password
========================"""
def xor(bytes_first, bytes_second):
d = b''
for i in range(len(bytes_second)):
d += bytes([bytes_first[i] ^ bytes_second[i]])
return d
def decrypt(ciphertext):
iv = ciphertext[:16]
ct = ciphertext[16:]
cipher = AES.new(KEY, AES.MODE_ECB)
pt = b''
state = iv
for i in range(len(ct)):
b = cipher.encrypt(state)[0]
c = b ^ ct[i]
pt += bytes([c])
state = state[1:] + bytes([ct[i]])
return pt
if __name__ == "__main__":
while True:
print(menu)
option = int(input("> "))
if option == 1:
password = bytes.fromhex(input("Password > "))
if password == PASSWORD:
print(FLAG)
exit(0)
else:
print("Wrong password!")
continue
elif option == 2:
token = input("Token > ").strip()
if len(token) != 64:
print("Wrong length!")
continue
hex_token = bytes.fromhex(token)
r_bytes = random.randbytes(32)
print(f"XORing with: {r_bytes.hex()}")
xorred = xor(r_bytes, hex_token)
PASSWORD = decrypt(xorred)
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/TFC/2022/crypto/TRAIN_TO_PADDINGTON/main.py | ctfs/TFC/2022/crypto/TRAIN_TO_PADDINGTON/main.py | import os
BLOCK_SIZE = 16
FLAG = b'|||REDACTED|||'
def pad_pt(pt):
amount_padding = 16 if (16 - len(pt) % 16) == 0 else 16 - len(pt) % 16
return pt + (b'\x3f' * amount_padding)
pt = pad_pt(FLAG)
key = os.urandom(BLOCK_SIZE)
ct = b''
j = 0
for i in range(len(pt)):
ct += (key[j] ^ pt[i]).to_bytes(1, 'big')
j += 1
j %= 16
with open('output.txt', 'w') as f:
f.write(ct.hex()) | python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/TFC/2022/crypto/ADMIN_PANEL/main.py | ctfs/TFC/2022/crypto/ADMIN_PANEL/main.py | import os
import random
from Crypto.Cipher import AES
KEY = os.urandom(16)
PASSWORD = os.urandom(16)
FLAG = os.getenv('FLAG')
menu = """========================
1. Access Flag
2. Change Password
========================"""
def xor(byte, bytes_second):
d = b''
for i in range(len(bytes_second)):
d += bytes([byte ^ bytes_second[i]])
return d
def decrypt(ciphertext):
iv = ciphertext[:16]
ct = ciphertext[16:]
cipher = AES.new(KEY, AES.MODE_ECB)
pt = b''
state = iv
for i in range(len(ct)):
b = cipher.encrypt(state)[0]
c = b ^ ct[i]
pt += bytes([c])
state = state[1:] + bytes([ct[i]])
return pt
if __name__ == "__main__":
while True:
print(menu)
option = int(input("> "))
if option == 1:
password = bytes.fromhex(input("Password > "))
if password == PASSWORD:
print(FLAG)
exit(0)
else:
print("Wrong password!")
continue
elif option == 2:
token = input("Token > ")
if len(token) != 64:
print("Wrong length!")
continue
hex_token = bytes.fromhex(token)
r_byte = random.randbytes(1)
print(f"XORing with: {r_byte.hex()}")
xorred = xor(r_byte[0], hex_token)
PASSWORD = decrypt(xorred)
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/TFC/2022/crypto/ADMIN_PANEL_BUT_HARDER/main.py | ctfs/TFC/2022/crypto/ADMIN_PANEL_BUT_HARDER/main.py | import os
import random
from Crypto.Cipher import AES
KEY = os.urandom(16)
PASSWORD = os.urandom(16)
FLAG = os.getenv('FLAG')
menu = """========================
1. Access Flag
2. Change Password
========================"""
def xor(bytes_first, bytes_second):
d = b''
for i in range(len(bytes_second)):
d += bytes([bytes_first[i] ^ bytes_second[i]])
return d
def decrypt(ciphertext):
iv = ciphertext[:16]
ct = ciphertext[16:]
cipher = AES.new(KEY, AES.MODE_ECB)
pt = b''
state = iv
for i in range(len(ct)):
b = cipher.encrypt(state)[0]
c = b ^ ct[i]
pt += bytes([c])
state = state[1:] + bytes([ct[i]])
return pt
if __name__ == "__main__":
while True:
print(menu)
option = int(input("> "))
if option == 1:
password = bytes.fromhex(input("Password > "))
if password == PASSWORD:
print(FLAG)
exit(0)
else:
print("Wrong password!")
continue
elif option == 2:
token = input("Token > ")
if len(token) != 64:
print("Wrong length!")
continue
hex_token = bytes.fromhex(token)
r_bytes = random.randbytes(32)
print(f"XORing with: {r_bytes.hex()}")
xorred = xor(r_bytes, hex_token)
PASSWORD = decrypt(xorred)
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/SCTF/2021/pwn/Christmas_Song/server.py | ctfs/SCTF/2021/pwn/Christmas_Song/server.py | #! /usr/bin/python3
import os
import subprocess
import sys
import uuid
def socket_print(string):
print("=====", string, flush=True)
def get_user_input():
socket_print("Enter partial source for edge compute app (EOF to finish):")
user_input = []
while True:
try:
line = input()
except EOFError:
break
if line == "EOF":
break
user_input.append(line)
socket_print("Input accepted!")
return user_input
def write_to_slang(contents, filename):
socket_print("Writing source to disk...")
with open("{}.slang".format(filename), 'w') as fd:
fd.write('\n'.join(contents))
def run_challenge(filename):
socket_print("Testing edge compute app...")
try:
result = subprocess.run("/home/ctf/Christmas_Song -r {}.slang".format(filename), shell=True, timeout=1)
except subprocess.TimeoutExpired:
pass
clean(filename);
socket_print("Test complete!")
def get_filename():
return "/tmp/{}".format(uuid.uuid4().hex)
def clean(filename):
result = subprocess.run("rm {}.*".format(filename), shell=True, timeout=10)
def main():
user_input = get_user_input()
if (len(user_input) == 0):
exit()
filename = get_filename()
write_to_slang(user_input, filename)
run_challenge(filename)
if __name__ == "__main__":
main()
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/SCTF/2021/pwn/Christmas_Bash/server.py | ctfs/SCTF/2021/pwn/Christmas_Bash/server.py | #! /usr/bin/python3
import os
import subprocess
import sys
import uuid
import urllib.request
def socket_print(string):
print("=====", string, flush=True)
def get_user_input(filename):
socket_print("please input your flag url: ")
url = input()
urllib.request.urlretrieve(url,filename)
socket_print("Okay, now I've got the file")
def run_challenge(filename):
socket_print("Don't think I don't know what you're up to.")
socket_print("You must be a little hack who just learned the Christmas song!")
socket_print("Come let me test what you gave me!")
result = subprocess.run("/home/ctf/Christmas_Bash -r {} < /dev/null".format(filename), shell=True)
print(result)
if (result == "hellow!"):
socket_print("wow, that looks a bit unusual, I'll try to decompile it and see.")
subprocess.run("/home/ctf/Christmas_Bash -r {} -d {} < /dev/null".format(filename, filename), shell=True)
else:
socket_print("Hahahahahahahahahahahahaha, indeed, you should also continue to learn Christmas songs!")
clean(filename);
def get_filename():
return "/tmp/{}.scom".format(uuid.uuid4().hex)
def clean(filename):
result = subprocess.run("rm {}".format(filename), shell=True, timeout=10)
def main():
filename = get_filename()
get_user_input(filename)
run_challenge(filename)
if __name__ == "__main__":
main()
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/SCTF/2021/crypto/ciruit_map/gen_key.py | ctfs/SCTF/2021/crypto/ciruit_map/gen_key.py |
import json
from block_cipher import decrypt
from random import randrange
from yao_circuit import GarbledGate as Ggate
flag = b'****************'
circuit_filename = "circuit_map.json"
with open(circuit_filename) as json_file:
circuit = json.load(json_file)
def init_keys(circuit):
keys = {}
gates = circuit["gates"]
wires = set()
for gate in gates:
wires.add(gate["id"])
wires.update(set(gate["in"]))
for wireidx in wires:
# the index of keys[wireidx] 1 and 0 means TRUE and FALSE in garbled circuit
keys[wireidx] = (randrange(0, 2**24),randrange(0, 2**24))
return keys
def validate_the_circuit(geta_table, key0, key1):
for g in geta_table:
gl, v = g
label = decrypt(gl, key0, key1)
validation = decrypt(v, key0, key1)
if validation == 0:
return label
def init_garbled_tables(circuit,keys):
gates = circuit["gates"]
garbled_tables = {}
for gate in gates:
garbled_table = Ggate(gate, keys)
garbled_tables[gate["id"]] = garbled_table
return garbled_tables
keys = init_keys(circuit)
G_Table = init_garbled_tables(circuit,keys)
# ic(keys)
# ic(G_Table)
# hint
# circuit wiring has only one situation mack ASSERT be true
geta_table = G_Table[9]
key0 = keys[7][1]
key1 = keys[4][0]
msg = validate_the_circuit(geta_table, key0, key1)
assert msg == keys[circuit["out"][0]][1]
#
with open("public_data.py","r+") as f:
print("G_Table = {}".format(G_Table),file=f)
with open("private_data.py","r+") as f:
print("keys = {}".format(keys),file=f)
print("flag = {}".format(str(flag)),file=f)
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/SCTF/2021/crypto/ciruit_map/task.py | ctfs/SCTF/2021/crypto/ciruit_map/task.py | import hashlib
from icecream import *
from private_data import keys,flag
from Crypto.Util.number import *
def xor(A, B):
return bytes(a ^ b for a, b in zip(A, B))
the_chaos=b''
for i in keys:
tmp = sum(keys[i])
the_chaos += bytes(long_to_bytes(tmp))
mask = hashlib.md5(the_chaos).digest()
print(xor(mask,flag).hex())
# 1661fe85c7b01b3db1d432ad3c5ac83a | python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/SCTF/2021/crypto/ciruit_map/public_data.py | ctfs/SCTF/2021/crypto/ciruit_map/public_data.py | G_Table = { 5: [(13303835, 2123830),
(2801785, 11303723),
(13499998, 248615),
(13892520, 7462011)],
6: [(3244202, 918053),
(3277177, 6281266),
(1016382, 7097624),
(10016472, 13600867)],
7: [(5944875, 3442862),
(7358369, 8423543),
(6495696, 9927178),
(13271900, 11855272)],
9: [(5333988, 87113),
(9375869, 11687470),
(5011062, 14981756),
(2509493, 12330305)]}
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/SCTF/2021/crypto/ciruit_map/block_cipher.py | ctfs/SCTF/2021/crypto/ciruit_map/block_cipher.py | SBoxes = [[15, 1, 7, 0, 9, 6, 2, 14, 11, 8, 5, 3, 12, 13, 4, 10], [3, 7, 8, 9, 11, 0, 15, 13, 4, 1, 10, 2, 14, 6, 12, 5], [4, 12, 9, 8, 5, 13, 11, 7, 6, 3, 10, 14, 15, 1, 2, 0], [2, 4, 10, 5, 7, 13, 1, 15, 0, 11, 3, 12, 14, 9, 8, 6], [3, 8, 0, 2, 13, 14, 5, 11, 9, 1, 7, 12, 4, 6, 10, 15], [14, 12, 7, 0, 11, 4, 13, 15, 10, 3, 8, 9, 2, 6, 1, 5]]
SInvBoxes = [[3, 1, 6, 11, 14, 10, 5, 2, 9, 4, 15, 8, 12, 13, 7, 0], [5, 9, 11, 0, 8, 15, 13, 1, 2, 3, 10, 4, 14, 7, 12, 6], [15, 13, 14, 9, 0, 4, 8, 7, 3, 2, 10, 6, 1, 5, 11, 12], [8, 6, 0, 10, 1, 3, 15, 4, 14, 13, 2, 9, 11, 5, 12, 7], [2, 9, 3, 0, 12, 6, 13, 10, 1, 8, 14, 7, 11, 4, 5, 15], [3, 14, 12, 9, 5, 15, 13, 2, 10, 11, 8, 4, 1, 6, 0, 7]]
def S(block, SBoxes):
output = 0
for i in range(0, len(SBoxes)):
output |= SBoxes[i][(block >> 4*i) & 0b1111] << 4*i
return output
PBox = [15, 22, 11, 20, 16, 8, 2, 3, 14, 19, 18, 1, 12, 4, 9, 13, 23, 21, 10, 17, 0, 5, 6, 7]
PInvBox = [20, 11, 6, 7, 13, 21, 22, 23, 5, 14, 18, 2, 12, 15, 8, 0, 4, 19, 10, 9, 3, 17, 1, 16]
def permute(block, pbox):
output = 0
for i in range(24):
bit = (block >> pbox[i]) & 1
output |= (bit << i)
return output
def encrypt_data(block, key):
for j in range(0, 3):
block ^= key
block = S(block, SBoxes)
block = permute(block, PBox)
block ^= key
return block
def decrypt_data(block, key):
block ^= key
for j in range(0, 3):
block = permute(block, PInvBox)
block = S(block, SInvBoxes)
block ^= key
return block
def encrypt(data, key1, key2):
encrypted = encrypt_data(data, key1)
encrypted = encrypt_data(encrypted, key2)
return encrypted
def decrypt(data, key1, key2):
decrypted = decrypt_data(data, key2)
decrypted = decrypt_data(decrypted, key1)
return decrypted
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/SCTF/2021/crypto/ciruit_map/yao_circuit.py | ctfs/SCTF/2021/crypto/ciruit_map/yao_circuit.py | from random import shuffle, randrange
from block_cipher import encrypt, decrypt
def garble_label(key0, key1, key2):
"""
key0, key1 = two input labels
key2 = output label
"""
gl = encrypt(key2, key0, key1)
validation = encrypt(0, key0, key1)
return (gl, validation)
def GarbledGate( gate, keys): # init g data
input = gate["in"]
output = gate["id"]
gate_type = gate["type"]
labels0 = keys[input[0]]
labels1 = keys[input[1]]
labels2 = keys[output]
if gate_type == "AND":
garbled_table = AND_gate(labels0, labels1, labels2)
if gate_type == "XOR":
garbled_table = XOR_gate(labels0, labels1, labels2)
return garbled_table
def AND_gate( labels0, labels1, labels2):
"""
labels0, labels1 = two input labels
labels2 = output label
"""
key0_0, key0_1 = labels0
key1_0, key1_1 = labels1
key2_0, key2_1 = labels2
G = []
G.append(garble_label(key0_0, key1_0, key2_0))
G.append(garble_label(key0_0, key1_1, key2_0))
G.append(garble_label(key0_1, key1_0, key2_0))
G.append(garble_label(key0_1, key1_1, key2_1))
shuffle(G)
return G
def XOR_gate( labels0, labels1, labels2):
key0_0, key0_1 = labels0
key1_0, key1_1 = labels1
key2_0, key2_1 = labels2
G = []
G.append(garble_label(key0_0, key1_0, key2_0))
G.append(garble_label(key0_0, key1_1, key2_1))
G.append(garble_label(key0_1, key1_0, key2_1))
G.append(garble_label(key0_1, key1_1, key2_0))
shuffle(G)
return G
def garble_label(key0, key1, key2):
"""
key0, key1 = two input labels
key2 = output label
"""
gl = encrypt(key2, key0, key1)
validation = encrypt(0, key0, key1)
return (gl, validation)
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/SCTF/2021/crypto/ChristmasZone/util.py | ctfs/SCTF/2021/crypto/ChristmasZone/util.py | from Crypto.Util.number import *
class Complex:
baseRe = 1
baseIm = 0
p= getPrime(512)
q= getPrime(512)
n = p*q
def __init__(self, re=0, im=0):
self.re = re
self.im = im
def Christmas_gift(self):
mistletoe = getPrime(400)
phi = (Complex.p*Complex.q)**2+Complex.p*Complex.q+1+(Complex.p*Complex.q+1)*(Complex.p+Complex.q)+(Complex.p**2+Complex.q**2)
Querce = inverse(mistletoe,phi)
return Querce
def OnePlus(self):
_re = (self.re*Complex.baseRe - self.im*Complex.baseIm)%Complex.n
_im = (self.re*Complex.baseIm + self.im*Complex.baseRe)%Complex.n
Complex.baseRe = _re
Complex.baseIm = _im
def Double(self):
_re = (self.re*self.re - self.im*self.im)%Complex.n
_im = (self.re*self.im + self.im*self.re)%Complex.n
self.re = _re
self.im = _im
def val(self):
return Complex.baseRe,Complex.baseIm,Complex.n
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/SCTF/2021/crypto/cubic/task.py | ctfs/SCTF/2021/crypto/cubic/task.py | #! /usr/bin/python3
from FLAG import flag
from Crypto.Util.number import *
import random
def genPrime():
while True:
a = random.getrandbits(512)
b = random.getrandbits(512)
if b % 3 == 0:
continue
p = a ** 2 + 3 * b ** 2
if p.bit_length() == 1024 and p % 3 == 1 and isPrime(p):
return p
def add(P, Q, mod):
x1, y1 = P
x2, y2 = Q
if x2 is None:
return P
if x1 is None:
return Q
if y1 is None and y2 is None:
x = x1 * x2 % mod
y = (x1 + x2) % mod
return (x, y)
if y1 is None and y2 is not None:
x1, y1, x2, y2 = x2, y2, x1, y1
if y2 is None:
if (y1 + x2) % mod != 0:
x = (x1 * x2 + 2) * inverse(y1 + x2, mod) % mod
y = (x1 + y1 * x2) * inverse(y1 + x2, mod) % mod
return (x, y)
elif (x1 - y1 ** 2) % mod != 0:
x = (x1 * x2 + 2) * inverse(x1 - y1 ** 2, mod) % mod
return (x, None)
else:
return (None, None)
else:
if (x1 + x2 + y1 * y2) % mod != 0:
x = (x1 * x2 + (y1 + y2) * 2) * inverse(x1 + x2 + y1 * y2, mod) % mod
y = (y1 * x2 + x1 * y2 + 2) * inverse(x1 + x2 + y1 * y2, mod) % mod
return (x, y)
elif (y1 * x2 + x1 * y2 + 2) % mod != 0:
x = (x1 * x2 + (y1 + y2) * 2) * inverse(y1 * x2 + x1 * y2 + 2, mod) % mod
return (x, None)
else:
return (None, None)
def myPower(P, a, mod):
target = (None, None)
t = P
while a > 0:
if a % 2:
target = add(target, t, mod)
t = add(t, t, mod)
a >>= 1
return target
def gennewkeys():
N = p*q
d = getPrime(350)
e = inverse(d, PHI)
return e,N
p, q = genPrime(),genPrime()
PHI = (p-1)*(q-1)
N = p*q
d = getPrime(350)
e = inverse(d, PHI)
banner = """
[1] get my pubkey
[2] gen a new key
[3] give me flag
[4] exit
"""
while 1:
print(banner)
op = input(">")
if(op=='1'):
print("here you are")
print(f'e:{e} N:{N}')
if(op=='2'):
print(r"oh you don't like my key:(")
e,N = gennewkeys()
print(f'e:{e} N:{N}')
if(op=="3"):
print('wait for secs...')
ln = len(flag)
pt1, pt2 = flag[: ln // 2], flag[ln // 2 :]
M = (bytes_to_long(pt1), bytes_to_long(pt2))
pad = genPrime()
finitN = N*pad
cipher = myPower(M, e, finitN)
print(f"cipher:{cipher}")
print(f"padding:{pad}")
print(r"c you next time")
exit()
if(op=='4'):
exit()
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/ToH/2025/rev/pickle_funny/pickle_morty.py | ctfs/ToH/2025/rev/pickle_funny/pickle_morty.py | import pickle
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | true |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/CRHC/2025/crypto/easy_Padding_Oracle/server.py | ctfs/CRHC/2025/crypto/easy_Padding_Oracle/server.py | import socket
from Crypto.Cipher import AES
from Crypto.Util.Padding import unpad
import binascii
HOST = "0.0.0.0"
PORT = 9999
key = b'????????????????'
BLOCK_SIZE = 16
def handle_client(conn):
conn.sendall(b"Welcome to Padding Oracle service!\nSend ciphertext hex and press enter.\n")
while True:
try:
data = conn.recv(1024).strip()
if not data:
break
ciphertext_hex = data.decode()
try:
ciphertext = binascii.unhexlify(ciphertext_hex)
iv = ciphertext[:BLOCK_SIZE]
ct = ciphertext[BLOCK_SIZE:]
cipher = AES.new(key, AES.MODE_CBC, iv)
plaintext = cipher.decrypt(ct)
unpad(plaintext, BLOCK_SIZE)
conn.sendall(b"Valid padding\n")
except Exception:
conn.sendall(b"Invalid padding\n")
except Exception:
break
conn.close()
def main():
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
s.bind((HOST, PORT))
s.listen()
print(f"Padding Oracle server listening on {HOST}:{PORT}")
while True:
conn, addr = s.accept()
print(f"Connection from {addr}")
handle_client(conn)
if __name__ == "__main__":
main() | python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/CRHC/2025/crypto/brrrrr_is_math/enc_public.py | ctfs/CRHC/2025/crypto/brrrrr_is_math/enc_public.py | import math
import json
def enc(msg, a=0????, b=0????, M=0????):
p = [ord(c) for c in msg]
max_p = max(p) if p else 0
prod = a * b
s = 0???????
if prod < 2 * max_p:
s = math.ceil(math.sqrt((2 * max_p) / prod))
a_eff = a * s
b_eff = b * s
l = [int(round((2 * x / (a_eff * b_eff)) * M)) for x in p]
return {"l": l}
if __name__ == "__main__":
msg = "flag_is_here"
c = enc(msg)
print(json.dumps(c, ensure_ascii=False, indent=2)) | python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/CRHC/2025/crypto/RSASRSASR/enc.py | ctfs/CRHC/2025/crypto/RSASRSASR/enc.py | import random
from math import prod
from Crypto.Util.number import getPrime, bytes_to_long
def generate_prime_from_byte(byte_val):
assert 0 <= byte_val <= 255
r = random.Random()
r.seed(byte_val)
return getPrime(512, randfunc=r.randbytes)
def main():
FLAG = open("flag.txt", "rb").read().strip()
primes = [generate_prime_from_byte(b) for b in FLAG]
N = prod(primes)
e = 0x10001
m = bytes_to_long(FLAG)
c = pow(m, e, N)
print(f"N = {hex(N)}")
print(f"c = {hex(c)}")
if __name__ == "__main__":
main()
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/CRHC/2025/crypto/Lattice/enc.py | ctfs/CRHC/2025/crypto/Lattice/enc.py | from Crypto.Util.number import getPrime
from Crypto.Cipher import AES
from ecdsa.curves import SECP256k1
from ecdsa.ellipticcurve import Point
from hashlib import sha256
from secrets import randbelow
C = SECP256k1
G = C.generator
n = C.order
def sign(d, Q, h, k):
R = k * G
r = R.x()
e = int.from_bytes(sha256(r.to_bytes(32, 'big') + Q.x().to_bytes(32, 'big') + h).digest(), 'big') % n
s = (k + e * d) % n
return r, s
def verify(Q, h, r, s):
e = int.from_bytes(sha256(r.to_bytes(32, 'big') + Q.x().to_bytes(32, 'big') + h).digest(), 'big') % n
sG = (s * G).to_affine()
eQ = (e * Q).to_affine()
Rp = Point(C.curve, sG.x(), sG.y()) + Point(C.curve, eQ.x(), (-eQ.y()) % C.curve.p())
return Rp.x() == r
def lcg(a, c, m, x):
while True:
x = (a * x + c) % m
yield x
if __name__ == "__main__":
d = randbelow(n)
Q = d * G
p = getPrime(256)
a, c, seed = [randbelow(p) for _ in range(3)]
lcg_gen = lcg(a, c, p, seed)
msgs = [
b"The true sign of intelligence is not knowledge but imagination.",
b"In the middle of difficulty lies opportunity.",
b"I have no special talent. I am only passionately curious.",
b"The only source of knowledge is experience.",
b"Logic will get you from A to B. Imagination will take you everywhere.",
b"Life is like riding a bicycle. To keep your balance, you must keep moving.",
b"Strive not to be a success, but rather to be of value.",
b"Weakness of attitude becomes weakness of character.",
b"Peace cannot be kept by force; it can only be achieved by understanding.",
b"It's not that I'm so smart, it's just that I stay with problems longer."
]
sigs = []
for m in msgs:
h = sha256(m).digest()
st = next(lcg_gen)
k = st >> 128
r, s = sign(d, Q, h, k)
assert verify(Q, h, r, s)
sigs.append((r, s))
print(f"Q = ({Q.x()}, {Q.y()})")
print(f"sigs = {sigs}")
flag = b"CRHC{fake_flag}"
key = sha256(d.to_bytes(32, 'big')).digest()[:16]
aes = AES.new(key, AES.MODE_GCM)
enc_flag, tag = aes.encrypt_and_digest(flag)
nonce = aes.nonce
print(f"\nenc_flag = {enc_flag.hex()}")
print(f"nonce = {nonce.hex()}")
print(f"tag = {tag.hex()}") | python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/BraekerCTF/2024/misc/Microservices/microservices.py | ctfs/BraekerCTF/2024/misc/Microservices/microservices.py | from scapy.all import *
load_layer("http")
from Crypto.Util.number import bytes_to_long, long_to_bytes
import random
def dropTheFlag(flag):
# Flag falls into bits
pieces = bytes_to_long(flag.encode())
pieces = bin(pieces)
pieces = pieces[2:]
pieces = [int(x) for x in pieces]
# Bits get scattered about
d = {}
for i,x in enumerate(pieces):
d[i]=x
l = list(d.items())
random.shuffle(l)
pieces = dict(l)
return pieces
# It was right here
flag = "brck{not_the_flag}"
# Oh dang I dropped the flag
pieces = dropTheFlag(flag)
# Let's pick it back up
pickMapping = {}
for i,v in enumerate(pieces):
pickMapping[i] = (v, pieces[v])
# Neat TCP things
FIN = 0x01
SYN = 0x02
PSH = 0x08
ACK = 0x10
# Server IP for filter
serverIP = "server_ip"
# Totally valid HTTP response
body = b"HTTP/1.1 404 OK\r\nConnection: close\r\nContent-Type: text/html\r\n\r\nKeep guessing!"
def processWebRequest(payload, dport):
# Secret and piece of flag
secret, b = pickMapping[dport-1000]
# Extract guess from request
filterString = b'GET /guess?guess='
guess = 0
try:
guess = payload[len(filterString)+2:payload.find(' ', len(filterString)+2)]
guess = int(guess)
except:
guess = 0
# Return based on guess
body_ret = body + b' guess = ' + str(guess).encode() + b'\r\n'
if guess > secret:
return 1, body_ret
elif guess == secret:
return 2+b, body_ret
else:
return 0, body_ret
def packet_callback(pkt):
# User packet
ip = pkt[IP]
tcp = pkt[TCP]
payload = str(bytes(tcp.payload))
# Init response packet
ip_response = IP(src=ip.dst, dst=ip.src)
# No response by default
pkt_resp = False
# ACK some SYNS
if tcp.flags == SYN:
syn_ack_tcp = TCP(sport=tcp.dport, dport=tcp.sport, flags="SA", ack=tcp.seq + 1, seq=1337)
pkt_resp = ip_response / syn_ack_tcp
# Respond to the PSH
elif tcp.flags & PSH == PSH:
if len(payload) > 10:
ret, lbody = processWebRequest(payload, tcp.dport)
# Reply OOB
pkt_resp = (ip_response /
TCP(sport=tcp.dport, dport=tcp.sport, flags="PAF", seq=1338, ack=tcp.seq+len(tcp.payload)) /
Raw(lbody))
send(pkt_resp)
pkt_resp = (ip_response /
TCP(sport=tcp.dport, dport=tcp.sport, flags="PAF", seq=7331+ret, ack=tcp.seq+len(tcp.payload)) /
Raw(lbody))
# ACK them FINs
elif tcp.flags & FIN == FIN:
pkt_resp = ip_response / TCP(sport=tcp.dport, dport=tcp.sport, flags="RA", seq=tcp.ack, ack=tcp.seq+len(tcp.payload))
# Respond if applicable
if pkt_resp:
send(pkt_resp)
# Filter packets for required ports
def packet_filter(pkt):
return (TCP in pkt and
pkt[IP].dst == serverIP and
pkt[TCP].dport >= 1000 and pkt[TCP].dport <= 1000+len(pickMapping)-1)
# Spin up hundreds of webservices just like in the cloud
sniff(filter="tcp", prn=packet_callback, lfilter=packet_filter)
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/BraekerCTF/2024/crypto/Flag_based_key_expansion/key_expansion.py | ctfs/BraekerCTF/2024/crypto/Flag_based_key_expansion/key_expansion.py | #!/usr/bin/python3
##
## Flag-based key expansion
##
##
import hashlib
from argon2 import PasswordHasher
# Init MD5
m = hashlib.md5()
# Get flag words
flag_data = open('flag.txt','r').read()[len('brck{'):-1]
flag_words = flag_data.split('_')
# Start with strong 256 char key
init_key = "aabacadaeafa0a1a2a3a4a5a6a7a8a9bbcbdbebfb0b1b2b3b4b5b6b7b8b9ccdcecfc0c1c2c3c4c5c6c7c8c9ddedfd0d1d2d3d4d5d6d7d8d9eefe0e1e2e3e4e5e6e7e8e9ff0f1f2f3f4f5f6f7f8f90010203040506070809112131415161718192232425262728293343536373839445464748495565758596676869778798899"
print("Init key: \n\n%s\n" % init_key)
# Generate init key
m.update(init_key.encode())
# Expand key with flag words
print("Generating digests..\n")
for flag_word in flag_words:
m.update(flag_word.encode())
print(m.hexdigest())
# Expand the key using Argon2
ph = PasswordHasher(time_cost = 16, parallelism = 32)
h = ph.hash(m.digest())
print("\nKey after expansion: \n%s\n" % h)
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/BraekerCTF/2024/crypto/Block_construction/block_construction.py | ctfs/BraekerCTF/2024/crypto/Block_construction/block_construction.py | import binascii
from Crypto.Cipher import AES
from os import urandom
from string import printable
import random
from time import time
flag = "brck{not_a_flag}"
key = urandom(32)
def encrypt(raw):
cipher = AES.new(key, AES.MODE_ECB)
return binascii.hexlify(cipher.encrypt(raw.encode()))
# Generate random bytes
random.seed(int(time()))
rand_printable = [x for x in printable]
random.shuffle(rand_printable)
# Generate ciphertext
with open('ciphertext','w') as fout:
for x in flag:
for y in rand_printable:
# add random padding to block and encrypt
fout.write(encrypt(x + (y*31)).decode()) | python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/BraekerCTF/2024/web/Empty_execution/empty_execution.py | ctfs/BraekerCTF/2024/web/Empty_execution/empty_execution.py | from flask import Flask, jsonify, request
import os
app = Flask(__name__)
# Run commands from leaderbot
@app.route('/run_command', methods=['POST'])
def run_command():
# Get command
data = request.get_json()
if 'command' in data:
command = str(data['command'])
# Length check
if len(command) < 5:
return jsonify({'message': 'Command too short'}), 501
# Perform security checks
if '..' in command or '/' in command:
return jsonify({'message': 'Hacking attempt detected'}), 501
# Find path to executable
executable_to_run = command.split()[0]
# Check if we can execute the binary
if os.access(executable_to_run, os.X_OK):
# Execute binary if it exists and is executable
out = os.popen(command).read()
return jsonify({'message': 'Command output: ' + str(out)}), 200
return jsonify({'message': 'Not implemented'}), 501
if __name__ == '__main__':
# Make sure we can only execute binaries in the executables directory
os.chdir('./executables/')
# Run server
app.run(host='0.0.0.0', port=80)
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/BraekerCTF/2024/web/Stuffy/app/app.py | ctfs/BraekerCTF/2024/web/Stuffy/app/app.py | ## Stuffy, a social media platform for sharing thoughts
###
import sqlite3
import urllib3
import string
import uuid
from flask import Flask, render_template, request, make_response
from random import choice
# init app
app = Flask(__name__)
# read flag
flag = open('flag.txt','r').read()
# load username prefixes
usernames = open('usernames.txt','r').readlines()
# init db
conn = sqlite3.connect('file::memory:?cache=shared', check_same_thread=False)
# create API key
internal_api_key = str(uuid.uuid4())
# check if username exists in database
def does_profile_exist(username):
sql = '''SELECT id from profiles where username = ?'''
cur = conn.cursor()
cur.execute(sql, [username])
ret = cur.fetchone()
if ret != None:
return True
else:
return False
# create new profile
def create_profile():
user_ip = request.remote_addr
new_username = choice(usernames).strip() + \
''.join(choice(string.ascii_letters) for i in range(4))
cur = conn.cursor()
sql = '''DELETE FROM profiles WHERE ip = ?'''
cur.execute(sql, (user_ip, ))
sql = '''INSERT INTO profiles (username, stuff, ip) VALUES (?,?,?)'''
cur.execute(sql, (new_username, '', user_ip))
conn.commit()
return new_username
# get stuff for username
def get_stuff(username):
sql = '''SELECT stuff from profiles where username = "''' + username + '''"'''
cur = conn.cursor()
cur.execute(sql)
ret = cur.fetchone()
if ret != None:
return ret[0]
else:
return ''
# select stuffs from users
def get_latest_stuff():
sql = "SELECT username,stuff from profiles WHERE stuff not LIKE ? ORDER BY username DESC LIMIT 40"
cur = conn.cursor()
cur.execute(sql, ["%%%s%%" % flag])
stuff = cur.fetchmany(size=40)
return stuff
# prevent vulnerabilities
def security_filter(value):
# prevent xss
value = value.replace('<','')
value = value.replace('>','')
# prevent sqli
value = value.replace('\'','')
# prevent too much stuff
if len(value) > 256:
value = value[:256]
return value
# give flag to a user (for internal use)
@app.route("/give_flag", methods=["POST"])
def give_flag():
username = request.form.get('username')
if request.headers['X-Real-IP'] == "127.0.0.1":
sql = '''UPDATE profiles SET stuff = ? WHERE username = ?'''
cur = conn.cursor()
cur.execute(sql, (flag, username))
conn.commit()
return 'congrats!'
else:
sql = '''UPDATE profiles SET stuff = ? WHERE username = ?'''
cur = conn.cursor()
cur.execute(sql, ('No stuff for you', username))
conn.commit()
return 'no congrats!'
# update stuff for a user (for internal use)
@app.route("/update_profile_internal", methods=["POST"])
def update_profile_internal():
api_key = request.form.get('api_key')
username = request.form.get('username')
stuff = request.form.get('stuff')
add_emoji = request.headers.get('emoji')
if add_emoji:
if add_emoji == 'cow':
stuff += ' 🐄'
if add_emoji == 'cat':
stuff += ' 🐱'
if add_emoji == 'fish':
stuff += ' 🐠'
add_image = request.headers.get('image')
if add_image:
if add_image == 'cow':
stuff += '<img id="mood" src="/static/images/cow.png">'
if add_image == 'cat':
stuff += '<img id="mood" src="/static/images/cat.png">'
if add_image == 'fish':
stuff += '<img id="mood" src="/static/images/fish.png">'
if api_key == internal_api_key:
sql = '''UPDATE profiles SET stuff = ? WHERE username = ?'''
cur = conn.cursor()
cur.execute(sql, (stuff, username))
conn.commit()
return 'Updated profile'
else:
return render_template('forbidden.html', reason='wrong key')
# show the latest stuff
@app.route("/view_stuff", methods=["GET"])
def view_stuffs():
username = request.cookies.get('username')
if username and does_profile_exist(username):
stuff = get_latest_stuff()
return render_template('view_stuff.html', stuff=stuff)
else:
return render_template('forbidden.html', reason='you don\'t have an active user profile')
# show user stuff or create a new user
@app.route("/")
def index() -> str:
username = request.cookies.get('username')
if username and does_profile_exist(username):
stuff = get_stuff(username)
return make_response(render_template('wb.html', username=username, stuff=stuff))
else:
username = create_profile()
msg = "New user created: %s" % username
resp = make_response(render_template('wb.html', msg=msg, username=username, stuff=''))
resp.set_cookie('username', username)
return resp
# set a user's stuff
@app.route('/set_stuff', methods=["POST"])
def set_stuff():
username = request.cookies.get('username')
if not username:
return render_template('forbidden.html', reason='no username provided')
if not does_profile_exist(username):
return render_template('forbidden.html', reason='username does not exist')
stuff = request.form.get('stuff')
if len(stuff) > 200:
return render_template('forbidden.html', reason='too much stuff')
special_type = request.form.get('special_type')
special_val = request.form.get('special_val')
if username and stuff and special_type and special_val:
# do security
stuff = security_filter(stuff)
special_type = security_filter(special_type)
special_val = security_filter(special_val)
username = security_filter(username)
# Update stuff internally
post_body = 'api_key=%s&username=%s&stuff=%s' % (internal_api_key,username,stuff)
http = urllib3.PoolManager()
url = 'http://127.0.0.1:3000/update_profile_internal'
headers = {
"Content-Type": "application/x-www-form-urlencoded",
special_type: special_val
}
response = http.request("POST", url, body=post_body, headers=headers)
return render_template('stuff_saved.html')
else:
return render_template('forbidden.html', reason='no stuff provided')
def main():
cur = conn.cursor()
cur.execute("""
create table profiles(
id integer primary key autoincrement not null,
username text,
stuff text,
ip text
);
""")
conn.commit()
app.run('0.0.0.0', 2000, threaded=True)
if __name__ == "__main__":
main()
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/CCCamp/2023/misc/d3c0d3r/main.py | ctfs/CCCamp/2023/misc/d3c0d3r/main.py | #!/usr/bin/env python3
import os
import subprocess
import base64
def main():
print("This challenge is derived from a real world example, no joke")
print("Anyway: Encode and exploit this")
try:
inp = input("Give input plox: ")
inp = inp.upper()
decoded = base64.b64decode(inp).lower()
open("/tmp/inp", "wb").write(decoded)
print(subprocess.check_output("/bin/bash < /tmp/inp", shell=True))
except Exception as e:
print("Something went wrong. Bye!")
if __name__ == "__main__":
main()
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/CCCamp/2023/misc/Navity/chal.py | ctfs/CCCamp/2023/misc/Navity/chal.py | import threading
from avatar2 import *
from avatar2.peripherals.avatar_peripheral import AvatarPeripheral
import signal
import sys
import time
firmware = abspath("/firmware.bin")
class IOPeripheral(AvatarPeripheral):
def hw_read(self, offset, size):
if offset == 4:
if self.char != None:
return 1
self.char = sys.stdin.buffer.read(1)
return 0
ret = int.from_bytes(self.char, byteorder="little")
self.char = None
return ret
def hw_write(self, offset, size, value: int):
sys.stdout.buffer.write(value.to_bytes(size, byteorder="little"))
sys.stdout.flush()
return True
def __init__(self, name, address, size, **kwargs):
AvatarPeripheral.__init__(self, name, address, size)
self.char = None
self.read_handler[0:size] = self.hw_read
self.write_handler[0:size] = self.hw_write
def main():
avatar = Avatar(arch=ARM_CORTEX_M3, output_directory="/tmp/avatar")
avatar.add_memory_range(
0x00000000, 128 * 1024, file=firmware, name="flash", permissions="rwx"
)
avatar.add_memory_range(0x20000, 64 * 1024, name="ram", permissions="rw-")
hw = avatar.add_memory_range(
0x40004C00, 0x100, name="io", emulate=IOPeripheral, permissions="rw-"
)
qemu = avatar.add_target(
QemuTarget, cpu_model="cortex-m3", entry_address=1 # force thumb
)
avatar.init_targets()
qemu.write_register("sp", qemu.read_memory(0x0, 4, 1))
qemu.write_register("pc", qemu.read_memory(0x4, 4, 1))
def signal_handler(signal, frame):
avatar.stop()
avatar.shutdown()
sys.exit(0)
signal.signal(signal.SIGINT, signal_handler)
avatar.load_plugin("gdbserver")
avatar.spawn_gdb_server(qemu, 1234, True)
qemu.cont()
qemu.wait(TargetStates.EXITED)
if __name__ == "__main__":
main()
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/CCCamp/2023/rev/Ikea/main.py | ctfs/CCCamp/2023/rev/Ikea/main.py | from sys import setrecursionlimit
from inst import *
setrecursionlimit(100000)
@Ribba
@Billy(16)
@Expedit
@Klippan
@Billy(0)
@Billy(1)
@Billy(15)
@Malm
@Billy(185)
@Billy(198)
@Billy(214)
@Billy(67)
@Billy(52)
@Billy(212)
@Billy(83)
@Billy(22)
@Billy(93)
@Billy(13)
@Billy(225)
@Billy(85)
@Billy(197)
@Billy(225)
@Billy(53)
@Billy(34)
@Billy(121)
@Billy(101)
@Billy(107)
@Billy(114)
@Billy(101)
@Billy(116)
@Billy(116)
@Billy(101)
@Billy(98)
@Billy(97)
@Billy(102)
@Billy(111)
@Billy(107)
@Billy(110)
@Billy(105)
@Billy(104)
@Billy(116)
@Billy(116)
@Billy(110)
@Billy(97)
@Billy(99)
@Billy(121)
@Billy(108)
@Billy(108)
@Billy(97)
@Billy(101)
@Billy(114)
@Billy(105)
@Billy(0)
@Docksta
@Billy(1)
@Billy(2)
@Poäng
@Billy(1)
@Rens
@Billy(1)
@Billy(1)
@Malm
@Billy(256)
@Expedit
@Billy(1)
@Billy(1)
@Malm
@Billy(1)
@Billy(3)
@Poäng
@Billy(3)
@Billy(4)
@Poäng
@Billy(1)
@Billy(1)
@Malm
@Billy(1)
@Billy(3)
@Poäng
@Ektorp
@Billy(2)
@Lack
@Billy(0)
@Billy(0)
@Docksta
@Billy(1)
@Billy(287)
@Poäng
@Billy(1)
@Billy(2)
@Malm
@Billy(1)
@Billy(4)
@Poäng
@Billy(256)
@Expedit
@Billy(3)
@Billy(260)
@Poäng
@Billy(256)
@Poäng
@Billy(1)
@Billy(2)
@Malm
@Billy(260)
@Billy(261)
@Poäng
@Rens
@Billy(2)
@Billy(260)
@Poäng
@Billy(256)
@Billy(257)
@Poäng
@Billy(256)
@Poäng
@Billy(259)
@Billy(287)
@Poäng
@Billy(284)
@Billy(285)
@Poäng
@Billy(1)
@Billy(1)
@Malm
@Billy(28)
@Stockholm
@Billy(1)
@Billy(1)
@Malm
@Billy(28)
@Expedit
@Billy(1)
@Billy(31)
@Poäng
@Billy(1)
@Billy(2)
@Poäng
@Billy(1)
@Billy(287)
@Poäng
@Billy(28)
@Poäng
@Billy(1)
@Billy(1)
@Malm
@Billy(287)
@Billy(288)
@Poäng
@Rens
@Billy(256)
@Stockholm
@Billy(1)
@Billy(287)
@Poäng
@Billy(28)
@Billy(29)
@Poäng
@Billy(28)
@Poäng
@Billy(28)
@Billy(287)
@Poäng
@Billy(257)
@Billy(258)
@Poäng
@Billy(1)
@Billy(2)
@Malm
@Billy(256)
@Expedit
@Billy(2)
@Billy(260)
@Poäng
@Billy(256)
@Poäng
@Billy(259)
@Billy(260)
@Poäng
@Billy(1)
@Billy(2)
@Poäng
@Billy(1)
@Billy(260)
@Poäng
@Billy(257)
@Billy(258)
@Poäng
@Billy(256)
@Poäng
@Billy(256)
@Billy(257)
@Poäng
@Billy(1)
@Billy(2)
@Malm
@Billy(256)
@Expedit
@Billy(2)
@Billy(259)
@Poäng
@Billy(256)
@Poäng
@Billy(1)
@Lack
@Billy(258)
@Billy(259)
@Poäng
@Billy(256)
@Billy(257)
@Poäng
@Billy(256)
@Poäng
@Billy(256)
@Billy(258)
@Poäng
@Billy(1)
@Rens
@Billy(1)
@Billy(1)
@Malm
@Billy(256)
@Expedit
@Billy(287)
@Billy(288)
@Poäng
@Billy(1)
@Billy(1)
@Malm
@Billy(1)
@Billy(3)
@Poäng
@Ektorp
@Billy(259)
@Billy(287)
@Poäng
@Billy(31)
@Lack
@Billy(0)
@Billy(0)
@Billy(0)
@Docksta
@Billy(1)
@Billy(2)
@Poäng
@Billy(1)
@Rens
@Billy(2)
@Billy(308)
@Poäng
@Billy(1)
@Rens
@Billy(256)
@Stockholm
@Billy(1)
@Billy(2)
@Malm
@Billy(2)
@Billy(4)
@Poäng
@Billy(2)
@Billy(260)
@Poäng
@Billy(256)
@Expedit
@Billy(1)
@Billy(258)
@Poäng
@Billy(256)
@Poäng
@Billy(1)
@Billy(3)
@Malm
@Billy(261)
@Billy(262)
@Poäng
@Rens
@Billy(256)
@Stockholm
@Billy(1)
@Billy(2)
@Malm
@Billy(4)
@Billy(263)
@Poäng
@Billy(295)
@Billy(296)
@Poäng
@Billy(1)
@Billy(1)
@Malm
@Billy(1)
@Billy(312)
@Poäng
@Färgrik
@Billy(279)
@Billy(295)
@Poäng
@Billy(274)
@Billy(275)
@Poäng
@Billy(1)
@Billy(1)
@Malm
@Billy(1)
@Billy(276)
@Poäng
@Billy(241)
@Färgrik
@Billy(257)
@Stockholm
@Billy(16)
@Stockholm
@Billy(1)
@Billy(1)
@Malm
@Billy(16)
@Expedit
@Billy(1)
@Billy(18)
@Poäng
@Billy(16)
@Poäng
@Billy(17)
@Billy(18)
@Poäng
@Rens
@Billy(257)
@Stockholm
@Billy(16)
@Billy(17)
@Poäng
@Billy(16)
@Poäng
@Billy(16)
@Billy(294)
@Poäng
@Billy(256)
@Billy(257)
@Poäng
@Billy(256)
@Poäng
@Billy(258)
@Billy(260)
@Poäng
@Billy(256)
@Expedit
@Billy(1)
@Billy(258)
@Poäng
@Billy(256)
@Poäng
@Billy(259)
@Billy(260)
@Poäng
@Billy(1)
@Billy(2)
@Poäng
@Billy(2)
@Billy(1)
@Malm
@Rens
@Billy(256)
@Stockholm
@Billy(2)
@Billy(261)
@Poäng
@Billy(256)
@Billy(257)
@Poäng
@Billy(256)
@Poäng
@Billy(256)
@Billy(257)
@Poäng
@Billy(1)
@Billy(2)
@Malm
@Billy(256)
@Expedit
@Billy(2)
@Billy(259)
@Poäng
@Billy(256)
@Poäng
@Billy(260)
@Billy(261)
@Poäng
@Billy(1)
@Billy(2)
@Poäng
@Billy(1)
@Lack
@Billy(256)
@Billy(257)
@Poäng
@Billy(256)
@Poäng
@Billy(258)
@Billy(259)
@Poäng
@Billy(1)
@Billy(1)
@Malm
@Billy(256)
@Expedit
@Billy(1)
@Billy(258)
@Poäng
@Billy(256)
@Poäng
@Billy(1)
@Billy(1)
@Malm
@Billy(260)
@Billy(261)
@Poäng
@Rens
@Billy(256)
@Stockholm
@Billy(1)
@Billy(275)
@Poäng
@Billy(256)
@Billy(257)
@Poäng
@Billy(256)
@Poäng
@Billy(256)
@Billy(258)
@Poäng
@Billy(306)
@Billy(308)
@Poäng
@Billy(1)
@Billy(1)
@Malm
@Billy(256)
@Expedit
@Billy(2)
@Billy(3)
@Poäng
@Billy(1)
@Billy(1)
@Malm
@Billy(1)
@Billy(3)
@Poäng
@Ektorp
@Billy(292)
@Billy(308)
@Poäng
@Billy(276)
@Lack
@Billy(16)
@Docksta
@Billy(1)
@Billy(2)
@Poäng
@Billy(1)
@Billy(1)
@Malm
@Billy(2)
@Rens
@Billy(1)
@Billy(1)
@Malm
@Billy(1)
@Rens
@Poäng
@Billy(3)
@Billy(4)
@Poäng
@Expedit
@Klippan
@Billy(1)
@Billy(1)
@Billy(2)
@Poäng
@Expedit
@Billy(2)
@Billy(1)
@Malm
@Billy(1)
@Billy(4)
@Poäng
@Ektorp
def checker(flag):
return True
print(checker(input().strip().encode()))
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/CCCamp/2023/game/Maze/src/server/server/server_runner.py | ctfs/CCCamp/2023/game/Maze/src/server/server/server_runner.py | from __future__ import annotations
import struct
import time
import traceback
from asyncio import (
Queue,
StreamReader,
StreamWriter,
as_completed,
create_task,
sleep,
start_server,
)
from copy import deepcopy
from datetime import datetime, timedelta
from threading import Event
from typing import Awaitable, Callable, Dict, Tuple, TypeVar, cast
from uuid import uuid4
from betterproto import which_one_of
import server
from server.game.auth import auth
from server.game.entity.area import AreaObject
from server.game.entity.enemy import Enemy
from server.game.entity.npc import NPC
from server.game.map.properties import CustomInteraction, InteractionOn
from shared.collison import point_in_poly
from shared.constants import PLAYER_DEATH_TIMEOUT, SERVER_TICK_RATE, START_X, START_Y
from shared.gen.messages.v1 import (
AcknowledgeDamage,
AttackEnemy,
ClientMessage,
Coords,
EnemyInfo,
Error,
ErrorType,
GiveDamage,
Interact,
InteractStatus,
InteractType,
LoggedIn,
Login,
Logout,
MapChunkRequest,
MapChunkResponse,
Object,
ObjectAsset,
ObjectAssetRequest,
Objects,
ObjectType,
Ping,
ServerMessage,
SessionType,
User,
Users,
)
from shared.utils import AsyncEventHandler
ServerMessageOneOfType = (
Ping
| Login
| Coords
| MapChunkRequest
| ObjectAssetRequest
| Interact
| AcknowledgeDamage
| AttackEnemy
| Logout
)
ServerMessageOneOfTypeVar = TypeVar(
"ServerMessageOneOfTypeVar",
Ping,
Login,
Coords,
MapChunkRequest,
ObjectAssetRequest,
Interact,
AcknowledgeDamage,
AttackEnemy,
Logout,
)
class Connection:
reader: StreamReader
writer: StreamWriter
# (ServerMessage, Handler)
network_queue: Queue[
Tuple[ServerMessage, Callable[[ServerMessageOneOfType], None] | None]
]
handlers: Dict[str, Callable[[ServerMessageOneOfType], None]]
peer: str
def __init__(self, reader: StreamReader, writer: StreamWriter) -> None:
self.reader = reader
self.writer = writer
self.network_queue = Queue()
self.handlers = {}
self.peer = reader._transport.get_extra_info("peername") # type: ignore
self.ping_handler = AsyncEventHandler([self._ping])
self.login_handler = AsyncEventHandler([self._login])
self.move_handler = AsyncEventHandler([self._move])
self.map_chunk_handler = AsyncEventHandler([self._chunk_request])
self.object_asset_handler = AsyncEventHandler([self._object_asset_request])
self.interact_handler = AsyncEventHandler([self._interact])
self.acknowledge_damage_handler = AsyncEventHandler([self._acknowledge_damage])
self.attack_enemy_handler = AsyncEventHandler([self._attack_enemy])
self.logout_handler = AsyncEventHandler([self._logout])
async def read_message_loop(self) -> None:
try:
while not self.reader.at_eof():
size_buf = await self.reader.readexactly(4)
size = struct.unpack("!i", size_buf)[0]
data_buf = await self.reader.readexactly(size)
message = ClientMessage().parse(data_buf)
message_id = message.uuid
_, inner_message = which_one_of(message=message, group_name="message")
match inner_message:
case Ping():
await self.ping_handler(message_id, inner_message)
case Login():
await self.login_handler(message_id, inner_message)
case Coords():
await self.move_handler(message_id, inner_message)
case MapChunkRequest():
await self.map_chunk_handler(message_id, inner_message)
case ObjectAssetRequest():
await self.object_asset_handler(message_id, inner_message)
case Interact():
await self.interact_handler(message_id, inner_message)
case AcknowledgeDamage():
await self.acknowledge_damage_handler(message_id, inner_message)
case AttackEnemy():
await self.attack_enemy_handler(message_id, inner_message)
case Logout():
await self.logout_handler(message_id, inner_message)
case default:
raise Exception(f"Unkown message_type: {default}")
except Exception:
traceback.print_exc()
if server.game_state.is_authenticated(self.peer):
await self.logout()
async def send_message_loop(self) -> None:
try:
while True:
message, handler = await self.network_queue.get()
if message.uuid == "":
message_id = str(uuid4())
message.uuid = message_id
if handler is not None:
self.handlers[message.uuid] = handler
self._send_message(message)
except Exception:
traceback.print_exc()
if server.game_state.is_authenticated(self.peer):
await self.logout()
def _send_message(self, client_message: ServerMessage) -> None:
message_bytes = client_message.SerializeToString()
message = struct.pack("!i", len(message_bytes)) + message_bytes
self.writer.write(message)
@staticmethod
def authenticated(
func: Callable[[Connection, str, ServerMessageOneOfTypeVar], Awaitable[None]]
) -> Callable[[Connection, str, ServerMessageOneOfTypeVar], Awaitable[None]]:
async def inner(
self: Connection, uuid: str, message: ServerMessageOneOfTypeVar
) -> None:
if server.game_state.is_authenticated(self.peer):
await func(self, uuid, message)
else:
response = ServerMessage(
error=Error(
type=ErrorType.ERROR_TYPE_UNAUTHORIZED,
message="Not logged in yet.",
),
uuid=uuid,
)
await self.network_queue.put((response, None))
return inner
@authenticated
async def _logout(self, uuid: str, message: Logout) -> None:
await self.logout()
async def logout(self) -> None:
session = server.game_state.peer_sessions[self.peer]
user = server.game_state.get_user(session.user_id)
if user is None:
return
if session.type != SessionType.SESSION_TYPE_FREE_CAM:
response = ServerMessage(logout=Logout(user=user))
await server.global_server.broadcast(response)
await server.game_state.logout(self.peer)
@authenticated
async def _ping(self, uuid: str, message: Ping) -> None:
await server.game_state.ping(self.peer, message)
response = ServerMessage(ping=Ping(time=datetime.now()), uuid=uuid)
await self.network_queue.put((response, None))
async def _login(self, uuid: str, message: Login) -> None:
res = auth(message.username, message.password)
error_msg = ErrorType.ERROR_TYPE_UNSPECIFIED
if res == None: # Invalid auth
error_msg = ErrorType.ERROR_TYPE_UNAUTHORIZED
user_uuid = server.game_state.get_user_uuid(message.username)
user = server.game_state.get_user(user_uuid)
if user is None:
user = await server.game_state.get_remote_fulluser(message.username)
if user:
user.coords.timestamp = datetime.now()
if user is None:
user_id = str(uuid4())
start_coords = Coords(x=START_X, y=START_Y)
start_coords.timestamp = datetime.now()
user = User(
username=message.username,
uuid=user_id,
coords=start_coords,
money=1000,
health=100,
last_death=0,
)
elif (
user.last_death != 0
and (time.time() - user.last_death)
< PLAYER_DEATH_TIMEOUT # Check if user is still in timeout
):
res = None
error_msg = ErrorType.ERROR_TYPE_TIMEOUT
else:
if server.game_state.is_logged_in(message.username):
res = None
error_msg = ErrorType.ERROR_TYPE_ALREADY_LOGGED_IN
if await server.game_state.is_logged_in_remote(message.username):
res = None
error_msg = ErrorType.ERROR_TYPE_ALREADY_LOGGED_IN
response = ServerMessage(
logged_in=LoggedIn(
success=res is not None,
type=res if res is not None else SessionType.SESSION_TYPE_UNSPECIFIED,
error=error_msg,
),
uuid=uuid,
)
if res:
response.logged_in.self = user
response.logged_in.assets = server.game_state.map.player_asset
response.logged_in.interact_distance = 14
await self.network_queue.put((response, None))
if res:
await server.game_state.login(self.peer, user.uuid, user, res)
if res != SessionType.SESSION_TYPE_FREE_CAM:
response = ServerMessage(users=Users(users=[user]))
await server.global_server.broadcast(response, exclude=[self.peer])
users = server.game_state.get_online_users(self.peer)
response = ServerMessage(
users=Users(users=users),
)
await self.network_queue.put((response, None))
await self._send_new_objects_view_distance(user)
@authenticated
async def _move(self, uuid: str, message: Coords) -> None:
message.timestamp = datetime.now()
valid = await server.game_state.move(self.peer, message)
session = server.game_state.peer_sessions[self.peer]
user_uuid = session.user_id
user = server.game_state.get_user(user_uuid)
if user is None:
return
await self._send_new_objects_view_distance(user)
if session.type != SessionType.SESSION_TYPE_FREE_CAM:
if not valid:
response = ServerMessage(users=Users(users=[user]))
await server.global_server.broadcast(response, include=[self.peer])
objects = server.game_state.get_objects_view_distance(
user_uuid, user.coords.x, user.coords.y
)
for o in objects:
match o:
case AreaObject():
if o.interaction_on != InteractionOn.COLLIDE:
continue
if point_in_poly(user.coords.x, user.coords.y, o.area):
if not o.actice:
interact = o.in_range(user_uuid)
if interact:
resp = ServerMessage()
resp.interact = interact
await server.global_server.broadcast(
resp, include=[self.peer]
)
elif o.actice:
interact = o.out_of_range(user_uuid)
if interact:
resp = ServerMessage()
resp.interact = interact
await server.global_server.broadcast(
resp, include=[self.peer]
)
case _:
pass
@authenticated
async def _chunk_request(self, uuid: str, message: MapChunkRequest) -> None:
session = server.game_state.peer_sessions[self.peer]
chunks = server.game_state.map.get_chunks(message.x, message.y, session.user_id)
response = ServerMessage(uuid=uuid)
if len(chunks) == 0:
response.error = Error(
type=ErrorType.ERROR_TYPE_INVALID_CHUNK,
message="Invalid Chunk requested",
)
else:
print("Sending Chunk", chunks[0].x, chunks[0].y)
response.chunk = MapChunkResponse(chunks=chunks)
await self.network_queue.put((response, None))
@authenticated
async def _acknowledge_damage(self, uuid: str, message: AcknowledgeDamage) -> None:
user_uuid = server.game_state.peer_sessions[self.peer].user_id
user = server.game_state.get_user(uuid=user_uuid)
if user is None:
return
response = ServerMessage(uuid=uuid)
if (
server.game_state.fight_manager.can_take_damage_user(
username=user.username, cooldown_ticks=30
)
and message.damage > 0
):
user.health -= message.damage
await self.network_queue.put((response, None))
await server.global_server.update_self(user.uuid)
@authenticated
async def _attack_enemy(self, uuid: str, message: AttackEnemy) -> None:
session = server.game_state.peer_sessions[self.peer]
if session.type != SessionType.SESSION_TYPE_NORMAL:
return
user = server.game_state.get_user(uuid=session.user_id)
if user is None:
print("User not found")
return
enemy = server.game_state.enemy_manager.get_enemy_for_user_by_uuid(
user_uuid=session.user_id, enemy_uuid=message.uuid
)
if enemy is None:
return # TODO: Enemy not found message to client?
if not server.game_state.fight_manager.is_plausible_attack(
user=user, enemy=enemy, attack_msg=message
):
print("not plausible attack")
return # TODO: Not plausible message to client?
if not server.game_state.fight_manager.can_take_damage_enemy(
enemy_uuid=enemy.uuid, cooldown_ticks=30
): # TODO: Dynamic cooldown for attacks
print("Enemy can't get damage again, cooldown not reached")
return # TODO: Not plausible message to client?
await enemy.take_damage(message.damage)
# We use `move_enemy_object` here to send the enemy update to the client. Lazy, but good enough
await server.global_server.move_enemy_object(
uuid=enemy.uuid,
x=enemy.x,
y=enemy.y,
health=enemy.health,
health_max=enemy.health_max,
last_attack=enemy.last_attack,
name=enemy.name,
include_user_ids=[user.uuid],
)
@authenticated
async def _object_asset_request(
self, uuid: str, message: ObjectAssetRequest
) -> None:
response = ServerMessage(uuid=uuid)
o = server.game_state.object_manager.get_object_by_uuid(message.uuid)
match o:
case NPC():
response.object_asset = ObjectAsset(
object_uuid=o.uuid,
assets=o.entity_assets,
name=o.name,
type=ObjectType.OBJECT_TYPE_NPC,
interactable=o.interactable,
interact_distance=o.interact_distance,
)
case Enemy():
response.object_asset = ObjectAsset(
object_uuid=o.uuid,
assets=o.entity_assets,
name=o.name,
type=ObjectType.OBJECT_TYPE_ENEMY,
interactable=False,
interact_distance=0,
)
case _:
if message.uuid in server.game_state.users:
response.object_asset = ObjectAsset(
object_uuid=message.uuid,
assets=server.game_state.map.player_asset,
)
elif (
await server.game_state.get_remote_userid(message.uuid) is not None
):
response.object_asset = ObjectAsset(
object_uuid=message.uuid,
assets=server.game_state.map.player_asset,
)
else:
response.error = Error(
type=ErrorType.ERROR_TYPE_INVALID_OBJECT,
message="Invalid Object requested",
)
await self.network_queue.put((response, None))
@authenticated
async def _interact(self, uuid: str, message: Interact) -> None:
response = ServerMessage(uuid=uuid)
obj = server.game_state.object_manager.get_object_by_uuid(message.uuid)
if obj is None:
response.error = Error(
type=ErrorType.ERROR_TYPE_INVALID_OBJECT,
message="Invalid Object requested",
)
else:
session = server.game_state.peer_sessions[self.peer]
user_id = session.user_id
if session.type != SessionType.SESSION_TYPE_NORMAL:
return
user = server.game_state.get_user(user_id)
match obj:
case AreaObject():
o = server.game_state.area_manager.get_areas_for_user_by_uuid(
user_uuid=user_id, area_uuid=message.uuid
)
if user is None or o is None:
response.error = Error(
type=ErrorType.ERROR_TYPE_INVALID_OBJECT,
message="Invalid Object requested",
)
else:
if o.interaction_on != InteractionOn.INTERACT:
response.error = Error(
type=ErrorType.ERROR_TYPE_INVALID_OBJECT,
message="Invalid interaction requested",
)
else:
if point_in_poly(user.coords.x, user.coords.y, o.area):
interact = await o.interact(user_id, message)
if not interact:
response.error = Error(
type=ErrorType.ERROR_TYPE_INVALID_OBJECT,
message="Invalid interaction requested",
)
else:
response.interact = interact
case NPC():
o = server.game_state.npc_manager.get_npc_for_user_by_uuid(
user_uuid=user_id, npc_uuid=message.uuid
)
player_asset = server.game_state.map.player_asset
if user is None or o is None:
response.error = Error(
type=ErrorType.ERROR_TYPE_INVALID_OBJECT,
message="Invalid Object requested",
)
else:
if not o.interactable:
return
dx = (user.coords.x + player_asset.width / 2) - (
(o.x + o.entity_assets.width / 2)
)
dy = (user.coords.y - player_asset.height / 2) - (
(o.y - o.entity_assets.height / 2)
)
distance_sq = dx**2 + dy**2
if distance_sq < (o.interact_distance + 14) ** 2:
status = message.status
text = ""
interaction_type = InteractType.INTERACT_TYPE_UNSPECIFIED
shop = []
progress = 0.0
if (
o.interactions[o.interaction_step].custom_interaction
== CustomInteraction.RUNNER
):
interaction = await o.interact(
user_id=user_id, interact=message
)
if o.runner_seed is not None:
progress = o.runner_seed
interaction_type = interaction.interaction_type
elif message.status != InteractStatus.INTERACT_STATUS_STOP:
interaction = await o.interact(
user_id=user_id, interact=message
)
text = await interaction.text
shop = interaction.shop
if (
text == ""
and len(shop) == 0
and interaction.interaction_type
!= InteractType.INTERACT_TYPE_RUNNER
):
status = InteractStatus.INTERACT_STATUS_STOP
interaction_type = interaction.interaction_type
for s in shop:
if s.item:
s.item.description = ""
if s.trade_in:
s.trade_in.description = ""
response.interact = Interact(
status=status,
uuid=message.uuid,
text=text,
type=interaction_type,
shop=shop,
progress=progress,
)
case _:
response.error = Error(
type=ErrorType.ERROR_TYPE_INVALID_OBJECT,
message="Invalid Object requested",
)
await self.network_queue.put((response, None))
async def _send_new_objects_view_distance(self, user: User) -> None:
objects: list[Object] = []
session = server.game_state.user_sessions[user.uuid]
for e in server.game_state.get_objects_view_distance(
uuid=user.uuid, x=user.coords.x, y=user.coords.y
):
if e.uuid in session.known_objects:
continue
obj_to_add = e.to_proto()
if e.type == ObjectType.OBJECT_TYPE_PICKUPABLE:
obj_to_add = deepcopy(obj_to_add)
obj_to_add.pickupable.description = ""
assert obj_to_add.type != ObjectType.OBJECT_TYPE_UNSPECIFIED, obj_to_add
objects.append(obj_to_add)
if len(objects) > 0:
session.known_objects |= set([o.uuid for o in objects])
response = ServerMessage(
objects=Objects(objects=objects),
)
await self.network_queue.put((response, None))
class Server:
connections: Dict[str, Connection]
def __init__(self, clickhouse_url: str) -> None:
self.connections = {}
self.clickhouse_url = clickhouse_url
async def start(self, host: str, port: int, running: Event) -> None:
self.running = running
await server.game_state.init(self.clickhouse_url)
s = await start_server(self.hande_cb, host=host, port=port)
update_loop_task = create_task(self.update_loop())
for coro in as_completed([update_loop_task]):
await coro
running.clear()
break
s.close()
# This is needed to give execution back to the control loop during the connection awaits
async def update_loop(self) -> None:
last_time = datetime.now()
while self.running.is_set():
current_time = datetime.now()
dt = (current_time - last_time).total_seconds()
if dt > (1 / (SERVER_TICK_RATE)) * 1.2:
print("REEE Server Lag")
await server.game_state.npc_manager.update(dt=dt)
await server.game_state.enemy_manager.update(dt=dt)
await server.game_state.pickupable_manager.update(dt=dt)
await server.game_state.object_manager.update(dt=dt)
# Check for user death and set timeout
for user in server.game_state.users.values():
if user.health < 0:
await server.game_state.die(user)
if user.uuid in server.game_state.user_sessions:
peer = server.game_state.user_sessions[user.uuid].peer
if (
peer in server.global_server.connections
and server.game_state.is_authenticated(peer)
):
await server.global_server.connections[peer].logout()
online_time = current_time - timedelta(minutes=1)
for s in list(server.game_state.peer_sessions.values()):
if s.last_ping.timestamp() < online_time.timestamp():
await server.global_server.connections[s.peer].logout()
await self.update_other_player_position()
last_time = datetime.now()
await sleep(1 / SERVER_TICK_RATE)
async def hande_cb(self, reader: StreamReader, writer: StreamWriter) -> None:
connection = Connection(reader, writer)
peer = cast(str, reader._transport.get_extra_info("peername")) # type: ignore
self.connections[peer] = connection
read_task = create_task(connection.read_message_loop())
send_task = create_task(connection.send_message_loop())
for coro in as_completed([read_task, send_task]):
await coro
break
del self.connections[peer]
def broadcast_sync(
self,
message: ServerMessage,
handler: Callable[[ServerMessageOneOfType], None] | None = None,
exclude: list[str] = [],
include: list[str] | None = None,
) -> None:
for peer, c in self.connections.items():
if not server.game_state.is_authenticated(peer):
continue
if peer in exclude:
continue
if include is not None and peer not in include:
continue
c.network_queue.put_nowait((message, handler))
async def broadcast(
self,
message: ServerMessage,
handler: Callable[[ServerMessageOneOfType], None] | None = None,
exclude: list[str] = [],
include: list[str] | None = None,
) -> None:
for peer, c in self.connections.items():
if not server.game_state.is_authenticated(peer):
continue
if peer in exclude:
continue
if include is not None and peer not in include:
continue
await c.network_queue.put((message, handler))
async def move_object(
self,
uuid: str,
x: float,
y: float,
include_user_ids: list[str] | None = None,
) -> None:
# No type specified, as this should be an object already known to the client
r = ServerMessage(objects=Objects([Object(uuid=uuid, coords=Coords(x=x, y=y))]))
users = server.game_state.get_local_users_distance(x, y)
users = [u.uuid for u in users]
if include_user_ids is not None:
users = [u for u in users if u in include_user_ids]
users_sessions = [
server.game_state.user_sessions[u].peer
for u in users
if u in server.game_state.user_sessions
]
if len(users_sessions) == 0:
return
await self.broadcast(r, include=users_sessions)
# This also includes enemy specific information
async def move_enemy_object(
self,
uuid: str,
x: float,
y: float,
health: int,
health_max: int,
last_attack: float,
name: str,
include_user_ids: list[str] | None = None,
) -> None:
# No type specified, as this should be an object already known to the client
r = ServerMessage(
objects=Objects(
[
Object(
uuid=uuid,
coords=Coords(x=x, y=y),
enemy_info=EnemyInfo(
health=health,
health_max=health_max,
name=name,
last_attack=last_attack,
),
)
]
)
)
users = server.game_state.get_local_users_distance(x, y)
users = [u.uuid for u in users]
if include_user_ids is not None:
users = [u for u in users if u in include_user_ids]
users_sessions = [
server.game_state.user_sessions[u].peer
for u in users
if u in server.game_state.user_sessions
]
if len(users_sessions) == 0:
return
await self.broadcast(r, include=users_sessions)
async def give_damage(
self, uuid: str, damage: int, include_user_ids: list[str] | None = None
) -> None:
r = ServerMessage(give_damage=GiveDamage(damage=damage))
users = server.game_state.users
if include_user_ids is not None:
users = [u for u in users if u in include_user_ids]
users_sessions = [
server.game_state.user_sessions[u].peer
for u in users
if u in server.game_state.user_sessions
]
if len(users_sessions) == 0:
return
await self.broadcast(r, include=users_sessions)
async def update_self(
self,
uuid: str,
) -> None:
user = server.game_state.users[uuid]
session = server.game_state.get_session(uuid)
r = ServerMessage(users=Users(users=[user]))
await server.game_state.update_remote_user(user)
if session:
await self.broadcast(r, include=[session])
async def update_other_player_position(self) -> None:
sessions = list(server.game_state.peer_sessions.values())
for s in sessions:
self_user = server.game_state.users.get(s.user_id, None)
if self_user is None:
continue
users = await server.game_state.get_online_users_distance(
self_user.coords.x, self_user.coords.y, s
)
new_known_users = set([u.uuid for u in users])
old_known_users = s.known_users - new_known_users
s.known_users = new_known_users
for u in old_known_users:
response = ServerMessage(logout=Logout(user=User(uuid=u)))
await server.global_server.broadcast(response, include=[s.peer])
message = ServerMessage(users=Users(users=users))
await self.broadcast(message, include=[s.peer])
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/CCCamp/2023/game/Maze/src/server/server/models.py | ctfs/CCCamp/2023/game/Maze/src/server/server/models.py | from dataclasses import dataclass, field
from datetime import datetime, timedelta
from typing import Any
from shared.gen.messages.v1 import Coords, MapChunk, SessionType
@dataclass
class Position:
coords: Coords
time: datetime
@dataclass
class Session:
type: SessionType = field(default=SessionType.SESSION_TYPE_NORMAL)
peer: str = field(default_factory=str)
user_id: str = field(default_factory=str)
known_objects: set[str] = field(default_factory=set)
last_positions: list[Position] = field(default_factory=list[Position])
maze: list[list[MapChunk]] = field(default_factory=list)
waiting_maze_chunks: list[tuple[int, int]] = field(default_factory=list)
last_ping: datetime = field(default=datetime.now())
known_users: set[str] = field(default_factory=set)
logout: bool = field(default_factory=bool)
def __getstate__(self) -> None:
return None
def __setstate__(self, state: Any) -> None:
self.__dict__ = Session().__dict__
@dataclass
class ScoreboardEntry:
user_id: str
username: str | None = None
start: datetime | None = None
end: datetime | None = None
@property
def time(self) -> timedelta:
if self.start and self.end:
return self.end - self.start
return timedelta.max
def reset(self) -> None:
self.start = None
self.end = None
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/CCCamp/2023/game/Maze/src/server/server/main.py | ctfs/CCCamp/2023/game/Maze/src/server/server/main.py | import argparse
import logging
import os
import sys
import tempfile
from asyncio import get_event_loop
from concurrent.futures import ProcessPoolExecutor
from datetime import datetime
from threading import Event
from typing import cast
import dill
from rpyc.core import SlaveService
from rpyc.utils.server import ThreadedServer
import server
from server.game import auth
from server.game.state import Game
from server.server_runner import Server
def save_thread(file: str | None) -> None:
if file is None:
file = "backups/state.pickle"
state = server.game_state
with tempfile.NamedTemporaryFile(delete=False) as f:
dill.dump(state, f)
os.rename(f.name, file)
logging.info(msg=f"Backup saved in {file}")
def debug_server(path: str):
server = ThreadedServer(service=SlaveService, auto_register=False, socket_path=path)
import threading
thread = threading.Thread(target=server.start)
thread.daemon = True
thread.start()
def run() -> None:
# tracer = VizTracer(
# log_async=True, tracer_entries=10000000, output_file="result.json"
# )
# tracer.enable_thread_tracing()
# tracer.start()
parser = argparse.ArgumentParser()
parser.add_argument("-v", "--verbose", help="Verbose", action="store_true")
parser.add_argument("-p", "--port", help="Port Default 1337", default=1337)
parser.add_argument("--host", help="Host Default 0.0.0.0", default="0.0.0.0")
parser.add_argument(
"--backup_file", help="Server backup file and auto restore", default=None
)
parser.add_argument("--debug_socket", help="Debug socket for server", default=None)
parser.add_argument("--auth_path", help="Path for credentials file", default=None)
parser.add_argument(
"--clickhouse_url", help="Clickhouse URL", default="http://localhost:8123/"
)
args = parser.parse_args()
log = logging.getLogger()
log.handlers.clear()
log.setLevel(level=logging.INFO)
handler = logging.StreamHandler(sys.stdout)
handler.setFormatter(
logging.Formatter("%(asctime)s - %(name)s - %(levelname)s - %(message)s")
)
log.addHandler(handler)
assert args.auth_path, "Auth Path Needed"
auth.auth_path = args.auth_path
if args.debug_socket:
debug_server(args.debug_socket)
if args.verbose:
log.setLevel(level=logging.DEBUG)
server.executor = ProcessPoolExecutor(max_workers=4)
if args.backup_file and os.path.isfile(args.backup_file):
with open(args.backup_file, "rb") as f:
state = cast(Game, dill.load(f))
state.user_sessions = {}
state.peer_sessions = {}
for u in state.users.values():
u.coords.timestamp = datetime.now()
server.game_state = state
else:
server.game_state = Game()
server.global_server = Server(args.clickhouse_url)
log.info(f"Listening on {args.host}:{args.port}")
running = Event()
running.set()
loop = get_event_loop()
server_coro = server.global_server.start(
host=args.host, port=args.port, running=running
)
# Backups are now done via db
# save_timer = RepeatedTimer(
# interval=60,
# function=save_thread,
# file=args.backup_file,
# )
# save_timer.start()
try:
server_task = loop.run_until_complete(server_coro)
loop.run_forever()
except KeyboardInterrupt:
pass
print("BYE")
# tracer.stop()
# tracer.save()
# Close the server
server_task.close() # type: ignore
loop.run_until_complete(server_task.wait_closed()) # type: ignore
loop.close()
running.clear()
# save_timer.stop()
def debug():
parser = argparse.ArgumentParser()
parser.add_argument("--debug_socket", help="Debug socket for server", default=None)
args = parser.parse_args()
assert args.debug_socket
from rpyc.utils.classic import unix_connect # type: ignore
conn = unix_connect(args.debug_socket) # type: ignore
modules = conn.modules # type: ignore
from IPython.terminal.embed import embed # type: ignore
server = modules["server"] # type: ignore
embed(local_ns=locals(), colors="neutral")
if __name__ == "__main__":
run()
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/CCCamp/2023/game/Maze/src/server/server/__init__.py | ctfs/CCCamp/2023/game/Maze/src/server/server/__init__.py | from concurrent.futures import ProcessPoolExecutor
from pathlib import Path
from server.game.state import Game
from server.server_runner import Server
game_state: Game
global_server: Server
executor: ProcessPoolExecutor
PATH = Path(__file__).parent
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.