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/WRECKCTF/2022/crypto/lsfr/lsfr.py
ctfs/WRECKCTF/2022/crypto/lsfr/lsfr.py
#!/usr/local/bin/python import random from pylfsr import LFSR with open ("flag.txt", "r") as f: flag = f.read() def enc(plaintext): r = random.getrandbits(32) state = [int(i) for i in list(bin(r)[2:].zfill(32))] plaintext = list([int(j) for j in ''.join(format(ord(i), 'b').zfill(8) for i in plaintext)]) l = LFSR(fpoly=[32,26,20,11,8,5,3,1], initstate=state) for i in range(0x1337): l.next() key = [] for i in range(len(plaintext)): key.append(l.next()) return "".join([str(plaintext[i]^key[i]) for i in range(len(plaintext))]) def menu(): print("1. Encrypt Random String") print("2. Encrypt Flag") print("3. Exit") return input(">> ") while True: choice = menu() if choice == "1": pt = input("Enter String: ") if len(pt)!=16: print("Invalid String Length") continue print(enc(pt)) elif choice == "2": print(enc(flag)) break elif choice == "3": break else: print("Invalid choice")
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/WRECKCTF/2022/crypto/prime/prime.py
ctfs/WRECKCTF/2022/crypto/prime/prime.py
#!/usr/local/bin/python import random import math with open ("flag.txt", "r") as f: flag = f.read() n = int(input(">> ")) n_len = n.bit_length() if n_len<1020 or n_len>1028: print("no.") quit() for i in range(2,1000): if n%i==0: print("no.") quit() if all([pow(random.randrange(1,n), n-1, n) == 1 for i in range(256)]): a = [] for _ in range(70): a.append(int(input(">> "))) if all([n%i==0 for i in a]): for i in range(len(a)): for j in range(i+1, len(a)): if math.gcd(a[i],a[j])!=1: print(a[i],a[j]) print("no.") quit() print(flag) else: print("no.") quit()
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/WRECKCTF/2022/crypto/token/challenge.py
ctfs/WRECKCTF/2022/crypto/token/challenge.py
#!/usr/local/bin/python import os import random from Crypto.Cipher import AES from Crypto.Util.Padding import pad, unpad KEY = ''.join(random.choice('0123456789abcdef') for _ in range(32)).encode() def encrypt(name): cipher = AES.new(KEY, AES.MODE_ECB) return cipher.encrypt(pad(name.encode(), AES.block_size)).hex() def decrypt(ciphertext): cipher = AES.new(KEY, AES.MODE_ECB) result = unpad(cipher.decrypt(bytes.fromhex(ciphertext)), AES.block_size) return result.decode() print('welcome to the flag viewer!') while 1: print('1. view flag') print('2. generate token') value = input('> ') if value == '1': token = input('token: ') try: name = decrypt(token) except ValueError: print('invalid token') continue if name == 'gary': print(os.environ.get('FLAG', 'no flag provided.')) else: print('sorry, only gary can view the flag') elif value == '2': name = input('name: ') if name == 'gary': print('nice try!') else: print(f'here\'s your token: {encrypt(name)}') else: print('unknown input!')
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/WRECKCTF/2022/crypto/mtp/server.py
ctfs/WRECKCTF/2022/crypto/mtp/server.py
#!/usr/local/bin/python -u import os import random LETTERS = set('abcdefghijklmnopqrstuvwxyz') def encrypt(plaintext, key): return ''.join( chr(permutation[ord(letter) - ord('a')] + ord('a')) if letter in LETTERS else letter for letter, permutation in zip(plaintext, key) ) key = [list(range(26)) for _ in range(256)] for permutation in key: random.shuffle(permutation) print('Welcome to the Multi-Time Pad!') while True: print('1. Encrypt message') print('2. Get flag') choice = input('> ') match choice: case '1': plaintext = input('What\'s your message? ') case '2': plaintext = os.environ.get('FLAG', 'no flag provided!') case _: print('Invalid choice!') continue print(f'Result: {encrypt(plaintext, key)}')
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/WRECKCTF/2022/crypto/spin/encrypt.py
ctfs/WRECKCTF/2022/crypto/spin/encrypt.py
with open('flag.txt', 'r') as file: plaintext = file.read().strip() def spin(c, key): return chr((ord(c) - ord('a') - key) % 26 + ord('a')) ciphertext = ''.join( spin(c, 43) if 'a' <= c <= 'z' else c for c in plaintext ) with open('ciphertext.txt', 'w+') as file: file.write(ciphertext)
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/WRECKCTF/2022/crypto/rsa/rsa.py
ctfs/WRECKCTF/2022/crypto/rsa/rsa.py
#!/usr/local/bin/python from Crypto.Util.number import * p = getPrime(1024) q = getPrime(1024) n = p * q e = 65537 flag = open('flag.txt', 'rb').read() d = inverse(e, (p-1)*(q-1)) pandaman = b"PANDAMAN! I LOVE PANDAMAN! PANDAMAN MY BELOVED! PANDAMAN IS MY FAVORITE PERSON IN THE WHOLE WORLD! PANDAMAN!!!!" def enc(m): if pandaman == m: return "No :(" else: return pow(bytes_to_long(m), d, n) def check(): if long_to_bytes(pow(int(input("Enter here: ")), e, n)) == pandaman: print(flag) else: print("darn :(") def menu(): print("1. Encrypt") print("2. Check") print("3. Exit") return input(">> ") while True: choice = menu() if choice == "1": pt = input("Enter String: ") print(enc(pt.encode('utf-8'))) elif choice == "2": check() elif choice == "3": break else: print("Invalid choice")
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/WRECKCTF/2022/web/password-1/server.py
ctfs/WRECKCTF/2022/web/password-1/server.py
from aiohttp import web class Server: def __init__(self): self.app = web.Application() def get(self, path, c_type='text/html'): def handle(handler): decorated_handler = self._handle_factory(handler, c_type) self.app.add_routes([web.get(path, decorated_handler)]) return handle def post(self, path, c_type='text/html'): def handle(handler): decorated_handler = self._handle_factory(handler, c_type) self.app.add_routes([web.post(path, decorated_handler)]) return handle def _handle_factory(self, handler, c_type): async def decorated_handler(request): status, data = await handler(request) if status == 200: return web.Response( text=data, content_type=c_type, ) if status == 302: raise web.HTTPFound( location=data, ) return web.Response( text=data, status=status, ) return decorated_handler def run(self, host, port): web.run_app(self.app, host=host, port=port)
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/WRECKCTF/2022/web/password-1/app.py
ctfs/WRECKCTF/2022/web/password-1/app.py
import os from server import Server FLAG = os.environ.get('FLAG', 'flag missing!') server = Server() @server.get('/') async def root(request): del request return (200, ''' <link rel="stylesheet" href="/style.css" /> <div class="container"> <form class="content"> <input type="text" placeholder="Password..."/> <input type="submit" value="Login" /> </form> </div> <script> const sha256 = async (message) => { const data = (new TextEncoder()).encode(message); const hashed = await crypto.subtle.digest('SHA-256', data); return Array.from(new Uint8Array(hashed)) .map((b) => b.toString(16).padStart(2, '0')) .join('') } (() => { const form = document.querySelector('form'); form.addEventListener('submit', async (event) => { event.preventDefault(); const input = document.querySelector('input[type="text"]'); const hash = ( '8c59346d674a352c' + 'aa36c0cb808ec0dd' + '28ba42144f760c12' + '564663b610c9ce2d' ); if (await sha256(input.value) === hash) { const flag = await (await fetch('/api/output')).text(); document.querySelector('.content').textContent = flag; } else { input.removeAttribute('style'); input.offsetWidth; input.style.animation = 'shake 0.25s'; } }); })(); </script> ''') @server.get('/style.css', c_type='text/css') async def style(request): del request return (200, ''' html, body { height: 100%; margin: 0; padding: 0; font-family: sans-serif; } body { background-color: rebeccapurple; } .incorrect { animation: shake 0.25s; } .content { transform: scale(4); background-color: white; padding: 2rem; border-radius: 0.5rem; max-width: 18vw; } .container { height: 100%; display: grid; place-items: center; } @keyframes shake { 0% { transform: rotate(0deg); } 25% { transform: rotate(5deg); } 50% { transform: rotate(0eg); } 75% { transform: rotate(-5deg); } 100% { transform: rotate(0deg); } } ''') @server.get('/api/output', c_type='text/plain') async def flag(request): del request return (200, FLAG) server.run('0.0.0.0', 3000)
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/WRECKCTF/2022/web/blog/flaskr/blog.py
ctfs/WRECKCTF/2022/web/blog/flaskr/blog.py
from flask import ( Blueprint, flash, g, redirect, render_template, render_template_string, request, url_for ) from werkzeug.exceptions import abort from flaskr.auth import login_required from flaskr.db import get_db bp = Blueprint('blog', __name__) @bp.route('/') @login_required def index(): db = get_db() posts = db.execute( 'SELECT p.id, title, body, created, author_id, username' ' FROM post p JOIN user u ON p.author_id = u.id' ' ORDER BY created DESC' ).fetchall() return render_template('blog/index.html', posts=posts) @bp.route('/postsuccess') @login_required def postsuccess(): quicktemplate = """ {% extends 'base.html' %} {% block header %} <h1>{% block title %}Success!{% endblock %}</h1> <a class="action" href="{{ url_for('blog.index') }}">Back</a> {% endblock %} {% block content %} <p>Post \"""" + request.args.get('title') + """\" created successfully. </p> {% endblock %} """ return render_template_string(quicktemplate) @bp.route('/create', methods=('GET', 'POST')) @login_required def create(): if request.method == 'POST': title = request.form['title'] body = request.form['body'] error = None if not title: error = 'Title is required.' if error is not None: flash(error) else: db = get_db() db.execute( 'INSERT INTO post (title, body, author_id)' ' VALUES (?, ?, ?)', (title, body, g.user['id']) ) db.commit() return redirect(url_for('blog.postsuccess', title=title)) return render_template('blog/create.html') def get_post(id, check_author=True): post = get_db().execute( 'SELECT p.id, title, body, created, author_id, username' ' FROM post p JOIN user u ON p.author_id = u.id' ' WHERE p.id = ?', (id,) ).fetchone() if post is None: abort(404, f"Post id {id} doesn't exist.") if check_author and post['author_id'] != g.user['id']: abort(403) return post @bp.route('/<int:id>/update', methods=('GET', 'POST')) @login_required def update(id): post = get_post(id) if request.method == 'POST': title = request.form['title'] body = request.form['body'] error = None if not title: error = 'Title is required.' if error is not None: flash(error) else: db = get_db() db.execute( 'UPDATE post SET title = ?, body = ?' ' WHERE id = ?', (title, body, id) ) db.commit() return redirect(url_for('blog.index')) return render_template('blog/update.html', post=post) @bp.route('/<int:id>/delete', methods=('POST',)) @login_required def delete(id): get_post(id) db = get_db() db.execute('DELETE FROM post WHERE id = ?', (id,)) db.commit() return redirect(url_for('blog.index'))
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/WRECKCTF/2022/web/blog/flaskr/db.py
ctfs/WRECKCTF/2022/web/blog/flaskr/db.py
import sqlite3 from werkzeug.security import generate_password_hash db = sqlite3.connect( 'data/db.sqlite3', detect_types=sqlite3.PARSE_DECLTYPES, isolation_level=None, ) db.row_factory = sqlite3.Row def get_db(): return db SCHEMA = ''' PRAGMA journal_mode=WAL; CREATE TABLE IF NOT EXISTS user ( id INTEGER PRIMARY KEY AUTOINCREMENT, username TEXT UNIQUE NOT NULL, password TEXT NOT NULL ); CREATE TABLE IF NOT EXISTS post ( id INTEGER PRIMARY KEY AUTOINCREMENT, author_id INTEGER NOT NULL, created TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP, title TEXT NOT NULL, body TEXT NOT NULL, FOREIGN KEY (author_id) REFERENCES user (id) ); ''' def init_db(): db.executescript(SCHEMA) username = "GeorgePBurdell" try: res = db.execute( "INSERT INTO user (username, password) VALUES (?, ?)", (username, generate_password_hash(open("flaskr/protected/burdellsecrets.txt").read())), ) except sqlite3.IntegrityError: return db.execute( 'INSERT INTO post (title, body, author_id)' ' VALUES (?, ?, ?)', ("No one can read my secrets :)", "/flaskr/protected/burdellsecrets.txt", res.lastrowid) ) db.commit()
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/WRECKCTF/2022/web/blog/flaskr/__init__.py
ctfs/WRECKCTF/2022/web/blog/flaskr/__init__.py
import os from flask import Flask, abort app = Flask(__name__, instance_relative_config=True) app.config.from_mapping( SECRET_KEY=open("flaskr/protected/burdellsecrets.txt").read(), ) # ensure the instance folder exists try: os.makedirs(app.instance_path) except OSError: pass from . import db db.init_db() @app.route('/flaskr/protected/<path:filename>') def protected(filename): if os.path.exists(os.path.join(app.root_path, 'protected', filename)): abort(403) else: abort(404) from . import auth app.register_blueprint(auth.bp) from . import blog app.register_blueprint(blog.bp) app.add_url_rule('/', endpoint='index')
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/WRECKCTF/2022/web/blog/flaskr/auth.py
ctfs/WRECKCTF/2022/web/blog/flaskr/auth.py
import functools from flask import ( Blueprint, flash, g, redirect, render_template, request, session, url_for ) from werkzeug.security import check_password_hash, generate_password_hash from flaskr.db import get_db bp = Blueprint('auth', __name__, url_prefix='/auth') @bp.before_app_request def load_logged_in_user(): user_id = session.get('user_id') if user_id is None: g.user = None else: g.user = get_db().execute( 'SELECT * FROM user WHERE id = ?', (user_id,) ).fetchone() def login_required(view): @functools.wraps(view) def wrapped_view(**kwargs): if g.user is None: db = get_db() user_num = db.execute( "SELECT COUNT(*) FROM user" ).fetchone() username = f'user{user_num[0]}' db.execute( "INSERT INTO user (username, password) VALUES (?, ?)", (username, generate_password_hash("password")), ) db.commit() user = db.execute( 'SELECT * FROM user WHERE username = ?', (username,) ).fetchone() session.clear() session['user_id'] = user['id'] return redirect(url_for('index')) return view(**kwargs) return wrapped_view
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/SekaiCTF/2024/rev/Magnum_Opus/magnum_opus.py
ctfs/SekaiCTF/2024/rev/Magnum_Opus/magnum_opus.py
# uses python 3.11.9 import pickle
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
true
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/SekaiCTF/2024/crypto/Some_Trick/sometrick.py
ctfs/SekaiCTF/2024/crypto/Some_Trick/sometrick.py
import random from secrets import randbelow, randbits from flag import FLAG CIPHER_SUITE = randbelow(2**256) print(f"oPUN_SASS_SASS_l version 4.0.{CIPHER_SUITE}") random.seed(CIPHER_SUITE) GSIZE = 8209 GNUM = 79 LIM = GSIZE**GNUM def gen(n): p, i = [0] * n, 0 for j in random.sample(range(1, n), n - 1): p[i], i = j, j return tuple(p) def gexp(g, e): res = tuple(g) while e: if e & 1: res = tuple(res[i] for i in g) e >>= 1 g = tuple(g[i] for i in g) return res def enc(k, m, G): if not G: return m mod = len(G[0]) return gexp(G[0], k % mod)[m % mod] + enc(k // mod, m // mod, G[1:]) * mod def inverse(perm): res = list(perm) for i, v in enumerate(perm): res[v] = i return res G = [gen(GSIZE) for i in range(GNUM)] FLAG = int.from_bytes(FLAG, 'big') left_pad = randbits(randbelow(LIM.bit_length() - FLAG.bit_length())) FLAG = (FLAG << left_pad.bit_length()) + left_pad FLAG = (randbits(randbelow(LIM.bit_length() - FLAG.bit_length())) << FLAG.bit_length()) + FLAG bob_key = randbelow(LIM) bob_encr = enc(FLAG, bob_key, G) print("bob says", bob_encr) alice_key = randbelow(LIM) alice_encr = enc(bob_encr, alice_key, G) print("alice says", alice_encr) bob_decr = enc(alice_encr, bob_key, [inverse(i) for i in G]) print("bob says", bob_decr)
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/SekaiCTF/2024/crypto/Squares_vs._Cubes/chall.py
ctfs/SekaiCTF/2024/crypto/Squares_vs._Cubes/chall.py
from Crypto.Util.number import bytes_to_long, getPrime from secrets import token_bytes, randbelow from flag import FLAG padded_flag = bytes_to_long(FLAG + token_bytes(128 - len(FLAG))) p, q, r = getPrime(512), getPrime(512), getPrime(512) N = e = p * q * r phi = (p - 1) * (q - 1) * (r - 1) d = pow(e, -1, phi) # Genni likes squares and SBG likes cubes. Let's calculate their values value_for_genni = p**2 + (q + r * padded_flag)**2 value_for_sbg = p**3 + (q + r * padded_flag)**3 x0 = randbelow(N) x1 = randbelow(N) print(f'{N = }') print(f'{x0 = }') print(f'{x1 = }') print('\nDo you prefer squares or cubes? Choose wisely!') # Generate a random k and send v := (x_i + k^e), for Oblivious Transfer # This will allow you to calculate either Genni's or SBG's value # I have no way of knowing who you support. Your secret is completely safe! v = int(input('Send me v: ')) m0 = (pow(v - x0, d, N) + value_for_genni) % N m1 = (pow(v - x1, d, N) + value_for_sbg) % N print(f'{m0 = }') print(f'{m1 = }')
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/SekaiCTF/2024/web/Funny_lfr/app.py
ctfs/SekaiCTF/2024/web/Funny_lfr/app.py
from starlette.applications import Starlette from starlette.routing import Route from starlette.responses import FileResponse async def download(request): return FileResponse(request.query_params.get("file")) app = Starlette(routes=[Route("/", endpoint=download)])
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/SekaiCTF/2023/misc/Just_Another_Pickle_Jail/my_pickle.py
ctfs/SekaiCTF/2023/misc/Just_Another_Pickle_Jail/my_pickle.py
"""Create portable serialized representations of Python objects. See module copyreg for a mechanism for registering custom picklers. See module pickletools source for extensive comments. Classes: Pickler Unpickler Functions: dump(object, file) dumps(object) -> string load(file) -> object loads(bytes) -> object Misc variables: __version__ format_version compatible_formats """ from types import FunctionType from copyreg import dispatch_table from copyreg import _extension_registry, _inverted_registry, _extension_cache from itertools import islice from functools import partial import sys from sys import maxsize from struct import pack, unpack import re import io import codecs import _compat_pickle __all__ = ["PickleError", "PicklingError", "UnpicklingError", "Pickler", "Unpickler", "dump", "dumps", "load", "loads"] try: from _pickle import PickleBuffer __all__.append("PickleBuffer") _HAVE_PICKLE_BUFFER = True except ImportError: _HAVE_PICKLE_BUFFER = False # Shortcut for use in isinstance testing bytes_types = (bytes, bytearray) # These are purely informational; no code uses these. format_version = "4.0" # File format version we write compatible_formats = ["1.0", # Original protocol 0 "1.1", # Protocol 0 with INST added "1.2", # Original protocol 1 "1.3", # Protocol 1 with BINFLOAT added "2.0", # Protocol 2 "3.0", # Protocol 3 "4.0", # Protocol 4 "5.0", # Protocol 5 ] # Old format versions we can read # This is the highest protocol number we know how to read. HIGHEST_PROTOCOL = 5 # The protocol we write by default. May be less than HIGHEST_PROTOCOL. # Only bump this if the oldest still supported version of Python already # includes it. DEFAULT_PROTOCOL = 4 class PickleError(Exception): """A common base class for the other pickling exceptions.""" pass class PicklingError(PickleError): """This exception is raised when an unpicklable object is passed to the dump() method. """ pass class UnpicklingError(PickleError): """This exception is raised when there is a problem unpickling an object, such as a security violation. Note that other exceptions may also be raised during unpickling, including (but not necessarily limited to) AttributeError, EOFError, ImportError, and IndexError. """ pass # An instance of _Stop is raised by Unpickler.load_stop() in response to # the STOP opcode, passing the object that is the result of unpickling. class _Stop(Exception): def __init__(self, value): self.value = value # Jython has PyStringMap; it's a dict subclass with string keys try: from org.python.core import PyStringMap except ImportError: PyStringMap = None # Pickle opcodes. See pickletools.py for extensive docs. The listing # here is in kind-of alphabetical order of 1-character pickle code. # pickletools groups them by purpose. MARK = b'(' # push special markobject on stack STOP = b'.' # every pickle ends with STOP POP = b'0' # discard topmost stack item POP_MARK = b'1' # discard stack top through topmost markobject DUP = b'2' # duplicate top stack item FLOAT = b'F' # push float object; decimal string argument INT = b'I' # push integer or bool; decimal string argument BININT = b'J' # push four-byte signed int BININT1 = b'K' # push 1-byte unsigned int LONG = b'L' # push long; decimal string argument BININT2 = b'M' # push 2-byte unsigned int NONE = b'N' # push None PERSID = b'P' # push persistent object; id is taken from string arg BINPERSID = b'Q' # " " " ; " " " " stack REDUCE = b'R' # apply callable to argtuple, both on stack STRING = b'S' # push string; NL-terminated string argument BINSTRING = b'T' # push string; counted binary string argument SHORT_BINSTRING = b'U' # " " ; " " " " < 256 bytes UNICODE = b'V' # push Unicode string; raw-unicode-escaped'd argument BINUNICODE = b'X' # " " " ; counted UTF-8 string argument APPEND = b'a' # append stack top to list below it BUILD = b'b' # call __setstate__ or __dict__.update() GLOBAL = b'c' # push self.find_class(modname, name); 2 string args DICT = b'd' # build a dict from stack items EMPTY_DICT = b'}' # push empty dict APPENDS = b'e' # extend list on stack by topmost stack slice GET = b'g' # push item from memo on stack; index is string arg BINGET = b'h' # " " " " " " ; " " 1-byte arg INST = b'i' # build & push class instance LONG_BINGET = b'j' # push item from memo on stack; index is 4-byte arg LIST = b'l' # build list from topmost stack items EMPTY_LIST = b']' # push empty list OBJ = b'o' # build & push class instance PUT = b'p' # store stack top in memo; index is string arg BINPUT = b'q' # " " " " " ; " " 1-byte arg LONG_BINPUT = b'r' # " " " " " ; " " 4-byte arg SETITEM = b's' # add key+value pair to dict TUPLE = b't' # build tuple from topmost stack items EMPTY_TUPLE = b')' # push empty tuple SETITEMS = b'u' # modify dict by adding topmost key+value pairs BINFLOAT = b'G' # push float; arg is 8-byte float encoding TRUE = b'I01\n' # not an opcode; see INT docs in pickletools.py FALSE = b'I00\n' # not an opcode; see INT docs in pickletools.py # Protocol 2 PROTO = b'\x80' # identify pickle protocol NEWOBJ = b'\x81' # build object by applying cls.__new__ to argtuple EXT1 = b'\x82' # push object from extension registry; 1-byte index EXT2 = b'\x83' # ditto, but 2-byte index EXT4 = b'\x84' # ditto, but 4-byte index TUPLE1 = b'\x85' # build 1-tuple from stack top TUPLE2 = b'\x86' # build 2-tuple from two topmost stack items TUPLE3 = b'\x87' # build 3-tuple from three topmost stack items NEWTRUE = b'\x88' # push True NEWFALSE = b'\x89' # push False LONG1 = b'\x8a' # push long from < 256 bytes LONG4 = b'\x8b' # push really big long _tuplesize2code = [EMPTY_TUPLE, TUPLE1, TUPLE2, TUPLE3] # Protocol 3 (Python 3.x) BINBYTES = b'B' # push bytes; counted binary string argument SHORT_BINBYTES = b'C' # " " ; " " " " < 256 bytes # Protocol 4 SHORT_BINUNICODE = b'\x8c' # push short string; UTF-8 length < 256 bytes BINUNICODE8 = b'\x8d' # push very long string BINBYTES8 = b'\x8e' # push very long bytes string EMPTY_SET = b'\x8f' # push empty set on the stack ADDITEMS = b'\x90' # modify set by adding topmost stack items FROZENSET = b'\x91' # build frozenset from topmost stack items NEWOBJ_EX = b'\x92' # like NEWOBJ but work with keyword only arguments STACK_GLOBAL = b'\x93' # same as GLOBAL but using names on the stacks MEMOIZE = b'\x94' # store top of the stack in memo FRAME = b'\x95' # indicate the beginning of a new frame # Protocol 5 BYTEARRAY8 = b'\x96' # push bytearray NEXT_BUFFER = b'\x97' # push next out-of-band buffer READONLY_BUFFER = b'\x98' # make top of stack readonly __all__.extend([x for x in dir() if re.match("[A-Z][A-Z0-9_]+$", x)]) class _Unframer: def __init__(self, file_read, file_readline, file_tell=None): self.file_read = file_read self.file_readline = file_readline self.current_frame = None def readinto(self, buf): if self.current_frame: n = self.current_frame.readinto(buf) if n == 0 and len(buf) != 0: self.current_frame = None n = len(buf) buf[:] = self.file_read(n) return n if n < len(buf): raise UnpicklingError( "pickle exhausted before end of frame") return n else: n = len(buf) buf[:] = self.file_read(n) return n def read(self, n): if self.current_frame: data = self.current_frame.read(n) if not data and n != 0: self.current_frame = None return self.file_read(n) if len(data) < n: raise UnpicklingError( "pickle exhausted before end of frame") return data else: return self.file_read(n) def readline(self): if self.current_frame: data = self.current_frame.readline() if not data: self.current_frame = None return self.file_readline() if data[-1] != b'\n'[0]: raise UnpicklingError( "pickle exhausted before end of frame") return data else: return self.file_readline() def load_frame(self, frame_size): if self.current_frame and self.current_frame.read() != b'': raise UnpicklingError( "beginning of a new frame before end of current frame") self.current_frame = io.BytesIO(self.file_read(frame_size)) # Tools used for pickling. def _getattribute(obj, name): for subpath in name.split('.'): if subpath == '<locals>': raise AttributeError("Can't get local attribute {!r} on {!r}" .format(name, obj)) try: parent = obj obj = getattr(obj, subpath) except AttributeError: raise AttributeError("Can't get attribute {!r} on {!r}" .format(name, obj)) from None return obj, parent def whichmodule(obj, name): """Find the module an object belong to.""" module_name = getattr(obj, '__module__', None) if module_name is not None: return module_name # Protect the iteration by using a list copy of sys.modules against dynamic # modules that trigger imports of other modules upon calls to getattr. for module_name, module in sys.modules.copy().items(): if (module_name == '__main__' or module_name == '__mp_main__' # bpo-42406 or module is None): continue try: if _getattribute(module, name)[0] is obj: return module_name except AttributeError: pass return '__main__' def encode_long(x): r"""Encode a long to a two's complement little-endian binary string. Note that 0 is a special case, returning an empty string, to save a byte in the LONG1 pickling context. >>> encode_long(0) b'' >>> encode_long(255) b'\xff\x00' >>> encode_long(32767) b'\xff\x7f' >>> encode_long(-256) b'\x00\xff' >>> encode_long(-32768) b'\x00\x80' >>> encode_long(-128) b'\x80' >>> encode_long(127) b'\x7f' >>> """ if x == 0: return b'' nbytes = (x.bit_length() >> 3) + 1 result = x.to_bytes(nbytes, byteorder='little', signed=True) if x < 0 and nbytes > 1: if result[-1] == 0xff and (result[-2] & 0x80) != 0: result = result[:-1] return result def decode_long(data): r"""Decode a long from a two's complement little-endian binary string. >>> decode_long(b'') 0 >>> decode_long(b"\xff\x00") 255 >>> decode_long(b"\xff\x7f") 32767 >>> decode_long(b"\x00\xff") -256 >>> decode_long(b"\x00\x80") -32768 >>> decode_long(b"\x80") -128 >>> decode_long(b"\x7f") 127 """ return int.from_bytes(data, byteorder='little', signed=True) # Unpickling machinery def die(): # ok theres no way you can like break all of these right... assert 1 == 0 exit() raise _Stop class _Unpickler: def __init__(self, file, *, fix_imports=True, encoding="ASCII", errors="strict", buffers=None): """This takes a binary file for reading a pickle data stream. The protocol version of the pickle is detected automatically, so no proto argument is needed. The argument *file* must have two methods, a read() method that takes an integer argument, and a readline() method that requires no arguments. Both methods should return bytes. Thus *file* can be a binary file object opened for reading, an io.BytesIO object, or any other custom object that meets this interface. The file-like object must have two methods, a read() method that takes an integer argument, and a readline() method that requires no arguments. Both methods should return bytes. Thus file-like object can be a binary file object opened for reading, a BytesIO object, or any other custom object that meets this interface. If *buffers* is not None, it should be an iterable of buffer-enabled objects that is consumed each time the pickle stream references an out-of-band buffer view. Such buffers have been given in order to the *buffer_callback* of a Pickler object. If *buffers* is None (the default), then the buffers are taken from the pickle stream, assuming they are serialized there. It is an error for *buffers* to be None if the pickle stream was produced with a non-None *buffer_callback*. Other optional arguments are *fix_imports*, *encoding* and *errors*, which are used to control compatibility support for pickle stream generated by Python 2. If *fix_imports* is True, pickle will try to map the old Python 2 names to the new names used in Python 3. The *encoding* and *errors* tell pickle how to decode 8-bit string instances pickled by Python 2; these default to 'ASCII' and 'strict', respectively. *encoding* can be 'bytes' to read these 8-bit string instances as bytes objects. """ self._buffers = iter(buffers) if buffers is not None else None self._file_readline = file.readline self._file_read = file.read self.memo = {} self.encoding = encoding self.errors = errors self.proto = 0 self.fix_imports = fix_imports def load(self): """Read a pickled object representation from the open file. Return the reconstituted object hierarchy specified in the file. """ # Check whether Unpickler was initialized correctly. This is # only needed to mimic the behavior of _pickle.Unpickler.dump(). if not hasattr(self, "_file_read"): raise UnpicklingError("Unpickler.__init__() was not called by " "%s.__init__()" % (self.__class__.__name__,)) self._unframer = _Unframer(self._file_read, self._file_readline) self.read = self._unframer.read self.readinto = self._unframer.readinto self.readline = self._unframer.readline self.metastack = [] self.stack = [] self.append = self.stack.append self.proto = 0 read = self.read dispatch = self.dispatch try: while True: key = read(1) if not key: raise EOFError assert isinstance(key, bytes_types) dispatch[key[0]](self) except _Stop as stopinst: return stopinst.value # Return a list of items pushed in the stack after last MARK instruction. def pop_mark(self): items = self.stack self.stack = self.metastack.pop() self.append = self.stack.append return items def persistent_load(self, pid): raise UnpicklingError("unsupported persistent id encountered") dispatch = {} def load_proto(self): proto = self.read(1)[0] if not 0 <= proto <= HIGHEST_PROTOCOL: raise ValueError("unsupported pickle protocol: %d" % proto) self.proto = proto dispatch[PROTO[0]] = load_proto def load_frame(self): frame_size, = unpack('<Q', self.read(8)) if frame_size > sys.maxsize: raise ValueError("frame size > sys.maxsize: %d" % frame_size) self._unframer.load_frame(frame_size) dispatch[FRAME[0]] = load_frame def load_persid(self): try: pid = self.readline()[:-1].decode("ascii") except UnicodeDecodeError: raise UnpicklingError( "persistent IDs in protocol 0 must be ASCII strings") self.append(self.persistent_load(pid)) dispatch[PERSID[0]] = load_persid def load_binpersid(self): pid = self.stack.pop() self.append(self.persistent_load(pid)) dispatch[BINPERSID[0]] = load_binpersid def load_none(self): self.append(None) dispatch[NONE[0]] = load_none def load_false(self): self.append(False) dispatch[NEWFALSE[0]] = load_false def load_true(self): self.append(True) dispatch[NEWTRUE[0]] = load_true def load_int(self): data = self.readline() if data == FALSE[1:]: val = False elif data == TRUE[1:]: val = True else: val = int(data, 0) self.append(val) dispatch[INT[0]] = load_int def load_binint(self): self.append(unpack('<i', self.read(4))[0]) dispatch[BININT[0]] = load_binint def load_binint1(self): self.append(self.read(1)[0]) dispatch[BININT1[0]] = load_binint1 def load_binint2(self): self.append(unpack('<H', self.read(2))[0]) dispatch[BININT2[0]] = load_binint2 def load_long(self): val = self.readline()[:-1] if val and val[-1] == b'L'[0]: val = val[:-1] self.append(int(val, 0)) dispatch[LONG[0]] = load_long def load_long1(self): n = self.read(1)[0] data = self.read(n) self.append(decode_long(data)) dispatch[LONG1[0]] = load_long1 def load_long4(self): n, = unpack('<i', self.read(4)) if n < 0: # Corrupt or hostile pickle -- we never write one like this raise UnpicklingError("LONG pickle has negative byte count") data = self.read(n) self.append(decode_long(data)) dispatch[LONG4[0]] = load_long4 def load_float(self): self.append(float(self.readline()[:-1])) dispatch[FLOAT[0]] = load_float def load_binfloat(self): self.append(unpack('>d', self.read(8))[0]) dispatch[BINFLOAT[0]] = load_binfloat def _decode_string(self, value): # Used to allow strings from Python 2 to be decoded either as # bytes or Unicode strings. This should be used only with the # STRING, BINSTRING and SHORT_BINSTRING opcodes. if self.encoding == "bytes": return value else: return value.decode(self.encoding, self.errors) def load_string(self): data = self.readline()[:-1] # Strip outermost quotes if len(data) >= 2 and data[0] == data[-1] and data[0] in b'"\'': data = data[1:-1] else: raise UnpicklingError("the STRING opcode argument must be quoted") self.append(self._decode_string(codecs.escape_decode(data)[0])) dispatch[STRING[0]] = load_string def load_binstring(self): # Deprecated BINSTRING uses signed 32-bit length len, = unpack('<i', self.read(4)) if len < 0: raise UnpicklingError("BINSTRING pickle has negative byte count") data = self.read(len) self.append(self._decode_string(data)) dispatch[BINSTRING[0]] = load_binstring def load_binbytes(self): len, = unpack('<I', self.read(4)) if len > maxsize: raise UnpicklingError("BINBYTES exceeds system's maximum size " "of %d bytes" % maxsize) self.append(self.read(len)) dispatch[BINBYTES[0]] = load_binbytes def load_unicode(self): self.append(str(self.readline()[:-1], 'raw-unicode-escape')) dispatch[UNICODE[0]] = load_unicode def load_binunicode(self): len, = unpack('<I', self.read(4)) if len > maxsize: raise UnpicklingError("BINUNICODE exceeds system's maximum size " "of %d bytes" % maxsize) self.append(str(self.read(len), 'utf-8', 'surrogatepass')) dispatch[BINUNICODE[0]] = load_binunicode def load_binunicode8(self): len, = unpack('<Q', self.read(8)) if len > maxsize: raise UnpicklingError("BINUNICODE8 exceeds system's maximum size " "of %d bytes" % maxsize) self.append(str(self.read(len), 'utf-8', 'surrogatepass')) dispatch[BINUNICODE8[0]] = load_binunicode8 def load_binbytes8(self): len, = unpack('<Q', self.read(8)) if len > maxsize: raise UnpicklingError("BINBYTES8 exceeds system's maximum size " "of %d bytes" % maxsize) self.append(self.read(len)) dispatch[BINBYTES8[0]] = load_binbytes8 def load_bytearray8(self): len, = unpack('<Q', self.read(8)) if len > maxsize: raise UnpicklingError("BYTEARRAY8 exceeds system's maximum size " "of %d bytes" % maxsize) b = bytearray(len) self.readinto(b) self.append(b) dispatch[BYTEARRAY8[0]] = load_bytearray8 def load_next_buffer(self): if self._buffers is None: raise UnpicklingError("pickle stream refers to out-of-band data " "but no *buffers* argument was given") try: buf = next(self._buffers) except StopIteration: raise UnpicklingError("not enough out-of-band buffers") self.append(buf) dispatch[NEXT_BUFFER[0]] = load_next_buffer def load_readonly_buffer(self): buf = self.stack[-1] with memoryview(buf) as m: if not m.readonly: self.stack[-1] = m.toreadonly() dispatch[READONLY_BUFFER[0]] = load_readonly_buffer def load_short_binstring(self): len = self.read(1)[0] data = self.read(len) self.append(self._decode_string(data)) dispatch[SHORT_BINSTRING[0]] = load_short_binstring def load_short_binbytes(self): len = self.read(1)[0] self.append(self.read(len)) dispatch[SHORT_BINBYTES[0]] = load_short_binbytes def load_short_binunicode(self): len = self.read(1)[0] self.append(str(self.read(len), 'utf-8', 'surrogatepass')) dispatch[SHORT_BINUNICODE[0]] = load_short_binunicode def load_tuple(self): items = self.pop_mark() self.append(tuple(items)) dispatch[TUPLE[0]] = load_tuple def load_empty_tuple(self): self.append(()) dispatch[EMPTY_TUPLE[0]] = load_empty_tuple def load_tuple1(self): self.stack[-1] = (self.stack[-1],) dispatch[TUPLE1[0]] = load_tuple1 def load_tuple2(self): self.stack[-2:] = [(self.stack[-2], self.stack[-1])] dispatch[TUPLE2[0]] = load_tuple2 def load_tuple3(self): self.stack[-3:] = [(self.stack[-3], self.stack[-2], self.stack[-1])] dispatch[TUPLE3[0]] = load_tuple3 def load_empty_list(self): self.append([]) dispatch[EMPTY_LIST[0]] = load_empty_list def load_empty_dictionary(self): self.append({}) dispatch[EMPTY_DICT[0]] = load_empty_dictionary def load_empty_set(self): self.append(set()) dispatch[EMPTY_SET[0]] = load_empty_set def load_frozenset(self): items = self.pop_mark() self.append(frozenset(items)) dispatch[FROZENSET[0]] = load_frozenset def load_list(self): items = self.pop_mark() self.append(items) dispatch[LIST[0]] = load_list def load_dict(self): items = self.pop_mark() d = {items[i]: items[i+1] for i in range(0, len(items), 2)} self.append(d) dispatch[DICT[0]] = load_dict # INST and OBJ differ only in how they get a class object. It's not # only sensible to do the rest in a common routine, the two routines # previously diverged and grew different bugs. # klass is the class to instantiate, and k points to the topmost mark # object, following which are the arguments for klass.__init__. def _instantiate(self, klass, args): die() # lets not! def load_inst(self): module = self.readline()[:-1].decode("ascii") name = self.readline()[:-1].decode("ascii") klass = self.find_class(module, name) # /shrug alr banned _instantiate, what are you going to do self._instantiate(klass, self.pop_mark()) dispatch[INST[0]] = load_inst def load_obj(self): # Stack is ... markobject classobject arg1 arg2 ... args = self.pop_mark() cls = args.pop(0) self._instantiate(cls, args) # ok more _instantiate wow im so scared dispatch[OBJ[0]] = load_obj def load_newobj(self): die() # nope dispatch[NEWOBJ[0]] = load_newobj def load_newobj_ex(self): die() # well... no dispatch[NEWOBJ_EX[0]] = load_newobj_ex def load_global(self): module = self.readline()[:-1].decode("utf-8") name = self.readline()[:-1].decode("utf-8") klass = self.find_class(module, name) self.append(klass) dispatch[GLOBAL[0]] = load_global def load_stack_global(self): name = self.stack.pop() module = self.stack.pop() if type(name) is not str or type(module) is not str: raise UnpicklingError("STACK_GLOBAL requires str") self.append(self.find_class(module, name)) dispatch[STACK_GLOBAL[0]] = load_stack_global def load_ext1(self): code = self.read(1)[0] self.get_extension(code) dispatch[EXT1[0]] = load_ext1 def load_ext2(self): code, = unpack('<H', self.read(2)) self.get_extension(code) dispatch[EXT2[0]] = load_ext2 def load_ext4(self): code, = unpack('<i', self.read(4)) self.get_extension(code) dispatch[EXT4[0]] = load_ext4 def get_extension(self, code): die() # here you can have errors! def find_class(self, _: str, name: str) -> object: # yoinked from azs chall, it was just that goated # Security measure -- prevent access to dangerous elements for x in ['exe', 'os', 'break', 'eva', 'help', 'sys', 'load', 'open', 'dis', 'lic', 'cre']: # you can have set.... ig if x in name: print("Smuggling contraband in broad daylight?! Guards!") break # Security measure -- only the main module is a valid lookup target else: __main__ = object.mgk.nested.__import__('__main__') # hope you didnt have getattr overwriting dreams... return object.__getattribute__(__main__, name) def load_reduce(self): die() # ... do i need to even say anything here... dispatch[REDUCE[0]] = load_reduce def load_pop(self): if self.stack: del self.stack[-1] else: self.pop_mark() dispatch[POP[0]] = load_pop def load_pop_mark(self): self.pop_mark() dispatch[POP_MARK[0]] = load_pop_mark def load_dup(self): self.append(self.stack[-1]) dispatch[DUP[0]] = load_dup def load_get(self): i = int(self.readline()[:-1]) try: self.append(self.memo[i]) except KeyError: msg = f'Memo value not found at index {i}' raise UnpicklingError(msg) from None dispatch[GET[0]] = load_get def load_binget(self): i = self.read(1)[0] try: self.append(self.memo[i]) except KeyError: msg = f'Memo value not found at index {i}' raise UnpicklingError(msg) from None dispatch[BINGET[0]] = load_binget def load_long_binget(self): i, = unpack('<I', self.read(4)) try: self.append(self.memo[i]) except KeyError as exc: msg = f'Memo value not found at index {i}' raise UnpicklingError(msg) from None dispatch[LONG_BINGET[0]] = load_long_binget def load_put(self): i = int(self.readline()[:-1]) try: if (i == 'setattr' or '__' in i): return except: pass if i < 0: raise ValueError("negative PUT argument") self.memo[i] = self.stack[-1] dispatch[PUT[0]] = load_put def load_binput(self): i = self.read(1)[0] try: if (i == 'setattr' or '__' in i): return except: pass if i < 0: raise ValueError("negative BINPUT argument") self.memo[i] = self.stack[-1] dispatch[BINPUT[0]] = load_binput def load_long_binput(self): i, = unpack('<I', self.read(4)) try: if (i == 'setattr' or '__' in i): return except: pass if i > maxsize: raise ValueError("negative LONG_BINPUT argument") self.memo[i] = self.stack[-1] dispatch[LONG_BINPUT[0]] = load_long_binput def load_memoize(self): memo = self.memo i = len(memo) try: if (i == 'setattr' or '__' in i): return except: pass memo[i] = self.stack[-1] dispatch[MEMOIZE[0]] = load_memoize def load_append(self): stack = self.stack value = stack.pop() list = stack[-1] list.append(value) dispatch[APPEND[0]] = load_append def load_appends(self): items = self.pop_mark() list_obj = self.stack[-1] try: extend = list_obj.extend except AttributeError: pass else: extend(items) return # Even if the PEP 307 requires extend() and append() methods, # fall back on append() if the object has no extend() method # for backward compatibility. append = list_obj.append for item in items: append(item) dispatch[APPENDS[0]] = load_appends def load_setitem(self): stack = self.stack value = stack.pop() key = stack.pop() dict = stack[-1] if not (key == 'setattr' or '__' in key): dict[key] = value dispatch[SETITEM[0]] = load_setitem def load_setitems(self): items = self.pop_mark() dict = self.stack[-1] for i in range(0, len(items), 2): if not (items[i] == 'setattr' or '__' in items[i]): dict[items[i]] = items[i + 1] dispatch[SETITEMS[0]] = load_setitems def load_additems(self): die() dispatch[ADDITEMS[0]] = load_additems # too insecure smh def load_build(self): stack = self.stack state = stack.pop() inst = stack[-1] # setstate = getattr(inst, "__setstate__", None) # if setstate is not None: # setstate(state) # return slotstate = None if isinstance(state, tuple) and len(state) == 2: state, slotstate = state if state: inst_dict = inst.__dict__ # intern = sys.intern for k, v in state.items(): # if type(k) is str: # inst_dict[intern(k)] = v # else: if not (k == 'setattr' or '__' in k): inst_dict[k] = v if slotstate: for k, v in slotstate.items(): setattr(inst, k, v) dispatch[BUILD[0]] = load_build def load_mark(self): self.metastack.append(self.stack) self.stack = [] self.append = self.stack.append dispatch[MARK[0]] = load_mark def load_stop(self): value = self.stack.pop() raise _Stop(value) dispatch[STOP[0]] = load_stop def _load(file, *, fix_imports=True, encoding="ASCII", errors="strict", buffers=None): return _Unpickler(file, fix_imports=fix_imports, buffers=buffers, encoding=encoding, errors=errors).load() def _loads(s, /, *, fix_imports=True, encoding="ASCII", errors="strict", buffers=None): if isinstance(s, str): raise TypeError("Can't load pickle from unicode string") file = io.BytesIO(s) return _Unpickler(file, fix_imports=fix_imports, buffers=buffers, encoding=encoding, errors=errors).load()
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
true
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/SekaiCTF/2023/misc/Just_Another_Pickle_Jail/chall.py
ctfs/SekaiCTF/2023/misc/Just_Another_Pickle_Jail/chall.py
#!/usr/bin/python3 # Heavily based on AZ's you shall not call (ictf 2023), because that was a great chall import __main__ # Security measure -- don't let people get io module from io import BytesIO from my_pickle import _Unpickler as Unpickler class mgk: class nested: pass mgk.nested.__import__ = __import__ mgk.nested.banned = list(Unpickler.__dict__.keys()) E = type('', (), {'__eq__': lambda s,o:o})() # from hsctf 2023 x = vars(object) == E x['mgk'] = mgk del x del mgk del E def __setattr__(self, a, b): # wow look it's the custom setattr no one asked for!!!! if a not in object.mgk.nested.banned: __main__ = object.mgk.nested.__import__('__main__') if not ((a == 'setattr' or '__' in a) and self == __main__): # overwriting my protections? How dare you! try: object.__setattr__(self, a, b) except: type.__setattr__(self, a, b) Unpickler.__setattr__ = __setattr__ __import__('builtins').__dict__['setattr'] = __setattr__ del __setattr__ def __import__(x, *_): # ok who needs more than 1 arg like wtf i did not know there was 5 args lmfao if x in ['builtins', '__main__']: return object.mgk.nested.__import__(x) # this is fair trust __import__('builtins').__dict__['__import__'] = __import__ del __main__.__import__ E = type('', (), {'__eq__': lambda s,o:o})() x = vars(type(__main__)) == E def mgetattr(self, a, d=None): for x in ['exe', 'os', 'break', 'eva', 'help', 'sys', 'load', 'open', 'dis', 'lic', 'cre']: if x in a: return None else: try: return object.__getattribute__(self, a) except: try: return type.__getattribute__(self, a) except: return d x['__getattribute__'] = mgetattr # not paranoid __import__('builtins').__dict__['getattr'] = mgetattr # :> del E del x del __main__.mgetattr # Security measure -- remove dangerous magic for k in list(globals()): if '_' in k and k not in ['__main__', '__builtins__']: del globals()[k] del k # Security measure -- remove dangerous magic __builtins__ = vars(__builtins__) for x in ['__name__', '__doc__', '__package__', '__loader__', '__spec__', '__build_class__', '__debug__', '__import__']: del __builtins__[x] try: up = Unpickler(BytesIO(bytes.fromhex(input(">>> ")))) up.load() except: pass
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/SekaiCTF/2023/misc/Blockchain_Play_for_Free/solve.py
ctfs/SekaiCTF/2023/misc/Blockchain_Play_for_Free/solve.py
# sample solve script to interface with the server import pwn # feel free to change this account_metas = [ ("program", "-r"), # read only ("data account", "-w"), # writable ("user", "sw"), # signer + writable ("user data", "sw"), ("system program", "-r"), ] instruction_data = b"placeholder" p = pwn.remote("0.0.0.0", 8080) with open("solve.so", "rb") as f: solve = f.read() p.sendlineafter(b"program pubkey: \n", b"placeholder") p.sendlineafter(b"program len: \n", str(len(solve)).encode()) p.send(solve) accounts = {} for l in p.recvuntil(b"num accounts: \n", drop=True).strip().split(b"\n"): [name, pubkey] = l.decode().split(": ") accounts[name] = pubkey p.sendline(str(len(account_metas)).encode()) for (name, perms) in account_metas: p.sendline(f"{perms} {accounts[name]}".encode()) p.sendlineafter(b"ix len: \n", str(len(instruction_data)).encode()) p.send(instruction_data) p.interactive()
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/SekaiCTF/2023/crypto/cryptoGRAPHy_3/server.py
ctfs/SekaiCTF/2023/crypto/cryptoGRAPHy_3/server.py
from itertools import product, chain from multiprocessing import Pool from lib import GES import networkx as nx import random import time from SECRET import flag, generate_tree, decrypt NODE_COUNT = 60 SECURITY_PARAMETER = 128 MENU = '''============ MENU ============ 1. Graph Information 2. Query Responses 3. Challenge 4. Exit ==============================''' def query_resps(cores: int, key: bytes, G: nx.Graph, myGES: GES.GESClass, enc_db): n = len(G.nodes()) query_list = [] queries = product(set(), set()) for component in nx.connected_components(G): queries = chain(queries, product(component, component)) iterable = product([key], queries) chunk = n * n // cores with Pool(cores) as pool: for token in pool.istarmap(myGES.tokenGen, iterable, chunksize=chunk): tok, resp = myGES.search(token, enc_db) query_list.append((token.hex() + tok.hex(), resp.hex())) random.shuffle(query_list) return query_list if __name__ == '__main__': try: G = generate_tree() assert len(G.nodes()) == NODE_COUNT myGES = GES.GESClass(cores=4, encrypted_db={}) key = myGES.keyGen(SECURITY_PARAMETER) enc_db = myGES.encryptGraph(key, G) t = time.time() print("[!] Recover 10 queries in 30 seconds. It is guaranteed that each answer is unique.") while True: print(MENU) option = input("> Option: ").strip() if option == "1": print("[!] Graph information:") print("[*] Edges:", G.edges()) elif option == "2": print(f"[*] Query Responses: ") resp = query_resps(4, key, G, myGES, enc_db) for r in resp: print(f"{r[0]} {r[1]}") elif option == "3": break else: exit() print("[!] In each query, input the shortest path decrypted from response. \ It will be a string of space-separated nodes from source to destination, e.g. '1 2 3 4'.") for q in range(10): print(f"[+] Challenge {q+1}/10.") while True: u, v = random.choices(list(G.nodes()), k=2) if u != v and nx.has_path(G, u, v): break token = myGES.tokenGen(key, (u, v)) print(f"[*] Token: {token.hex()}") tok, resp = myGES.search(token, enc_db) print(f"[*] Query Response: {tok.hex() + resp.hex()}") ans = input("> Original query: ").strip() if ans != decrypt(u, v, resp, key): print("[!] Wrong answer!") exit() if time.time() - t > 30: print("[!] Time's up!") exit() print(f"[+] Flag: {flag}") except: exit()
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/SekaiCTF/2023/crypto/Noisier_CRC/chall.py
ctfs/SekaiCTF/2023/crypto/Noisier_CRC/chall.py
import secrets from Crypto.Util.number import * from Crypto.Cipher import AES from hashlib import sha256 from flag import FLAG isIrreducible = [True for i in range(1 << 17)] def init(): for f in range(2, 1 << 17): if isIrreducible[f]: ls = [0] # store all multiples of polynomial `f` cur_term = f while cur_term < (1 << 17): ls = ls + [x ^ cur_term for x in ls] cur_term <<= 1 for g in ls[2:]: # the first two terms are 0, f respectively isIrreducible[g] = False def getCRC16(msg, gen_poly): assert (1 << 16) <= gen_poly < (1 << 17) # check if deg = 16 msglen = msg.bit_length() msg <<= 16 for i in range(msglen - 1, -1, -1): if (msg >> (i + 16)) & 1: msg ^= (gen_poly << i) return msg def oracle(secret, gen_poly): l = int(13.37) res = [secrets.randbits(16) for _ in range(l)] res[secrets.randbelow(l)] = getCRC16(secret, gen_poly) return res def main(): init() # build table of irreducible polynomials key = secrets.randbits(512) cipher = AES.new(sha256(long_to_bytes(key)).digest()[:16], AES.MODE_CTR, nonce=b"12345678") enc_flag = cipher.encrypt(FLAG) print(f"Encrypted flag: {enc_flag.hex()}") used = set({}) for _ in range(int(133.7)): gen_poly = int(input("Give me your generator polynomial: ")) assert (1 << 16) <= gen_poly < (1 << 17) # check if deg = 16 if not isIrreducible[gen_poly]: print("Invalid polynomial") exit(1) if gen_poly in used: print("No cheating") exit(1) used.add(gen_poly) print(oracle(key, gen_poly)) main()
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/SekaiCTF/2023/crypto/cryptoGRAPHy_1/utils.py
ctfs/SekaiCTF/2023/crypto/cryptoGRAPHy_1/utils.py
from typing import * import multiprocessing.pool as mpp import networkx as nx from Crypto.Hash import HMAC, SHA256 from Crypto.Cipher import AES from Crypto.Util.Padding import pad, unpad ''' Utility functions ''' def istarmap(self, func, iterable, chunksize): ''' starmap equivalent using imap. Feel free to ignore this function for challenge purposes. ''' if self._state != mpp.RUN: raise ValueError("Pool not running") if chunksize < 1: raise ValueError("Chunksize must be 1+, not {0:n}".format(chunksize)) task_batches = mpp.Pool._get_tasks(func, iterable, chunksize) result = mpp.IMapIterator(self) self._taskqueue.put(( self._guarded_task_generation(result._job, mpp.starmapstar, task_batches), result._set_length )) return (item for chunk in result for item in chunk) mpp.Pool.istarmap = istarmap def int_to_bytes(x: int) -> bytes: return str(x).encode() def pair_to_bytes(pair: Tuple[int, int]) -> bytes: return int_to_bytes(pair[0]) + b',' + int_to_bytes(pair[1]) def generate_graph(edges: List[List[int]]) -> nx.Graph: ''' Input: A list of edges (u, v) Output: A networkx graph ''' G = nx.Graph() for edge in edges: G.add_edge(*edge) return G def Hash(data: bytes) -> bytes: h = SHA256.new() h.update(data) return h.digest() def SymmetricEncrypt(key: bytes, plaintext: bytes) -> bytes: ''' Encrypt the plaintext using AES-CBC mode with provided key. Input: 16-byte key and plaintext Output: Ciphertext ''' if len(key) != 16: raise ValueError cipher = AES.new(key, AES.MODE_CBC) ct = cipher.encrypt(pad(plaintext, AES.block_size)) iv = cipher.iv return ct + iv def SymmetricDecrypt(key: bytes, ciphertext: bytes) -> bytes: ''' Decrypt the ciphertex using AES-CBC mode with provided key. Input: 16-byte key and ciphertext Output: Plaintext ''' if len(key) != 16: raise ValueError ct, iv = ciphertext[:-16], ciphertext[-16:] cipher = AES.new(key, AES.MODE_CBC, iv) pt = unpad(cipher.decrypt(ct), AES.block_size) return pt def HashMAC(key: bytes, plaintext: bytes) -> bytes: ''' Input: Key and plaintext Output: A token on plaintext with the key using HMAC ''' token = HMAC.new(key, digestmod=SHA256) token.update(bytes(plaintext)) return token.digest() if __name__ == '__main__': # Test SymmetricEncrypt and SymmetricDecrypt key = b"a" * 16 plaintext = b"Hello world!" ciphertext = SymmetricEncrypt(key, plaintext) assert SymmetricDecrypt(key, ciphertext) == plaintext # Test generate_graph G = generate_graph([[1, 2], [2, 4], [1, 3], [3, 5], [5, 4]]) assert G.number_of_nodes() == 5 assert nx.shortest_path(G, 1, 4) == [1, 2, 4]
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/SekaiCTF/2023/crypto/cryptoGRAPHy_1/DES.py
ctfs/SekaiCTF/2023/crypto/cryptoGRAPHy_1/DES.py
from __future__ import annotations from typing import * from Crypto.Random import get_random_bytes from itertools import product from multiprocessing import Pool import utils class DESClass: ''' Implementation of dictionary encryption scheme ''' def __init__(self, encrypted_db: dict[bytes, bytes] = {}): self.encrypted_db = encrypted_db def keyGen(self, security_parameter: int) -> bytes: ''' Input: Security parameter Output: Secret key ''' return get_random_bytes(security_parameter) def encryptDict(self, key: bytes, plaintext_dx: dict[bytes, bytes], cores: int) -> dict[bytes, bytes]: ''' Input: A key and a plaintext dictionary Output: An encrypted dictionary EDX ''' encrypted_db = {} chunk = int(len(plaintext_dx)/cores) iterable = product([key], plaintext_dx.items()) with Pool(cores) as pool: for ct_label, ct_value in pool.istarmap(encryptDictHelper, iterable, chunksize=chunk): encrypted_db[ct_label] = ct_value return encrypted_db def tokenGen(self, key: bytes, label: bytes) -> bytes: ''' Input: A key and a label Output: A token on label ''' K1 = utils.HashMAC(key, b'1'+label)[:16] K2 = utils.HashMAC(key, b'2'+label)[:16] return K1 + K2 def search(self, search_token: bytes, encrypted_db: dict[bytes, bytes]) -> bytes: ''' Input: Search token and EDX Output: The corresponding encrypted value. ''' K1 = search_token[:16] K2 = search_token[16:] hash_val = utils.Hash(K1) if hash_val in encrypted_db: ct_value = encrypted_db[hash_val] return utils.SymmetricDecrypt(K2, ct_value) else: return b'' def encryptDictHelper(key, dict_item): label = dict_item[0] value = dict_item[1] K1 = utils.HashMAC(key, b'1'+label)[:16] K2 = utils.HashMAC(key, b'2'+label)[:16] ct_label = utils.Hash(K1) ct_value = utils.SymmetricEncrypt(K2, value) return ct_label, ct_value
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/SekaiCTF/2023/crypto/cryptoGRAPHy_1/GES.py
ctfs/SekaiCTF/2023/crypto/cryptoGRAPHy_1/GES.py
from __future__ import annotations from typing import * from multiprocessing import Pool from itertools import product from Crypto.Random import get_random_bytes import networkx as nx import gc import DES import utils DES = DES.DESClass({}) class GESClass: ''' Implementation of graph encryption scheme ''' def __init__(self, cores: int, encrypted_db: dict[bytes, bytes] = {}): self.encrypted_db = encrypted_db self.cores = cores def keyGen(self, security_parameter: int) -> bytes: ''' Input: Security parameter Output: Secret key key_SKE||key_DES ''' key_SKE = get_random_bytes(security_parameter) key_DES = DES.keyGen(security_parameter) return key_SKE + key_DES def encryptGraph(self, key: bytes, G: nx.Graph) -> dict[bytes, bytes]: ''' Input: Secret key and a graph G Output: Encrypted graph encrypted_db ''' SPDX = computeSPDX(key, G, self.cores) key_DES = key[16:] EDB = DES.encryptDict(key_DES, SPDX, self.cores) del(SPDX) gc.collect() return EDB def tokenGen(self, key: bytes, query: tuple(int,int)) -> bytes: key_DES = key[16:] label = utils.pair_to_bytes(query) return DES.tokenGen(key_DES, label) def search(self, token: bytes, encrypted_db: dict[bytes, bytes]) -> Tuple(bytes, bytes): ''' Input: Search token Output: (tokens, cts) ''' resp, tok = b"", b"" curr = token while True: value = DES.search(curr, encrypted_db) if value == b'': break curr = value[:32] resp += value[32:] tok += curr return tuple([tok, resp]) def computeSDSP(G: nx.Graph, root): ''' Input: Graph G and a root Output: Tuples of the form ((start, root), (next_vertex, root)) ''' paths = nx.single_source_shortest_path(G, root) S = set() for _, path in paths.items(): path.reverse() if len(path) > 1: for i in range(len(path)-1): label = (path[i], root) value = (path[i+1],root) S.add((label, value)) return S def computeSPDX(key: bytes, G: nx.Graph, cores: int) -> dict[bytes, bytes]: SPDX = {} chunk = round(len(G.nodes())/cores) key_SKE = key[:16] key_DES = key[16:] with Pool(cores) as pool: iterable = product([G], G) for S in pool.istarmap(computeSDSP, iterable, chunksize=chunk): for pair in S: label, value = pair[0], pair[1] label_bytes = utils.pair_to_bytes(label) value_bytes = utils.pair_to_bytes(value) if label_bytes not in SPDX: token = DES.tokenGen(key_DES, value_bytes) ct = utils.SymmetricEncrypt(key_SKE,value_bytes) ct_value = token + ct SPDX[label_bytes] = ct_value return SPDX
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/SekaiCTF/2023/crypto/cryptoGRAPHy_1/server.py
ctfs/SekaiCTF/2023/crypto/cryptoGRAPHy_1/server.py
from lib import GES, utils import networkx as nx import random from SECRET import flag, decrypt NODE_COUNT = 130 EDGE_COUNT = 260 SECURITY_PARAMETER = 16 def gen_random_graph(node_count: int, edge_count: int) -> nx.Graph: nodes = [i for i in range(1, node_count + 1)] edges = [] while len(edges) < edge_count: u, v = random.choices(nodes, k=2) if u != v and (u, v) not in edges and (v, u) not in edges: edges.append([u, v]) return utils.generate_graph(edges) if __name__ == '__main__': try: print("[+] Generating random graph...") G = gen_random_graph(NODE_COUNT, EDGE_COUNT) myGES = GES.GESClass(cores=4, encrypted_db={}) key = myGES.keyGen(SECURITY_PARAMETER) print(f"[*] Key: {key.hex()}") print("[+] Encrypting graph...") enc_db = myGES.encryptGraph(key, G) print("[!] Answer 50 queries to get the flag. In each query, input the shortest path \ decrypted from response. It will be a string of space-separated nodes from \ source to destination, e.g. '1 2 3 4'.") for q in range(50): while True: u, v = random.choices(list(G.nodes), k=2) if nx.has_path(G, u, v): break print(f"[+] Query {q+1}/50: {u} {v}") token = myGES.tokenGen(key, (u, v)) _, resp = myGES.search(token, enc_db) print(f"[*] Response: {resp.hex()}") ans = input("> Original query: ").strip() if ans != decrypt(u, v, resp, key): print("[!] Wrong answer!") exit() print(f"[+] Flag: {flag}") except: exit()
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/SekaiCTF/2023/crypto/Diffecientwo/diffecientwo.py
ctfs/SekaiCTF/2023/crypto/Diffecientwo/diffecientwo.py
import math import mmh3 class BloomFilter: def __init__(self, m, k, hash_func=mmh3.hash): self.__m = m self.__k = k self.__i = 0 self.__digests = set() self.hash = hash_func def security(self): false_positive = pow( 1 - pow(math.e, -self.__k * self.__i / self.__m), self.__k) try: return int(1 / false_positive).bit_length() except (ZeroDivisionError, OverflowError): return float('inf') def _add(self, item): self.__i += 1 for i in range(self.__k): self.__digests.add(self.hash(item, i) % self.__m) def check(self, item): return all(self.hash(item, i) % self.__m in self.__digests for i in range(self.__k)) def num_passwords(self): return self.__i def memory_consumption(self): return 4 * len(self.__digests) class SocialCache(BloomFilter): def __init__(self, m, k, post_size=32, num_posts=16, hash_func=mmh3.hash): super().__init__(m, k, hash_func) self.post_size = post_size self._num_posts = num_posts def add_post(self, post: bytes): if len(post) > self.post_size: print("Post too long") elif self._num_posts <= 0: print("User exceeded number of allowed posts") else: self._add(post) self._num_posts -= 1 print("Added successfully! Posts remaining", self._num_posts) def find_post(self, post: bytes): if self.check(post): print("Found the post in our DB") else: print("Could not find post in our DB") def grant_free_api(self): if self.check(b"#SEKAICTF #DEUTERIUM #DIFFECIENTWO #CRYPTO"): from flag import flag print(flag) else: print("Sorry, you dont seem to have posted about us") BANNER = r""" ____ ____ ____ ____ ____ ___ ____ ____ _ _ ____ _ _ _____ ( _ \(_ _)( ___)( ___)( ___)/ __)(_ _)( ___)( \( )(_ _)( \/\/ )( _ ) )(_) )_)(_ )__) )__) )__)( (__ _)(_ )__) ) ( )( ) ( )(_)( (____/(____)(__) (__) (____)\___)(____)(____)(_)\_) (__) (__/\__)(_____) Welcome to diffecientwo caching database API for tracking and storing content across social media. We have repurposed our security product as saving the admin key was probably not the best idea, but we have decided to change our policies and to achieve better marketing, we are offering free API KEY to customers sharing #SEKAICTF #DEUTERIUM #DIFFECIENTWO #CRYPTO on LonelyFans (our premium business partner). """ print(BANNER) LONELY_FANS = SocialCache(2**32 - 5, 64, 32, 22) while True: try: option = int(input("Enter API option:\n")) if option == 1: post = bytes.fromhex(input("Enter post in hex\n")) LONELY_FANS.find_post(post) elif option == 2: post = bytes.fromhex(input("Enter post in hex\n")) LONELY_FANS.add_post(post) elif option == 3: LONELY_FANS.grant_free_api() elif option == 4: exit(0) except BaseException: print("Something wrong happened") exit(1)
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/SekaiCTF/2023/crypto/Noisy_CRC/chall.py
ctfs/SekaiCTF/2023/crypto/Noisy_CRC/chall.py
import secrets from Crypto.Util.number import * from Crypto.Cipher import AES from hashlib import sha256 from flag import FLAG def getCRC16(msg, gen_poly): assert (1 << 16) <= gen_poly < (1 << 17) # check if deg = 16 msglen = msg.bit_length() msg <<= 16 for i in range(msglen - 1, -1, -1): if (msg >> (i + 16)) & 1: msg ^= (gen_poly << i) return msg def oracle(secret, gen_poly): res = [secrets.randbits(16) for _ in range(3)] res[secrets.randbelow(3)] = getCRC16(secret, gen_poly) return res def main(): key = secrets.randbits(512) cipher = AES.new(sha256(long_to_bytes(key)).digest()[:16], AES.MODE_CTR, nonce=b"12345678") enc_flag = cipher.encrypt(FLAG) print(f"Encrypted flag: {enc_flag.hex()}") used = set({}) while True: gen_poly = int(input("Give me your generator polynomial: ")) assert (1 << 16) <= gen_poly < (1 << 17) # check if deg = 16 if gen_poly in used: print("No cheating") exit(1) used.add(gen_poly) print(oracle(key, gen_poly)) main()
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/SekaiCTF/2023/crypto/cryptoGRAPHy_2/server.py
ctfs/SekaiCTF/2023/crypto/cryptoGRAPHy_2/server.py
from lib import GES, utils import networkx as nx import random from SECRET import flag, get_SDSP_node_degrees ''' get_SDSP_node_degrees(G, dest) returns the node degrees in the single-destination shortest path (SDSP) tree, sorted in ascending order. For example, if G has 5 nodes with edges (1,2),(1,3),(2,3),(2,5),(4,5) and dest=1, returns "1 1 2 2 2". [+] Original: [+] SDSP: 1--2--5--4 1--2--5--4 | / | 3 3 ''' # Another example for sanity check TestGraph = utils.generate_graph([[1, 2], [1, 4], [1, 6], [6, 5], [6, 7], [4, 7], [2, 5]]) assert get_SDSP_node_degrees(TestGraph, 1) == '1 1 1 2 2 3' NODE_COUNT = 130 EDGE_PROB = 0.031 SECURITY_PARAMETER = 32 def gen_random_graph() -> nx.Graph: return nx.fast_gnp_random_graph(n=NODE_COUNT, p=EDGE_PROB) if __name__ == '__main__': try: print("[!] Pass 10 challenges to get the flag:") for q in range(10): print(f"[+] Challenge {q+1}/10. Generating random graph...") while True: G = gen_random_graph() if nx.is_connected(G): break myGES = GES.GESClass(cores=4, encrypted_db={}) key = myGES.keyGen(SECURITY_PARAMETER) print("[+] Encrypting graph...") enc_db = myGES.encryptGraph(key, G) dest = random.choice(list(G.nodes())) print(f"[*] Destination: {dest}") attempts = NODE_COUNT while attempts > 0: attempts -= 1 query = input("> Query u,v: ").strip() try: u, v = map(int, query.split(',')) assert u in G.nodes() and v in G.nodes() and u != v except: print("[!] Invalid query!") break token = myGES.tokenGen(key, (u, v)) print(f"[*] Token: {token.hex()}") tok, resp = myGES.search(token, enc_db) print(f"[*] Query Response: {tok.hex() + resp.hex()}") ans = input("> Answer: ").strip() if ans != get_SDSP_node_degrees(G, dest): print("[!] Wrong answer!") exit() print(f"[+] Flag: {flag}") except: exit()
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/SekaiCTF/2023/crypto/RandSubWare/chall.py
ctfs/SekaiCTF/2023/crypto/RandSubWare/chall.py
from math import log2 import random import secrets import signal def gen_pbox(s, n): """ Generate a balanced permutation box for an SPN :param s: Integer, number of bits per S-box. :param n: Integer, number of S-boxes. :return: List of integers, representing the generated P-box. """ return [(s * i + j) % (n * s) for j in range(s) for i in range(n)] def gen_sbox(n): """ Gen SBox for a given non negative integer n using a random permutation. Parameters: :param n: Integer, the bit size of sbox :return: List of integers, representing 2^n elements corresponding to the SBox permutation generated for the input. """ a, b = 2**((n + 1) // 2), 2**(n // 2) x = list(range(a)) random.shuffle(x) res = x[:] for i in range(b - 1): for j in range(len(x)): res.insert((i + 2) * j - 1, a * (i + 1) + x[j]) res = [res[i] for i in res] return res def rotate_left(val, shift, mod): """ Rotate the bits of the value to the left by the shift amount. The function rotates the bits of the value to the left by the shift amount, wrapping the bits that overflow. The result is then masked by (1<<mod)-1 to only keep the mod number of least significant bits. :param val: Integer, the value to be rotated. :param shift: Integer, the number of places to shift the value to the left. :param mod: Integer, the modulo to be applied on the result. :return: Integer, the rotated value. """ shift = shift % mod return (val << shift | val >> (mod - shift)) & ((1 << mod) - 1) class SPN: def __init__(self, SBOX, PBOX, key, rounds): """ Initialize the SPN class with the provided parameters. :param SBOX: List of integers representing the S-box. :param PBOX: List of integers representing the P-box. :param key: List of integers, bytes or bytearray representing the key. LSB BLOCK_SIZE bits will be used :param rounds: Integer, number of rounds for the SPN. """ self.SBOX = SBOX self.PBOX = PBOX self.SINV = [SBOX.index(i) for i in range(len(SBOX))] self.PINV = [PBOX.index(i) for i in range(len(PBOX))] self.BLOCK_SIZE = len(PBOX) self.BOX_SIZE = int(log2(len(SBOX))) self.NUM_SBOX = len(PBOX) // self.BOX_SIZE self.rounds = rounds self.round_keys = self.expand_key(key, rounds) def perm(self, inp): """ Apply the P-box permutation on the input. :param inp: Integer, the input value to apply the P-box permutation on. :return: Integer, the permuted value after applying the P-box. """ ct = 0 for i, v in enumerate(self.PBOX): ct |= (inp >> (self.BLOCK_SIZE - 1 - i) & 1) << (self.BLOCK_SIZE - 1 - v) return ct def inv_perm(self, inp): """ Apply the inverse P-box permutation on the input. :param inp: Integer, the input value to apply the inverse P-box permutation on. :return: Integer, the permuted value after applying the inverse P-box. """ ct = 0 for i, v in enumerate(self.PINV): ct |= (inp >> (self.BLOCK_SIZE - 1 - i) & 1) << (self.BLOCK_SIZE - 1 - v) return ct def sbox(self, inp): """ Apply the S-box substitution on the input. :param inp: Integer, the input value to apply the S-box substitution on. :return: Integer, the substituted value after applying the S-box. """ ct, BS = 0, self.BOX_SIZE for i in range(self.NUM_SBOX): ct |= self.SBOX[(inp >> (i * BS)) & ((1 << BS) - 1)] << (BS * i) return ct def inv_sbox(self, inp: int) -> int: """ Apply the inverse S-box substitution on the input. :param inp: Integer, the input value to apply the inverse S-box substitution on. :return: Integer, the substituted value after applying the inverse S-box. """ ct, BS = 0, self.BOX_SIZE for i in range(self.NUM_SBOX): ct |= self.SINV[(inp >> (i * BS)) & ((1 << BS) - 1)] << (BS * i) return ct def int_to_list(self, inp): """ Convert a len(PBOX)-sized integer to a list of S-box sized integers. :param inp: Integer, representing a len(PBOX)-sized input. :return: List of integers, each representing an S-box sized input. """ BS = self.BOX_SIZE return [(inp >> (i * BS)) & ((1 << BS) - 1) for i in range(self.NUM_SBOX - 1, -1, -1)] def list_to_int(self, lst): """ Convert a list of S-box sized integers to a len(PBOX)-sized integer. :param lst: List of integers, each representing an S-box sized input. :return: Integer, representing the combined input as a len(PBOX)-sized integer. """ res = 0 for i, v in enumerate(lst[::-1]): res |= v << (i * self.BOX_SIZE) return res def expand_key(self, key, rounds): """ Derive round keys deterministically from the given key. :param key: List of integers, bytes, or bytearray representing the key. :param rounds: Integer, number of rounds for the SPN. :return: List of integers, representing the derived round keys. """ if isinstance(key, list): key = self.list_to_int(key) elif isinstance(key, (bytes, bytearray)): key = int.from_bytes(key, 'big') block_mask = (1 << self.BLOCK_SIZE) - 1 key = key & block_mask keys = [key] for _ in range(rounds): keys.append(self.sbox(rotate_left( keys[-1], self.BOX_SIZE + 1, self.BLOCK_SIZE))) return keys def encrypt(self, pt): """ Encrypt plaintext using the SPN, where the last round doesn't contain the permute operation. :param pt: Integer, plaintext input to be encrypted. :return: Integer, ciphertext after encryption. """ ct = pt ^ self.round_keys[0] for round_key in self.round_keys[1:-1]: ct = self.sbox(ct) ct = self.perm(ct) ct ^= round_key ct = self.sbox(ct) return ct ^ self.round_keys[-1] def decrypt(self, ct): """ Decrypt ciphertext using the SPN, where the last round doesn't contain the permute operation. :param ct: Integer, ciphertext input to be decrypted. :return: Integer, plaintext after decryption. """ ct = ct ^ self.round_keys[-1] ct = self.inv_sbox(ct) for rk in self.round_keys[-2:0:-1]: ct ^= rk ct = self.inv_perm(ct) ct = self.inv_sbox(ct) return ct ^ self.round_keys[0] def encrypt_bytes(self, pt): """ Encrypt bytes using the SPN, in ECB on encrypt :param pt: bytes, should be multiple of BLOCK_SIZE//8 :return: bytes, ciphertext after block-by-block encryption """ block_len = self.BLOCK_SIZE // 8 assert len(pt) % block_len == 0 int_blocks = [int.from_bytes(pt[i:i + block_len], 'big') for i in range(0, len(pt), block_len)] return b''.join(self.encrypt(i).to_bytes(block_len, 'big') for i in int_blocks) class Challenge: def __init__(self, box_size, num_box, num_rounds, max_mess): pbox = gen_pbox(box_size, num_box) sbox = gen_sbox(box_size) key = secrets.randbits(box_size * num_box) self.spn = SPN(sbox, pbox, key, num_rounds) self.quota = max_mess def query(self, text_hex): block_len = self.spn.BLOCK_SIZE // 8 if len(text_hex) & 1: text_hex += "0" text = bytes.fromhex(text_hex) text += bytes((block_len - len(text)) % block_len) if self.quota <= 0: raise Exception( "Encryption quota exceeded, buy pro subscription for $69/month") self.quota -= len(text) // block_len print("Quota remaining:", self.quota) return self.spn.encrypt_bytes(text).hex() def get_flag(self, key_guess): if key_guess == self.spn.round_keys[0]: from flag import flag print(flag) else: raise Exception("There is no free lunch") if __name__ == "__main__": BOX_SIZE = 6 NUM_BOX = 16 QUOTA = 50000 ROUNDS = 5 PROMPT = ("Choose API option\n" "1. Test encryption\n" "2. Get Flag\n") challenge = Challenge(BOX_SIZE, NUM_BOX, ROUNDS, QUOTA) print("sbox:", "".join(hex(i)[2:].zfill(2) for i in challenge.spn.SBOX)) signal.alarm(500) while True: try: option = int(input(PROMPT)) if option == 1: pt = input("(hex) text: ") print(challenge.query(pt)) elif option == 2: key = int(input("(int) key: ")) challenge.get_flag(key) exit(0) except Exception as e: print(e) exit(1)
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/SekaiCTF/2023/web/Chunky/blog/src/app.py
ctfs/SekaiCTF/2023/web/Chunky/blog/src/app.py
from flask import ( Flask, render_template, request, session, redirect, make_response, ) import os import blog_posts.blog_posts as blog_posts import users.users as users from admin.admin import admin_bp app = Flask(__name__) app.secret_key = os.getenv("SECRET_KEY") app.register_blueprint(admin_bp) def do_not_cache(s): r = make_response(s) r.headers["Cache-Control"] = "no-store" return r def init_db(): users.init_table() blog_posts.init_table() init_db() @app.route("/") def home(): return do_not_cache(render_template("home.html")) @app.route("/signup", methods=["GET", "POST"]) def signup(): if request.method == "POST": username = request.form["username"] password = request.form["password"] user, err = users.create_user(username, password) if err is not None: return do_not_cache(render_template("error.html", error=err)) return do_not_cache(redirect("/login")) return do_not_cache(render_template("signup.html")) @app.route("/login", methods=["GET", "POST"]) def login(): if request.method == "POST": username = request.form["username"] password = request.form["password"] res, user = users.verify_credentials(username, password) if res is True: session["user_id"] = user["id"] return do_not_cache(redirect("/")) else: return do_not_cache( render_template("login.html", error="Invalid username or password") ) return do_not_cache(render_template("login.html")) @app.route("/logout") def logout(): session.pop("user_id", None) return do_not_cache(redirect("/")) @app.route("/create_post", methods=["GET", "POST"]) def create_post(): if "user_id" not in session: return do_not_cache(redirect("/login")) if request.method == "POST": title = request.form["title"] content = request.form["content"] user_id = session["user_id"] post_id = blog_posts.create_post(title, content, user_id) return do_not_cache(redirect(f"/post/{user_id}/{post_id}")) if request.method == "GET": return do_not_cache(render_template("create_post.html")) @app.route("/post/<user_id>/<post_id>") def post(user_id, post_id): post = blog_posts.get_post(post_id) return render_template("post.html", post=post) @app.route("/<user_id>/.well-known/jwks.json") def jwks(user_id): f = open("jwks.json", "r") jwks_contents = f.read() f.close() return jwks_contents
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/SekaiCTF/2023/web/Chunky/blog/src/blog_posts/blog_posts.py
ctfs/SekaiCTF/2023/web/Chunky/blog/src/blog_posts/blog_posts.py
import os import uuid import sqlite3 db = os.getenv("DB") def init_table(): conn = sqlite3.connect(db) cursor = conn.cursor() cursor.execute( """ CREATE TABLE IF NOT EXISTS blog_posts ( id TEXT PRIMARY KEY, title TEXT NOT NULL, content TEXT NOT NULL, user_id TEXT NOT NULL, FOREIGN KEY (user_id) REFERENCES users (id) ) """ ) conn.commit() conn.close() def create_post(title, content, userid): conn = sqlite3.connect(db) cursor = conn.cursor() post_id = str(uuid.uuid4()) cursor.execute( "INSERT INTO blog_posts (id, title, content, user_id) VALUES (?, ?, ?, ?)", (post_id, title, content, userid), ) conn.commit() conn.close() return post_id def get_post(post_id): conn = sqlite3.connect(db) cursor = conn.cursor() cursor.execute("SELECT title, content FROM blog_posts WHERE id = ?", (post_id,)) post = cursor.fetchone() conn.close() return post
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/SekaiCTF/2023/web/Chunky/blog/src/admin/admin.py
ctfs/SekaiCTF/2023/web/Chunky/blog/src/admin/admin.py
from flask import Blueprint, request, session import os import jwt import requests admin_bp = Blueprint("admin", __name__, url_prefix="/admin") jwks_url_template = os.getenv("JWKS_URL_TEMPLATE") valid_algo = "RS256" def get_public_key_url(user_id): return jwks_url_template.format(user_id=user_id) def get_public_key(url): resp = requests.get(url) resp = resp.json() key = resp["keys"][0]["x5c"][0] return key def has_valid_alg(token): header = jwt.get_unverified_header(token) algo = header["alg"] return algo == valid_algo def authorize_request(token, user_id): pubkey_url = get_public_key_url(user_id) if has_valid_alg(token) is False: raise Exception( "Invalid algorithm. Only {valid_algo} allowed!".format( valid_algo=valid_algo ) ) pubkey = get_public_key(pubkey_url) print(pubkey, flush=True) pubkey = "-----BEGIN PUBLIC KEY-----\n{pubkey}\n-----END PUBLIC KEY-----".format( pubkey=pubkey ).encode() decoded_token = jwt.decode(token, pubkey, algorithms=["RS256"]) if "user" not in decoded_token: raise Exception("user claim missing!") if decoded_token["user"] == "admin": return True return False @admin_bp.before_request def authorize(): if "user_id" not in session: return "User not signed in!", 403 if "Authorization" not in request.headers: return "No Authorization header found!", 403 authz_header = request.headers["Authorization"].split(" ") if len(authz_header) < 2: return "Bearer token not found!", 403 token = authz_header[1] if not authorize_request(token, session["user_id"]): return "Authorization failed!", 403 @admin_bp.route("/flag") def flag(): return os.getenv("FLAG")
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/SekaiCTF/2023/web/Chunky/blog/src/users/users.py
ctfs/SekaiCTF/2023/web/Chunky/blog/src/users/users.py
import sqlite3 import hashlib import uuid import os db = os.getenv("DB") def init_table(): conn = sqlite3.connect(db) cursor = conn.cursor() cursor.execute( """ CREATE TABLE IF NOT EXISTS users ( id TEXT PRIMARY KEY, username TEXT NOT NULL, password TEXT NOT NULL ) """ ) conn.commit() conn.close() def get_conn(): conn = sqlite3.connect(db) return conn def user_exists(username): conn = get_conn() cur = conn.cursor() res = cur.execute("SELECT id FROM users WHERE username=?", (username,)) result = res.fetchone() is not None conn.close() return result def create_user(username, password): conn = get_conn() cur = conn.cursor() if user_exists(username): return None, "User already exists!" pwhash = hashlib.sha256(password.encode()).hexdigest() user_id = str(uuid.uuid4()) cur.execute( "INSERT INTO users(id, username, password) VALUES(?,?,?)", (user_id, username, pwhash), ) conn.commit() conn.close() return { "id": user_id, "username": username, }, None def verify_credentials(username, password): conn = get_conn() cur = conn.cursor() pwhash = hashlib.sha256(password.encode()).hexdigest() res = cur.execute( "SELECT id, username FROM users WHERE username=? AND password=?", (username, pwhash), ) result = res.fetchone() conn.close() if result is None: return False, None userid, username = result return True, { "id": userid, "username": username, }
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/SekaiCTF/2025/misc/Literal_Eval/chall.py
ctfs/SekaiCTF/2025/misc/Literal_Eval/chall.py
from Crypto.Util.number import bytes_to_long from hashlib import shake_128 from ast import literal_eval from secrets import token_bytes from math import floor, ceil, log2 import os FLAG = os.getenv("FLAG", "SEKAI{}") m = 256 w = 21 n = 128 l1 = ceil(m / log2(w)) l2 = floor(log2(l1*(w-1)) / log2(w)) + 1 l = l1 + l2 class WOTS: def __init__(self): self.sk = [token_bytes(n // 8) for _ in range(l)] self.pk = [WOTS.chain(sk, w - 1) for sk in self.sk] def sign(self, digest: bytes) -> list[bytes]: assert 8 * len(digest) == m d1 = WOTS.pack(bytes_to_long(digest), l1, w) checksum = sum(w-1-i for i in d1) d2 = WOTS.pack(checksum, l2, w) d = d1 + d2 sig = [WOTS.chain(self.sk[i], w - d[i] - 1) for i in range(l)] return sig def get_pubkey_hash(self) -> bytes: hasher = shake_128(b"\x04") for i in range(l): hasher.update(self.pk[i]) return hasher.digest(16) @staticmethod def pack(num: int, length: int, base: int) -> list[int]: packed = [] while num > 0: packed.append(num % base) num //= base if len(packed) < length: packed += [0] * (length - len(packed)) return packed @staticmethod def chain(x: bytes, n: int) -> bytes: if n == 0: return x x = shake_128(b"\x03" + x).digest(16) return WOTS.chain(x, n - 1) @staticmethod def verify(digest: bytes, sig: list[bytes]) -> bytes: d1 = WOTS.pack(bytes_to_long(digest), l1, w) checksum = sum(w-1-i for i in d1) d2 = WOTS.pack(checksum, l2, w) d = d1 + d2 sig_pk = [WOTS.chain(sig[i], d[i]) for i in range(l)] hasher = shake_128(b"\x04") for i in range(len(sig_pk)): hasher.update(sig_pk[i]) sig_hash = hasher.digest(16) return sig_hash class MerkleTree: def __init__(self, height: int = 8): self.h = height self.keys = [WOTS() for _ in range(2**height)] self.tree = [] self.root = self.build_tree([key.get_pubkey_hash() for key in self.keys]) def build_tree(self, leaves: list[bytes]) -> bytes: self.tree.append(leaves) if len(leaves) == 1: return leaves[0] parents = [] for i in range(0, len(leaves), 2): left = leaves[i] if i + 1 < len(leaves): right = leaves[i + 1] else: right = leaves[i] hasher = shake_128(b"\x02" + left + right).digest(16) parents.append(hasher) return self.build_tree(parents) def sign(self, index: int, digest: bytes) -> list: assert 0 <= index < len(self.keys) key = self.keys[index] wots_sig = key.sign(digest) sig = [wots_sig] for i in range(self.h): leaves = self.tree[i] u = index >> i if u % 2 == 0: if u + 1 < len(leaves): sig.append((0, leaves[u + 1])) else: sig.append((0, leaves[u])) else: sig.append((1, leaves[u - 1])) return sig @staticmethod def verify(sig: list, digest: bytes) -> bytes: wots_sig = sig[0] sig = sig[1:] pk_hash = WOTS.verify(digest, wots_sig) root_hash = pk_hash for (side, leaf) in sig: if side == 0: root_hash = shake_128(b"\x02" + root_hash + leaf).digest(16) else: root_hash = shake_128(b"\x02" + leaf + root_hash).digest(16) return root_hash class Challenge: def __init__(self, h: int = 8): self.h = h self.max_signs = 2 ** h - 1 self.tree = MerkleTree(h) self.root = self.tree.root self.used = set() self.before_input = f"public key: {self.root.hex()}" def sign(self, num_sign: int, inds: list, messages: list): assert num_sign + len(self.used) <= self.max_signs assert len(inds) == len(set(inds)) == len(messages) == num_sign assert self.used.isdisjoint(inds) assert all(b"flag" not in msg for msg in messages) sigs = [] for i in range(num_sign): digest = shake_128(b"\x00" + messages[i]).digest(32) sigs.append(self.tree.sign(inds[i], digest)) self.used.update(inds) return sigs def next(self): new_tree = MerkleTree(self.h) digest = shake_128(b"\x01" + new_tree.root).digest(32) index = next(i for i in range(2 ** self.h) if i not in self.used) sig = new_tree.sign(index, digest) self.tree = new_tree return { "root": new_tree.root, "sig": sig, "index": index, } def verify(self, sig: list, message: bytes): digest = shake_128(b"\x00" + message).digest(32) for i, s in enumerate(reversed(sig)): if i != 0: digest = shake_128(b"\x01" + digest).digest(32) digest = MerkleTree.verify(s, digest) return digest == self.root def get_flag(self, sig: list): if not self.verify(sig, b"Give me the flag"): return {"message": "Invalid signature"} else: return {"message": f"Congratulations! Here is your flag: {FLAG}"} def __call__(self, type: str, **kwargs): assert type in ["sign", "next", "get_flag"] return getattr(self, type)(**kwargs) challenge = Challenge() print(challenge.before_input) try: while True: print(challenge(**literal_eval(input("input: ")))) except: exit(1)
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/SekaiCTF/2025/crypto/SSSS/chall.py
ctfs/SekaiCTF/2025/crypto/SSSS/chall.py
import random, os p = 2 ** 256 - 189 FLAG = os.getenv("FLAG", "SEKAI{}") def challenge(secret): t = int(input()) assert 20 <= t <= 50, "Number of parties not in range" f = gen(t, secret) for i in range(t): x = int(input()) assert 0 < x < p, "Bad input" print(poly_eval(f, x)) if int(input()) == secret: print(FLAG) exit(0) else: print(":<") def gen(degree, secret): poly = [random.randrange(0, p) for _ in range(degree + 1)] index = random.randint(0, degree) poly[index] = secret return poly def poly_eval(f, x): return sum(c * pow(x, i, p) for i, c in enumerate(f)) % p if __name__ == "__main__": secret = random.randrange(0, p) for _ in range(2): challenge(secret)
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/SekaiCTF/2025/crypto/I_Dream_of_Genni/idog.py
ctfs/SekaiCTF/2025/crypto/I_Dream_of_Genni/idog.py
from hashlib import sha256 from Crypto.Cipher import AES x = int(input('Enter an 8-digit multiplicand: ')) y = int(input('Enter a 7-digit multiplier: ')) assert 1e6 <= y < 1e7 <= x < 1e8, "Incorrect lengths" assert x * y != 3_81_40_42_24_40_28_42, "Insufficient ntr-opy" def dream_multiply(x, y): x, y = str(x), str(y) assert len(x) == len(y) + 1 digits = x[0] for a, b in zip(x[1:], y): digits += str(int(a) * int(b)) return int(digits) assert dream_multiply(x, y) == x * y, "More like a nightmare" ct = '75bd1089b2248540e3406aa014dc2b5add4fb83ffdc54d09beb878bbb0d42717e9cc6114311767dd9f3b8b070b359a1ac2eb695cd31f435680ea885e85690f89' print(AES.new(sha256(str((x, y)).encode()).digest(), AES.MODE_ECB).decrypt(bytes.fromhex(ct)).decode())
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/SekaiCTF/2025/crypto/APES/chall.py
ctfs/SekaiCTF/2025/crypto/APES/chall.py
import os FLAG = os.getenv("FLAG", "SEKAI{TESTFLAG}") def play(): plainperm = bytes.fromhex(input('Plainperm: ')) assert sorted(plainperm) == list(range(256)), "Invalid permutation" key = os.urandom(64) def f(i): for k in key[:-1]: i = plainperm[i ^ k] return i ^ key[-1] cipherperm = bytes(map(f, range(256))) print(f'Cipherperm: {cipherperm.hex()}') print('Do you know my key?') return bytes.fromhex(input()) == key if __name__ == '__main__': # if you're planning to brute force anyway, let's prevent excessive connections while not play(): print('Bad luck, try again.') print(f'APES TOGETHER STRONG! {FLAG}')
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/SekaiCTF/2025/crypto/unfairy_ring/chall.py
ctfs/SekaiCTF/2025/crypto/unfairy_ring/chall.py
from functools import reduce from uov import uov_1p_pkc as uov # https://github.com/mjosaarinen/uov-py/blob/main/uov.py import os FLAG = os.getenv("FLAG", "SEKAI{TESTFLAG}") def xor(a, b): assert len(a) == len(b), "XOR inputs must be of the same length" return bytes(x ^ y for x, y in zip(a, b)) names = ['Miku', 'Ichika', 'Minori', 'Kohane', 'Tsukasa', 'Kanade', 'Mai'] pks = [uov.expand_pk(uov.shake256(name.encode(), 43576)) for name in names] msg = b'SEKAI' sig = bytes.fromhex(input('Ring signature (hex): ')) assert len(sig) == 112 * len(names), 'Incorrect signature length' t = reduce(xor, [uov.pubmap(sig[i*112:(i+1)*112], pks[i]) for i in range(len(names))]) assert t == uov.shake256(msg, 44), 'Invalid signature' print(FLAG)
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/SekaiCTF/2025/crypto/unfairy_ring/uov.py
ctfs/SekaiCTF/2025/crypto/unfairy_ring/uov.py
# uov.py # 2024-04-24 Markku-Juhani O. Saarinen <mjos@iki.fi>. See LICENSE # === Implementation of UOV 1.0 === from Crypto.Cipher import AES from Crypto.Hash import SHAKE256 import os class UOV: # initialize def __init__(self, gf=256, n=112, m=44, pkc=False, skc=False, name='', rbg=os.urandom): """ Initialize the class with UOV parameters. """ self.gf = gf # _GFSIZE self.n = n # _PUB_N self.m = m # _PUB_M self.v = n - m # _V self.pkc = pkc # public key compression self.skc = skc # secret key compression self.name = name # spec name self.rbg = rbg # randombytes() callback if pkc: # variant names as in KAT files kc = 'pkc' # spec uses pkc/skc, KAT cpk/csk else: kc = 'classic' if skc: kc += '-skc' self.katname = f'OV({gf},{n},{m})-{kc}' if self.gf == 256: # two kinds of Finite fields self.gf_bits = 8 self.gf_mul = self.gf256_mul self.gf_mulm = self.gf256_mulm elif self.gf == 16: self.gf_bits = 4 self.gf_mul = self.gf16_mul self.gf_mulm = self.gf16_mulm else: raise ValueError self.v_sz = self.gf_bits * self.v // 8 # _V_BYTE self.n_sz = self.gf_bits * self.n // 8 # _PUB_N_BYTE self.m_sz = self.gf_bits * self.m // 8 # _PUB_M_BYTE, _O_BYTE self.seed_sk_sz = 32 # LEN_SKSEED self.seed_pk_sz = 16 # LEN_PKSEED self.salt_sz = 16 # _SALT_BYTE # bit mask for "mulm" multipliers mm = 0 for i in range(self.m): mm = self.gf * mm + (self.gf >> 1) self.mm = mm # external sizes def triangle(n): return n * (n + 1) // 2 self.sig_sz = self.n_sz + self.salt_sz # OV_SIGNATUREBYTES self.so_sz = self.m * self.v_sz # self.p1_sz = self.m_sz * triangle(self.v) # _PK_P1_BYTE self.p2_sz = self.m_sz * self.v * self.m # _PK_P2_BYTE self.p3_sz = self.m_sz * triangle(self.m) # _PK_P3_BYTE if self.pkc: self.pk_sz = self.seed_pk_sz + self.p3_sz # |cpk| else: self.pk_sz = self.p1_sz + self.p2_sz + self.p3_sz # |epk| if self.skc: self.sk_sz = self.seed_sk_sz # |csk| else: self.sk_sz = ( self.seed_sk_sz + self.so_sz + # |esk| self.p1_sz + self.p2_sz ) # random & symmetric crypto hooks def set_random(self, rbg): """ Set the key material RBG.""" self.rbg = rbg def shake256(self, x, l): """ shake256s(x, l): Internal hook.""" return SHAKE256.new(x).read(l) def aes128ctr(self, key, l, ctr=0): """ aes128ctr(key, l): Internal hook.""" iv = b'\x00' * 12 aes = AES.new(key, AES.MODE_CTR, nonce=iv, initial_value=ctr) return aes.encrypt(b'\x00' * l) # basic finite field arithmetic def gf16_mul(self, a, b): """ GF(16) multiply: a*b mod (x^4 + x + 1). """ r = a & (-(b & 1)) for i in range(1, 4): t = a & 8 a = ((a ^ t) << 1) ^ (t >> 2) ^ (t >> 3) r ^= a & (-((b >> i) & 1)) return r def gf16_mulm(self, v, a): """ Vector (length m) * scalar multiply in GF(16). """ r = v & (-(a & 1)) for i in range(1, 4): t = v & self.mm v = ((v ^ t) << 1) ^ (t >> 3) ^ (t >> 2) if (a >> i) & 1: r ^= v return r def gf256_mul(self, a, b): """ GF(256) multiply: a*b mod (x^8 + x^4 + x^3 + x + 1). """ r = a & (-(b & 1)); for i in range(1, 8): a = (a << 1) ^ ((-(a >> 7)) & 0x11B); r ^= a & (-((b >> i) & 1)); return r def gf256_mulm(self, v, a): """ Vector (length m) * scalar multiply in GF(256). """ r = v & (-(a & 1)) for i in range(1, 8): t = v & self.mm v = ((v ^ t) << 1) ^ (t >> 7) ^ (t >> 6) ^ (t >> 4) ^ (t >> 3) if (a >> i) & 1: r ^= v return r def gf_inv(self, a): """ GF multiplicative inverse: a^-1.""" r = a # computes 2^14 or a^254 == a^-1 for _ in range(2, self.gf_bits): a = self.gf_mul(a, a) r = self.gf_mul(r, a) r = self.gf_mul(r, r) return r # serialization helpers def gf_pack(self, v): """ Pack a vector of GF elements into bytes. """ if self.gf == 256: return bytes(v) elif self.gf == 16: return bytes( [ v[i] + (v[i + 1] << 4) for i in range(0, len(v), 2) ] ) def gf_unpack(self, b): """ Unpack bytes into a vector of GF elements """ if self.gf == 256: return bytearray(b) elif self.gf == 16: v = [] for x in b: v += [ x & 0xF, x >> 4 ] return bytearray(v) def unpack_mtri(self, b, d): """ Unpack an (upper) triangular matrix.""" m = [ [ 0 ] * d for i in range(d) ] p = 0 for i in range(d): for j in range(i, d): m[i][j] = int.from_bytes( b[ p : p + self.m_sz ] ) p += self.m_sz return m def pack_mtri(self, m, d): """ Pack an upper triangular matrix.""" b = b'' for i in range(d): for j in range(i, d): t = m[i][j] b += t.to_bytes(self.m_sz) return b def unpack_mrect(self, b, h, w): """ Unpack a rectangular matrix.""" m = [ [ 0 ] * w for i in range(h) ] p = 0 for i in range(h): for j in range(w): m[i][j] = int.from_bytes( b[ p : p + self.m_sz ] ) p += self.m_sz return m def pack_mrect(self, m, h, w): """ Pack a rectangular matrix.""" b = b'' for i in range(h): for j in range(w): b += m[i][j].to_bytes(self.m_sz) return b def unpack_rect(self, b, h, w): """ Unpack a rectangular matrix.""" if self.gf == 256: m = [ b[i : i + w] for i in range(0, h * w, w) ] elif self.gf == 16: w_sz = w // 2 m = [ self.gf_unpack(b[i : i + w_sz]) for i in range(0, h * w_sz, w_sz) ] return m # === UOV internal arithmetic ========================================= def calc_f2_p3(self, p1, p2, so): # extract p1 (tri) and p2 (rectangular) m1 = self.unpack_mtri(p1, self.v) m2 = self.unpack_mrect(p2, self.v, self.m) mo = self.unpack_rect(so, self.m, self.v) # create p3 m3 = [ [ 0 ] * self.m for i in range(self.m) ] for j in range(self.m): for i in range(self.v): t = m2[i][j] for k in range(i, self.v): t ^= self.gf_mulm( m1[i][k], mo[j][k] ) for k in range(self.m): u = self.gf_mulm( t, mo[k][i] ) if j < k: m3[j][k] ^= u else: m3[k][j] ^= u # create sks in place of m2 for i in range(self.v): for j in range(self.m): t = m2[i][j] for k in range(i + 1): t ^= self.gf_mulm( m1[k][i], mo[j][k] ) for k in range(i, self.v): t ^= self.gf_mulm( m1[i][k], mo[j][k] ) m2[i][j] = t # fold and collect p3 (tri) p3 = self.pack_mtri(m3, self.m) # collect sks (rect) sks = self.pack_mrect(m2, self.v, self.m) return (sks, p3) def gauss_solve(self, l, c): """ Solve a system of linear equations in GF.""" # system of linear equations: # transpose and add constant on right hand side h = self.m w = self.m + 1 l = [ self.gf_unpack( x.to_bytes(self.m_sz) ) for x in l ] m = [ [l[i][j] for i in range(h)] + [c[j]] for j in range(h) ] # gaussian elimination -- create a diagonal matrix on left for i in range(h): j = i while m[j][i] == 0: j += 1 if j == h: return None if i != j: for k in range(w): m[i][k] ^= m[j][k] x = self.gf_inv( m[i][i] ) for k in range(w): m[i][k] = self.gf_mul( m[i][k], x ) for j in range(h): x = m[j][i] if j != i: for k in range(w): m[j][k] ^= self.gf_mul(m[i][k], x) # extract the solution (don't pack) return [ m[i][w - 1] for i in range(h) ] def pubmap(self, z, tm): """ Apply public map to z.""" v = self.v m = self.m # unserialize m1 = self.unpack_mtri(tm, v) m2 = self.unpack_mrect(tm[self.p1_sz:], v, m) m3 = self.unpack_mtri(tm[self.p1_sz + self.p2_sz:], m) x = self.gf_unpack(z) y = 0 # result # P1 for i in range(v): for j in range(i, v): y ^= self.gf_mulm(m1[i][j], self.gf_mul(x[i], x[j])) # P2 for i in range(v): for j in range(m): y ^= self.gf_mulm(m2[i][j], self.gf_mul(x[i], x[v + j])) # P3 for i in range(m): for j in range(i, m): y ^= self.gf_mulm(m3[i][j], self.gf_mul(x[v + i], x[v + j])) return y.to_bytes(self.m_sz) def expand_p(self, seed_pk): """ UOV.ExpandP(). """ pk = self.aes128ctr(seed_pk, self.p1_sz + self.p2_sz); return (pk[0:self.p1_sz], pk[self.p1_sz:]) def expand_pk(self, cpk): """ UOV.ExpandPK(cpk). """ seed_pk = cpk[:self.seed_pk_sz] p3 = cpk[self.seed_pk_sz:] (p1, p2) = self.expand_p(seed_pk) epk = p1 + p2 + p3 return epk def expand_sk(self, csk): """ UOV.ExpandSK(csk). """ seed_sk = csk[:self.seed_sk_sz] seed_pk_so = self.shake256(seed_sk, self.seed_pk_sz + self.so_sz) seed_pk = seed_pk_so[:self.seed_pk_sz] so = seed_pk_so[self.seed_pk_sz:] (p1, p2) = self.expand_p(seed_pk) (sks, p3) = self.calc_f2_p3(p1, p2, so) esk = seed_sk + so + p1 + sks return esk # === external / kat test api ========================================= def keygen(self): """ UOV.classic.KeyGen(). """ seed_sk = self.rbg(self.seed_sk_sz) seed_pk_so = self.shake256(seed_sk, self.seed_pk_sz + self.so_sz) seed_pk = seed_pk_so[:self.seed_pk_sz] so = seed_pk_so[self.seed_pk_sz:] (p1, p2) = self.expand_p(seed_pk) (sks, p3) = self.calc_f2_p3(p1, p2, so) # public key compression if self.pkc: pk = seed_pk + p3 # cpk else: pk = p1 + p2 + p3 # epk # secret key compression if self.skc: sk = seed_sk # csk else: sk = seed_sk + so + p1 + sks # esk return (pk, sk) def sign(self, msg, sk): """ UOV.Sign().""" # unpack secret key if necessary if self.skc: sk = self.expand_sk(sk) # separate components j = self.seed_sk_sz seed_sk = sk[ : self.seed_sk_sz ] so = sk[ self.seed_sk_sz : self.seed_sk_sz + self.so_sz ] p1 = sk[ self.seed_sk_sz + self.so_sz : self.seed_sk_sz + self.so_sz + self.p1_sz ] sks = sk[ self.seed_sk_sz + self.so_sz + self.p1_sz : self.seed_sk_sz + self.so_sz + self.p1_sz + self.p2_sz ] # deserialization mo = [ self.gf_unpack( so[i : i + self.v_sz] ) for i in range(0, self.so_sz, self.v_sz) ] m1 = self.unpack_mtri(p1, self.v) ms = self.unpack_mrect(sks, self.v, self.m) # 1: salt <- {0, 1}^salt_len salt = self.rbg(self.salt_sz) # 2: t <- hash( mu || salt ) t = self.shake256(msg + salt, self.m_sz) # 3: for ctr = 0 upto 255 do ctr = 0 x = None while x == None and ctr < 0x100: # 4: v := Expand_v(mu || salt || seed_sk || ctr) v = self.gf_unpack(self.shake256( msg + salt + seed_sk + bytes([ctr]), self.v_sz)) ctr += 1 # 5: L := 0_{m*m} ll = [ 0 ] * self.m # 6: for i = 1 upto m do for i in range(self.m): # 7: Set i-th row of L to v^T S_i for j in range(self.v): ll[i] ^= self.gf_mulm(ms[j][i], v[j]) # 9: y <- v^t * Pi^(1) * v # 10: Solve Lx = t - y for x # "evaluate P1 with the vinegars" r = int.from_bytes(t) for i in range(self.v): u = 0 for j in range(i, self.v): u ^= self.gf_mulm( m1[i][j], v[j] ) r ^= self.gf_mulm( u, v[i] ) r = self.gf_unpack(r.to_bytes(self.m_sz)) x = self.gauss_solve(ll, r) # y = O * x y = bytearray(v) # subtract from v for i in range(self.m): for j in range(self.v): y[j] ^= self.gf_mul(mo[i][j], x[i]) # construct signature sig = self.gf_pack(y) + self.gf_pack(x) + salt return sig def verify(self, sig, msg, pk): """ UOV.Verify() and UOV.pkc.Verify(). Return boolean if valid. """ # unpack public key if necessary if self.pkc: pk = self.expand_pk(pk) x = sig[0 : self.n_sz] salt = sig[self.n_sz : self.n_sz + self.salt_sz] # 1: t <- hash( mu || salt ) t = self.shake256(msg + salt, self.m_sz) # 2: return ( t == [ s^T*P_i*s ] for i in [m] ). return t == self.pubmap(x, pk) def open(self, sm, pk): """ Verify a signed message sm = msg + sig. Return msg or None. """ msg_sz = len(sm) - self.sig_sz msg = sm[:msg_sz] sig = sm[msg_sz:] if not self.verify(sig, msg, pk): return None return msg # === Instantiate UOV Parameter Sets ====================================== uov_1p = UOV(gf=256, n=112, m=44, name='uov-Ip-classic') uov_1p_pkc = UOV(gf=256, n=112, m=44, pkc=True, name='uov-Ip-pkc') uov_1p_pkc_skc = UOV(gf=256, n=112, m=44, pkc=True, skc=True, name='uov-Ip-pkc+skc') uov_1s = UOV(gf=16, n=160, m=64, name='uov-Is-classic') uov_1s_pkc = UOV(gf=16, n=160, m=64, pkc=True, name='uov-Is-pkc') uov_1s_pkc_skc = UOV(gf=16, n=160, m=64, pkc=True, skc=True, name='uov-Is-pkc+skc') uov_3 = UOV(gf=256, n=184, m=72, name='uov-III-classic') uov_3_pkc = UOV(gf=256, n=184, m=72, pkc=True, name='uov-III-pkc') uov_3_pkc_skc = UOV(gf=256, n=184, m=72, pkc=True, skc=True, name='uov-III-pkc+skc') uov_5 = UOV(gf=256, n=244, m=96, name='uov-V-classic') uov_5_pkc = UOV(gf=256, n=244, m=96, pkc=True, name='uov-V-pkc') uov_5_pkc_skc = UOV(gf=256, n=244, m=96, pkc=True, skc=True, name='uov-V-pkc+skc') # a list of all variants uov_all = [ uov_1p, uov_1p_pkc, uov_1p_pkc_skc, uov_1s, uov_1s_pkc, uov_1s_pkc_skc, uov_3, uov_3_pkc, uov_3_pkc_skc, uov_5, uov_5_pkc, uov_5_pkc_skc ]
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/SekaiCTF/2025/crypto/unfairy_ring++/chall.py
ctfs/SekaiCTF/2025/crypto/unfairy_ring++/chall.py
from functools import reduce from uov import uov_1p_pkc as uov # https://github.com/mjosaarinen/uov-py/blob/main/uov.py import os FLAG = os.getenv("FLAG", "SEKAI{TESTFLAG}") def xor(a, b): assert len(a) == len(b), "XOR inputs must be of the same length" return bytes(x ^ y for x, y in zip(a, b)) names = ['Miku', 'Ichika', 'Minori', 'Kohane', 'Tsukasa', 'Kanade'] pks = [uov.expand_pk(uov.shake256(name.encode(), 43576)) for name in names] msg = b'SEKAI' sig = bytes.fromhex(input('Ring signature (hex): ')) assert len(sig) == 112 * len(names), 'Incorrect signature length' t = reduce(xor, [uov.pubmap(sig[i*112:(i+1)*112], pks[i]) for i in range(len(names))]) assert t == uov.shake256(msg, 44), 'Invalid signature' print(FLAG)
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/SekaiCTF/2025/crypto/unfairy_ring++/uov.py
ctfs/SekaiCTF/2025/crypto/unfairy_ring++/uov.py
# uov.py # 2024-04-24 Markku-Juhani O. Saarinen <mjos@iki.fi>. See LICENSE # === Implementation of UOV 1.0 === from Crypto.Cipher import AES from Crypto.Hash import SHAKE256 import os class UOV: # initialize def __init__(self, gf=256, n=112, m=44, pkc=False, skc=False, name='', rbg=os.urandom): """ Initialize the class with UOV parameters. """ self.gf = gf # _GFSIZE self.n = n # _PUB_N self.m = m # _PUB_M self.v = n - m # _V self.pkc = pkc # public key compression self.skc = skc # secret key compression self.name = name # spec name self.rbg = rbg # randombytes() callback if pkc: # variant names as in KAT files kc = 'pkc' # spec uses pkc/skc, KAT cpk/csk else: kc = 'classic' if skc: kc += '-skc' self.katname = f'OV({gf},{n},{m})-{kc}' if self.gf == 256: # two kinds of Finite fields self.gf_bits = 8 self.gf_mul = self.gf256_mul self.gf_mulm = self.gf256_mulm elif self.gf == 16: self.gf_bits = 4 self.gf_mul = self.gf16_mul self.gf_mulm = self.gf16_mulm else: raise ValueError self.v_sz = self.gf_bits * self.v // 8 # _V_BYTE self.n_sz = self.gf_bits * self.n // 8 # _PUB_N_BYTE self.m_sz = self.gf_bits * self.m // 8 # _PUB_M_BYTE, _O_BYTE self.seed_sk_sz = 32 # LEN_SKSEED self.seed_pk_sz = 16 # LEN_PKSEED self.salt_sz = 16 # _SALT_BYTE # bit mask for "mulm" multipliers mm = 0 for i in range(self.m): mm = self.gf * mm + (self.gf >> 1) self.mm = mm # external sizes def triangle(n): return n * (n + 1) // 2 self.sig_sz = self.n_sz + self.salt_sz # OV_SIGNATUREBYTES self.so_sz = self.m * self.v_sz # self.p1_sz = self.m_sz * triangle(self.v) # _PK_P1_BYTE self.p2_sz = self.m_sz * self.v * self.m # _PK_P2_BYTE self.p3_sz = self.m_sz * triangle(self.m) # _PK_P3_BYTE if self.pkc: self.pk_sz = self.seed_pk_sz + self.p3_sz # |cpk| else: self.pk_sz = self.p1_sz + self.p2_sz + self.p3_sz # |epk| if self.skc: self.sk_sz = self.seed_sk_sz # |csk| else: self.sk_sz = ( self.seed_sk_sz + self.so_sz + # |esk| self.p1_sz + self.p2_sz ) # random & symmetric crypto hooks def set_random(self, rbg): """ Set the key material RBG.""" self.rbg = rbg def shake256(self, x, l): """ shake256s(x, l): Internal hook.""" return SHAKE256.new(x).read(l) def aes128ctr(self, key, l, ctr=0): """ aes128ctr(key, l): Internal hook.""" iv = b'\x00' * 12 aes = AES.new(key, AES.MODE_CTR, nonce=iv, initial_value=ctr) return aes.encrypt(b'\x00' * l) # basic finite field arithmetic def gf16_mul(self, a, b): """ GF(16) multiply: a*b mod (x^4 + x + 1). """ r = a & (-(b & 1)) for i in range(1, 4): t = a & 8 a = ((a ^ t) << 1) ^ (t >> 2) ^ (t >> 3) r ^= a & (-((b >> i) & 1)) return r def gf16_mulm(self, v, a): """ Vector (length m) * scalar multiply in GF(16). """ r = v & (-(a & 1)) for i in range(1, 4): t = v & self.mm v = ((v ^ t) << 1) ^ (t >> 3) ^ (t >> 2) if (a >> i) & 1: r ^= v return r def gf256_mul(self, a, b): """ GF(256) multiply: a*b mod (x^8 + x^4 + x^3 + x + 1). """ r = a & (-(b & 1)); for i in range(1, 8): a = (a << 1) ^ ((-(a >> 7)) & 0x11B); r ^= a & (-((b >> i) & 1)); return r def gf256_mulm(self, v, a): """ Vector (length m) * scalar multiply in GF(256). """ r = v & (-(a & 1)) for i in range(1, 8): t = v & self.mm v = ((v ^ t) << 1) ^ (t >> 7) ^ (t >> 6) ^ (t >> 4) ^ (t >> 3) if (a >> i) & 1: r ^= v return r def gf_inv(self, a): """ GF multiplicative inverse: a^-1.""" r = a # computes 2^14 or a^254 == a^-1 for _ in range(2, self.gf_bits): a = self.gf_mul(a, a) r = self.gf_mul(r, a) r = self.gf_mul(r, r) return r # serialization helpers def gf_pack(self, v): """ Pack a vector of GF elements into bytes. """ if self.gf == 256: return bytes(v) elif self.gf == 16: return bytes( [ v[i] + (v[i + 1] << 4) for i in range(0, len(v), 2) ] ) def gf_unpack(self, b): """ Unpack bytes into a vector of GF elements """ if self.gf == 256: return bytearray(b) elif self.gf == 16: v = [] for x in b: v += [ x & 0xF, x >> 4 ] return bytearray(v) def unpack_mtri(self, b, d): """ Unpack an (upper) triangular matrix.""" m = [ [ 0 ] * d for i in range(d) ] p = 0 for i in range(d): for j in range(i, d): m[i][j] = int.from_bytes( b[ p : p + self.m_sz ] ) p += self.m_sz return m def pack_mtri(self, m, d): """ Pack an upper triangular matrix.""" b = b'' for i in range(d): for j in range(i, d): t = m[i][j] b += t.to_bytes(self.m_sz) return b def unpack_mrect(self, b, h, w): """ Unpack a rectangular matrix.""" m = [ [ 0 ] * w for i in range(h) ] p = 0 for i in range(h): for j in range(w): m[i][j] = int.from_bytes( b[ p : p + self.m_sz ] ) p += self.m_sz return m def pack_mrect(self, m, h, w): """ Pack a rectangular matrix.""" b = b'' for i in range(h): for j in range(w): b += m[i][j].to_bytes(self.m_sz) return b def unpack_rect(self, b, h, w): """ Unpack a rectangular matrix.""" if self.gf == 256: m = [ b[i : i + w] for i in range(0, h * w, w) ] elif self.gf == 16: w_sz = w // 2 m = [ self.gf_unpack(b[i : i + w_sz]) for i in range(0, h * w_sz, w_sz) ] return m # === UOV internal arithmetic ========================================= def calc_f2_p3(self, p1, p2, so): # extract p1 (tri) and p2 (rectangular) m1 = self.unpack_mtri(p1, self.v) m2 = self.unpack_mrect(p2, self.v, self.m) mo = self.unpack_rect(so, self.m, self.v) # create p3 m3 = [ [ 0 ] * self.m for i in range(self.m) ] for j in range(self.m): for i in range(self.v): t = m2[i][j] for k in range(i, self.v): t ^= self.gf_mulm( m1[i][k], mo[j][k] ) for k in range(self.m): u = self.gf_mulm( t, mo[k][i] ) if j < k: m3[j][k] ^= u else: m3[k][j] ^= u # create sks in place of m2 for i in range(self.v): for j in range(self.m): t = m2[i][j] for k in range(i + 1): t ^= self.gf_mulm( m1[k][i], mo[j][k] ) for k in range(i, self.v): t ^= self.gf_mulm( m1[i][k], mo[j][k] ) m2[i][j] = t # fold and collect p3 (tri) p3 = self.pack_mtri(m3, self.m) # collect sks (rect) sks = self.pack_mrect(m2, self.v, self.m) return (sks, p3) def gauss_solve(self, l, c): """ Solve a system of linear equations in GF.""" # system of linear equations: # transpose and add constant on right hand side h = self.m w = self.m + 1 l = [ self.gf_unpack( x.to_bytes(self.m_sz) ) for x in l ] m = [ [l[i][j] for i in range(h)] + [c[j]] for j in range(h) ] # gaussian elimination -- create a diagonal matrix on left for i in range(h): j = i while m[j][i] == 0: j += 1 if j == h: return None if i != j: for k in range(w): m[i][k] ^= m[j][k] x = self.gf_inv( m[i][i] ) for k in range(w): m[i][k] = self.gf_mul( m[i][k], x ) for j in range(h): x = m[j][i] if j != i: for k in range(w): m[j][k] ^= self.gf_mul(m[i][k], x) # extract the solution (don't pack) return [ m[i][w - 1] for i in range(h) ] def pubmap(self, z, tm): """ Apply public map to z.""" v = self.v m = self.m # unserialize m1 = self.unpack_mtri(tm, v) m2 = self.unpack_mrect(tm[self.p1_sz:], v, m) m3 = self.unpack_mtri(tm[self.p1_sz + self.p2_sz:], m) x = self.gf_unpack(z) y = 0 # result # P1 for i in range(v): for j in range(i, v): y ^= self.gf_mulm(m1[i][j], self.gf_mul(x[i], x[j])) # P2 for i in range(v): for j in range(m): y ^= self.gf_mulm(m2[i][j], self.gf_mul(x[i], x[v + j])) # P3 for i in range(m): for j in range(i, m): y ^= self.gf_mulm(m3[i][j], self.gf_mul(x[v + i], x[v + j])) return y.to_bytes(self.m_sz) def expand_p(self, seed_pk): """ UOV.ExpandP(). """ pk = self.aes128ctr(seed_pk, self.p1_sz + self.p2_sz); return (pk[0:self.p1_sz], pk[self.p1_sz:]) def expand_pk(self, cpk): """ UOV.ExpandPK(cpk). """ seed_pk = cpk[:self.seed_pk_sz] p3 = cpk[self.seed_pk_sz:] (p1, p2) = self.expand_p(seed_pk) epk = p1 + p2 + p3 return epk def expand_sk(self, csk): """ UOV.ExpandSK(csk). """ seed_sk = csk[:self.seed_sk_sz] seed_pk_so = self.shake256(seed_sk, self.seed_pk_sz + self.so_sz) seed_pk = seed_pk_so[:self.seed_pk_sz] so = seed_pk_so[self.seed_pk_sz:] (p1, p2) = self.expand_p(seed_pk) (sks, p3) = self.calc_f2_p3(p1, p2, so) esk = seed_sk + so + p1 + sks return esk # === external / kat test api ========================================= def keygen(self): """ UOV.classic.KeyGen(). """ seed_sk = self.rbg(self.seed_sk_sz) seed_pk_so = self.shake256(seed_sk, self.seed_pk_sz + self.so_sz) seed_pk = seed_pk_so[:self.seed_pk_sz] so = seed_pk_so[self.seed_pk_sz:] (p1, p2) = self.expand_p(seed_pk) (sks, p3) = self.calc_f2_p3(p1, p2, so) # public key compression if self.pkc: pk = seed_pk + p3 # cpk else: pk = p1 + p2 + p3 # epk # secret key compression if self.skc: sk = seed_sk # csk else: sk = seed_sk + so + p1 + sks # esk return (pk, sk) def sign(self, msg, sk): """ UOV.Sign().""" # unpack secret key if necessary if self.skc: sk = self.expand_sk(sk) # separate components j = self.seed_sk_sz seed_sk = sk[ : self.seed_sk_sz ] so = sk[ self.seed_sk_sz : self.seed_sk_sz + self.so_sz ] p1 = sk[ self.seed_sk_sz + self.so_sz : self.seed_sk_sz + self.so_sz + self.p1_sz ] sks = sk[ self.seed_sk_sz + self.so_sz + self.p1_sz : self.seed_sk_sz + self.so_sz + self.p1_sz + self.p2_sz ] # deserialization mo = [ self.gf_unpack( so[i : i + self.v_sz] ) for i in range(0, self.so_sz, self.v_sz) ] m1 = self.unpack_mtri(p1, self.v) ms = self.unpack_mrect(sks, self.v, self.m) # 1: salt <- {0, 1}^salt_len salt = self.rbg(self.salt_sz) # 2: t <- hash( mu || salt ) t = self.shake256(msg + salt, self.m_sz) # 3: for ctr = 0 upto 255 do ctr = 0 x = None while x == None and ctr < 0x100: # 4: v := Expand_v(mu || salt || seed_sk || ctr) v = self.gf_unpack(self.shake256( msg + salt + seed_sk + bytes([ctr]), self.v_sz)) ctr += 1 # 5: L := 0_{m*m} ll = [ 0 ] * self.m # 6: for i = 1 upto m do for i in range(self.m): # 7: Set i-th row of L to v^T S_i for j in range(self.v): ll[i] ^= self.gf_mulm(ms[j][i], v[j]) # 9: y <- v^t * Pi^(1) * v # 10: Solve Lx = t - y for x # "evaluate P1 with the vinegars" r = int.from_bytes(t) for i in range(self.v): u = 0 for j in range(i, self.v): u ^= self.gf_mulm( m1[i][j], v[j] ) r ^= self.gf_mulm( u, v[i] ) r = self.gf_unpack(r.to_bytes(self.m_sz)) x = self.gauss_solve(ll, r) # y = O * x y = bytearray(v) # subtract from v for i in range(self.m): for j in range(self.v): y[j] ^= self.gf_mul(mo[i][j], x[i]) # construct signature sig = self.gf_pack(y) + self.gf_pack(x) + salt return sig def verify(self, sig, msg, pk): """ UOV.Verify() and UOV.pkc.Verify(). Return boolean if valid. """ # unpack public key if necessary if self.pkc: pk = self.expand_pk(pk) x = sig[0 : self.n_sz] salt = sig[self.n_sz : self.n_sz + self.salt_sz] # 1: t <- hash( mu || salt ) t = self.shake256(msg + salt, self.m_sz) # 2: return ( t == [ s^T*P_i*s ] for i in [m] ). return t == self.pubmap(x, pk) def open(self, sm, pk): """ Verify a signed message sm = msg + sig. Return msg or None. """ msg_sz = len(sm) - self.sig_sz msg = sm[:msg_sz] sig = sm[msg_sz:] if not self.verify(sig, msg, pk): return None return msg # === Instantiate UOV Parameter Sets ====================================== uov_1p = UOV(gf=256, n=112, m=44, name='uov-Ip-classic') uov_1p_pkc = UOV(gf=256, n=112, m=44, pkc=True, name='uov-Ip-pkc') uov_1p_pkc_skc = UOV(gf=256, n=112, m=44, pkc=True, skc=True, name='uov-Ip-pkc+skc') uov_1s = UOV(gf=16, n=160, m=64, name='uov-Is-classic') uov_1s_pkc = UOV(gf=16, n=160, m=64, pkc=True, name='uov-Is-pkc') uov_1s_pkc_skc = UOV(gf=16, n=160, m=64, pkc=True, skc=True, name='uov-Is-pkc+skc') uov_3 = UOV(gf=256, n=184, m=72, name='uov-III-classic') uov_3_pkc = UOV(gf=256, n=184, m=72, pkc=True, name='uov-III-pkc') uov_3_pkc_skc = UOV(gf=256, n=184, m=72, pkc=True, skc=True, name='uov-III-pkc+skc') uov_5 = UOV(gf=256, n=244, m=96, name='uov-V-classic') uov_5_pkc = UOV(gf=256, n=244, m=96, pkc=True, name='uov-V-pkc') uov_5_pkc_skc = UOV(gf=256, n=244, m=96, pkc=True, skc=True, name='uov-V-pkc+skc') # a list of all variants uov_all = [ uov_1p, uov_1p_pkc, uov_1p_pkc_skc, uov_1s, uov_1s_pkc, uov_1s_pkc_skc, uov_3, uov_3_pkc, uov_3_pkc_skc, uov_5, uov_5_pkc, uov_5_pkc_skc ]
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/SekaiCTF/2025/crypto/Law_And_Order/chall.py
ctfs/SekaiCTF/2025/crypto/Law_And_Order/chall.py
from py_ecc.secp256k1 import P, G as G_lib, N from py_ecc.secp256k1.secp256k1 import multiply, add import random import os from hashlib import sha256 import sys CONTEXT = os.urandom(69) NUM_PARTIES = 9 THRESHOLD = (2 * NUM_PARTIES) // 3 + 1 NUM_SIGNS = 100 FLAG = os.environ.get("FLAG", "FLAG{I_AM_A_NINCOMPOOP}") # IO def send(msg): print(msg, flush=True) def handle_error(msg): send(msg) sys.exit(1) def receive_line(): try: return sys.stdin.readline().strip() except BaseException: handle_error("Connection closed by client. Exiting.") def input_int(range=P): try: x = int(receive_line()) assert 0 <= x <= range - 1 return x except BaseException: handle_error("Invalid input integer") def input_point(): try: x = input_int() y = input_int() assert not (x == 0 and y == 0) return Point(x, y) except BaseException: handle_error("Invalid input Point") # Helper class class Point: """easy operator overloading""" def __init__(self, x, y): self.point = (x, y) def __add__(self, other): return Point(*add(self.point, other.point)) def __mul__(self, scalar): return Point(*multiply(self.point, scalar)) def __rmul__(self, scalar): return Point(*multiply(self.point, scalar)) def __neg__(self): return Point(self.point[0], -self.point[1]) def __eq__(self, other): return (self + (-other)).point[0] == 0 def __repr__(self): return str(self.point) G = Point(*G_lib) def random_element(P): return random.randint(1, P - 1) def H(*args): return int.from_bytes(sha256(str(args).encode()).digest(), "big") def sum_pts(points): res = 0 * G for point in points: res = res + point return res def sample_poly(t): return [random_element(N) for _ in range(t)] def gen_proof(secret, i): k = random_element(P) R = k * G mu = k + secret * H(CONTEXT, i, secret * G, R) return R, mu % N def verify_proof(C, R, mu, i): c = H(CONTEXT, i, C, R) return R == mu * G + (-c * C) def gen_poly_comms(coeffs): return [i * G for i in coeffs] def eval_poly(coeffs, x): res = 0 for coeff in coeffs[::-1]: res = (res * x + coeff) % N return res def gen_shares(n, coeffs): return {i: eval_poly(coeffs, i) for i in range(1, n + 1)} def poly_eval_comms(comms, i): return sum_pts([comms[k] * pow(i, k, N) for k in range(THRESHOLD)]) def check_shares(comms, shares, i): return G * shares[i] == poly_eval_comms(comms, i) def gen_nonsense(): d, e = random_element(N), random_element(N) D, E = d * G, e * G return (d, e), (D, E) def lamb(i, S): num, den = 1, 1 for j in S: if j == i: continue num *= j den *= (j - i) return (num * pow(den, -1, N)) % N def main(): """https://eprint.iacr.org/2020/852.pdf""" send("=" * 50) send("=== Law and Order! You should always include your friends to sign and you are mine <3 ===") send("=" * 50) send( f"We have {NUM_PARTIES - 1} parties here, and you will be party #{NUM_PARTIES}.") send(f"Idk why is our group signing not working") send("\n--- Round 1: Commitment ---") # Keygen send(f"context string {CONTEXT.hex()}") your_id = NUM_PARTIES all_coeffs = {} all_comms = {} for i in range(1, NUM_PARTIES): # 1.1 coeffs = sample_poly(THRESHOLD) # 1.2 zero_proof = gen_proof(coeffs[0], i) # 1.3 comms = gen_poly_comms(coeffs) # 1.5 if not verify_proof(comms[0], zero_proof[0], zero_proof[1], i): handle_error(f"[-] Party {i} secret PoK invalid") all_coeffs[i] = coeffs all_comms[i] = comms send(f"[+] Commitments from party {i}:") for k, C_ik in enumerate(comms): send(f" C_{i},{k} = {C_ik}") send("\n[?] Now, provide the commitments (points) for your coefficients.") your_comms = [input_point() for _ in range(THRESHOLD)] send("\n[?] Finally, provide your proof-of-knowledge for your secret share (c_i,0).") send("[>] Send Point R:") your_zero_proof_R = input_point() send("[>] Send mu:") your_zero_proof_mu = input_int() your_zero_proof = (your_zero_proof_R, your_zero_proof_mu) if not verify_proof(your_comms[0], your_zero_proof[0], your_zero_proof[1], your_id): handle_error(f"[-] party {your_id} secret PoK invalid") all_comms[your_id] = your_comms send("[+] Your commitments and proof have been accepted.") send("\n--- Round 2: Share Distribution ---") send(f"[?] Please provide your shares for the other {NUM_PARTIES} parties.") # 2.1 your_shares = {} for i in range(1, NUM_PARTIES + 1): send(f"[>] Send share for party {i}:") your_shares[i] = input_int(N) # 2.2 for i in range(1, NUM_PARTIES + 1): if not check_shares(your_comms, your_shares, i): handle_error(f"[-] party {your_id} shares for party {i} invalid") send("[+] Your shares have been verified") all_shares = {} for l in range(1, NUM_PARTIES): shares_l = gen_shares(NUM_PARTIES, all_coeffs[l]) for i in range(1, NUM_PARTIES + 1): if not check_shares(all_comms[l], shares_l, i): handle_error(f"[-] party {l} shares for party {i} invalid") all_shares[l] = shares_l send(f"[+] Share for you from party {l}: {shares_l[your_id]}") all_shares[your_id] = your_shares # 2.3 signing_shares = {} for i in range(1, NUM_PARTIES + 1): signing_shares[i] = 0 for j in range(1, NUM_PARTIES + 1): signing_shares[i] += all_shares[j][i] # 2.4 group_public_key = sum_pts([all_comms[i][0] for i in range(1, NUM_PARTIES + 1)]) send(f"\n[+] Group Public Key: {group_public_key}") public_shares = {i: v * G for i, v in signing_shares.items()} your_public_share = sum_pts([poly_eval_comms(all_comms[j], your_id) for j in range(1, NUM_PARTIES + 1)]) public_shares[your_id] = your_public_share send("[+] Public verification shares have been computed.") send(f"\n--- Phase 3: Presign and Sign ({NUM_SIGNS} rounds) ---") for _ in range(NUM_SIGNS): # presign send("[?] Provide your nonces (D_i, E_i) for this round.") your_D = input_point() your_E = input_point() your_nonsense = (your_D, your_E) nonsense_sec, nonsense = {}, {} for i in range(1, NUM_PARTIES + 1): # 1.a, 1.b & 1.c (d, e), (D, E) = gen_nonsense() nonsense_sec[i] = (d, e) nonsense[i] = (D, E) nonsense[your_id] = your_nonsense # Sign # S is set of alpha, alpha is in t to n right? S = {random.randint(THRESHOLD, NUM_PARTIES) for _ in range(NUM_PARTIES - THRESHOLD)} S.add(your_id) # should always include you <3 send(f"[+] Set of signers for this round: {S}") m = "GIVE ME THE FLAG PLEASE" combined_nonsense = {} group_nonsense = 0 * G nonsense = {i: nonsense[i] for i in S} # 2 nonsense_ordered = sorted([(i, Di, Ei) for i, (Di, Ei) in nonsense.items()]) # 4 rhos = {i: H(i, m, nonsense_ordered) for i in S} for i, (D, E) in nonsense.items(): send(f"[+] Party {i} nonces: D={D}, E={E}") D, E = nonsense[i] nonsense_i = D + rhos[i] * E group_nonsense = group_nonsense + nonsense_i combined_nonsense[i] = nonsense_i group_challenge = H(group_nonsense, group_public_key, m) send(f"[+] Group challenge `c`: {group_challenge}") send("[?] Provide your signature share `z_i`.") your_zi = input_int(N) # 7.b if your_zi * G != combined_nonsense[your_id] + \ public_shares[your_id] * group_challenge * lamb(your_id, S): handle_error(f"[-] party {your_id} signature shares invalid") final_signing_shares = {your_id: your_zi} for i in S - {your_id}: si = signing_shares[i] di, ei = nonsense_sec[i] # 5 zi = di + (ei * rhos[i]) + si * group_challenge * lamb(i, S) Ri, Yi = combined_nonsense[i], public_shares[i] if Yi != sum_pts([poly_eval_comms(all_comms[j], i) for j in range(1, NUM_PARTIES + 1)]): handle_error(f"[-] party {i} public share invalid") if zi * G != Ri + Yi * group_challenge * lamb(i, S): handle_error(f"[-] party {i} signature share invalid") final_signing_shares[i] = zi # 7.c z = sum(final_signing_shares.values()) % N if z * G == group_nonsense + group_public_key * group_challenge: send("[+] Signature verification successful") send(f"[+] Here is your flag: {FLAG}") sys.exit(0) handle_error("[-] We are out of signing ink") if __name__ == "__main__": try: main() except Exception as e: handle_error("[-] An error occured: {e}")
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/SekaiCTF/2022/crypto/EZmaze/chall.py
ctfs/SekaiCTF/2022/crypto/EZmaze/chall.py
#!/usr/bin/env python3 import os import random from Crypto.Util.number import * from flag import flag directions = "LRUD" SOLUTION_LEN = 64 def toPath(x: int): s = bin(x)[2:] if len(s) % 2 == 1: s = "0" + s path = "" for i in range(0, len(s), 2): path += directions[int(s[i:i+2], 2)] return path def toInt(p: str): ret = 0 for d in p: ret = ret * 4 + directions.index(d) return ret def final_position(path: str): return (path.count("R") - path.count("L"), path.count("U") - path.count("D")) class RSA(): def __init__(self): self.p = getPrime(512) self.q = getPrime(512) self.n = self.p * self.q self.phi = (self.p - 1) * (self.q - 1) self.e = 65537 self.d = pow(self.e, -1, self.phi) def encrypt(self, m: int): return pow(m, self.e, self.n) def decrypt(self, c: int): return pow(c, self.d, self.n) def main(): solution = "".join([random.choice(directions) for _ in range(SOLUTION_LEN)]) sol_int = toInt(solution) print("I have the solution of the maze, but I'm not gonna tell you OwO.") rsa = RSA() print(f"n = {rsa.n}") print(f"e = {rsa.e}") print(hex(rsa.encrypt(sol_int))) while True: try: opt = int(input("Options: 1. Decrypt 2. Check answer.\n")) if opt == 1: c = int(input("Ciphertext in hex: "), 16) path = toPath(rsa.decrypt(c)) print(final_position(path)) elif opt == 2: path = input("Solution: ").strip() if path == solution: print(flag) else: print("Wrong solution.") exit(0) else: print("Invalid option.") exit(0) except: 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/SekaiCTF/2022/crypto/TimeCapsule/chall.py
ctfs/SekaiCTF/2022/crypto/TimeCapsule/chall.py
import time import os import random from SECRET import flag def encrypt_stage_one(message, key): u = [s for s in sorted(zip(key, range(len(key))))] res = '' for i in u: for j in range(i[1], len(message), len(key)): res += message[j] return res def encrypt_stage_two(message): now = str(time.time()).encode('utf-8') now = now + "".join("0" for _ in range(len(now), 18)).encode('utf-8') random.seed(now) key = [random.randrange(256) for _ in message] return [m ^ k for (m,k) in zip(message + now, key + [0x42]*len(now))] # I am generating many random numbers here to make my message secure rand_nums = [] while len(rand_nums) != 8: tmp = int.from_bytes(os.urandom(1), "big") if tmp not in rand_nums: rand_nums.append(tmp) for _ in range(42): # Answer to the Ultimate Question of Life, the Universe, and Everything... flag = encrypt_stage_one(flag, rand_nums) # print(flag) # Another layer of randomness based on time. Unbreakable. res = encrypt_stage_two(flag.encode('utf-8')) with open("flag.enc", "wb") as f: f.write(bytes(res)) f.close()
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/SekaiCTF/2022/crypto/SecureImageEncryption/server-player.py
ctfs/SekaiCTF/2022/crypto/SecureImageEncryption/server-player.py
from io import BytesIO from PIL import Image from flask import Flask, request, render_template import base64 app = Flask(__name__, template_folder="") app.config['MAX_CONTENT_LENGTH'] = 2 * 1000 * 1000 FLAG_PATH = "flag.png" flag_img = Image.open(FLAG_PATH) def encrypt_img(img: Image) -> Image: # Permutation-only encryption algorithm pass def img_to_data_url(img: Image) -> str: f = BytesIO() img.save(f, format="PNG") img_base64 = base64.b64encode(f.getvalue()).decode("utf-8") return f"data:image/png;base64,{img_base64}" @app.route("/") def index(): return render_template("index.html") @app.route("/upload", methods=["POST"]) def upload(): # Captcha verification pass if "image" not in request.files: return "Image not found", 403 files = request.files.getlist('image') imgs = [] for file in files: try: im = Image.open(file.stream) except Exception as e: return "Invalid image", 403 if im.format != "PNG": return "Invalid image format: Please upload PNG files", 403 if im.size[0] > 256 or im.size[1] > 256: return "Image too large: Maximum allowed size is 256x256", 403 im = im.convert('L') imgs.append(im) imgs.append(flag_img) try: urls = [img_to_data_url(encrypt_img(im)) for im in imgs] except Exception as e: return "I don't know how but black magic is detected", 403 return render_template("upload.html", url1=urls[0], url2=urls[1], url3=urls[2]) if __name__ == "__main__": app.run(debug=False)
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/SekaiCTF/2022/crypto/FaILProof/source.py
ctfs/SekaiCTF/2022/crypto/FaILProof/source.py
import hashlib from os import urandom from flag import FLAG def gen_pubkey(secret: bytes, hasher=hashlib.sha512) -> list: def hash(m): return hasher(m).digest() state = hash(secret) pubkey = [] for _ in range(len(hash(b'0')) * 4): pubkey.append(int.from_bytes(state, 'big')) state = hash(state) return pubkey def happiness(x: int) -> int: return x - sum((x >> i) for i in range(1, x.bit_length())) def encode_message(message: bytes, segment_len: int) -> list: message += bytes(segment_len - len(message) % (segment_len)) encoded = [] for i in range(0, len(message), segment_len): block = message[i:i + segment_len] encoded.append(int.from_bytes(block, 'big')) return encoded def encrypt(pubkey: list, message: bytes) -> list: encrypted_blocks = [] for block_int in encode_message(message, len(pubkey) // 4): encrypted_blocks.append([happiness(i & block_int) for i in pubkey]) return encrypted_blocks secret = urandom(16) A = gen_pubkey(secret, hashlib.sha256) enc = encrypt(A, FLAG) print(secret.hex()) print(enc)
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/SekaiCTF/2022/crypto/Diffecient/diffecient.py
ctfs/SekaiCTF/2022/crypto/Diffecient/diffecient.py
import math import random import re import mmh3 def randbytes(n): return bytes ([random.randint(0,255) for i in range(n)]) class BloomFilter: def __init__(self, m, k, hash_func=mmh3.hash): self.__m = m self.__k = k self.__i = 0 self.__digests = set() self.hash = hash_func def security(self): false_positive = pow( 1 - pow(math.e, -self.__k * self.__i / self.__m), self.__k) try: return int(1 / false_positive).bit_length() except (ZeroDivisionError, OverflowError): return float('inf') def _add(self, item): self.__i += 1 for i in range(self.__k): self.__digests.add(self.hash(item, i) % self.__m) def check(self, item): return all(self.hash(item, i) % self.__m in self.__digests for i in range(self.__k)) def num_passwords(self): return self.__i def memory_consumption(self): return 4*len(self.__digests) class PasswordDB(BloomFilter): def __init__(self, m, k, security, hash_func=mmh3.hash): super().__init__(m, k, hash_func) self.add_keys(security) self.addition_quota = 1 self.added_keys = set() def add_keys(self, thresh_security): while self.security() > thresh_security: self._add(randbytes(256)) print("Added {} security keys to DB".format(self.num_passwords())) print("Original size of keys {} KB vs {} KB in DB".format( self.num_passwords()//4, self.memory_consumption()//1024)) def check_admin(self, key): if not re.match(b".{32,}", key): print("Admin key should be atleast 32 characters long") return False if not re.match(b"(?=.*[a-z])", key): print("Admin key should contain atleast 1 lowercase character") return False if not re.match(b"(?=.*[A-Z])", key): print("Admin key should contain atleast 1 uppercase character") return False if not re.match(br"(?=.*\d)", key): print("Admin key should contain atleast 1 digit character") return False if not re.match(br"(?=.*\W)", key): print("Admin key should contain atleast 1 special character") return False if key in self.added_keys: print("Admin account restricted for free tier") return False return self.check(key) def query_db(self, key): if self.check(key): print("Key present in DB") else: print("Key not present in DB") def add_sample(self, key): if self.addition_quota > 0: self._add(key) self.added_keys.add(key) self.addition_quota -= 1 print("key added successfully to DB") else: print("API quota exceeded") BANNER = r""" ____ ____ ____ ____ ____ ___ ____ ____ _ _ ____ ( _ \(_ _)( ___)( ___)( ___)/ __)(_ _)( ___)( \( )(_ _) )(_) )_)(_ )__) )__) )__)( (__ _)(_ )__) ) ( )( (____/(____)(__) (__) (____)\___)(____)(____)(_)\_) (__) Welcome to diffecient security key database API for securely and efficiently saving tonnes of long security keys! Feel FREE to query your security keys and pay a little to add your own security keys to our state of the art DB! We trust our product so much that we even save our own keys here """ print(BANNER) PASSWORD_DB = PasswordDB(2**32 - 5, 47, 768, mmh3.hash) while True: try: option = int(input("Enter API option:\n")) if option == 1: key = bytes.fromhex(input("Enter key in hex\n")) PASSWORD_DB.query_db(key) elif option == 2: key = bytes.fromhex(input("Enter key in hex\n")) PASSWORD_DB.add_sample(key) elif option == 3: key = bytes.fromhex(input("Enter key in hex\n")) if PASSWORD_DB.check_admin(key): from flag import flag print(flag) else: print("No Admin no flag") elif option == 4: exit(0) except: print("Something wrong happened") exit(1)
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/AlpacaHack/2025/crypto/Equivalent_Privacy_Wired/server.py
ctfs/AlpacaHack/2025/crypto/Equivalent_Privacy_Wired/server.py
import os import signal from Crypto.Cipher import ARC4 import string import random signal.alarm(300) FLAG = os.environ.get("FLAG", "Alpaca{*** FAKEFLAG ***}") chars = string.digits + string.ascii_lowercase + string.ascii_uppercase master_key = "".join(random.choice(chars) for _ in range(16)).encode() for _ in range(1000): iv = bytes.fromhex(input("iv: ")) ciphertext = bytes.fromhex(input("ciphertext: ")) key = master_key + iv plaintext = ARC4.new(key, drop=3072).decrypt(ciphertext) if plaintext == master_key: print(FLAG) break print("plaintext:", plaintext.hex())
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/MetaCTF/2021/rev/I_Hate_Python/python.py
ctfs/MetaCTF/2021/rev/I_Hate_Python/python.py
import random def do_thing(a, b): return ((a << 1) & b) ^ ((a << 1) | b) x = input("What's the password? ") if len(x) != 25: print("WRONG!!!!!") else: random.seed(997) k = [random.randint(0, 256) for _ in range(len(x))] a = { b: do_thing(ord(c), d) for (b, c), d in zip(enumerate(x), k) } b = list(range(len(x))) random.shuffle(b) c = [a[i] for i in b[::-1]] print(k) print(c) kn = [47, 123, 113, 232, 118, 98, 183, 183, 77, 64, 218, 223, 232, 82, 16, 72, 68, 191, 54, 116, 38, 151, 174, 234, 127] valid = len(list(filter(lambda s: kn[s[0]] == s[1], enumerate(c)))) if valid == len(x): print("Password is correct! Flag:", x) else: print("WRONG!!!!!!")
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/MetaCTF/2021/crypto/hide_and_seek_the_flag/client.py
ctfs/MetaCTF/2021/crypto/hide_and_seek_the_flag/client.py
import socket, sys, select, gmpy2 def establish_communication(ip, port): with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s: s.connect((ip, port)) keys = [] while True: active = select.select([s, sys.stdin], [], [])[0] if s in active: buf = s.recv(260) if buf[0] == 0: pub = int.from_bytes(buf[1:4], byteorder="big") p = int.from_bytes(buf[4:132], byteorder="big") q = int.from_bytes(buf[132:260], byteorder="big") priv = gmpy2.invert(pub, (p-1) * (q-1)) keys += [(int(priv), p * q)] else: msg = int.from_bytes(buf[1:], byteorder="big") msg = pow(msg, keys[0][0], keys[0][1]) keys = keys[1:] print(msg.to_bytes(256, byteorder="big")) if sys.stdin in active: buf = int.from_bytes(sys.stdin.read(250).encode("utf-8"), byteorder="big") s.send(b"\x00") enckey = s.recv(260) pub = int.from_bytes(enckey[1:4], byteorder="big") mod = int.from_bytes(enckey[4:260], byteorder="big") enc = pow(buf, pub, mod) s.send(b"\x01" + enc.to_bytes(259, byteorder="big")) establish_communication(sys.argv[1], int(sys.argv[2]))
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/MetaCTF/2021/crypto/hide_and_seek_the_flag/server.py
ctfs/MetaCTF/2021/crypto/hide_and_seek_the_flag/server.py
import gmpy2 import random import socket import select sockets = [] def get_rsa_info(): p = gmpy2.next_prime(random.getrandbits(1024)) q = gmpy2.next_prime(random.getrandbits(1024)) e = 65537 d = gmpy2.invert(e, (p - 1) * (q - 1)) return (e, int(p), int(q)) def establish_communication(port): global sockets with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s: s.bind(("0.0.0.0", port)) s.listen(2) while len(sockets) != 2: c, addr = s.accept() sockets += [c] while True: active = select.select(sockets, [], [])[0] for s in active: buf = s.recv(260) if(buf[0] == 0): e, p, q = get_rsa_info() send_buf = b"\x00" send_buf += e.to_bytes(3, "big") send_buf += p.to_bytes(128, "big") send_buf += q.to_bytes(128, "big") print("Sending ", b"\x00" + e.to_bytes(3, "big") + (p * q).to_bytes(256, "big")) s.send(b"\x00" + e.to_bytes(3, "big") + (p * q).to_bytes(256, "big")) for s1 in sockets: if s1 != s: s1.send(send_buf) else: for s1 in sockets: if s1 != s: s1.send(buf) establish_communication(1337)
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/MetaCTF/2025/crypto/ShaNOISEmir/ShaNOISEmir.py
ctfs/MetaCTF/2025/crypto/ShaNOISEmir/ShaNOISEmir.py
#!/usr/bin/env python3 from os import urandom from Crypto.Util.number import getPrime as gp from random import getrandbits, shuffle random_int = lambda size: int(urandom(size).hex(), 16) secret = b'FLAG' secret = int(secret.hex(),16) class shamir: def __init__(self, p, coeffs): self.p = p self.coeffs = coeffs def getshare(self, x, randfactor): result = 0 for i, coeff in enumerate(self.coeffs): result = (result + coeff * pow(x, i)) % self.p return result + random_int(5)*randfactor def getshares(self,amount): factors = list(range(amount)) shuffle(factors) x = random_int(5) ys = [] factors = [self.getshare(x,i) for i in factors] return x, factors p = gp(30) print(f"Public Parameter: {p}") coeffs = [secret] + [random_int(28) for i in range(4)] poly = shamir(p, coeffs) while True: opt = input('Share (yes/no) > ') if opt != 'yes': break amount = int(input('Amount > ')) assert amount > 4 res = poly.getshares(amount) print(res)
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/MetaCTF/2020/steg_as_a_service/steg/www/server.py
ctfs/MetaCTF/2020/steg_as_a_service/steg/www/server.py
#!/usr/bin/env python3 from flask import Flask, render_template, request import subprocess import uuid import os from os import path app = Flask(__name__) app.config['UPLOAD_FOLDER'] = './uploads/' app.config['MAX_CONTENT_LENGTH'] = 16 * 1024 * 1024 @app.route('/') def upload_file(): return render_template('./upload.html') @app.route('/stegsolver', methods = ['POST']) def process_file(): if request.method == 'POST': if 'file' in request.files and 'passphrase' in request.form: f = request.files['file'] stegfile_name = str(uuid.uuid4()) outfile_name = str(uuid.uuid4()) f.save(app.config['UPLOAD_FOLDER'] + stegfile_name) os.chdir(app.config['UPLOAD_FOLDER']) try: subprocess.run(['steghide', 'extract', '-sf', stegfile_name, '-p', request.form['passphrase'], '-xf', outfile_name], check=True, timeout=60) except Exception: os.chdir('..') if path.exists(app.config['UPLOAD_FOLDER'] + stegfile_name): os.remove(app.config['UPLOAD_FOLDER'] + stegfile_name) if path.exists(app.config['UPLOAD_FOLDER'] + outfile_name): os.remove(app.config['UPLOAD_FOLDER'] + outfile_name) return 'Either no data was embedded, or something went wrong with the extraction' os.chdir("..") if path.exists(app.config['UPLOAD_FOLDER'] + outfile_name): outfile = open(app.config['UPLOAD_FOLDER'] + outfile_name, "rb") result = outfile.read() outfile.close() if path.exists(app.config['UPLOAD_FOLDER'] + stegfile_name): os.remove(app.config['UPLOAD_FOLDER'] + stegfile_name) if path.exists(app.config['UPLOAD_FOLDER'] + outfile_name): os.remove(app.config['UPLOAD_FOLDER'] + outfile_name) return result else: if path.exists(app.config['UPLOAD_FOLDER'] + stegfile_name): os.remove(app.config['UPLOAD_FOLDER'] + stegfile_name) return 'Either no data was embedded, or something went wrong with the extraction' else: return 'Either the passphrase or the file is missing.' else: return 'Invalid request type' if __name__ == '__main__': app.run(host='0.0.0.0', port=8000)
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/TSCCTF/2025/crypto/Random_Strangeeeeee_Algorithm/server.py
ctfs/TSCCTF/2025/crypto/Random_Strangeeeeee_Algorithm/server.py
import os import random import sys from Crypto.Util.number import getRandomNBitInteger, bytes_to_long from gmpy2 import is_prime from secret import FLAG def get_prime(nbits: int): if nbits < 2: raise ValueError("'nbits' must be larger than 1.") while True: num = getRandomNBitInteger(nbits) | 1 if is_prime(num): return num def pad(msg: bytes, nbytes: int): if nbytes < (len(msg) + 1): raise ValueError("'nbytes' must be larger than 'len(msg) + 1'.") return msg + b'\0' + os.urandom(nbytes - len(msg) - 1) def main(): for cnt in range(4096): nbits_0 = 1000 + random.randint(1, 256) nbits_1 = 612 + random.randint(1, 256) p, q, r = get_prime(nbits_0), get_prime(nbits_0), get_prime(nbits_0) n = p * q * r d = get_prime(nbits_1) e = pow(d, -1, (p - 1) * (q - 1) * (r - 1)) m = bytes_to_long(pad(FLAG, (n.bit_length() - 1) // 8)) c = pow(m, e, n) print(f'{n, e = }') print(f'{c = }') msg = input('Do you want to refresh [Y/N] > ') if msg != 'Y': break if __name__ == '__main__': try: main() except Exception: sys.exit() except KeyboardInterrupt: sys.exit()
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/TSCCTF/2025/crypto/Very_Simple_Login/server.py
ctfs/TSCCTF/2025/crypto/Very_Simple_Login/server.py
import base64 import hashlib import json import os import re import sys import time from secret import FLAG def xor(message0: bytes, message1: bytes) -> bytes: return bytes(byte0 & byte1 for byte0, byte1 in zip(message0, message1)) def sha256(message: bytes) -> bytes: return hashlib.sha256(message).digest() def hmac_sha256(key: bytes, message: bytes) -> bytes: blocksize = 64 if len(key) > blocksize: key = sha256(key) if len(key) < blocksize: key = key + b'\x00' * (blocksize - len(key)) o_key_pad = xor(b'\x5c' * blocksize, key) i_key_pad = xor(b'\x3c' * blocksize, key) return sha256(o_key_pad + sha256(i_key_pad) + message) def sha256_jwt_dumps(data: dict, exp: int, key: bytes): header = {'alg': 'HS256', 'typ': 'JWT'} payload = {'sub': data, 'exp': exp} header = base64.urlsafe_b64encode(json.dumps(header).encode()) payload = base64.urlsafe_b64encode(json.dumps(payload).encode()) signature = hmac_sha256(key, header + b'.' + payload) signature = base64.urlsafe_b64encode(signature).rstrip(b'=') return header + b'.' + payload + b'.' + signature def sha256_jwt_loads(jwt: bytes, exp: int, key: bytes) -> dict | None: header_payload, signature = jwt.rsplit(b'.', 1) sig = hmac_sha256(key, header_payload) sig = base64.urlsafe_b64encode(sig).rstrip(b'=') if sig != signature: raise ValueError('JWT error') try: header, payload = header_payload.split(b'.')[0], header_payload.split(b'.')[-1] header = json.loads(base64.urlsafe_b64decode(header)) payload = json.loads(base64.urlsafe_b64decode(payload)) if (header.get('alg') != 'HS256') or (header.get('typ') != 'JWT'): raise ValueError('JWT error') if int(payload.get('exp')) < exp: raise ValueError('JWT error') except Exception: raise ValueError('JWT error') return payload.get('sub') def register(username: str, key: bytes): if re.fullmatch(r'[A-z0-9]+', username) is None: raise ValueError("'username' format error.") return sha256_jwt_dumps({'username': username}, int(time.time()) + 86400, key) def login(token: bytes, key: bytes): userdata = sha256_jwt_loads(token, int(time.time()), key) return userdata['username'] def menu(): for _ in range(32): print('==================') print('1. Register') print('2. Login') print('3. Exit') try: choice = int(input('> ')) except Exception: pass if 1 <= choice <= 3: return choice print('Error choice !', end='\n\n') sys.exit() def main(): key = os.urandom(32) for _ in range(32): choice = menu() if choice == 1: username = input('Username > ') try: token = register(username, key) except Exception: print('Username Error !', end='\n\n') continue print(f'Token : {token.hex()}', end='\n\n') if choice == 2: token = bytes.fromhex(input('Token > ')) try: username = login(token, key) except Exception: print('Token Error !', end='\n\n') if username == 'Admin': print(f'FLAG : {FLAG}', end='\n\n') sys.exit() else: print('FLAG : TSC{???}', end='\n\n') if choice == 3: sys.exit() if __name__ == '__main__': try: main() except Exception: sys.exit() except KeyboardInterrupt: sys.exit()
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/TSCCTF/2025/crypto/AES_Encryption_Oracle/chal.py
ctfs/TSCCTF/2025/crypto/AES_Encryption_Oracle/chal.py
#!/usr/bin/env python3 from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes from cryptography.hazmat.primitives import padding from cryptography.hazmat.backends import default_backend import os def aes_cbc_encrypt(msg: bytes, key: bytes) -> bytes: """ Encrypts a message using AES in CBC mode. Parameters: msg (bytes): The plaintext message to encrypt. key (bytes): The encryption key (must be 16, 24, or 32 bytes long). Returns: bytes: The initialization vector (IV) concatenated with the encrypted ciphertext. """ if len(key) not in {16, 24, 32}: raise ValueError("Key must be 16, 24, or 32 bytes long.") # Generate a random Initialization Vector (IV) iv = os.urandom(16) # Pad the message to be a multiple of the block size (16 bytes for AES) padder = padding.PKCS7(algorithms.AES.block_size).padder() padded_msg = padder.update(msg) + padder.finalize() # Create the AES cipher in CBC mode cipher = Cipher(algorithms.AES(key), modes.CBC(iv), backend=default_backend()) encryptor = cipher.encryptor() # Encrypt the padded message ciphertext = encryptor.update(padded_msg) + encryptor.finalize() # Return IV concatenated with ciphertext return iv + ciphertext def aes_cbc_decrypt(encrypted_msg: bytes, key: bytes) -> bytes: """ Decrypts a message encrypted using AES in CBC mode. Parameters: encrypted_msg (bytes): The encrypted message (IV + ciphertext). key (bytes): The decryption key (must be 16, 24, or 32 bytes long). Returns: bytes: The original plaintext message. """ if len(key) not in {16, 24, 32}: raise ValueError("Key must be 16, 24, or 32 bytes long.") # Extract the IV (first 16 bytes) and ciphertext (remaining bytes) iv = encrypted_msg[:16] ciphertext = encrypted_msg[16:] # Create the AES cipher in CBC mode cipher = Cipher(algorithms.AES(key), modes.CBC(iv), backend=default_backend()) decryptor = cipher.decryptor() # Decrypt the ciphertext padded_msg = decryptor.update(ciphertext) + decryptor.finalize() # Remove padding from the decrypted message unpadder = padding.PKCS7(algorithms.AES.block_size).unpadder() msg = unpadder.update(padded_msg) + unpadder.finalize() return msg def main(): with open("/home/kon/image-small.jpeg", "rb") as f: image = f.read() key = os.urandom(16) encrypted_image = aes_cbc_encrypt(image, key) k0n = int(input("What do you want to know? ")) print(f'{key = }') print(f'{encrypted_image[k0n:k0n+32] = }') 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/TSCCTF/2025/web/E4sy_SQLi/main.py
ctfs/TSCCTF/2025/web/E4sy_SQLi/main.py
from flask import Flask, render_template, request, redirect, url_for, session, flash, jsonify import mysql.connector import os, time from werkzeug.security import generate_password_hash, check_password_hash from functools import wraps from flask_wtf.csrf import CSRFProtect from flag_generate import create_discount_code FLAG = os.getenv('FLAG') or "FLAG{BUY1000OFF}" app = Flask(__name__) app.secret_key = os.urandom(24) # 資料庫連接重試函數 def get_db_connection(max_retries=10, delay_seconds=5): for attempt in range(max_retries): try: return mysql.connector.connect( host=os.getenv('MYSQL_HOST'), user=os.getenv('MYSQL_USER') or "shop_user", password=os.getenv('MYSQL_PASSWORD') or "shop_password123", database=os.getenv('MYSQL_DATABASE') or "laptop_shop", charset='utf8mb4', collation='utf8mb4_unicode_ci' ) except mysql.connector.Error as err: if attempt == max_retries - 1: raise print(f"資料庫連接失敗,{delay_seconds} 秒後重試... (嘗試 {attempt + 1}/{max_retries})") print(f"錯誤: {err}") time.sleep(delay_seconds) # 在啟動 Flask 前建立折扣碼 try: db = get_db_connection() cursor = db.cursor() # 使用 flag.py 中的函數建立折扣碼 if create_discount_code(cursor, FLAG): print("成功建立折扣碼") db.commit() else: print("建立折扣碼失敗") except Exception as e: print(f"初始化折扣碼時發生錯誤: {e}") finally: if 'cursor' in locals(): cursor.close() if 'db' in locals() and db.is_connected(): db.close() # 初始化資料庫連接 try: db = get_db_connection() except Exception as e: print(f"無法連接到資料庫: {e}") db = None # 資料庫連接檢查裝飾器 def check_db_connection(f): @wraps(f) def decorated_function(*args, **kwargs): global db try: if db is None or not db.is_connected(): db = get_db_connection() except Exception as e: print(f"資料庫連接錯誤: {e}") flash('系統暫時無法使用,請稍後再試', 'danger') return redirect(url_for('home')) return f(*args, **kwargs) return decorated_function def admin_required(f): @wraps(f) def decorated_function(*args, **kwargs): if 'user_id' not in session: flash('請先登入', 'danger') return redirect(url_for('login')) cursor = db.cursor(dictionary=True) cursor.execute("SELECT role FROM users WHERE id = %s", (session['user_id'],)) user = cursor.fetchone() if not user or user['role'] != 'admin': flash('沒有權限訪問此頁面', 'danger') return redirect(url_for('home')) return f(*args, **kwargs) return decorated_function # 初始化 CSRF 保護 csrf = CSRFProtect(app) @app.route('/') def home(): return render_template('home.html') @app.route('/products') @check_db_connection def products(): cursor = db.cursor(dictionary=True) cursor.execute("SELECT * FROM products") products = cursor.fetchall() return render_template('index.html', products=products) @app.route('/login', methods=['GET', 'POST']) @check_db_connection def login(): if request.method == 'POST': username = request.form['username'] password = request.form['password'] # 檢查是否有空欄位 if not username or not password: flash('請填寫所有欄位', 'danger') return render_template('login.html') cursor = db.cursor(dictionary=True) cursor.execute("SELECT * FROM users WHERE username = %s", (username,)) user = cursor.fetchone() if user and check_password_hash(user['password'], password): session['user_id'] = user['id'] session['username'] = user['username'] session['role'] = user['role'] flash('登入成功!', 'success') return redirect(url_for('home')) else: flash('帳號或密碼錯誤', 'danger') return render_template('login.html') @app.route('/register', methods=['GET', 'POST']) @check_db_connection def register(): if request.method == 'POST': username = request.form['username'] password = request.form['password'] email = request.form['email'] if not username or not password or not email: flash('請填寫所有欄位', 'danger') return render_template('register.html') if len(password) < 6: flash('密碼長度必須至少6個字元', 'danger') return render_template('register.html') try: cursor = db.cursor(dictionary=True) cursor.execute("SELECT * FROM users WHERE username = %s", (username,)) if cursor.fetchone(): flash('使用者名稱已被使用', 'danger') return render_template('register.html') hashed_password = generate_password_hash(password) cursor.execute(""" INSERT INTO users (username, password, email, role) VALUES (%s, %s, %s, 'user') """, (username, hashed_password, email)) db.commit() flash('註冊成功!請登入', 'success') return redirect(url_for('login')) except Exception as e: db.rollback() flash('操作失敗,請稍後再試', 'danger') print(f"Error in register: {str(e)}") return render_template('register.html') return render_template('register.html') @app.route('/cart') @check_db_connection def cart(): if 'cart' not in session: session['cart'] = [] return render_template('cart.html') @app.route('/remove_from_cart/<int:product_id>') @check_db_connection def remove_from_cart(product_id): if 'user_id' not in session: return redirect(url_for('login')) try: cursor = db.cursor() cursor.execute(""" DELETE FROM cart WHERE user_id = %s AND product_id = %s """, (session['user_id'], product_id)) db.commit() except Exception as e: db.rollback() flash('刪除失敗,請稍後再試', 'danger') print(f"Error in remove_from_cart: {str(e)}") return redirect(url_for('cart')) @app.route('/update_cart_quantity', methods=['POST']) @check_db_connection @csrf.exempt def update_cart_quantity(): try: data = request.get_json() index = data.get('index') quantity = int(data.get('quantity')) if 'cart' in session and 0 <= index < len(session['cart']): session['cart'][index]['quantity'] = quantity session.modified = True return jsonify({'success': True}) except Exception as e: print(f"Error in update_cart_quantity: {str(e)}") return jsonify({'success': False}) @app.route('/remove_cart_item', methods=['POST']) @check_db_connection @csrf.exempt def remove_cart_item(): try: data = request.get_json() index = data.get('index') if 'cart' in session and 0 <= index < len(session['cart']): session['cart'].pop(index) session.modified = True return jsonify({'success': True}) except Exception as e: print(f"Error in remove_cart_item: {str(e)}") return jsonify({'success': False}) @app.route('/add_to_cart_custom/<int:product_id>', methods=['POST']) @check_db_connection def add_to_cart_custom(product_id): if 'cart' not in session: session['cart'] = [] cursor = db.cursor(dictionary=True) try: # 獲取所有必要的組件類別 cursor.execute("SELECT id, name FROM component_categories") required_categories = cursor.fetchall() # 檢查是否所有必要的組件都已選擇 missing_components = [] for category in required_categories: component_key = f'component_{category["id"]}' if component_key not in request.form or not request.form[component_key]: missing_components.append(category["name"]) # 如果有未選擇的組件,返回錯誤 if missing_components: missing_items = '、'.join(missing_components) flash(f'請選擇以下必要組件:{missing_items}', 'danger') return redirect(url_for('customize_product', product_id=product_id)) # 獲取基礎產品信息 cursor.execute("SELECT * FROM products WHERE id = %s", (product_id,)) product = cursor.fetchone() total_price = float(product['price']) # 收集所有選擇的組件 custom_components = {} for category in required_categories: component_id = request.form[f'component_{category["id"]}'] # 獲取組件信息 cursor.execute("SELECT name, price FROM components WHERE id = %s", (component_id,)) component = cursor.fetchone() custom_components[category['name']] = component['name'] total_price += float(component['price']) # 創建購物車項目 cart_item = { 'id': product_id, 'name': product['name'], 'price': total_price, 'quantity': 1, 'type': 'custom', 'custom_components': custom_components } session['cart'].append(cart_item) session.modified = True flash('自定義商品已成功加入購物車!', 'success') except Exception as e: flash('添加商品時出現錯誤,請重試。', 'danger') print(f"Error: {str(e)}") return redirect(url_for('cart')) @app.route('/logout') def logout(): session.clear() return redirect(url_for('home')) @app.route('/checkout') def checkout(): if 'cart' not in session or not session['cart']: flash('購物車是空的', 'warning') return redirect(url_for('cart')) # 計算總價 total_price = sum(item['price'] * item['quantity'] for item in session['cart']) # 設定運費(可以根據需求調整運費計算邏輯) shipping_fee = 100 if total_price < 3000 else 0 return render_template('checkout.html', total_price=total_price, shipping_fee=shipping_fee) @app.route('/place_order', methods=['POST']) @check_db_connection def place_order(): if 'cart' not in session or not session['cart']: flash('購物車是空的', 'warning') return redirect(url_for('cart')) try: cursor = db.cursor(dictionary=True) # 計算訂單金額 total_amount = sum(item['price'] * item['quantity'] for item in session['cart']) shipping_fee = 100 if total_amount < 3000 else 0 discount_amount = 0 # 處理折扣碼 discount_code = request.form.get('discount_code') if discount_code: cursor.execute(""" SELECT * FROM discount_codes WHERE code = %s AND is_active = TRUE AND start_date <= NOW() AND end_date >= NOW() AND (usage_limit IS NULL OR used_count < usage_limit) """, (discount_code,)) discount = cursor.fetchone() if discount and total_amount >= discount['min_purchase']: if discount['discount_type'] == 'percentage': discount_amount = total_amount * (discount['discount_value'] / 100) else: discount_amount = discount['discount_value'] # 更新折扣碼使用次數 cursor.execute(""" UPDATE discount_codes SET used_count = used_count + 1 WHERE id = %s """, (discount['id'],)) final_amount = total_amount + shipping_fee - discount_amount # 創建訂單 cursor.execute(""" INSERT INTO orders ( user_id, total_amount, shipping_fee, recipient_name, recipient_phone, recipient_email, shipping_address, note, payment_method ) VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s) """, ( session.get('user_id'), final_amount, shipping_fee, request.form.get('name'), request.form.get('phone'), request.form.get('email'), request.form.get('address'), request.form.get('note'), request.form.get('payment') )) order_id = cursor.lastrowid # 保存訂單項目 for item in session['cart']: # 插入訂單項目 cursor.execute(""" INSERT INTO order_items ( order_id, product_id, quantity, price, is_custom ) VALUES (%s, %s, %s, %s, %s) """, ( order_id, item['id'], item['quantity'], item['price'], item['type'] == 'custom' )) # 獲取插入的訂單項目 ID item_id = cursor.lastrowid # 如果是客製化商品,保存配置 if item['type'] == 'custom' and 'custom_components' in item: for category, component in item['custom_components'].items(): cursor.execute(""" INSERT INTO order_configurations ( order_item_id, category_name, component_name ) VALUES (%s, %s, %s) """, ( item_id, # 使用正確的訂單項目 ID category, component )) # 如果使用了折扣碼,記錄使用情況 if discount_code and discount: cursor.execute(""" INSERT INTO discount_usage ( discount_code_id, order_id, user_id ) VALUES (%s, %s, %s) """, (discount['id'], order_id, session['user_id'])) db.commit() # 清空購物車 session.pop('cart', None) flash('訂單已成功建立!', 'success') return redirect(url_for('order_complete', order_id=order_id)) except Exception as e: db.rollback() flash('訂單建立失敗,請重試', 'danger') print(f"Error: {str(e)}") return redirect(url_for('checkout')) @app.route('/customize/<product_id>') @check_db_connection @csrf.exempt def customize_product(product_id): if 'user_id' not in session: return redirect(url_for('login')) try: cursor = db.cursor(dictionary=True) # 獲取基礎產品信息 cursor.execute(f"SELECT * FROM products WHERE id = {product_id}") product = cursor.fetchone() # while True: # row = cursor.fetchone() # if row is None: # break if not product: return redirect(url_for('products')) # 獲取所有配件類別和選項 cursor.execute("SELECT * FROM component_categories") categories = cursor.fetchall() components = {} for category in categories: cursor.execute(""" SELECT c.*, pc.is_default FROM components c LEFT JOIN product_configurations pc ON c.id = pc.component_id AND pc.base_product_id = %s WHERE c.category_id = %s """, (product_id, category['id'])) components[category['id']] = cursor.fetchall() return render_template( 'customize.html', product=product, categories=categories, components=components ) except Exception as e: print(f"Error in customize_product: {str(e)}") return redirect(url_for('products')) @app.route('/orders') @check_db_connection def orders(): if 'user_id' not in session: flash('請先登入', 'danger') return redirect(url_for('login')) cursor = db.cursor(dictionary=True) # 獲取用戶的所有訂單 cursor.execute(""" SELECT orders.*, COUNT(order_items.id) as item_count, SUM(order_items.quantity) as total_items FROM orders LEFT JOIN order_items ON orders.id = order_items.order_id WHERE orders.user_id = %s GROUP BY orders.id ORDER BY orders.created_at DESC """, (session['user_id'],)) orders = cursor.fetchall() return render_template('orders.html', orders=orders) @app.route('/order/<int:order_id>') @check_db_connection def order_detail(order_id): if 'user_id' not in session: flash('請先登入', 'danger') return redirect(url_for('login')) cursor = db.cursor(dictionary=True) # 獲取訂單基本信息 cursor.execute(""" SELECT * FROM orders WHERE id = %s AND user_id = %s """, (order_id, session['user_id'])) order = cursor.fetchone() if not order: flash('找不到此訂單', 'danger') return redirect(url_for('orders')) # 獲取訂單項目 cursor.execute(""" SELECT order_items.*, products.name as product_name FROM order_items JOIN products ON order_items.product_id = products.id WHERE order_items.order_id = %s """, (order_id,)) items = cursor.fetchall() # 獲取客製化配置 for item in items: if item['is_custom']: cursor.execute(""" SELECT category_name, component_name FROM order_configurations WHERE order_item_id = %s """, (item['id'],)) item['configurations'] = cursor.fetchall() return render_template('order_detail.html', order=order, items=items) @app.route('/order_complete/<int:order_id>') @check_db_connection def order_complete(order_id): if 'user_id' not in session: flash('請先登入', 'danger') return redirect(url_for('login')) cursor = db.cursor(dictionary=True) cursor.execute(""" SELECT * FROM orders WHERE id = %s AND user_id = %s """, (order_id, session['user_id'])) order = cursor.fetchone() if not order: flash('找不到此訂單', 'danger') return redirect(url_for('orders')) return render_template('order_complete.html', order=order) @app.route('/admin/discount_codes') @admin_required def admin_discount_codes(): cursor = db.cursor(dictionary=True) cursor.execute(""" SELECT dc.*, u.username as created_by_name FROM discount_codes dc LEFT JOIN users u ON dc.created_by = u.id ORDER BY dc.created_at DESC """) discount_codes = cursor.fetchall() return render_template('admin/discount_codes.html', discount_codes=discount_codes) @app.route('/admin/discount_codes/create', methods=['GET', 'POST']) @admin_required def create_discount_code(): if request.method == 'POST': try: cursor = db.cursor() cursor.execute(""" INSERT INTO discount_codes ( code, discount_type, discount_value, min_purchase, start_date, end_date, usage_limit, created_by ) VALUES (%s, %s, %s, %s, %s, %s, %s, %s) """, ( request.form['code'], request.form['discount_type'], float(request.form['discount_value']), float(request.form['min_purchase']), request.form['start_date'], request.form['end_date'], int(request.form['usage_limit']) if request.form['usage_limit'] else None, session['user_id'] )) db.commit() flash('折扣碼創建成功', 'success') return redirect(url_for('admin_discount_codes')) except Exception as e: db.rollback() flash('創建失敗:' + str(e), 'danger') return render_template('admin/create_discount_code.html') @app.route('/validate_discount', methods=['POST']) @csrf.exempt def validate_discount(): try: data = request.get_json() code = data.get('discount_code') total_amount = (data.get('total_amount', 0)) cursor = db.cursor(dictionary=True) cursor.execute(""" SELECT * FROM discount_codes WHERE code = %s AND is_active = TRUE AND start_date <= NOW() AND end_date >= NOW() AND (usage_limit IS NULL OR used_count < usage_limit) """, (code,)) discount = cursor.fetchone() if not discount: return jsonify({'valid': False, 'message': '無效的折扣碼'}) if total_amount < discount['min_purchase']: return jsonify({ 'valid': False, 'message': f'訂單金額需要達到 ${discount["min_purchase"]} 才能使用此折扣碼' }) discount_amount = 0 if discount['discount_type'] == 'percentage': discount_amount = total_amount * (discount['discount_value'] / 100) else: discount_amount = discount['discount_value'] return jsonify({ 'valid': True, 'discount_amount': discount_amount, 'message': '折扣碼有效' }) except Exception as e: print(f"Error in validate_discount: {str(e)}") return jsonify({'valid': False, 'message': '折扣碼驗證失敗,請稍後再試'}) @app.route('/admin/orders') @admin_required def admin_orders(): cursor = db.cursor(dictionary=True) cursor.execute(""" SELECT orders.*, users.username, COUNT(order_items.id) as item_count, SUM(order_items.quantity) as total_items FROM orders LEFT JOIN users ON orders.user_id = users.id LEFT JOIN order_items ON orders.id = order_items.order_id GROUP BY orders.id ORDER BY orders.created_at DESC """) orders = cursor.fetchall() return render_template('admin/orders.html', orders=orders) @app.route('/admin/order/<int:order_id>') @admin_required def admin_order_detail(order_id): cursor = db.cursor(dictionary=True) # 獲取訂單基本信息 cursor.execute(""" SELECT orders.*, users.username FROM orders LEFT JOIN users ON orders.user_id = users.id WHERE orders.id = %s """, (order_id,)) order = cursor.fetchone() if not order: flash('找不到此訂單', 'danger') return redirect(url_for('admin_orders')) # 獲取訂單項目 cursor.execute(""" SELECT order_items.*, products.name as product_name FROM order_items JOIN products ON order_items.product_id = products.id WHERE order_items.order_id = %s """, (order_id,)) items = cursor.fetchall() # 獲取客製化配置 for item in items: if item['is_custom']: cursor.execute(""" SELECT category_name, component_name FROM order_configurations WHERE order_item_id = %s """, (item['id'],)) item['configurations'] = cursor.fetchall() return render_template('admin/order_detail.html', order=order, items=items) @app.route('/admin/order/update_status', methods=['POST']) @admin_required def update_order_status(): try: order_id = request.form.get('order_id') new_status = request.form.get('status') admin_note = request.form.get('admin_note') cursor = db.cursor() cursor.execute(""" UPDATE orders SET status = %s, admin_note = %s WHERE id = %s """, (new_status, admin_note, order_id)) db.commit() flash('訂單狀態已更新', 'success') except Exception as e: db.rollback() flash('更新失敗:' + str(e), 'danger') return redirect(url_for('admin_order_detail', order_id=order_id)) if __name__ == '__main__': app.run(debug=True)
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/RVCExIITBxYCF/2024/crypto/Art_of_Predictability/chall.py
ctfs/RVCExIITBxYCF/2024/crypto/Art_of_Predictability/chall.py
from Crypto.Util.number import bytes_to_long, isPrime from secrets import randbelow from sympy import nextprime s = 696969 p = bytes_to_long(REDACTED) c = 0 while not isPrime(p): p+=1 c+=1 assert isPrime(p) a = randbelow(p) b = randbelow(p) def mathemagic(seed): return (a * seed + b) % p print("c = ", c) print("a = ", a) print("b = ", b) print("mathemagic(seed) = ", mathemagic(s)) print("mathemagic(mathemagic(seed)) = ", mathemagic(mathemagic(s)))
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/FullWeakEngineer/2025/rev/A/main.py
ctfs/FullWeakEngineer/2025/rev/A/main.py
class _A(type): def __xor__(AA, AAA): return AA(AAA) def __invert__(AA): return globals() def __mod__(AA, AAA): return __import__("base64").b64decode(['QXJpdGhtZXRpY0Vycm9y', 'QXNzZXJ0aW9uRXJyb3I=', 'QXR0cmlidXRlRXJyb3I=', 'QmFzZUV4Y2VwdGlvbg==', 'QmFzZUV4Y2VwdGlvbkdyb3Vw', 'QmxvY2tpbmdJT0Vycm9y', 'QnJva2VuUGlwZUVycm9y', 'QnVmZmVyRXJyb3I=', 'Qnl0ZXNXYXJuaW5n', 'Q2hpbGRQcm9jZXNzRXJyb3I=', 'Q29ubmVjdGlvbkFib3J0ZWRFcnJvcg==', 'Q29ubmVjdGlvbkVycm9y', 'Q29ubmVjdGlvblJlZnVzZWRFcnJvcg==', 'Q29ubmVjdGlvblJlc2V0RXJyb3I=', 'RGVwcmVjYXRpb25XYXJuaW5n', 'RU9GRXJyb3I=', 'RWxsaXBzaXM=', 'RW5jb2RpbmdXYXJuaW5n', 'RW52aXJvbm1lbnRFcnJvcg==', 'RXhjZXB0aW9u', 'RXhjZXB0aW9uR3JvdXA=', 'RmFsc2U=', 'RmlsZUV4aXN0c0Vycm9y', 'RmlsZU5vdEZvdW5kRXJyb3I=', 'RmxvYXRpbmdQb2ludEVycm9y', 'RnV0dXJlV2FybmluZw==', 'R2VuZXJhdG9yRXhpdA==', 'SU9FcnJvcg==', 'SW1wb3J0RXJyb3I=', 'SW1wb3J0V2FybmluZw==', 'X19idWlsdGluc19f', 'a29rb25pX19fYnVpbHRpbnNfX19nYV9hcmltYXN1SW5kZW50YXRpb25FcnJvcg==', 'SW5kZXhFcnJvcg==', 'SW50ZXJydXB0ZWRFcnJvcg==', 'SXNBRGlyZWN0b3J5RXJyb3I=', 'S2V5RXJyb3I=', 'S2V5Ym9hcmRJbnRlcnJ1cHQ=', 'TG9va3VwRXJyb3I=', 'TWVtb3J5RXJyb3I=', 'TW9kdWxlTm90Rm91bmRFcnJvcg==', 'TmFtZUVycm9y', 'Tm9uZQ==', 'Tm90QURpcmVjdG9yeUVycm9y', 'Tm90SW1wbGVtZW50ZWQ=', 'Tm90SW1wbGVtZW50ZWRFcnJvcg==', 'T1NFcnJvcg==', 'T3ZlcmZsb3dFcnJvcg==', 'UGVuZGluZ0RlcHJlY2F0aW9uV2FybmluZw==', 'UGVybWlzc2lvbkVycm9y', 'UHJvY2Vzc0xvb2t1cEVycm9y', 'UmVjdXJzaW9uRXJyb3I=', 'UmVmZXJlbmNlRXJyb3I=', 'UmVzb3VyY2VXYXJuaW5n', 'UnVudGltZUVycm9y', 'UnVudGltZVdhcm5pbmc=', 'U3RvcEFzeW5jSXRlcmF0aW9u', 'U3RvcEl0ZXJhdGlvbg==', 'U3ludGF4RXJyb3I=', 'U3ludGF4V2FybmluZw==', 'U3lzdGVtRXJyb3I=', 'U3lzdGVtRXhpdA==', 'VGFiRXJyb3I=', 'VGltZW91dEVycm9y', 'VHJ1ZQ==', 'VHlwZUVycm9y', 'VW5ib3VuZExvY2FsRXJyb3I=', 'VW5pY29kZURlY29kZUVycm9y', 'VW5pY29kZUVuY29kZUVycm9y', 'VW5pY29kZUVycm9y', 'VW5pY29kZVRyYW5zbGF0ZUVycm9y', 'VW5pY29kZVdhcm5pbmc=', 'VXNlcldhcm5pbmc=', 'VmFsdWVFcnJvcg==', 'V2FybmluZw==', 'V2luZG93c0Vycm9y', 'WmVyb0RpdmlzaW9uRXJyb3I=', 'Xw==', 'X19idWlsZF9jbGFzc19f', 'X19kZWJ1Z19f', 'X19kb2NfXw==', 'X19pbXBvcnRfXw==', 'X19sb2FkZXJfXw==', 'X19uYW1lX18=', 'X19wYWNrYWdlX18=', 'X19zcGVjX18=', 'YWJz', 'YWl0ZXI=', 'YWxs', 'YW5leHQ=', 'YW55', 'YXNjaWk=', 'Ymlu', 'Ym9vbA==', 'YnJlYWtwb2ludA==', 'Ynl0ZWFycmF5', 'Ynl0ZXM=', 'Y2FsbGFibGU=', 'Y2hy', 'Y2xhc3NtZXRob2Q=', 'Z2V0', 'Y29tcGlsZQ==', 'Y29tcGxleA==', 'Y29weXJpZ2h0', 'am9pbg==', 'Y3JlZGl0cw==', 'ZGVsYXR0cg==', 'ZGljdA==', 'ZGly', 'ZGl2bW9k', 'ZW51bWVyYXRl', 'ZXZhbA==', 'ZXhlYw==', 'ZXhpdA==', 'ZmlsdGVy', 'ZmxvYXQ=', 'Zm9ybWF0', 'ZnJvemVuc2V0', 'Z2V0YXR0cg==', 'Z2xvYmFscw==', 'aGFzYXR0cg==', 'aGFzaA==', 'aGVscA==', 'aGV4', 'aWQ=', 'aW5wdXQ=', 'aW50', 'aXNpbnN0YW5jZQ==', 'aXNzdWJjbGFzcw==', 'aXRlcg==', 'bGVu', 'bGljZW5zZQ==', 'bGlzdA==', 'bG9jYWxz', 'bWFw', 'bWF4', 'bWVtb3J5dmlldw==', 'bWlu', 'bmV4dA==', 'b2JqZWN0', 'b2N0', 'b3Blbg==', 'b3Jk', 'cG93', 'cHJpbnQ=', 'cHJvcGVydHk=', 'cXVpdA==', 'cmFuZ2U=', 'cmVwcg==', 'cmV2ZXJzZWQ=', 'cm91bmQ=', 'c2V0', 'c2V0YXR0cg==', 'c2xpY2U=', 'c29ydGVk', 'c3RhdGljbWV0aG9k', 'c3Ry', 'c3Vt', 'c3VwZXI=', 'dHVwbGU=', 'dHlwZQ==', 'dmFycw==', 'emlw', 'X19idWlsdGluc19fa2FyYV9jb3B5X3NpbWFzaXRh', 'WW9rdW1pdHN1a2V0YW5lIQ==', 'TW90bW90b2hhX3NoYTI1Nl9UdWthdHRldGFrZWRvX0thZXRh', 'RGVidWdnZXJfYm91Z2FpX3R0ZV9kb3V5YXJ1bm9nYV9paW5uZGFybw=='][AAA].encode()).decode() class A(metaclass=_A): def __init__(AA, AAA): AA.A=AAA def __mul__(AA,AAA): return AA-(A:=-AA)-(A+AAA) def __sub__(AA,AAA): return (AA.A.append(AAA),AA)[1] def __neg__(AA): return AA.A.pop() def __xor__(AA,AAA): return AA-(-AA)(*[-AA for AAA in [AAA]*AAA]) def __mod__(AA,AAA): return [AA:=(AA-eval(-((AA-A%117)))(-AA,-AA)) for AAA in [AAA]*AAA][~AAA//(AAA+AAA//AAA)] def __truediv__(AA,AAA): return ((AA//AAA-""-A%103-A%155)**1)%1^2 def __pow__(AA,AAA): return ((AA-A%30-A%99-~A)%1^1)%1 def __floordiv__(AA,AAA): return AA-[-AA for AAA in [AAA]*AAA] def __pos__(AA): return [AA:=AA-AAA for AAA in -AA][-1] t=A^[];(((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((t-(-((((((t-58)*45*-6*11*-6*-70*82*3*-6*10*-89*82*-13*15*-6*-41//16-A%97)**249-A%133)**36^2)-""-A%103-A%155)**37%1^2))-(-((((((t-116)*1*-5*-2*-5//5-A%97)**96-A%133)**193^2)-""-A%103-A%155)**47%1^2)))**136)^1)-(-((((((t-101)*-1*11*-12*11*-9//6-A%97)**241-A%133)**173^2)-""-A%103-A%155)**5%1^2))-'tr'-'s')/2)**62)%1)^1)*b'')-(-((((((t-109)*8*-2//3-A%97)**251-A%133)**209^2)-""-A%103-A%155)**95%1^2)))**210)^1)-(-((((((t-100)*1*0*14//4-A%97)**222-A%133)**99^2)-""-A%103-A%155)**86%1^2))-(-((((((t-109)*2*-11*10*-13*17//6-A%97)**226-A%133)**131^2)-""-A%103-A%155)**172%1^2))-(-((((((t-95)*0*21*-2*-3*1*-3*-4*-10*0//10-A%97)**67-A%133)**106^2)-""-A%103-A%155)**238%1^2)))**68)^1)%1)^1)-(-((((((t-41)*0*0*57*-53*71*-76*0*5*-5*18*40*-54*53*-65*65*3*-2*11*-12*11//21-A%97)**105-A%133)**124^2)-""-A%103-A%155)**147%1^2))-(-((((((t-108)*-11*21*-17//4-A%97)**106-A%133)**201^2)-""-A%103-A%155)**86%1^2)))**99)^1)^2)*b'')-(-((((((t-110)*-9*7//3-A%97)**133-A%133)**109^2)-""-A%103-A%155)**224%1^2)))**127)^1)-(-((((((t-95)*0*18*-12*-6*0//6-A%97)**76-A%133)**248^2)-""-A%103-A%155)**42%1^2))-49)%1)^1)-(-((((((t-95)*0*5*10*-13*-2*0//7-A%97)**30-A%133)**16^2)-""-A%103-A%155)**120%1^2))-(-((((t-102)*14*-17*2*18*-17//6-A%95)**118)^1))-(-((((((t-104)*12*-11*14*-4*1*-2*-17*19*-1//10-A%97)**222-A%133)**47^2)-""-A%103-A%155)**168%1^2))-(-((((((t-93)*-40*-8*46*-26*-19*70*-58*39*3*-2*11*-12*11//14-A%97)**105-A%133)**95^2)-""-A%103-A%155)**249%1^2))-(-((((((t-108)*-11*21*-17//4-A%97)**16-A%133)**175^2)-""-A%103-A%155)**203%1^2)))**23)^1)^0)%1)^1)%1)^1)-(-((((((t-95)*0*14*-8*15*-11*11*-15*2*-8*0//11-A%97)**24-A%133)**237^2)-""-A%103-A%155)**17%1^2))-(-((((((t-41)*0*0*8*45*-53*10*0*-9*0*-1*0*0*9*44*-45*-12*17*-3*-1*-8*0*-1*12*0*-4*-12*28*-20*6*-3*1*-12*28*-20*-11*0*11*-4*9*44*-39*-2*-4*-7*0*-1*10*0*-2*-12*28*-20*8*-2*-9*0*-1*14*2*-20*28*-20*7*-5*0*4*-9*6*1*-4*-3*7*-4*-3*-1*13*-5*0*-4*71*-76*0*0*0*0*0*5*-5*5*-4*9*44*-53*10*1*-2*-8*0*-1*0*0*9*44*-45*-12*17*-4*-8*0*-1*12*0*-4*-12*28*-20*6*-3*1*-12*28*-20*-11*0*11*-4*9*44*-41*4*-8*-7*0*-1*10*0*-2*-12*28*-20*3*4*-10*0*-1*14*2*-20*28*-20*6*-4*0*3*-1*-7*11*-4*-4*-3*-1*9*-1*0*-4*71*-76*0*0*0*0*0*5*-5*5*-4*8*45*-53*16*-5*-2*-8*0*-1*0*0*9*44*-45*-12*19*-4*-3*-7*0*-1*12*0*-4*-12*28*-20*6*-3*1*-12*28*-20*-11*0*11*-4*9*44*-42*-3*-7*0*-1*10*0*-2*-12*28*-20*8*-2*-2*-7*0*-1*14*2*-20*28*-20*7*-5*0*8*-6*-4*-3*7*1*-8*7*0*-4*-3*-1*15*-8*1*-4*71*-76*0*0*0*0*0*5*-5*5*-4*0*9*44*-45*-12*12*0*-7*0*-1*12*0*-4*-12*28*-20*6*-3*1*-12*28*-20*-11*0*11*-4*9*44*-38*-5*-1*-8*0*-1*10*0*-2*-12*28*-20*12*-5*-2*-8*0*-1*14*2*-20*28*-20*11*-7*2*-4*0*2*0*-7*8*-1*-4*-3*7*0*-7*8*-5*-3*9*-9*11*1*-12*9*3*-9*-3*13*-4*-9*14*-7*-7*11*-8*-3*11*-11*6*-6*6*-6*6*-6*6*-6*6*-6*6*-6*6*-6*6*-6*12*1*-10*-3*7*6*-13*11*-8*-3*9*-6*-3*6*-6*8*-1*-7*10*-7*-3*9*-6*-3*13*-13*10*-7*-3*11*-11*11*-8*-3*11*-11*6*-6*6*-6*6*-6*6*-6*6*-6*12*1*-10*-3*7*6*-13*10*-7*-3*6*-6*11*-8*-3*9*-2*-7*7*-4*-3*9*-6*-3*15*-12*-3*8*-1*-7*9*-6*-3*14*-11*-3*7*0*-7*9*-6*-3*14*-11*-3*7*0*-7*13*-10*-3*7*-7*12*-12*9*-6*-3*10*-7*-3*8*-5*-3*15*-15*13*-10*-3*12*-9*-3*14*-14*6*-6*14*-11*-3*6*1*-7*6*2*-5*-3*14*-6*-8*6*2*-5*-3*8*-8*10*-3*-7*7*-4*-3*6*-6*14*-11*-3*7*-7*9*-6*-3*13*-13*6*2*-5*-3*14*-6*-8*8*-1*-4*-3*8*-5*-3*6*-6*6*1*-7*7*-4*-3*6*-6*13*-10*-3*7*-7*10*-7*-3*8*2*-7*-3*10*0*-10*15*-15*10*-7*-3*7*0*-7*6*-6*7*0*-4*-3*6*2*-5*-3*14*-6*-8*8*-1*-4*-3*7*-7*9*-6*-3*12*-12*6*2*-5*-3*14*-6*-8*8*-1*-4*-3*10*-7*-3*6*-6*8*-1*-7*7*-4*-3*6*-6*13*-10*-3*6*-6*13*-10*-3*15*-8*-7*8*-1*-4*-3*11*-1*-7*-3*10*0*-10*15*-15*6*-6*10*-7*-3*11*-11*11*-8*-3*11*-11*6*-6*6*-6*6*-6*6*-6*6*-6*12*1*-10*-3*7*6*-13*10*-7*-3*7*-7*15*-12*-3*12*-5*-7*7*-4*-3*14*-11*-3*14*-14*9*-6*-3*10*-7*-3*6*-6*13*-13*13*-10*-3*7*-7*12*-12*9*-6*-3*10*-7*-3*8*-5*-3*15*-15*13*-10*-3*12*-9*-3*14*-14*6*-6*13*-10*-3*15*-15*6*2*-5*-3*14*-6*-8*6*2*-5*-3*8*-8*10*-3*-7*7*-4*-3*6*-6*9*-2*-4*-3*13*-13*9*-9*6*2*-5*-3*14*-6*-8*8*-1*-4*-3*8*-5*-3*6*-6*6*1*-7*7*-4*-3*6*-6*6*1*-4*-3*8*-5*-3*6*4*-7*-3*10*0*-10*15*-15*10*-7*-3*7*0*-7*6*-6*7*0*-4*-3*6*2*-5*-3*14*-6*-8*8*-1*-4*-3*7*-7*9*-6*-3*12*-12*6*2*-5*-3*14*-6*-8*8*-1*-4*-3*10*-7*-3*6*-6*8*-1*-7*7*-4*-3*6*-6*13*-10*-3*8*-5*-3*6*-6*10*-3*-7*8*-1*-4*-3*11*-1*-7*-3*10*0*-10*15*-15*6*-6*10*-7*-3*11*-11*11*-8*-3*11*-11*6*-6*6*-6*6*-6*6*-6*6*-6*12*1*-10*-3*7*6*-13*8*-1*-4*-3*10*-10*8*-1*-7*7*-4*-3*12*-9*-3*12*-12*14*-11*-3*7*-7*13*-13*9*-6*-3*11*-8*-3*14*-14*9*-6*-3*12*-9*-3*15*-15*13*-10*-3*13*-13*9*-6*-3*12*-9*-3*15*-15*9*-6*-3*13*-10*-3*6*1*-7*9*-6*-3*10*-7*-3*7*-7*12*-12*12*-9*-3*7*-7*6*-6*8*-5*-3*7*-7*9*-9*6*2*-5*-3*14*-6*-8*6*2*-5*-3*8*-8*10*-3*-7*7*-4*-3*6*-6*13*-10*-3*14*-11*-3*6*-6*8*-1*-7*6*2*-5*-3*14*-6*-8*8*-1*-4*-3*8*-5*-3*6*-6*6*1*-7*7*-4*-3*6*-6*13*-10*-3*8*-5*-3*11*-8*-3*14*-5*-6*-3*10*0*-10*15*-15*10*-7*-3*7*0*-7*6*-6*7*0*-4*-3*6*2*-5*-3*14*-6*-8*8*-1*-4*-3*7*-7*9*-6*-3*12*-12*6*2*-5*-3*14*-6*-8*8*-1*-4*-3*10*-7*-3*6*-6*8*-1*-7*7*-4*-3*6*-6*10*-3*-4*-3*11*-11*10*-3*-7*8*-1*-4*-3*11*-1*-7*-3*10*0*-10*15*-15*6*-6*6*-6*7*-4*-3*6*-6*13*-10*-3*12*-9*-3*8*-5*-3*12*-5*-7*9*2*-8*-3*11*-1*-10*14*-14*6*-6*10*-10*8*-1*-4*-3*14*-14*9*2*-8*-3*10*0*-10*15*-15*6*-6*6*-6*-1*8*3*-7*71*-76*0*0*0*0*0*5*-5*5*-4*9*44*-53*12*2*-6*-7*0*-1*0*0*9*44*-45*-12*11*2*-8*0*-1*12*0*-4*-12*28*-20*6*-3*1*-12*28*-20*-11*0*11*-4*9*44*-45*8*-15*0*-1*10*0*-2*-12*28*-20*8*2*-13*0*-1*14*2*-20*28*-20*8*-6*0*8*-6*-7*9*-2*-4*-3*13*-13*8*-8*-1*8*-1*1*-4*71*-76*0*0*0*0*0*5*-5*5*-4*7*-3*-4*16*-5*-7*71*-76*0*0*0*0*0*0*0*0*0*0*0*0*0*0*5*-5*18*39*3*-2*11*-12*11//1342-A%97)**87-A%133)**93^2)-""-A%103-A%155)**15%1^2))-(-((((((t-108)*-11*21*-17//4-A%97)**42-A%133)**35^2)-""-A%103-A%155)**107%1^2)))**226)^1)-(-((((((t-41)*11*4*-6*44*-53*7*46*-53*14*-4*-2*-7*0*-1*0*0*9*44*-45*-12*17*-5*1*-8*0*-1*12*0*-4*-12*28*-20*6*-3*1*-12*28*-20*-11*0*11*-4*9*44*-39*-4*-9*0*-1*10*0*-2*-12*28*-20*10*-3*-10*0*-1*14*2*-20*28*-20*7*-5*0*10*-8*-4*-3*11*-4*-7*7*0*-4*-3*-1*13*-5*0*-4*71*-76*0*0*0*0*0*5*-5*5*-4*8*45*-53*8*2*-2*-7*0*-1*0*0*9*44*-45*-12*13*0*-1*-7*0*-1*12*0*-4*-12*28*-20*6*-3*1*-12*28*-20*-11*0*11*-4*9*44*-38*1*-15*0*-1*10*0*-2*-12*28*-20*7*4*-14*0*-1*14*2*-20*28*-20*8*-6*0*3*-5*-3*15*-15*11*-8*-3*12*-9*-3*-1*13*-5*0*-4*71*-76*0*0*0*0*0*5*-5*5*-4*0*9*44*-45*-12*13*4*-12*0*-1*12*0*-4*-12*28*-20*6*-3*1*-12*28*-20*-11*0*11*-4*9*44*-39*-7*1*-7*0*-1*10*0*-2*-12*28*-20*9*1*-6*-7*0*-1*14*2*-20*28*-20*12*-10*0*8*-4*-6*-3*7*0*-7*8*-1*-4*-3*9*-6*-3*6*-6*9*-2*-7*8*-8*13*-6*-4*-3*-1*13*-5*0*-4*71*-76*0*0*0*0*0*5*-5*5*71*-76*0*0*0*0*0*0*18*39*3*-2*11*-12*11//295-A%97)**117-A%133)**103^2)-""-A%103-A%155)**56%1^2))-(-((((((t-108)*-11*21*-17//4-A%97)**174-A%133)**239^2)-""-A%103-A%155)**177%1^2)))**61)^1)//2)%1)^1)^0)-(-((((((t-93)*-52*75*-71*-1*72*-71*-5*72*-7*17*-90*78*-5*-73*66*-54*53*-65*82*-3*-9*-70*9*0*0*8*45*-53*8*-12*4*0*57*-53*-4*0*9*44*-45*-12*13*4*-12*0*-1*12*0*-4*-12*28*-20*6*-3*1*-12*28*-20*-11*0*11*-4*9*44*-45*-1*1*-7*0*-1*10*0*-2*-12*28*-20*4*1*-8*0*-1*14*2*-20*28*-20*10*-8*0*1*-6*11*-3*-5*-3*15*-15*9*-6*-3*15*-8*-7*6*-6*-1*12*4*-12*71*-76*0*0*0*0*0*5*-5*5*-4*56*-52*71*-76*0*0*0*0*0*5*-5*51*-33*39*3*-2*11*-12*11//139-A%97)**227-A%133)**26^2)-""-A%103-A%155)**201%1^2))-(-((((((t-108)*-11*21*-17//4-A%97)**192-A%133)**94^2)-""-A%103-A%155)**244%1^2)))**107)^1)^0)-(-((((((t-95)*0*18*-12*-6*0//6-A%97)**56-A%133)**171^2)-""-A%103-A%155)**36%1^2))-(-((t-141)*95*-215*51*-41*156*-34*-27*58*-137*201*-223*48*-44*73*150*-80*78*-95*74*-130*55*55*-74*-9*-22*-49*38*122*-130*-12*15*53*83*-96*-114*99*142*-84*48*-71*82*-121*-93*-14*142*4*85*-88//49)))%1)^1)-(-((((((t-95)*0*14*-8*15*-11*11*-15*2*-8*0//11-A%97)**24-A%133)**167^2)-""-A%103-A%155)**55%1^2))-(-((((((t-41)*11*4*-6*44*-53*7*46*-53*13*-2*-3*-7*0*-1*0*0*9*44*-45*-12*14*5*-14*0*-1*12*0*-4*-12*28*-20*6*-3*1*-12*28*-20*-11*0*11*-4*9*44*-41*1*-5*-7*0*-1*10*0*-2*-12*28*-20*3*0*2*-8*0*-1*14*2*-20*28*-20*7*-5*0*10*-8*-4*-3*11*-4*-7*7*0*-4*-3*-1*13*-5*0*-4*71*-76*0*0*0*0*0*5*-5*5*-4*8*45*-53*14*-6*1*-8*0*-1*0*0*9*44*-45*-12*20*-6*-2*-7*0*-1*12*0*-4*-12*28*-20*6*-3*1*-12*28*-20*-11*0*11*-4*9*44*-45*7*-14*0*-1*10*0*-2*-12*28*-20*8*-4*0*-7*0*-1*14*2*-20*28*-20*8*-6*0*3*-5*-3*15*-15*11*-8*-3*12*-9*-3*-1*13*-5*0*-4*71*-76*0*0*0*0*0*5*-5*5*-4*0*9*44*-45*-12*11*5*-11*0*-1*12*0*-4*-12*28*-20*6*-3*1*-12*28*-20*-11*0*11*-4*9*44*-39*-4*-9*0*-1*10*0*-2*-12*28*-20*6*4*-6*-7*0*-1*14*2*-20*28*-20*11*-9*0*5*0*-7*-3*9*-6*-3*6*-6*9*-2*-7*8*-8*13*-6*-4*-3*9*5*-14*-1*10*0*-6*71*-76*0*0*0*0*0*5*-5*5*71*-76*0*0*0*0*0*0*18*-26*65*3*-2*11*-12*11//292-A%97)**174-A%133)**8^2)-""-A%103-A%155)**134%1^2))-(-((((((t-108)*-11*21*-17//4-A%97)**40-A%133)**140^2)-""-A%103-A%155)**147%1^2)))**167)^1)-(-((((((t-41)*11*4*-6*44*-53*7*46*-53*9*5*-6*-7*0*-1*0*0*9*44*-45*-12*18*-2*-11*0*-1*12*0*-4*-12*28*-20*6*-3*1*-12*28*-20*-11*0*11*-4*9*44*-44*-8*0*-1*10*0*-2*-12*28*-20*9*-4*-1*-7*0*-1*14*2*-20*28*-20*7*-5*0*10*-8*-4*-3*11*-4*-7*7*0*-4*-3*-1*13*-5*0*-4*71*-76*0*0*0*0*0*5*-5*5*-4*8*45*-53*7*4*-2*-8*0*-1*0*0*9*44*-45*-12*19*-4*-2*-8*0*-1*12*0*-4*-12*28*-20*6*-3*1*-12*28*-20*-11*0*11*-4*9*44*-40*-5*0*-7*0*-1*10*0*-2*-12*28*-20*11*-2*-5*-7*0*-1*14*2*-20*28*-20*8*-6*0*3*-5*-3*15*-15*11*-8*-3*12*-9*-3*-1*13*-5*0*-4*71*-76*0*0*0*0*0*5*-5*5*-4*0*9*44*-45*-12*15*-1*-2*-7*0*-1*12*0*-4*-12*28*-20*6*-3*1*-12*28*-20*-11*0*11*-4*9*44*-44*3*-3*-8*0*-1*10*0*-2*-12*28*-20*8*0*-11*0*-1*14*2*-20*28*-20*12*-10*0*8*-4*-6*-3*7*0*-7*8*-1*-4*-3*9*-6*-3*6*-6*9*-2*-7*8*-8*13*-6*-4*-3*-1*13*-5*0*-4*71*-76*0*0*0*0*0*5*-5*5*71*-76*0*0*0*0*0*0*18*-26*65*3*-2*11*-12*11//297-A%97)**184-A%133)**140^2)-""-A%103-A%155)**252%1^2))-(-((((((t-108)*-11*21*-17//4-A%97)**3-A%133)**50^2)-""-A%103-A%155)**201%1^2)))**222)^1)//2)%1)^1)^0)
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/FullWeakEngineer/2025/rev/reeeeeee/reeeeeee.py
ctfs/FullWeakEngineer/2025/rev/reeeeeee/reeeeeee.py
from _sre import compile from sys import version_info assert version_info[0] == 3 and version_info[1] >= 11 flag = input("Enter flag > ") print("YNeos!!"[not compile("dummy",0,[14, 4, 0, 0, 0, 4, 40, 0, 6, 0, 16, 102, 16, 119, 16, 101, 16, 99, 16, 116, 16, 102, 16, 123, 24, 16, 48, 48, 13, 11, 9, 0, 2214526978, 2281701374, 134217726, 0, 0, 0, 0, 0, 1, 16, 125, 6, 5, 1, 4, 39, 0, 6, 0, 23, 30, 0, 4294967295, 7, 5, 20, 99, 15, 22, 20, 16, 99, 4, 14, 0, 17, 0, 13, 6, 16, 116, 16, 48, 0, 17, 1, 1, 15, 2, 0, 18, 6, 5, 1, 4, 46, 0, 6, 0, 23, 37, 0, 4294967295, 7, 5, 20, 100, 15, 29, 27, 16, 100, 4, 21, 0, 17, 2, 7, 7, 16, 95, 16, 82, 15, 7, 5, 16, 49, 15, 2, 0, 17, 3, 1, 15, 2, 0, 18, 6, 5, 1, 4, 46, 0, 6, 0, 23, 37, 0, 4294967295, 7, 5, 20, 101, 15, 29, 27, 16, 101, 4, 21, 0, 17, 4, 7, 5, 16, 99, 15, 9, 7, 16, 88, 16, 120, 15, 2, 0, 17, 5, 1, 15, 2, 0, 18, 6, 5, 1, 4, 39, 0, 6, 0, 23, 30, 0, 4294967295, 7, 5, 20, 102, 15, 22, 20, 16, 102, 4, 14, 0, 17, 6, 13, 6, 16, 119, 16, 123, 0, 17, 7, 1, 15, 2, 0, 18, 6, 5, 1, 4, 48, 0, 6, 0, 23, 39, 0, 4294967295, 7, 5, 20, 104, 15, 31, 29, 16, 104, 4, 23, 0, 17, 8, 7, 7, 16, 49, 16, 63, 15, 9, 7, 16, 95, 16, 68, 15, 2, 0, 17, 9, 1, 15, 2, 0, 18, 6, 5, 1, 4, 32, 0, 6, 0, 23, 23, 0, 4294967295, 7, 5, 20, 108, 15, 15, 13, 16, 108, 4, 7, 0, 16, 51, 16, 100, 1, 15, 2, 0, 18, 6, 5, 1, 4, 30, 0, 6, 0, 23, 21, 0, 4294967295, 7, 5, 20, 109, 15, 13, 11, 16, 109, 4, 5, 0, 16, 66, 1, 15, 2, 0, 18, 6, 5, 1, 4, 48, 0, 6, 0, 23, 39, 0, 4294967295, 7, 5, 20, 112, 15, 31, 29, 16, 112, 4, 23, 0, 17, 10, 7, 7, 16, 49, 16, 108, 15, 9, 7, 16, 114, 16, 52, 15, 2, 0, 17, 11, 1, 15, 2, 0, 18, 6, 5, 1, 4, 55, 0, 6, 0, 23, 46, 0, 4294967295, 7, 5, 20, 114, 15, 38, 36, 16, 114, 4, 30, 0, 17, 12, 7, 7, 16, 95, 16, 100, 15, 16, 7, 16, 83, 16, 101, 15, 9, 7, 16, 52, 16, 95, 15, 2, 0, 17, 13, 1, 15, 2, 0, 18, 6, 5, 1, 4, 46, 0, 6, 0, 23, 37, 0, 4294967295, 7, 5, 20, 115, 15, 29, 27, 16, 115, 4, 21, 0, 17, 14, 7, 7, 16, 83, 16, 52, 15, 7, 5, 16, 51, 15, 2, 0, 17, 15, 1, 15, 2, 0, 18, 6, 5, 1, 4, 30, 0, 6, 0, 23, 21, 0, 4294967295, 7, 5, 20, 116, 15, 13, 11, 16, 116, 4, 5, 0, 16, 102, 1, 15, 2, 0, 18, 6, 5, 1, 4, 46, 0, 6, 0, 23, 37, 0, 4294967295, 7, 5, 20, 117, 15, 29, 27, 16, 117, 4, 21, 0, 17, 16, 7, 5, 16, 115, 15, 9, 7, 16, 83, 16, 52, 15, 2, 0, 17, 17, 1, 15, 2, 0, 18, 6, 5, 1, 4, 46, 0, 6, 0, 23, 37, 0, 4294967295, 7, 5, 20, 119, 15, 29, 27, 16, 119, 4, 21, 0, 17, 18, 7, 5, 16, 101, 15, 9, 7, 16, 104, 16, 49, 15, 2, 0, 17, 19, 1, 15, 2, 0, 18, 6, 5, 1, 4, 32, 0, 6, 0, 23, 23, 0, 4294967295, 7, 5, 20, 120, 15, 15, 13, 16, 120, 4, 7, 0, 16, 88, 16, 33, 1, 15, 2, 0, 18, 6, 5, 1, 4, 30, 0, 6, 0, 23, 21, 0, 4294967295, 7, 5, 20, 66, 15, 13, 11, 16, 66, 4, 5, 0, 16, 33, 1, 15, 2, 0, 18, 6, 5, 1, 4, 46, 0, 6, 0, 23, 37, 0, 4294967295, 7, 5, 20, 68, 15, 29, 27, 16, 68, 4, 21, 0, 17, 20, 7, 7, 16, 49, 16, 115, 15, 7, 5, 16, 95, 15, 2, 0, 17, 21, 1, 15, 2, 0, 18, 6, 5, 1, 4, 46, 0, 6, 0, 23, 37, 0, 4294967295, 7, 5, 20, 69, 15, 29, 27, 16, 69, 4, 21, 0, 17, 22, 7, 5, 16, 114, 15, 9, 7, 16, 95, 16, 119, 15, 2, 0, 17, 23, 1, 15, 2, 0, 18, 6, 5, 1, 4, 46, 0, 6, 0, 23, 37, 0, 4294967295, 7, 5, 20, 77, 15, 29, 27, 16, 77, 4, 21, 0, 17, 24, 7, 5, 16, 112, 15, 9, 7, 16, 120, 16, 66, 15, 2, 0, 17, 25, 1, 15, 2, 0, 18, 6, 5, 1, 4, 32, 0, 6, 0, 23, 23, 0, 4294967295, 7, 5, 20, 82, 15, 15, 13, 16, 82, 4, 7, 0, 16, 51, 16, 57, 1, 15, 2, 0, 18, 6, 5, 1, 4, 46, 0, 6, 0, 23, 37, 0, 4294967295, 7, 5, 20, 83, 15, 29, 27, 16, 83, 4, 21, 0, 17, 26, 7, 5, 16, 52, 15, 9, 7, 16, 115, 16, 51, 15, 2, 0, 17, 27, 1, 15, 2, 0, 18, 6, 5, 1, 4, 48, 0, 6, 0, 23, 39, 0, 4294967295, 7, 5, 20, 85, 15, 31, 29, 16, 85, 4, 23, 0, 17, 28, 7, 7, 16, 95, 16, 117, 15, 9, 7, 16, 49, 16, 63, 15, 2, 0, 17, 29, 1, 15, 2, 0, 18, 6, 5, 1, 4, 46, 0, 6, 0, 23, 37, 0, 4294967295, 7, 5, 20, 88, 15, 29, 27, 16, 88, 4, 21, 0, 17, 30, 7, 5, 16, 120, 15, 9, 7, 16, 33, 16, 95, 15, 2, 0, 17, 31, 1, 15, 2, 0, 18, 6, 5, 1, 4, 46, 0, 6, 0, 23, 37, 0, 4294967295, 7, 5, 20, 48, 15, 29, 27, 16, 48, 4, 21, 0, 17, 32, 7, 5, 16, 77, 15, 9, 7, 16, 49, 16, 82, 15, 2, 0, 17, 33, 1, 15, 2, 0, 18, 6, 5, 1, 4, 56, 0, 6, 0, 23, 47, 0, 4294967295, 7, 5, 20, 49, 15, 39, 37, 16, 49, 4, 31, 0, 17, 34, 7, 5, 16, 108, 15, 19, 5, 16, 63, 15, 14, 7, 16, 115, 16, 83, 15, 7, 5, 16, 68, 15, 2, 0, 17, 35, 1, 15, 2, 0, 18, 6, 5, 1, 4, 56, 0, 6, 0, 23, 47, 0, 4294967295, 7, 5, 20, 51, 15, 39, 37, 16, 51, 4, 31, 0, 17, 36, 7, 7, 16, 100, 16, 95, 15, 17, 5, 16, 57, 15, 12, 5, 16, 109, 15, 7, 5, 16, 63, 15, 2, 0, 17, 37, 1, 15, 2, 0, 18, 6, 5, 1, 4, 32, 0, 6, 0, 23, 23, 0, 4294967295, 7, 5, 20, 52, 15, 15, 13, 16, 52, 4, 7, 0, 16, 83, 16, 115, 1, 15, 2, 0, 18, 6, 5, 1, 4, 32, 0, 6, 0, 23, 23, 0, 4294967295, 7, 5, 20, 57, 15, 15, 13, 16, 57, 4, 7, 0, 16, 101, 16, 88, 1, 15, 2, 0, 18, 6, 5, 1, 4, 48, 0, 6, 0, 23, 39, 0, 4294967295, 7, 5, 20, 123, 15, 31, 29, 16, 123, 4, 23, 0, 17, 38, 7, 7, 16, 99, 16, 48, 15, 9, 7, 16, 51, 16, 102, 15, 2, 0, 17, 39, 1, 15, 2, 0, 18, 6, 5, 1, 4, 46, 0, 6, 0, 23, 37, 0, 4294967295, 7, 5, 20, 33, 15, 29, 27, 16, 33, 4, 21, 0, 17, 40, 7, 7, 16, 95, 16, 119, 15, 7, 5, 16, 69, 15, 2, 0, 17, 41, 1, 15, 2, 0, 18, 6, 5, 1, 4, 46, 0, 6, 0, 23, 37, 0, 4294967295, 7, 5, 20, 63, 15, 29, 27, 16, 63, 4, 21, 0, 17, 42, 7, 7, 16, 104, 16, 95, 15, 7, 5, 16, 125, 15, 2, 0, 17, 43, 1, 15, 2, 0, 18, 6, 5, 1, 4, 68, 0, 6, 0, 23, 59, 0, 4294967295, 7, 5, 20, 95, 15, 51, 49, 16, 95, 4, 43, 0, 17, 44, 7, 5, 16, 82, 15, 31, 7, 16, 119, 16, 104, 15, 24, 7, 16, 68, 16, 49, 15, 17, 5, 16, 100, 15, 12, 5, 16, 85, 15, 7, 5, 16, 117, 15, 2, 0, 17, 45, 1, 15, 2, 0, 18, 6, 5, 1, 1],23,{},(None,)*24).match(flag)::2])
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/WorldWide/2024/misc/Mutual_TLS/serv.py
ctfs/WorldWide/2024/misc/Mutual_TLS/serv.py
import ssl from OpenSSL import crypto from flask import Flask, request from werkzeug.serving import WSGIRequestHandler, make_server app = Flask(__name__) def extract_subject_from_cert(ssl_socket): try: for cert in ssl_socket.get_unverified_chain(): cert = cert cert = crypto.load_certificate(crypto.FILETYPE_ASN1, cert) subject = cert.get_subject().CN return subject.strip() except Exception as e: return '' class CustomRequestHandler(WSGIRequestHandler): def make_environ(self): environ = super().make_environ() environ['subject'] = self.subject return environ def run_wsgi(self): ssl_socket = self.connection self.subject = extract_subject_from_cert(ssl_socket) super().run_wsgi() @app.route("/") def home(): subject = request.environ.get('subject', []) print(subject) if subject == 'client.local': return "Hello user!\n", 200 if subject == 'admin.local': return "Congrats! Here is the flag: wwf{REDACTED}\n", 200 return "Invalid client certificate provided.\n", 401 if __name__ == "__main__": context = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER) context.verify_mode = ssl.CERT_REQUIRED context.load_cert_chain(certfile="certs/server-cert.pem", keyfile="certs/server-key.pem") context.load_verify_locations(cafile="certs/ca-cert.pem") server = make_server("0.0.0.0", 443, app, request_handler=CustomRequestHandler, ssl_context=context) server.serve_forever()
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/WorldWide/2024/crypto/Simpler_RSA/chal.py
ctfs/WorldWide/2024/crypto/Simpler_RSA/chal.py
from secret import flag from Crypto.Util.number import bytes_to_long, getPrime flag = bytes_to_long(flag) p = getPrime(2048) q = getPrime(2048) c = pow(flag, p, q) # i believe this is the fancy rsa encryption? print(f'{p=}') print(f'{q=}') print(f'{c=}')
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/WorldWide/2024/crypto/Subathon/chall.py
ctfs/WorldWide/2024/crypto/Subathon/chall.py
from notaes import notAES from os import urandom from time import time # ugh standard flag shenanigans yada yada key = urandom(16) cipher = notAES(key) from secret import flag flag_enc = cipher.encrypt(flag.encode()) print(f'{flag_enc = }') # time for the subathon! st = time() TIME_LEFT = 30 while time() - st < TIME_LEFT: print("=================") print("1. Subscrib") print("2. Play rand gaem") print("3. Quit") print("=================") choice = str(input()) if choice == "1": print("Thank you for the sub!!") TIME_LEFT += 30 elif choice == "2": print("Guess the number!") ur_guess = int(input(">> ")) my_number = int.from_bytes(cipher.encrypt(urandom(16)), "big") if ur_guess != my_number: print(f"You lose, the number was {my_number}") else: print("Omg you won! Here's the flag") print(flag) else: break print("The subathon's over! Hope you had fun!!")
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/WorldWide/2024/crypto/Subathon/notaes.py
ctfs/WorldWide/2024/crypto/Subathon/notaes.py
#!/usr/bin/env python3 # https://github.com/boppreh/aes/blob/master/aes.py, definitely unaltered s_box = ( 0x63, 0x7C, 0x77, 0x7B, 0xF2, 0x6B, 0x6F, 0xC5, 0x30, 0x01, 0x67, 0x2B, 0xFE, 0xD7, 0xAB, 0x76, 0xCA, 0x82, 0xC9, 0x7D, 0xFA, 0x59, 0x47, 0xF0, 0xAD, 0xD4, 0xA2, 0xAF, 0x9C, 0xA4, 0x72, 0xC0, 0xB7, 0xFD, 0x93, 0x26, 0x36, 0x3F, 0xF7, 0xCC, 0x34, 0xA5, 0xE5, 0xF1, 0x71, 0xD8, 0x31, 0x15, 0x04, 0xC7, 0x23, 0xC3, 0x18, 0x96, 0x05, 0x9A, 0x07, 0x12, 0x80, 0xE2, 0xEB, 0x27, 0xB2, 0x75, 0x09, 0x83, 0x2C, 0x1A, 0x1B, 0x6E, 0x5A, 0xA0, 0x52, 0x3B, 0xD6, 0xB3, 0x29, 0xE3, 0x2F, 0x84, 0x53, 0xD1, 0x00, 0xED, 0x20, 0xFC, 0xB1, 0x5B, 0x6A, 0xCB, 0xBE, 0x39, 0x4A, 0x4C, 0x58, 0xCF, 0xD0, 0xEF, 0xAA, 0xFB, 0x43, 0x4D, 0x33, 0x85, 0x45, 0xF9, 0x02, 0x7F, 0x50, 0x3C, 0x9F, 0xA8, 0x51, 0xA3, 0x40, 0x8F, 0x92, 0x9D, 0x38, 0xF5, 0xBC, 0xB6, 0xDA, 0x21, 0x10, 0xFF, 0xF3, 0xD2, 0xCD, 0x0C, 0x13, 0xEC, 0x5F, 0x97, 0x44, 0x17, 0xC4, 0xA7, 0x7E, 0x3D, 0x64, 0x5D, 0x19, 0x73, 0x60, 0x81, 0x4F, 0xDC, 0x22, 0x2A, 0x90, 0x88, 0x46, 0xEE, 0xB8, 0x14, 0xDE, 0x5E, 0x0B, 0xDB, 0xE0, 0x32, 0x3A, 0x0A, 0x49, 0x06, 0x24, 0x5C, 0xC2, 0xD3, 0xAC, 0x62, 0x91, 0x95, 0xE4, 0x79, 0xE7, 0xC8, 0x37, 0x6D, 0x8D, 0xD5, 0x4E, 0xA9, 0x6C, 0x56, 0xF4, 0x93, 0x65, 0x7A, 0xAE, 0x08, 0xBA, 0x78, 0x25, 0x2E, 0x1C, 0xA6, 0xB4, 0xC6, 0xE8, 0xDD, 0x74, 0x1F, 0x4B, 0xBD, 0x8B, 0x8A, 0x70, 0x3E, 0xB5, 0x66, 0x48, 0x03, 0xF6, 0x0E, 0x61, 0x35, 0x57, 0xB9, 0x86, 0xC1, 0x1D, 0x9E, 0xE1, 0xF8, 0x98, 0x11, 0x69, 0xD9, 0x8E, 0x94, 0x9B, 0x1E, 0x87, 0xE9, 0xCE, 0x55, 0x28, 0xDF, 0x8C, 0xA1, 0x89, 0x0D, 0xBF, 0xE6, 0x42, 0x68, 0x41, 0x99, 0x2D, 0x0F, 0xB0, 0x54, 0xBB, 0x16, ) def sub_bytes(s): for i in range(4): for j in range(4): s[i][j] = s_box[s[i][j]] def shift_rows(s): s[0][1], s[1][1], s[2][1], s[3][1] = s[1][1], s[2][1], s[3][1], s[0][1] s[0][2], s[1][2], s[2][2], s[3][2] = s[2][2], s[3][2], s[0][2], s[1][2] s[0][3], s[1][3], s[2][3], s[3][3] = s[3][3], s[0][3], s[1][3], s[2][3] def inv_shift_rows(s): s[0][1], s[1][1], s[2][1], s[3][1] = s[3][1], s[0][1], s[1][1], s[2][1] s[0][2], s[1][2], s[2][2], s[3][2] = s[2][2], s[3][2], s[0][2], s[1][2] s[0][3], s[1][3], s[2][3], s[3][3] = s[1][3], s[2][3], s[3][3], s[0][3] def add_round_key(s, k): for i in range(4): for j in range(4): s[i][j] ^= k[i][j] # learned from https://web.archive.org/web/20100626212235/http://cs.ucsb.edu/~koc/cs178/projects/JT/aes.c xtime = lambda a: (((a << 1) ^ 0x1B) & 0xFF) if (a & 0x80) else (a << 1) def mix_single_column(a): # see Sec 4.1.2 in The Design of Rijndael t = a[0] ^ a[1] ^ a[2] ^ a[3] u = a[0] a[0] ^= t ^ xtime(a[0] ^ a[1]) a[1] ^= t ^ xtime(a[1] ^ a[2]) a[2] ^= t ^ xtime(a[2] ^ a[3]) a[3] ^= t ^ xtime(a[3] ^ u) def mix_columns(s): for i in range(4): mix_single_column(s[i]) def inv_mix_columns(s): # see Sec 4.1.3 in The Design of Rijndael for i in range(4): u = xtime(xtime(s[i][0] ^ s[i][2])) v = xtime(xtime(s[i][1] ^ s[i][3])) s[i][0] ^= u s[i][1] ^= v s[i][2] ^= u s[i][3] ^= v mix_columns(s) r_con = ( 0x00, 0x01, 0x02, 0x04, 0x08, 0x10, 0x20, 0x40, 0x80, 0x1B, 0x36, 0x6C, 0xD8, 0xAB, 0x4D, 0x9A, 0x2F, 0x5E, 0xBC, 0x63, 0xC6, 0x97, 0x35, 0x6A, 0xD4, 0xB3, 0x7D, 0xFA, 0xEF, 0xC5, 0x91, 0x39, ) def bytes2matrix(text): """ Converts a 16-byte array into a 4x4 matrix. """ return [list(text[i:i+4]) for i in range(0, len(text), 4)] def matrix2bytes(matrix): """ Converts a 4x4 matrix into a 16-byte array. """ return bytes(sum(matrix, [])) def xor_bytes(a, b): """ Returns a new byte array with the elements xor'ed. """ return bytes(i^j for i, j in zip(a, b)) def pad(plaintext): """ Pads the given plaintext with PKCS#7 padding to a multiple of 16 bytes. Note that if the plaintext size is a multiple of 16, a whole block will be added. """ padding_len = 16 - (len(plaintext) % 16) padding = bytes([padding_len] * padding_len) return plaintext + padding def split_blocks(message, block_size=16, require_padding=True): assert len(message) % block_size == 0 or not require_padding return [message[i:i+16] for i in range(0, len(message), block_size)] class notAES: """ Class for AES-128 encryption This is a raw implementation of AES, without key stretching or IV management. Unless you need that, please use `encrypt` and `decrypt`. """ rounds_by_key_size = {16: 10, 24: 12, 32: 14} def __init__(self, master_key): """ Initializes the object with a given key. """ assert len(master_key) in notAES.rounds_by_key_size self.n_rounds = notAES.rounds_by_key_size[len(master_key)] self._key_matrices = self._expand_key(master_key) def _expand_key(self, master_key): """ Expands and returns a list of key matrices for the given master_key. """ # Initialize round keys with raw key material. key_columns = bytes2matrix(master_key) iteration_size = len(master_key) // 4 i = 1 while len(key_columns) < (self.n_rounds + 1) * 4: # Copy previous word. word = list(key_columns[-1]) # Perform schedule_core once every "row". if len(key_columns) % iteration_size == 0: # Circular shift. word.append(word.pop(0)) # Map to S-BOX. word = [s_box[b] for b in word] # XOR with first byte of R-CON, since the others bytes of R-CON are 0. word[0] ^= r_con[i] i += 1 elif len(master_key) == 32 and len(key_columns) % iteration_size == 4: # Run word through S-box in the fourth iteration when using a # 256-bit key. word = [s_box[b] for b in word] # XOR with equivalent word from previous iteration. word = xor_bytes(word, key_columns[-iteration_size]) key_columns.append(word) # Group key words in 4x4 byte matrices. return [key_columns[4*i : 4*(i+1)] for i in range(len(key_columns) // 4)] def encrypt_block(self, plaintext): """ Encrypts a single block of 16 byte long plaintext. """ assert len(plaintext) == 16 plain_state = bytes2matrix(plaintext) add_round_key(plain_state, self._key_matrices[0]) for i in range(1, self.n_rounds): sub_bytes(plain_state) shift_rows(plain_state) mix_columns(plain_state) add_round_key(plain_state, self._key_matrices[i]) sub_bytes(plain_state) shift_rows(plain_state) add_round_key(plain_state, self._key_matrices[-1]) return matrix2bytes(plain_state) def encrypt(self, plaintext): plaintext = pad(plaintext) ciphertext = b"" for i in range(0, len(plaintext), 16): ciphertext += self.encrypt_block(plaintext[i:i+16]) return ciphertext
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/WorldWide/2024/crypto/Rolypoly/chall.py
ctfs/WorldWide/2024/crypto/Rolypoly/chall.py
from sage.all import GF, PolynomialRing, ZZ, save from hashlib import sha256 from Crypto.Cipher import AES n = 1201 q = 467424413 K = GF(q) PR = PolynomialRing(K, names=('t',)); (t,) = PR._first_ngens(1) R = PR.quotient(PR.ideal([t**n-1 ])) PR2 = PolynomialRing(R,2 , names=('x', 'y',)); (x, y,) = PR2._first_ngens(2) def SamplePoly(): p = R.zero() for i in range(0,n): p += ZZ.random_element(0,q)*t**i return p def SampleSmallPoly(): sp = R.zero() for i in range(0,n): sp += ZZ.random_element(0,4)*t**i return sp def r2int(r): out = 1 for ri in r.coefficients(): out *= int(sum([j for j in ri.lift().coefficients()])) return out def keyGen(): ux = SampleSmallPoly() uy = SampleSmallPoly() X10 = SamplePoly() X01 = SamplePoly() X00 = -X10*ux - X01*uy return (ux,uy,X00,X10,X01) def Encrypt(m, key): _,_,X00,X10,X01 = key Ctx = X00 + X10*x + X01*y r = SamplePoly() + SamplePoly()*x + SamplePoly()*y Ctx = Ctx*r for i in range(0,3): for j in range(0,3-i): Ctx += 4*SampleSmallPoly()*x**i*y**j return (Ctx + m, r2int(r)) flag = b"wwf{??????????????????????????????????????}\x05\x05\x05\x05\x05" gkey = keyGen() pubkey = gkey[2:] r0 = SampleSmallPoly() Ctx, r = Encrypt(r0, gkey) rk = sha256(str(r).encode()).digest() flag_enc = AES.new(key=rk, mode=AES.MODE_ECB).encrypt(flag) save([flag_enc, pubkey, Ctx], "output.sobj")
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/WorldWide/2024/crypto/Amineo/chall.py
ctfs/WorldWide/2024/crypto/Amineo/chall.py
from secrets import randbits from hashlib import sha256 import os flag = os.getenv("flag", "wwf{<REDACTED>}").encode() assert len(flag) == 32 p = 0xffffffffffffffffffffffffffffff53 Nr = 4 bSEED = b"AMINEO" A = int.from_bytes(sha256(b"A" + bSEED).digest(), "big") % p B = int.from_bytes(sha256(b"B" + bSEED).digest(), "big") % p Ci = [int.from_bytes(sha256(b"C" + bSEED + str(r).encode()).digest(), "big") % p for r in range(Nr)] Di = [int.from_bytes(sha256(b"D" + bSEED + str(r).encode()).digest(), "big") % p for r in range(Nr)] Ei = [int.from_bytes(sha256(b"E" + bSEED + str(r).encode()).digest(), "big") % p for r in range(Nr)] Fi = [int.from_bytes(sha256(b"F" + bSEED + str(r).encode()).digest(), "big") % p for r in range(Nr)] Gi = [int.from_bytes(sha256(b"G" + bSEED + str(r).encode()).digest(), "big") % p for r in range(Nr)] Hi = [int.from_bytes(sha256(b"H" + bSEED + str(r).encode()).digest(), "big") % p for r in range(Nr)] def xor(a, b): return bytes(x ^ y for x, y in zip(a, b)) class Amineo: def __init__(self, nr): self.nr = nr self.k = pow(3, -1, p - 1) def H(self, S): x, y = S x += A*y**2 y += pow(x, self.k, p) x += B*y return x % p, y % p def M(self, S, r): x, y = S return Ci[r]*x + Di[r]*y + Ei[r] % p, Fi[r]*x + Gi[r]*y + Hi[r] % p def encrypt(self, S): Se = S.copy() for r in range(self.nr): Se = self.H(self.M(Se, r)) return list(Se) if __name__ == "__main__": print("I dont trust you but I guess you don't either...") try: user_B = bytes.fromhex(input("Give me 2 RANDOM blocks of 16 bytes (hex) >")) assert len(user_B) == 32 except: print("I KNEW YOUD TRY TO CHEAT IF I GAVE YOU ANY CONTROL !!!") print("GET OUT OF HERE !!!") exit() S = [int.from_bytes(user_B[i:i+16], "big") % p for i in range(0, len(user_B), 16)] print("I dont trust you I'll add my part ...") tamper_idx = randbits(1) S[tamper_idx] *= randbits(128) % p enc = Amineo(Nr) OTP = enc.encrypt(S) print("Just to be sure I mean ... More random never hurts right ? :) ") OTP[0] *= randbits(128) OTP[1] *= randbits(128) OTP[0] %= p OTP[1] %= p OPTb = b"".join(int.to_bytes(OTP[i], 16, "big") for i in range(2)) print("Here you go... :", xor(flag, OPTb).hex())
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/WorldWide/2024/crypto/epsilonDH/chall.py
ctfs/WorldWide/2024/crypto/epsilonDH/chall.py
from Crypto.Util.number import getStrongPrime, getRandomNBitInteger, bytes_to_long import os p = getStrongPrime(1024) flag = os.getenv("flag", "wwf{<REDACTED>}").encode() class Epsilon: def __init__(self, a, b): self.a, self.b = a, b def __add__(self, other): if type(other) == int: other = Epsilon(other, 0) return Epsilon(self.a + other.a, self.b + other.b) def __radd__(self, other): return self.__add__(other) def __mul__(self, other): if type(other) == int: other = Epsilon(other, 0) return Epsilon(self.a * other.a, self.a * other.b + other.a * self.b) def __rmul__(self, other): return self.__mul__(other) def __mod__(self, other: int): return Epsilon(self.a % other, self.b % other) def __repr__(self): return f"{self.a} + {self.b}ɛ" @staticmethod def getRandomBits(n): return Epsilon(getRandomNBitInteger(n), getRandomNBitInteger(n)) def powm(b, e, m): r = 1 while e > 1: if e & 1: r = (r * b) % m b = (b * b) % m e >>= 1 return (b * r) % m ɛ = Epsilon(0, 1) g = ɛ.getRandomBits(1024) m = bytes_to_long(flag) assert m < p A = powm(g, m, p) print(f"{p = }") print(f"{g = }") print(f"{A = }")
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/WorldWide/2024/crypto/Modnar/chall.py
ctfs/WorldWide/2024/crypto/Modnar/chall.py
import random import time from secret import flag def get_random_array(x): y = list(range(1,x)) random.Random().shuffle(y) return y my_seed = bytes(get_random_array(42)) random.seed(my_seed) my_random_val = random.getrandbits(9999) print(f"my seed: {my_seed.hex()}") start = time.time() ur_seed = bytes.fromhex(input("Enter your seed! > ")) if ur_seed == my_seed: print("Hey that's my seed! No copying >:(") exit() if time.time() - start > 5: print("Too slow I've already lost interest in seeds -_- ") exit() random.seed(ur_seed) ur_random_val = random.getrandbits(9999) print(flag) if my_random_val == ur_random_val else print("in rand we trust.")
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/WorldWide/2024/crypto/Modnar/random.py
ctfs/WorldWide/2024/crypto/Modnar/random.py
"""Random variable generators. bytes ----- uniform bytes (values between 0 and 255) integers -------- uniform within range sequences --------- pick random element pick random sample pick weighted random sample generate random permutation distributions on the real line: ------------------------------ uniform triangular normal (Gaussian) lognormal negative exponential gamma beta pareto Weibull distributions on the circle (angles 0 to 2pi) --------------------------------------------- circular uniform von Mises General notes on the underlying Mersenne Twister core generator: * The period is 2**19937-1. * It is one of the most extensively tested generators in existence. * The random() method is implemented in C, executes in a single Python step, and is, therefore, threadsafe. """ # Translated by Guido van Rossum from C source provided by # Adrian Baddeley. Adapted by Raymond Hettinger for use with # the Mersenne Twister and os.urandom() core generators. from warnings import warn as _warn from math import log as _log, exp as _exp, pi as _pi, e as _e, ceil as _ceil from math import sqrt as _sqrt, acos as _acos, cos as _cos, sin as _sin from math import tau as TWOPI, floor as _floor, isfinite as _isfinite from os import urandom as _urandom from _collections_abc import Set as _Set, Sequence as _Sequence from operator import index as _index from itertools import accumulate as _accumulate, repeat as _repeat from bisect import bisect as _bisect import os as _os import _random try: # hashlib is pretty heavy to load, try lean internal module first from _sha512 import sha512 as _sha512 except ImportError: # fallback to official implementation from hashlib import sha512 as _sha512 __all__ = [ "Random", "SystemRandom", "betavariate", "choice", "choices", "expovariate", "gammavariate", "gauss", "getrandbits", "getstate", "lognormvariate", "normalvariate", "paretovariate", "randbytes", "randint", "random", "randrange", "sample", "seed", "setstate", "shuffle", "triangular", "uniform", "vonmisesvariate", "weibullvariate", ] NV_MAGICCONST = 4 * _exp(-0.5) / _sqrt(2.0) LOG4 = _log(4.0) SG_MAGICCONST = 1.0 + _log(4.5) BPF = 53 # Number of bits in a float RECIP_BPF = 2 ** -BPF _ONE = 1 class Random(_random.Random): """Random number generator base class used by bound module functions. Used to instantiate instances of Random to get generators that don't share state. Class Random can also be subclassed if you want to use a different basic generator of your own devising: in that case, override the following methods: random(), seed(), getstate(), and setstate(). Optionally, implement a getrandbits() method so that randrange() can cover arbitrarily large ranges. """ VERSION = 3 # used by getstate/setstate def __init__(self, x=None): """Initialize an instance. Optional argument x controls seeding, as for Random.seed(). """ self.seed(x) self.gauss_next = None def seed(self, a=None, version=1): """Initialize internal state from a seed. The only supported seed types are None, int, float, str, bytes, and bytearray. None or no argument seeds from current time or from an operating system specific randomness source if available. If *a* is an int, all bits are used. For version 2 (the default), all of the bits are used if *a* is a str, bytes, or bytearray. For version 1 (provided for reproducing random sequences from older versions of Python), the algorithm for str and bytes generates a narrower range of seeds. """ if version == 1 and isinstance(a, (str, bytes)): a = a.decode('latin-1') if isinstance(a, bytes) else a x = ord(a[0]) << 7 if a else 0 for c in map(ord, a): x = ((1000003 * x) ^ c) & 0xFFFFFFFFFFFFFFFF x ^= len(a) a = -2 if x == -1 else x elif version == 2 and isinstance(a, (str, bytes, bytearray)): if isinstance(a, str): a = a.encode() a = int.from_bytes(a + _sha512(a).digest()) elif not isinstance(a, (type(None), int, float, str, bytes, bytearray)): raise TypeError('The only supported seed types are: None,\n' 'int, float, str, bytes, and bytearray.') super().seed(a) self.gauss_next = None def getstate(self): """Return internal state; can be passed to setstate() later.""" return self.VERSION, super().getstate(), self.gauss_next def setstate(self, state): """Restore internal state from object returned by getstate().""" version = state[0] if version == 3: version, internalstate, self.gauss_next = state super().setstate(internalstate) elif version == 2: version, internalstate, self.gauss_next = state # In version 2, the state was saved as signed ints, which causes # inconsistencies between 32/64-bit systems. The state is # really unsigned 32-bit ints, so we convert negative ints from # version 2 to positive longs for version 3. try: internalstate = tuple(x % (2 ** 32) for x in internalstate) except ValueError as e: raise TypeError from e super().setstate(internalstate) else: raise ValueError("state with version %s passed to " "Random.setstate() of version %s" % (version, self.VERSION)) ## ------------------------------------------------------- ## ---- Methods below this point do not need to be overridden or extended ## ---- when subclassing for the purpose of using a different core generator. ## -------------------- pickle support ------------------- # Issue 17489: Since __reduce__ was defined to fix #759889 this is no # longer called; we leave it here because it has been here since random was # rewritten back in 2001 and why risk breaking something. def __getstate__(self): # for pickle return self.getstate() def __setstate__(self, state): # for pickle self.setstate(state) def __reduce__(self): return self.__class__, (), self.getstate() ## ---- internal support method for evenly distributed integers ---- def __init_subclass__(cls, /, **kwargs): """Control how subclasses generate random integers. The algorithm a subclass can use depends on the random() and/or getrandbits() implementation available to it and determines whether it can generate random integers from arbitrarily large ranges. """ for c in cls.__mro__: if '_randbelow' in c.__dict__: # just inherit it break if 'getrandbits' in c.__dict__: cls._randbelow = cls._randbelow_with_getrandbits break if 'random' in c.__dict__: cls._randbelow = cls._randbelow_without_getrandbits break def _randbelow_with_getrandbits(self, n): "Return a random int in the range [0,n). Defined for n > 0." getrandbits = self.getrandbits k = n.bit_length() # don't use (n-1) here because n can be 1 r = getrandbits(k) # 0 <= r < 2**k while r >= n: r = getrandbits(k) return r def _randbelow_without_getrandbits(self, n, maxsize=1<<BPF): """Return a random int in the range [0,n). Defined for n > 0. The implementation does not use getrandbits, but only random. """ random = self.random if n >= maxsize: _warn("Underlying random() generator does not supply \n" "enough bits to choose from a population range this large.\n" "To remove the range limitation, add a getrandbits() method.") return _floor(random() * n) rem = maxsize % n limit = (maxsize - rem) / maxsize # int(limit * maxsize) % n == 0 r = random() while r >= limit: r = random() return _floor(r * maxsize) % n _randbelow = _randbelow_with_getrandbits ## -------------------------------------------------------- ## ---- Methods below this point generate custom distributions ## ---- based on the methods defined above. They do not ## ---- directly touch the underlying generator and only ## ---- access randomness through the methods: random(), ## ---- getrandbits(), or _randbelow(). ## -------------------- bytes methods --------------------- def randbytes(self, n): """Generate n random bytes.""" return self.getrandbits(n * 8).to_bytes(n, 'little') ## -------------------- integer methods ------------------- def randrange(self, start, stop=None, step=_ONE): """Choose a random item from range(stop) or range(start, stop[, step]). Roughly equivalent to ``choice(range(start, stop, step))`` but supports arbitrarily large ranges and is optimized for common cases. """ # This code is a bit messy to make it fast for the # common case while still doing adequate error checking. try: istart = _index(start) except TypeError: istart = int(start) if istart != start: _warn('randrange() will raise TypeError in the future', DeprecationWarning, 2) raise ValueError("non-integer arg 1 for randrange()") _warn('non-integer arguments to randrange() have been deprecated ' 'since Python 3.10 and will be removed in a subsequent ' 'version', DeprecationWarning, 2) if stop is None: # We don't check for "step != 1" because it hasn't been # type checked and converted to an integer yet. if step is not _ONE: raise TypeError('Missing a non-None stop argument') if istart > 0: return self._randbelow(istart) raise ValueError("empty range for randrange()") # stop argument supplied. try: istop = _index(stop) except TypeError: istop = int(stop) if istop != stop: _warn('randrange() will raise TypeError in the future', DeprecationWarning, 2) raise ValueError("non-integer stop for randrange()") _warn('non-integer arguments to randrange() have been deprecated ' 'since Python 3.10 and will be removed in a subsequent ' 'version', DeprecationWarning, 2) width = istop - istart try: istep = _index(step) except TypeError: istep = int(step) if istep != step: _warn('randrange() will raise TypeError in the future', DeprecationWarning, 2) raise ValueError("non-integer step for randrange()") _warn('non-integer arguments to randrange() have been deprecated ' 'since Python 3.10 and will be removed in a subsequent ' 'version', DeprecationWarning, 2) # Fast path. if istep == 1: if width > 0: return istart + self._randbelow(width) raise ValueError("empty range for randrange() (%d, %d, %d)" % (istart, istop, width)) # Non-unit step argument supplied. if istep > 0: n = (width + istep - 1) // istep elif istep < 0: n = (width + istep + 1) // istep else: raise ValueError("zero step for randrange()") if n <= 0: raise ValueError("empty range for randrange()") return istart + istep * self._randbelow(n) def randint(self, a, b): """Return random integer in range [a, b], including both end points. """ return self.randrange(a, b+1) ## -------------------- sequence methods ------------------- def choice(self, seq): """Choose a random element from a non-empty sequence.""" if not seq: raise IndexError('Cannot choose from an empty sequence') return seq[self._randbelow(len(seq))] def shuffle(self, x): """Shuffle list x in place, and return None.""" randbelow = self._randbelow for i in reversed(range(1, len(x))): # pick an element in x[:i+1] with which to exchange x[i] j = randbelow(i + 1) x[i], x[j] = x[j], x[i] def sample(self, population, k, *, counts=None): """Chooses k unique random elements from a population sequence. Returns a new list containing elements from the population while leaving the original population unchanged. The resulting list is in selection order so that all sub-slices will also be valid random samples. This allows raffle winners (the sample) to be partitioned into grand prize and second place winners (the subslices). Members of the population need not be hashable or unique. If the population contains repeats, then each occurrence is a possible selection in the sample. Repeated elements can be specified one at a time or with the optional counts parameter. For example: sample(['red', 'blue'], counts=[4, 2], k=5) is equivalent to: sample(['red', 'red', 'red', 'red', 'blue', 'blue'], k=5) To choose a sample from a range of integers, use range() for the population argument. This is especially fast and space efficient for sampling from a large population: sample(range(10000000), 60) """ # Sampling without replacement entails tracking either potential # selections (the pool) in a list or previous selections in a set. # When the number of selections is small compared to the # population, then tracking selections is efficient, requiring # only a small set and an occasional reselection. For # a larger number of selections, the pool tracking method is # preferred since the list takes less space than the # set and it doesn't suffer from frequent reselections. # The number of calls to _randbelow() is kept at or near k, the # theoretical minimum. This is important because running time # is dominated by _randbelow() and because it extracts the # least entropy from the underlying random number generators. # Memory requirements are kept to the smaller of a k-length # set or an n-length list. # There are other sampling algorithms that do not require # auxiliary memory, but they were rejected because they made # too many calls to _randbelow(), making them slower and # causing them to eat more entropy than necessary. if not isinstance(population, _Sequence): raise TypeError("Population must be a sequence. " "For dicts or sets, use sorted(d).") n = len(population) if counts is not None: cum_counts = list(_accumulate(counts)) if len(cum_counts) != n: raise ValueError('The number of counts does not match the population') total = cum_counts.pop() if not isinstance(total, int): raise TypeError('Counts must be integers') if total <= 0: raise ValueError('Total of counts must be greater than zero') selections = self.sample(range(total), k=k) bisect = _bisect return [population[bisect(cum_counts, s)] for s in selections] randbelow = self._randbelow if not 0 <= k <= n: raise ValueError("Sample larger than population or is negative") result = [None] * k setsize = 21 # size of a small set minus size of an empty list if k > 5: setsize += 4 ** _ceil(_log(k * 3, 4)) # table size for big sets if n <= setsize: # An n-length list is smaller than a k-length set. # Invariant: non-selected at pool[0 : n-i] pool = list(population) for i in range(k): j = randbelow(n - i) result[i] = pool[j] pool[j] = pool[n - i - 1] # move non-selected item into vacancy else: selected = set() selected_add = selected.add for i in range(k): j = randbelow(n) while j in selected: j = randbelow(n) selected_add(j) result[i] = population[j] return result def choices(self, population, weights=None, *, cum_weights=None, k=1): """Return a k sized list of population elements chosen with replacement. If the relative weights or cumulative weights are not specified, the selections are made with equal probability. """ random = self.random n = len(population) if cum_weights is None: if weights is None: floor = _floor n += 0.0 # convert to float for a small speed improvement return [population[floor(random() * n)] for i in _repeat(None, k)] try: cum_weights = list(_accumulate(weights)) except TypeError: if not isinstance(weights, int): raise k = weights raise TypeError( f'The number of choices must be a keyword argument: {k=}' ) from None elif weights is not None: raise TypeError('Cannot specify both weights and cumulative weights') if len(cum_weights) != n: raise ValueError('The number of weights does not match the population') total = cum_weights[-1] + 0.0 # convert to float if total <= 0.0: raise ValueError('Total of weights must be greater than zero') if not _isfinite(total): raise ValueError('Total of weights must be finite') bisect = _bisect hi = n - 1 return [population[bisect(cum_weights, random() * total, 0, hi)] for i in _repeat(None, k)] ## -------------------- real-valued distributions ------------------- def uniform(self, a, b): "Get a random number in the range [a, b) or [a, b] depending on rounding." return a + (b - a) * self.random() def triangular(self, low=0.0, high=1.0, mode=None): """Triangular distribution. Continuous distribution bounded by given lower and upper limits, and having a given mode value in-between. http://en.wikipedia.org/wiki/Triangular_distribution """ u = self.random() try: c = 0.5 if mode is None else (mode - low) / (high - low) except ZeroDivisionError: return low if u > c: u = 1.0 - u c = 1.0 - c low, high = high, low return low + (high - low) * _sqrt(u * c) def normalvariate(self, mu=0.0, sigma=1.0): """Normal distribution. mu is the mean, and sigma is the standard deviation. """ # Uses Kinderman and Monahan method. Reference: Kinderman, # A.J. and Monahan, J.F., "Computer generation of random # variables using the ratio of uniform deviates", ACM Trans # Math Software, 3, (1977), pp257-260. random = self.random while True: u1 = random() u2 = 1.0 - random() z = NV_MAGICCONST * (u1 - 0.5) / u2 zz = z * z / 4.0 if zz <= -_log(u2): break return mu + z * sigma def gauss(self, mu=0.0, sigma=1.0): """Gaussian distribution. mu is the mean, and sigma is the standard deviation. This is slightly faster than the normalvariate() function. Not thread-safe without a lock around calls. """ # When x and y are two variables from [0, 1), uniformly # distributed, then # # cos(2*pi*x)*sqrt(-2*log(1-y)) # sin(2*pi*x)*sqrt(-2*log(1-y)) # # are two *independent* variables with normal distribution # (mu = 0, sigma = 1). # (Lambert Meertens) # (corrected version; bug discovered by Mike Miller, fixed by LM) # Multithreading note: When two threads call this function # simultaneously, it is possible that they will receive the # same return value. The window is very small though. To # avoid this, you have to use a lock around all calls. (I # didn't want to slow this down in the serial case by using a # lock here.) random = self.random z = self.gauss_next self.gauss_next = None if z is None: x2pi = random() * TWOPI g2rad = _sqrt(-2.0 * _log(1.0 - random())) z = _cos(x2pi) * g2rad self.gauss_next = _sin(x2pi) * g2rad return mu + z * sigma def lognormvariate(self, mu, sigma): """Log normal distribution. If you take the natural logarithm of this distribution, you'll get a normal distribution with mean mu and standard deviation sigma. mu can have any value, and sigma must be greater than zero. """ return _exp(self.normalvariate(mu, sigma)) def expovariate(self, lambd): """Exponential distribution. lambd is 1.0 divided by the desired mean. It should be nonzero. (The parameter would be called "lambda", but that is a reserved word in Python.) Returned values range from 0 to positive infinity if lambd is positive, and from negative infinity to 0 if lambd is negative. """ # lambd: rate lambd = 1/mean # ('lambda' is a Python reserved word) # we use 1-random() instead of random() to preclude the # possibility of taking the log of zero. return -_log(1.0 - self.random()) / lambd def vonmisesvariate(self, mu, kappa): """Circular data distribution. mu is the mean angle, expressed in radians between 0 and 2*pi, and kappa is the concentration parameter, which must be greater than or equal to zero. If kappa is equal to zero, this distribution reduces to a uniform random angle over the range 0 to 2*pi. """ # Based upon an algorithm published in: Fisher, N.I., # "Statistical Analysis of Circular Data", Cambridge # University Press, 1993. # Thanks to Magnus Kessler for a correction to the # implementation of step 4. random = self.random if kappa <= 1e-6: return TWOPI * random() s = 0.5 / kappa r = s + _sqrt(1.0 + s * s) while True: u1 = random() z = _cos(_pi * u1) d = z / (r + z) u2 = random() if u2 < 1.0 - d * d or u2 <= (1.0 - d) * _exp(d): break q = 1.0 / r f = (q + z) / (1.0 + q * z) u3 = random() if u3 > 0.5: theta = (mu + _acos(f)) % TWOPI else: theta = (mu - _acos(f)) % TWOPI return theta def gammavariate(self, alpha, beta): """Gamma distribution. Not the gamma function! Conditions on the parameters are alpha > 0 and beta > 0. The probability distribution function is: x ** (alpha - 1) * math.exp(-x / beta) pdf(x) = -------------------------------------- math.gamma(alpha) * beta ** alpha """ # alpha > 0, beta > 0, mean is alpha*beta, variance is alpha*beta**2 # Warning: a few older sources define the gamma distribution in terms # of alpha > -1.0 if alpha <= 0.0 or beta <= 0.0: raise ValueError('gammavariate: alpha and beta must be > 0.0') random = self.random if alpha > 1.0: # Uses R.C.H. Cheng, "The generation of Gamma # variables with non-integral shape parameters", # Applied Statistics, (1977), 26, No. 1, p71-74 ainv = _sqrt(2.0 * alpha - 1.0) bbb = alpha - LOG4 ccc = alpha + ainv while True: u1 = random() if not 1e-7 < u1 < 0.9999999: continue u2 = 1.0 - random() v = _log(u1 / (1.0 - u1)) / ainv x = alpha * _exp(v) z = u1 * u1 * u2 r = bbb + ccc * v - x if r + SG_MAGICCONST - 4.5 * z >= 0.0 or r >= _log(z): return x * beta elif alpha == 1.0: # expovariate(1/beta) return -_log(1.0 - random()) * beta else: # alpha is between 0 and 1 (exclusive) # Uses ALGORITHM GS of Statistical Computing - Kennedy & Gentle while True: u = random() b = (_e + alpha) / _e p = b * u if p <= 1.0: x = p ** (1.0 / alpha) else: x = -_log((b - p) / alpha) u1 = random() if p > 1.0: if u1 <= x ** (alpha - 1.0): break elif u1 <= _exp(-x): break return x * beta def betavariate(self, alpha, beta): """Beta distribution. Conditions on the parameters are alpha > 0 and beta > 0. Returned values range between 0 and 1. """ ## See ## http://mail.python.org/pipermail/python-bugs-list/2001-January/003752.html ## for Ivan Frohne's insightful analysis of why the original implementation: ## ## def betavariate(self, alpha, beta): ## # Discrete Event Simulation in C, pp 87-88. ## ## y = self.expovariate(alpha) ## z = self.expovariate(1.0/beta) ## return z/(y+z) ## ## was dead wrong, and how it probably got that way. # This version due to Janne Sinkkonen, and matches all the std # texts (e.g., Knuth Vol 2 Ed 3 pg 134 "the beta distribution"). y = self.gammavariate(alpha, 1.0) if y: return y / (y + self.gammavariate(beta, 1.0)) return 0.0 def paretovariate(self, alpha): """Pareto distribution. alpha is the shape parameter.""" # Jain, pg. 495 u = 1.0 - self.random() return u ** (-1.0 / alpha) def weibullvariate(self, alpha, beta): """Weibull distribution. alpha is the scale parameter and beta is the shape parameter. """ # Jain, pg. 499; bug fix courtesy Bill Arms u = 1.0 - self.random() return alpha * (-_log(u)) ** (1.0 / beta) ## ------------------------------------------------------------------ ## --------------- Operating System Random Source ------------------ class SystemRandom(Random): """Alternate random number generator using sources provided by the operating system (such as /dev/urandom on Unix or CryptGenRandom on Windows). Not available on all systems (see os.urandom() for details). """ def random(self): """Get the next random number in the range [0.0, 1.0).""" return (int.from_bytes(_urandom(7)) >> 3) * RECIP_BPF def getrandbits(self, k): """getrandbits(k) -> x. Generates an int with k random bits.""" if k < 0: raise ValueError('number of bits must be non-negative') numbytes = (k + 7) // 8 # bits / 8 and rounded up x = int.from_bytes(_urandom(numbytes)) return x >> (numbytes * 8 - k) # trim excess bits def randbytes(self, n): """Generate n random bytes.""" # os.urandom(n) fails with ValueError for n < 0 # and returns an empty bytes string for n == 0. return _urandom(n) def seed(self, *args, **kwds): "Stub method. Not used for a system random number generator." return None def _notimplemented(self, *args, **kwds): "Method should not be called for a system random number generator." raise NotImplementedError('System entropy source does not have state.') getstate = setstate = _notimplemented # ---------------------------------------------------------------------- # Create one instance, seeded from current time, and export its methods # as module-level functions. The functions share state across all uses # (both in the user's code and in the Python libraries), but that's fine # for most programs and is easier for the casual user than making them # instantiate their own Random() instance. _inst = Random() seed = _inst.seed random = _inst.random uniform = _inst.uniform triangular = _inst.triangular randint = _inst.randint choice = _inst.choice randrange = _inst.randrange sample = _inst.sample shuffle = _inst.shuffle choices = _inst.choices normalvariate = _inst.normalvariate lognormvariate = _inst.lognormvariate expovariate = _inst.expovariate vonmisesvariate = _inst.vonmisesvariate gammavariate = _inst.gammavariate gauss = _inst.gauss betavariate = _inst.betavariate paretovariate = _inst.paretovariate weibullvariate = _inst.weibullvariate getstate = _inst.getstate setstate = _inst.setstate getrandbits = _inst.getrandbits randbytes = _inst.randbytes ## ------------------------------------------------------ ## ----------------- test program ----------------------- def _test_generator(n, func, args): from statistics import stdev, fmean as mean from time import perf_counter t0 = perf_counter() data = [func(*args) for i in _repeat(None, n)] t1 = perf_counter() xbar = mean(data) sigma = stdev(data, xbar) low = min(data) high = max(data) print(f'{t1 - t0:.3f} sec, {n} times {func.__name__}') print('avg %g, stddev %g, min %g, max %g\n' % (xbar, sigma, low, high)) def _test(N=2000): _test_generator(N, random, ()) _test_generator(N, normalvariate, (0.0, 1.0)) _test_generator(N, lognormvariate, (0.0, 1.0)) _test_generator(N, vonmisesvariate, (0.0, 1.0)) _test_generator(N, gammavariate, (0.01, 1.0)) _test_generator(N, gammavariate, (0.1, 1.0)) _test_generator(N, gammavariate, (0.1, 2.0)) _test_generator(N, gammavariate, (0.5, 1.0)) _test_generator(N, gammavariate, (0.9, 1.0)) _test_generator(N, gammavariate, (1.0, 1.0)) _test_generator(N, gammavariate, (2.0, 1.0)) _test_generator(N, gammavariate, (20.0, 1.0)) _test_generator(N, gammavariate, (200.0, 1.0)) _test_generator(N, gauss, (0.0, 1.0)) _test_generator(N, betavariate, (3.0, 3.0)) _test_generator(N, triangular, (0.0, 1.0, 1.0 / 3.0)) ## ------------------------------------------------------ ## ------------------ fork support --------------------- if hasattr(_os, "fork"): _os.register_at_fork(after_in_child=_inst.seed) if __name__ == '__main__': _test()
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/WorldWide/2024/crypto/Just_Lattice/chal.py
ctfs/WorldWide/2024/crypto/Just_Lattice/chal.py
import numpy as np from secret import flag def gen(q, n, N, sigma): t = np.random.randint(0, high=q//2, size=n) s = np.concatenate([np.ones(1, dtype=np.int32), t]) A = np.random.randint(0, high=q//2, size=(N, n)) e = np.round(np.random.randn(N) * sigma ** 2).astype(np.int32) % q b = ((np.dot(A, t) + e).reshape(-1, 1)) % q P = np.hstack([b, -A]) return P, s def enc(P, M, q): N = P.shape[0] n = len(M) r = np.random.randint(0, 2, (n, N)) Z = np.zeros((n, P.shape[1]), dtype=np.int32) Z[:, 0] = 1 C = np.zeros((n, P.shape[1]), dtype=np.int32) for i in range(n): C[i] = (np.dot(P.T, r[i]) + (np.floor(q/2) * Z[i] * M[i])) % q return C q = 127 n = 3 N = int(1.1 * n * np.log(q)) sigma = 1.0 P, s = gen(q, n, N, sigma) def prep(s): return np.array([int(b) for char in s for b in f'{ord(char):08b}'], dtype=np.int32) C = enc(P, prep(flag), q) P = P.tolist() C = C.tolist() print(f"{P=}") print(f"{C=}")
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/WorldWide/2024/crypto/Twister/deploy.py
ctfs/WorldWide/2024/crypto/Twister/deploy.py
from dataclasses import dataclass from cmath import exp import secrets import time import os FLAG = os.getenv("FLAG") or "test{flag_for_local_testing}" @dataclass class Wave: a: int b: int def eval(self, x): theta = x / self.a + self.b return ((exp(1j * theta) - exp(-1j * theta)) / 2j).real ALL_WAVES = [Wave(a, b) for a in range(2, 32) for b in range(7)] class MaximTwister: """ Next-generation PRNG with really **complex** nature. More reliable than /dev/random cuz doesn't block ever. """ def __init__(self, state=None): if state is None: state = (1337, [secrets.randbits(1) for _ in ALL_WAVES]) self.point = state[0] self.waves = [wave for wave, mask in zip(ALL_WAVES, state[1]) if mask] def get_randbit(self) -> int: result = 0 for wave in self.waves: # you would never decompose a sum of waves 😈 result += round(wave.eval(self.point)) # especially if you know only the remainder, right? give up result %= 2 self.point += 1 return result def get_randbits(self, k: int) -> int: return int("".join(str(self.get_randbit()) for _ in range(k)), 2) def get_token_bytes(self, k: int) -> bytes: return bytes([self.get_randbits(8) for _ in range(k)]) print("*** BUG DESTROYER ***") print("You encounter: 😈 SEGMENTATION FAULT 😈") opponent_hp = int(time.time()) * 123 days_passed = 0 random = MaximTwister() while True: print( f"🕺 You ({10-days_passed} days till release) -- 😈 SEGMENTATION FAULT ({opponent_hp} lines)" ) print(f"Day {days_passed + 1}. You can:") print("1. Make a fix") print("2. Call a senior") choice = input("> ").strip() if choice == "1": damage = random.get_randbits(32) opponent_hp -= damage if opponent_hp <= 0: print( f"You commited a fix deleting {damage} lines. Miraculously, it worked!" ) break else: print(f"You commited a fix deleting {damage} lines. The bug remained 😿") elif choice == "2": print("You called a senior. It's super effective! The bug is destroyed.") break else: print( f"You spent {random.get_randbits(4)} hours doing whatever {choice} means." ) print("A day has passed. You couldn't fix the bug.") days_passed += 1 if days_passed == 10: print("It's release date! The bug is still there. You're fired.") exit() print("The bug is gone! You got a raise.") print( "In your new office you see a strange door. It is locked. You try to guess the password from the digital lock:" ) password = input("> ") if bytes.fromhex(password) == random.get_token_bytes(16): print("Somehow, you guessed the password! The room opens before you.") print("You see a mysterious text:", FLAG) print( "What could it mean?... You turn around and see your boss right behind you..." ) print("BAD ENDING") else: print("Incorrect. Well, let's get back to work...") print("GOOD ENDING")
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/WorldWide/2025/blockchain/Solidity_Jail_2/JailTalker.py
ctfs/WorldWide/2025/blockchain/Solidity_Jail_2/JailTalker.py
#!/usr/local/bin/python import signal from solcx import compile_standard import os from web3 import Web3 import string import re import requests import sys contr_add = os.environ.get("CONTRACT_ADDDR") rpc_url = os.environ.get("RPC_URL") print("Enter the body of main() (end with three blank lines):") lines = [] empty_count = 0 while True: try: line = input() except EOFError: break if line.strip() == "": empty_count += 1 else: empty_count = 0 if empty_count >= 3: lines = lines[:-2] break lines.append(line) body = "\n".join(f" {l}" for l in lines) if not all(ch in string.printable for ch in body): raise ValueError("Non-printable characters detected in contract.") if len(body) > 25000: raise ValueError("Maximum 25000 characters allowed.") blacklist = [ "call", "store", "load", "revert", "flag", "wwf", "transfer", "address", "this", "ext", "push", "bytes4", "keccak", "block", "tx", "origin", "gas", "fallback", "receive", "selfdestruct", "suicide" ] if any(banned in body for banned in blacklist): raise ValueError(f"Blacklisted string found in contract.") if re.search(r"(\d)\1", body): raise ValueError("Regex check failed.") source = f"""// SPDX-License-Identifier: MIT pragma solidity ^0.8.20; contract Solution {{ function main() external returns (string memory) {{ {body} }} }} """ print("Final contract with inserted main() body:") print(source) compiled = compile_standard( { "language": "Solidity", "sources": {"Solution.sol": {"content": source}}, "settings": { "outputSelection": { "*": { "*": ["evm.bytecode.object"] } } }, }, solc_version="0.8.20", ) bytecode_hex = "0x" + compiled["contracts"]["Solution.sol"]["Solution"]["evm"]["bytecode"]["object"] salt_hex = "0x" + os.urandom(32).hex() web3 = Web3(Web3.HTTPProvider(rpc_url)) contr_abi = [{"inputs":[],"name":"flag","outputs":[{"internalType":"string","name":"","type":"string"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"bytes","name":"_bytecode","type":"bytes"},{"internalType":"bytes32","name":"_salt","type":"bytes32"}],"name":"run","outputs":[{"internalType":"bool","name":"success","type":"bool"},{"internalType":"bytes","name":"result","type":"bytes"}],"stateMutability":"nonpayable","type":"function"}] contr = web3.eth.contract(address=contr_add, abi=contr_abi) bytecode_bytes = Web3.to_bytes(hexstr=bytecode_hex) salt_bytes = Web3.to_bytes(hexstr=salt_hex) print(contr.functions.run(bytecode_bytes, salt_bytes).call())
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/WorldWide/2025/blockchain/Solidity_Jail_1/jailTalk.py
ctfs/WorldWide/2025/blockchain/Solidity_Jail_1/jailTalk.py
#!/usr/local/bin/python import signal from solcx import compile_standard import os from web3 import Web3 import string import requests from urllib.parse import urlparse contr_add = os.environ.get("CONTRACT_ADDDR") rpc_url = os.environ.get("RPC_URL") try: parsed = urlparse(rpc_url) resp = requests.get(f"{parsed.scheme}://{parsed.netloc}") if resp.text != "ok": print("Contact admins challenge not working...") exit() except Exception as e: print("Contact admins challenge not working...") exit() print("Enter the body of main() (end with three blank lines):") lines = [] empty_count = 0 while True: try: line = input() except EOFError: break if line.strip() == "": empty_count += 1 else: empty_count = 0 if empty_count >= 3: lines = lines[:-2] break lines.append(line) body = "\n".join(f" {l}" for l in lines) if not all(ch in string.printable for ch in body): raise ValueError("Non-printable characters detected in contract.") blacklist = [ "flag", "transfer", "address", "this", "block", "tx", "origin", "gas", "fallback", "receive", "selfdestruct", "suicide" ] if any(banned in body for banned in blacklist): raise ValueError(f"Blacklisted string found in contract.") source = f"""// SPDX-License-Identifier: MIT pragma solidity ^0.8.20; contract Solution {{ function main() external returns (string memory) {{ {body} }} }} """ print("Final contract with inserted main() body:") print(source) compiled = compile_standard( { "language": "Solidity", "sources": {"Solution.sol": {"content": source}}, "settings": { "outputSelection": { "*": { "*": ["evm.bytecode.object"] } } }, }, solc_version="0.8.20", ) bytecode_hex = "0x" + compiled["contracts"]["Solution.sol"]["Solution"]["evm"]["bytecode"]["object"] salt_hex = "0x" + os.urandom(32).hex() web3 = Web3(Web3.HTTPProvider(rpc_url)) contr_abi = [{"inputs":[],"name":"flag","outputs":[{"internalType":"string","name":"","type":"string"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"bytes","name":"_bytecode","type":"bytes"},{"internalType":"bytes32","name":"_salt","type":"bytes32"}],"name":"run","outputs":[{"internalType":"bool","name":"success","type":"bool"},{"internalType":"bytes","name":"result","type":"bytes"}],"stateMutability":"nonpayable","type":"function"}] contr = web3.eth.contract(address=contr_add, abi=contr_abi) bytecode_bytes = Web3.to_bytes(hexstr=bytecode_hex) salt_bytes = Web3.to_bytes(hexstr=salt_hex) print(contr.functions.run(bytecode_bytes, salt_bytes).call())
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/WorldWide/2025/misc/Non_Functional_Calculator_2/jail.py
ctfs/WorldWide/2025/misc/Non_Functional_Calculator_2/jail.py
#!/usr/local/bin/python values = {} whitelist_chars = set("abcdefghijklmnopqrstuvwxyz0123456789.,()") blacklist_words = { "exe", "import", "eval", "os", "sys", "run", "sub", "class", "process", "cat", "repr", "base", "echo", "open", "file", "sh", "item", "call", "spawn", "output", "status", "load", "module", "reduce", "builtins", "locals", "globals", } variable_name = "" variable_value = "" def calculate(equation): global variable_name, variable_value if not len(equation) != 0: print("There is no equation for me to run... (╥﹏╥)") exit() equation = equation.encode().decode("ascii", errors="ignore") if "=" in equation: value_name, equation = equation.split("=", 1) if not (len(value_name) == 1 and value_name in whitelist_chars): print("Bad characters detected! (-`д´-)") exit() equation = equation.strip() else: value_name = "" if not set(equation).issubset(whitelist_chars): print("Non whitelisted characters in equation (╯°□°)╯︵ ┻━┻") exit() for i in blacklist_words: if i in equation.lower(): print("Blacklisted words in equation (╯°□°)╯︵ ┻━┻") exit() equation = equation.replace(variable_name, variable_value) try: result = eval(equation, {"__builtins__": None}) except: print("Invalid equation (´;ω;`)") exit() if value_name: variable_name = str(value_name.strip()) variable_value = str(result) print(f"Saved {value_name} = {result}") else: print(f"Result: {result}") calculate(input("Equation: ")) calculate("x")
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/WorldWide/2025/misc/Non_Functional_Calculator/jail.py
ctfs/WorldWide/2025/misc/Non_Functional_Calculator/jail.py
#!/usr/local/bin/python values = {} whitelist_chars = set("abcdefghijklmnopqrstuvwxyz0123456789.,()") blacklist_words = { "exe", "import", "eval", "os", "sys", "run", "sub", "class", "process", "cat", "repr", "base", "echo", "open", "file", "sh", "item", "call", "spawn", "output", "status", "load", "module", "reduce", "builtins", "locals", "globals", } variable_name = "" variable_value = "" def calculate(equation): global variable_name, variable_value if not len(equation) != 0: print("There is no equation for me to run... (╥﹏╥)") exit() equation = equation.encode().decode("ascii", errors="ignore") if "=" in equation: value_name, equation = equation.split("=", 1) if not (len(value_name) == 1 and value_name in whitelist_chars): print("Bad characters detected! (-`д´-)") exit() equation = equation.strip() else: value_name = "" if not set(equation).issubset(whitelist_chars): print("Non whitelisted characters in equation (╯°□°)╯︵ ┻━┻") exit() for i in blacklist_words: if i in equation.lower(): print("Blacklisted words in equation (╯°□°)╯︵ ┻━┻") exit() equation = equation.replace(variable_name, variable_value) try: result = eval(equation, {"__builtins__": None}) except: print("Invalid equation (´;ω;`)") exit() if value_name: variable_name = str(value_name.strip()) variable_value = str(result) print(f"Saved {value_name} = {result}") else: print(f"Result: {result}") for _ in range(2): calculate(input("Equation: "))
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/WorldWide/2025/misc/Ouroboros/chall.py
ctfs/WorldWide/2025/misc/Ouroboros/chall.py
import os import random import string import sys import tempfile import hashlib import subprocess import shutil BASE = os.path.join(tempfile.gettempdir(), 'sandbox') sys.stdout.write('''\x1b[31;1m ⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⢀⣀⣀⣀⣀⣀⣀⣄⣀⠀⠀⠀⠀⠀⠀⠀ ⠀⠀⠀⠀⠀⠀⠀⠀⢀⣠⣴⡶⢿⣟⡛⣿⢉⣿⠛⢿⣯⡈⠙⣿⣦⡀⠀⠀⠀⠀ ⠀⠀⠀⠀⠀⠀⣠⡾⠻⣧⣬⣿⣿⣿⣿⣿⡟⠉⣠⣾⣿⠿⠿⠿⢿⣿⣦⠀⠀⠀ ⠀⠀⠀⠀⣠⣾⡋⣻⣾⣿⣿⣿⠿⠟⠛⠛⠛⠀⢻⣿⡇⢀⣴⡶⡄⠈⠛⠀⠀⠀ ⠀⠀⠀⣸⣿⣉⣿⣿⣿⡿⠋⠀⠀⠀⠀⠀⠀⠀⠈⢿⣇⠈⢿⣤⡿⣦⠀⠀⠀⠀ ⠀⠀⢰⣿⣉⣿⣿⣿⠏⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠙⠦⠀⢻⣦⠾⣆⠀⠀⠀ ⠀⠀⣾⣏⣿⣿⣿⡟⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠈⣿⡶⢾⡀⠀⠀ ⠀⠀⣿⠉⣿⣿⣿⡇⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⣿⣧⣼⡇⠀⠀ ⠀⠀⣿⡛⣿⣿⣿⡇⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⢀⣿⣧⣼⡇⠀⠀ ⠀⠀⠸⡿⢻⣿⣿⣿⡄⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⢀⣼⣿⣥⣽⠁⠀⠀ ⠀⠀⠀⢻⡟⢙⣿⣿⣿⣦⡀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⣠⣾⣿⣧⣸⡏⠀⠀⠀ ⠀⠀⠀⠀⠻⣿⡋⣻⣿⣿⣿⣦⣤⣀⣀⣀⣀⣀⣠⣴⣿⣿⢿⣥⣼⠟⠀⠀⠀⠀ ⠀⠀⠀⠀⠀⠈⠻⣯⣤⣿⠻⣿⣿⣿⣿⣿⣿⣿⣿⣿⠛⣷⣴⡿⠋⠀⠀⠀⠀⠀ ⠀⠀⠀⠀⠀⠀⠀⠈⠙⠛⠾⣧⣼⣟⣉⣿⣉⣻⣧⡿⠟⠋⠁⠀⠀⠀⠀⠀⠀⠀ ⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠉⠉⠉⠉⠁⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀ \x1b[0m''') def prompt_code(): sys.stdout.write('Welcome to the ouroboros challenge, give me your code: (empty line to end)\n') sys.stdout.flush() code = "" w = input() while w: code += w + '\n' w = input() return code def run_code(code, stdin): if not code.strip(): sys.stderr.write('Your code was so short it couldn\'t find its own tail.\n') sys.stdout.flush() return if len(code) > 99999: sys.stderr.write('Your code was so long it couldn\'t find its own tail.\n') sys.stdout.flush() return h = hashlib.sha256(code.encode()).hexdigest() jobdir = os.path.join(BASE, h) os.makedirs(jobdir, exist_ok=True) sandbox_root = os.path.join(jobdir, 'root') os.makedirs(sandbox_root, exist_ok=True) src_path = os.path.join(jobdir, 'main.c') with open(src_path, 'w') as f: f.write(code) bin_path = os.path.join(sandbox_root, 'main') proc = subprocess.run([ 'gcc', '-O0', '-std=c99', '-fno-common', '-pipe', '-static', '-nostdlib', '-o', bin_path, src_path, ], capture_output=True) os.remove(src_path) if proc.returncode != 0: sys.stdout.write('Your code was so bad it couldn\'t find its own tail.\n') sys.stdout.flush() print(proc.stderr.decode(), file=sys.stderr) shutil.rmtree(jobdir) return nsjail_cmd = [ "nsjail", "--mode", "o", "--user", "99999", "--group", "99999", "--disable_proc", "--disable_clone_newnet", "--disable_clone_newipc", "--disable_clone_newuts", "--disable_clone_newpid", "--rlimit_as", "64", "--rlimit_cpu", "1", "--rlimit_fsize", "1", "--rlimit_nofile", "1", "--rlimit_nproc", "1", "--chroot", sandbox_root, "--bindmount_ro", f"{sandbox_root}:/", "--seccomp_string", "ALLOW { read, write, close, execve, exit_group } DEFAULT KILL_PROCESS", "--", "/main", ] proc = subprocess.run( nsjail_cmd, input=stdin.encode(), capture_output=True, timeout=1, ) out = proc.stdout.decode().strip() shutil.rmtree(jobdir) if proc.returncode != 0: sys.stdout.write('Your code was so bad it died.\n') sys.stdout.flush() return return out def _reverse(): s = ''.join(random.choices(string.ascii_lowercase, k=random.randint(3, 10))) return s, s[::-1] def _sum(): nums = [random.randint(0, 20) for _ in range(random.randint(3, 7))] return f'{len(nums)} {" ".join(map(str, nums))}', sum(nums) def _is_prime(): n = random.randint(2, 100) prime = n > 1 and all(n % i for i in range(2, int(n**0.5) + 1)) return n, prime def _fibonacci(): n = random.randint(1, 15) a, b = 0, 1 for _ in range(n - 1): a, b = b, a + b return n, b def _caesar(): shift = random.randint(1, 25) text = ''.join(random.choices(string.ascii_lowercase, k=random.randint(5, 12))) encoded = ''.join( chr((ord(c) - 97 + shift) % 26 + 97) if 'a' <= c <= 'z' else c for c in text ) return f'{shift} {text}', encoded def task(): fn = random.choice([_reverse, _sum, _is_prime, _fibonacci, _caesar]) return fn.__name__[1:], *fn() def main(): original = code = prompt_code() tasks = [task() for _ in range(69)] code = run_code(code, tasks[0][0]) if code is None: return for i, (_, input_data, expected_output) in enumerate(tasks): sys.stdout.write(f'task {i+1}/{len(tasks)}\n') sys.stdout.flush() out = run_code(code, str(input_data) + '\n'+(tasks[i+1][0] if i + 1 < len(tasks) else '')) if out is None: return ans = out[:out.find('\n')] if '\n' in out else out code = out[out.find('\n')+1:] if '\n' in out else '' if ans != str(expected_output): sys.stdout.write('Your code was so bad it couldn\'t find its own tail.\n') sys.stdout.flush() return if original.strip() != code.strip(): sys.stdout.write('Your code was so bad it couldn\'t find its own tail.\n') print(code) print("\n\n") print(original) return else: sys.stdout.write('Your code was a true ouroboros!\n') sys.stdout.write(os.environ.get('FLAG', 'flag{this_is_a_fake_flag}') + '\n') sys.stdout.flush() 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/WorldWide/2025/misc/bf_jail/chall.py
ctfs/WorldWide/2025/misc/bf_jail/chall.py
#!/usr/bin/env python3 import sys def bf(code): output = "" s = [] matches = {} tape = [0] * 1000000 for i, j in enumerate(code): if j == "[": s.append(i) if j == "]": m = s.pop() matches[m] = i matches[i] = m cp = 0 p = 0 while cp < len(code): if code[cp] == "+": tape[p] = (tape[p] + 1) % 256 if code[cp] == "-": tape[p] = (tape[p] - 1) % 256 if code[cp] == ",": c = sys.stdin.read(1) tape[p] = (ord(c) if c else 0) % 256 if code[cp] == ".": output += chr(tape[p]) if code[cp] == "<": p -= 1 if code[cp] == ">": p += 1 if code[cp] == "[": if not tape[p]: cp = matches[cp] if code[cp] == "]": if tape[p]: cp = matches[cp] cp += 1 return output if __name__ == "__main__": code = input("> ") if len(code) > 200: print("200 chars max") sys.exit(0) if not all(c in set("+-<>[],.") for c in code): print("nope") exit(0) code = bf(code) exec(code)
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/WorldWide/2025/crypto/Cheops/server.py
ctfs/WorldWide/2025/crypto/Cheops/server.py
from hashlib import shake_256 import os from typing import Callable def xor(a, b): assert len(a) == len(b) return bytes([x ^ y for x, y in zip(a, b)]) def rotr(a, n): a = int.from_bytes(a, "big") a = ((a >> n) | (a << (32 - n))) & 0xFFFFFFFF a = a.to_bytes(4, "big") return a ROTATION_SCHEDULE = [16, 16, 8, 8, 16, 16, 24, 24] class Khufu: def __init__(self, key: bytes, n_rounds: int = 16): # modification using 16 byte key assert len(key) == 16 self.auxkeys = [key[:8], key[8:]] assert n_rounds % 8 == 0 self.n_rounds = n_rounds self.n_octets = self.n_rounds // 8 self.sboxes = self._generate_sboxes(key) def _generate_sboxes(self, key: bytes) -> "list[list[bytes]]": material = shake_256(key).digest(256 * 4 * self.n_octets) material_index = 0 def next_material() -> int: nonlocal material_index material_index += 1 return material[material_index - 1] return [Khufu._generate_sbox(next_material) for _ in range(self.n_octets)] @staticmethod def _generate_sbox(next_material: Callable[[], int]) -> "list[bytes]": sbox = [bytearray([i] * 4) for i in range(256)] for col in range(4): for i in range(256 - 1): j = i + next_material() % (256 - i) sbox[i][col], sbox[j][col] = sbox[j][col], sbox[i][col] sbox = [bytes(b) for b in sbox] return sbox def encrypt_block(self, block: bytes) -> bytes: assert len(block) == 8 block = xor(block, self.auxkeys[0]) left, right = block[:4], block[4:] for octet in range(self.n_octets): sbox = self.sboxes[octet] for i in range(8): left = xor(left, sbox[right[-1]]) right = rotr(right, ROTATION_SCHEDULE[i]) left, right = right, left return xor(left + right, self.auxkeys[1]) def encrypt(self, pt: bytes) -> bytes: padding = 8 - (len(pt) % 8) pt += bytes([padding] * padding) ct = bytearray() for i in range(0, len(pt), 8): block = pt[i : i + 8] ct.extend(self.encrypt_block(block)) ct = bytes(ct) return ct if __name__ == "__main__": khufu = Khufu( os.urandom(16), # I'll go easy on you this time n_rounds=8 ) encrypted_flag = khufu.encrypt(b"wwf{REDACTEDREDACTEDREDACTEDREDACTEDRED}") print("Flag:", encrypted_flag.hex()) for _ in range(123): pt = bytes.fromhex(input("Try my encryption > ")) ct = khufu.encrypt(pt) print("Result:", ct.hex()) print("Enough already.")
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/WorldWide/2025/crypto/Layered_Signatures/chall.py
ctfs/WorldWide/2025/crypto/Layered_Signatures/chall.py
# /usr/bin/env python import sys from Crypto.Util.number import ( getPrime, getRandomInteger, isPrime, bytes_to_long, long_to_bytes, ) from hashlib import sha256 from flag import flag nbits = 1024 # openssl prime -generate -bits 1024 -safe p = 157177458027947738464608587718505170872557537311336022386936190418737852141444802600222526305430833558655717806361264485789209743716195302937247478034883845835496282499162731072456548430299962306072692670825782721923481661135742935447793446928303177027490662275563294516442565718398572361235897805000082380599 # Nobody wants dlog to be so easy assert isPrime(p) assert isPrime((p - 1) // 2) assert p.bit_length() == 1024 q = getPrime(100) print(f"{q=}") s = getRandomInteger(nbits) g = 25 gs = pow(g, s, p) print(f"{gs=}") def weird_schnorr_sign(m, x): k = getRandomInteger(nbits) r = pow(g, k, p) e = bytes_to_long(sha256(long_to_bytes(r) + long_to_bytes(m)).digest()) s = (k + x * e) % ((p - 1) // 2) return [s, e] def weird_schnorr_verify(m, s, e, y): r = pow(g, s, p) * pow(y, -e, p) % p ep = bytes_to_long(sha256(long_to_bytes(r) + long_to_bytes(m)).digest()) return e == ep def nxt(m): return bytes_to_long(sha256(long_to_bytes(m)).digest()) def sign(m, s): ta = [getRandomInteger(100)] * 4 cc = [nxt(m % q)] for i in range(3): cc += [nxt(cc[-1])] sta = (m - sum([pow(g, b, p) * c % p for b, c in zip(ta, cc)])) % q r = getRandomInteger(100) a = (p - 1 - s) * p - (q * r + sta) * (p - 1) assert a * gs * pow(g, a, p) % p == q * r + sta return weird_schnorr_sign(a, s) + [a] + ta def verify(m, sig, gs): s, e, st = sig[0], sig[1], sig[2:] if len(st) < 5: return False if not weird_schnorr_verify(st[0], s, e, gs): return False cc = [nxt(m % q)] for i in range(len(st) - 2): cc += [nxt(cc[-1])] mp = st[0] * gs * pow(g, st[0], p) % p + sum([ pow(g, x, p) * c % p for x, c in zip(st[1:], cc) ]) return mp % q == m % q msg = b"this is just a test so that you trust the algo" sm = sign(bytes_to_long(msg), s) assert verify(bytes_to_long(msg), sm, gs) print(f"{sm=}") leak = bytes_to_long(flag) % q print(f"{leak=}") print("Give me valid signature for flag:") MAX_LINE = 2 ** 14 line = sys.stdin.readline(MAX_LINE + 1) if len(line) > MAX_LINE: print("Do you want to break the server of what?") else: sig = list(map(int, line.split(","))) if verify(bytes_to_long(flag), sig, gs): print(flag.decode()) else: print( "Verification failed!\nHopefully next time you succeed, keep going!" )
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/WorldWide/2025/crypto/IsogenyMaze2/chall.py
ctfs/WorldWide/2025/crypto/IsogenyMaze2/chall.py
from sage.all import EllipticCurve, GF from sage.all_cmdline import x flag = "wwf{?????????????????????????????????????????????????????}" p = 2**51 * 3**37 - 1 F = GF(p**2 , modulus=x**2 +1 , names=('i',)); (i,) = F._first_ngens(1) def H(num, seed=0): j_prev = F(0) j = F(seed) while num: E = EllipticCurve(j = j) ns = [] for m in E(0).division_points(2): ns.append(E.isogeny_codomain(m).j_invariant()) ns = sorted(list(set(ns) - {j} - set(j_prev))) j_prev = j j = ns[num % len(ns)] num //= len(ns) return j import random from Crypto.Util.number import bytes_to_long, long_to_bytes from time import time START = time() rr = random.randbytes(16) xx = bytes_to_long(rr) hx = H(xx) challenge = (xx, hx) print(f'{challenge = }') response = int(input("response: ")) if response == xx: exit() if H(response) != hx: exit() if not all(0x20 <= i <= 0x7e for i in long_to_bytes(response)): exit() if time() - START > 10: exit() print(flag)
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/WorldWide/2025/crypto/LFSR_Hamster/chall.py
ctfs/WorldWide/2025/crypto/LFSR_Hamster/chall.py
from flag import flag import os assert flag[:4] == b"wwf{" and flag[-1:] == b"}" class LFSRHamster: def __init__(self, key): self.state = [int(eb) for b in key for eb in bin(b)[2:].zfill(8)] self.taps = [0, 1, 2, 7] self.filter = [85, 45, 76, 54, 45, 35, 39, 37, 117, 13, 112, 64, 75, 117, 21, 40] for _ in range(128): self.clock() def xorsum(self, l): s = 0 for x in l: s ^= x return s def hamster(self, l): return l[min(sum(l), len(l) - 1)] def clock(self): x = [self.state[i] for i in self.filter] self.state = self.state[1:] + [self.xorsum(self.state[p] for p in self.taps)] return self.hamster(x) def encrypt(self, data): c = [] for p in data: b = 0 for _ in range(8): b = (b << 1) | self.clock() c += [p ^ b] return bytes(c) if __name__ == "__main__": H = LFSRHamster(os.urandom(16)) while True: t = input(">") if t == "flag": print(H.encrypt(flag).hex()) elif t == "enc": p = bytes.fromhex(input(">")) print(H.encrypt(p).hex())
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/WorldWide/2025/crypto/FaultyCurve/chall.py
ctfs/WorldWide/2025/crypto/FaultyCurve/chall.py
def add(P, Q, a, p): if P is None: return Q if Q is None: return P x1, y1 = P x2, y2 = Q if x1 == x2 and (y1 != y2 or y1 == 0): return None if x1 == x2: m = (3 * x1 * x1 + a) * pow(2 * y1, -1, p) % p else: m = (y2 - y1) * pow(x2 - x1, -1, p) % p x3 = (m * m - x1 - x2) % p y3 = (m * (x1 - x3) - y1) % p return (x3, y3) def mul(k, P, a, p): R0 = None R1 = P for bit in bin(k)[2:]: if bit == '0': R1 = add(R0, R1, a, p) R0 = add(R0, R0, a, p) else: R0 = add(R0, R1, a, p) R1 = add(R1, R1, a, p) return R0 flag = int.from_bytes(b"wwf{???????????????????????????}") from secret import p, a, b, G # EllipticCurve(GF(p), [a,b]) in sage gives an error for some reason :sob: # Some error in /src/sage/schemes/elliptic_curves but i'm too nub to figure out why :sob: :sob: Gx = G[0] Qx = mul(flag, G, a, p)[0] print(f'{p = }') print(f'{a = }') print(f'{Gx = }') print(f'{Qx = }') """ p = 3059506932006842768669313045979965122802573567548630439761719809964279577239571933 a = 2448848303492708630919982332575904911263442803797664768836842024937962142592572096 Gx = 3 Qx = 1461547606525901279892022258912247705593987307619875233742411837094451720970084133 """
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/WorldWide/2025/beginner/Evil_Snek/jail.py
ctfs/WorldWide/2025/beginner/Evil_Snek/jail.py
#!/usr/bin/python3 def blacklist(cmd): if cmd.isascii() == False: return True bad_cmds = ['"', "'", "print", "_", ".", "import", "os", "lambda", "system", "(", ")", "getattr", "setattr", "globals", "builtins", "input", "compile", "eval", "exec", "open", "read"] for i in bad_cmds: if i in cmd: return True return False while True: inp = input("> ") if not blacklist(inp): try: exec(inp) except Exception as e: print("snek says: Error!") exit(0) else: print("snek says: Blacklisted!") exit(0)
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/WorldWide/2025/beginner/Shuffle/chall.py
ctfs/WorldWide/2025/beginner/Shuffle/chall.py
from hashlib import sha256 import os from random import shuffle class Cipher: def __init__(self): self.state = [i for i in range(10000)] shuffle(self.state) def key(self): shuffled = [] for i in range(5000): shuffled.append(self.state[i]) shuffled.append(self.state[5000+i]) self.state = shuffled return sha256((':'.join(map(str,self.state))).encode()).digest()[0] def encrypt(self, data): return bytes([data[i] ^ self.key() for i in range(len(data))]) FLAG = os.environ['FLAG'] if 'FLAG' in os.environ else 'wwctf{example_flag}' cipher = Cipher() print("Welcome to my encryption service! Here's a demo!") print(cipher.encrypt(FLAG.encode()).hex()) try: for i in range(10): text = bytes.fromhex(input(f"Input {i+1} (hex): ")) print(cipher.encrypt(text).hex()) print("Thank you for using my service!") except Exception:pass except OSError:pass
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/BCACTF/2021/crypto/FNES_3/fnes3.py
ctfs/BCACTF/2021/crypto/FNES_3/fnes3.py
#!/usr/bin/env python3 import random import math import time import binascii p = 2**135 + 2**75 + 1 a = 313370 b = 12409401451673702436179381616844751057480 # discriminant is zero g = (313379, 9762458732130899649993884045943131856797, False) def negp(P): x,y,z = P return (-x,y,z) def dubp(P): x,y,z = P if z: return P if y == 0: return (0, 0, True) L = (3 * x * x + a) * pow(2 * y, -1, p) xr = L * L - 2 * x yr = y + L * (xr - x) return (xr % p, -yr % p, False) def addp(P, Q): xp,yp,zp = P xq,yq,zq = Q if zp: return Q if zq: return P if P == negp(Q): return (0, 0, True) if P == Q: return dubp(P) L = (yq - yp) * pow(xq - xp, -1, p) xr = L*L - xp - xq yr = yp + L * (xr - xp) return (xr % p, -yr % p, False) def mulp(P, n): s = bin(n)[3:] r = P for c in s: r = dubp(r) if c == '1': r = addp(r, P) return r print(""" Welcome to the final iteration of FNES. The purpose of FNES is now to generate a shared secret using input from both parties. Here are the steps: 1. Friends A and B both launch FNES 3 2. A and B follow the instructions to generate a shared secret 3. A and B can now pass messages back and forth as normal No more unencryptable characters, but you need to make sure to not make any mistakes or your keystreams can come out of sync. """, flush=True) print("Are you friend A or friend B?", flush=True) l = input(">>> ").strip().upper() if (len(l) > 1): print("You inputted more than one character...", flush=True) elif (l == "A"): print("Please enter a large random number to use as your secret key.", flush=True) aa = int(input(">>> ").strip()) A = mulp(g, aa) if (A[2]): print("That didn't work. Try again with a different key.", flush=True) exit() print(f"Your public key is x={A[0]}, y={A[1]}. \nSend this to B. \nWhat is their public key?", flush=True) B = (int(input(">>> x = ").strip()), int(input(">>> y = ").strip()), False) S = mulp(B, aa) random.seed(S[0] + S[1]) print("Seeding complete.", flush=True) elif (l == "B"): print("Please enter a large random number to use as your secret key.", flush=True) aa = int(input(">>> ").strip()) A = mulp(g, aa) if (A[2]): print("That didn't work. Try again with a different key.", flush=True) exit() print("What is A's public key?", flush=True) B = (int(input(">>> x = ").strip()), int(input(">>> y = ").strip()), False) S = mulp(B, aa) random.seed(S[0] + S[1]) print(f"Your public key is x={A[0]}, y={A[1]}. \nSend this to A.", flush=True) print("Seeding complete.", flush=True) else: print("That's not A or B!", flush=True) exit() while True: print("Would you like to encrypt (E), decrypt (D), or quit (Q)?", flush=True) l = input(">>> ").strip().upper() if (len(l) > 1): print("You inputted more than one character...", flush=True) elif (l == "Q"): print("We hope you enjoyed!", flush=True) exit() elif (l == "E"): print("What would you like to encrypt?", flush=True) I = str.encode(input(">>> ").strip()) print("Here's your message:", flush=True) i = int(binascii.hexlify(I), 16) i ^= random.getrandbits(len(I) * 8) i = hex(i)[2:] if len(i) % 2 == 1: i = '0' + i print(i, flush=True) elif (l == "D"): print("What was the message?", flush=True) I = input(">>> ").strip() try: m = int(I, 16) m ^= random.getrandbits(4 * len(I)) m = str(binascii.unhexlify(hex(m)[2:]))[2:-1] print("Here's the decoded message:", flush=True) print(m, flush=True) except ValueError: print("I can't read that!", flush=True)
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/BCACTF/2021/crypto/FNES_2.5/app.py
ctfs/BCACTF/2021/crypto/FNES_2.5/app.py
from flask import Flask, render_template, request, redirect, make_response from json import loads, dumps import secrets import random import math import time import binascii import sys from Crypto.Cipher import AES from Crypto.Hash import SHA from Crypto.Util.Padding import pad, unpad sys.tracebacklimit = 0 app = Flask(__name__) with open("flag.txt", "r") as file: flag = file.read() with open("key.txt", "r") as f: key = SHA.new(int(f.read().strip()).to_bytes(64, 'big')).digest()[0:16] def encrypt(msg: str): iv = secrets.token_bytes(16) cipher = AES.new(key, AES.MODE_CBC, iv) ct = cipher.encrypt(pad(msg.encode('utf-8'), 16)) iv_enc = AES.new(key[3:] + b'tmp', AES.MODE_ECB).encrypt(iv) return binascii.hexlify(iv_enc + ct).decode("ascii") def decrypt(token: str): ive = binascii.unhexlify(token[:32]) ct = binascii.unhexlify(token[32:]) iv = AES.new(key[3:] + b'tmp', AES.MODE_ECB).decrypt(ive) cipher = AES.new(key, AES.MODE_CBC, iv) return unpad(cipher.decrypt(ct), 16).decode("ascii", errors='ignore') def check_token(token: str): contents = decrypt(token) try: return loads(contents) except: return None @app.route("/") def home(): user = None token = request.cookies.get("enterprise-grade-token") if token is not None: user = check_token(token) if user is None: return render_template("flagmachine.html", message="At Generic Enterprise™, We have Standards™. That's why we require all input Data™ to be strictly valid JSON.", hidebutton=True), 400 return render_template("home.html", username=user["name"], is_admin=user["admin"]) else: return render_template("home.html") @app.route("/login") def login(): contents = dumps({"name": "Enterprise Vampire", "admin": False}) token = encrypt(contents) response = redirect("/", code=303) response.set_cookie("enterprise-grade-token", token) return response @app.route("/logout") def logout(): response = redirect("/", code=303) response.delete_cookie("enterprise-grade-token") return response @app.route("/flagmachine/on") def turn_flagmachine_on(): token = request.cookies.get("enterprise-grade-token") if token is None: return render_template("flagmachine.html", message="At Generic Enterprise™, We Care about Security and Privacy. That's why we require you to Authenticate™ first before modifying any Enterprise™ Industrial™-Grade Settings™."), 401 user = check_token(token) if user is None: return render_template("flagmachine.html", message="At Generic Enterprise™, We have Standards™. That's why we require all input Data™ to be strictly valid JSON."), 400 if user["admin"]: return render_template("flagmachine.html", message=flag) else: return render_template("flagmachine.html", message="At Generic Enterprise™, We Care about Security and Privacy. That's why only Authorized™ Personnel™ are permitted to modify our Enterprise™ Industrial™-Grade Settings™."), 403
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/BCACTF/2021/crypto/FNES_2/fnes2.py
ctfs/BCACTF/2021/crypto/FNES_2/fnes2.py
#!/usr/bin/env python3 import random import math import time import binascii import secrets from Crypto.Cipher import AES from Crypto.Hash import SHA from Crypto.Util.Padding import pad, unpad with open("flag.txt", "r") as f: flag = f.read().strip().encode("ascii") with open("key.txt", "r") as f: key = int(f.read().strip()) target_query = "Open sesame... Flag please!" print(""" Welcome to your new and improved FNES... FNES 2! As before, if you and a friend both run this service at the same time, you should be able to send messages to each other! Here are the steps: 1. Friends A and B connect to the server at the same time (you have about a five second margin) 2. Friend A encodes a message and sends it to Friend B 3. Friend B decodes the message, encodes their reply, and sends it to Friend A 4. Friend A decodes the reply, rinse and repeat PS: For security reasons, there are still some characters you aren't allowed to encrypt. Sorry! """, flush=True) tempkey = SHA.new(int(key + int(time.time() / 10)).to_bytes(64, 'big')).digest()[0:16] while True: print("Would you like to encrypt (E), decrypt (D), or quit (Q)?", flush=True) l = input(">>> ").strip().upper() if (len(l) > 1): print("You inputted more than one character...", flush=True) elif (l == "Q"): print("We hope you enjoyed!", flush=True) exit() elif (l == "E"): print("What would you like to encrypt?", flush=True) I = input(">>> ").strip() if (set(I.lower()) & set("flg!nsm")): # Disallowed characters changed to make the target query more difficult print("You're never getting my flag!", flush=True) exit() else: iv = secrets.token_bytes(16) cipher = AES.new(tempkey, AES.MODE_CBC, iv) c = str(binascii.hexlify(iv + cipher.encrypt(pad(str.encode(I), 16))))[2:-1] print("Here's your message:", flush=True) print(c, flush=True) elif (l == "D"): print("What was the message?", flush=True) I = input(">>> ").strip() iv = I[:32] I = I[32:] try: cipher = AES.new(tempkey, AES.MODE_CBC, binascii.unhexlify(iv)) m = str(unpad(cipher.decrypt(binascii.unhexlify(I)), 16))[2:-1] if (m == target_query): print("\nPassphrase accepted. Here's your flag:\n", flush=True) print(str(flag)[2:-1], flush=True) try: with open("advertisement.txt", "r") as ff: print(ff.read(), flush=True) except: pass exit() else: print("Here's the decoded message:", flush=True) print(m, flush=True) except ValueError: print("I can't read that!", flush=True)
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/BCACTF/2021/crypto/FNES_1/fnes1.py
ctfs/BCACTF/2021/crypto/FNES_1/fnes1.py
#!/usr/bin/env python3 import random import math import time import binascii from Crypto.Cipher import ARC4 from Crypto.Hash import SHA with open("flag.txt", "r") as f: flag = f.read().strip().encode("ascii") with open("key.txt", "r") as f: key = int(f.read().strip()) target_query = "Open sesame... Flag please!" print(""" Welcome to your Friendly Neighborhood Encryption Service (FNES)! If you and a friend both run this service at the same time, you should be able to send messages to each other! Here are the steps: 1. Friends A and B connect to the server at the same time (you have about a five second margin) 2. Friend A encodes a message and sends it to Friend B 3. Friend B decodes the message, encodes their reply, and sends it to Friend A 4. Friend A decodes the reply, rinse and repeat Make sure to not make any mistakes, though, or your keystreams might come out of sync... PS: For security reasons, there are four characters you aren't allowed to encrypt. Sorry! """, flush=True) tempkey = SHA.new(int(key + int(time.time() / 10)).to_bytes(64, 'big')).digest()[0:16] cipher = ARC4.new(tempkey) while True: print("Would you like to encrypt (E), decrypt (D), or quit (Q)?", flush=True) l = input(">>> ").strip().upper() if (len(l) > 1): print("You inputted more than one character...", flush=True) elif (l == "Q"): print("We hope you enjoyed!", flush=True) exit() elif (l == "E"): print("What would you like to encrypt?", flush=True) I = input(">>> ").strip() if (set(I.lower()) & set("flg!")): # You're not allowed to encrypt any of the characters in "flg!" print("You're never getting my flag!", flush=True) exit() else: print("Here's your message:", flush=True) c = str(binascii.hexlify(cipher.encrypt(str.encode(I))))[2:-1] print(c, flush=True) elif (l == "D"): print("What was the message?", flush=True) I = input(">>> ").strip() m = str(cipher.decrypt(binascii.unhexlify(I)))[2:-1] if (m == target_query): print("Passphrase accepted. Here's your flag:", flush=True) print(str(flag)[2:-1], flush=True) exit() else: print("Here's the decoded message:", flush=True) print(m, flush=True)
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/BCACTF/2021/crypto/Rainbow_Passage/rp.py
ctfs/BCACTF/2021/crypto/Rainbow_Passage/rp.py
#!/usr/bin/env python3 import math import binascii from Crypto.Util.Padding import pad, unpad print(""" Welcome to the official communication encryption system for rainbow bridges. Input the encryption password given to you by your sponsor diety to encode messages, and use the decryption password given to you to decode messages. """) def encode_block(m, pm): m = [i for i in m] c = [0] * 16 for i, w in enumerate(pm): for j, l in enumerate(w): if l == '1': c[j] ^= m[i] return binascii.hexlify(bytes(c)) def encode(m, pwd): pm = [] while pwd: a = '0'*8 + bin(ord(pwd[0]))[2:] a = a[-8:] b = '0'*8 + bin(ord(pwd[1]))[2:] b = b[-8:] pm.append(a + b) pwd = pwd[2:] c = b"" while m: c += encode_block(m[:16], pm) m = m[16:] return c while True: print("Would you like to encrypt (E), decrypt (D), or quit (Q)?") l = input(">>> ").strip().upper() if (len(l) > 1): print("You inputted more than one character...") elif (l == "Q"): print("Don't forget to perform sacrifices for your sponsor diety daily!") exit() elif (l == "E"): print("What is your encryption password?") pwd = input(">>> ").strip() assert len(pwd) == 32 print("What would you like to encrypt?") m = input(">>> ").strip() c = encode(pad(m.encode('ascii'), 16), pwd) print("Here's your encoded message:") print(c) elif (l == "D"): print("Oops, for now, that feature is reserved for your sponsor diety.")
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/BCACTF/2024/misc/MathJail/pycalculator.py
ctfs/BCACTF/2024/misc/MathJail/pycalculator.py
print("Welcome to your friendly python calculator!") equation = input("Enter your equation below and I will give you the answer:\n") while equation!="e": answer = eval(equation, {"__builtins__":{}},{}) print(f"Here is your answer: {answer}") equation = input("Enter your next equation below (type 'e' to exit):\n") print("Goodbye!")
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/BCACTF/2024/misc/JailBreak_2/main.py
ctfs/BCACTF/2024/misc/JailBreak_2/main.py
def sanitize(letter): print("Checking for contraband...") return any([i in letter.lower() for i in BANNED_CHARS]) def end(): print("Contraband letters found!\nMessages Deleted!") exit() BANNED_CHARS = "gdvxfiyundmnet/\\'~`@#$%^&.{}0123456789" flag = open('flag.txt').read().strip() print("Welcome to the prison's mail center") msg = input("\nPlease enter your message: ") while msg != "": if sanitize(msg): end() try: x = eval(msg) if len(x) != len(flag): end() print(x) except Exception as e: print(f'Error occured: {str(e)}; Message could not be sent.') msg = input("\nPlease enter your message: ")
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/BCACTF/2024/misc/JailBreak_Revenge/main.py
ctfs/BCACTF/2024/misc/JailBreak_Revenge/main.py
def sanitize(letter): print("Checking for contraband...") return any([(i in letter.lower()) for i in BANNED_CHARS]) or any([ord(l)>120 for l in letter]) def end(): print("Contraband letters found!\nMessages Deleted!") exit() BANNED_CHARS = "gdvxfiyundmpnetkb/\\'\"~`!@#$%^&*.{},:;=0123456789#-_|? \t\n\r\x0b\x0c" flag = open('flag.txt').read().strip() print("Welcome to the prison's mail center") msg = input("\nPlease enter your message: ") while msg != "": if sanitize(msg): end() try: x = eval(msg) if len(x) != len(flag): end() print(x) except Exception as e: print(f'Error.') msg = input("\nPlease enter your message: ")
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/BCACTF/2024/misc/JailBreak_1/deploy.py
ctfs/BCACTF/2024/misc/JailBreak_1/deploy.py
def sanitize(letter): print("Checking for contraband...") return any([i in letter.lower() for i in BANNED_CHARS]) BANNED_CHARS = "gdvxftundmnt'~`@#$%^&*-/.{}" flag = open('flag.txt').read().strip() print("Welcome to the prison's mail center") msg = input("Please enter your message: ") if sanitize(msg): print("Contraband letters found!\nMessage Deleted!") exit() exec(msg)
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/BCACTF/2024/misc/reload_decode/main.py
ctfs/BCACTF/2024/misc/reload_decode/main.py
from flask import Flask, render_template import random app = Flask(__name__) @app.route('/') def index(): #Gets the main page return render_template('index.html') @app.route('/flag') def getFlag(): #Get flag from flag.txt with open("flag.txt") as f: flag = bytearray(f.read().encode()) flag_str = "" for b in flag: b = b << 4 ^ ((b << 4 & 0xff) >> 4) bm = 1 << random.randint(0, 11) cb = b ^ bm flag_str += bin(cb)[2:].zfill(12) return render_template('index.html', joined_flag = flag_str) 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/BCACTF/2024/crypto/RSAEncrypter/rsa_encrypter.py
ctfs/BCACTF/2024/crypto/RSAEncrypter/rsa_encrypter.py
from Crypto.Util.number import getPrime, bytes_to_long, long_to_bytes message = open("./flag.txt").read().encode('utf-8') def encode(): n = getPrime(512)*getPrime(512) ciphertext = pow(bytes_to_long(message), 3, n) return (ciphertext, n) print("Return format: (ciphertext, modulus)") print(encode()) sent = input("Did you recieve the message? (y/n) ") while sent=='n': print(encode()) sent = input("How about now? (y/n) ") print("Message acknowledged.")
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/BCACTF/2024/crypto/Superstitious_2/superstitious-2.py
ctfs/BCACTF/2024/crypto/Superstitious_2/superstitious-2.py
from Crypto.Util.number import * def myGetPrime(): while True: x = getRandomNBitInteger(1024) & ((1 << 1024) - 1)//3 if isPrime(x): return x p = myGetPrime() q = myGetPrime() n = p * q e = 65537 message = open('flag.txt', 'rb') m = bytes_to_long(message.read()) c = pow(m, e, n) open("superstitious-2.txt", "w").write(f"n = {n}\ne = {e}\nc = {c}")
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/BCACTF/2024/crypto/Talk_to_Echo/echo.py
ctfs/BCACTF/2024/crypto/Talk_to_Echo/echo.py
from random import randint from time import sleep from Crypto.Hash import SHA256 from Crypto.Cipher import AES from Crypto.Util.Padding import pad a = 0xffffffff00000001000000000000000000000000fffffffffffffffffffffffc b = 0x5ac635d8aa3a93e7b3ebbd55769886bc651d06b0cc53b0f63bce3c3e27d2604b n = 0xffffffff00000001000000000000000000000000ffffffffffffffffffffffff G = (0x6b17d1f2e12c4247f8bce6e563a440f277037d812deb33a0f4a13945d898c296, 0x4fe342e2fe1a7f9b8ee7eb4a7c0f9e162bce33576b315ececbb6406837bf51f5) def add(p, q): if p == (0, 0): return q if q == (0, 0): return p if p[0] == q[0] and p[1] != q[1]: return (0, 0) if p != q: l = ((q[1] - p[1]) * pow(q[0] - p[0], -1, n)) % n else: if p[1] == 0: return (0, 0) l = ((3 * p[0] * p[0] + a) * pow(2 * p[1], -1, n)) % n x = (l * l - p[0] - q[0]) % n y = (l * (p[0] - x) - p[1]) % n return (x, y) def mul(k, p): q = (0, 0) while k > 0: if k & 1: q = add(q, p) p = add(p, p) k >>= 1 return q priv = randint(1, n - 1) pub = mul(priv, G) def enc(m, key=0): if key == 0: r = randint(1, n - 1) R = mul(r, G) K = mul(r, pub) else: R = None K = key h = SHA256.new() h.update(str(K[0]).encode()) k = h.digest()[:16] cipher = AES.new(k, AES.MODE_ECB) if R: return (R, cipher.encrypt(pad(m, 16))) return cipher.encrypt(pad(m, 16)) print("Hi! I'm Echo!") print("Just a second, I just received a message... give me a bit as I read it...") print(f"*mumbles* {enc(open("flag.txt", "rb").read())} *mumbles* ah interesting") while True: print("Talk to me! Let's use Diffie-Hellman Key Exchange to stay secure.") print("Here is my public key:") print(pub) print("Please send me a point.") x = int(input("x: ")) y = int(input("y: ")) rA = (x, y) assert rA != (0, 0) K = mul(priv, rA) print(enc(b"Hey there! Thanks for talking to me :)", K)) h = input("Want to speak again? (y/n)") if h.lower() != "y": break
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/BCACTF/2024/crypto/Encryptor_Shop/server.py
ctfs/BCACTF/2024/crypto/Encryptor_Shop/server.py
from Crypto.Util.number import * p = getPrime(1024) q = getPrime(1024) r = getPrime(1024) n = p * q phi = (p - 1) * (q - 1) e = 65537 d = pow(e, -1, phi) print("Welcome to the enc-shop!") print("What can I encrypt for you today?") for _ in range(3): message = input("Enter text to encrypt: ") m = bytes_to_long(message.encode()) c = pow(m, e, n) print(f"Here is your encrypted message: {c}") print(f"c = {c}") print("Here is the public key for your reference:") print(f"n = {n}") print(f"e = {e}") print("Thank you for encrypting with us!") print("In order to guarantee the security of your data, we will now let you view the encrypted flag.") x=input("Would you like to view it? (yes or no) ") if x.lower() == "yes": with open("flag.txt", "r") as f: flag = f.read().strip() m = bytes_to_long(flag.encode()) n = p*r c = pow(m, e, n) print(f"Here is the encrypted flag: {c}") print("Here is the public key for your reference:") print(f"n = {n}")
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/BCACTF/2024/crypto/rad_be_damned/message.py
ctfs/BCACTF/2024/crypto/rad_be_damned/message.py
import random def find_leftmost_set_bit(plaintext): pos = 0 while plaintext > 0: plaintext = plaintext >> 1 pos += 1 return pos def encrypt(plaintext: str): enc_plaintext = "" for letter in plaintext: cp = int("10011", 2) cp_length = cp.bit_length() bin_letter, rem = ord(letter), ord(letter) * 2**(cp_length - 1) while (rem.bit_length() >= cp_length): first_pos = find_leftmost_set_bit(rem) rem = rem ^ (cp << (first_pos - cp_length)) enc_plaintext += format(bin_letter, "08b") + format(rem, "0" + f"{cp_length - 1}" + "b") return enc_plaintext def rad(text: str): corrupted_str = "" for ind in range(0, len(text), 12): bit_mask = 2 ** (random.randint(0, 11)) snippet = int(text[ind : ind + 12], base = 2) rad_str = snippet ^ bit_mask corrupted_str += format(rad_str, "012b") return corrupted_str def main(): with open('flag.txt') as f: plaintext = f.read().strip() enc_plaintext = encrypt(plaintext) cor_text = rad(enc_plaintext) print(cor_text) 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/BCACTF/2024/crypto/Cha_Cha_Slide/server.py
ctfs/BCACTF/2024/crypto/Cha_Cha_Slide/server.py
from Crypto.Cipher import ChaCha20 from os import urandom key = urandom(32) nonce = urandom(12) secret_msg = urandom(16).hex() def encrypt_msg(plaintext): cipher = ChaCha20.new(key=key, nonce=nonce) return cipher.encrypt(plaintext.encode()).hex() print('Secret message:') print(encrypt_msg(secret_msg)) print('\nEnter your message:') user_msg = input() if len(user_msg) > 256: print('\nToo long!') exit() print('\nEncrypted:') print(encrypt_msg(user_msg)) print('\nEnter decrypted secret message:') decrypted_secret_msg = input() if len(decrypted_secret_msg) == len(secret_msg): if decrypted_secret_msg == secret_msg: with open('../flag.txt') as file: print('\n' + file.read()) exit() print('\nIncorrect!')
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false