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/UCTF/2024/crypto/Modal_1/challenge.py | ctfs/UCTF/2024/crypto/Modal_1/challenge.py | from secret import flag
size = len(flag)
for i in range(size-1):
print(ord(flag[i]) + ord(flag[i+1]), end=",") | python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/UCTF/2024/crypto/Karaball/challenge.py | ctfs/UCTF/2024/crypto/Karaball/challenge.py | from ECC import Curve, Coord
from secrets import randbelow
flag = "uctf{test_flag}"
signatures = {}
valid_hosts = {'uctf.ir'}
a = 0x0
b = 0x7
p = 0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f
Gx = 0x79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798
Gy = 0x483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8
ecc = Curve(a, b, p)
G = Coord(Gx, Gy)
assert ecc.is_on_curve(G)
for host in valid_hosts:
d = randbelow(p)
Q = ecc.sign(G, d)
signatures[host] = [hex(Q.x),hex(Q.y)]
print(signatures)
print("Give me your generator and private key for verification process")
data0 = input("G(x,y) in hex format: ")
data1 = input("d in hex format: ")
try:
Coordinates = data0.split(',')
PrivateKey = data1
G1 = Coord(int(Coordinates[0], 16), int(Coordinates[1], 16))
d1 = int(PrivateKey, 16)
except Exception as e:
print('Wrong format! try again.')
exit()
if not ecc.is_on_curve(G1):
print('Point is not on the curve!')
exit()
if d1 < 2:
print("Security Issues Discovered!")
exit()
sig = ecc.sign(G1, d1)
if sig.x == int(signatures['uctf.ir'][0], 16) and sig.y == int(signatures['uctf.ir'][1], 16):
print(f"Access granted. Here is your reward : {flag}".encode())
else:
print("Verficication process failed!") | python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/UCTF/2024/crypto/Karaball/ECC.py | ctfs/UCTF/2024/crypto/Karaball/ECC.py |
class Coord:
def __init__(self, x, y) -> None:
self.x = x
self.y = y
class Curve:
def __init__(self, a, b, p) -> None:
self.a = a
self.b = b
self.p = p
def addition(self, P, Q):
x3 = -1
y3 = -1
if P.x == 0 and P.x == 0:
x3 = Q.x
y3 = Q.y
elif Q.x == 0 and Q.x == 0:
x3 = P.x
y3 = P.y
elif P.x == Q.x and P.y == -Q.y:
x3 = 0
y3 = 0
elif P.x == Q.x and P.y == Q.y :
slope = ((3 * P.x**2 + self.a) * pow(2*P.y, -1, self.p)) % self.p
x3 = (slope**2 - (P.x + Q.x)) % self.p
y3 = (slope*(P.x - x3) - P.y) % self.p
else:
slope = ((Q.y - P.y) * pow(Q.x - P.x, -1, self.p)) % self.p
x3 = (slope**2 - (P.x + Q.x)) % self.p
y3 = (slope*(P.x - x3) - P.y) % self.p
R = Coord(x3, y3)
return R
def double_and_add(self, P, n):
if n == -1:
return Coord(P.x, self.p - P.y)
Q = Coord(P.x, P.y)
R = Coord(0, 0)
while n > 0:
if (n % 2) == 1:
R = self.addition(R, Q)
Q = self.addition(Q, Q)
n //= 2
return R
def get_y(self, x):
assert (self.p + 1) % 4 == 0
y2 = (x**3 + self.a * x + self.b) % self.p
y = pow(y2, (self.p+1)//4, self.p)
return y
def sign(self, G, d):
return self.double_and_add(G, d)
def is_on_curve(self, G):
return G.y == self.get_y(G.x) or G.y == -self.get_y(G.x) % self.p | python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/SHELL/2021/rev/keygen/keygen.py | ctfs/SHELL/2021/rev/keygen/keygen.py | python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false | |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/SHELL/2021/crypto/PowerRSA/script.py | ctfs/SHELL/2021/crypto/PowerRSA/script.py | from Crypto.Util.number import getPrime,isPrime,bytes_to_long
from Crypto.PublicKey.RSA import construct
from secret import flag
def getNextPrime(number):
while not isPrime(number):
number+=1
return number
p = getPrime(2048)
q = getNextPrime(p+1)
n = p*q
e = 65537
encrypted_flag = pow(bytes_to_long(flag.encode('utf-16')),e,n)
print("Public Key = \n{}".format(construct((n,e)).publickey().exportKey().decode()))
print("Encrypted Flag = {}".format(hex(encrypted_flag)))
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/SHELL/2021/crypto/Puny_Factors/secret.py | ctfs/SHELL/2021/crypto/Puny_Factors/secret.py | from Crypto.Util.number import getPrime,inverse,long_to_bytes,bytes_to_long
from Crypto.PublicKey import RSA
flag = "shellctf{something_here}"
n = getPrime(4096)
e = 65537
phi = (n-1)*(n-1)
d = inverse(e,phi)
encrypted_flag = pow(bytes_to_long(flag.encode()),e,n)
decrypted_flag = long_to_bytes(pow(encrypted_flag,d,n)).decode()
assert decrypted_flag == flag
print(RSA.construct((n,e)).publickey().exportKey().decode())
print("c = ",encrypted_flag)
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/SHELL/2021/crypto/Vuln-AES/encrypt.py | ctfs/SHELL/2021/crypto/Vuln-AES/encrypt.py | #!/usr/bin/env python3
import base64
from Crypto.Cipher import AES
secret_code = "<flag>"
def pad(message):
if len(message) % 16 != 0:
message = message + '0'*(16 - len(message)%16 ) #block-size = 16
return message
def encrypt(key, plain):
cipher = AES.new( key, AES.MODE_ECB )
return cipher.encrypt(plain)
sitrep = str(input("Crewmate! enter your situation report: "))
message = '''sixteen byte AES{sitrep}{secret_code}'''.format(sitrep = sitrep, secret_code = secret_code) #the message is like [16-bytes]/[report]/[flag]
message = pad(message)
message1 = bytes(message,'utf-8')
cipher = encrypt( b'sixteen byte key', message1 )
cipher = base64.b64encode(cipher)
print(cipher.decode('ascii'))
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/SHELL/2021/crypto/BruteforceRSA/script.py | ctfs/SHELL/2021/crypto/BruteforceRSA/script.py | from Crypto.Util.number import bytes_to_long,inverse,getPrime,long_to_bytes
from secret import message
import json
p = getPrime(128)
q = getPrime(128)
n = p * q
e = 65537
enc = pow(bytes_to_long(message.encode()),e,n)
print("Encrypted Flag is {}".format(enc))
open('./values.json','w').write(json.dumps({"e":e,"n":n,"enc_msg":enc}))
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/SHELL/2021/crypto/arc-cipher/script.py | ctfs/SHELL/2021/crypto/arc-cipher/script.py | text = "<flag>"
key = "MANGEKYOU"
s = []
k = []
for i in key:
k.append(((ord(i))))
for i in range(0,256):
s.append(i) # i.e. s = [0 1 2 3 4 5 6 7 ..]
if i >= len(key):
k.append(k[i%len(key)])
def key_sche(s,k):
j = 0
for i in range(0,256):
j = (j + s[i] + k[i])%256
temp = s[i]
s[i] = s[j]
s[j] = temp
# print("s in the iteration:",i+1," is :",s)
return s
def key_stream(text,s):
ks = []
i = 0
j = 0
status = 1
while(status == 1):
i = (i+1) % 256
j = (j+s[i])%256
s[i],s[j] = s[j],s[i]
t = (s[i]+s[j])%256
ks.append(s[t])
if len(ks) == len(text):
status = 0
return ks
def encrypt(text,k):
encrypted_txt = ''
hex_enc_txt = ''
for i in range(0,len(text)):
xored = (ord(text[i])) ^ (k[i])
encrypted_txt += chr(xored)
hex_enc_txt += hex(xored)[2:] + ' '
li = list(hex_enc_txt)
li.pop()
hex_enc_txt = ''.join(li)
return encrypted_txt,hex_enc_txt
key_new = key_stream(text,key_sche(s,k))
ciphered_txt,ciphered_hex = encrypt(text,key_new)
print("ciphered hex : ",ciphered_hex)
print("ciphered text : ",ciphered_txt)
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/SHELL/2021/crypto/Algoric-Shift/script.py | ctfs/SHELL/2021/crypto/Algoric-Shift/script.py | text = 'flag{...}'
key = [3,1,2]
li0 = []
li1 = []
li2 = []
for i in range(0,len(text)):
if i % 3 == 0:
li0.append(text[i])
elif (i - 1) % 3 == 0:
li1.append(text[i])
elif (i - 2) % 3 == 0:
li2.append(text[i])
li = []
for i in range(len(li1)):
li.append(li1[i])
li.append(li2[i])
li.append(li0[i])
# print(li)
print("The ciphered text is :")
ciphered_txt = (''.join(li))
print(ciphered_txt)
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/SHELL/2021/crypto/Subsi/script.py | ctfs/SHELL/2021/crypto/Subsi/script.py | alpha = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ{}_1234567890'
key = 'QWERTPOIUYASDFGLKJHZXCVMNB{}_1234567890'
text = <flag>
def encrypter(text,key):
encrypted_msg = ''
for i in text:
index = alpha.index(i)
encrypted_msg += key[index]
# print(encrypted_msg)
return encrypted_msg
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/SHELL/2022/crypto/OX9OR2/encryption.py | ctfs/SHELL/2022/crypto/OX9OR2/encryption.py | def xor(msg, key):
o = ''
for i in range(len(msg)):
o += chr(ord(msg[i]) ^ ord(key[i % len(key)]))
return o
with open('message', 'r') as f:
msg = ''.join(f.readlines()).rstrip('\n')
with open('key', 'r') as k:
key = ''.join(k.readlines()).rstrip('\n')
assert key.isalnum() and (len(key) == 9)
assert 'SHELL' in msg
with open('encrypted', 'w') as fo:
fo.write(xor(msg, key))
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/WATCTF/2025/rev/those_who_rev/run.py | ctfs/WATCTF/2025/rev/those_who_rev/run.py | #!/usr/local/bin/python
import sys, os
inpfile = open('/tmp/input', 'w')
while True:
line = input()
if line == "":
break
inpfile.write(line + "\n")
inpfile.close()
os.system('FLAG="$(cat flag.txt)" /k/k chall.k')
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/WATCTF/2025/crypto/alice_and_bob/communicate.py | ctfs/WATCTF/2025/crypto/alice_and_bob/communicate.py | #!/usr/local/bin/python
from cryptography.hazmat.primitives import hashes
from cryptography.hazmat.primitives.asymmetric import ec
from cryptography.hazmat.primitives.kdf.hkdf import HKDF
from cryptography.hazmat.primitives import serialization as ser
from cryptography.fernet import Fernet
import base64
from secret import alice_or_bob, other
def send_msg_raw(msg):
print(f'Send to {other}:', msg.hex())
def get_msg_raw():
line = input(f"Input response from {other}: ").strip()
return bytes.fromhex(line)
# Exchange keys
privkey = ec.generate_private_key(ec.SECP384R1())
encoded_pubkey = privkey.public_key().public_bytes(ser.Encoding.PEM, ser.PublicFormat.SubjectPublicKeyInfo)
send_msg_raw(encoded_pubkey)
other_pubkey = ser.load_pem_public_key(get_msg_raw())
if not isinstance(other_pubkey, ec.EllipticCurvePublicKey):
print("Hey, that's not an elliptic curve key! Connection compromised, terminating!")
shared_key = privkey.exchange(ec.ECDH(), other_pubkey)
derived_key = HKDF(
algorithm=hashes.SHA256(),
length=32,
salt=b'a salt',
info=b'arbitrary',
).derive(shared_key)
f = Fernet(base64.urlsafe_b64encode(derived_key))
def send_msg(msg, raw=False):
if raw:
send_msg_raw(msg)
else:
send_msg_raw(f.encrypt(msg))
def recv_msg():
return f.decrypt(get_msg_raw())
alice_or_bob(recv_msg, send_msg)
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/GPN/2024/crypto/Hackerman_Hash/hackerman-hash/generate.py | ctfs/GPN/2024/crypto/Hackerman_Hash/hackerman-hash/generate.py | import sys
from rich.progress import track
import random
SALT_RANGE = (150000,250000)
Prev_Mod = 426900
CHUNK_SIZE=4
FLAG = open("FLAG").readline().strip()
def keyedAck(key):
def ack(m,n):
if m == 0:
return n+key
if n == 0:
return ack(m-1,1)
return ack(m-1,ack(m,n-1))
return ack
def split_flag(flag):
flag = flag.encode()
flag = [flag[i:i+CHUNK_SIZE] for i in range(0,len(flag),CHUNK_SIZE)]
print(flag)
return [int(i.hex(),16) for i in flag]
def chain(keys):
out = []
salts = []
prev = 0
for c_k in track(keys):
salt = (2,random.randint(*SALT_RANGE)+prev)
ch = keyedAck(c_k)(*salt)
prev = ch % Prev_Mod
out.append(ch)
salts.append(salt[1])
return out,salts
if __name__ == "__main__":
sf=split_flag(FLAG)
f= open(f"out{sys.argv[1]}.txt","w")
f.write(str(chain(sf)))
f.close()
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/scriptCTF/2025/misc/Div_2/chall.py | ctfs/scriptCTF/2025/misc/Div_2/chall.py | import secrets
import decimal
decimal.getcontext().prec = 50
secret = secrets.randbelow(1 << 127) + (1 << 127) # Choose a 128 bit number
for _ in range(1000):
print("[1] Provide a number\n[2] Guess the secret number")
choice = int(input("Choice: "))
if choice == 1:
num = input('Enter a number: ')
fl_num = decimal.Decimal(num)
assert int(fl_num).bit_length() == secret.bit_length()
div = secret / fl_num
print(int(div))
if choice == 2:
guess = int(input("Enter secret number: "))
if guess == secret:
print(open('flag.txt').read().strip())
else:
print("Incorrect!")
exit(0)
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/scriptCTF/2025/misc/Div/chall.py | ctfs/scriptCTF/2025/misc/Div/chall.py | import os
import decimal
decimal.getcontext().prec = 50
secret = int(os.urandom(16).hex(),16)
num = input('Enter a number: ')
if 'e' in num.lower():
print("Nice try...")
exit(0)
if len(num) >= 10:
print('Number too long...')
exit(0)
fl_num = decimal.Decimal(num)
div = secret / fl_num
if div == 0:
print(open('flag.txt').read().strip())
else:
print('Try again...') | python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/scriptCTF/2025/misc/Modulo/jail.py | ctfs/scriptCTF/2025/misc/Modulo/jail.py | import ast
print("Welcome to the jail! You're never gonna escape!")
payload = input("Enter payload: ") # No uppercase needed
blacklist = list("abdefghijklmnopqrstuvwxyz1234567890\\;._")
for i in payload:
assert ord(i) >= 32
assert ord(i) <= 127
assert (payload.count('>') + payload.count('<')) <= 1
assert payload.count('=') <= 1
assert i not in blacklist
tree = ast.parse(payload)
for node in ast.walk(tree):
if isinstance(node, ast.BinOp):
if not isinstance(node.op, ast.Mod): # Modulo because why not?
raise ValueError("I don't like math :(")
exec(payload,{'__builtins__':{},'c':getattr}) # This is enough right?
print('Bye!') | python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/scriptCTF/2025/crypto/Mod/chall.py | ctfs/scriptCTF/2025/crypto/Mod/chall.py | #!/usr/local/bin/python3
import os
secret = int(os.urandom(32).hex(),16)
print("Welcome to Mod!")
num=int(input("Provide a number: "))
print(num % secret)
guess = int(input("Guess: "))
if guess==secret:
print(open('flag.txt').read())
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/scriptCTF/2025/programming/Back_From_Where/real_server.py | ctfs/scriptCTF/2025/programming/Back_From_Where/real_server.py | import random
import sys
import subprocess
import time
n = 100
grid_lines = []
for _ in range(n):
row = []
for _ in range(n):
flip = random.randint(1, 2)
if flip == 1:
row.append(str(random.randint(1, 696) * 2))
else:
row.append(str(random.randint(1, 696) * 5))
grid_lines.append(' '.join(row))
for line in grid_lines:
sys.stdout.write(line + '\n')
start = int(time.time())
proc = subprocess.run(['./solve'], input='\n'.join(grid_lines).encode(), stdout=subprocess.PIPE)
ans = []
all_ans = proc.stdout.decode()
for line in all_ans.split('\n')[:100]:
ans.append(list(map(int, line.strip().split(' '))))
ur_output = []
for i in range(n):
ur_output.append(list(map(int, input().split())))
if int(time.time()) - start > 20:
print("Time Limit Exceeded!")
exit(-1)
if ur_output == ans:
with open('flag.txt', 'r') as f:
print(f.readline())
else:
print("Wrong Answer!")
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/scriptCTF/2025/programming/Sums/server.py | ctfs/scriptCTF/2025/programming/Sums/server.py | #!/usr/bin/env python3
import random
import subprocess
import sys
import time
start = time.time()
n = 123456
nums = [str(random.randint(0, 696969)) for _ in range(n)]
print(' '.join(nums), flush=True)
ranges = []
for _ in range(n):
l = random.randint(0, n - 2)
r = random.randint(l, n - 1)
ranges.append(f"{l} {r}") #inclusive on [l, r] 0 indexed
print(l, r)
big_input = ' '.join(nums) + "\n" + "\n".join(ranges) + "\n"
proc = subprocess.Popen(
['./solve'],
stdin=subprocess.PIPE,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
text=True
)
stdout, stderr = proc.communicate(input=big_input)
out_lines = stdout.splitlines()
ans = [int(x) for x in out_lines[:n]]
urnums = []
for _ in range(n):
urnums.append(int(input()))
if ans != urnums:
print("wawawawawawawawawa")
sys.exit(1)
if time.time() - start > 10:
print("tletletletletletle")
sys.exit(1)
print(open('flag.txt', 'r').readline())
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/scriptCTF/2025/programming/Windows_To_Infinity/server.py | ctfs/scriptCTF/2025/programming/Windows_To_Infinity/server.py | mport random
import subprocess
n = 1000000
window_size = n / 2
"""
You will receive {n} numbers.
Every round, you will need to calculate a specific value for every window.
You will be doing the calculations on the same {n} numbers every round.
For example, in this round, you will need to find the sum of every window.
Sample testcase for Round 1 if n = 10
Input:
1 6 2 8 7 6 2 8 3 8
Output:
24 29 25 31 26 27
"""
a = []
for i in range(n):
a.append(str(random.randint(0, 100000)))
print(a[i], end=' ')
print()
proc = subprocess.Popen(['./solve'], stdin=subprocess.PIPE, stdout=subprocess.PIPE, text=True)
proc.stdin.write(' '.join(a) + '\n')
proc.stdin.flush()
def round(roundnumber, roundname):
print(f"Round {roundnumber}: {roundname}!")
ur_output = list(map(int, input().split()))
correct_output = list(map(int, proc.stdout.readline().split()))
if ur_output != correct_output:
print('uh oh')
exit(1)
round(1, "Sums")
round(2, "Xors")
round(3, "Means") # Note: means are rounded down
round(4, "Median") # Note: medians are calculated using a[floor(n / 2)]
round(5, "Modes") # Note: if there is a tie, print the mode with the largest value
round(6, "Mex (minimum excluded)") # examples: mex(5, 4, 2, 0) = 1, mex(4, 1, 2, 0) = 3, mex(5, 4, 2, 1) = 0
round(7, "# of Distinct Numbers")
round(8, "Sum of pairwise GCD") # If bounds of the window are [l, r], find the sum of gcd(a[i], a[j]) for every i, j where l <= i < j <= r,
print(open('flag.txt', 'r').readline())
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/Intent/2021/crypto/SANSA/sign_file.py | ctfs/Intent/2021/crypto/SANSA/sign_file.py |
from STARK.rescue_stark import rescue_sign
from STARK.rescue.rescue_hash import rescue
import yaml
from hashlib import blake2s
blake = lambda x: blake2s(x).digest()
PASSWORD = "<REDACTED>"
PASSWORD_HASH = [2019939026277137767,979901374969048238,1067125847181633502,445793449878813313]
def sign_file(path):
"""
path: a file path to be signed
returns signature - merkel_root1, merkel_root2, merkel_root3, merkel_branches1, merkel_branches2, merkel_branches3, low_degree_stark_proof
"""
with open(path, "rb") as f:
data = f.read()
data_blake_hash = blake(data)
file_hash = rescue([x for x in data_blake_hash])
proof = rescue_sign([ord(x) for x in PASSWORD], PASSWORD_HASH, file_hash)
proof_yaml = yaml.dump(proof, Dumper=yaml.SafeDumper)
return proof_yaml
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/Intent/2021/crypto/SANSA/verify_file.py | ctfs/Intent/2021/crypto/SANSA/verify_file.py | from STARK.rescue_stark import rescue_verify
from STARK.rescue.rescue_hash import rescue
import yaml
from hashlib import blake2s
from logging import *
blake = lambda x: blake2s(x).digest()
PASSWORD_HASH = [2019939026277137767,979901374969048238,1067125847181633502,445793449878813313]
def verify_file(path, signature):
with open(path, "rb") as f:
data = f.read()
return verify_data(data, signature)
def verify_data(data, signature):
try:
signature = yaml.load(signature, Loader=yaml.SafeLoader)
except Exception as e:
return False
data_blake_hash = blake(data)
file_hash = rescue([x for x in data_blake_hash])
return rescue_verify(PASSWORD_HASH, signature, file_hash, 18, 4096)
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/Intent/2021/crypto/SANSA/index.py | ctfs/Intent/2021/crypto/SANSA/index.py | import os
from flask import Flask, request, render_template
from verify_file import verify_data
import base64
from logging import *
import yaml
import json
app = Flask(__name__, template_folder=".", static_folder="public", static_url_path="/")
app.config['DEBUG'] = True
app.config["SECRET_KEY"] = os.getenv("SECRET_KEY", os.urandom(32))
@app.route('/')
def index():
return render_template('index.html')
@app.post("/sansa_update")
def verify_update():
try:
data = json.loads(request.files['file'].read())
except:
return "invalid json file"
try:
update_content = base64.b64decode(bytes(data["content"], 'utf-8'))
update_signature = data["signature"]
except:
return "invalid SANSA structure"
if verify_data(update_content, update_signature):
return "<HERE_GOES_THE_FLAG>"
else:
return "invalid signature"
if __name__ == "__main__":
app.run(host="0.0.0.0", port=5000, debug=True, threaded=True) | python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/Intent/2021/crypto/SANSA/STARK/fri.py | ctfs/Intent/2021/crypto/SANSA/STARK/fri.py | from .permuted_tree import merkelize, mk_branch, verify_branch, mk_multi_branch, verify_multi_branch
from .utils import get_power_cycle, get_pseudorandom_indices
from .poly_utils import PrimeField
# Generate an FRI proof that the polynomial that has the specified
# values at successive powers of the specified root of unity has a
# degree lower than maxdeg_plus_1
#
# We use maxdeg+1 instead of maxdeg because it's more mathematically
# convenient in this case.
def prove_low_degree(values, root_of_unity, maxdeg_plus_1, modulus, exclude_multiples_of=0, verbose = False):
f = PrimeField(modulus)
if verbose:
print('Proving %d values are degree <= %d' % (len(values), maxdeg_plus_1))
# If the degree we are checking for is less than or equal to 32,
# use the polynomial directly as a proof
if maxdeg_plus_1 <= 16:
if verbose:
print('Produced FRI proof')
return [[x.to_bytes(32, 'big') for x in values]]
# Calculate the set of x coordinates
xs = get_power_cycle(root_of_unity, modulus)
assert len(values) == len(xs)
# Put the values into a Merkle tree. This is the root that the
# proof will be checked against
m = merkelize(values)
# Select a pseudo-random x coordinate
special_x = int.from_bytes(m[1], 'big') % modulus
# Calculate the "column" at that x coordinate
# (see https://vitalik.ca/general/2017/11/22/starks_part_2.html)
# We calculate the column by Lagrange-interpolating each row, and not
# directly from the polynomial, as this is more efficient
quarter_len = len(xs)//4
x_polys = f.multi_interp_4(
[[xs[i+quarter_len*j] for j in range(4)] for i in range(quarter_len)],
[[values[i+quarter_len*j] for j in range(4)] for i in range(quarter_len)]
)
column = [f.eval_quartic(p, special_x) for p in x_polys]
m2 = merkelize(column)
# Pseudo-randomly select y indices to sample
ys = get_pseudorandom_indices(m2[1], len(column), 40, exclude_multiples_of=exclude_multiples_of)
# Compute the positions for the values in the polynomial
poly_positions = sum([[y + (len(xs) // 4) * j for j in range(4)] for y in ys], [])
# This component of the proof, including Merkle branches
o = [m2[1], mk_multi_branch(m2, ys), mk_multi_branch(m, poly_positions)]
# Recurse...
return [o] + prove_low_degree(column, f.exp(root_of_unity, 4),
maxdeg_plus_1 // 4, modulus, exclude_multiples_of=exclude_multiples_of)
# Verify an FRI proof
def verify_low_degree_proof(merkle_root, root_of_unity, proof, maxdeg_plus_1, modulus, exclude_multiples_of=0, verbose = False):
f = PrimeField(modulus)
# Calculate which root of unity we're working with
testval = root_of_unity
roudeg = 1
while testval != 1:
roudeg *= 2
testval = (testval * testval) % modulus
# Powers of the given root of unity 1, p, p**2, p**3 such that p**4 = 1
quartic_roots_of_unity = [1,
f.exp(root_of_unity, roudeg // 4),
f.exp(root_of_unity, roudeg // 2),
f.exp(root_of_unity, roudeg * 3 // 4)]
# Verify the recursive components of the proof
for prf in proof[:-1]:
root2, column_branches, poly_branches = prf
if verbose:
print('Verifying degree <= %d' % maxdeg_plus_1)
# Calculate the pseudo-random x coordinate
special_x = int.from_bytes(merkle_root, 'big') % modulus
# Calculate the pseudo-randomly sampled y indices
ys = get_pseudorandom_indices(root2, roudeg // 4, 40,
exclude_multiples_of=exclude_multiples_of)
# Compute the positions for the values in the polynomial
poly_positions = sum([[y + (roudeg // 4) * j for j in range(4)] for y in ys], [])
# Verify Merkle branches
column_values = verify_multi_branch(root2, ys, column_branches)
poly_values = verify_multi_branch(merkle_root, poly_positions, poly_branches)
# For each y coordinate, get the x coordinates on the row, the values on
# the row, and the value at that y from the column
xcoords = []
rows = []
columnvals = []
for i, y in enumerate(ys):
# The x coordinates from the polynomial
x1 = f.exp(root_of_unity, y)
xcoords.append([(quartic_roots_of_unity[j] * x1) % modulus for j in range(4)])
# The values from the original polynomial
row = [int.from_bytes(x, 'big') for x in poly_values[i*4: i*4+4]]
rows.append(row)
columnvals.append(int.from_bytes(column_values[i], 'big'))
# Verify for each selected y coordinate that the four points from the
# polynomial and the one point from the column that are on that y
# coordinate are on the same deg < 4 polynomial
polys = f.multi_interp_4(xcoords, rows)
for p, c in zip(polys, columnvals):
assert f.eval_quartic(p, special_x) == c
# Update constants to check the next proof
merkle_root = root2
root_of_unity = f.exp(root_of_unity, 4)
maxdeg_plus_1 //= 4
roudeg //= 4
# Verify the direct components of the proof
data = [int.from_bytes(x, 'big') for x in proof[-1]]
if verbose:
print('Verifying degree <= %d' % maxdeg_plus_1)
assert maxdeg_plus_1 <= 16
# Check the Merkle root matches up
mtree = merkelize(data)
assert mtree[1] == merkle_root
# Check the degree of the data
powers = get_power_cycle(root_of_unity, modulus)
if exclude_multiples_of:
pts = [x for x in range(len(data)) if x % exclude_multiples_of]
else:
pts = range(len(data))
poly = f.lagrange_interp([powers[x] for x in pts[:maxdeg_plus_1]],
[data[x] for x in pts[:maxdeg_plus_1]])
for x in pts[maxdeg_plus_1:]:
assert f.eval_poly_at(poly, powers[x]) == data[x]
if verbose:
print('FRI proof verified')
return True | python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/Intent/2021/crypto/SANSA/STARK/permuted_tree.py | ctfs/Intent/2021/crypto/SANSA/STARK/permuted_tree.py | from .merkle_tree import merkelize as _merkelize
from .merkle_tree import mk_branch as _mk_branch
from .merkle_tree import verify_branch as _verify_branch
from .merkle_tree import mk_multi_branch as _mk_multi_branch
from .merkle_tree import verify_multi_branch as _verify_multi_branch
from .merkle_tree import blake
def permute4_values(values):
o = []
ld4 = len(values) // 4
for i in range(ld4):
o.extend([values[i], values[i + ld4], values[i + ld4 * 2], values[i + ld4 * 3]])
return o
def permute4_index(x, L):
ld4 = L // 4
return x//ld4 + 4 * (x % ld4)
def permute4_indices(xs, L):
ld4 = L // 4
return [x//ld4 + 4 * (x % ld4) for x in xs]
def merkelize(L):
return _merkelize(permute4_values(L))
def mk_branch(tree, index):
return _mk_branch(tree, permute4_index(index, len(tree) // 2))
def verify_branch(root, index, proof, output_as_int=False):
return _verify_branch(root, permute4_index(index, 2**len(proof) // 2), proof, output_as_int)
def mk_multi_branch(tree, indices):
return _mk_multi_branch(tree, permute4_indices(indices, len(tree) // 2))
def verify_multi_branch(root, indices, proof):
return _verify_multi_branch(root, permute4_indices(indices, 2**len(proof[0]) // 2), proof) | python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/Intent/2021/crypto/SANSA/STARK/rescue_stark.py | ctfs/Intent/2021/crypto/SANSA/STARK/rescue_stark.py | import numpy as np
from math import ceil, log
import time
from .rescue.rescue_constants import MDS_MATRIX, INV_MDS_MATRIX, ROUND_CONSTANTS, PRIME, WORD_SIZE, NUM_ROUNDS, STATE_SIZE
from .poly_utils import PrimeField
from .utils import get_power_cycle, get_pseudorandom_indices, is_a_power_of_2
from .fft import fft
from .fri import prove_low_degree, verify_low_degree_proof
from .permuted_tree import merkelize, mk_branch, verify_branch, blake, mk_multi_branch, verify_multi_branch
import random
modulus = PRIME
extension_factor = 8
f = PrimeField(modulus)
TRACE_SIZE = 16
RAND_BEFORE = 1
RAND_AFTER = 0
spot_check_security_factor = 20
BatchHeight = 32
HashesPerBatch = 3
constraints_powers_dict = {i : (lambda x,y:0) for i in range(20)}
constrains_power_dict = {
0: lambda total_power, comp_length: total_power - comp_length,
1: lambda total_power, comp_length: total_power - comp_length,
2: lambda total_power, comp_length: total_power - 6*comp_length,
3: lambda total_power, comp_length: total_power - 6*comp_length,
4: lambda total_power, comp_length: total_power - 6*comp_length,
5: lambda total_power, comp_length: total_power - 6*comp_length,
6: lambda total_power, comp_length: total_power - 4*comp_length,
7: lambda total_power, comp_length: total_power - comp_length,
8: lambda total_power, comp_length: total_power - comp_length,
9: lambda total_power, comp_length: total_power - comp_length,
10: lambda total_power, comp_length: total_power - comp_length,
11: lambda total_power, comp_length: total_power - comp_length,
12: lambda total_power, comp_length: total_power - comp_length,
13: lambda total_power, comp_length: total_power - comp_length,
14: lambda total_power, comp_length: total_power - comp_length,
15: lambda total_power, comp_length: total_power - comp_length,
16: lambda total_power, comp_length: total_power - comp_length,
17: lambda total_power, comp_length: total_power - comp_length,
18: lambda total_power, comp_length: total_power - comp_length,
19: lambda total_power, comp_length: total_power - comp_length,
}
NUM_CONSTRAINTS = 200
def HalfRound(state, round_index, p):
mds_matrix = np.array(MDS_MATRIX, dtype=object) % p
if round_index % 2 == 1:
state = [pow(x, (2*p - 1) // 3, p) for x in state]
else:
state = [pow(x, 3, p) for x in state]
state = mds_matrix.dot(state) % p
state = [(state[i] + ROUND_CONSTANTS[round_index][i]) % p for i in range(STATE_SIZE)]
return state
def get_power_list(total_length, comp_length, hash = True):
powers = []
for i in range(4):
powers.append(constraints_powers_dict[0](total_length, comp_length))
for i in range(4):
powers.append(constraints_powers_dict[1](total_length, comp_length))
for i in range(STATE_SIZE):
powers.append(constraints_powers_dict[2](total_length, comp_length))
for i in range(4):
powers.append(constraints_powers_dict[3](total_length, comp_length))
for i in range(STATE_SIZE - 4):
powers.append(constraints_powers_dict[4](total_length, comp_length))
for i in range(4):
powers.append(constraints_powers_dict[5](total_length, comp_length))
for i in range(STATE_SIZE):
powers.append(constraints_powers_dict[6](total_length, comp_length))
for i in range(4):
powers.append(constraints_powers_dict[7](total_length, comp_length))
for i in range(4):
powers.append(constraints_powers_dict[8](total_length, comp_length))
for i in range(STATE_SIZE*STATE_SIZE):
powers.append(constraints_powers_dict[9](total_length, comp_length))
if hash:
for i in range(4):
powers.append(constraints_powers_dict[10](total_length, comp_length))
for i in range(TRACE_SIZE + 1):
powers.append(total_length - comp_length)
return powers
def append_state(trace, state):
for i in range(STATE_SIZE):
trace[i].append(state[i])
for i in range(STATE_SIZE, TRACE_SIZE):
trace[i].append(0)
def rescue_computational_trace(input, file_hash = None, output = None):
input_length = len(input)
if file_hash is not None:
input_and_hash = input + [random.randrange(1, PRIME) for _ in range(12*RAND_BEFORE)] + file_hash + [random.randrange(1, PRIME) for _ in range(8 + 12*RAND_AFTER)]
else:
input_and_hash = input[:]
inp_hash_length = len(input_and_hash)
chain_length = ceil((inp_hash_length - 4) / 4)
# We do HashesPerBatch so that the total append_states amount will be BatchHeight, which is a power of two
log_trace_length = log(ceil(chain_length / HashesPerBatch), 2)
# We want to have a power of 2 number of batches, so that the total height will also be a power of 2
trace_length = 2**(ceil(log_trace_length))
#We want the trace to be of length that is a power of two.
new_input = input_and_hash + [random.randrange(1, PRIME)for _ in range(4 + 12*trace_length - inp_hash_length)]
trace_length = 32*trace_length
p = PRIME
trace = [[] for i in range(TRACE_SIZE)]
state = [0] * STATE_SIZE
inp_index = 0
for i in range(4):
state[i] = new_input[inp_index + i]
inp_index += 4
while len(trace[0]) < trace_length:
for hash_ind in range(3):
for i in range(4):
state[4 + i] = new_input[inp_index + i]
state[8 + i] = 0
inp_index += 4
if hash_ind == 0:
append_state(trace, state)
state = [(state[i] + ROUND_CONSTANTS[0][i]) % p for i in range(STATE_SIZE)]
for round in range(NUM_ROUNDS):
state = HalfRound(state, round*2 + 1, p)
append_state(trace, state)
state = HalfRound(state, round*2 + 2, p)
if input_length <= inp_index and inp_index < input_length + 4:
#We're right after the original hash calculation
assert state[:4] == output, "Error in hash calculation"
append_state(trace, state)
assert len(trace[0]) % 32 == 0
full_trace = []
for i in range(len(trace[0])):
for s in trace:
full_trace.append(s[i])
return full_trace
def create_rescue_polynoms(precision, output, file_hash = None):
comp_length = precision // extension_factor
# Root of unity such that x^precision=1
G2 = f.exp(7, (modulus - 1) // precision)
# Root of unity such that x^steps=1
skips = precision // comp_length
G1 = f.exp(G2, skips)
#Create consts polynomial for each state_ind
all_even_consts = []
all_odd_consts = []
for state_ind in range(TRACE_SIZE):
odd_consts = []
even_consts = []
even_consts.append(0)
if state_ind < STATE_SIZE:
for j in range(HashesPerBatch):
if state_ind < 4:
even_consts[-1] += ROUND_CONSTANTS[0][state_ind]
else:
even_consts[-1] = ROUND_CONSTANTS[0][state_ind]
for round in range(NUM_ROUNDS):
odd_consts.append(ROUND_CONSTANTS[2*round + 1][state_ind])
even_consts.append(ROUND_CONSTANTS[2*round + 2][state_ind])
even_consts.append(0)
odd_consts.append(0)
odd_consts.append(0)
else:
even_consts = [0]*BatchHeight
odd_consts = [0]*BatchHeight
all_even_consts.append(even_consts)
all_odd_consts.append(odd_consts)
all_even_next_eval = [all_even_consts[i % TRACE_SIZE][(i // TRACE_SIZE) % BatchHeight] for i in range(comp_length)]
all_even_poly = fft(all_even_next_eval, modulus, G1, inv = True)
all_even_eval = fft(all_even_poly, modulus, G2)
all_odd_next_eval = [all_odd_consts[i % TRACE_SIZE][(i // TRACE_SIZE) % BatchHeight] for i in range(comp_length)]
new_mds = [[] for i in range(TRACE_SIZE)]
new_inv_mds = [[] for i in range(TRACE_SIZE)]
for i in range(TRACE_SIZE):
for j in range(TRACE_SIZE):
if i < STATE_SIZE and j < STATE_SIZE:
new_mds[i].append(MDS_MATRIX[i][j])
new_inv_mds[i].append(INV_MDS_MATRIX[i][j])
else:
new_mds[i].append(0)
new_inv_mds[i].append(0)
mds_mini = []
inv_mds_mini = []
for i in range(TRACE_SIZE):
mds_mini.append([new_mds[j % TRACE_SIZE][i] for j in range(comp_length)])
inv_mds_mini.append([new_inv_mds[j % TRACE_SIZE][i] for j in range(comp_length)])
mds_poly = [fft(mini, modulus, G1, inv = True) for mini in mds_mini]
inv_mds_poly = [fft(mini, modulus, G1, inv = True) for mini in inv_mds_mini]
mds_eval = [fft(poly, modulus, G2) for poly in mds_poly]
inv_mds_eval = [fft(poly, modulus, G2) for poly in inv_mds_poly]
odd_consts_mod_mini = []
for i in range(TRACE_SIZE):
odd_consts_mod_mini.append([all_odd_next_eval[j - (j % TRACE_SIZE) + i] for j in range(comp_length)])
odd_consts_mod_poly = [fft(mini, modulus, G1, inv = True) for mini in odd_consts_mod_mini]
odd_consts_mod_eval = [fft(poly, modulus, G2) for poly in odd_consts_mod_poly]
output_mini = [output[i % len(output)] for i in range(comp_length)]
output_poly = fft(output_mini, modulus, G1, inv = True)
output_eval = fft(output_poly, modulus, G2)
if file_hash is not None:
file_hash_mini = [file_hash[i % len(file_hash)] for i in range(comp_length)]
file_hash_poly = fft(file_hash_mini, modulus, G1, inv = True)
file_hash_eval = fft(file_hash_poly, modulus, G2)
return all_even_eval, odd_consts_mod_eval, mds_eval, inv_mds_eval, output_eval, file_hash_eval
return all_even_eval, odd_consts_mod_eval, mds_eval, inv_mds_eval, output_eval, None
def rescue_sign(password, password_output, file_hash = None, constraints_powers_dict=constraints_powers_dict):
start_time = time.time()
full_trace = rescue_computational_trace(password, file_hash, output = password_output)
comp_length = len(full_trace)
input_length = len(password)
chain_length = ceil((input_length - 4) / 4)
precision = comp_length * extension_factor
# Root of unity such that x^precision=1
G2 = f.exp(7, (modulus - 1) // precision)
# Root of unity such that x^steps=1
skips = precision // comp_length
G1 = f.exp(G2, skips)
# Powers of the higher-order root of unity
xs = get_power_cycle(G2, modulus)
skips2 = comp_length // (BatchHeight * TRACE_SIZE)
all_even_eval, odd_consts_mod_eval, mds_eval, inv_mds_eval, output_eval, file_hash_eval = create_rescue_polynoms(precision, password_output, file_hash)
# Interpolate the computational trace into a polynomial P, with each step
# along a successive power of G1
computational_trace_polynomial = fft(full_trace, modulus, G1, inv=True)
p_evaluations_extension = fft(computational_trace_polynomial, modulus, G2)
print('Converted computational steps into a polynomial and low-degree extended it')
p_mod_mini = []
for i in range(TRACE_SIZE):
p_mod_mini.append([full_trace[j - (j % TRACE_SIZE) + i] for j in range(comp_length)])
p_mod_poly = [fft(mini, modulus, G1, inv = True) for mini in p_mod_mini]
p_mod_eval = [fft(poly, modulus, G2) for poly in p_mod_poly]
state_after_eval = all_even_eval[:]
for i in range(TRACE_SIZE):
state_after_eval = [f.add(st, f.mul(m, f.exp(p, 3))) for (st, m, p) in zip(state_after_eval, mds_eval[i], p_mod_eval[i])]
state_before_eval = [0 for i in range(precision)]
for i in range(TRACE_SIZE):
subbed = [f.sub(p_mod_eval[i][(j + TRACE_SIZE * extension_factor) % precision], odd_consts_mod_eval[i][j]) for j in range(precision)]
state_before_eval = [f.add(st, f.mul(m, su)) for (st, m, su) in zip(state_before_eval, inv_mds_eval[i], subbed)]
state_before_eval = [f.exp(st, 3) for st in state_before_eval]
#We compute evaluation on the extension field
trace_plus_round0_eval = [p_evaluations_extension[i] + all_even_eval[i] for i in range(precision)]
trace_minus_output_eval = [p_evaluations_extension[i] - output_eval[i] for i in range(precision)]
if file_hash_eval is not None:
trace_minus_file_hash_eval = [p_evaluations_extension[i] - file_hash_eval[i] for i in range(precision)]
print("Computed all values polynomials")
constraints = []
#We enforce constraints on the state - such that
# 1. The trace is a true rescue computation state
# 2. The hash of the passwords appears in the state
# 3. The file_hash is hashed as well
# 4. The p_mod_evals are correct
skips3 = comp_length // TRACE_SIZE
#This represents something that happens once every state
once_state_eval = [xs[(i*skips3) % precision] - 1 for i in range(precision)]
#Constraints 0 check that the last 4 bytes of every state are 0 (since we need a power of 2, but the original state is only of size 12)
for state_ind in range(STATE_SIZE, TRACE_SIZE):
filler_states = [once_state_eval[(i - state_ind*extension_factor)%precision] for i in range(precision)]
filler_states_inv = f.multi_inv(filler_states)
constraint0_evals = [f.mul(pv, fs) for (pv, fs) in zip(p_evaluations_extension, filler_states_inv)]
constraints.append((0, constraint0_evals))
#This represents something that happens once every batch
once_batch_eval = [xs[(i*skips2) % precision] - 1 for i in range(precision)]
#Constraints 1 check that in the beginning of each batch, bytes 8-12 are 0 (since the inital state is only of size 8)
for state_ind in range(8, STATE_SIZE):
barch_ind0 = [once_batch_eval[(i - 0 * TRACE_SIZE * extension_factor - state_ind * extension_factor) %precision] for i in range(precision)]
batch_ind0_inv = f.multi_inv(barch_ind0)
constraint1_evals = [f.mul(pv , bi) for (pv, bi) in zip(p_evaluations_extension, batch_ind0_inv)]
constraints.append((1, constraint1_evals))
#Constraints 2 check that at the beginning of each batch, the first state is just half_state before the next one (this is a rescue demand)
for state_ind in range(0, STATE_SIZE):
batch_ind0 = [once_batch_eval[(i - 0 * TRACE_SIZE*extension_factor - state_ind * extension_factor) %precision] for i in range(precision)]
batch_ind0_inv = f.multi_inv(batch_ind0)
constraints2_eval = [f.mul(f.sub(tpc0, stb) ,bi) for (tpc0, stb, bi) in zip(trace_plus_round0_eval, state_before_eval, batch_ind0_inv)]
constraints.append((2, constraints2_eval))
#Constraint3 represents that for every 2 states that are not the beginning or end
# (i % 32 != 0, 30, 31), we have state_before(next half round) = state_after(half round)
# That's true for the first 4 bytes because:
# a) they pass on (and not deleted in the next hash iteration)
# b) we've fixed consts such that they already include consts[0]
for state_ind in range(0, 4):
batch_ind0 = [once_batch_eval[(i - 0 * TRACE_SIZE *extension_factor - state_ind * extension_factor)%precision] for i in range(precision)]
batch_ind30 = [once_batch_eval[(i - 30 * TRACE_SIZE *extension_factor - state_ind * extension_factor)%precision] for i in range(precision)]
batch_ind31 = [once_batch_eval[(i - 31 * TRACE_SIZE *extension_factor - state_ind * extension_factor)%precision] for i in range(precision)]
all_batches = [f.mul(f.mul(bi0, bi30),bi31) for (bi0, bi30, bi31) in zip(batch_ind0, batch_ind30, batch_ind31)]
filler_states = [once_state_eval[(i - state_ind* extension_factor)%precision] for i in range(precision)]
filler_states_inv = f.multi_inv(filler_states)
constraints3_eval = [(sta - stb) * abi * fs for (sta, stb, abi, fs) in zip(state_after_eval, state_before_eval, all_batches, filler_states_inv)]
constraints.append((3, constraints3_eval))
#Constraint4 is almost as 3, but for 4:12, and that means that this condition does not apply
# also when starting a new hash within the same batch (index 10, 20 as well)
for state_ind in range(4, STATE_SIZE):
batch_ind0 = [once_batch_eval[(i - 0 * TRACE_SIZE * extension_factor - state_ind * extension_factor)%precision] for i in range(precision)]
batch_ind10 = [once_batch_eval[(i - 10 * TRACE_SIZE * extension_factor - state_ind * extension_factor)%precision] for i in range(precision)]
batch_ind20 = [once_batch_eval[(i - 20 * TRACE_SIZE * extension_factor - state_ind * extension_factor)%precision] for i in range(precision)]
batch_ind30 = [once_batch_eval[(i - 30 * TRACE_SIZE * extension_factor - state_ind * extension_factor)%precision] for i in range(precision)]
batch_ind31 = [once_batch_eval[(i - 31 * TRACE_SIZE * extension_factor - state_ind * extension_factor)%precision] for i in range(precision)]
all_batches = [f.mul(f.mul(f.mul(f.mul(bi0, bi10),bi20), bi30),bi31) for (bi0, bi10 , bi20, bi30, bi31) in zip(batch_ind0, batch_ind10, batch_ind20, batch_ind30, batch_ind31)]
filler_states = [once_state_eval[(i - state_ind * extension_factor)%precision] for i in range(precision)]
filler_states_inv = f.multi_inv(filler_states)
constraints4_eval = [(sta - stb) * abi * fs for (sta, stb, abi, fs) in zip(state_after_eval, state_before_eval, all_batches, filler_states_inv)]
constraints.append((4, constraints4_eval))
# Constraints 5 check that in the new hashes within the same batch (indexes 10, 20), bytes 8:12 are 0 (since a new hash's initial state is only 8 bytes)
for state_ind in range(STATE_SIZE - 4, STATE_SIZE):
batch_ind10 = [once_batch_eval[(i - 10 * TRACE_SIZE* extension_factor - state_ind * extension_factor)%precision] for i in range(precision)]
batch_ind20 = [once_batch_eval[(i - 20 * TRACE_SIZE* extension_factor - state_ind * extension_factor)%precision] for i in range(precision)]
all_batches = [f.mul(b10, b20) for (b10, b20) in zip(batch_ind10, batch_ind20)]
all_batches_inv = f.multi_inv(all_batches)
constraints5_eval = [f.sub(state_before_eval[i], all_even_eval[i]) * all_batches_inv[i] for i in range(precision)]
constraints.append((5, constraints5_eval))
# Constraints 6 checks that the start of the last state is just half round after the one before it.
for state_ind in range(0, STATE_SIZE):
batch_ind30 = [once_batch_eval[(i - 30 * TRACE_SIZE* extension_factor - state_ind * extension_factor)%precision] for i in range(precision)]
batch30_inv = f.multi_inv(batch_ind30)
constraints6_eval = [(p_evaluations_extension[(i + extension_factor*TRACE_SIZE) % precision] - state_after_eval[i]) * batch30_inv[i] for i in range(precision)]
constraints.append((6, constraints6_eval))
# Constraints 7 check that the first row after a batch is the last row before the batch (since this is how we create the trace)
for state_ind in range(0, 4):
batch_ind31 = [once_batch_eval[(i - 31 * TRACE_SIZE* extension_factor - state_ind * extension_factor)%precision] for i in range(precision)]
batch31_inv = f.multi_inv(batch_ind31)
last_step_eval = [xs[i] - xs[(comp_length - TRACE_SIZE + state_ind)*extension_factor] for i in range(precision)]
constraints7_eval = [(p_evaluations_extension[(i + extension_factor*TRACE_SIZE) % precision] - p_evaluations_extension[i]) * batch31_inv[i] * last_step_eval[i] for i in range(precision)]
constraints.append((7, constraints7_eval))
#Constraints 8 check that the password hash is actually within the trace in the right spot (this checks that we actually have a preimage of the hash)
for state_ind in range(0, len(password_output)):
output_row_eval = [xs[i] - xs[(ceil(chain_length/HashesPerBatch) * BatchHeight * TRACE_SIZE - TRACE_SIZE + state_ind)*extension_factor] for i in range(precision)]
output_row_inv = f.multi_inv(output_row_eval)
constraints8_eval = [tmo * ori for (tmo, ori) in zip(trace_minus_output_eval, output_row_inv)]
constraints.append((8, constraints8_eval))
#This checks that p_mod_evals are actually computed properly
for state_ind in range(0, STATE_SIZE):
for poly_ind in range(0, STATE_SIZE):
filler_states = [once_state_eval[(i) % precision] for i in range(precision)]
filler_states_inv = f.multi_inv(filler_states)
constraints9_eval = [f.mul(f.sub(p_evaluations_extension[(i + extension_factor*poly_ind) % precision] ,p_mod_eval[poly_ind][(i + state_ind*extension_factor) % precision]), filler_states_inv[i]) for i in range(precision)]
constraints.append((9, constraints9_eval))
#The last constraints check that the file_hash appears within the computational trace in the place it should appear in.
if file_hash is not None:
for state_ind in range(4, 8):
file_hash_row_eval = [xs[i] - xs[(ceil(chain_length/HashesPerBatch) * BatchHeight * TRACE_SIZE + BatchHeight*TRACE_SIZE*RAND_BEFORE + state_ind)*extension_factor] for i in range(precision)]
file_hash_row_inv = f.multi_inv(file_hash_row_eval)
constraints10_eval = [tmo * ori for (tmo, ori) in zip(trace_minus_file_hash_eval, file_hash_row_inv)]
constraints.append((10, constraints10_eval))
print("Computed all constraints polynomials")
#We create merkel trees for the p's and c's (trace polynomials and constraints polynomials)
p_eval_bytes = [x.to_bytes(8, 'big') for x in p_evaluations_extension]
p_mod_eval_bytes = [[x.to_bytes(8, 'big') for x in p_mod_i] for p_mod_i in p_mod_eval]
p_values_bytes = [p_eval_bytes[i] + b"".join([p[i] for p in p_mod_eval_bytes]) for i in range(precision)]
p_mtree = merkelize(p_values_bytes)
constraints_bytes = [[(x % modulus).to_bytes(8,'big') for x in constraint] for _, constraint in constraints]
constraints_concat_bytes = [b"".join([c[i] for c in constraints_bytes]) for i in range(precision)]
c_mtree = merkelize(constraints_concat_bytes)
print("Computed hash roots")
#We generate a linear combination of those polynomials, deg adjusted, with random constants
ks = []
for i in range(2*(len(constraints) + len(p_mod_eval)) + 2):
ks.append(int.from_bytes(blake(p_mtree[1] + i.to_bytes(2, 'big')), 'big') % modulus)
total_power = comp_length*6
#toatl_power - deg(constraint) for each constraint type
#We also add the total_power - def(p) or p_mod (which is comp_length) for them at the end
powers_list = [constraints_powers_dict[ind](total_power, comp_length) for ind, _ in constraints] + [total_power - comp_length for i in range(len(p_mod_eval) + 1)]
powers_eval = []
for power in powers_list:
G2_to_the_power = f.exp(G2, power)
tmp_powers = [1]
for i in range(1, precision):
tmp_powers.append(tmp_powers[-1]*G2_to_the_power % modulus)
powers_eval.append(tmp_powers)
l_evaluations = [0 for i in range(precision)]
#We add all the constraints, deg adjusted
for c_ind, (_, constraint) in enumerate(constraints):
#l += (k[2*c_ind] + k[2*c_ind + 1]*g**constraint_power) * constraint
l_evaluations = [f.add(l_evaluations[i], f.mul(f.add(ks[c_ind*2], f.mul(ks[c_ind*2 + 1], powers_eval[c_ind][i])), constraint[i])) for i in range(precision)]
num_constraints = NUM_CONSTRAINTS
if file_hash is not None:
num_constraints += 4
assert num_constraints == len(constraints)
#We add all the p_mod values, deg adjusted
for p_ind, p_mod_i in enumerate(p_mod_eval):
l_evaluations = [f.add(l_evaluations[i], f.mul(f.add(ks[2*num_constraints + p_ind*2], f.mul(ks[2*num_constraints + p_ind*2 + 1], powers_eval[num_constraints + p_ind][i])), p_mod_i[i])) for i in range(precision)]
#We add p_evaluations, deg adjusted
l_evaluations = [f.add(l_evaluations[i], f.mul(f.add(ks[-2], f.mul(ks[-1], powers_eval[-1][i])), p_evaluations_extension[i])) for i in range(precision)]
l_mtree = merkelize(l_evaluations)
print("Computed random linear combination")
# Do some spot checks of the Merkle tree at pseudo-random coordinates, excluding
# multiples of `extension_factor`
samples = spot_check_security_factor
positions = get_pseudorandom_indices(l_mtree[1], precision, samples,
exclude_multiples_of=extension_factor)
augmented_positions = sum([[(x - ((x // extension_factor) % TRACE_SIZE)* extension_factor + i*extension_factor) % precision for i in range(2*TRACE_SIZE)] for x in positions], [])
print('Computed %d spot checks' % samples)
# Return the Merkle roots of P and D, the spot check Merkle proofs,
# and low-degree proofs of P and D
low_degree_pf = prove_low_degree(l_evaluations, G2, total_power, modulus, exclude_multiples_of=extension_factor)
o = [p_mtree[1],
c_mtree[1],
l_mtree[1],
mk_multi_branch(p_mtree, augmented_positions),
mk_multi_branch(c_mtree, augmented_positions),
mk_multi_branch(l_mtree, augmented_positions),
low_degree_pf]
print("STARK computed in %.4f sec" % (time.time() - start_time))
assert verify_low_degree_proof(l_mtree[1], G2, low_degree_pf, total_power, modulus, exclude_multiples_of=extension_factor), "Couldn't verify low_degree pf"
return o
# Verifies a STARK
def rescue_verify(output, proof, file_hash = None, chain_length = 12, comp_length = 4096):
p_root, c_root, l_root, p_branches, c_branches, linear_comb_branches, fri_proof = proof
start_time = time.time()
if not is_a_power_of_2(comp_length):
return False
precision = comp_length * extension_factor
# Get (steps)th root of unity
G2 = f.exp(7, (modulus-1)//precision)
skips2 = comp_length // (BatchHeight * TRACE_SIZE)
skips3 = comp_length // TRACE_SIZE
total_power = comp_length * 6
if not verify_low_degree_proof(l_root, G2, fri_proof, total_power, modulus, exclude_multiples_of=extension_factor):
return False
print("Verified the random linear combination is low degree")
all_even_eval, odd_consts_mod_eval, mds_eval, inv_mds_eval, output_eval, file_hash_eval = create_rescue_polynoms(precision, output, file_hash)
num_constraints = NUM_CONSTRAINTS
if file_hash is not None:
num_constraints += 4
powers = get_power_list(total_power, comp_length, file_hash is not None)
# Performs the spot checks
ks = []
for i in range(2*(num_constraints + TRACE_SIZE) + 2):
ks.append(int.from_bytes(blake(p_root + i.to_bytes(2, 'big')), 'big') % modulus)
samples = spot_check_security_factor
positions = get_pseudorandom_indices(l_root, precision, samples,
exclude_multiples_of=extension_factor)
augmented_positions = sum([[(x - ((x // extension_factor) % TRACE_SIZE)* extension_factor + i*extension_factor) % precision for i in range(2*TRACE_SIZE)] for x in positions], [])
p_branch_leaves = verify_multi_branch(p_root, augmented_positions, p_branches)
c_branch_leaves = verify_multi_branch(c_root, augmented_positions, c_branches)
linear_comb_branch_leaves = verify_multi_branch(l_root, augmented_positions, linear_comb_branches)
print("Verified Merkle branches")
for i, pos in enumerate(positions):
p_branches = [p_branch_leaves[i*(2*TRACE_SIZE) + j] for j in range(2*TRACE_SIZE)]
p_vals = []
p_mod_vals = [[] for j in range(TRACE_SIZE)]
for j in range(2*TRACE_SIZE):
p_vals.append(int.from_bytes(p_branches[j][:8], 'big'))
for k in range(TRACE_SIZE):
p_mod_vals[k].append(int.from_bytes(p_branches[j][8 + 8*k : 16 + 8*k], 'big'))
for pos_ind in range(TRACE_SIZE):
l_res = 0
pos = pos - ((pos // extension_factor) % TRACE_SIZE)*extension_factor + pos_ind * extension_factor
x = f.exp(G2, pos)
c_branch = c_branch_leaves[i*(2*TRACE_SIZE) + pos_ind]
#Calculate the values of all the polynomials
l_of_x = int.from_bytes(linear_comb_branch_leaves[i*(2*TRACE_SIZE) + pos_ind], 'big')
if not pos_ind == (pos // extension_factor) % TRACE_SIZE:
return False
c_vals = []
for j in range(0, len(c_branch)// 8):
c_vals.append(int.from_bytes(c_branch[8*j : 8 + 8*j], 'big'))
l_res += c_vals[-1] * (ks[j*2 + 0]+ ks[j*2 + 1] * f.exp(x, powers[j]))
state_after_eval = all_even_eval[pos]
for j in range(TRACE_SIZE):
state_after_eval = f.add(state_after_eval, f.mul(mds_eval[j][pos], f.exp(p_mod_vals[j][pos_ind], 3)))
state_before_eval = 0
for j in range(TRACE_SIZE):
subbed = f.sub(p_mod_vals[j][pos_ind + TRACE_SIZE], odd_consts_mod_eval[j][pos])
state_before_eval = f.add(state_before_eval, f.mul(inv_mds_eval[j][pos], subbed))
state_before_eval = f.exp(state_before_eval, 3)
#Validate the constraints:
const_ind = 0
const_type_ind = 0
for state_ind in range(STATE_SIZE, TRACE_SIZE):
filler_state = f.sub(f.exp(G2, skips3 * (pos - state_ind*extension_factor) % precision), 1)
if not c_vals[const_ind] == f.div(p_vals[pos_ind], filler_state):
print(f"Failed in Constraints {const_type_ind}")
return False
const_ind += 1
const_type_ind += 1
for state_ind in range(8, STATE_SIZE):
batch_ind0 = f.sub(f.exp(G2, skips2*(pos - 0 * TRACE_SIZE * extension_factor - state_ind*extension_factor) % precision), 1)
if not c_vals[const_ind] == f.div(p_vals[pos_ind], batch_ind0):
print(f"Failed in Constraints {const_type_ind}")
return False
const_ind += 1
const_type_ind += 1
for state_ind in range(0, STATE_SIZE):
batch_ind0 = f.sub(f.exp(G2, skips2*(pos - 0 * TRACE_SIZE * extension_factor - state_ind*extension_factor) % precision), 1)
if not c_vals[const_ind] == f.div(f.sub(f.add(p_vals[pos_ind], all_even_eval[pos]), state_before_eval), batch_ind0):
print(f"Failed in Constraints {const_type_ind}")
return False
const_ind += 1
const_type_ind += 1
for state_ind in range(0, 4):
batch_ind0 = f.sub(f.exp(G2, skips2*(pos - 0 * TRACE_SIZE * extension_factor - state_ind*extension_factor) % precision), 1)
batch_ind30 = f.sub(f.exp(G2, skips2*(pos - 30 * TRACE_SIZE * extension_factor - state_ind*extension_factor) % precision), 1)
batch_ind31 = f.sub(f.exp(G2, skips2*(pos - 31 * TRACE_SIZE * extension_factor - state_ind*extension_factor) % precision), 1)
all_batches = f.mul(f.mul(batch_ind0, batch_ind30),batch_ind31)
filler_state = f.sub(f.exp(G2, skips3 * (pos - state_ind*extension_factor) % precision), 1)
if not c_vals[const_ind] == f.div(f.mul(f.sub(state_after_eval, state_before_eval), all_batches), filler_state):
print(f"Failed in Constraints {const_type_ind}")
return False
const_ind += 1
const_type_ind += 1
for state_ind in range(4, STATE_SIZE):
batch_ind0 = f.sub(f.exp(G2, skips2*(pos - 0 * TRACE_SIZE * extension_factor - state_ind*extension_factor) % precision), 1)
batch_ind10 = f.sub(f.exp(G2, skips2*(pos - 10 * TRACE_SIZE * extension_factor - state_ind*extension_factor) % precision), 1)
batch_ind20 = f.sub(f.exp(G2, skips2*(pos - 20 * TRACE_SIZE * extension_factor - state_ind*extension_factor) % precision), 1)
batch_ind30 = f.sub(f.exp(G2, skips2*(pos - 30 * TRACE_SIZE * extension_factor - state_ind*extension_factor) % precision), 1)
batch_ind31 = f.sub(f.exp(G2, skips2*(pos - 31 * TRACE_SIZE * extension_factor - state_ind*extension_factor) % precision), 1)
all_batches = f.mul(f.mul(f.mul(f.mul(batch_ind0, batch_ind10), batch_ind20), batch_ind30),batch_ind31)
filler_state = f.sub(f.exp(G2, skips3 * (pos - state_ind*extension_factor) % precision), 1)
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | true |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/Intent/2021/crypto/SANSA/STARK/utils.py | ctfs/Intent/2021/crypto/SANSA/STARK/utils.py | from .merkle_tree import blake
# Get the set of powers of R, until but not including when the powers
# loop back to 1
def get_power_cycle(r, modulus):
o = [1, r]
while o[-1] != 1:
o.append((o[-1] * r) % modulus)
return o[:-1]
# Extract pseudorandom indices from entropy
def get_pseudorandom_indices(seed, modulus, count, exclude_multiples_of=0):
assert modulus < 2**24
data = seed
while len(data) < 4 * count:
data += blake(data[-32:])
if exclude_multiples_of == 0:
return [int.from_bytes(data[i: i+4], 'big') % modulus for i in range(0, count * 4, 4)]
else:
real_modulus = modulus * (exclude_multiples_of - 1) // exclude_multiples_of
o = [int.from_bytes(data[i: i+4], 'big') % real_modulus for i in range(0, count * 4, 4)]
return [x+1+x//(exclude_multiples_of-1) for x in o]
def is_a_power_of_2(x):
return True if x==1 else False if x%2 else is_a_power_of_2(x//2) | python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/Intent/2021/crypto/SANSA/STARK/__init__.py | ctfs/Intent/2021/crypto/SANSA/STARK/__init__.py | python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false | |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/Intent/2021/crypto/SANSA/STARK/poly_utils.py | ctfs/Intent/2021/crypto/SANSA/STARK/poly_utils.py | # Creates an object that includes convenience operations for numbers
# and polynomials in some prime field
class PrimeField():
def __init__(self, modulus):
assert pow(2, modulus, modulus) == 2
self.modulus = modulus
def add(self, x, y):
return (x+y) % self.modulus
def sub(self, x, y):
return (x-y) % self.modulus
def mul(self, x, y):
return (x*y) % self.modulus
def exp(self, x, p):
return pow(x, p, self.modulus)
# Modular inverse using the extended Euclidean algorithm
def inv(self, a):
if a == 0:
return 0
lm, hm = 1, 0
low, high = a % self.modulus, self.modulus
while low > 1:
r = high//low
nm, new = hm-lm*r, high-low*r
lm, low, hm, high = nm, new, lm, low
return lm % self.modulus
def multi_inv(self, values):
partials = [1]
for i in range(len(values)):
partials.append(self.mul(partials[-1], values[i] or 1))
inv = self.inv(partials[-1])
outputs = [0] * len(values)
for i in range(len(values), 0, -1):
outputs[i-1] = self.mul(partials[i-1], inv) if values[i-1] else 0
inv = self.mul(inv, values[i-1] or 1)
return outputs
def div(self, x, y):
return self.mul(x, self.inv(y))
# Evaluate a polynomial at a point
def eval_poly_at(self, p, x):
y = 0
power_of_x = 1
for i, p_coeff in enumerate(p):
y += power_of_x * p_coeff
power_of_x = (power_of_x * x) % self.modulus
return y % self.modulus
# Arithmetic for polynomials
def add_polys(self, a, b):
return [((a[i] if i < len(a) else 0) + (b[i] if i < len(b) else 0))
% self.modulus for i in range(max(len(a), len(b)))]
def sub_polys(self, a, b):
return [((a[i] if i < len(a) else 0) - (b[i] if i < len(b) else 0))
% self.modulus for i in range(max(len(a), len(b)))]
def mul_by_const(self, a, c):
return [(x*c) % self.modulus for x in a]
def mul_polys(self, a, b):
o = [0] * (len(a) + len(b) - 1)
for i, aval in enumerate(a):
for j, bval in enumerate(b):
o[i+j] += a[i] * b[j]
return [x % self.modulus for x in o]
def div_polys(self, a, b):
assert len(a) >= len(b)
a = [x for x in a]
o = []
apos = len(a) - 1
bpos = len(b) - 1
diff = apos - bpos
while diff >= 0:
quot = self.div(a[apos], b[bpos])
o.insert(0, quot)
for i in range(bpos, -1, -1):
a[diff+i] -= b[i] * quot
apos -= 1
diff -= 1
return [x % self.modulus for x in o]
def mod_polys(self, a, b):
return self.sub_polys(a, self.mul_polys(b, self.div_polys(a, b)))[:len(b)-1]
# Build a polynomial from a few coefficients
def sparse(self, coeff_dict):
o = [0] * (max(coeff_dict.keys()) + 1)
for k, v in coeff_dict.items():
o[k] = v % self.modulus
return o
# Build a polynomial that returns 0 at all specified xs
def zpoly(self, xs):
root = [1]
for x in xs:
root.insert(0, 0)
for j in range(len(root)-1):
root[j] -= root[j+1] * x
return [x % self.modulus for x in root]
# Given p+1 y values and x values with no errors, recovers the original
# p+1 degree polynomial.
# Lagrange interpolation works roughly in the following way.
# 1. Suppose you have a set of points, eg. x = [1, 2, 3], y = [2, 5, 10]
# 2. For each x, generate a polynomial which equals its corresponding
# y coordinate at that point and 0 at all other points provided.
# 3. Add these polynomials together.
def lagrange_interp(self, xs, ys):
# Generate master numerator polynomial, eg. (x - x1) * (x - x2) * ... * (x - xn)
root = self.zpoly(xs)
assert len(root) == len(ys) + 1
# print(root)
# Generate per-value numerator polynomials, eg. for x=x2,
# (x - x1) * (x - x3) * ... * (x - xn), by dividing the master
# polynomial back by each x coordinate
nums = [self.div_polys(root, [-x, 1]) for x in xs]
# Generate denominators by evaluating numerator polys at each x
denoms = [self.eval_poly_at(nums[i], xs[i]) for i in range(len(xs))]
invdenoms = self.multi_inv(denoms)
# Generate output polynomial, which is the sum of the per-value numerator
# polynomials rescaled to have the right y values
b = [0 for y in ys]
for i in range(len(xs)):
yslice = self.mul(ys[i], invdenoms[i])
for j in range(len(ys)):
if nums[i][j] and ys[i]:
b[j] += nums[i][j] * yslice
return [x % self.modulus for x in b]
# Optimized poly evaluation for degree 4
def eval_quartic(self, p, x):
xsq = x * x % self.modulus
xcb = xsq * x
return (p[0] + p[1] * x + p[2] * xsq + p[3] * xcb) % self.modulus
# Optimized version of the above restricted to deg-4 polynomials
def lagrange_interp_4(self, xs, ys):
x01, x02, x03, x12, x13, x23 = \
xs[0] * xs[1], xs[0] * xs[2], xs[0] * xs[3], xs[1] * xs[2], xs[1] * xs[3], xs[2] * xs[3]
m = self.modulus
eq0 = [-x12 * xs[3] % m, (x12 + x13 + x23), -xs[1]-xs[2]-xs[3], 1]
eq1 = [-x02 * xs[3] % m, (x02 + x03 + x23), -xs[0]-xs[2]-xs[3], 1]
eq2 = [-x01 * xs[3] % m, (x01 + x03 + x13), -xs[0]-xs[1]-xs[3], 1]
eq3 = [-x01 * xs[2] % m, (x01 + x02 + x12), -xs[0]-xs[1]-xs[2], 1]
e0 = self.eval_poly_at(eq0, xs[0])
e1 = self.eval_poly_at(eq1, xs[1])
e2 = self.eval_poly_at(eq2, xs[2])
e3 = self.eval_poly_at(eq3, xs[3])
e01 = e0 * e1
e23 = e2 * e3
invall = self.inv(e01 * e23)
inv_y0 = ys[0] * invall * e1 * e23 % m
inv_y1 = ys[1] * invall * e0 * e23 % m
inv_y2 = ys[2] * invall * e01 * e3 % m
inv_y3 = ys[3] * invall * e01 * e2 % m
return [(eq0[i] * inv_y0 + eq1[i] * inv_y1 + eq2[i] * inv_y2 + eq3[i] * inv_y3) % m for i in range(4)]
# Optimized version of the above restricted to deg-2 polynomials
def lagrange_interp_2(self, xs, ys):
m = self.modulus
eq0 = [-xs[1] % m, 1]
eq1 = [-xs[0] % m, 1]
e0 = self.eval_poly_at(eq0, xs[0])
e1 = self.eval_poly_at(eq1, xs[1])
invall = self.inv(e0 * e1)
inv_y0 = ys[0] * invall * e1
inv_y1 = ys[1] * invall * e0
return [(eq0[i] * inv_y0 + eq1[i] * inv_y1) % m for i in range(2)]
# Optimized version of the above restricted to deg-4 polynomials
def multi_interp_4(self, xsets, ysets):
data = []
invtargets = []
m = self.modulus
for xs, ys in zip(xsets, ysets):
x01, x02, x03, x12, x13, x23 = \
xs[0] * xs[1], xs[0] * xs[2], xs[0] * xs[3], xs[1] * xs[2], xs[1] * xs[3], xs[2] * xs[3]
eq0 = [-x12 * xs[3] % m, (x12 + x13 + x23), -xs[1]-xs[2]-xs[3], 1]
eq1 = [-x02 * xs[3] % m, (x02 + x03 + x23), -xs[0]-xs[2]-xs[3], 1]
eq2 = [-x01 * xs[3] % m, (x01 + x03 + x13), -xs[0]-xs[1]-xs[3], 1]
eq3 = [-x01 * xs[2] % m, (x01 + x02 + x12), -xs[0]-xs[1]-xs[2], 1]
e0 = self.eval_quartic(eq0, xs[0])
e1 = self.eval_quartic(eq1, xs[1])
e2 = self.eval_quartic(eq2, xs[2])
e3 = self.eval_quartic(eq3, xs[3])
data.append([ys, eq0, eq1, eq2, eq3])
invtargets.extend([e0, e1, e2, e3])
invalls = self.multi_inv(invtargets)
o = []
for (i, (ys, eq0, eq1, eq2, eq3)) in enumerate(data):
invallz = invalls[i*4:i*4+4]
inv_y0 = ys[0] * invallz[0] % m
inv_y1 = ys[1] * invallz[1] % m
inv_y2 = ys[2] * invallz[2] % m
inv_y3 = ys[3] * invallz[3] % m
o.append([(eq0[i] * inv_y0 + eq1[i] * inv_y1 + eq2[i] * inv_y2 + eq3[i] * inv_y3) % m for i in range(4)])
# assert o == [self.lagrange_interp_4(xs, ys) for xs, ys in zip(xsets, ysets)]
return o | python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/Intent/2021/crypto/SANSA/STARK/merkle_tree.py | ctfs/Intent/2021/crypto/SANSA/STARK/merkle_tree.py | from hashlib import blake2s
blake = lambda x: blake2s(x).digest()
def merkelize(L):
# L = permute4(L)
nodes = [b''] * len(L) + [x.to_bytes(32, 'big') if isinstance(x, int) else x for x in L]
for i in range(len(L) - 1, 0, -1):
nodes[i] = blake(nodes[i*2] + nodes[i*2+1])
return nodes
def mk_branch(tree, index):
# index = get_index_in_permuted(index, len(tree) // 2)
index += len(tree) // 2
o = [tree[index]]
while index > 1:
o.append(tree[index ^ 1])
index //= 2
return o
def verify_branch(root, index, proof, output_as_int=False):
# index = get_index_in_permuted(index, 2**len(proof) // 2)
index += 2**len(proof)
v = proof[0]
for p in proof[1:]:
if index % 2:
v = blake(p + v)
else:
v = blake(v + p)
index //= 2
assert v == root
return int.from_bytes(proof[0], 'big') if output_as_int else proof[0]
# Make a compressed proof for multiple indices
def mk_multi_branch(tree, indices):
# Branches we are outputting
output = []
# Elements in the tree we can get from the branches themselves
calculable_indices = {}
for i in indices:
new_branch = mk_branch(tree, i)
index = len(tree) // 2 + i
calculable_indices[index] = True
for j in range(1, len(new_branch)):
calculable_indices[index ^ 1] = True
index //= 2
output.append(new_branch)
# Fill in the calculable list: if we can get or calculate both children, we can calculate the parent
complete = False
while not complete:
complete = True
keys = sorted([x//2 for x in calculable_indices])[::-1]
for k in keys:
if k*2 in calculable_indices and (k*2)+1 in calculable_indices and k not in calculable_indices:
calculable_indices[k] = True
complete = False
# If for any branch node both children are calculable, or the node overlaps with a leaf, or the node
# overlaps with a previously calculated one, elide it
scanned = {}
for i, b in zip(indices, output):
index = len(tree) // 2 + i
scanned[index] = True
for j in range(1, len(b)):
if ((index^1)*2 in calculable_indices and (index^1)*2+1 in calculable_indices) or ((index^1)-len(tree)//2 in indices) or (index^1) in scanned:
b[j] = b''
scanned[index^1] = True
index //= 2
return output
# Verify a compressed proof
def verify_multi_branch(root, indices, proof):
# The values in the Merkle tree we can fill in
partial_tree = {}
# Fill in elements from the branches
for i, b in zip(indices, proof):
half_tree_size = 2**(len(b) - 1)
index = half_tree_size+i
partial_tree[index] = b[0]
for j in range(1, len(b)):
if b[j]:
partial_tree[index ^ 1] = b[j]
index //= 2
# If we can calculate or get both children, we can calculate the parent
complete = False
while not complete:
complete = True
keys = sorted([x//2 for x in partial_tree])[::-1]
for k in keys:
if k*2 in partial_tree and k*2+1 in partial_tree and k not in partial_tree:
partial_tree[k] = blake(partial_tree[k*2] + partial_tree[k*2+1])
complete = False
# If any branch node is missing, we can calculate it
for i, b in zip(indices, proof):
index = half_tree_size + i
for j in range(1, len(b)):
if b[j] == b'':
b[j] = partial_tree[index ^ 1]
partial_tree[index^1] = b[j]
index //= 2
# Verify the branches and output the values
return [verify_branch(root, i, b) for i,b in zip(indices, proof)]
# Byte length of a multi proof
def bin_length(proof):
return sum([len(b''.join(x)) + len(x) // 8 for x in proof]) + len(proof) * 2 | python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/Intent/2021/crypto/SANSA/STARK/fft.py | ctfs/Intent/2021/crypto/SANSA/STARK/fft.py | def _simple_ft(vals, modulus, roots_of_unity):
L = len(roots_of_unity)
o = []
for i in range(L):
last = 0
for j in range(L):
last += vals[j] * roots_of_unity[(i*j)%L]
o.append(last % modulus)
return o
def _fft(vals, modulus, roots_of_unity):
if len(vals) <= 4:
#return vals
return _simple_ft(vals, modulus, roots_of_unity)
L = _fft(vals[::2], modulus, roots_of_unity[::2])
R = _fft(vals[1::2], modulus, roots_of_unity[::2])
o = [0 for i in vals]
for i, (x, y) in enumerate(zip(L, R)):
y_times_root = y*roots_of_unity[i]
o[i] = (x+y_times_root) % modulus
o[i+len(L)] = (x-y_times_root) % modulus
return o
def expand_root_of_unity(root_of_unity, modulus):
# Build up roots of unity
rootz = [1, root_of_unity]
while rootz[-1] != 1:
rootz.append((rootz[-1] * root_of_unity) % modulus)
return rootz
def fft(vals, modulus, root_of_unity, inv=False):
rootz = expand_root_of_unity(root_of_unity, modulus)
# Fill in vals with zeroes if needed
if len(rootz) > len(vals) + 1:
vals = vals + [0] * (len(rootz) - len(vals) - 1)
if inv:
# Inverse FFT
invlen = pow(len(vals), modulus-2, modulus)
return [(x*invlen) % modulus for x in
_fft(vals, modulus, rootz[:0:-1])]
else:
# Regular FFT
return _fft(vals, modulus, rootz[:-1])
# Evaluates f(x) for f in evaluation form
def inv_fft_at_point(vals, modulus, root_of_unity, x):
if len(vals) == 1:
return vals[0]
# 1/2 in the field
half = (modulus + 1)//2
# 1/w
inv_root = pow(root_of_unity, len(vals)-1, modulus)
# f(-x) in evaluation form
f_of_minus_x_vals = vals[len(vals)//2:] + vals[:len(vals)//2]
# e(x) = (f(x) + f(-x)) / 2 in evaluation form
evens = [(f+g) * half % modulus for f,g in zip(vals, f_of_minus_x_vals)]
# o(x) = (f(x) - f(-x)) / 2 in evaluation form
odds = [(f-g) * half % modulus for f,g in zip(vals, f_of_minus_x_vals)]
# e(x^2) + coordinate * x * o(x^2) in evaluation form
comb = [(o * x * inv_root**i + e) % modulus for i, (o, e) in enumerate(zip(odds, evens))]
return inv_fft_at_point(comb[:len(comb)//2], modulus, root_of_unity ** 2 % modulus, x**2 % modulus)
def shift_domain(vals, modulus, root_of_unity, factor):
if len(vals) == 1:
return vals
# 1/2 in the field
half = (modulus + 1)//2
# 1/w
inv_factor = pow(factor, modulus - 2, modulus)
half_length = len(vals)//2
# f(-x) in evaluation form
f_of_minus_x_vals = vals[half_length:] + vals[:half_length]
# e(x) = (f(x) + f(-x)) / 2 in evaluation form
evens = [(f+g) * half % modulus for f,g in zip(vals, f_of_minus_x_vals)]
print('e', evens)
# o(x) = (f(x) - f(-x)) / 2 in evaluation form
odds = [(f-g) * half % modulus for f,g in zip(vals, f_of_minus_x_vals)]
print('o', odds)
shifted_evens = shift_domain(evens[:half_length], modulus, root_of_unity ** 2 % modulus, factor ** 2 % modulus)
print('se', shifted_evens)
shifted_odds = shift_domain(odds[:half_length], modulus, root_of_unity ** 2 % modulus, factor ** 2 % modulus)
print('so', shifted_odds)
return (
[(e + inv_factor * o) % modulus for e, o in zip(shifted_evens, shifted_odds)] +
[(e - inv_factor * o) % modulus for e, o in zip(shifted_evens, shifted_odds)]
)
def shift_poly(poly, modulus, factor):
factor_power = 1
inv_factor = pow(factor, modulus - 2, modulus)
o = []
for p in poly:
o.append(p * factor_power % modulus)
factor_power = factor_power * inv_factor % modulus
return o
def mul_polys(a, b, modulus, root_of_unity):
rootz = [1, root_of_unity]
while rootz[-1] != 1:
rootz.append((rootz[-1] * root_of_unity) % modulus)
if len(rootz) > len(a) + 1:
a = a + [0] * (len(rootz) - len(a) - 1)
if len(rootz) > len(b) + 1:
b = b + [0] * (len(rootz) - len(b) - 1)
x1 = _fft(a, modulus, rootz[:-1])
x2 = _fft(b, modulus, rootz[:-1])
return _fft([(v1*v2)%modulus for v1,v2 in zip(x1,x2)],
modulus, rootz[:0:-1]) | python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/Intent/2021/crypto/SANSA/STARK/rescue/rescue_hash.py | ctfs/Intent/2021/crypto/SANSA/STARK/rescue/rescue_hash.py | import numpy as np
from .rescue_constants import MDS_MATRIX, NUM_ROUNDS, PRIME, ROUND_CONSTANTS, WORD_SIZE
def pow_mod(vector: np.ndarray, exponent: int, p: int) -> np.ndarray:
"""
Returns a numpy array which, in index i, will be equal to (vector[i] ** exponent % p), where
'**' is the power operator.
"""
return np.vectorize(lambda x: pow(x, exponent, p))(vector)
def rescue_hash(
inputs, mds_matrix=MDS_MATRIX, round_constants=ROUND_CONSTANTS,
word_size=WORD_SIZE, p=PRIME, num_rounds=NUM_ROUNDS):
"""
Returns the result of the Rescue hash on the given input.
The state size is word_size * 3.
inputs is a list/np.array of size (word_size * 2)
round_constants consists of (2 * num_rounds + 1) vectors, each of the same size as state size.
mds_matrix is an MDS (Maximum Distance Separable) matrix of size (state size)x(state size).
"""
mds_matrix = np.array(mds_matrix, dtype=object) % p
round_constants = np.array(round_constants, dtype=object)[:, :, np.newaxis] % p
inputs = np.array(inputs, dtype=object).reshape(2 * word_size, 1) % p
zeros = np.zeros((word_size, 1), dtype=object)
state = np.concatenate((inputs, zeros))
#print("state:", [x[0] for x in state])
state = (state + round_constants[0]) % p
for i in range(1, 2 * num_rounds, 2):
# First half of round i/2.
#print("before first half", [x[0] for x in state])
state = pow_mod(state, (2 * p - 1) // 3, p)
state = mds_matrix.dot(state) % p
state = (state + round_constants[i]) % p
# Second half of round i/2.
#print("before second half", [x[0] for x in state])
state = pow_mod(state, 3, p)
state = mds_matrix.dot(state) % p
state = (state + round_constants[i + 1]) % p
return (state[:word_size].flatten() % p).tolist()
def rescue(input):
inp = input[:8]
ind = 8
while ind < len(input):
res = rescue_hash(inp)
inp = res + input[ind: ind + 4]
ind += 4
return rescue_hash(inp)
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/Intent/2021/crypto/SANSA/STARK/rescue/__init__.py | ctfs/Intent/2021/crypto/SANSA/STARK/rescue/__init__.py | python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false | |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/Intent/2021/crypto/SANSA/STARK/rescue/rescue_constants.py | ctfs/Intent/2021/crypto/SANSA/STARK/rescue/rescue_constants.py | # The MDS matrix used in Rescue, generated by the function generate_mds_matrix() which is located in
# rescue_constants.sage.
MDS_MATRIX = [[823338088869439231, 2117108638373820691, 2229447756518613873,
1267826118149340713, 1914040319882762128, 1517472965193791713,
1517185983240457465, 1173996590568495268, 422851619803761585,
1602586210003543191, 35735290356331136, 1478684443030049290],
[1185084594364363143, 386504857525734201, 900805054056138048,
2206086765722274276, 77358030797185120, 168814859743553085,
609019594106244118, 967259826801110417, 1245941946974910944,
331754017570996207, 1042813765834987924, 1416706138472890797],
[1644685178030218132, 84777539421936552, 211114716802537324,
1452180437296649780, 1981779992650434186, 1244315040009035360,
141834693084545970, 587855844772411290, 947501996990717579,
1160394519596317219, 1353794997748857692, 1084801327806912709],
[294000575516900023, 1038834305701615220, 2028636067677044788,
556344854738395739, 673598438439868941, 866232706825334403,
8439985508328051, 531309808133015717, 913058415036251803,
1418541144229396763, 260962125129513116, 1629568606490204964],
[1338168026761758784, 639198938790892266, 1175728442583937526,
1253161805104066097, 322912216969028600, 1265589681041505318,
1761319009648514235, 329080691196806583, 2206868075918138340,
363841372535877030, 1058835961667518417, 1378873053370828919],
[2057042464687056702, 1477921882920214288, 1811799613479311691,
692883914293934706, 1722129634696879434, 1738023165613368735,
1557039527687079106, 361948928633069941, 1838764902588232309,
1093073101857924446, 2235148041867494472, 736122639993481301],
[1703087819126335355, 695176839652737917, 935213047666097451,
112265271919339588, 732242643028035086, 1068706827223187857,
2025842508514124257, 893511342449768918, 444847765696352207,
133898360419762315, 1251377835122996224, 402098614266030486],
[1098942770164522421, 2094292053893791057, 1502787197562159741,
1506874785637887678, 1806798579414918424, 454975914767324193,
1414323121744038944, 1012955095007255065, 861851233384124269,
2077817807364448578, 1772311895174947970, 1149025038050060293],
[815640283800696837, 910813018030261660, 1678340892848250907,
1739246628486150295, 392018795657995396, 175248342069728052,
1623271890288900249, 1102183448493964872, 689450485525198961,
961174862671750376, 1153405115385730434, 783761602692458549],
[611048852495693121, 407835610147611058, 1413610481177231988,
1597579600935506441, 1818379701514592062, 415649361088711773,
1849052475707052634, 1240815129692687473, 1428195511403744241,
1532291835431068707, 723086321983531860, 962876074383023221],
[634881164868706703, 1727184416336696360, 207049339081848952,
278975366067907545, 1120181182190432182, 18233512741727800,
265294688458162921, 874129395388464351, 1578938804158614352,
2212191138094533493, 2294115954950092712, 1860899752959121220],
[1172680933710958004, 1130453267765242573, 339548184768822637,
2304496873779114990, 102144016531266329, 1193667180704190946,
1408113390435388199, 717197251166574721, 1815513230372816916,
341598652663476560, 830720924367081080, 1053020951839477025]]
INV_MDS_MATRIX = [[1276136404767274105, (1542954871449298201),(2299068283759097430),(404853310344982221),
(1786565524538336517),
(896867597939293503),
(1971739626568873699),
(528896295377250076),
(184014694692122096),
(1106646164544035711),
(552427400184096601),
(1806224779849020773),
],
[
(1539408794601174416),
(138948501429602896),
(41010364350894355),
(280794287708347151),
(985509337584959998),
(940798162762446320),
(347982822312563046),
(1427156967496478784),
(1651479079530725465),
(673768486617092508),
(1271501854677669412),
(164894602158622635),
],
[
(705260741927665589),
(571645905974736832),
(1143988689015673776),
(1867306197911741254),
(1166532828140593845),
(1720611288621635400),
(618231561063869898),
(1377690466838998031),
(1731670042674952999),
(1974507124319721175),
(1105915583331783113),
(1391900616272166050),
],
[
(1127566350061446719),
(220426544920911058),
(1182050517713646250),
(2216226340648429492),
(565020541341622690),
(1312172643486204442),
(281066280262788917),
(1135731035497095975),
(1093206821519790360),
(615964150416133804),
(1105101355771180035),
(990905784625028126),
],
[
(1218585597071791612),
(1169302767842455950),
(1195183214386914001),
(2067279124388748180),
(2271061485416900593),
(299781398557914644),
(1183271189019536608),
(991754589982134451),
(1179031748105208445),
(1195069077509678286),
(2185384919087577911),
(1056390367653299192),
],
[
(1956314984219210143),
(752678681503811642),
(2213705442920057493),
(1982187525505471684),
(51395396168416913),
(976936990326380927),
(374353516971744832),
(2272444445913305511),
(1647352703331663867),
(376181718611165876),
(642951261169313171),
(1659026389595013947),
],
[
(235000879735942816),
(1646405634224863063),
(218443667085897627),
(1885386055565028287),
(170662272521234137),
(2120793149379302751),
(869956144731445265),
(2119944435613864210),
(2095632803816823095),
(2164052175963081950),
(1615236191464521375),
(1415446723361522115),
],
[
(504070108328726551),
(727824617651704299),
(1766144176568576808),
(1958026709832452867),
(1611976463745995328),
(452589068412269705),
(702814653590877108),
(760044529253515839),
(1799510921921923238),
(1156085546658757752),
(1836863202651989897),
(580114224573381874),
],
[
(1780499450529004292),
(1863373705261259405),
(926712177903193650),
(764353538039324119),
(1219324803395655080),
(1636647015892378145),
(1395362143357703118),
(1057265994455655488),
(665014636679184489),
(465232312736969629),
(1028493342089805696),
(2246179580581698968),
],
[
(1864023788980957913),
(824115422831878254),
(49747283878086277),
(698393763370877610),
(1669091048421338280),
(2183070563450407500),
(934334071574168537),
(992884359353711530),
(274785091585525229),
(370839196680912466),
(447246467719497575),
(137069407546894437),
],
[
(1109858166964028488),
(1600387265138675246),
(712084546618162345),
(2294293402358704608),
(1890454462789993500),
(508341103713194581),
(354325802634164641),
(293614218776850123),
(2083819601163761237),
(469272455874052999),
(977821056322177942),
(449206228425357891),
],
[
(2193102094952964155),
(868099100895799078),
(1959230992075386668),
(2054940601917590237),
(127910955913287033),
(82614338666938137),
(1581000249116109692),
(1818005273896915691),
(924632754590293985),
(613146855352145874),
(1486517957808363758),
(1755627503496737095),
],
]
# Const vectors used in Rescue, generated by the function generate_marvellous_round_constants()
# which is located in rescue_constants.sage.
ROUND_CONSTANTS = [[2042818120891737159, 1251281670991585583, 87735185202960209,
2239947377130062957, 1202333810816364401, 1162846502830521269,
623506559418885740, 983132627954367464, 1692585507853367924,
614434911971959133, 1475208038133342681, 1679827746384315454],
[747537749585950820, 281243186875312044, 577778549251741988,
930733653279957976, 601036810767521071, 844997634310431678,
535625794500683031, 387792557346100131, 2290807885147290051,
412710737781166849, 698021613999022168, 2011187931735891298],
[493937490574304097, 1281480994870021098, 2259490076968797675,
1235930869844471537, 1298179147529217314, 1653777939234648915,
1076776212042405112, 1846317782146915287, 1943236668281632557,
372142997247419599, 710165010137978345, 218537828684534192],
[520609803532189995, 707898450210178991, 847978691682020271,
1334285484100308642, 1407379196672604628, 2161367985954999845,
86755235034489424, 1630065556428161079, 716722026371742101,
1263049714368577205, 1117518665566820522, 950174000589711385],
[198517426672277682, 86695144645827371, 2187548543249998775,
922142624336596840, 1752242016771886790, 2304678542276059055,
600389121639559558, 374181594632348730, 340307195727706273,
716218400946171534, 138094832090652684, 690843318036757995],
[193511554562434645, 1347516947337253242, 221546067322565025,
489148271399341556, 1433314196554393111, 21973403424522711,
487881858917079384, 93488507358721690, 615974275608639070,
1884317404581534724, 1279579857348096203, 1725479157980007481],
[1206414713016571596, 1272929673568255340, 1215778875376871174,
796711930395126786, 320849871674784758, 1258276448999113920,
446372573493581620, 2190288547065790170, 2054643653445292478,
2238591918157558551, 1980008705377633232, 1839661662117695692],
[278407696580824381, 125776442012429146, 315557857274936530,
2091587670997900419, 1089830490551268650, 1144843865766276138,
1372108008260706030, 1998888828914333416, 1536346384010279125,
692208840987320273, 1975020094131349442, 1426718347923665415],
[1959546819596601413, 1499770558289184118, 160360799112268413,
808735650660468096, 1444854056222378048, 2227478673566160814,
1794393697991644654, 1910916815467673227, 1781803434280447429,
381837820710577140, 1168027492599875599, 484196283848702206],
[1752116853587453696, 1278899684774745491, 1560087107270113257,
1186434072897280021, 1911808996736941706, 373821226799726998,
1006081993496229961, 1432462461735230475, 646240400389472231,
742219888259870808, 1622801466246986223, 21753060634846415],
[1498921976510789728, 851729105126672762, 1560964754908825059,
1256398552198827905, 1657027511916227971, 1606959451746934965,
479421438058659938, 1868108429218566031, 1458733866439678339,
1993098699435787743, 1419662103870913692, 153876999007760884],
[908681488047354322, 1059648683476947663, 1422298696872448116,
796258829872076259, 2000011051100278251, 2126799898235151598,
1142806555394880963, 87167887627879201, 1764967010086677148,
2287906206318134809, 1096147872006094440, 327418705403835827],
[538002031346175307, 954643699263118063, 231381803649991513,
663192079795165472, 2052785578538651955, 1721402442157477925,
1170602796480668123, 609215085111019548, 113782509706051502,
1716861710896364704, 116919897596734456, 1343001087851755513],
[2108352352321337234, 2227804721703603316, 1775288589300214998,
980962507104284863, 178660157568212885, 859919812738625071,
2156893786645445400, 78968556671150056, 387686852242622737,
45037490438723424, 1304951229653950874, 285866640459851966],
[162855497825821715, 523015450590782059, 825807589241238118,
233052756044923835, 2174416936012547239, 1136523934428914167,
2297465697057698646, 836519015094728779, 669068558290948602,
979819749607976822, 1406688303361863979, 126596842750082386],
[1234962960995210246, 855883590780627034, 2145878408265271523,
1032518865840032202, 420058468927174885, 996269423857214312,
33228897344264057, 865159915081398990, 3817962206233155,
983529707461844057, 575124192072844629, 727705461310098765],
[1522124062684018341, 1965166303063462651, 1691333373858847010,
471239528822870101, 1472204230630832684, 2295140230758830623,
223993327430719953, 1048764872114546433, 289614844801844810,
1078799541847222477, 1779782174543016555, 487523037435046127],
[172981144895510015, 1238497101916441175, 498613150496703853,
878170907867777677, 2266860576851213993, 1412791579505025663,
1437515572647265884, 1741475713399184521, 330061347949363822,
477925221841207735, 2263763058137952322, 1619947233610158726],
[940724378607303967, 1181269157980671174, 188339616924359284,
1299637427989459156, 585261879838086507, 1174457836833591758,
1942762107882876289, 103333255791005935, 1005015829648581780,
1636159002087098512, 463457549802674229, 1617813204793984351],
[1973128493244667159, 714582191075944714, 1014965583137013174,
556181343124801510, 1303640756115560327, 1882603328598651335,
1975394374759354209, 756422884954475762, 767121195914306160,
349191896186480870, 2294018818388081028, 2140594108859825781],
[1726786311817636675, 1990508092581003274, 389997650067319062,
1593873652210973012, 650758433296124269, 136349023515684250,
1132243506236411862, 1262936684747966538, 834693119115512475,
1326961047368845805, 76749345156462865, 410458115535409705]]
# The characteristic of the prime field used in Rescue.
PRIME = 2**61 + 20 * 2**32 + 1
# The word size used in Rescue.
WORD_SIZE = 4
# The number of rounds used in Rescue.
NUM_ROUNDS = 10
STATE_SIZE = 12 | python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/Intent/2021/crypto/SANSA/STARK/rescue/rescue_hash_test.py | ctfs/Intent/2021/crypto/SANSA/STARK/rescue/rescue_hash_test.py | from .rescue_hash import rescue_hash
def test_rescue_hash():
# The list of constants being compared to the result of rescue_hash was generated by performing
# the hash on [1, 2, 3, 4, 5, 6, 7, 8] with the marvellous_hash function given in
# https://starkware.co/hash-challenge-implementation-reference-code/#marvellous.
assert rescue_hash([1, 2, 3, 4, 5, 6, 7, 8]) == \
[1701009513277077950, 394821372906024995,
428352609193758013, 1822402221604548281] | python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/Hackappatoi/2023/misc/Poetry_contest/buildd.py | ctfs/Hackappatoi/2023/misc/Poetry_contest/buildd.py | import os
def banner():
pacciani = """\tSe ni’ mondo esistesse un po’ di bene
e ognun si considerasse suo fratello,
ci sarebbe meno pensieri e meno pene
e il mondo ne sarebbe assai più bello."""
eng = """\tIf only a little good existed in the world\t
and each considered himself the other's brother\t
there would be fewer painful thoughts and fewer pains
and the world would be much more beautiful\t"""
pacciani_lines = pacciani.splitlines()
eng_lines = eng.splitlines()
print("-"*145)
for line_pacciani, line_eng in zip(pacciani_lines, eng_lines):
print(f"|{line_pacciani.ljust(60)}|{line_eng}\t\t\t|")
print("-"*145+"\n")
def main():
file = "exploit.js"
xpl = ""
inp = input(">>> ")
while inp!= "END":
xpl += inp + "\n"
inp = input(">>> ")
with open(file, "w") as f:
f.write(xpl)
os.system("./mjs exploit.js")
if __name__ == "__main__":
banner()
main()
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/Hackappatoi/2022/web/BeerFast/run.py | ctfs/Hackappatoi/2022/web/BeerFast/run.py | import app
from app.bot import run_bot
if __name__ == "__main__":
application, admin_usr, admin_pwd = app.create_app(__name__, config=None)
run_bot(admin_usr, admin_pwd)
application.run(host="0.0.0.0", port=8000, debug=False)
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/Hackappatoi/2022/web/BeerFast/miniserver.py | ctfs/Hackappatoi/2022/web/BeerFast/miniserver.py | from flask import Flask
import secrets
import sys
import os
app = Flask(__name__)
@app.route('/')
def index():
raise Exception('test')
if __name__ == '__main__':
# generate stronger pin
if "WERKZEUG_DEBUG_PIN" not in os.environ:
rand_pin = 100000000000000 + secrets.randbelow(999999999999999)
rand_pin = "-".join([str(rand_pin)[i:i + 3] for i in range(0, len(str(rand_pin)), 3)])
os.environ["WERKZEUG_DEBUG_PIN"] = rand_pin
app.run(host="0.0.0.0", port=int(sys.argv[1]), debug=True)
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/Hackappatoi/2022/web/BeerFast/app/helper.py | ctfs/Hackappatoi/2022/web/BeerFast/app/helper.py | from datetime import datetime
import time
import os
import secrets
from .models import User
from .globals import Database
from .models import LoginLog
from threading import Thread
import socket
import logging
import subprocess
class LoginHelper:
usr = None
def _constant_time_compare(self, s1, s2):
val = 0
for i in range(0, len(s1)):
val |= ord(s1[i]) ^ ord(s2[i % len(s2)])
return val == 0
def check_user(self, user, password, ip=None):
log = logging.getLogger("LoginHelper.check_user")
log.debug("Checking user %s", user)
if user != "" and password != "":
self.usr = User.query.filter_by(username=user).first()
if self.usr is not None:
# This is a secure feature, basically to prevent timing attacks, basically it will
# take always the same amount of time to check the password
# this way an attacker can't know if the password is correct or not
# by checking the time it takes to check the password
# wikipedia: https://en.wikipedia.org/wiki/Timing_attack
if self.usr.level > 1:
log.info("[ADMIN_AUTH] [%s] - Trying authentication for user %s", user,
time.strftime("%Y-%m-%d %H:%M:%S"))
usr = self.usr
self.usr = None
ret = self._constant_time_compare(usr.password, usr.hash_password(password)), usr
if ret[0]:
# Log accesses for admins
rec = LoginLog(user, ip, datetime.utcnow(), True)
Database.session.add(rec)
Database.session.commit()
return ret
else:
log.info("[USER_AUTH] [%s] - Trying authentication for user %s", user,
time.strftime("%Y-%m-%d %H:%M:%S"))
ret = self._constant_time_compare(self.usr.password, self.usr.hash_password(password)), self.usr
self.usr = None
return ret
self.usr = None
return False
class ServerHelper:
def stop_miniserver(self, proc):
time.sleep(600)
# kill process
proc.kill()
def start_miniserver(self):
global ServerPID, ServerPort
if ServerPID != 0:
# check if process is still running
try:
os.kill(ServerPID, 0)
except OSError:
# process is dead
ServerPID = 0
else:
# process is alive
return ServerPID, ServerPort, None
# get free port
# start miniserver
port = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
port.bind(("", 0))
port.listen(1)
free = port.getsockname()[1]
port.close()
# start miniserver
# spawn process and get pid
# save pid and port in db
# return pid and port
try:
# redirect stdout and stderr to /dev/null
proc = subprocess.Popen(["python3", "miniserver.py", str(free)])
thread = Thread(target=self.stop_miniserver, args=(proc,))
thread.daemon = True
thread.start()
ServerPID = proc.pid
ServerPort = free
return proc.pid, free, None
except Exception as e:
return None, None, e
ServerPort = 0
ServerPID = 0
Manager = LoginHelper()
ServerManager = ServerHelper()
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/Hackappatoi/2022/web/BeerFast/app/models.py | ctfs/Hackappatoi/2022/web/BeerFast/app/models.py | from flask_login import UserMixin
from . import globals
class User(globals.Database.Model, UserMixin):
id = globals.Database.Column(globals.Database.Integer, primary_key=True)
username = globals.Database.Column(globals.Database.String(64), nullable=False)
password = globals.Database.Column(globals.Database.String(32), nullable=False)
level = globals.Database.Column(globals.Database.Integer, nullable=False)
def __init__(self, username, password, level=1):
self.username = username
self.level = level
self.password = self.hash_password(password)
def hash_password(self, pwd):
k = globals.App.config["SECRET_KEY"]
pwd = bytearray(pwd, encoding='latin1')
for i in range(0, len(pwd)):
pwd[i] ^= ord(k[(i + self.level) % len(k)])
return pwd.hex()
@property
def is_admin(self):
return self.level == 10
@property
def is_moderator(self):
return self.level == 8
@property
def is_user(self):
return self.level == 1
@property
def is_active(self):
return True
@property
def is_anonymous(self):
return False
def get_id(self):
return str(self.id)
def __repr__(self):
return '<User %r>' % self.username
class LoginLog(globals.Database.Model):
id = globals.Database.Column(globals.Database.Integer, primary_key=True)
username = globals.Database.Column(globals.Database.String(64), nullable=False)
ip = globals.Database.Column(globals.Database.String(64), nullable=False)
time = globals.Database.Column(globals.Database.DateTime, nullable=False)
success = globals.Database.Column(globals.Database.Boolean, nullable=False)
def __init__(self, username, ip, time, success):
self.username = username
self.ip = ip
self.time = time
self.success = success
def __repr__(self):
return '<LoginLog %r>' % self.username
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/Hackappatoi/2022/web/BeerFast/app/database.py | ctfs/Hackappatoi/2022/web/BeerFast/app/database.py | from flask_sqlalchemy import SQLAlchemy
from . import globals
import string
import random
def random_string(count=32):
charset = string.digits + string.ascii_lowercase + string.ascii_uppercase
pwd = ""
for _ in range(0, count):
pwd += random.choice(charset)
return pwd
def init_database(app):
globals.Database = SQLAlchemy(app)
from .models import User
globals.App.config["SESSION_SQLALCHEMY"] = globals.Database
globals.Database.create_all()
u = User.query.filter_by(username="admin").first()
# delete the admin user if it exists
if u is not None:
globals.Database.session.delete(u)
globals.Database.session.commit()
# add the admin user
admin_usr = "admin"
admin_pwd = random_string(32)
u = User(username=admin_usr, password=admin_pwd, level=10)
globals.Database.session.add(u)
globals.Database.session.commit()
u = User.query.filter_by(username="jonathan").first()
if u is None:
user = User("jonathan", random_string(32), 1)
globals.Database.session.add(user)
globals.Database.session.commit()
return admin_usr, admin_pwd
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/Hackappatoi/2022/web/BeerFast/app/config.py | ctfs/Hackappatoi/2022/web/BeerFast/app/config.py | import os
SESSION_USE_SIGNER = True
SECRET_KEY = os.getenv("SECRET_KEY")
SQLALCHEMY_DATABASE_URI = "sqlite:///database.sqlite"
SQLALCHEMY_TRACK_MODIFICATIONS = False
TEMPLATES_AUTO_RELOAD = True
SESSION_TYPE = "sqlalchemy"
SESSION_SQLALCHEMY_TABLE = 'sessions'
CACHE_TYPE = "SimpleCache"
CACHE_DEFAULT_TIMEOUT = 5
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/Hackappatoi/2022/web/BeerFast/app/__init__.py | ctfs/Hackappatoi/2022/web/BeerFast/app/__init__.py | from .app import create_app
__all__ = ["create_app"]
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/Hackappatoi/2022/web/BeerFast/app/routes.py | ctfs/Hackappatoi/2022/web/BeerFast/app/routes.py | import base64
import json
import logging
import hashlib
import os
import re
import time
from . import helper
from . import globals as __globals__
from .models import User
from .app import Login
from logging.handlers import RotatingFileHandler
from flask_login import login_user, login_required, logout_user, current_user
from flask import render_template, request, jsonify, redirect
Formats = {
1: "json",
2: "apache",
}
def init_routes(app):
handler = RotatingFileHandler(os.path.join(os.path.dirname(__file__), "logs", "http.log"), maxBytes=50*1024,
backupCount=3)
http_logger = logging.getLogger("http")
http_logger.setLevel(logging.DEBUG)
http_logger.addHandler(handler)
def cache_key(*args, **kwargs):
key = request.method + request.path + str(request.query_string) + \
str(request.data) + request.headers["User-Agent"]
# hash the key to keep it short
return hashlib.sha256(key.encode("utf-8")).hexdigest()
@Login.user_loader
def load_user(uid):
return User.query.filter_by(id=uid).first()
@Login.unauthorized_handler
def unauthorized():
return redirect("/", 302)
def lang_injection(data):
def safe(v):
v = v.replace("&", "&").replace(
"<", "<").replace(">", ">")
v = re.sub(r"on\w+\s*=", "forbidden=", v)
v = re.sub(r"style\s*=", "forbidden=", v)
return v
lang = request.headers["Accept-Language"].split(",")[0]
lang = safe(lang)
data = data.replace('@LANG@', lang)
return data
@app.after_request
def after_request(response):
data = {
"method": request.method,
"path": request.path,
"status": response.status_code,
"ip": request.remote_addr,
"user_agent": request.user_agent.string,
"date_and_time": time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()),
}
http_logger.debug("%s", json.dumps(data))
return response
@app.route("/")
def index():
return render_template("index.html")
@app.route("/login", methods=["POST"])
def login():
user = request.json.get("user")
password = request.json.get("password")
ip = request.headers["x-forwarded-for"] if "x-forwarded-for" in request.headers else request.remote_addr
success, usr = helper.Manager.check_user(user, password, ip=ip)
if success:
login_user(usr)
return jsonify({"status": "ok"})
return jsonify({"status": "error"})
@app.route("/dashboard")
@login_required
@__globals__.Cache.cached(timeout=5, make_cache_key=cache_key)
def dashboard():
usr = current_user
return lang_injection(render_template("dashboard.html", user=usr, level=usr.level))
@app.route("/logout")
@login_required
def logout():
if current_user.is_user:
logout_user()
return redirect("/", 302)
else:
return redirect("/dashboard", 302)
@app.route("/static/js/analytics.js")
@login_required
@__globals__.Cache.cached(timeout=5, make_cache_key=cache_key)
def analytics():
host = request.headers["X-Forwarded-Host"] if "X-Forwarded-Host" in request.headers else request.host
# remove all ' and " from the host
host = host.replace("'", "").replace('"', "")
return render_template("analytics.js", host=host)
# take parameters from the URL
@app.route("/api/backup", methods=["GET"])
@login_required
def backup():
if current_user.level == 10:
file = request.args.get("file")
seek = int(request.args.get("seek")
) if request.args.get("seek") else 0
length = int(request.args.get("length")
) if request.args.get("length") else 0
try:
with open(os.path.join(os.path.dirname(__file__), "backups", file), "rb") as f:
if seek > 0:
f.seek(int(seek))
if length > 0:
data = f.read(int(length))
else:
data = open(file, "rb").read()
return jsonify({"status": "ok", "content": base64.b64encode(data).decode()}), 200, \
{"Content-Type": "text/plain"}
except Exception as e:
return jsonify({"status": "error", "error": str(e)})
else:
return jsonify({"status": "error", "error": "you are not allowed to do this"})
@app.route("/api/miniserver/start", methods=["GET"])
@login_required
def start_miniserver():
if current_user.is_admin:
pid, port, err = helper.ServerManager.start_miniserver()
if pid:
return jsonify({"status": "ok", "pid": pid, "port": port})
else:
return jsonify({"status": "error", "msg": str(err)})
else:
return jsonify({"status": "error", "msg": "Permission denied"})
@app.route('/logs')
def log():
log_type = request.args["type"] if "type" in request.args else "1"
fmt = f"{{0[Formats][{log_type}]}}"
with open(os.path.join(os.path.dirname(__file__), "logs", "http.log"), "r") as f:
logs = f.read().split("\n")
if log_type == "1":
logs = "\n".join(logs)
else:
for i in range(0, len(logs)):
if logs[i] != "":
decoded = json.loads(logs[i])
logs[i] = f"{decoded['ip']} - - [{decoded['date_and_time']}] \"{decoded['method']} " \
f"{decoded['path']} HTTP/1.1\" {decoded['status']} - \"{decoded['user_agent']}\""
logs = "\n".join(logs)
return render_template("log.html", log_type=fmt.format(globals()), log_types=Formats, log_lines=logs)
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/Hackappatoi/2022/web/BeerFast/app/globals.py | ctfs/Hackappatoi/2022/web/BeerFast/app/globals.py | App = None
Database = None
Session = None
Cache = None
__all__ = ["App", "Database", "Session", "Cache"]
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/Hackappatoi/2022/web/BeerFast/app/bot.py | ctfs/Hackappatoi/2022/web/BeerFast/app/bot.py | from selenium import webdriver
from selenium.webdriver.common.by import By
# import chromedriver_binary
from threading import Thread
import time
def run_bot(user, password):
thread = Thread(target=run, args=(user, password))
thread.daemon = True
thread.start()
def run(user, password):
time.sleep(2)
options = webdriver.ChromeOptions()
options.add_argument('--headless')
options.add_argument('--no-sandbox')
options.add_argument('--disable-dev-shm-usage')
options.add_argument(
'--user-agent=Mozilla/5.0 (Macintosh; Intel Mac OS X 10_8_2) AppleWebKit/537.17 (KHTML, like Gecko) Chrome/24.0.1309.0 Safari/537.17')
# TODO: remove this line
options.add_argument('--disable-web-security') # CORS bypass for testing
while True:
try:
driver = webdriver.Chrome(options=options)
driver.get("http://127.0.0.1:8000/")
# populate the form
driver.find_element(By.ID, "user").send_keys(user)
driver.find_element(By.ID, "password").send_keys(password)
# submit the form
driver.find_element(By.ID, "submit").click()
# wait for the page to load
time.sleep(2)
# print the page source
while True:
# check if the page has changed
if driver.current_url != "http://127.0.0.1:8000/dashboard":
driver.get("http://127.0.0.1:8000/dashboard")
else:
time.sleep(30)
driver.refresh()
except Exception as e:
print(e)
time.sleep(10)
pass
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/Hackappatoi/2022/web/BeerFast/app/app.py | ctfs/Hackappatoi/2022/web/BeerFast/app/app.py | from flask import Flask
from flask_sessionstore import Session
from flask_login import LoginManager
from flask_caching import Cache
from . import globals
from dotenv import load_dotenv
Login = LoginManager()
def create_app(name, config=None):
load_dotenv()
globals.App = Flask(name)
if config is not None:
globals.App.config.from_object(config)
else:
globals.App.config.from_pyfile("app/config.py")
with globals.App.app_context():
globals.Cache = Cache(globals.App)
Login.init_app(globals.App)
globals.Session = Session(globals.App)
globals.Session.app.session_interface.db.create_all()
from . import database
admin_usr, admin_pwd = database.init_database(globals.App)
from . import routes
routes.init_routes(globals.App)
return globals.App, admin_usr, admin_pwd
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/Hackappatoi/2022/web/Hackbar/src/vendor/mockery/mockery/docs/conf.py | ctfs/Hackappatoi/2022/web/Hackbar/src/vendor/mockery/mockery/docs/conf.py | # -*- coding: utf-8 -*-
#
# Mockery Docs documentation build configuration file, created by
# sphinx-quickstart on Mon Mar 3 14:04:26 2014.
#
# This file is execfile()d with the current directory set to its
# containing dir.
#
# Note that not all possible configuration values are present in this
# autogenerated file.
#
# All configuration values have a default; values that are commented out
# serve to show the default.
import sys
import os
# If extensions (or modules to document with autodoc) are in another directory,
# add these directories to sys.path here. If the directory is relative to the
# documentation root, use os.path.abspath to make it absolute, like shown here.
#sys.path.insert(0, os.path.abspath('.'))
# -- General configuration ------------------------------------------------
# If your documentation needs a minimal Sphinx version, state it here.
#needs_sphinx = '1.0'
# Add any Sphinx extension module names here, as strings. They can be
# extensions coming with Sphinx (named 'sphinx.ext.*') or your custom
# ones.
extensions = [
'sphinx.ext.todo',
]
# Add any paths that contain templates here, relative to this directory.
templates_path = ['_templates']
# The suffix of source filenames.
source_suffix = '.rst'
# The encoding of source files.
#source_encoding = 'utf-8-sig'
# The master toctree document.
master_doc = 'index'
# General information about the project.
project = u'Mockery Docs'
copyright = u'Pádraic Brady, Dave Marshall and contributors'
# The version info for the project you're documenting, acts as replacement for
# |version| and |release|, also used in various other places throughout the
# built documents.
#
# The short X.Y version.
version = '1.0'
# The full version, including alpha/beta/rc tags.
release = '1.0-alpha'
# The language for content autogenerated by Sphinx. Refer to documentation
# for a list of supported languages.
#language = None
# There are two options for replacing |today|: either, you set today to some
# non-false value, then it is used:
#today = ''
# Else, today_fmt is used as the format for a strftime call.
#today_fmt = '%B %d, %Y'
# List of patterns, relative to source directory, that match files and
# directories to ignore when looking for source files.
exclude_patterns = ['_build']
# The reST default role (used for this markup: `text`) to use for all
# documents.
#default_role = None
# If true, '()' will be appended to :func: etc. cross-reference text.
#add_function_parentheses = True
# If true, the current module name will be prepended to all description
# unit titles (such as .. function::).
#add_module_names = True
# If true, sectionauthor and moduleauthor directives will be shown in the
# output. They are ignored by default.
#show_authors = False
# The name of the Pygments (syntax highlighting) style to use.
pygments_style = 'sphinx'
# A list of ignored prefixes for module index sorting.
#modindex_common_prefix = []
# If true, keep warnings as "system message" paragraphs in the built documents.
#keep_warnings = False
# -- Options for HTML output ----------------------------------------------
# The theme to use for HTML and HTML Help pages. See the documentation for
# a list of builtin themes.
html_theme = 'default'
# Theme options are theme-specific and customize the look and feel of a theme
# further. For a list of options available for each theme, see the
# documentation.
#html_theme_options = {}
# Add any paths that contain custom themes here, relative to this directory.
#html_theme_path = []
# The name of an image file (within the static path) to use as favicon of the
# docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32
# pixels large.
#html_favicon = None
# Add any paths that contain custom static files (such as style sheets) here,
# relative to this directory. They are copied after the builtin static files,
# so a file named "default.css" will overwrite the builtin "default.css".
html_static_path = ['_static']
# Add any extra paths that contain custom files (such as robots.txt or
# .htaccess) here, relative to this directory. These files are copied
# directly to the root of the documentation.
#html_extra_path = []
# If not '', a 'Last updated on:' timestamp is inserted at every page bottom,
# using the given strftime format.
#html_last_updated_fmt = '%b %d, %Y'
# If true, SmartyPants will be used to convert quotes and dashes to
# typographically correct entities.
#html_use_smartypants = True
# Custom sidebar templates, maps document names to template names.
#html_sidebars = {}
# Additional templates that should be rendered to pages, maps page names to
# template names.
#html_additional_pages = {}
# If false, no module index is generated.
#html_domain_indices = True
# If false, no index is generated.
#html_use_index = True
# If true, the index is split into individual pages for each letter.
#html_split_index = False
# If true, links to the reST sources are added to the pages.
#html_show_sourcelink = True
# If true, "Created using Sphinx" is shown in the HTML footer. Default is True.
#html_show_sphinx = True
# If true, "(C) Copyright ..." is shown in the HTML footer. Default is True.
#html_show_copyright = True
# If true, an OpenSearch description file will be output, and all pages will
# contain a <link> tag referring to it. The value of this option must be the
# base URL from which the finished HTML is served.
#html_use_opensearch = ''
# This is the file name suffix for HTML files (e.g. ".xhtml").
#html_file_suffix = None
# Output file base name for HTML help builder.
htmlhelp_basename = 'MockeryDocsdoc'
# -- Options for LaTeX output ---------------------------------------------
latex_elements = {
# The paper size ('letterpaper' or 'a4paper').
#'papersize': 'letterpaper',
# The font size ('10pt', '11pt' or '12pt').
#'pointsize': '10pt',
# Additional stuff for the LaTeX preamble.
#'preamble': '',
}
# Grouping the document tree into LaTeX files. List of tuples
# (source start file, target name, title,
# author, documentclass [howto, manual, or own class]).
latex_documents = [
('index', 'MockeryDocs.tex', u'Mockery Docs Documentation',
u'Pádraic Brady, Dave Marshall, Wouter, Graham Campbell', 'manual'),
]
# The name of an image file (relative to this directory) to place at the top of
# the title page.
#latex_logo = None
# For "manual" documents, if this is true, then toplevel headings are parts,
# not chapters.
#latex_use_parts = False
# If true, show page references after internal links.
#latex_show_pagerefs = False
# If true, show URL addresses after external links.
#latex_show_urls = False
# Documents to append as an appendix to all manuals.
#latex_appendices = []
# If false, no module index is generated.
#latex_domain_indices = True
# -- Options for manual page output ---------------------------------------
# One entry per manual page. List of tuples
# (source start file, name, description, authors, manual section).
man_pages = [
('index', 'mockerydocs', u'Mockery Docs Documentation',
[u'Pádraic Brady, Dave Marshall, Wouter, Graham Campbell'], 1)
]
# If true, show URL addresses after external links.
#man_show_urls = False
# -- Options for Texinfo output -------------------------------------------
# Grouping the document tree into Texinfo files. List of tuples
# (source start file, target name, title, author,
# dir menu entry, description, category)
texinfo_documents = [
('index', 'MockeryDocs', u'Mockery Docs Documentation',
u'Pádraic Brady, Dave Marshall, Wouter, Graham Campbell', 'MockeryDocs', 'One line description of project.',
'Miscellaneous'),
]
# Documents to append as an appendix to all manuals.
#texinfo_appendices = []
# If false, no module index is generated.
#texinfo_domain_indices = True
# How to display URL addresses: 'footnote', 'no', or 'inline'.
#texinfo_show_urls = 'footnote'
# If true, do not generate a @detailmenu in the "Top" node's menu.
#texinfo_no_detailmenu = False
#on_rtd is whether we are on readthedocs.org, this line of code grabbed from docs.readthedocs.org
on_rtd = os.environ.get('READTHEDOCS', None) == 'True'
if not on_rtd: # only import and set the theme if we're building docs locally
import sphinx_rtd_theme
html_theme = 'sphinx_rtd_theme'
html_theme_path = [sphinx_rtd_theme.get_html_theme_path()]
print sphinx_rtd_theme.get_html_theme_path()
# load PhpLexer
from sphinx.highlighting import lexers
from pygments.lexers.web import PhpLexer
# enable highlighting for PHP code not between <?php ... ?> by default
lexers['php'] = PhpLexer(startinline=True)
lexers['php-annotations'] = PhpLexer(startinline=True)
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/BSidesCanberra/2021/crypto/Despicable_Key/enc.py | ctfs/BSidesCanberra/2021/crypto/Despicable_Key/enc.py | ## ENCRYPT
## pip install pycryptodomex
from binascii import *
from Cryptodome.Cipher import AES
key = b'cybearscybears20'
import os
n = os.urandom(12)
with open('flag.png', 'rb') as f:
d = f.read()
a = AES.new(key, AES.MODE_GCM, nonce=n)
cipher, tag = a.encrypt_and_digest(d)
with open('flag.png.enc', 'wb') as g:
g.write(cipher)
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/BSidesCanberra/2021/crypto/Rot_Away_Rust/client_initiator.py | ctfs/BSidesCanberra/2021/crypto/Rot_Away_Rust/client_initiator.py | import json
import Crypto.Cipher.AES as aes
import Crypto.Random as rand
from binascii import *
import struct
from pwn import *
import argparse
class ClientInitiator:
def __init__(self, responder_address, responder_port, server_address, server_port, client_id, client_server_key):
self.client_id = client_id
self.responder_address = responder_address
self.responder_port = responder_port
self.server_address = server_address
self.server_port = server_port
self.client_server_key = client_server_key
def connect_to_responder(self):
####Initiator
log.info("Connecting to Client Responder...")
try:
self.cr = remote(self.responder_address, self.responder_port)
except Exception as e:
log.error("ERROR: Could not connect to client responder: ({},{}) : {}".format(self.responder_address, self.responder_port, e))
exit(-1)
def step1s(self):
## Step 1 - send client_id to client_responder
log.info("STEP 1 - send client_id to client_responder")
self.cr.sendline(json.dumps({"ID_A" : self.client_id}))
def step2r(self):
## Step 2 - receive from client_responder
log.info("STEP 2 - receive from client_responder")
step2r = self.cr.recvuntil(b'}')
log.debug(step2r)
try:
step2rj = json.loads(step2r)
except Exception as e:
print("ERROR: Expecting JSON with key success, session_id, ID_A, ID_B, gcm_nonce, gcm_cipher, gcm_tag")
exit(-1)
step2r_keys = {'success', 'session_id', 'ID_A', 'ID_B', 'gcm_nonce', 'gcm_cipher', 'gcm_tag'}
if 'success' in step2rj.keys():
step2r_success = step2rj['success']
else:
print("ERROR: Expecting JSON with key success")
exit(-1)
if step2r_success != True:
print("ERROR, step2r failed: {}".format(step2rj['error']))
exit(-1)
self.step2rj = step2rj
def connect_to_server(self):
log.info("STEP 3 - Send to server")
try:
self.s = remote(self.server_address, self.server_port)
except Exception as e:
log.error("ERROR: Could not connect to server: ({},{}) : {}".format(self.server_address, self.server_port, e))
exit(-1)
def get_directory(self):
#requires active connection to server - run connect_to_server() first
self.s.recvuntil(b'Choice:')
self.s.sendline("1")
d = self.s.recvuntil(b']')
self.directory = json.loads(d)
def step3s(self):
## Step 3 - send to server
nonce_a = rand.get_random_bytes(4)
log.debug("nonce_a : {}".format(hexlify(nonce_a)))
id_a_packed = struct.pack("I", self.client_id)
id_b_packed = struct.pack("I", self.step2rj['ID_B'])
e3 = aes.new(self.client_server_key, mode=aes.MODE_GCM)
gcm_nonce_AS = e3.nonce
(gcm_cipher_AS, gcm_tag_AS) = e3.encrypt_and_digest(nonce_a + unhexlify(self.step2rj['session_id']) + id_a_packed + id_b_packed)
step3s = { 'session_id' : self.step2rj['session_id'],
'ID_A' : self.client_id,
'ID_B' : self.step2rj['ID_B'],
'gcm_nonce_AS' : hexlify(gcm_nonce_AS).decode(),
'gcm_cipher_AS' : hexlify(gcm_cipher_AS).decode(),
'gcm_tag_AS' : hexlify(gcm_tag_AS).decode(),
'gcm_nonce_BS' : self.step2rj['gcm_nonce'], #Just pass on encrypted details from B to server
'gcm_cipher_BS' : self.step2rj['gcm_cipher'],
'gcm_tag_BS': self.step2rj['gcm_tag']
}
self.s.recvuntil(b'Choice:')
self.s.sendline("2")
self.s.sendline(json.dumps(step3s))
self.step3s = step3s
self.nonce_a = nonce_a
def step4r(self):
## Step 4 - receive shared key from server
log.info("STEP 4 - receive shared key from server")
step4r = self.s.recvuntil(b'}')
log.debug(step4r)
try:
step4rj = json.loads(step4r)
except Exception as e:
print("ERROR: Expecting JSON with key success, session_id, ID_A, ID_B, step4A_nonce, step4A_cipher, step4A_tag, step4B_nonce, step4B_cipher, step4B_tag")
exit(-1)
if 'success' in step4rj.keys():
step4r_success = step4rj['success']
else:
print("ERROR: Expecting JSON with key success")
exit(-1)
if step4r_success != True:
print("ERROR, step4r failed: {}".format(step4rj['error']))
exit(-1)
#Extract shared key
e4 = aes.new(self.client_server_key, aes.MODE_GCM, nonce=unhexlify(step4rj['step4A_nonce']))
try:
step4_plain = e4.decrypt_and_verify(unhexlify(step4rj['step4A_cipher']), unhexlify(step4rj['step4A_tag']))
except Exception as e:
print("ERROR: GCM verify failed {}".format(e))
exit(-1)
step4_dec_nonce_a, step4_dec_k_ab = struct.unpack('4s16s', step4_plain)
log.debug("nonce_a_e4 {}, K_AB {}".format(hexlify(step4_dec_nonce_a), hexlify(step4_dec_k_ab)))
if step4_dec_nonce_a != self.nonce_a:
print("ERROR: nonce_a mismatch under cipher")
exit(-1)
self.K_AB = step4_dec_k_ab
self.step4rj = step4rj
def step5s(self):
## Step 5 - send shared key to client_responder
log.info("STEP 5 - send shared key to client_responder")
step5s = { 'session_id' : self.step2rj['session_id'],
'gcm_nonce' : self.step4rj['step4B_nonce'], #Just pass on encrypted details from B to server
'gcm_cipher' : self.step4rj['step4B_cipher'],
'gcm_tag': self.step4rj['step4B_tag']
}
self.cr.sendline(json.dumps(step5s))
def step6r(self):
## Step 6 - receive message from client_responder
log.info("STEP 6 - receive message from client_responder ")
step6r = self.cr.recvuntil(b'}')
log.debug(step6r)
step6rj = json.loads(step6r)
try:
e6 = aes.new(self.K_AB, mode=aes.MODE_GCM, nonce=unhexlify(step6rj['gcm_nonce']))
log.success("MESSAGE RECEIVED! {}".format(e6.decrypt_and_verify(unhexlify(step6rj['gcm_cipher']), unhexlify(step6rj['gcm_tag']))))
except Exception as e:
print("ERROR in step 6 - decrypt message [{}]".format(e))
exit(-1)
def close_and_exit(self, status):
#######################################################
self.cr.close()
self.s.close()
exit(status)
#######################################################
#############################################################
#### MAIN
#############################################################
if __name__ == "__main__":
## Extract command line args
parser = argparse.ArgumentParser()
parser.add_argument('-i', '--clientid', type=int, default=9006, help="client_id of client_initiator (default:guest)")
parser.add_argument('-s', '--serveraddress', default="localhost", help="server address (domain or IP string)")
parser.add_argument('-t', '--responderaddress', default="localhost", help="client responder address (domain or IP string)")
parser.add_argument('-p', '--serverport', type=int, default=9000, help="Port number of server")
parser.add_argument('-q', '--responderport', type=int, default=9007, help="Port number of client responder (default:echo)")
parser.add_argument('-d', '--debug', help="Print debug", action="store_true")
args = parser.parse_args()
if args.debug:
context.log_level = 'debug'
else:
context.log_level = 'info'
server_address = args.serveraddress
server_port = args.serverport
responder_address = args.responderaddress
responder_port = args.responderport
log.debug("s_add - {}\ns_port - {}\ncr_add - {}\ncr_port - {}".format(server_address, server_port, responder_address, responder_port))
client_id = args.clientid
## Get server directory - find guest and echo users
log.info("Connecting to server to download directory")
try:
server = remote(server_address, server_port)
except Exception as e:
log.error("ERROR: Could not connect to server: ({},{}) : {}".format(server_address, server_port, e))
exit(-1)
server.recvuntil(b'Choice:')
server.sendline("1")
d = server.recvuntil(b']')
dj = json.loads(d)
friends_list = []
for user in dj:
if user['name'] == 'guest': #get our server key
client_server_key = unhexlify(user['server_key'])
client_name = user['name']
client_id = user['id']
client_affiliation = user['affiliation']
if user['name'] == 'echo': #get echo's port
responder_port = user['port']
if user['affiliation'] == 'none':
friends_list.append(user['id'])
log.debug("DEBUG: \n\tclient_id - {}\n\tclient_name - {}\n\tclient_affiliation - {}\n\tfriends_list - {}".format(client_id, client_name, client_affiliation, friends_list))
## Start Client Initiator Protocol run
CI = ClientInitiator(responder_address, responder_port, server_address, server_port, client_id, client_server_key)
CI.connect_to_responder()
CI.step1s()
CI.step2r()
CI.connect_to_server()
CI.get_directory()
log.info(str(CI.directory))
CI.step3s()
CI.step4r()
CI.step5s()
CI.step6r()
CI.close_and_exit(0)
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/BSidesCanberra/2021/crypto/Rot_Away_Rust/server.py | ctfs/BSidesCanberra/2021/crypto/Rot_Away_Rust/server.py | #!/usr/bin/python3
import json
import Crypto.Cipher.AES as aes
import Crypto.Random as rand
from binascii import *
import struct
import string
import sys
def debug_print(err):
sys.stderr.write(err)
from RARsecrets import secrets_server
def validate(value, check, minimum=None, maximum=None):
valid_types = ["bool", "int", "hex"]
if check not in valid_types:
return False
#Check for boolean
if check == "bool":
if type(value) == bool:
return True
else:
return False
#Check for valid int with optional min/max
if check == "int":
if type(value) != int:
return False
if (minimum == None) and (maximum == None):
return True
if (minimum == None) and (maximum != None):
if value <= maximum:
return True
else:
return False
if (minimum != None) and (maximum == None):
if value >= minimum:
return True
else:
return False
if (minimum != None) and (maximum != None):
if (value >= minimum) and (value <= maximum):
return True
else:
return False
#Check for valid hex string
if check == "hex":
if type(value) != str:
return False
if all(c in string.hexdigits for c in value) == True:
return True
else:
return False
###################
## SERVER
###################
class RARServer:
def __init__(self, secrets_server):
self.secrets = secrets_server
def step3r(self):
## Step 3 - receive
step3r = input()
try:
step3rj = json.loads(step3r.strip())
except Exception as e:
err = "ERROR: Expecting JSON with keys session_id, ID_A, ID_B, gcm_cipher_AS, gcm_nonce_AS, gcm_tag_AS, gcm_cipher_BS, gcm_nonce_BS, gcm_tag_BS, failed: {}".format(e)
print(json.dumps({"success":False, "error": err}))
exit(-1)
### Check all keys are included
step3_keys = set(['session_id','ID_A', 'ID_B', 'gcm_cipher_AS', 'gcm_nonce_AS', 'gcm_tag_AS', 'gcm_cipher_BS', 'gcm_nonce_BS', 'gcm_tag_BS'])
if step3_keys.issubset(set(step3rj.keys())) != True:
err = "ERROR: Expecting JSON with keys session_id, ID_A, ID_B, gcm_cipher_AS, gcm_nonce_AS, gcm_tag_AS, gcm_cipher_BS, gcm_nonce_BS, gcm_tag_BS"
print(json.dumps({"success":False, "error": err}))
exit(-1)
### Validate all entries
if (validate(step3rj['session_id'], "hex") != True) or \
(validate(step3rj['ID_A'], "int", minimum=0, maximum=2**32) != True) or \
(validate(step3rj['ID_B'], "int", minimum=0, maximum=2**32) != True) or \
(validate(step3rj['gcm_cipher_AS'], "hex") != True) or \
(validate(step3rj['gcm_nonce_AS'], "hex") != True) or \
(validate(step3rj['gcm_tag_AS'], "hex") != True) or \
(validate(step3rj['gcm_cipher_BS'], "hex") != True) or \
(validate(step3rj['gcm_nonce_BS'], "hex") != True) or \
(validate(step3rj['gcm_tag_BS'], "hex") != True):
err = "ERROR: Found invalid hex string"
print(json.dumps({"success":False, "error": err}))
exit(-1)
### Get appropriate key
if not {step3rj['ID_A'], step3rj['ID_B']}.issubset( set(secrets_server.keys())):
err = "ERROR: ID_A or ID_B not known "
print(json.dumps({"success":False, "error": err}))
exit(-1)
K_AS = unhexlify(secrets_server[step3rj['ID_A']]['server_key'])
K_BS = unhexlify(secrets_server[step3rj['ID_B']]['server_key'])
### Ensure session ID outside of cipher matches BOTH session_IDs inside cipher
try:
e3A = aes.new(K_AS, aes.MODE_GCM, nonce=unhexlify(step3rj['gcm_nonce_AS']))
step3_plainA = e3A.decrypt_and_verify(unhexlify(step3rj['gcm_cipher_AS']), unhexlify(step3rj['gcm_tag_AS']))
except Exception as e:
err = "ERROR: GCM verify A failed {}".format(e)
print(json.dumps({"success":False, "error": err}))
exit(-1)
nonce_A_eA, session_id_eA, ID_A_eA, ID_B_eA = struct.unpack('4s8s2I', step3_plainA)
try:
e3B = aes.new(K_BS, aes.MODE_GCM, nonce=unhexlify(step3rj['gcm_nonce_BS']))
step3_plainB = e3B.decrypt_and_verify(unhexlify(step3rj['gcm_cipher_BS']), unhexlify(step3rj['gcm_tag_BS']))
except Exception as e:
err = "ERROR: GCM verify B failed {}".format(e)
print(json.dumps({"success":False, "error": err}))
exit(-1)
nonce_B_eB, session_id_eB, ID_A_eB, ID_B_eB = struct.unpack('4s8s2I', step3_plainB)
### Ensure session_id's provided match session_id's under both cipher
if not (unhexlify(step3rj['session_id']) == session_id_eA == session_id_eB):
err = "ERROR: Session ID provided does not match both encrypted session ids"
print(json.dumps({"success":False, "error": err}))
debug_print("external {}, eA {}, eB {}".format(step3rj['session_id'], hexlify(session_id_eA), hexlify(session_id_eB)))
exit(-1)
### Ensure ID's provided match ID's under both cipher
if not (step3rj['ID_A'] == ID_A_eA == ID_A_eB):
err = "ERROR: ID_A provided does not match both encrypted ID_As"
print(json.dumps({"success":False, "error": err}))
debug_print("external {}, eA {}, eB {}".format(step3rj['ID_A'], ID_A_eA, ID_A_eB))
exit(-1)
if not (step3rj['ID_B'] == ID_B_eA == ID_B_eB):
err = "ERROR: ID_B provided does not match both encrypted ID_Bs"
print(json.dumps({"success":False, "error": err}))
exit(-1)
self.ID_A = ID_A_eA
self.ID_B = ID_B_eA
self.K_AS = K_AS
self.K_BS = K_BS
self.nonce_A = nonce_A_eA
self.nonce_B = nonce_B_eB
self.session_id = session_id_eA
#print("DEBUG:\tnonce_A: {}\n\tsession_id: {}\n\tID_A: {}\n\tID_B: {}".format(hexlify(nonce_A_eA), hexlify(session_id_eA), hex(ID_A_eA), hex(ID_B_eA)))
#print("DEBUG:\tnonce_A: {}\n\tsession_id: {}\n\tID_A: {}\n\tID_B: {}".format(hexlify(nonce_B_eB), hexlify(session_id_eB), hex(ID_B_eB), hex(ID_B_eB)))
def step4s(self):
## Step 4 - Send
### Calculate random session key, send back, encrypted with both recipients server keys
K_AB = rand.get_random_bytes(16)
e4A = aes.new(self.K_AS, mode=aes.MODE_GCM)
step4A_nonce = e4A.nonce
(step4A_cipher, step4A_tag) = e4A.encrypt_and_digest(self.nonce_A + K_AB)
e4B = aes.new(self.K_BS, mode=aes.MODE_GCM)
step4B_nonce = e4B.nonce
(step4B_cipher, step4B_tag) = e4B.encrypt_and_digest(self.nonce_B + K_AB)
step4s = { 'success' : True,
'session_id' : hexlify(self.session_id).decode(),
'ID_A' : self.ID_A,
'ID_B' : self.ID_B,
'step4A_nonce' : hexlify(step4A_nonce).decode(),
'step4A_cipher' : hexlify(step4A_cipher).decode(),
'step4A_tag' : hexlify(step4A_tag).decode(),
'step4B_nonce' : hexlify(step4B_nonce).decode(),
'step4B_cipher' : hexlify(step4B_cipher).decode(),
'step4B_tag' : hexlify(step4B_tag).decode()
}
print(json.dumps(step4s))
def print_directory(self):
d = []
for k in self.secrets.keys():
if self.secrets[k]['name'] == 'guest':
d.append( {'id': k, 'name' : self.secrets[k]['name'], 'affiliation' : self.secrets[k]['affiliation'], 'port' : 0, 'server_key' : self.secrets[k]['server_key'] } )
else:
d.append( {'id': k, 'name' : self.secrets[k]['name'], 'affiliation' : self.secrets[k]['affiliation'], 'port' : self.secrets[k]['port'] } )
print(json.dumps(d))
def show_menu(self):
while(True):
try:
c = input("1) Show directory\n2) Key exchange\nq) Quit\nEnter Choice:")
except Exception as e:
print("ERROR in input. Closing... {}".format(e))
exit(-1)
if c.strip() == "1":
self.print_directory()
continue
if c.strip() == "2":
self.step3r()
self.step4s()
continue
if c.strip() == 'q':
exit(0)
###################
## MAIN
###################
if __name__ == "__main__":
S = RARServer(secrets_server)
S.show_menu()
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/BSidesCanberra/2021/crypto/Rot_Away_Rust/client_responder.py | ctfs/BSidesCanberra/2021/crypto/Rot_Away_Rust/client_responder.py | import json
import Crypto.Cipher.AES as aes
import Crypto.Random as rand
from binascii import *
import struct
import string
import argparse
from RARsecrets import flag
from RARsecrets import secrets_server as ss
def validate(value, check, minimum=None, maximum=None):
valid_types = ["bool", "int", "hex"]
if check not in valid_types:
return False
#Check for boolean
if check == "bool":
if type(value) == bool:
return True
else:
return False
#Check for valid int with optional min/max
if check == "int":
if type(value) != int:
return False
if (minimum == None) and (maximum == None):
return True
if (minimum == None) and (maximum != None):
if value <= maximum:
return True
else:
return False
if (minimum != None) and (maximum == None):
if value >= minimum:
return True
else:
return False
if (minimum != None) and (maximum != None):
if (value >= minimum) and (value <= maximum):
return True
else:
return False
#Check for valid hex string
if check == "hex":
if type(value) != str:
return False
if all(c in string.hexdigits for c in value) == True:
return True
else:
return False
#########################
#### RESPONDER
#########################
class ClientResponder:
def __init__(self, client_id, client_server_key, friends_list, message):
self.client_id = client_id
self.K_BS = client_server_key
self.friends_list = friends_list
self.message = message
def step1r(self):
## Step 1 - receive
step1r = input()
try:
step1rj = json.loads(step1r.strip())
except Exception as e:
err = "ERROR: Expecting JSON with key ID_A, failed: {}".format(e)
print(json.dumps({"success":False, "error": err}))
exit(-1)
if 'ID_A' not in step1rj.keys():
err = "ERROR: Expecting JSON with key ID_A, failed"
print(json.dumps({"success":False, "error": err}))
exit(-1)
ID_A = step1rj['ID_A']
if validate(ID_A, "int", minimum=0, maximum=2**32) != True:
err = "ERROR: ID_A not a valid integer"
print(json.dumps({"success":False, "error": err}))
exit(-1)
if ID_A not in self.friends_list:
err = "ERROR: ID_A not in my friends list"
print(json.dumps({"success":False, "error": err}))
exit(-1)
self.step1rj = step1rj
self.ID_A = ID_A
def step2s(self):
## Step 2 - send
nonce_b = rand.get_random_bytes(4)
session_id = rand.get_random_bytes(8)
id_a_packed = struct.pack("I", self.ID_A)
id_b_packed = struct.pack("I", self.client_id)
e2 = aes.new(self.K_BS, mode=aes.MODE_GCM)
e2_gcm_nonce = e2.nonce
(step2c, step2tag) = e2.encrypt_and_digest(nonce_b + session_id + id_a_packed + id_b_packed)
step2s = { 'success' : True,
'session_id' : hexlify(session_id).decode(),
'ID_A' : self.ID_A,
'ID_B' : self.client_id,
'gcm_nonce' : hexlify(e2_gcm_nonce).decode(),
'gcm_cipher' : hexlify(step2c).decode(),
'gcm_tag' : hexlify(step2tag).decode()
}
print(json.dumps(step2s))
self.step2s = step2s
self.nonce_b = nonce_b
self.session_id = session_id
def step5r(self):
## Step 5 - receive
step5r = input()
try:
step5rj = json.loads(step5r.strip())
except Exception as e:
err = "ERROR: Expecting JSON with key session_id, gcm_nonce, gcm_cipher, gcm_tag, failed: {}".format(e)
print(json.dumps({"success":False, "error": err}))
exit(-1)
step5_keys = set(['session_id', 'gcm_nonce', 'gcm_cipher', 'gcm_tag'])
if step5_keys.issubset(set(step5rj.keys())) != True:
err = "ERROR: Expecting JSON with key session_id, gcm_nonce, gcm_cipher, gcm_tag"
print(json.dumps({"success":False, "error": err}))
exit(-1)
## Checks
# 1. dec session_id is same as above
# 2. nonce_b is same as above
if validate(step5rj['session_id'], "hex") != True or \
validate(step5rj['gcm_nonce'], "hex") != True or \
validate(step5rj['gcm_cipher'], "hex") != True or \
validate(step5rj['gcm_tag'], "hex") != True :
err = "ERROR: Found invalid hex string"
print(json.dumps({"success":False, "error": err}))
exit(-1)
if unhexlify(step5rj['session_id']) != self.session_id:
err = "ERROR: session_id mismatch"
print(json.dumps({"success":False, "error": err}))
exit(-1)
try:
e5 = aes.new(self.K_BS, aes.MODE_GCM, nonce=unhexlify(step5rj['gcm_nonce']))
step5_plain = e5.decrypt_and_verify(unhexlify(step5rj['gcm_cipher']), unhexlify(step5rj['gcm_tag']))
except Exception as e:
err = "ERROR: GCM verify failed {}".format(e)
print(json.dumps({"success":False, "error": err}))
exit(-1)
try:
step5_dec_nonce, step5_dec_k_ab = struct.unpack('4s16s', step5_plain)
except Exception as e:
err = "ERROR: Incorrect decrypted format. Expecting (nonce_b || key) {}".format(e)
print(json.dumps({"success":False, "error": err}))
exit(-1)
if step5_dec_nonce != self.nonce_b:
err = "ERROR: decrypted nonce_b mismatch"
print(json.dumps({"success":False, "error": err}))
exit(-1)
self.K_AB = step5_dec_k_ab
def step6s(self):
### Step 6 - send
e6 = aes.new(self.K_AB, mode=aes.MODE_GCM)
e6_gcm_nonce = e6.nonce
e6_gcm_cipher, e6_gcm_tag = e6.encrypt_and_digest(self.message)
step6s = { 'success' : True,
'session_id' : hexlify(self.session_id).decode(),
'gcm_nonce' : hexlify(e6_gcm_nonce).decode(),
'gcm_cipher' : hexlify(e6_gcm_cipher).decode(),
'gcm_tag' : hexlify(e6_gcm_tag).decode()
}
print(json.dumps(step6s))
#########################
#### MAIN
#########################
if __name__ == "__main__":
parser = argparse.ArgumentParser()
parser.add_argument('-i', '--clientid', type=int, default=9001, help="client_id of client_responder")
args = parser.parse_args()
client_id = args.clientid
if client_id not in ss.keys():
print("ERROR: Invalid client_id - {}".format(client_id))
exit(-1)
client_name = ss[client_id]['name']
client_affiliation = ss[client_id]['affiliation'] #['cybears', 'decepticomtss', 'none']
client_server_key = unhexlify(ss[client_id]['server_key'])
if client_affiliation == 'none':
friends_list = ss.keys()
else:
friends_list = []
for k in ss.keys():
if ss[k]['affiliation'] == client_affiliation:
friends_list.append(k)
if client_id == 9001: #Flagimus Prime
message = flag
else:
message = b"Beep Bop Boop, handshake successful but I don't have the flag!"
CR = ClientResponder(client_id, client_server_key, friends_list, message)
CR.step1r()
CR.step2s()
CR.step5r()
CR.step6s()
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/BSidesCanberra/2021/crypto/Bomb_Disposal/bomb.py | ctfs/BSidesCanberra/2021/crypto/Bomb_Disposal/bomb.py | from secrets import flag
assert(len(flag) > 512//8)
seed = int.from_bytes(flag, byteorder='big')
class BBSnLCG:
def __init__(this, seed):
this.B = int.from_bytes(b'BSides CBR', byteorder='big')
this.C = int.from_bytes(b'cybears', byteorder='big')
this.D = 2020
this.N = 133329403635104636891429937256104361307834148892567075810781974525019940196738419111061390432404940560467873684206839810286509876858329703550705859195697849826490388233366569881709667248117952214502616623921379296197606033756105490632562475495591221340492570618714533225999432158266347487875153737481576276481
this.e = 2
this.rng_state = seed
def step(this):
# Linear Congruential Generator part
# Step the internal state of the RNG
this.rng_state = (this.B*(this.rng_state**3) + this.C*this.rng_state + this.D) % this.N
def get_state(this):
#Blum-Blum-Shub part
return pow(this.rng_state, this.e, this.N)
if __name__ == "__main__":
print("Arming bomb...")
rng = BBSnLCG(seed)
print("Parameters used")
print("B {}, C {}, D {}, N {}, e {}".format(rng.B, rng.C, rng.D, rng.N, rng.e))
#print("{}: {}".format(0, rng.get_state() ))
internal_state = [rng.rng_state]
external_state = [rng.get_state()]
print("Beginning countdown...")
#Step RNG and save internal and external states
for i in range(1,10):
rng.step()
internal_state.append(rng.rng_state)
external_state.append(rng.get_state())
#print("{},".format(rng.get_state() ))
#print("internal_state = {}".format(internal_state))
print("external_state = {}".format(external_state))
with open("countdown", "w") as g:
g.write("countdown = {}".format(external_state))
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/BSidesCanberra/2021/crypto/Empty_Vault/mt_flask.py | ctfs/BSidesCanberra/2021/crypto/Empty_Vault/mt_flask.py | from flask import Flask,render_template, request
app = Flask(__name__)
'''
"What is identity? It is the difference between us. Difference is experienced in the mind, yet the Buddha said this mind creates the world, that this world only exists in the mind and nowhere else."
'''
from hashlib import sha256
import os
from binascii import *
from flag import flag
class MerkleTree(object):
def __init__(self):
self.leaves = list()
self.levels = None
self.is_ready = False
def add_leaf(self, value):
self.leaves.append(sha256(value).digest())
def _calculate_next_level(self):
solo_leave = None
N = len(self.levels[0]) # number of leaves on the level
if N % 2 == 1: # if odd number of leaves on the level
solo_leave = self.levels[0][-1]
N -= 1
new_level = []
for l, r in zip(self.levels[0][0:N:2], self.levels[0][1:N:2]):
new_level.append(sha256(l+r).digest())
if solo_leave is not None:
new_level.append(solo_leave)
self.levels = [new_level, ] + self.levels # prepend new level
def make_tree(self):
self.is_ready = False
if len(self.leaves) > 0:
self.levels = [self.leaves, ]
while len(self.levels[0]) > 1:
self._calculate_next_level()
self.is_ready = True
def get_merkle_root(self):
if self.is_ready:
if self.levels is not None:
return self.levels[0][0]
else:
return None
else:
return None
def hashPassword(p):
mt = MerkleTree()
for c in p:
mt.add_leaf(c)
mt.make_tree()
return hexlify(mt.get_merkle_root())
def generateRandomPassword(length):
p = os.urandom(length)
return hexlify(p)
def splitPassword(p, isString=True):
if isString:
return ",".join([c for c in p]).split(",")
else:
return b",".join([chr(c).encode() for c in p]).split(b",")
def validatePassword(user_password, password_hashes, denyList=[], debug=False):
try:
joined_password = unhexlify("".join(user_password.split(",")))
except Exception as e:
raise Exception("ERROR: Formatting error. Exiting")
if joined_password in denyList:
raise Exception("Nice try, but that password is not allowed...")
split_password = [unhexlify(c) for c in user_password.split(",")]
user_password_hash = hashPassword(split_password)
if debug:
print("user_password entered: [", user_password, "]")
print("hashes", password_hashes)
print("deny list", denyList)
print("hash", user_password_hash)
if (user_password_hash in password_hashes):
return True
return False
test_password = b"SuperSecretPassword"
test_password_list = splitPassword(test_password, isString=False)
test_password_hash = hashPassword(test_password_list)
password_hashes = [test_password_hash]
for i in range(0,9):
new_password = generateRandomPassword(32)
new_password_list = splitPassword(new_password, isString=False)
new_password_hash = hashPassword(new_password_list)
password_hashes.append(new_password_hash)
@app.route('/')
def hello_world():
return render_template("login.html")
@app.route('/auth', methods=['GET'])
def do_auth():
TP = request.args.get('transformed','')
P = request.args.get('password','').encode()
if P == test_password:
return 'Nice try, but that password is not allowed :P'
try:
res = validatePassword(TP, password_hashes, denyList=[test_password])
except Exception as e:
return str(e)
if res:
return 'Authed! Here is your flag: '+flag
else:
return 'Wrong Password'
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/BSidesCanberra/2021/crypto/Super_Cool_Facts_Server/EC.py | ctfs/BSidesCanberra/2021/crypto/Super_Cool_Facts_Server/EC.py | import Crypto.Util.number as nt
from binascii import *
#cybears 2020 params
p = 273540544991637969479760315194669352313
a = int(hexlify(b'cybears'), 16)
b = 2020
gx = 27880441596758306727342197655611673569
gy = 214924393757041059014541565759775133463
order = 273540544991637969474690923574060066154
class ec_point:
def __init__(self,E, x,y):
self.x = x % E.p
self.y = y % E.p
class ec_curve:
def __init__(self, p, a, b):
self.p = p
self.a = a
self.b = b
E = ec_curve(p,a,b)
G = ec_point(E, gx,gy)
O = ec_point(E, 0,1) #Point at Infinity
def ec_inverse(E, P):
return ec_point(E, P.x, (-P.y) % E.p)
def ec_isInf(P):
if P.x == 0 and P.y == 1:
return True
else:
return False
def ec_equals(P1,P2):
if P1.x == P2.x and P1.y == P2.y:
return True
else:
return False
def ec_add(E, P1,P2):
if ec_isInf(P1):
return P2
if ec_isInf(P2):
return P1
if ec_equals(P1, ec_inverse(E, P2)):
return O
if ec_equals(P1,P2):
m = (3*P1.x**2 + E.a) * nt.inverse(2*P1.y,E.p)
else:
m = (P2.y - P1.y)*nt.inverse((P2.x-P1.x) , E.p)
x3 = m*m - P1.x - P2.x
y3 = m*(P1.x - x3) - P1.y
return ec_point(E,x3,y3)
def ec_scalar(E,k,P):
result = O
Q = ec_point(E, P.x, P.y)
while (k > 0):
if k%2 == 1: #isodd(k)
result = ec_add(E,result, Q)
Q = ec_add(E,Q,Q)
k = k >> 1
return result
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/BSidesCanberra/2021/crypto/Super_Cool_Facts_Server/SuperCoolFactsServer.py | ctfs/BSidesCanberra/2021/crypto/Super_Cool_Facts_Server/SuperCoolFactsServer.py | #!/usr/bin/python3
#Super Cool Facts Server
#author: cybears_cipher
#python3 SuperCoolFactsServer.py
#requirements
#pip3 install pycrypto
## SERVER
# socat TCP-LISTEN:3141,reuseaddr,fork EXEC:"python3 ./SuperCoolFactsServer.py"
##CLIENT
# nc localhost 3141
import os
from random import SystemRandom, choice
import json
import EC
import Crypto.Cipher.AES as AES
import hashlib
from binascii import *
from SuperCoolFactsSecret import flag, cool_facts
randrange = SystemRandom().randrange
def pad(data,blocksize):
padlen = blocksize - (len(data)%blocksize)
return data + (padlen.to_bytes(1,byteorder="little"))*padlen
# Key Derivation Function
# input: Elliptic curve point (from EC library)
# output: 16-byte AES key
def kdf(shared_point):
s = str(shared_point.x) + str(shared_point.y)
return hashlib.sha1(s.encode("utf-8")).digest()[0:16]
def encrypt_message(message, key):
iv = os.urandom(16)
pmessage = pad(message,16)
a = AES.new(key, IV=iv, mode=AES.MODE_CBC)
cipher = a.encrypt(pmessage)
return {'iv':hexlify(iv).decode("utf-8"), 'cipher':hexlify(cipher).decode("utf-8")}
def decrypt_message(cipher, key, iv):
a = AES.new(key, IV=iv, mode=AES.MODE_CBC)
plain = a.decrypt(cipher)
return plain
def print_menu():
print("\nWelcome to the Super Cool Facts Server. Enter your choice:\n"
"(0) Print Cryptographic Parameters\n"
"(1) Perform ECDH handshake with server\n"
"(2) Get a Super Cool Fact!\n"
"(3) Submit hash of private key for flag\n"
"(q) quit\n")
def print_crypto_params():
print("params are:" + "\n")
print(" Elliptic curve E: y^2 = x^3 + ax + b mod p \n")
print(" p = {}".format(EC.p))
print(" a = {}".format(EC.a))
print(" b = {}".format(EC.b))
print(" Elliptic Curve G = (gx, gy) on E \n")
print(" gx = {}".format(EC.gx))
print(" gy = {}".format(EC.gy))
class Server:
def __init__(this):
this.handshake_done = False
this.key = None
this.privkey = randrange(2,EC.order)
this.pubkey = EC.ec_scalar(EC.E, this.privkey, EC.G)
this.hash_privkey = hashlib.sha1(str(this.privkey).encode("utf-8")).hexdigest()
if __name__ == "__main__":
cmd = ""
S = Server()
while cmd != "q":
print_menu()
cmd = input("Enter a value: ").strip()
#Print crypto parameters
if cmd == "0":
print_crypto_params()
continue
#Perform ECDH handshake with server
if cmd == "1":
print("My public point:")
j = {"x":S.pubkey.x, "y":S.pubkey.y}
print(json.dumps(j))
sender_public = input("Provide your public point:")
try:
spub = json.loads(sender_public)
except Exception as e:
print(e.args[0] +": JSON Error - quitting")
exit()
try:
if ('x' not in spub.keys()) or ('y' not in spub.keys()):
print("ERROR: need x,y keys in json")
exit()
except Exception as e:
print(e.args[0] +": JSON Error II - quitting")
exit()
if (type(spub['x']) != int) or (type(spub['y']) != int):
print("ERROR: x and y should be ints")
exit()
spub_point = EC.ec_point(EC.E, spub['x'], spub['y'])
shared_point = EC.ec_scalar(EC.E, S.privkey, spub_point)
S.key = kdf(shared_point)
S.handshake_done = True
continue
#Get Super Cool Fact!
if cmd == "2":
if S.handshake_done == False:
print("Need to perform handshake first!")
continue
cf = choice(cool_facts)
cipher = encrypt_message(cf.encode("utf-8"), S.key)
print(json.dumps(cipher))
continue
#Submit hash of private key for flag
if cmd == "3":
print("Provide the hex encoded SHA1 hash of the private key...")
print('Something like: hashlib.sha1(str(privkey).encode("utf-8")).hexdigest()')
answer = input().strip()
if answer == S.hash_privkey:
print("SUCCESS! Here's your flag: " + flag)
else:
print("INCORRECT")
exit()
if cmd == "q":
exit()
print("Incorrect option\n")
exit()
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/Platypwn/2023/crypto/Non_Zero_Knowledge_Proof/server.py | ctfs/Platypwn/2023/crypto/Non_Zero_Knowledge_Proof/server.py | from secrets import randbelow
from hashlib import sha256
from Crypto.Util.number import long_to_bytes
import os
def H(msg):
return sha256(msg).digest()
class NZKP:
def __init__(self):
self.p = 26758122283288400636617299098044383566046025569206625247969009149087529122945186469955025131558423244906400120599593226103736432404955901283002339947768387 # prime
self.q = (self.p - 1) // 2 # prime
self.g = 3
self.w = randbelow(self.q)
self.x = pow(self.g, self.w, self.p)
def encrypt(self, pubkey, flag):
secretkey = long_to_bytes(pow(pubkey, self.w ** 2, self.p)) # w**2 for doubled protection
return bytes(a ^ b for a, b in zip(H(secretkey), flag.encode()))
def ZKPannounce(self):
u = randbelow(self.q)
a = pow(self.g, u, self.p)
return u, a
def ZKPchallenge(self):
c = randbelow(self.q)
return c
def ZKPresponse(self, c, u, w):
return (c * u + w) % self.q
def ZKPverify(self, a, c, r, x):
return pow(self.g, r, self.p) == (pow(a, c, self.p) * x) % self.p
def main():
nzkp = NZKP()
flag = os.getenv("FLAG")
if not flag:
print("Did not find flag in env, crashing.")
exit(1)
print("--- GREETING ---")
print("Welcome to the private data vault. You can create a personalized time capsule that will be safe until "
"big quantum computers are around.\nTo protect against misuse, it employees mutual zero-knowledge "
"proofs.")
print("--- PARAMETERS ---")
print(f"Generator g: {nzkp.g}")
print(f"Safe prime p: {nzkp.p}")
while True:
try:
nzkp = NZKP()
print("\n--- NEW SESSION ---")
print("A new keypair was generated!")
print(f"Server public key x: {nzkp.x}")
print("--- KEY EXCHANGE ---")
# Pub key upload
upub = int(input("Enter user public key as long int> "))
y = upub % nzkp.p
if nzkp.g != y and 0 != y:
print(f"User public key saved as: {y}")
else:
print("Invalid public key!")
continue
# User key ZKP
print("You now have to prove that your public key is valid.")
a = int(input("Enter user announcement as long int> "))
c = nzkp.ZKPchallenge()
print(f"Your challenge is: {c}")
r = int(input("Enter user response as long int> "))
r = r % nzkp.q
if nzkp.ZKPverify(a, c, r, y):
print("Authentication succeeded!")
else:
print("Authentication failed!")
continue
# Server key ZKP
print("The server will now prove that its public key is valid.")
u, a = nzkp.ZKPannounce()
print(f"The announcement a is: {a}")
c = int(input("Enter user challenge c as long int> "))
c = c % nzkp.q
r = nzkp.ZKPresponse(c, u, nzkp.w)
print(f"The response r is: {r}")
print("You may now verify the knowledge as follows:")
print("pow(g, r, p) == (pow(a, c, p) * x) % p")
print("--- FLAG GEN ---")
print(f"Encrypted flag: {nzkp.encrypt(y, flag).hex()}")
print("--- END ---")
except:
print(f"An error occurred! Restarting...")
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/picoCTF/2019/crypto/AES-ABC/aes-abc.py | ctfs/picoCTF/2019/crypto/AES-ABC/aes-abc.py | #!/usr/bin/env python
from Crypto.Cipher import AES
from key import KEY
import os
import math
BLOCK_SIZE = 16
UMAX = int(math.pow(256, BLOCK_SIZE))
def to_bytes(n):
s = hex(n)
s_n = s[2:]
if 'L' in s_n:
s_n = s_n.replace('L', '')
if len(s_n) % 2 != 0:
s_n = '0' + s_n
decoded = s_n.decode('hex')
pad = (len(decoded) % BLOCK_SIZE)
if pad != 0:
decoded = "\0" * (BLOCK_SIZE - pad) + decoded
return decoded
def remove_line(s):
# returns the header line, and the rest of the file
return s[:s.index('\n') + 1], s[s.index('\n')+1:]
def parse_header_ppm(f):
data = f.read()
header = ""
for i in range(3):
header_i, data = remove_line(data)
header += header_i
return header, data
def pad(pt):
padding = BLOCK_SIZE - len(pt) % BLOCK_SIZE
return pt + (chr(padding) * padding)
def aes_abc_encrypt(pt):
cipher = AES.new(KEY, AES.MODE_ECB)
ct = cipher.encrypt(pad(pt))
blocks = [ct[i * BLOCK_SIZE:(i+1) * BLOCK_SIZE] for i in range(len(ct) / BLOCK_SIZE)]
iv = os.urandom(16)
blocks.insert(0, iv)
for i in range(len(blocks) - 1):
prev_blk = int(blocks[i].encode('hex'), 16)
curr_blk = int(blocks[i+1].encode('hex'), 16)
n_curr_blk = (prev_blk + curr_blk) % UMAX
blocks[i+1] = to_bytes(n_curr_blk)
ct_abc = "".join(blocks)
return iv, ct_abc, ct
if __name__=="__main__":
with open('flag.ppm', 'rb') as f:
header, data = parse_header_ppm(f)
iv, c_img, ct = aes_abc_encrypt(data)
with open('body.enc.ppm', 'wb') as fw:
fw.write(header)
fw.write(c_img)
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/insomnihack/2024/Quals/blockchain/UnnamedWeb3/webserver-b090a196cf855731600b234535767182f3d838904e2f3cb329469ef06d3b96f4.py | ctfs/insomnihack/2024/Quals/blockchain/UnnamedWeb3/webserver-b090a196cf855731600b234535767182f3d838904e2f3cb329469ef06d3b96f4.py | #!/usr/bin/env python3
from flask import Flask, send_from_directory, render_template, session, request
from flask_limiter import Limiter
from secrets import token_hex
import os
import requests
import helpers
FLAG = os.getenv("FLAG", "INS{fake_flag}")
CHALLENGE_DOMAIN = "insomnihack.flag"
app = Flask(__name__)
app.secret_key = os.getenv("FLASK_SECRET_KEY") or token_hex(16)
app.config["SESSION_PERMANENT"] = False
app.config["SESSION_TYPE"] = "filesystem"
def get_remote_address():
return request.access_route[0]
limiter = Limiter(get_remote_address,
app=app,
default_limits=["60 per minute", "10 per second"],
storage_uri="memory://")
@app.route("/", methods=["GET"])
def index():
if "subdomain" not in session:
session["subdomain"] = token_hex(8)
challenge_host = session["subdomain"] + "." + CHALLENGE_DOMAIN
deployed = False
rpc = None
wallet = None
contract = None
if "instance_id" in session:
if helpers.is_instance_running(session["instance_id"]):
deployed = True
rpc = session["rpc"]
wallet = session["wallet"]
contract = session["contract"]
else:
del session["instance_id"]
del session["rpc"]
del session["wallet"]
del session["contract"]
return render_template(
"index.html",
challenge_host=challenge_host,
deployed=deployed,
rpc=rpc,
wallet=wallet,
contract=contract,
)
@app.route("/static/<path:path>", methods=["GET"])
def static_file(path):
return send_from_directory("static", path)
@app.route("/domain-query", methods=["GET"])
def dns_query_get():
domain = request.args.get("domain")
if domain is None:
return "Invalid request", 400
if "instance_id" not in session:
return "Instance not running", 400
return helpers.resolve_domain(session["instance_id"], domain)
@app.route("/transfer-codes", methods=["GET"])
def transfer_codes():
if "instance_id" not in session:
return "Invalid session", 400
contract = helpers.get_contract(session["instance_id"])
events = contract.events.TransferInitiated().get_logs(fromBlock=0)
transfer_codes = []
for event in events:
domain = event["args"]["domain"]
recipient = event["args"]["destination"]
code = helpers.generate_transfer_code(domain, recipient)
transfer_codes.append({"domain": domain, "recipient": recipient, "code": code})
return transfer_codes
@app.route("/transfer-code/<req_domain>/<req_recipient>", methods=["GET"])
def transfer_code(req_domain, req_recipient):
if "instance_id" not in session:
return "Invalid session", 400
contract = helpers.get_contract(session["instance_id"])
events = contract.events.TransferInitiated().get_logs(fromBlock=0)
for event in events:
domain = event["args"]["domain"]
recipient = event["args"]["destination"]
if domain == req_domain and recipient.lower() == req_recipient.lower():
return helpers.generate_transfer_code(domain, recipient), 200
return "Transfer not initiated", 401
@app.route("/send-flag", methods=["POST"])
def send_flag():
if "subdomain" not in session:
return "Invalid session", 400
if "instance_id" not in session:
return "Instance not running", 400
port = 80
if "port" in request.args:
try:
port = int(request.args["port"])
except:
return "Invalid port", 400
if port < 1 or port > 65535:
return "Invalid port", 400
# Resolve the domain by calling the `resolveIp` function of the contract
host = helpers.resolve_domain(
session["instance_id"], session["subdomain"] + "." + CHALLENGE_DOMAIN
)
if host is None or host == "":
return "No DNS entry for this domain", 400
try:
requests.post(f"http://{host}:{port}", data=FLAG, timeout=2)
except Exception as e:
return str(e)
return f"Flag sent to {host}"
@app.route("/create-instance", methods=["POST"])
@limiter.limit("2 per minute; 3 per 10 minutes; 4 per 20 minutes")
def create():
# Remark: The instance is destroyed after 20 minutes
instance = helpers.create_instance()
if instance["status"] == "success":
session["instance_id"] = instance["instance_id"]
session["rpc"] = instance["rpc"]
session["wallet"] = instance["wallet"]
session["contract"] = instance["contract"]
return instance
@app.route("/stop-instance", methods=["POST"])
def stop():
if "instance_id" in session:
helpers.stop_instance(session["instance_id"])
del session["instance_id"]
del session["rpc"]
del session["wallet"]
del session["contract"]
return {"status": "success", "message": "Instance stopped"}
else:
return {"status": "failed", "message": "No instance running"}
if __name__ == "__main__":
app.run(debug=True)
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/insomnihack/2024/Quals/misc/PPP/ppp.py | ctfs/insomnihack/2024/Quals/misc/PPP/ppp.py | from os import popen
import hashlib, time, math, subprocess, json
def response(res):
print(res + ' | ' + popen('date').read())
exit()
def generate_nonce():
current_time = time.time()
rounded_time = round(current_time / 60) * 60 # Round to the nearest 1 minutes (60 seconds)
return hashlib.sha256(str(int(rounded_time)).encode()).hexdigest()
def is_valid_proof(data, nonce):
DIFFICULTY_LEVEL = 6
guess_hash = hashlib.sha256(f'{data}{nonce}'.encode()).hexdigest()
return guess_hash[:DIFFICULTY_LEVEL] == '0' * DIFFICULTY_LEVEL
class Blacklist:
def __init__(self, data, nonce):
self.data = data
self.nonce = nonce
def get_data(self):
out = {}
out['data'] = self.data if 'data' in self.__dict__ else ()
out['nonce'] = self.nonce if 'nonce' in self.__dict__ else ()
return out
def add_to_blacklist(src, dst):
for key, value in src.items():
if hasattr(dst, '__getitem__'):
if dst[key] and type(value) == dict:
add_to_blacklist(value, dst.get(key))
else:
dst[key] = value
elif hasattr(dst, key) and type(value) == dict:
add_to_blacklist(value, getattr(dst, key))
else:
setattr(dst, key, value)
def lists_to_set(data):
if type(data) == dict:
res = {}
for key, value in data.items():
res[key] = lists_to_set(value)
elif type(data) == list:
res = ()
for value in data:
res = (*res, lists_to_set(value))
else:
res = data
return res
def is_blacklisted(json_input):
bl_data = blacklist.get_data()
if json_input['data'] in bl_data['data']:
return True
if json_input['nonce'] in bl_data['nonce']:
return True
json_input = lists_to_set(json_input)
add_to_blacklist(json_input, blacklist)
return False
if __name__ == '__main__':
blacklist = Blacklist(['dd9ae2332089200c4d138f3ff5abfaac26b7d3a451edf49dc015b7a0a737c794'], ['2bfd99b0167eb0f400a1c6e54e0b81f374d6162b10148598810d5ff8ef21722d'])
try:
json_input = json.loads(input('Prove your work 😼\n'))
except Exception:
response('no')
if not isinstance(json_input, dict):
response('message')
data = json_input.get('data')
nonce = json_input.get('nonce')
client_hash = json_input.get('hash')
if not (data and nonce and client_hash):
response('Missing data, nonce, or hash')
server_nonce = generate_nonce()
if server_nonce != nonce:
response('nonce error')
if not is_valid_proof(data, nonce):
response('Proof of work is invalid')
server_hash = hashlib.sha256(f'{data}{nonce}'.encode()).hexdigest()
if server_hash != client_hash:
response('Hash does not match')
if is_blacklisted(json_input):
response('blacklisted PoW')
response('Congratulation, You\'ve proved your work 🎷🐴')
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/insomnihack/2024/Quals/misc/Terminal_Pursuit/gui.py | ctfs/insomnihack/2024/Quals/misc/Terminal_Pursuit/gui.py | menu = """
______________________
| __________________ |
| | | |
| | Terminal pursuit | |
| |__________________| |
| |
| What to do? |
| 1) Play |
| 2) Scoreboards |
| 3) Exit |
|______________________|
"""
category = """
______________________
| __________________ |
| | | |
| | Terminal pursuit | |
| |__________________| |
| |
| Pick a category: |
| - books |
| - ctf |
| - miscgod |
|______________________|
"""
username = """
______________________
| __________________ |
| | | |
| | Terminal pursuit | |
| |__________________| |
| |
| Who is playing? |
|______________________|
"""
scoreboard_head = """
================
= Scoreboard =
================
"""
scoreboard_tail = """
================
"""
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/insomnihack/2024/Quals/misc/Terminal_Pursuit/main.py | ctfs/insomnihack/2024/Quals/misc/Terminal_Pursuit/main.py | #!/usr/bin/env python3
import string
import subprocess
import sys
import os
import gui
alphabet = "abcdefghijklmnopqrstuvwxyz/,:;[]_-."
prefix = "/app/quizzes/"
results = prefix + "pts.txt"
def menu():
print(gui.menu)
choice = int(input("> "))
if choice != 1 and choice != 2:
exit(0)
return choice
def get_user_string(text):
print(text)
s = input("> ").lower()
for c in s:
if c not in alphabet:
exit(0)
return s[:7]
def run_quizz(username, category):
command = f"make run quizz=\"{prefix + category}\" username=\"{username}\""
os.system(command)
def play():
username = get_user_string(gui.username)
category = get_user_string(gui.category)
run_quizz(username, category)
# TODO: improve and combine categories scores
def scoreboard():
scores = {}
for line in open(results, 'r').readlines():
k = line.split(' ')[0]
v = int(line.strip().split(',')[-1][:-1])
scores[k] = v
scores = sorted(scores.items(), reverse=True, key=lambda item: item[1])
print(gui.scoreboard_head)
for i, r in enumerate(scores):
print(f" {i+1}. {r[0]}\t{r[1]}")
print(gui.scoreboard_tail)
def main():
while True:
try:
choice = menu()
if choice == 1:
play()
elif choice == 2:
scoreboard()
except Exception:
exit()
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/insomnihack/2024/Quals/web/InsoBank/api/exec_transfers.py | ctfs/insomnihack/2024/Quals/web/InsoBank/api/exec_transfers.py | #!/usr/local/bin/python
import psycopg2
import mysql.connector
import sqlite3
import os
MYSQL_DB_HOST = os.getenv("MYSQL_HOST") or 'mysql'
MYSQL_DB_USER = os.getenv("MYSQL_USER") or 'user'
MYSQL_DB_PASSWORD = os.getenv("MYSQL_PASSWORD") or 'password'
MYSQL_DB_DATABASE = os.getenv("MYSQL_DB") or 'inso24'
PG_DB_HOST = os.getenv("PG_HOST") or 'pg'
PG_DB_USER = os.getenv("PG_USER") or 'postgres'
PG_DB_PASSWORD = os.getenv("PG_PASSWORD") or 'postgres'
PG_DB_DATABASE = os.getenv("PG_DB") or 'inso24'
def get_db(type='mysql'):
if type == 'mysql':
conn = mysql.connector.connect(
host=MYSQL_DB_HOST,
user=MYSQL_DB_USER,
password=MYSQL_DB_PASSWORD,
database=MYSQL_DB_DATABASE
)
elif type == 'sqlite':
conn = sqlite3.connect("/app/db/db.sqlite")
elif type == 'pg':
conn = psycopg2.connect(
host=PG_DB_HOST,
database=PG_DB_DATABASE,
user=PG_DB_USER,
password=PG_DB_PASSWORD)
return conn
conn = get_db()
cursor = conn.cursor()
connpg = get_db(type='pg')
cursorpg = connpg.cursor()
cursorpg.execute('''
SELECT DISTINCT batchid FROM batch_transactions WHERE verified = true and executed = false
''')
for (batchid,) in cursorpg.fetchall():
TRANSFERS = {}
cursorpg.execute('''
SELECT id,sender,recipient,amount FROM batch_transactions WHERE batchid = %s AND verified = true AND executed = false
''',(batchid,))
transactions = cursorpg.fetchall()
for (txid,sender,recipient,amount) in transactions:
cursor.execute('''
UPDATE batch_transactions SET executed = true WHERE id = %s
''',(txid,))
cursorpg.execute('''
UPDATE batch_transactions SET executed = true WHERE id = %s
''',(txid,))
TRANSFERS[recipient] = amount if recipient not in TRANSFERS.keys() else TRANSFERS[recipient] + amount
for recipient in TRANSFERS:
cursor.execute('''
UPDATE accounts SET balance = balance + %s WHERE id = %s
''', (TRANSFERS[recipient], recipient))
cursor.execute('''
UPDATE batches SET executed = true WHERE id = %s
''',(batchid,))
connpg.commit()
conn.commit()
connpg.close()
conn.close()
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/insomnihack/2024/Quals/web/InsoBank/api/app.py | ctfs/insomnihack/2024/Quals/web/InsoBank/api/app.py | import os
import shutil
import mysql.connector
from flask import Flask, request, jsonify, send_from_directory, redirect
from werkzeug.utils import secure_filename
from flask_jwt_extended import JWTManager, jwt_required, get_jwt_identity, get_jwt, create_access_token
from flask_cors import CORS
import base64
import time
import psycopg2
from time import sleep
import uuid
from flask_jwt_extended import create_access_token
from flask_jwt_extended import get_jwt_identity
from flask_jwt_extended import jwt_required
from flask_jwt_extended import JWTManager
app = Flask(__name__)
cors = CORS(app, resources={r"/*": {"origins": "*"}})
app.config["JWT_SECRET_KEY"] = os.urandom(64)
jwt = JWTManager(app)
MYSQL_DB_HOST = os.getenv("MYSQL_HOST") or 'mysql'
MYSQL_DB_USER = os.getenv("MYSQL_USER") or 'root'
MYSQL_DB_PASSWORD = os.getenv("MYSQL_PASSWORD") or 'password'
MYSQL_DB_DATABASE = os.getenv("MYSQL_DB") or 'inso24'
PG_DB_HOST = os.getenv("PG_HOST") or 'pg'
PG_DB_USER = os.getenv("PG_USER") or 'postgres'
PG_DB_PASSWORD = os.getenv("PG_PASSWORD") or 'postgres'
PG_DB_DATABASE = os.getenv("PG_DB") or 'inso24'
FLAG = os.getenv("FLAG") or 'INS{fake-flag}'
def get_db(type='mysql'):
if type == 'mysql':
conn = mysql.connector.connect(
host=MYSQL_DB_HOST,
user=MYSQL_DB_USER,
password=MYSQL_DB_PASSWORD,
database=MYSQL_DB_DATABASE
)
elif type == 'pg':
conn = psycopg2.connect(
host=PG_DB_HOST,
database=PG_DB_DATABASE,
user=PG_DB_USER,
password=PG_DB_PASSWORD)
return conn
@app.route("/accounts", methods=['GET','PUT'])
@jwt_required()
def accounts():
results = {}
userid = get_jwt_identity()
conn = get_db()
cursor = conn.cursor()
if request.method == "PUT":
for accid in request.json:
cursor.execute("UPDATE accounts SET name = %s WHERE id = %s AND userid = %s",(request.json[accid]["name"],accid,userid))
conn.commit()
cursor.execute('''
SELECT id,name,balance FROM accounts WHERE userid = %s
''', (userid,))
for (accountid,name,balance) in cursor.fetchall():
if balance > 13.37:
results[accountid] = {'name': name, 'balance': balance, 'flag': FLAG}
else:
results[accountid] = {'name': name, 'balance': balance}
conn.close()
return jsonify(results)
@app.route("/profile", methods=['GET','PUT'])
@jwt_required()
def profile():
userid = get_jwt_identity()
conn = get_db()
cursor = conn.cursor()
if request.method == "PUT":
cursor.execute('''
UPDATE users SET firstname = %s, lastname = %s, email = %s WHERE id = %s
''', (request.json.get("firstname"),request.json.get("lastname"),request.json.get("email"),userid))
conn.commit()
cursor.execute('''
SELECT id,firstname,lastname,email FROM users WHERE id = %s
''', (userid,))
(userid,firstname,lastname,email) = cursor.fetchone()
conn.close()
return jsonify({'id': userid, 'firstname': firstname, 'lastname': lastname, 'email': email})
@app.route("/transactions", methods=['GET','DELETE'])
@jwt_required()
def transactions():
userid = get_jwt_identity()
conn = get_db()
cursor = conn.cursor()
batchid = request.args.get("batchid")
if request.method == "DELETE":
connpg = get_db(type='pg')
cursorpg = connpg.cursor()
cursorpg.execute("DELETE FROM batch_transactions WHERE batchid = %s AND id = %s", (batchid,request.json.get("txid")))
connpg.commit()
connpg.close()
cursor.execute("DELETE FROM batch_transactions WHERE batchid = %s and id = %s", (batchid,request.json.get("txid")))
conn.commit()
cursor.execute('''
SELECT bt.id, bt.batchid, bt.recipient, a.name, bt.amount, bt.verified, bt.executed FROM batch_transactions bt LEFT OUTER JOIN accounts a ON a.id = bt.recipient WHERE bt.batchid = %s
''', (batchid,))
results = []
try:
for (txid,batchid,recipient,recipientname,amount,verified,executed) in cursor.fetchall():
results.append({'txid':txid,'batchid':batchid,'recipient':recipient,'recipientname':recipientname,'amount':amount,'verified':verified,'executed':executed})
except:
pass
conn.close()
return jsonify(results)
@app.route("/batch/new", methods=['POST'])
@jwt_required()
def newbatch():
userid = get_jwt_identity()
batchid = str(uuid.uuid4())
senderid = request.json.get("senderid")
conn = get_db()
cursor = conn.cursor()
cursor.execute('''
SELECT userid FROM accounts WHERE id = %s
''',(senderid,))
data = cursor.fetchone()
if data == None or data[0]!=userid:
return jsonify({"error":"Invalid account"})
cursor.execute('''
INSERT INTO batches(id,senderid,userid) VALUES (%s,%s,%s)
''', (batchid,senderid,userid))
conn.commit()
conn.close()
return redirect("/batches")
@app.route("/batches", methods=['GET','DELETE'])
@jwt_required()
def batches():
userid = get_jwt_identity()
conn = get_db()
cursor = conn.cursor()
if request.method == "DELETE":
cursor.execute('''
SELECT userid,executed,verified FROM batches WHERE id = %s
''', (request.json.get("batchid"),))
(buserid,verified,executed) = cursor.fetchone()
if verified or executed:
return jsonify({"error":"Cannot delete a verified or executed batch"})
if buserid != userid:
return jsonify({"error":"Cannot delete batch"})
connpg = get_db(type='pg')
cursorpg = connpg.cursor()
cursorpg.execute("DELETE FROM batch_transactions WHERE batchid = %s",(request.json.get("batchid"),))
connpg.commit()
connpg.close()
cursor.execute('''
DELETE FROM batch_transactions WHERE batchid = %s
''', (request.json.get("batchid"),))
cursor.execute('''
DELETE FROM batches WHERE id = %s
''', (request.json.get("batchid"),))
conn.commit()
cursor.execute('''
SELECT b.id,b.senderid,a.name,b.executed,b.verified FROM batches b LEFT OUTER JOIN accounts a ON a.id = b.senderid WHERE b.userid = %s
''',(userid,))
batches = []
for (batchid,senderid,sendername,executed,verified) in cursor.fetchall():
batches.append({'batchid':batchid,'senderid':senderid,'sendername':sendername,'executed':executed,'verified':verified})
return jsonify(batches)
@app.route("/login", methods=['POST'])
def login():
username = request.json.get('username')
password = request.json.get('password')
conn = get_db()
cursor = conn.cursor()
cursor.execute('''
SELECT id FROM users WHERE username = %s AND password = %s
''', (username,password))
data = cursor.fetchone()
conn.close()
if data == None:
return jsonify({"error":"Login failed"})
access_token = create_access_token(identity=data[0])
return jsonify({"userid":data[0],"jwt":access_token})
@app.route("/register", methods=['POST'])
def register():
username = request.json.get('username')
password = request.json.get('password')
if len(password) < 15:
return jsonify({"error":"Strong password required for security reasons"})
conn = get_db()
cursor = conn.cursor()
cursor.execute('''
SELECT count(*) FROM users WHERE username = %s
''', (username,))
data = cursor.fetchone()
if data[0] != 0:
return jsonify({"error":"User already exists"})
cursor.execute('''
INSERT INTO users (username,password) VALUES (%s,%s)
''',(username,password))
userid = cursor.lastrowid
cursor.execute('''
INSERT INTO accounts(id, userid, name, balance) VALUES (%s,%s,%s,%s)
''',(str(uuid.uuid4()),userid,'Savings account',0))
cursor.execute('''
INSERT INTO accounts(id, userid, name, balance) VALUES (%s,%s,%s,%s)
''',(str(uuid.uuid4()),userid,'Current account',10))
cursor.execute('''
INSERT INTO accounts(id, userid, name, balance) VALUES (%s,%s,%s,%s)
''',(str(uuid.uuid4()),userid,'Checkings account',0))
conn.commit()
conn.close()
access_token = create_access_token(identity=userid)
return jsonify({"userid":userid,"jwt":access_token})
@app.route("/logout", methods=['GET'])
@jwt_required()
def logout():
return jsonify({"message":"Logged out"})
@app.route("/validate", methods=['POST'])
@jwt_required()
def validate():
userid = get_jwt_identity()
batchid = request.json.get("batchid")
conn = get_db()
cursor = conn.cursor()
cursor.execute("SELECT id,senderid FROM batches WHERE id = %s AND userid = %s", (batchid,userid))
data = cursor.fetchone()
if data == None or data[0] != batchid:
return jsonify({"error":"Invalid batchid"})
senderid = data[1]
cursor.execute("LOCK TABLES batch_transactions WRITE, accounts WRITE, batches WRITE")
cursor.execute("SELECT sum(amount) FROM batch_transactions WHERE batchid = %s", (batchid,))
data = cursor.fetchone()
if data == None or data[0] == None:
cursor.execute("UNLOCK TABLES")
conn.close()
return jsonify({"error":"Invalid batch"})
total = data[0]
cursor.execute('''
SELECT balance FROM accounts WHERE id = %s
''', (senderid,))
data = cursor.fetchone()
balance = data[0] if data else 0
if total > balance:
cursor.execute("UNLOCK TABLES")
conn.close()
return jsonify({"error":"Insufficient balance ("+str(total)+" > " + str(balance) +")"})
cursor.execute('''
UPDATE accounts SET balance = (balance - %s) WHERE id = %s
''',(total,senderid))
cursor.execute('''
UPDATE batch_transactions SET verified = true WHERE batchid = %s;
''',(batchid,))
connpg = get_db(type='pg')
cursorpg = connpg.cursor()
cursorpg.execute('''
UPDATE batch_transactions SET verified = true WHERE batchid = %s
''',(batchid,))
connpg.commit()
connpg.close()
cursor.execute('''
UPDATE batches SET verified = true WHERE id = %s;
''',(batchid,))
cursor.execute('''
UNLOCK TABLES;
''')
conn.close()
return redirect("/batches")
@app.route("/transfer", methods=['POST'])
@jwt_required()
def transfer():
userid = get_jwt_identity()
txid = str(uuid.uuid4())
amount = request.json.get('amount')
recipient = request.json.get('recipient')
batchid = request.json.get('batchid')
if not float(amount) > 0:
return jsonify({"error":"Invalid amount"})
conn = get_db()
cursor = conn.cursor()
cursor.execute('''
SELECT count(*) FROM batches WHERE id = %s AND userid = %s AND verified = false
''',(batchid,userid))
data = cursor.fetchone()
if data[0] != 1:
conn.close()
return jsonify({"error":"Invalid batchid"})
cursor.execute('''
SELECT userid FROM accounts WHERE id = %s
''', (recipient,))
data = cursor.fetchone()
if data == None or data[0] != userid:
conn.close()
return jsonify({"error": "Recipient account does not belong to you"})
cursor.execute('''
SELECT count(*) FROM batch_transactions WHERE batchid = %s AND recipient = %s
''',(batchid,recipient))
data = cursor.fetchone()
if data[0] > 0:
conn.close()
return jsonify({"error":"You can only have one transfer per recipient in a batch"})
cursor.execute('''
SELECT balance FROM accounts WHERE id = (SELECT senderid FROM batches WHERE id = %s)
''', (batchid,))
data = cursor.fetchone()
balance = data[0]
connpg = get_db(type='pg')
cursorpg = connpg.cursor()
cursorpg.execute('''
LOCK TABLE batch_transactions;
INSERT INTO batch_transactions (id,batchid,recipient,amount) SELECT %s,%s,%s,%s WHERE (SELECT coalesce(sum(amount),0)+%s FROM batch_transactions WHERE batchid = %s) <= %s
''', (txid,batchid,recipient,amount,amount,batchid,balance))
connpg.commit()
connpg.close()
cursor.execute('''
INSERT INTO batch_transactions (id,batchid,recipient,amount) SELECT %s,%s,%s,%s WHERE (SELECT coalesce(sum(amount),0)+%s FROM batch_transactions WHERE batchid = %s) <= %s
''', (txid,batchid,recipient,amount,amount,batchid,balance))
conn.commit()
conn.close()
return redirect("/transactions?batchid="+batchid)
if __name__ == '__main__':
app.run(debug=False,host='0.0.0.0')
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/insomnihack/2023/Quals/crypto/GCM/parameters-43dd0692544fb3f248e60cc2f09597974e0aa659e299cfcd2167d624d4e528b4.py | ctfs/insomnihack/2023/Quals/crypto/GCM/parameters-43dd0692544fb3f248e60cc2f09597974e0aa659e299cfcd2167d624d4e528b4.py | m1 = b'ySsIQtp0JKMuoZ2llTPI8PaFPzeYPvY+R87SwM3agHWmBs+Xh3cGFPt3JRSR1V37jXf0vQ5OjPiVRGkCisVNX2jP1U9jFH0+xIm4h3CW2Vb15fHlDFLxXIxiiYd2aBkwvA+2QfWYx1zPad7092tz+srM6E66FlmFEV1RH02evIWipVud5nI9Gt9FuvYCvaF0O02DVhZ/wIoktcN4IdWjIBAIONV+1uRQ6ROqOwzBBa/hcBTpj5a/2arGjp0yjEF7V78fCRESiqY7cC0lGjLjzF9l949ulpQkvyGRlZBhA4YPILnY9UPW4V1MU7RSP7fjORsHZbB60gsMaw6Lj6xLgIHOKhUSP52RPREoIt7mQV/FFR15UIkBgp1lWRr14neHq/Vp+5NmMrKGOjybTgS6Bn0F/KFTb1s145UAUWq1OEX0hwu+z3R9SSTWDfdyr+JhWneJ0INTLAUPg6WF5XkSEAprIbUqI+ZoC6fjDnYTWAWQ678CCc05dHM6+uScOGneKwCiEkXUABK825iXHsBUmRDjfmSeskT3UAN9zlcun8k96pZr+UwmdEP1FFbBuA0YMOVmN3gulwJS7WBQFiaA7KzbGdH7ggCh8QTYENwvWtSyyJbxsBVsqkijy4VizT32D6hzUgThTIH0NZw6jLe3thwphOZm4vZ6NkgqpLeKy+cHFME2GY6d45HdhAXaXfrtlNo1r/2DEgLlTtJD6g2xb/RP/lyplhbLFCye5kdMwbcoa4aw2O/hkZ1fUcdTg5cyAGvNyS540dR/rxwuwLw/bTdgk+atBFCJIeC+7v0eDojy0K4SKPnMa1IpaKCoR2/0scEJAbhxaiVsLsXOrNGJNdG9WMqX8xf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hCh5VHSKg0UQ9uFj0iqqfwVBYCKkjbkswyD2rXqCvNEO9SymKWoqhhtFc5Ut+fQQR6N8VMNkPkyiQqbhfusxe4JmFgFxvAxHt45eGZQt3gP0zO4XdCGUtrwO8hSEHgJinRUQOO9brrPQ/d0/Cgl66e48gFDADMngu1VI82tgZkWjJ+7D/hqVabzr8XwmOxIyGI+QEqq3iRnW8bEp71rNgSNmAovPVbamAm9kJa019o4uHqgVGZKpZXZh7Dgb8NRHNPXeMhhQXaxMPgmUqizB5KLwheSdClaKis5gIh80VI3U7IwwkvZVEonIilWbqHxKcp7/4L4xi+GYDMHtCmLEmaK7ZxlFi4MKCgnBvsiZiHAKB+NbucdpFY9Zm4/vVjDLcbJ0qGCeLEqfrgfl7vHFYhzyFpdyn1uIVKM+/4HpgpNMXuo1aBUC9IC1lT9hZJIPIG6UHhJdcg+E2HPHXqEzVccmSi5sREkFDTyWUtxUnDS5ySbF9eJenbewpO3XxsS1ScSW9+88B1tTEzsYavSSDOWcoEmTvjBuLPId+dQWwF8VJ5IVksgDP9eRVBDGizKR+syp5T+YEM30eh9bO2vuNtieVlHIhFxbrvSA1rImVAXRig3/4Rc+D | python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | true |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/insomnihack/2023/Quals/web/webpix/bot.py | ctfs/insomnihack/2023/Quals/web/webpix/bot.py | #!/usr/bin/python3
from flask import Flask, request
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.support.ui import WebDriverWait
from waitress import serve
import os
app = Flask(__name__)
def visit(url):
options = Options()
options.add_argument('headless')
options.add_argument('no-sandbox')
driver = webdriver.Chrome('./chromedriver', options=options)
driver.get(os.environ.get("URL"))
driver.add_cookie({'name': 'flag','value': os.environ.get("FLAG")})
try:
driver.get(url)
WebDriverWait(driver, 5).until(lambda r: r.execute_script('return document.readyState') == 'complete')
except:
pass
finally:
driver.quit()
@app.route("/visit", methods=["POST"])
def response():
try:
url = request.json.get("url")
assert(url.startswith('https://') or url.startswith('http://'))
visit(url)
return {"Success": "1"}
except:
return {"Failure": "1"}
@app.errorhandler(404)
def error_handler(error):
return "<h1>URL not found</h1><br/>", 404
if __name__ == "__main__":
serve(app, host="0.0.0.0", port=8888) | python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/insomnihack/2022/Quals/web/Vault/webapp/app/app.py | ctfs/insomnihack/2022/Quals/web/Vault/webapp/app/app.py | #!/usr/bin/python3
from flask import Flask, render_template, jsonify, request, session
from flask.sessions import SecureCookieSessionInterface
import pyodbc
from flask_session import Session
import os
import re
app = Flask(__name__)
app.secret_key = os.urandom(24)
app.config['SESSION_TYPE'] = 'FileSystemSessionInterface'
app.config['SESSION_FILE_DIR'] = '/tmp'
admin_conn_str = ("Driver={ODBC Driver 17 for SQL Server};"
"Server=db,1433;"
"Database=Vault;"
"UID=sa;"
"PWD=" + os.environ.get("SA_PASSWORD") + ";")
SESSION_COOKIE_HTTPONLY = True
def is_safe(s):
pattern = re.compile("^[a-zA-Z0-9-_!]+$")
if pattern.match(s):
return True
return False
@app.route('/')
def index():
if "username" in session:
return render_template("index.html", login="Logout")
else:
return render_template("index.html", login="Login")
@app.route('/api/secrets', methods=['GET','POST'])
def secrets():
if "username" in session and "password" in session:
if request.method == 'POST':
conn_str = ("Driver={ODBC Driver 17 for SQL Server};"
"Server=db,1433;"
"Database=Vault;"
"UID=" + session["username"] + ";"
"PWD=" + session["password"])
conn = pyodbc.connect(conn_str, autocommit=True)
cursor = conn.cursor()
cursor.execute("INSERT INTO dbo.Vault (username,secret_name,secret_value) VALUES (?,?,?)", session["username"],request.form["secret_name"],request.form["secret_value"])
cursor.execute("INSERT INTO dbo.Stats (username) VALUES (?)", session["username"])
cursor.close()
conn.close()
return {'status':'OK'}
else:
conn_str = ("Driver={ODBC Driver 17 for SQL Server};"
"Server=db,1433;"
"Database=Vault;"
"UID=" + session["username"] + ";"
"PWD=" + session["password"])
conn = pyodbc.connect(conn_str)
cursor = conn.cursor()
sql = "SELECT secret_name,secret_value FROM dbo.Vault ;"
cursor.execute(sql)
res = cursor.fetchall()
ret = []
for row in res:
ret.append({'secret_name':row[0], 'secret_value':row[1]})
cursor.close()
conn.close()
return {'status':'OK','result':ret}
else:
return {'status': 'KO','msg':'Not logged in!'}
@app.route('/api/register', methods=['POST'])
def register():
credentials = request.form
if is_safe(credentials["username"]) and is_safe(credentials["password"]):
try:
conn = pyodbc.connect(admin_conn_str, autocommit=True)
cursor = conn.cursor()
sql = "EXEC dbo.CreateUser @login=?,@password=?"
cursor.execute(sql,credentials["username"],credentials["password"])
cursor.close()
conn.close()
return {'status':'OK'}
except:
return {'status':'KO','msg':'Registration error'}
else:
return {'status':'KO','msg':'Invalid user or pwd'}
@app.route('/api/login', methods=['POST'])
def login():
credentials = request.form
if is_safe(credentials["username"]) and is_safe(credentials["password"]):
try:
conn_str = ("Driver={ODBC Driver 17 for SQL Server};"
"Server=db,1433;"
"Database=Vault;"
"UID="+credentials["username"] +";"
"PWD="+credentials["password"]+";")
conn = pyodbc.connect(conn_str, autocommit=True)
session["username"] = credentials["username"]
session["password"] = credentials["password"]
if credentials["username"] == "admin":
session["admin"] = 1;
return {'status':'OK'}
except:
return {'status':'KO','msg':'Login failed'}
else:
return {'status':'KO','msg':'Invalid user or pwd'}
@app.route('/api/logout')
def logout():
del session["username"]
del session["password"]
return {'status':'OK'}
@app.route('/api/stats')
def stats():
if not "admin" in session or session["admin"] != 1:
return {'status':'KO', 'msg': 'You are not admin'}
else:
try:
conn_str = ("Driver={ODBC Driver 17 for SQL Server};"
"Server=db,1433;"
"Database=Vault;"
"UID=" + session["username"] + ";"
"PWD=" + session["password"])
conn = pyodbc.connect(conn_str)
cursor = conn.cursor()
sql = "SELECT inserttime FROM dbo.Stats WHERE username = '" + request.args.get("username") + "'"
cursor.execute(sql)
res=cursor.fetchall()
ret=[]
for row in res:
ret.append({'inserttime':row[0]})
cursor.close()
conn.close()
return {'status':'OK','results':ret}
except:
return {'status':'NOK'}
@app.route('/api/report', methods=['POST'])
def contact():
url = request.form["url"]
pattern = re.compile("^https?:\/\/")
if len(url) > 0 and pattern.match(url):
try:
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.chrome.options import Options
import time
session_serializer = SecureCookieSessionInterface().get_signing_serializer(app)
adminsession = dict()
adminsession["admin"] = 1
adminsession["username"] = "admin"
adminsession["password"] = os.environ.get("ADMIN_PWD")
session_cookie = session_serializer.dumps(dict(adminsession))
chrome_options = Options()
chrome_options.headless = True
chrome_options.add_argument('--no-sandbox')
driver = webdriver.Chrome("/app/chromedriver", options=chrome_options)
driver.set_page_load_timeout(30)
driver.get("http://" + os.environ.get("VHOST") + "/")
time.sleep(1)
driver.add_cookie({"name": "session", "value":session_cookie,"httpOnly": True})
driver.get(url)
time.sleep(30)
driver.close()
return {'status':'OK'}
except:
return {'status':'KO','msg':'Error checking page'}
return {'status':'KO','msg':'Invalid URL'}
if __name__ == '__main__':
app.run(debug=False, host='0.0.0.0')
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/WaniCTF/2023/pwn/shell-basic/solver_template.py | ctfs/WaniCTF/2023/pwn/shell-basic/solver_template.py | from pwn import *
pc = process("./chall")
# pc = remote("",)
shell_code = b"" # PUT YOUR SHELL CODE HERE
pc.sendline(shell_code)
pc.interactive()
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/WaniCTF/2023/crypto/fusion/chall.py | ctfs/WaniCTF/2023/crypto/fusion/chall.py | from Crypto.PublicKey import RSA
RSAkeys = RSA.generate(2048)
p = RSAkeys.p
q = RSAkeys.q
n = RSAkeys.n
e = RSAkeys.e
m = b"FAKE{<REDACTED>}"
c = pow(int.from_bytes(m, "big"), e, n)
mask = int("55" * 128, 16)
r = p & mask
mask = mask << 1
r += q & mask
print(f"n = {n}")
print(f"e = {e}")
print(f"c = {c}")
print(f"r = {r}")
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/WaniCTF/2023/crypto/dsa/chall.py | ctfs/WaniCTF/2023/crypto/dsa/chall.py | from Crypto.Util.number import isPrime
from hashlib import sha256
from os import getenv
from random import randbytes
import re
q = 139595134938137125662213161156181357366667733392586047467709957620975239424132898952897224429799258317678109670496340581564934129688935033567814222358970953132902736791312678038626149091324686081666262178316573026988062772862825383991902447196467669508878604109723523126621328465807542441829202048500549865003
p = 2 * q + 1
g = 2
assert isPrime(p)
assert isPrime(q)
FLAG = getenv("FLAG", "FAKE{NOTE:THIS_IS_NOT_THE_FLAG}")
assert len(FLAG) < 32
def keygen(p: int, q: int, g: int):
x = int(randbytes(48).hex(), 16)
y = pow(g, x, p)
return x, y
def sign(message: str, x: int):
k = pow(int.from_bytes(message.encode(), "big"), -1, q)
r = pow(g, k, p) % q
h = sha256(message.encode()).hexdigest()
s = pow(k, -1, q) * (int(h, 16) + x * r) % q
return h, r, s
def verify(message_hash: str, r: int, s: int, y: int):
message_hash = int(message_hash, 16)
w = pow(s, -1, q)
u1 = message_hash * w % q
u2 = r * w % q
v = (pow(g, u1, p) * pow(y, u2, p) % p) % q
return v == r
x, y = keygen(p, q, g)
print(f"p = {p}")
print(f"q = {q}")
print(f"g = {g}")
print(f"y = {y}")
hash, r, s = sign(FLAG, x)
assert verify(hash, r, s, y)
print("FLAG = {}".format(re.sub(r"([\S+])", r"*", FLAG)))
print(f"sha256(FLAG) = {hash}")
print(f"r = {r}")
print(f"s = {s}")
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/WaniCTF/2023/crypto/EZDORSA-Lv2/chall.py | ctfs/WaniCTF/2023/crypto/EZDORSA-Lv2/chall.py | from Crypto.Util.number import bytes_to_long, getPrime, long_to_bytes
p = getPrime(1024)
q = getPrime(1024)
n = p * q
e = 7
m = b"FAKE{DUNMMY_FLAG}"
c = pow(bytes_to_long(m), e, n)
c *= pow(5, 100, n)
print(f"n = {n}")
print(f"e = {e}")
print(f"c = {c}")
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/WaniCTF/2023/crypto/pqqp/chall.py | ctfs/WaniCTF/2023/crypto/pqqp/chall.py | import os
from Crypto.Util.number import bytes_to_long, getPrime
flag = os.environb.get(b"FLAG", b"FAKE{THIS_IS_FAKE_FLAG}")
p = getPrime(1024)
q = getPrime(1024)
n = p * q
e = 0x10001
d = pow(e, -1, (p - 1) * (q - 1))
m = bytes_to_long(flag)
c = pow(m, e, n)
s = (pow(p, q, n) + pow(q, p, n)) % n
print(n)
print(e)
print(c)
print(s)
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/WaniCTF/2023/crypto/EZDORSA-Lv3/chall.py | ctfs/WaniCTF/2023/crypto/EZDORSA-Lv3/chall.py | from Crypto.Util.number import *
e = 65537
n = 1
prime_list = []
while len(prime_list) < 100:
p = getPrime(25)
if not (p in prime_list):
prime_list.append(p)
for i in prime_list:
n *= i
m = b"FAKE{DUMMY_FLAG}"
c = pow(bytes_to_long(m), e, n)
print(f"n = {n}")
print(f"e = {e}")
print(f"c = {c}")
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/CrewCTF/2024/crypto/Boring_LCG/chall.py | ctfs/CrewCTF/2024/crypto/Boring_LCG/chall.py | import os
from sage.all import *
set_random_seed(1337)
Fp = GF(6143872265871328074704442651454311068421530353607832481181)
a, b = Fp.random_element(), Fp.random_element()
flag = (os.getenv('flag') or 'crew{submit_this_if_desperate}').encode()
s = Fp.from_integer(int.from_bytes(flag[len('crew{'):-len('}')], 'big'))
out = []
for _ in range(12): out.extend(s:=a*s+b)
print([x>>57 for x in out])
# [50, 32, 83, 12, 49, 34, 81, 101, 46, 108, 106, 57, 105, 115, 102, 51, 67, 34, 124, 15, 125, 117, 51, 124, 38, 10, 30, 76, 125, 27, 89, 14, 50, 93, 88, 56] | python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/CrewCTF/2024/crypto/Noisy_Encryption/server.py | ctfs/CrewCTF/2024/crypto/Noisy_Encryption/server.py | import secrets
import sympy
FLAG="crew{fake_flag}"
BITS=512
LIM=pow(2,BITS)
while True:
while (not sympy.isprime(p:=secrets.randbelow(LIM//2)+LIM//2)) or (p-1)%3==0:
pass
while (not sympy.isprime(q:=secrets.randbelow(LIM//2)+LIM//2)) or (q-1)%3==0:
pass
n=p*q
if n>pow(2,1023):
break
phi=(p-1)*(q-1)
e=3
Secret=secrets.randbelow(LIM)
d=pow(e,-1,phi)
sig=pow(Secret,d,n)
print("The signature is: "+str(sig))
def hamming_weight(x):
return sum([int(y) for y in bin(x)[2:]])
while True:
print("I can encrypt anything for you! But the bits may get messy")
msg=input()
if msg=="guess":
print("Do you know the secret?")
msg=int(input())
if msg==Secret:
print("You sure do! Here is your prize:")
print(FLAG)
exit(0)
else:
print("Wrong answer!")
exit(0)
msg=int(msg)
enc=pow(msg,3,n)
print(hamming_weight(enc)%2)
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/CrewCTF/2023/blockchain/positive/solve-pow.py | ctfs/CrewCTF/2023/blockchain/positive/solve-pow.py | import hashlib,random
x = 100000000+random.randint(0,200000000000)
for i in range(x,x+20000000000):
m = hashlib.sha256()
ticket = str(i)
m.update(ticket.encode('ascii'))
digest1 = m.digest()
m = hashlib.sha256()
m.update(digest1 + ticket.encode('ascii'))
if m.hexdigest().startswith('0000000'):
print(i)
break | python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/CrewCTF/2023/blockchain/deception/solve-pow.py | ctfs/CrewCTF/2023/blockchain/deception/solve-pow.py | import hashlib,random
x = 100000000+random.randint(0,200000000000)
for i in range(x,x+20000000000):
m = hashlib.sha256()
ticket = str(i)
m.update(ticket.encode('ascii'))
digest1 = m.digest()
m = hashlib.sha256()
m.update(digest1 + ticket.encode('ascii'))
if m.hexdigest().startswith('0000000'):
print(i)
break | python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/CrewCTF/2023/blockchain/infinite/solve-pow.py | ctfs/CrewCTF/2023/blockchain/infinite/solve-pow.py | import hashlib,random
x = 100000000+random.randint(0,200000000000)
for i in range(x,x+20000000000):
m = hashlib.sha256()
ticket = str(i)
m.update(ticket.encode('ascii'))
digest1 = m.digest()
m = hashlib.sha256()
m.update(digest1 + ticket.encode('ascii'))
if m.hexdigest().startswith('0000000'):
print(i)
break | python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/CrewCTF/2023/misc/setjail/src/void.py | ctfs/CrewCTF/2023/misc/setjail/src/void.py | """
⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⢀⠀⢆⡱⢫⡟⣿⣿⢿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⡿⣿⣿⣿⣿⣿⢿⣻⢿⣟⡿⡤⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀
⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠄⠠⠀⢂⡘⢦⡳⣏⣾⣟⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⢿⣿⣿⣿⣿⣿⣿⣿⣞⣿⣳⣁⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀
⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠠⠐⠈⣌⢣⡑⢦⣙⢮⣳⢻⡾⣿⣻⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⡿⣾⢷⣿⢯⠄⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀
⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⣌⡳⢈⡒⡌⡖⣭⢺⡭⣞⡥⣏⣿⣽⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣻⣟⡾⣏⡂⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀
⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠰⡈⢑⡣⢜⡜⡱⣌⢧⡽⣲⣽⢻⣾⢿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣽⣿⣽⣻⡽⣷⡂⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀
⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠐⠁⠂⠐⢈⠐⡡⠊⢎⡳⣟⠾⣝⡾⣛⣾⢳⢯⡻⡝⣯⢟⡿⣻⢿⣟⡿⣟⣿⢻⠿⡿⣿⢿⡿⣿⣿⢿⣾⣿⣿⣷⡿⣽⣳⠭⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀
⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠠⠐⣸⢮⣷⡱⣭⣞⡵⣏⢿⡱⣏⠷⣎⣟⢮⢳⡙⡴⢋⡴⢩⠞⡼⡙⢮⠘⣉⠣⡙⠤⢋⡹⢱⠫⣟⢿⣽⣿⣟⣿⣯⣟⡷⡀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀
⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⢀⠂⢭⣻⣽⣿⡷⣯⢻⣜⣣⢟⣼⡻⣝⣮⣛⢦⡙⡖⢣⠜⣡⠚⡔⣩⠂⢇⢢⠱⡱⢌⡒⠤⡃⠵⣈⠞⣽⣾⣿⣿⣽⣯⠷⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀
⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠁⠠⣈⣶⣽⣾⡿⣽⢏⡷⣎⢷⣫⠾⣽⣹⢶⡹⣎⡵⣍⢳⢪⢅⡫⠴⣡⢋⡜⢢⢣⡑⢎⡸⢐⡉⢖⡡⢚⡜⣯⣿⣿⣯⣟⡏⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀
⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠰⡸⣟⣿⡿⣽⣻⢎⣷⡹⣎⣷⣛⣧⢯⣗⡻⣜⡞⣬⢇⡳⢊⡕⢣⢆⢣⠜⣡⠆⡍⢦⠡⠣⠜⢢⡑⢣⢜⣱⢯⣿⢿⡽⠌⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀
⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠠⣁⢷⣻⣯⢿⣯⢷⣛⠶⣝⣳⢾⣹⢮⢷⡺⣝⢧⡻⣔⢫⡔⢫⠜⡡⢎⢎⡜⢢⡙⡜⠤⢋⡅⣋⠦⡙⢆⢮⡹⣟⣾⣿⡻⠄⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀
⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⢀⠰⢬⢏⣷⡿⣟⣮⢳⣭⢻⣭⣟⣯⣿⣯⣿⣷⣯⣿⣳⣮⣳⣜⢣⢎⡱⢎⡖⣸⢡⠚⣄⠫⠔⡘⡔⢢⠍⢎⢲⡹⣽⢾⡷⣟⠂⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀
⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⡉⢆⢫⣞⢿⡝⣮⢳⢮⣟⣼⢻⣞⡷⢯⡳⣏⢿⡻⣟⡿⣷⢯⣟⣎⠖⣭⢞⡵⣎⡵⣂⠧⣙⠰⣉⠦⡙⡌⢶⣹⢯⣟⣿⡱⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀
⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠐⡐⢬⢷⡞⣯⡝⣮⢏⣷⣚⣮⢷⣻⣾⣿⣷⣿⣞⣷⣯⣟⣿⣻⡾⣝⠎⡜⢯⡾⣿⣽⢿⣻⣮⢷⡜⣦⣑⢚⢦⣻⣯⡿⣞⠥⠁⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀
⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠂⡄⢫⠞⡑⢊⠱⠉⠞⣲⣛⠾⣏⡿⣹⢾⡹⢣⢏⠾⣽⣻⢾⣽⣻⢭⡚⣌⢣⢛⣷⣯⣿⣧⡝⣎⡝⠶⡭⡞⢦⣻⣯⢿⡉⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀
⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⢀⠰⣎⡷⣞⣧⡚⠀⠀⠀⠀⡘⠴⣩⠿⣜⣳⡱⢎⡵⣋⢮⡟⣷⢯⣟⣾⢣⠷⡱⢌⠦⡙⣎⠿⣹⠻⡟⣷⢾⡱⢣⠝⡲⢯⡟⠁⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀
⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⢌⣻⣽⣻⡽⣶⡹⠄⠀⢌⠰⣌⡳⣝⣯⢳⡧⣝⣏⢶⡹⣎⡿⣽⣻⢾⣝⡯⢏⡵⢊⠖⡱⢌⡚⢥⠓⡜⢤⠣⡙⢥⢋⡵⣻⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀
⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠂⢳⣳⢯⣟⡾⣝⢦⠈⣂⠳⡜⣽⢺⡼⣳⡽⣞⣼⣳⢿⣹⣟⡷⢯⣛⣮⡝⣮⠰⣉⢎⡱⠌⡜⢢⡙⡜⢢⡑⡩⢆⢣⢺⡅⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀
⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠡⢏⡿⣾⣽⢫⣮⡑⠤⡛⣼⢣⡯⣗⡯⢷⣛⡾⣽⣞⣷⣻⣾⢿⡿⣷⢿⣞⣳⣵⢪⠴⡩⢜⠡⡒⠌⡥⢒⡱⢊⢆⠯⣼⢆⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀
⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠭⢳⢧⣛⡧⣷⣙⢦⡙⣦⢏⡷⣹⢞⡯⣯⣽⢳⣞⡷⣯⣟⣯⠿⣝⠻⡜⡭⠻⣍⠚⡵⣊⠵⣡⢋⡔⢣⠜⣡⠞⡰⢭⡇⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀
⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠈⠾⣱⠿⣼⡹⢮⡱⣎⠿⣜⢧⢯⣳⠷⣭⣟⡾⡽⢧⣻⣜⠳⣌⠳⡩⠔⢣⠌⡓⢬⢃⡞⢤⠣⡜⢣⡙⣤⢛⡥⢫⠐⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀
⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠉⠠⢉⢧⡳⣭⢻⡜⣯⢞⣵⣻⣳⢯⡾⣽⢯⣷⣞⣷⣬⣳⡹⣌⠣⡜⢱⢊⠖⡸⢂⡳⢌⢣⠜⡰⣋⠖⠁⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀
⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⡘⢦⡻⣜⢧⣻⡜⣯⢞⡵⣯⣿⣿⣿⣿⣿⣾⣽⣾⣽⣿⣽⣷⣎⡕⡪⢜⡡⢓⡜⡌⢦⡙⡔⠡⠂⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀
⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⢉⠲⣝⢮⡳⢧⡻⣜⢯⡽⣳⡽⣞⣯⣟⡻⣙⢛⠻⣻⢿⡿⣟⢯⡛⡕⢪⠔⡣⢜⡘⠆⠱⠈⠁⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀
⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⢪⠔⡹⢮⡝⣧⢻⡜⣧⢻⡵⣛⣾⢳⣯⢷⣹⢮⡗⣧⢛⡼⢌⠦⡑⢮⡑⢎⡱⢊⠔⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀
⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⢣⢞⡡⣛⡼⣣⢟⡼⣣⠿⣜⠿⣼⣻⣞⣯⢷⣻⣼⢣⢏⡲⣉⠖⡩⢆⡙⢦⠱⡉⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀
⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⢭⡚⣵⢣⡟⣵⢯⣞⡵⣻⢭⡟⡶⣓⠮⡜⢭⡒⣍⠣⢎⠴⡡⢎⡕⢪⡑⢎⡱⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀
⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⢣⢟⡼⣣⢿⡹⡾⣼⣹⢧⡟⣾⣱⢏⡷⣙⢦⡱⢌⠳⣌⠲⡑⢎⡜⡥⡙⢦⡑⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀
⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠭⣞⡵⣛⡮⣗⢿⣱⢯⠾⣝⡾⣭⣟⡾⣵⢮⣱⢋⠶⣈⢧⣙⠲⣜⡡⢝⢢⡹⣄⡀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀
⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⡹⢎⡷⣫⢷⣹⡞⣧⢟⣻⡽⣽⣳⢯⡿⣽⣞⡷⣯⢻⡭⢶⢩⠓⢦⡙⢬⠲⣑⢻⣷⣦⣀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀
⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⢄⠱⣏⡞⣷⢫⣶⢻⡼⣫⣗⢯⡷⣯⠿⣽⠳⢯⡝⣎⢳⡙⢎⡲⡙⢦⡙⢦⡙⠤⠈⣿⣿⣿⣷⣤⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀
⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠘⠄⠛⠼⡙⢞⠻⡜⡳⢏⠷⣞⣻⡼⢧⡻⣜⢫⠖⣜⡸⢆⡝⣪⢕⡹⢦⡙⢦⡙⠆⠀⢾⣿⣿⣿⣿⣿⣦⣄⡀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀
⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠌⣀⡾⡀⢄⡀⠀⠀⠀⠈⣈⠀⣈⣟⣧⢻⣌⢳⡚⡴⢣⢏⡼⣡⢎⡵⢪⡱⢣⡝⠠⠀⢺⣿⣿⣿⣿⣿⣿⣿⣿⣭⡳⣖⡤⣄⣠⢀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀
⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⢀⠀⠄⡌⠀⠀⠌⢢⣝⣣⠷⣌⢯⡻⣝⢯⣟⢧⡛⣵⣻⣼⡳⣎⢷⣹⢣⠟⣜⡲⡱⢎⡜⣣⢽⡓⠄⠀⠀⢺⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣱⣳⣎⡷⣯⣛⡷⣚⡴⣠⢄⣀⢀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀
⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⡀⡔⢤⢃⡜⢤⣉⠒⡀⠀⢈⠜⢤⡿⣜⣯⠽⣎⡳⡭⢞⢮⡳⣙⢾⣳⢯⡿⣽⡺⣵⢫⡟⢦⢳⡙⢮⣜⡷⡋⠔⠀⠀⠀⣻⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣷⣿⣞⣿⣽⣯⣟⡷⣽⡖⣯⢾⣹⣞⣵⣲⢦⣤⣄⣀⡀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀
⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⡀⣄⢢⢵⣸⡼⣧⣻⣜⠧⢦⣉⠀⠀⠰⣈⠲⣟⡹⣎⠿⣼⡹⣝⣫⠶⣍⠧⣻⡽⣯⣟⣷⣻⡵⣻⡜⣯⢇⣿⣳⢏⠇⠡⠀⠀⠀⠀⢿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣾⣿⣿⣷⣿⣿⣿⣳⣿⡾⣽⣻⣾⣽⣳⢯⣟⡶⣤⣄⡀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀
⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⡀⢀⢡⡘⣌⡟⣼⣿⣿⣿⣿⣼⡟⡄⢀⠀⠀⡁⠀⢡⣏⡘⣏⠛⣤⢹⡌⣧⢋⡙⣌⢡⣿⣡⢻⡜⣇⣿⢡⢻⣸⢻⡜⢡⠈⠀⠀⠀⠀⠀⠀⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣧⣿⣿⣿⣿⣿⣿⣿⣏⡟⣧⣼⢹⡟⣤⣄⣀⡀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀
⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⡀⠄⢢⡱⣜⣮⣷⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⡱⣃⠀⢀⠐⠈⢠⣯⠵⣯⡻⣵⢫⡞⣵⢫⠷⣌⢻⡶⣯⢿⣽⣻⣞⣯⢿⡽⡏⢎⠁⠂⠀⠀⠀⠀⠀⢰⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣾⣿⣿⣷⣆⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀
⠀⠀⠀⠀⠀⠀⠀⠀⢀⠀⡄⢢⠱⣤⢫⣷⣽⣾⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣷⣛⡄⠀⠀⡌⢀⠰⣏⢿⡱⣟⡼⢧⡻⣜⢯⡳⣌⢳⡿⣽⣻⡾⣷⣻⢾⢏⠓⡁⠂⠀⠀⠀⠀⠀⠀⢀⣾⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣧⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀
⠀⠀⠀⠀⢀⠠⡐⡌⢤⠳⣜⣣⣿⣾⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⡷⡌⠀⠐⢨⠀⡜⣿⣺⢽⣺⡝⣧⣻⠼⣧⣛⠤⣫⣟⣷⢿⡽⡷⢏⠋⠄⠃⢀⠀⠀⠀⠀⠀⠀⢀⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣷⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀
⠀⠀⢠⡘⣤⠳⡼⣜⣷⣻⣽⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⠀⠀⢀⠣⡘⢸⣷⢯⣛⡶⣏⠷⣭⢟⡶⢭⣚⣱⢿⣞⢯⠹⡑⠊⠌⠐⠀⠀⠀⠀⠀⠀⠠⢠⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣇⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀
⠀⢀⣶⡽⣞⣿⣽⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⠀⠀⢄⠓⡌⢳⣿⢯⣝⠾⣭⣻⢧⣻⡼⢧⡳⠘⡏⠜⢂⠡⠐⠡⠈⠀⠀⠀⠀⠀⠀⠐⣤⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀
⠀⢼⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⡀⠐⣌⢘⡰⠉⢞⡛⠎⠛⠱⠋⠉⠑⠙⠋⠓⠡⢎⠘⣀⠂⡁⠂⠠⠀⠀⠀⠀⠀⢄⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⡅⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀
⠀⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⡆⢡⣂⡶⣤⣳⣼⣟⣶⣳⡾⣴⣦⣤⣤⣖⡴⣎⢧⡛⣤⣒⡄⡁⠀⠀⠀⠀⠀⡈⡔⣋⢟⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣖⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀
⠠⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣛⢏⡻⠹⣿⠁⠁⠹⠿⣿⢿⣿⣿⣿⣿⣿⣿⣿⣿⣷⣦⣴⣦⣼⣷⣿⣿⣾⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀
⢐⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣾⣷⡔⠀⠀⠀⠀⢁⣰⣎⣴⣈⣦⡑⣬⢡⡉⢌⠈⣁⠫⣙⠹⣋⠟⢿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⡿⠿⡿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣟⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀
⢸⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⡿⢻⠟⡝⠀⠀⠀⠀⠀⠿⡿⣿⢿⣿⣿⣿⣿⣿⣿⣿⣿⣷⣿⣷⣾⣾⣾⣽⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣏⡳⣼⡱⢻⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⡇⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀
⣽⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣷⣧⣾⡔⠈⠀⠄⠀⢀⡸⣄⣄⣊⣄⢂⡡⢉⠜⣩⠋⠟⡛⠟⡿⠿⡿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⢞⣵⣳⢏⡷⣻⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⡟⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀
⣾⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⢿⡿⢆⠁⠀⠀⠀⠂⣿⣿⣿⣿⣿⣿⣿⣿⣿⣷⣿⣿⣼⣷⣮⣷⣼⣳⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣫⢾⣽⣻⢼⡱⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⡟⠁⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀
⢾⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣟⣦⣓⡆⢀⠦⣄⠀⡀⢰⡠⡑⣨⠉⡝⢩⠛⣛⠻⡛⠿⠿⡿⢿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣧⢿⣳⣟⣮⢳⣿⣿⣿⣿⣿⣿⣿⣿⣿⠛⡛⢿⣿⣿⣿⣿⣿⣿⣿⡗⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀
⣹⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⢇⠠⢈⠀⢂⠰⣿⣷⣿⣷⣿⣿⣷⣿⣶⣷⣽⣮⣵⣜⣶⡴⣮⣝⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣯⢿⡽⣾⡹⢾⣿⣿⣿⣿⣿⣿⡿⢣⣛⠜⡠⢉⠿⣿⣿⣿⣿⣿⡦⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀
⠸⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⡽⣌⠆⡐⢀⡈⠄⠂⠭⡙⢋⠟⡛⢟⠻⢟⠿⢿⠿⣿⢿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣯⢿⡽⣧⢻⡹⣿⣿⣿⡿⣟⠣⣍⠣⢜⢢⡑⢦⣜⡽⣿⣿⣿⣿⣿⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀
⠈⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⢆⣠⢀⢀⡈⢤⣷⣯⣿⣮⣷⣮⣷⣬⣮⣤⣳⣌⣦⣱⣊⡵⣩⢟⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣟⢾⣻⣽⢣⡳⡹⢿⡿⣵⢊⡱⢠⡍⢦⣣⣟⡿⣾⣿⣿⣿⣿⣿⣿⠁⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀
⠀⢻⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⡿⣙⠦⣹⣯⣀⡘⡿⢻⠿⡻⢿⠿⣿⢿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣯⢿⡽⣾⢯⣗⣯⢯⡝⣆⠳⣜⢧⡟⣷⣻⣾⣿⣿⣿⣿⣿⣿⡿⠃⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀
⠀⢹⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣷⣯⡗⣯⣜⣿⣴⣧⣮⣵⣎⡶⣤⣃⣆⢦⡱⣨⢱⡩⢍⣋⢟⡹⣟⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⡿⢯⣿⣽⣻⢾⣝⡾⣽⢎⡷⣈⠎⡝⣎⢟⣿⣿⣿⣿⣿⣿⣿⡃⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀
⠀⢸⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⡿⢿⡙⣿⢸⣿⢿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣷⣿⣿⣾⣿⣷⣿⣾⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣻⣞⡷⢯⣟⡾⣽⣳⡟⡶⣥⢚⡘⣤⢋⠾⣿⣿⣿⣿⣿⣿⣷⣄⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀
⠀⢼⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣮⣧⣙⡯⢜⣳⣌⡖⣌⢦⣡⢋⡜⡩⢍⢫⡙⣋⠟⡛⢟⡻⢟⠿⣿⢿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣯⢷⣯⣟⣳⢎⡳⢧⣏⠿⣽⢖⡯⣞⡶⣍⢏⣿⣿⣿⣿⣿⣿⣿⣿⣧⡄⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀
⠀⢼⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⠧⣿⢸⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣶⣿⣼⣷⣽⣶⣳⣮⣷⣾⣯⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣻⣾⣽⣻⢮⡱⢫⡜⣹⢎⡽⢺⡵⢻⡜⣿⣾⣿⣿⣿⣿⣿⣿⣿⣿⣿⣦⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀
⠀⣻⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⢤⡛⣷⢸⡏⣍⢫⠝⣋⠟⡹⢛⠻⡛⢿⠻⠿⢿⠿⣿⢿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣷⢯⣿⡽⣧⣻⡕⣮⡱⢎⡔⢣⢚⡕⢺⣽⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣷⣀⠀⠀⠀⠀⠀⠀⠀⠀
⠀⣽⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣝⡷⢺⣿⣾⣿⣿⣾⣽⣷⣯⣷⣽⣦⣽⣜⣦⣳⣌⡶⣰⣎⡼⣧⣻⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⢯⣿⣽⢯⡷⡙⢦⢻⡜⣬⡓⣎⡜⣣⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣷⡄⠀⠀⠀⠀⠀⠀⠀
⠀⢺⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⡟⡼⣯⢹⡟⢿⠻⡟⠿⡿⢿⢿⡿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣽⢫⣟⡯⣟⢾⡹⣏⠳⣉⠢⡙⡟⣶⡹⢆⡿⣱⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣷⡀⠀⠀⠀⠀⠀⠀
⠀⢹⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⡼⣧⢻⣽⣶⣷⣮⣷⣼⣎⣦⣵⣢⢦⡱⣌⣣⢍⡹⣩⠛⣝⣫⢟⡿⣻⢿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣷⣫⢞⡵⣋⠶⡱⣍⠳⢄⠢⢱⡙⢦⡙⢮⡜⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣖⠀⠀⠀⠀⠀⠀
⠀⠰⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣹⢧⣻⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣷⣿⣿⣾⣷⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣷⣿⡼⣝⢮⡱⢎⡵⣊⡕⣣⢎⡳⣌⢇⠾⣱⣻⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣇⠀⠀⠀⠀⠀
⠀⠀⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣷⢺⣧⢿⣳⣜⣦⣕⢮⣡⢏⣭⢫⡝⣋⠟⡛⡟⡻⠿⣿⢿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣷⣹⢚⡶⣽⣺⢵⣫⢶⡝⣮⢻⡵⣻⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⢆⠀⠀⠀⠀
⠀⠀⣻⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⢯⡷⣻⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣾⣷⣿⣴⣫⣼⣍⣟⣿⣻⢿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣯⢿⣷⡿⣯⢷⣏⢿⣼⣳⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣄⠀⠀⠀
⠀⠀⠼⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⢺⣗⣿⣭⣋⣟⣹⢋⡟⡹⢛⡛⣟⠻⡟⢿⠿⡿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣾⣽⣯⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣾⣿⣾⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⡄⠀⠀
⠀⠀⢸⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⡽⣾⣽⣿⣿⣿⣿⣿⣾⣿⣷⣿⣼⣷⣿⣮⣷⣵⣦⣧⣝⣮⣝⣯⣻⣽⣻⣟⣿⢿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⡀⠀
⠀⠀⡸⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣞⡷⣯⢟⡛⣟⠻⣟⠿⡿⢿⢿⡿⣿⢿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⠆⠀
⠀⠀⢼⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣺⣽⣻⣿⣿⣾⣿⣾⣿⣽⣾⣶⣳⣭⣾⣴⣣⡽⣌⣯⣹⣙⣏⡻⣝⢯⣛⣿⣻⣟⣿⡿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣆⠀
⠀⠀⢺⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣵⣳⣿⢿⢻⠟⡿⢿⠿⣿⢿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⡄
⠀⢀⢻⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣞⡷⣿⣧⣿⣾⣵⣯⣾⣼⣳⣮⣷⣭⢯⣹⣍⣻⣙⡟⣛⡟⣛⢻⡛⡟⢿⡻⣟⠿⣿⢿⡿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⡷
⠀⠀⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⢺⣽⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣷⣿⣿⣷⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣻⢿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⠏
⠀⠀⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣯⢻⣞⣿⣦⣳⣴⣦⣵⣬⣖⣭⣞⣭⣏⡿⣹⣛⣟⣻⠻⣟⢻⠟⡿⣻⠿⣟⡿⣟⡿⣿⢿⡿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣾⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⠃⠀
https://emojicombos.com/rick-roll-ascii-art
"""
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/CrewCTF/2023/misc/setjail/src/main.py | ctfs/CrewCTF/2023/misc/setjail/src/main.py | import re
import ast
import void
"""
Example:
( when root object is A )
path: .B.C["D"][1][2][3]
value: "pyjail is fun!"
->
A.B.C["D"][1][2][3] = "pyjail is fun!"
"""
DISALLOWED_WORDS = ["os", "posix"]
ROOT_OBJECT = void
def abort(s):
print(s)
exit(1)
def to_value(s):
return ast.literal_eval(s)
# gift
module = input("import: ")
__import__(module)
path = input("path: ")
value = to_value(input("value: "))
path, _, last_item_key, last_attr_key = re.match(r"(.*)(\[(.*)\]|\.(.*))", path).groups()
# set root object
current_obj = ROOT_OBJECT
# walk object
while path != "":
_, item_key, attr_key, path = re.match(r"(\[(.*?)\]|\.([^\.\[]*))(.*)", path).groups()
if item_key is not None:
item_key = to_value(item_key)
if any([word in item_key for word in DISALLOWED_WORDS]):
abort("deny")
current_obj = current_obj[item_key]
elif attr_key is not None:
if any([word in attr_key for word in DISALLOWED_WORDS]):
abort("deny")
current_obj = getattr(current_obj, attr_key)
else:
abort("invalid")
# set value
if last_item_key is not None:
last_item_key = to_value(last_item_key)
current_obj[last_item_key] = value
elif last_attr_key is not None:
setattr(current_obj, last_attr_key, value)
print("Done")
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/CrewCTF/2023/misc/starship-1/sandbox.py | ctfs/CrewCTF/2023/misc/starship-1/sandbox.py | #!/usr/bin/env python3
import re
import sys
class Nobuffers:
def __init__(self, stream):
self.stream = stream
def write(self, data):
self.stream.write(data)
self.stream.flush()
def writelines(self, datas):
self.stream.writelines([f"{data}\n" for data in datas])
self.stream.flush()
def __getattr__(self, attr):
return getattr(self.stream, attr)
banned = re.escape('\\(~}?>{&/%`)<$|*=#!-+\'0123456789;[] ')
stdout = Nobuffers(sys.stdout)
stdout.write('''
__..,,-----l"|-.
__/"__ |----"" | i--voo..,,__
.-'=|:|/\|-------o.,,,---. Y88888888o,,_
_+=:_|_|__|_| ___|__|___-| """"````"""`----------.........___
__============:' "" |==|__\===========(=>=+ | ,_, .-"`--..._
;="|"| |"| `.____|__|__/===========(=>=+----+===-|---------<---------_=-
| ==|:|\/| | | o|.-'__,-| .' _______|o `----'| __\ __,.-'"
"`--""`--"'"""`.-+------'" .' _L___,,...-----------""""""" "
`------""""""""
''')
stdout.write('Enter command: ')
prompt = input()
if prompt.isascii() and not re.findall(f'[{banned}]', prompt):
try:
exec(prompt, {'__builtins__': {'__build_class__': __build_class__, "__name__":__name__}})
except:
pass
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/CrewCTF/2023/misc/starship/sandbox.py | ctfs/CrewCTF/2023/misc/starship/sandbox.py | #!/usr/bin/env python
import re
import sys
class Nobuffers:
def __init__(self, stream, limit=1024):
self.stream = stream
self.limit = limit
def write(self, data):
if len(data) > self.limit:
raise ValueError(f"Data exceeds the maximum limit of {self.limit} characters")
self.stream.write(data)
self.stream.flush()
def writelines(self, datas):
datas = [f"{data}\n" for data in datas if len(data) <= self.limit]
self.stream.writelines(datas)
self.stream.flush()
def __getattr__(self, attr):
return getattr(self.stream, attr)
blacklisted_chars = re.escape('\\(~}?>{)&/%`<$|*=#!-@+"\'0123456789;')
blacklisted_words = [
'unicode', 'name', 'setattr', 'import', 'open', 'enum',
'char', 'quit', 'getattr', 'locals', 'globals', 'len',
'exit', 'exec', 'blacklisted_words', 'print', 'builtins',
'eval', 'blacklisted_chars', 'repr', 'main', 'subclasses', 'file',
'class', 'mro', 'input', 'compile', 'init', 'doc', 'fork',
'popen', 'read', 'map', 'dir', 'help', 'error', 'warning',
'func_globals', 'vars', 'filter', 'debug', 'object', 'next',
'word', 'base', 'prompt', 'breakpoint', 'class', 'pass',
'chr', 'ord', 'iter', 'banned'
]
blacklisted_unicode = [
'\u202e', '\u2060', '\u200f', '\u202a', '\u202b', '\u202c'
'\u202d', '\u202f', '\u2061', '\u2062', '\u2063', '\u2064', '\ufeff'
]
blacklisted_chars = f'[{blacklisted_chars}]'
blacklisted_words = '|'.join(f'({word})' for word in blacklisted_words)
blacklisted_unicode_pattern = '|'.join(blacklisted_unicode)
blacklisted_nonascii = '[^\x00-\x7F]'
stdout = Nobuffers(sys.stdout)
stdout.write('''
__..,,-----l"|-.
__/"__ |----"" | i--voo..,,__
.-'=|:|/\|-------o.,,,---. Y88888888o,,_
_+=:_|_|__|_| ___|__|___-| """"````"""`----------.........___
__============:' "" |==|__\===========(=>=+ | ,_, .-"`--..._
;="|"| |"| `.____|__|__/===========(=>=+----+===-|---------<---------_=-
| ==|:|\/| | | o|.-'__,-| .' _______|o `----'| __\ __,.-'"
"`--""`--"'"""`.-+------'" .' _L___,,...-----------""""""" "
`------""""""""
''')
stdout.write('Enter command: ')
prompt = input()
prompt = prompt.encode('unicode-escape').decode('ascii')
prompt = bytes(prompt, 'ascii').decode('unicode-escape')
if re.findall(blacklisted_chars, prompt):
raise Exception('Blacklisted character detected. Go away!')
if re.findall(blacklisted_words, prompt, re.I):
raise Exception('Blacklisted word detected. Go away!')
if re.search(blacklisted_unicode_pattern, prompt):
raise Exception('Blacklisted unicode detected. Go away!')
if re.search(blacklisted_nonascii, prompt):
raise Exception('Non-ASCII character detected. Go away!')
try:
exec(prompt)
except:
pass
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/CrewCTF/2023/misc/jailpie/share/chall.py | ctfs/CrewCTF/2023/misc/jailpie/share/chall.py | #!/usr/local/bin/python3
import base64
import types
import dis
def is_valid(code):
whitelist = {
'LOAD_CONST',
'BINARY_OP',
'COMPARE_OP',
'POP_JUMP_BACKWARD_IF_TRUE',
'RETURN_VALUE',
}
for instr in dis.Bytecode(code):
if instr.opname not in whitelist:
return False
if 'JUMP' in instr.opname and not (0 <= instr.argval < len(code.co_code)):
return False
return True
if __name__ == '__main__':
_print, _eval = print, eval
# try:
prog = bytes.fromhex(input('Program: '))
code = types.CodeType(0, 0, 0, 0, 0, 0, prog, (0,), (), (), '', '', '', 0, b'', b'', (), ())
assert is_valid(code)
__builtins__.__dict__.clear()
_print(_eval(code, {}))
# except:
# _print('Nice try!')
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/CrewCTF/2023/crypto/matrixrsa/server.py | ctfs/CrewCTF/2023/crypto/matrixrsa/server.py | import os
import random
from Crypto.Util.number import getPrime, long_to_bytes, bytes_to_long
from sympy.polys.matrices import DomainMatrix
from sympy import FiniteField
# secret import
from secret import decrypt
from flag import FLAG
size = 1024//8
e = 65537
def pad(data, length):
if len(data) >= length:
raise ValueError("length of data is too large.")
pad_data = bytes([random.randint(1, 255) for _ in range(length - len(data) - 1)])
return pad_data + b'\x00' + data
def unpad(paddeddata):
if b'\x00' not in paddeddata:
raise ValueError("padding is incorrect.")
return paddeddata[paddeddata.index(b'\x00')+1:]
def keygen():
p, q = getPrime(8*size), getPrime(8*size)
n = p*q
return ((p, q), n)
def encrypt(msgint, n):
a = bytes_to_long(os.urandom(int(2*size-1)))
# sympy.FiniteField treats non-prime modulus instance as Z/nZ
Zmodn = FiniteField(n)
mat = DomainMatrix([
[Zmodn(a), Zmodn(msgint)],
[Zmodn(0), Zmodn(a)]
], (2, 2), Zmodn)
enc = mat**int(e)
enc_0 = int(enc[0,0].element.val)
enc_1 = int(enc[0,1].element.val)
return (enc_0, enc_1)
def main():
try:
banner = "Welcome to matrix RSA world"
print(banner)
(p,q), n = keygen()
paddedflag = pad(FLAG, 2*size-1)
assert unpad(paddedflag) == FLAG
paddedflagint = bytes_to_long(paddedflag)
encflag_0, encflag_1 = encrypt(paddedflagint, n)
assert decrypt((encflag_0, encflag_1), (p, q)) == paddedflagint
print("Here is encrypted flag(enc_0, enc_1):")
print(long_to_bytes(encflag_0).hex())
print(long_to_bytes(encflag_1).hex())
while True:
print("Please input encrypted message(enc_0, enc_1):")
enc_0 = bytes_to_long(bytes.fromhex(input('>> ')))
enc_1 = bytes_to_long(bytes.fromhex(input('>> ')))
if enc_0 >= n or enc_1 >= n:
print("size error")
continue
if (enc_0 * encflag_1 - enc_1 * encflag_0) % n == 0:
print("Do not input related to encrypted flag")
continue
dec = decrypt((enc_0, enc_1), (p, q))
if FLAG in long_to_bytes(dec):
print("Do not input encrypted flag")
else:
print("Here is decrypted message:")
print(long_to_bytes(int(dec)).hex())
except:
quit()
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/CrewCTF/2023/crypto/sspasswd/server.py | ctfs/CrewCTF/2023/crypto/sspasswd/server.py | from Crypto.Util.number import *
# secret import
from param_secret import p, pollst
from ss_config import FLAG, ALICE_PW, BOB_PW
PWCHARSET = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz@_'
assert len(ALICE_PW) == 12
assert len(BOB_PW) == 12
assert all([ch in PWCHARSET for ch in ALICE_PW])
assert all([ch in PWCHARSET for ch in BOB_PW])
assert len(FLAG) <= 64
ALICE_PW = ALICE_PW.encode()
BOB_PW = BOB_PW.encode()
def evalpoly(pollst, p, pnt):
return sum([coef * pow(pnt, idx, p) for idx, coef in enumerate(pollst)]) % p
def main():
assert evalpoly(pollst, p, 0) == int.from_bytes(FLAG, 'big')
assert evalpoly(pollst, p, 1) == int.from_bytes(ALICE_PW, 'big')
assert evalpoly(pollst, p, 2) == int.from_bytes(BOB_PW, 'big')
assert len(pollst) == 4 + 1
public_shares = []
for pnt in [1337, 0xbeef, 0xcafe, 0xdead]:
public_shares.append((pnt, evalpoly(pollst, p, pnt)))
print(f"p = {p}")
print(f"public_shares = {public_shares}")
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/CrewCTF/2023/crypto/pi_is_3.14/server.py | ctfs/CrewCTF/2023/crypto/pi_is_3.14/server.py | import os
import signal
from flag import FLAG
N = 10000
M = 100
class XorShiftPlus:
A = 10
B = 15
C = 7
L = 23
def __init__(self) -> None:
self.x = int(os.urandom(4).hex(), 16)
self.y = int(os.urandom(4).hex(), 16)
def gen32(self) -> int:
t = self.x
s = self.y
self.x = s
t ^= (t << self.A) & 0xFFFFFFFF
t ^= t >> self.B
t ^= s ^ (s >> self.C)
self.y = t
return (s + t) & 0xFFFFFFFF
def random(self) -> float:
n32 = self.gen32()
nL = 0
# only L bits are used for 32-bit floating point
for _ in range(self.L):
nL *= 2
nL += n32 & 1
n32 >>= 1
return nL / 2**self.L
def simulate(rand: XorShiftPlus) -> bool:
a = rand.random()
b = rand.random()
r2 = a**2 + b**2
return r2 < 1
if __name__ == "__main__":
"""
Area of a quarter circle of radius 1 is pi/4
Let's estimate pi by Monte Carlo simulation!
"""
rand = XorShiftPlus()
result = ""
for _ in range(N):
if simulate(rand):
result += "o"
else:
result += "x"
count = result.count("o")
pi = count / N * 4
print(result)
print(f"\npi is {pi}")
print(f"BTW, can you predict the following {M} simulation results?")
signal.alarm(30)
predicts = input("> ")
assert len(predicts) == M
assert len(set(predicts) - set("ox")) == 0
for i in range(M):
if simulate(rand):
assert predicts[i] == "o"
else:
assert predicts[i] == "x"
print(FLAG)
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/CrewCTF/2023/crypto/frsa/server.py | ctfs/CrewCTF/2023/crypto/frsa/server.py | from json import dump as json_dump
from random import randint
from mpmath import mp
from Crypto.Util.number import bytes_to_long, getPrime, GCD
size = 768//8
def pad(data, length):
if len(data) >= length:
raise ValueError("length of data is too large.")
pad_data = bytes([randint(1, 255) for _ in range(length - len(data) - 1)])
return pad_data + b'\x00' + data
mp.dps = 8*size*16
p = getPrime(8*size)
q = getPrime(8*size)
e = 3
while GCD(q-1, e) != 1 or GCD(p-1, e) != 1:
p = getPrime(8*size)
q = getPrime(8*size)
if p > q:
p, q = q, p
p_n = mp.fdiv(mp.mpf(str(1)), mp.mpf(p))
q_n = mp.mpf(q)
n = mp.fmul(p_n, q_n)
flag = open("flag.txt","rb").read().strip()
flag = bytes_to_long(pad(flag, size-1))
ciphertext = pow(flag, e) % n
json_dump(
{
'n': str(n),
'e': str(e),
'c': str(ciphertext),
},
open('output.txt', 'w')
)
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/CrewCTF/2023/crypto/matrixrsa2/server.py | ctfs/CrewCTF/2023/crypto/matrixrsa2/server.py | import os
import random
from Crypto.Util.number import getPrime, long_to_bytes, bytes_to_long
from sympy.polys.matrices import DomainMatrix
from sympy import FiniteField
# secret import
from secret import decrypt
from flag import FLAG
size = 1024//8
e = 65537
def pad(data, length):
if len(data) >= length:
raise ValueError("length of data is too large.")
pad_data = bytes([random.randint(1, 255) for _ in range(length - len(data) - 1)])
return pad_data + b'\x00' + data
def unpad(paddeddata):
if b'\x00' not in paddeddata:
raise ValueError("padding is incorrect.")
return paddeddata[paddeddata.index(b'\x00')+1:]
def keygen():
p, q = getPrime(8*size), getPrime(8*size)
n = p*q
return ((p, q), n)
def encrypt(msgint, n):
a = bytes_to_long(os.urandom(int(2*size-1)))
# sympy.FiniteField treats non-prime modulus instance as Z/nZ
Zmodn = FiniteField(n)
mat = DomainMatrix([
[Zmodn(a), Zmodn(msgint) - Zmodn(a) ** 0x1337 - Zmodn(0xdeadbeef)],
[Zmodn(0), Zmodn(a)]
], (2, 2), Zmodn)
enc = mat**int(e)
enc_0 = int(enc[0,0].element.val)
enc_1 = int(enc[0,1].element.val)
return (enc_0, enc_1)
def main():
try:
banner = "Welcome to matrix RSA world v2"
print(banner)
(p,q), n = keygen()
paddedflag = pad(FLAG, 2*size-1)
assert unpad(paddedflag) == FLAG
paddedflagint = bytes_to_long(paddedflag)
encflag_0, encflag_1 = encrypt(paddedflagint, n)
assert decrypt((encflag_0, encflag_1), (p, q)) == paddedflagint
print("Here is encrypted flag(enc_0, enc_1):")
print(long_to_bytes(encflag_0).hex())
print(long_to_bytes(encflag_1).hex())
while True:
print("Please input encrypted message(enc_0, enc_1):")
enc_0 = bytes_to_long(bytes.fromhex(input('>> ')))
enc_1 = bytes_to_long(bytes.fromhex(input('>> ')))
if enc_0 >= n or enc_1 >= n:
print("size error")
continue
if (enc_0 * encflag_1 - enc_1 * encflag_0) % n == 0:
print("Do not input related to encrypted flag")
continue
dec = decrypt((enc_0, enc_1), (p, q))
if FLAG in long_to_bytes(dec):
print("Do not input encrypted flag")
else:
print("Here is decrypted message:")
print(long_to_bytes(int(dec)).hex())
except:
quit()
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/CrewCTF/2023/web/archive_stat_viewer/web-apps/src/main.py | ctfs/CrewCTF/2023/web/archive_stat_viewer/web-apps/src/main.py | from pathlib import Path
from uuid import uuid4
from secrets import token_hex
from datetime import datetime
import os
import tarfile
import json
import shutil
from flask import Flask, request, session, send_file, render_template, redirect, make_response
app = Flask(__name__)
app.config['SECRET_KEY'] = open('./secret').read()
app.config['MAX_CONTENT_LENGTH'] = 1024 * 128
UPLOAD_DIR = Path('./archives')
class HackingException(Exception):
pass
def extract_archive(archive_path, extract_folder):
with tarfile.open(archive_path) as archive:
for member in archive.getmembers():
if member.name[0] == '/' or '..' in member.name:
raise HackingException('Malicious archive')
archive.extractall(extract_folder)
def get_folder_info(extract_folder):
data = {}
for file in extract_folder.iterdir():
stat = file.lstat()
name = file.name
size = stat.st_size
last_updated = datetime.utcfromtimestamp(stat.st_mtime).strftime('%Y-%m-%d %H:%M:%S')
data[file.name] = {}
data[file.name]['Size'] = size
data[file.name]['Last updated'] = last_updated
return data
@app.get('/')
def index():
if 'archives' not in session:
session['archives'] = []
return render_template('index.html', archives = session['archives'])
@app.get('/results/<archive_id>')
def download_result(archive_id):
if 'archives' not in session:
session['archives'] = []
archive_id = Path(archive_id).name
return send_file(UPLOAD_DIR / archive_id / 'result.json')
@app.get('/clean')
def clean_results():
if 'archives' not in session:
session['archives'] = []
for archive in session['archives']:
shutil.rmtree(UPLOAD_DIR / archive['id'])
session['archives'] = []
return redirect('/')
@app.post('/analyze')
def analyze_archive():
if 'archives' not in session:
session['archives'] = []
archive_id = str(uuid4())
archive_folder = UPLOAD_DIR / archive_id
extract_folder = archive_folder / 'files/'
archive_path = archive_folder / 'archive.tar'
result_path = archive_folder / 'result.json'
extract_folder.mkdir(parents=True)
archive = request.files['archive']
archive_name = archive.filename
archive.save(archive_path)
try:
extract_archive(archive_path, extract_folder)
except HackingException:
return make_response("Don't hack me!", 400)
data = get_folder_info(extract_folder)
with open(result_path, 'w') as f:
json.dump(data, f, indent=2)
session['archives'] = session['archives'] + [{
'id': archive_id,
'name': archive_name
}]
return redirect('/')
if __name__ == '__main__':
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/CrewCTF/2023/web/sequence_gallery/main.py | ctfs/CrewCTF/2023/web/sequence_gallery/main.py | import os
import sqlite3
import subprocess
from flask import Flask, request, render_template
app = Flask(__name__)
@app.get('/')
def index():
sequence = request.args.get('sequence', None)
if sequence is None:
return render_template('index.html')
script_file = os.path.basename(sequence + '.dc')
if ' ' in script_file or 'flag' in script_file:
return ':('
proc = subprocess.run(
['dc', script_file],
capture_output=True,
text=True,
timeout=1,
)
output = proc.stdout
return render_template('index.html', output=output)
if __name__ == '__main__':
app.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/CrewCTF/2025/ppc/rotating_subsequence/chall.py | ctfs/CrewCTF/2025/ppc/rotating_subsequence/chall.py | import signal
import secrets
from check import checker
def TLE(signum, frame):
print("Timeout!")
exit(0)
signal.signal(signal.SIGALRM, TLE)
signal.alarm(200)
print("Let's see if you have what it takes!")
TT=50
nbits=256
for i in range(TT):
N=secrets.randbits(nbits)
K=secrets.randbelow(100)+3
print(f"{N=}")
print(f"{K=}")
S=list(map(int,input("S=").split(",")))
assert len(S)<=K*nbits, "Too big!"
for i in range(len(S)):
assert 0<=S[i] and S[i]<K, "Not in the correct range"
assert checker(S,N,K), "Incorrect input"
print("Good job!")
print("Well done! Here, take a flag for your effort:")
print(open('flag.txt','r').read())
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/CrewCTF/2025/ppc/IOIOIOI/chall.py | ctfs/CrewCTF/2025/ppc/IOIOIOI/chall.py | from solver import Solve
import signal
import secrets
def TLE(signum, frame):
print("Time Limit Exceeded. Try again...")
exit(0)
signal.signal(signal.SIGALRM, TLE)
signal.alarm(300)
params = [ # (N_min, N_max, K_min, K_max)
(1, 15, 0, 15), # Test 1
(1, 1000, 0, 1000), # Test 2
(5 * 10**8, 10**9, 0, 1000), # Test 3
(5 * 10**17, 10**18, 900, 1000), # Test 4
]
T = 300
for i in range(T):
test_id = i // 75
N_min, N_max, K_min, K_max = params[test_id]
N = N_min + secrets.randbelow(N_max - N_min + 1)
K = K_min + secrets.randbelow(K_max - K_min + 1)
ans = Solve(N, K)
assert 0 <= ans < 998244353
print("Test", i + 1)
print(f"{N = }")
print(f"{K = }")
print("Your answer: ", end="")
player_ans = int(input())
if ans == player_ans:
print("Accepted!")
else:
print("Wrong Answer. Try again...")
exit(0)
print("Congratulations! Here is your flag:")
print(open("flag.txt", "r").read())
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/CrewCTF/2025/crypto/Inverse_With_Errors/main.py | ctfs/CrewCTF/2025/crypto/Inverse_With_Errors/main.py | import secrets
import hashlib
from Crypto.Cipher import AES
from Crypto.Util.number import getPrime
from Crypto.Util.Padding import pad
flag = b'crew{*** REDACTED ***}'
N_size = 1024
N = secrets.randbits(N_size) | (1 << N_size)
d = N
while d >= N:
d = getPrime(N_size)
values = []
R = []
for _ in range(30):
r = secrets.randbits(100)
R.append(r)
values.append(pow(d, -1, N + r))
key = hashlib.sha256(str(d).encode()).digest()
flag = pad(flag, 16)
cipher = AES.new(key, AES.MODE_CBC)
iv = cipher.iv.hex()
enc = cipher.encrypt(flag).hex()
print(f'{R = }')
print(f'{values = }')
print(f'{iv = }')
print(f'{enc = }')
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/CrewCTF/2025/crypto/po1337nomial/server.py | ctfs/CrewCTF/2025/crypto/po1337nomial/server.py | #!/usr/bin/env python3
from os import getenv
from random import getrandbits, randbytes, randrange, shuffle
FLAG = getenv('FLAG', 'crew{fake_flag}')
a = [getrandbits(32) for _ in range(1337)]
options = {'1': 'Get coefficients', '2': 'Evaluate', '3': 'Unlock flag'}
while options:
option = input(''.join(f'\n{k}. {v}' for k, v in options.items()) + '\n> ')
if option not in options:
break
options.pop(option)
if option == '1':
shuffle(s := a.copy())
print('s:', s)
if option == '2':
x = int(input('x: '))
a[randrange(0, 1337)] = 1337
print('y:', sum(a_i * x ** i for i, a_i in enumerate(a)))
if option == '3':
if input('k: ') == randbytes(1337).hex():
print(FLAG)
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/CrewCTF/2025/crypto/EPOW/chall.py | ctfs/CrewCTF/2025/crypto/EPOW/chall.py | from sage.all import EllipticCurve, GF, os, is_prime
# Doing PoW's with elliptic curves!
Nm = 10
for TT in range(Nm):
m = os.urandom(7)
print(f"Entering proof #{TT + 1} of {Nm}, the salt is: {m.hex()}")
X = bytes.fromhex(input("> "))
A = int.from_bytes(X + m)
p = int(input("> "))
E = EllipticCurve(GF(p), [0, A, 0, 1, 0])
assert len(X) == 1
assert is_prime(p), "Are you kidding me?"
assert p.bit_length() >= 384, "Too small! I can't be fooled like that!"
assert p.bit_length() <= 640, "Too big! You'll fry my PC!"
assert E.is_supersingular(), "You failed the proof!"
print("All levels were passed! You deserve a flag for your effort!")
print(open("flag.txt").read())
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/CrewCTF/2025/crypto/Smol_Aes/chall.py | ctfs/CrewCTF/2025/crypto/Smol_Aes/chall.py | from sage.all import *
import secrets
import os
BLOCK_LEN = 8
SECRETS = 30
def create_sbox():
sbox = [i for i in range(256)]
for i in range(256 - 1, -1, -1):
U = secrets.randbelow(i + 1)
sbox[i], sbox[U] = sbox[U], sbox[i]
return sbox
def create_sbox_layer(sz):
return [create_sbox() for _ in range(sz)]
def create_linear(sz):
while True:
M = []
for i in range(sz * 8):
R = secrets.randbits(sz * 8)
M.append([])
for j in range(sz * 8):
M[i].append((R >> j) & 1)
M = Matrix(GF(2), M)
if M.det() == 1:
break
return M
def apply_sbox(inpt, sboxlist):
answer = b""
for (a, b) in zip(inpt, sboxlist):
answer += bytes([b[a]])
return answer
def bitify(inpt):
ans = []
for c in inpt:
for i in range(8):
ans.append((c >> i) & 1)
return vector(GF(2), ans)
def unbitify(inpt):
ans = []
for i in range(0, len(inpt), 8):
c = 0
for j in range(8):
c += pow(2, j) * int(inpt[j + i])
ans.append(c)
return bytes(ans)
def apply_linear(inpt, layer):
return unbitify(bitify(inpt) * layer)
def genkey(num_layers, start_layer):
LAYERS = []
for i in range(num_layers):
if i % 2 == start_layer:
LAYERS.append(['sbox', create_sbox_layer(BLOCK_LEN)])
else:
LAYERS.append(['linear', create_linear(BLOCK_LEN)])
return LAYERS
def encrypt_block(pt, key):
ct = pt
for a in key:
if a[0] == 'sbox':
ct = apply_sbox(ct, a[1])
else:
ct = apply_linear(ct, a[1])
return ct
def main():
key = genkey(3, 0)
while True:
pt = input("Insert plaintext \n> ")
if pt == "-1":
break
try:
pt = bytes.fromhex(pt)
assert (len(pt) == BLOCK_LEN)
except:
print("An error occured")
exit(0)
ct = encrypt_block(pt, key)
print("Ciphertext :", ct.hex())
for i in range(SECRETS):
print(f"SECRET {i + 1}/{SECRETS}")
secret = os.urandom(BLOCK_LEN)
enc = encrypt_block(secret, key)
print("Encrypted secret:", enc.hex())
pt = input("What is the secret? \n> ")
try:
pt = bytes.fromhex(pt)
assert (len(pt) == BLOCK_LEN)
except:
print("An error occured")
exit(0)
if pt != secret:
print(f"Incorrect secret. Secret was: {secret.hex()}")
exit(0)
print("Congratulations! You guessed all secrets. Here is your flag:")
print(open("flag.txt").read())
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/cjail2/jail.py | ctfs/MapleCTF/2023/misc/cjail2/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) or re.search(r'\]', lines):
quit() # disallow arrays
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/flakey_ci/ci.py | ctfs/MapleCTF/2023/misc/flakey_ci/ci.py | import os
from socket import socket
import socketserver
import select
import subprocess
NIXOWOS = r"""
_______ ____________ _______
/ \ \ \ / \
\ \ \ \ / \
\ \ \ \ / /
\ \ \ \ / / __
\ \ \ \/ / _____/ /
__ \ \ \ / _____--- /
\ -----____ \ ---------------\\ /___-- /
\ ---\ \ \ \ /_/ /
\ \____/ \\ \ /
\ ____________________________\\ \ /
\ _----------/ \ \ /
\ / / \ \ /
\ / / \ \ _________/
\ / >>>> <<<<\ \/-------
__________________\/ / >>> <<< \ // \_______________
/ / >>> <<< \ // \
/ / >>>> <<<< \// \
\ //\ ww ww / /
\_____________ / / \ ><><>< ww www ww ><><>< / ___________________/
/ // \ wwwwww wwwwww / /
/ // \ / /
/ / \ \ / /
/ / \ \ / /
\ / \ \ __________________/___________/_________________
\ / \ \ \ /
\ / \ \ \ /
\ / / \ \ /
\/ / \\_______________ ______________/
/ \ \ \
/ ___ \ \ \
/ / \ \ \ \
/ / \ \ \ \
\ / \ \ \ /
\ / \ \ \ /
------- ---------- -------"""
class ReuseAddr(socketserver.ThreadingTCPServer):
allow_reuse_address = True
allow_reuse_port = True
class Server(socketserver.StreamRequestHandler):
request: socket
def handle(self):
def say(m):
if isinstance(m, str):
m = (m + '\n').encode('utf-8')
self.request.sendall(m)
def get():
return self.request.recv(4096)
say(NIXOWOS)
say("Welcome to Maple Bacon's Flakey CI\n\n")
say('Enter a git-https repo URL to build, e.g. github.com/lf-/flaketest')
repo = get().decode('utf-8').strip()
print('repo: ', repo)
if 'nixpkgs' in repo:
say("Please don't clone nixpkgs, it will take a very long time and cause problems")
self.request.close()
return
say('Enter a flake output to build, e.g. packages.x86_64-linux.default:')
output = get().decode('utf-8').strip()
print('flake output', output)
cmd = ['nix', 'build', '-v', '--accept-flake-config', '--print-build-logs', '--print-out-paths', '--refresh', f'git+https://{repo}#{output}']
say('$ ' + ' '.join(cmd))
print(cmd)
proc = subprocess.Popen(cmd, shell=False, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
pollobj = select.poll()
if proc.stderr is None or proc.stdout is None:
# wtf
raise ValueError('stdout or stderr is none wtf')
pollobj.register(proc.stderr.fileno())
pollobj.register(proc.stdout.fileno())
go = 2
while go > 0:
fds = pollobj.poll(1.)
for (fd, ev) in fds:
if ev == select.POLLIN:
data = os.read(fd, 2048)
self.request.sendall(data)
print(data)
if go == 1:
go = 0
elif proc.poll() is not None:
go = 1
say('done')
print('done')
self.request.close()
if __name__ == '__main__':
svc = ReuseAddr(('0.0.0.0', 1337), Server)
svc.allow_reuse_address = True
svc.allow_reuse_port = True
svc.serve_forever()
| 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.