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/Hack.lu/2022/web/YummyGIFs/adminbot/bot-master/src/worker.py
ctfs/Hack.lu/2022/web/YummyGIFs/adminbot/bot-master/src/worker.py
import json import subprocess from queue import Queue from threading import Thread, current_thread import log import config bot_queue = Queue() POISON_PILL = 'POISON_PILL' workers = [] def start_worker(i): t = Thread(name='worker-{}'.format(i), target=worker_main, args=[i]) t.start() workers.append(t) def kill_one_worker(): bot_queue.put(POISON_PILL) def kill_all_workers(): for _ in range(len(workers)): kill_one_worker() def add_task(task): log.log('[flask]', 'Adding {}'.format(task)) position = bot_queue.qsize() + 1 bot_queue.put(task) return position def queue_size(): return bot_queue.qsize() def worker_main(i): global config, workers tag = '[worker-{}]'.format(i) log.log(tag, 'started') while i < config.config['worker_count']: try: task = bot_queue.get(block=True, timeout=5) except: continue # abort condition, stop working if task == POISON_PILL: return # work on the task visit_link(tag, *task) # remove myself from the worker list workers.remove(current_thread()) log.log(tag, 'stopped') def visit_link(tag, link, loginInfo={}): global config log.log(tag, 'Visiting {} {}'.format(link, loginInfo)) docker_args = [ 'docker', 'run', # run interactive '-i', # remove container after execution '--rm', # use a specific network '--network', config.config['docker_network'], # seccomp chrome '--security-opt', 'seccomp=chrome.json', # limit run time '-e', 'TIMEOUT_SECS={}'.format(config.config['timeout_secs']), # the image to run config.config['docker_image'], ] args = docker_args + [ # the link to visit link, # the cookies json.dumps(loginInfo) ] log.log(tag, 'Executing: {}'.format(args)) subprocess.run(args)
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/Hack.lu/2022/web/YummyGIFs/adminbot/bot-master/src/log.py
ctfs/Hack.lu/2022/web/YummyGIFs/adminbot/bot-master/src/log.py
def log(tag, *msg): print(tag, *msg)
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/Hack.lu/2022/web/YummyGIFs/adminbot/bot-master/src/config.py
ctfs/Hack.lu/2022/web/YummyGIFs/adminbot/bot-master/src/config.py
import json from time import sleep from threading import Thread from log import log from worker import workers, start_worker, kill_one_worker config = {} old_config = {} config_load = None config_loader = None running = True def init_config(config_file): global config_loader load_config(config_file) config_loader = Thread(name='config-loader', target=config_loader_main, args=[config_file]) config_loader.start() def stop_config_loader(): global running running = False config_loader.join() def config_loader_main(config_file): global running while running: load_config(config_file) sleep(1) def load_config(config_file): global config, old_config, workers # parse the config file with open(config_file, 'r') as f: new_config = json.loads(f.read()) any_changes = False for key in set(list(old_config.keys()) + list(new_config.keys())): old_value = old_config[key] if key in old_config else None new_value = new_config[key] if key in new_config else None if old_value != new_value: log('[config]', "{} changed from '{}' to '{}'".format(key, old_value, new_value)) any_changes = True if not any_changes: return else: old_config = new_config.copy() config = new_config # recaptcha keys config['use_recaptcha'] = config.get('use_recaptcha', False) if config.get('use_recaptcha', False) is True: if config['recaptcha_public_key'] is None or config.get('recaptcha_secret_key', None) is None: raise Exception('recaptcha_public_key and recaptcha_secret_key must be defined in config') # link pattern if config.get('link_pattern', None) is None: config['link_pattern'] = '^https?://' # default cookie if config.get('cookies', None) is None: config['cookies'] = [] # default timeout if config.get('timeout_secs', None) is None: config['timeout_secs'] = 30 # worker count current_worker_count = len(workers) if config.get('worker_count', None) is None: config['worker_count'] = 1 if config['worker_count'] > current_worker_count: # spawn more workers for i in range(current_worker_count, config['worker_count']): start_worker(i) elif config['worker_count'] < current_worker_count: # kill some workers for i in range(config['worker_count'], current_worker_count, -1): kill_one_worker() # docker stuff if config.get('docker_network', None) is None: config['docker_network'] = 'bridge' if config.get('docker_image', None) is None: config['docker_image'] = 'chrome-bot'
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/Hack.lu/2022/web/YummyGIFs/adminbot/bot-master/src/recaptcha.py
ctfs/Hack.lu/2022/web/YummyGIFs/adminbot/bot-master/src/recaptcha.py
import json import requests def verify(secret_key, response): """Performs a call to reCaptcha API to validate the given response""" data = { 'secret': secret_key, 'response': response, } r = requests.post('https://www.google.com/recaptcha/api/siteverify', data=data) try: result = json.loads(r.text) except json.JSONDecodeError as e: print('[reCAPTCHA] JSONDecodeError: {}'.format(e)) return False if result['success']: return True else: print('[reCAPTCHA] Validation failed: {}'.format(result['error-codes'])) return False
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/Hack.lu/2022/web/YummyGIFs/adminbot/bot-master/src/app.py
ctfs/Hack.lu/2022/web/YummyGIFs/adminbot/bot-master/src/app.py
#!/usr/bin/env python from curses.ascii import SI import os import re import sys import datetime from flask import Flask, request, render_template import config import worker import recaptcha PORT = int(os.getenv('PORT', '5000')) BIND_ADDR = os.getenv('BIND_ADDR', '127.0.0.1') ADMIN_PASS = os.getenv('ADMIN_PASSWORD') LOGIN_URL = os.getenv('LOGIN_URL') LOGIN_CHECK = os.getenv('LOGIN_CHECK') app = Flask(__name__) @app.route('/', methods=['POST']) def index(): global config msg = '' error = '' link = request.form.get('link') # check recaptcha if config.config['use_recaptcha']: recaptcha_secret_key = config.config.get('recaptcha_secret_key', None) recaptcha_response = request.form.get('g-recaptcha-response') captcha_ok = recaptcha.verify(recaptcha_secret_key, recaptcha_response) else: captcha_ok = True # check link, level and captcha if(re.search(config.config['link_pattern'], link) and captcha_ok): # spawn admin bot task = (link, { "user": "admin", "password": ADMIN_PASS, "loginUrl": LOGIN_URL, "loginCheck": LOGIN_CHECK }) position = worker.add_task(task) msg = 'We will have a look. You are at position {} in the queue.'.format(position) else: error = 'Error!' return msg or error, 200 if msg else 400 @app.route('/info', methods=['GET']) def info(): return { 'queue_size': worker.queue_size(), 'worker_count': config.config['worker_count'], 'timeout_secs': config.config['timeout_secs'], 'use_recaptcha': config.config['use_recaptcha'], 'timestamp': datetime.datetime.now().isoformat() } def main(config_file): config.init_config(config_file) app.run(host=BIND_ADDR, port=PORT) # debug=True # shutdown worker.kill_all_workers() config.stop_config_loader() if __name__ == '__main__': if len(sys.argv) != 2: print('Usage: {} <config.json>'.format(sys.argv[0])) exit(1) main(sys.argv[1]) elif __name__ == 'app': # we are in gunicorn, so just load the config config.init_config('./config.json')
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/Hack.lu/2022/web/babyelectron_2/adminbot/bot-master/src/worker.py
ctfs/Hack.lu/2022/web/babyelectron_2/adminbot/bot-master/src/worker.py
import json import subprocess from queue import Queue from threading import Thread, current_thread import log import config bot_queue = Queue() POISON_PILL = 'POISON_PILL' workers = [] def start_worker(i): t = Thread(name='worker-{}'.format(i), target=worker_main, args=[i]) t.start() workers.append(t) def kill_one_worker(): bot_queue.put(POISON_PILL) def kill_all_workers(): for _ in range(len(workers)): kill_one_worker() def add_task(task): log.log('[flask]', 'Adding {}'.format(task)) position = bot_queue.qsize() + 1 bot_queue.put(task) return position def queue_size(): return bot_queue.qsize() def worker_main(i): global config, workers tag = '[worker-{}]'.format(i) log.log(tag, 'started') while i < config.config['worker_count']: try: task = bot_queue.get(block=True, timeout=5) except: continue # abort condition, stop working if task == POISON_PILL: return # work on the task visit_report(tag, *task) # remove myself from the worker list workers.remove(current_thread()) log.log(tag, 'stopped') def visit_report(tag, report, loginInfo={}): global config log.log(tag, 'Visiting {} {}'.format(report, loginInfo)) docker_args = [ 'docker', 'run', # run interactive '-i', # remove container after execution '--rm', # use a specific network '--network', config.config['docker_network'], # limit run time '-e', 'BOT=1', '-e', 'REPORT_ID=' + report, '-e', 'API_URL=http://api:1024', # the image to run config.config['docker_image'], ] log.log(tag, 'Executing: {}'.format(docker_args)) subprocess.run(docker_args)
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/Hack.lu/2022/web/babyelectron_2/adminbot/bot-master/src/log.py
ctfs/Hack.lu/2022/web/babyelectron_2/adminbot/bot-master/src/log.py
def log(tag, *msg): print(tag, *msg)
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/Hack.lu/2022/web/babyelectron_2/adminbot/bot-master/src/config.py
ctfs/Hack.lu/2022/web/babyelectron_2/adminbot/bot-master/src/config.py
import json from time import sleep from threading import Thread from log import log from worker import workers, start_worker, kill_one_worker config = {} old_config = {} config_load = None config_loader = None running = True def init_config(config_file): global config_loader load_config(config_file) config_loader = Thread(name='config-loader', target=config_loader_main, args=[config_file]) config_loader.start() def stop_config_loader(): global running running = False config_loader.join() def config_loader_main(config_file): global running while running: load_config(config_file) sleep(1) def load_config(config_file): global config, old_config, workers # parse the config file with open(config_file, 'r') as f: new_config = json.loads(f.read()) any_changes = False for key in set(list(old_config.keys()) + list(new_config.keys())): old_value = old_config[key] if key in old_config else None new_value = new_config[key] if key in new_config else None if old_value != new_value: log('[config]', "{} changed from '{}' to '{}'".format(key, old_value, new_value)) any_changes = True if not any_changes: return else: old_config = new_config.copy() config = new_config # recaptcha keys config['use_recaptcha'] = config.get('use_recaptcha', False) if config.get('use_recaptcha', False) is True: if config['recaptcha_public_key'] is None or config.get('recaptcha_secret_key', None) is None: raise Exception('recaptcha_public_key and recaptcha_secret_key must be defined in config') # link pattern if config.get('link_pattern', None) is None: config['link_pattern'] = '^https?://' # default cookie if config.get('cookies', None) is None: config['cookies'] = [] # default timeout if config.get('timeout_secs', None) is None: config['timeout_secs'] = 30 # worker count current_worker_count = len(workers) if config.get('worker_count', None) is None: config['worker_count'] = 1 if config['worker_count'] > current_worker_count: # spawn more workers for i in range(current_worker_count, config['worker_count']): start_worker(i) elif config['worker_count'] < current_worker_count: # kill some workers for i in range(config['worker_count'], current_worker_count, -1): kill_one_worker() # docker stuff if config.get('docker_network', None) is None: config['docker_network'] = 'bridge' if config.get('docker_image', None) is None: config['docker_image'] = 'chrome-bot'
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/Hack.lu/2022/web/babyelectron_2/adminbot/bot-master/src/recaptcha.py
ctfs/Hack.lu/2022/web/babyelectron_2/adminbot/bot-master/src/recaptcha.py
import json import requests def verify(secret_key, response): """Performs a call to reCaptcha API to validate the given response""" data = { 'secret': secret_key, 'response': response, } r = requests.post('https://www.google.com/recaptcha/api/siteverify', data=data) try: result = json.loads(r.text) except json.JSONDecodeError as e: print('[reCAPTCHA] JSONDecodeError: {}'.format(e)) return False if result['success']: return True else: print('[reCAPTCHA] Validation failed: {}'.format(result['error-codes'])) return False
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/Hack.lu/2022/web/babyelectron_2/adminbot/bot-master/src/app.py
ctfs/Hack.lu/2022/web/babyelectron_2/adminbot/bot-master/src/app.py
#!/usr/bin/env python from curses.ascii import SI import os import re import sys import datetime from flask import Flask, request, render_template import config import worker import recaptcha PORT = int(os.getenv('PORT', '5000')) BIND_ADDR = os.getenv('BIND_ADDR', '127.0.0.1') ADMIN_PASS = os.getenv('ADMIN_PASSWORD') LOGIN_URL = os.getenv('LOGIN_URL') LOGIN_CHECK = os.getenv('LOGIN_CHECK') app = Flask(__name__) @app.route('/', methods=['GET', 'POST']) def index(): global config msg = '' error = '' if request.method == 'POST': link = request.form.get('link') # check recaptcha if config.config['use_recaptcha']: recaptcha_secret_key = config.config.get('recaptcha_secret_key', None) recaptcha_response = request.form.get('recaptcha') captcha_ok = recaptcha.verify(recaptcha_secret_key, recaptcha_response) else: captcha_ok = True # check link, level and captcha if(re.search(config.config['link_pattern'], link) and captcha_ok): # spawn admin bot print('[+] Spawning Admin Bot') task = (link, ) position = worker.add_task(task) msg = 'We will have a look. You are at position {} in the queue.'.format(position) else: error = 'Error!' return render_template('index.html', use_recaptcha=config.config['use_recaptcha'], recaptcha_public_key=config.config.get('recaptcha_public_key', None), link_pattern=config.config['link_pattern'], msg=msg, error=error, ) @app.route('/info', methods=['GET']) def info(): return { 'queue_size': worker.queue_size(), 'worker_count': config.config['worker_count'], 'timeout_secs': config.config['timeout_secs'], 'use_recaptcha': config.config['use_recaptcha'], 'timestamp': datetime.datetime.now().isoformat() } def main(config_file): config.init_config(config_file) app.run(host=BIND_ADDR, port=PORT) # debug=True # shutdown worker.kill_all_workers() config.stop_config_loader() if __name__ == '__main__': if len(sys.argv) != 2: print('Usage: {} <config.json>'.format(sys.argv[0])) exit(1) main(sys.argv[1]) elif __name__ == 'app': # we are in gunicorn, so just load the config config.init_config('./config.json')
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/Hack.lu/2022/web/culinary_class_room/worker/app.py
ctfs/Hack.lu/2022/web/culinary_class_room/worker/app.py
from flask import Flask, request, jsonify from tempfile import NamedTemporaryFile import subprocess import re # Reference solution uses 140 lines of code, 250 should be well enough. MAX_DECORATION = 250 decorator_re = re.compile(r'^@[a-z._]+$', re.IGNORECASE) app = Flask(__name__) def checkCode(code): lines = code.strip().split("\n") if (len(lines) < 2): raise SyntaxError("The culinary class room need at least _some_ decoration.") if len(lines) > MAX_DECORATION: raise SyntaxError("This is too much, this culinary class room does not have THAT much space.") if (lines[-1] != "class room: ..."): raise SyntaxError("What are you trying to decorate?") for idx, line in enumerate(lines[:-1], start=1): if not line.strip(): continue if not decorator_re.match(line): raise SyntaxError(f"You can't decorate with that! (line {idx})") def runCode(code): with NamedTemporaryFile() as f: f.write(code.encode('utf-8')) f.flush() return subprocess.check_output(['python3', f.name], timeout=.1).decode() @app.route('/api/submit', methods=['POST']) def submit(): code = request.get_json().get('code', '') try: checkCode(code) output = runCode(code) return jsonify({'output': output}) except Exception as e: return jsonify({'output': f"ERROR: {e}"}) if __name__ == '__main__': app.run(host="0.0.0.0", port=5000)
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/Hack.lu/2022/web/foodAPI/src/browser-bot/bot-master/src/worker.py
ctfs/Hack.lu/2022/web/foodAPI/src/browser-bot/bot-master/src/worker.py
import json import subprocess from queue import Queue from threading import Thread, current_thread import log import config bot_queue = Queue() POISON_PILL = 'POISON_PILL' workers = [] def start_worker(i): t = Thread(name='worker-{}'.format(i), target=worker_main, args=[i]) t.start() workers.append(t) def kill_one_worker(): bot_queue.put(POISON_PILL) def kill_all_workers(): for _ in range(len(workers)): kill_one_worker() def add_task(task): log.log('[flask]', 'Adding {}'.format(task)) position = bot_queue.qsize() + 1 bot_queue.put(task) return position def queue_size(): return bot_queue.qsize() def worker_main(i): global config, workers tag = '[worker-{}]'.format(i) log.log(tag, 'started') while i < config.config['worker_count']: try: task = bot_queue.get(block=True, timeout=5) except: continue # abort condition, stop working if task == POISON_PILL: return # work on the task visit_link(tag, *task) # remove myself from the worker list workers.remove(current_thread()) log.log(tag, 'stopped') def visit_link(tag, link): global config log.log(tag, 'Visiting {}'.format(link)) docker_args = [ 'docker', 'run', # run interactive '-i', # remove container after execution '--rm', # seccomp chrome '--security-opt', 'seccomp=chrome.json', # load .env file '--env-file', '/.env-challenge', # the image to run config.config['docker_image'], ] args = docker_args + [ # the link to visit link, str(config.config['timeout_secs']) ] log.log(tag, 'Executing: {}'.format(args)) subprocess.run(args)
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/Hack.lu/2022/web/foodAPI/src/browser-bot/bot-master/src/log.py
ctfs/Hack.lu/2022/web/foodAPI/src/browser-bot/bot-master/src/log.py
def log(tag, *msg): print(tag, *msg)
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/Hack.lu/2022/web/foodAPI/src/browser-bot/bot-master/src/config.py
ctfs/Hack.lu/2022/web/foodAPI/src/browser-bot/bot-master/src/config.py
import json from time import sleep from threading import Thread from log import log from worker import workers, start_worker, kill_one_worker config = {} old_config = {} config_load = None config_loader = None running = True def init_config(config_file): global config_loader load_config(config_file) config_loader = Thread(name='config-loader', target=config_loader_main, args=[config_file]) config_loader.start() def stop_config_loader(): global running running = False config_loader.join() def config_loader_main(config_file): global running while running: load_config(config_file) sleep(1) def load_config(config_file): global config, old_config, workers # parse the config file with open(config_file, 'r') as f: new_config = json.loads(f.read()) any_changes = False for key in set(list(old_config.keys()) + list(new_config.keys())): old_value = old_config[key] if key in old_config else None new_value = new_config[key] if key in new_config else None if old_value != new_value: log('[config]', "{} changed from '{}' to '{}'".format(key, old_value, new_value)) any_changes = True if not any_changes: return else: old_config = new_config.copy() config = new_config # recaptcha keys config['use_recaptcha'] = config.get('use_recaptcha', False) if config.get('use_recaptcha', False) is True: if config['recaptcha_public_key'] is None or config.get('recaptcha_secret_key', None) is None: raise Exception('recaptcha_public_key and recaptcha_secret_key must be defined in config') # link pattern if config.get('link_pattern', None) is None: config['link_pattern'] = '^https?://' # default cookie if config.get('cookies', None) is None: config['cookies'] = [] # default timeout if config.get('timeout_secs', None) is None: config['timeout_secs'] = 30 # worker count current_worker_count = len(workers) if config.get('worker_count', None) is None: config['worker_count'] = 1 if config['worker_count'] > current_worker_count: # spawn more workers for i in range(current_worker_count, config['worker_count']): start_worker(i) elif config['worker_count'] < current_worker_count: # kill some workers for i in range(config['worker_count'], current_worker_count, -1): kill_one_worker() # docker stuff if config.get('docker_image', None) is None: config['docker_image'] = 'chrome-bot'
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/Hack.lu/2022/web/foodAPI/src/browser-bot/bot-master/src/recaptcha.py
ctfs/Hack.lu/2022/web/foodAPI/src/browser-bot/bot-master/src/recaptcha.py
import json import requests def verify(secret_key, response): """Performs a call to reCaptcha API to validate the given response""" data = { 'secret': secret_key, 'response': response, } r = requests.post('https://www.google.com/recaptcha/api/siteverify', data=data) try: result = json.loads(r.text) except json.JSONDecodeError as e: print('[reCAPTCHA] JSONDecodeError: {}'.format(e)) return False if result['success']: return True else: print('[reCAPTCHA] Validation failed: {}'.format(result['error-codes'])) return False
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/Hack.lu/2022/web/foodAPI/src/browser-bot/bot-master/src/app.py
ctfs/Hack.lu/2022/web/foodAPI/src/browser-bot/bot-master/src/app.py
#!/usr/bin/env python import os import re import sys import datetime from flask import Flask, request, render_template import config import worker import recaptcha PORT = int(os.getenv('PORT', '5000')) BIND_ADDR = os.getenv('BIND_ADDR', '127.0.0.1') app = Flask(__name__) @app.route('/', methods=['GET', 'POST']) def index(): global config msg = '' error = '' if request.method == 'POST': link = request.form.get('link') # check recaptcha if config.config['use_recaptcha']: recaptcha_secret_key = config.config.get('recaptcha_secret_key', None) recaptcha_response = request.form.get('recaptcha') captcha_ok = recaptcha.verify(recaptcha_secret_key, recaptcha_response) else: captcha_ok = True # check link, level and captcha if(re.search(config.config['link_pattern'], link) and captcha_ok): # spawn admin bot print('[+] Spawning Admin Bot') task = (link, ) position = worker.add_task(task) msg = 'We will have a look. You are at position {} in the queue.'.format(position) else: error = 'Error!' return render_template('index.html', use_recaptcha=config.config['use_recaptcha'], recaptcha_public_key=config.config.get('recaptcha_public_key', None), link_pattern=config.config['link_pattern'], msg=msg, error=error, ) @app.route('/info', methods=['GET']) def info(): return { 'queue_size': worker.queue_size(), 'worker_count': config.config['worker_count'], 'timeout_secs': config.config['timeout_secs'], 'use_recaptcha': config.config['use_recaptcha'], 'timestamp': datetime.datetime.now().isoformat() } def main(config_file): config.init_config(config_file) app.run(host=BIND_ADDR, port=PORT) # debug=True # shutdown worker.kill_all_workers() config.stop_config_loader() if __name__ == '__main__': if len(sys.argv) != 2: print('Usage: {} <config.json>'.format(sys.argv[0])) exit(1) main(sys.argv[1]) elif __name__ == 'app': # we are in gunicorn, so just load the config config.init_config('./config.json')
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/Hack.lu/2022/web/babyelectron_1/adminbot/bot-master/src/worker.py
ctfs/Hack.lu/2022/web/babyelectron_1/adminbot/bot-master/src/worker.py
import json import subprocess from queue import Queue from threading import Thread, current_thread import log import config bot_queue = Queue() POISON_PILL = 'POISON_PILL' workers = [] def start_worker(i): t = Thread(name='worker-{}'.format(i), target=worker_main, args=[i]) t.start() workers.append(t) def kill_one_worker(): bot_queue.put(POISON_PILL) def kill_all_workers(): for _ in range(len(workers)): kill_one_worker() def add_task(task): log.log('[flask]', 'Adding {}'.format(task)) position = bot_queue.qsize() + 1 bot_queue.put(task) return position def queue_size(): return bot_queue.qsize() def worker_main(i): global config, workers tag = '[worker-{}]'.format(i) log.log(tag, 'started') while i < config.config['worker_count']: try: task = bot_queue.get(block=True, timeout=5) except: continue # abort condition, stop working if task == POISON_PILL: return # work on the task visit_report(tag, *task) # remove myself from the worker list workers.remove(current_thread()) log.log(tag, 'stopped') def visit_report(tag, report, loginInfo={}): global config log.log(tag, 'Visiting {} {}'.format(report, loginInfo)) docker_args = [ 'docker', 'run', # run interactive '-i', # remove container after execution '--rm', # use a specific network '--network', config.config['docker_network'], # limit run time '-e', 'BOT=1', '-e', 'REPORT_ID=' + report, '-e', 'API_URL=http://api:1024', # the image to run config.config['docker_image'], ] log.log(tag, 'Executing: {}'.format(docker_args)) subprocess.run(docker_args)
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/Hack.lu/2022/web/babyelectron_1/adminbot/bot-master/src/log.py
ctfs/Hack.lu/2022/web/babyelectron_1/adminbot/bot-master/src/log.py
def log(tag, *msg): print(tag, *msg)
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/Hack.lu/2022/web/babyelectron_1/adminbot/bot-master/src/config.py
ctfs/Hack.lu/2022/web/babyelectron_1/adminbot/bot-master/src/config.py
import json from time import sleep from threading import Thread from log import log from worker import workers, start_worker, kill_one_worker config = {} old_config = {} config_load = None config_loader = None running = True def init_config(config_file): global config_loader load_config(config_file) config_loader = Thread(name='config-loader', target=config_loader_main, args=[config_file]) config_loader.start() def stop_config_loader(): global running running = False config_loader.join() def config_loader_main(config_file): global running while running: load_config(config_file) sleep(1) def load_config(config_file): global config, old_config, workers # parse the config file with open(config_file, 'r') as f: new_config = json.loads(f.read()) any_changes = False for key in set(list(old_config.keys()) + list(new_config.keys())): old_value = old_config[key] if key in old_config else None new_value = new_config[key] if key in new_config else None if old_value != new_value: log('[config]', "{} changed from '{}' to '{}'".format(key, old_value, new_value)) any_changes = True if not any_changes: return else: old_config = new_config.copy() config = new_config # recaptcha keys config['use_recaptcha'] = config.get('use_recaptcha', False) if config.get('use_recaptcha', False) is True: if config['recaptcha_public_key'] is None or config.get('recaptcha_secret_key', None) is None: raise Exception('recaptcha_public_key and recaptcha_secret_key must be defined in config') # link pattern if config.get('link_pattern', None) is None: config['link_pattern'] = '^https?://' # default cookie if config.get('cookies', None) is None: config['cookies'] = [] # default timeout if config.get('timeout_secs', None) is None: config['timeout_secs'] = 30 # worker count current_worker_count = len(workers) if config.get('worker_count', None) is None: config['worker_count'] = 1 if config['worker_count'] > current_worker_count: # spawn more workers for i in range(current_worker_count, config['worker_count']): start_worker(i) elif config['worker_count'] < current_worker_count: # kill some workers for i in range(config['worker_count'], current_worker_count, -1): kill_one_worker() # docker stuff if config.get('docker_network', None) is None: config['docker_network'] = 'bridge' if config.get('docker_image', None) is None: config['docker_image'] = 'chrome-bot'
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/Hack.lu/2022/web/babyelectron_1/adminbot/bot-master/src/recaptcha.py
ctfs/Hack.lu/2022/web/babyelectron_1/adminbot/bot-master/src/recaptcha.py
import json import requests def verify(secret_key, response): """Performs a call to reCaptcha API to validate the given response""" data = { 'secret': secret_key, 'response': response, } r = requests.post('https://www.google.com/recaptcha/api/siteverify', data=data) try: result = json.loads(r.text) except json.JSONDecodeError as e: print('[reCAPTCHA] JSONDecodeError: {}'.format(e)) return False if result['success']: return True else: print('[reCAPTCHA] Validation failed: {}'.format(result['error-codes'])) return False
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/Hack.lu/2022/web/babyelectron_1/adminbot/bot-master/src/app.py
ctfs/Hack.lu/2022/web/babyelectron_1/adminbot/bot-master/src/app.py
#!/usr/bin/env python from curses.ascii import SI import os import re import sys import datetime from flask import Flask, request, render_template import config import worker import recaptcha PORT = int(os.getenv('PORT', '5000')) BIND_ADDR = os.getenv('BIND_ADDR', '127.0.0.1') ADMIN_PASS = os.getenv('ADMIN_PASSWORD') LOGIN_URL = os.getenv('LOGIN_URL') LOGIN_CHECK = os.getenv('LOGIN_CHECK') app = Flask(__name__) @app.route('/', methods=['GET', 'POST']) def index(): global config msg = '' error = '' if request.method == 'POST': link = request.form.get('link') # check recaptcha if config.config['use_recaptcha']: recaptcha_secret_key = config.config.get('recaptcha_secret_key', None) recaptcha_response = request.form.get('recaptcha') captcha_ok = recaptcha.verify(recaptcha_secret_key, recaptcha_response) else: captcha_ok = True # check link, level and captcha if(re.search(config.config['link_pattern'], link) and captcha_ok): # spawn admin bot print('[+] Spawning Admin Bot') task = (link, ) position = worker.add_task(task) msg = 'We will have a look. You are at position {} in the queue.'.format(position) else: error = 'Error!' return render_template('index.html', use_recaptcha=config.config['use_recaptcha'], recaptcha_public_key=config.config.get('recaptcha_public_key', None), link_pattern=config.config['link_pattern'], msg=msg, error=error, ) @app.route('/info', methods=['GET']) def info(): return { 'queue_size': worker.queue_size(), 'worker_count': config.config['worker_count'], 'timeout_secs': config.config['timeout_secs'], 'use_recaptcha': config.config['use_recaptcha'], 'timestamp': datetime.datetime.now().isoformat() } def main(config_file): config.init_config(config_file) app.run(host=BIND_ADDR, port=PORT) # debug=True # shutdown worker.kill_all_workers() config.stop_config_loader() if __name__ == '__main__': if len(sys.argv) != 2: print('Usage: {} <config.json>'.format(sys.argv[0])) exit(1) main(sys.argv[1]) elif __name__ == 'app': # we are in gunicorn, so just load the config config.init_config('./config.json')
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/Hack.lu/2020/right-spot/run.py
ctfs/Hack.lu/2020/right-spot/run.py
#!/usr/bin/env python3 import zlib import sys import os import subprocess import io import bz2 import sys from flag import flag COMPRESSED_LIMIT = 2**20 # 1 MB compressed DECOMPRESSED_LIMIT = 30*2**20 # 30 MB uncompressed EXPECTED_STRING = b"pwned!\n" NUM_TESTS = 4 def compress(data): if len(data) > DECOMPRESSED_LIMIT: print('ERROR: File size limit exceeded!') exit(0) return bz2.compress(data, compresslevel=9) def decompress(data): bz2d = bz2.BZ2Decompressor() output = bz2d.decompress(data, max_length=DECOMPRESSED_LIMIT) if bz2d.needs_input == True: print('ERROR: File size limit exceeded!') exit(0) return output print(f"Welcome! Please send bz2 compressed binary data. How many bytes will you send (MAX: {COMPRESSED_LIMIT})?", flush=True) try: num_bytes = int(sys.stdin.readline()) except ValueError: print("A valid number, please") exit(0) if not (0 < num_bytes <= COMPRESSED_LIMIT): print("Bad number of bytes. Bye!") exit(0) print("What is your calculated CRC of the compressed data (hex)?", flush=True) try: crc = int(sys.stdin.readline(), 16) except ValueError: print("A valid hex crc, please") exit(0) print(f"Okay got CRC: {crc:x}, please start sending data", flush=True) compressed_payload = sys.stdin.buffer.read(num_bytes) while len(compressed_payload) < num_bytes: compressed_payload += sys.stdin.buffer.read(0, num_bytes - len(compressed_payload)) print(f"Read {len(compressed_payload)} bytes") calc_crc = zlib.crc32(compressed_payload) if crc == calc_crc: print("[+] CRC Checks out, all good.", flush=True) else: print(f"CRC mismatch. Calculated CRC: {calc_crc:x}, expected: {crc:x}") exit(0) payload = decompress(compressed_payload) if len(payload) > DECOMPRESSED_LIMIT: print(f"Payload too long. Got: {len(payload)} bytes. Limit: {DECOMPRESSED_LIMIT}") exit(0) print("[+] Decompressed payload", flush=True) for seed in range(1 << 5): print(f"Trying seed: 0x{seed:x}", flush=True) for i in range(1, NUM_TESTS + 1): print(f"Try #{i}", flush=True) try: p = subprocess.Popen(["./right_spot", str(seed)], stdin=subprocess.PIPE, stdout=subprocess.PIPE) stdout_output, stderr_output = p.communicate(input=payload, timeout=5) if stdout_output != EXPECTED_STRING: print("[-] Mh, not the correct output.") print(f"Output was: {stdout_output}") exit(0) if p.returncode != 0: print(f"[-] Did not return success status code. Status was: {p.returncode}") exit(0) except subprocess.TimeoutExpired as e: print("[-] Process timed out") p.kill() exit(0) except Exception as e: print("Something unforeseen went wrong...") print(e) p.kill() exit(0) print(f"Congrats, here is your flag: {flag}", flush=True)
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/Hack.lu/2020/right-spot/flag.py
ctfs/Hack.lu/2020/right-spot/flag.py
flag = "flag{fake_flag}"
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/GLSC/2021/crypto/Bashing_My_Head_In/passwordgen.py
ctfs/GLSC/2021/crypto/Bashing_My_Head_In/passwordgen.py
import time import os import sys class Random: def __init__(self, seed=None): if seed is None: self.seed = int(time.time() * (10 ** 7)) else: try: self.seed = int(seed) except ValueError: raise ValueError("Please use a valid integer for the seed.") self.next_seed = 0 def __generatePercentage(self): a = 1664525 c = 1013904223 m = 2 ** 32 if self.next_seed == 0: next_seed = (self.seed * a + c) % m else: next_seed = (self.next_seed * a + c) % m self.next_seed = next_seed randomPercentage = next_seed / m return randomPercentage def choice(self, index): randomIndex = round((self.__generatePercentage() * (len(index) - 1))) randomChoice = index[randomIndex] return randomChoice if __name__ == "__main__": if len(sys.argv) < 2: print("Usage: python passwordgen.py <int>") exit(1) else: alphabet = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890?!@#$%^&*()" rand = Random(os.getpid()) password = ''.join([rand.choice(alphabet) for i in range(int(sys.argv[1]))]) print(password)
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/EBCTF/2022/crypto/cryptomachine01/encrypt.py
ctfs/EBCTF/2022/crypto/cryptomachine01/encrypt.py
#!/usr/bin/env python import sys import binascii import base64 import string if len(sys.argv) < 2: print "Usage: %s <plaintext message>" % sys.argv[0] sys.exit(1) message = sys.argv[1] def h(m): return binascii.hexlify(m) def b(m): return base64.b64encode(m) def r(m): t = string.maketrans( "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz", "NOPQRSTUVWXYZABCDEFGHIJKLMnopqrstuvwxyzabcdefghijklm") return string.translate(m,t) def x(m): return ''.join(chr(ord(c)^0x42) for c in m) def encrypt(s): print(b(x(h(r(s))))) if __name__ == "__main__": encrypt(message)
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/EBCTF/2022/crypto/squaringoff/squaring_off.py
ctfs/EBCTF/2022/crypto/squaringoff/squaring_off.py
#!/usr/bin/python from Crypto.Util.number import bytes_to_long from secret import flag # parameters BASE = 2 MODULUS = 0xfffffffe00000002fffffffe0000000100000001fffffffe00000001fffffffe00000001fffffffefffffffffffffffffffffffe000000000000000000000001 print( pow(BASE, bytes_to_long(flag), MODULUS) )
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/EBCTF/2022/crypto/cryptomachine02/encrypt.py
ctfs/EBCTF/2022/crypto/cryptomachine02/encrypt.py
#!/usr/bin/python import sys, binascii, base64, string, random if len(sys.argv) < 2: print "Usage: %s <flag>" % sys.argv[0] sys.exit(1) flag = sys.argv[1] def H(m): return binascii.hexlify(m) def B(m): return base64.b64encode(m) def R(m): t = string.maketrans( "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz:", "NOPQRSTUVWXYZABCDEFGHIJKLMnopqrstuvwxyzabcdefghijklm#") return string.translate(m,t) def X(m): return H(''.join(chr(ord(c)^0x42) for c in m)) def encrypt(s): out = s f = [ X, B, R ] for i in range(random.randint(8,14)): a = random.randint(1,len(out)/2) b = random.randint(a+1,len(out)-1) tmp = [out[0:a],out[a:b],out[b:]] for j in range(3): k = random.randint(0,2) tmp[j] = str(k) + f[k](tmp[j]) out = ':'.join(tmp) return out if __name__ == "__main__": open("MESSAGE", "wb").write(encrypt(flag))
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/EBCTF/2022/crypto/everything/query.py
ctfs/EBCTF/2022/crypto/everything/query.py
import sys import gzip import pickle import numpy as np # Import our fancy neural network from gpt import sample if __name__ == "__main__": # Load the model weights ParamW, ParamB, itos, stoi = pickle.load(gzip.open("weights.p.gz","rb")) vocab_size = len(itos) # Get model prompt from first argument if len(sys.argv) == 1: print("Please pass one argument containing a string to prompt the language model") exit(1) prompt = bytes(sys.argv[1],'ascii') x = np.array(stoi[list(prompt)], dtype=np.uint64) # Run neural network on the prompt y = sample(x, ParamW, ParamB) # Print to stdout print(b"".join(itos[y]).decode("ascii"))
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/EBCTF/2022/crypto/everything/build_model.py
ctfs/EBCTF/2022/crypto/everything/build_model.py
# set up logging import numba import time import pickle import logging from numba.pycc import CC cc = CC('gpt') import numpy as np import math @cc.export('sample', 'i8[:](i8[:], f4[:,:,::1], f4[:,::1])') def sample(xx, ParamW, ParamB): block_size = 128 for k in range(100): x_cond = xx[-block_size:] idx = np.ascontiguousarray(x_cond) x = ParamW[0].T[idx,:128] + ParamW[1].T[:len(idx), :128] K = 16 for i in range(8): #ln = LayerNorm(2+i*K, x, ParamB, 128) dim = 128 weight = ParamB[2+i*K][:dim] bias = ParamB[2+i*K+1][:dim] y = (x - (x).sum(1).reshape((x.shape[0],1))/x.shape[1]) v = y - (y).sum(1).reshape((x.shape[0],1))/y.shape[1] v = (v**2).sum(1).reshape((x.shape[0],1)) / (v.shape[1]-1) y /= np.sqrt(v + 1e-5) y *= weight y += bias ln = y # csa = CausalSelfAttention(6+i*K, ln, ParamW, ParamB) n_head = 8 T, C = x.shape; def Linear(i, x, ParamW, ParamB, di, do): weight = ParamW[i][:di, :do] return x @ weight + ParamB[i+1][:do] k = Linear(6+i*K+0, ln, ParamW, ParamB, 128, 128).reshape((T, n_head, C // n_head)).transpose((1, 0, 2)) q = Linear(6+i*K+2, ln, ParamW, ParamB, 128, 128).reshape((T, n_head, C // n_head)).transpose((1, 0, 2)) v = Linear(6+i*K+4, ln, ParamW, ParamB, 128, 128).reshape((T, n_head, C // n_head)).transpose((1, 0, 2)) def matmul(a, b): c = np.zeros((a.shape[0], a.shape[1], b.shape[2]), dtype=np.float32) for i in range(a.shape[0]): c[i,:,:] = a[i] @ b[i] return c att = (matmul(q, k.transpose((0,2,1)))) / np.array(np.sqrt(k.shape[-1]),dtype=np.float32) mask = (1-np.tril(np.ones((1, T, T), dtype=np.float32))) * 100 att -= mask# TODO ex = np.exp(att)# - x.max(1)) att = ex / ex.sum(axis=2).reshape((ex.shape[0], ex.shape[1], 1)) y = matmul(att, v) y = np.ascontiguousarray(y.transpose((1, 0, 2))).reshape((T, C)) csa = Linear(6+i*K+6, y, ParamW, ParamB, 128, 128) x = x + csa #ln = LayerNorm(4+i*K, x, ParamB, 128) dim = 128 weight = ParamB[4+i*K][:dim] bias = ParamB[4+i*K+1][:dim] y = (x - (x).sum(1).reshape((x.shape[0],1))/x.shape[1]) v = y - (y).sum(1).reshape((x.shape[0],1))/y.shape[1] v = (v**2).sum(1).reshape((x.shape[0],1)) / (v.shape[1]-1) y /= np.sqrt(v + 1e-5) y *= weight y += bias ln = y di, do = 128, 512 weight = ParamW[14+i*K][:di, :do] lin = ln @ weight + ParamB[15+i*K][:do] z = np.maximum(lin, 0) x = np.ascontiguousarray(x) + Linear(16+i*K, np.ascontiguousarray(z), ParamW, ParamB, 512, 128) ## x = Layernorm(x) dim = 128 i = 18+7*K weight = ParamB[i][:dim] bias = ParamB[i+1][:dim] y = (x - (x).sum(1).reshape((x.shape[0],1))/x.shape[1]) v = y - (y).sum(1).reshape((x.shape[0],1))/y.shape[1] v = (v**2).sum(1).reshape((x.shape[0],1)) / (v.shape[1]-1) y /= np.sqrt(v + 1e-5) y *= weight y += bias x = y ## logits = Linear(x) i = 20+7*K di, do = 128, 94 weight = ParamW[i][:di, :do] logits = x @ weight + ParamB[i+1][:do] def softmax(x): ex = np.exp(x)# - x.max(1)) return ex / ex.sum(axis=1).reshape((ex.shape[0], 1)) probs = softmax(logits) probs = probs[-1, :] probs_sum = np.cumsum(probs) rint = np.random.random() ix = np.where(probs_sum > rint)[0][0] #ix = probs.argmax() xx = np.append(xx, ix) return xx if __name__ == '__main__': cc.compile()
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/EBCTF/2022/crypto/everything/build_weights.py
ctfs/EBCTF/2022/crypto/everything/build_weights.py
import pickle import numpy if __name__ == "__main__": Param = pickle.load(open("model_before.p","rb")) Param.append(np.zeros(94,dtype=np.float32)) itos = np.array([10, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 61, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99, 100, 101, 102, 103, 104, 105, 106, 107, 108, 109, 110, 111, 112, 113, 114, 115, 116, 117, 118, 119, 120, 121, 122, 123, 124, 125, 126], dtype=np.uint8) stoi = np.array([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 0, 29, 0, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], dtype=np.uint8) vocab_size = len(itos) ParamW = [] s = [] for x in Param: if len(x.shape) == 2: s.append(x.shape) ParamW.append(np.pad(x, [(0, 512-x.shape[0]),(0, 512-x.shape[1])])) else: s.append((512, 512)) ParamW.append(np.zeros((512, 512))) ParamW = np.array(ParamW, dtype=np.float32) ParamB = [] s = [] for x in Param: if len(x.shape) == 2: s.append((512,)) ParamB.append(np.zeros((512))) else: s.append((x.shape)) ParamB.append(np.pad(x, [(0, 512-x.shape[0])])) ParamB = np.array(ParamB, dtype=np.float32) pickle.dump([ParamW, ParamB, itos, stoi], open("weights.p","wb")) context = "Alice Bobson's password is" x = np.array([stoi[ord(s)] for s in context]) print("GO") y = sample(x, ParamW, ParamB) completion = b''.join(itos[y]) print(completion.decode("ascii"))
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/CyBRICS/2021/crypto/Signer/signer.py
ctfs/CyBRICS/2021/crypto/Signer/signer.py
from multiprocessing import Process import os import random import socket from ecdsa import ecdsa as ec from datetime import datetime RNG = random.Random() import hashlib g = ec.generator_192 N = g.order() secret = RNG.randrange(1, N) PUBKEY = ec.Public_key(g, g * secret) PRIVKEY = ec.Private_key(PUBKEY, secret) def read_line(s): body = b"" while True: ch = s.recv(1) if ch == b"\n": break body = body + ch return body def action(s): try: s.send(b"What you want to do?\n1) Make signature of data\n2) Get flag \n>") line = read_line(s) if line == b"1": now = datetime.now() time = now.strftime("%H:%M:%S") random_data = f"{RNG.getrandbits(512):x}" hash = int(hashlib.md5(f"{time}:{random_data}".encode()).hexdigest(), 16) nonce = RNG.randrange(1, N) signature = PRIVKEY.sign(hash, nonce) s.send(f"{signature.r}, {signature.s}, {hash}\n".encode()) elif line == b"2": now = datetime.now() time = now.strftime("%H:%M:%S") to_check = int(hashlib.md5(f"{time}:get_flag".encode()).hexdigest(), 16) s.send(f"Get signature for md5(\"{time}:get_flag\")\n".encode()) sig_line = read_line(s).decode().split(",") sig = ec.Signature(int(sig_line[0]), int(sig_line[1])) if PUBKEY.verifies( to_check, sig ): s.send(b"Get your flag") f = open("flag.txt", "r") flag = f.read() f.close() s.send(flag.encode()) else: s.send(b"Failed!\n") pass else: s.send(b"As you wish...") except socket.timeout: print("Exit via timeout!") finally: s.close() if __name__ == '__main__': s = socket.socket() s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) s.bind(("0.0.0.0", 10105)) s.listen(10) while True: client, addr = s.accept() print(f"Got connect from {addr}") p = Process(target=action, args=(client,)) p.daemon = True p.start() client.close()
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/CyBRICS/2021/crypto/To_The_Moon/tothemoon_encrypt.py
ctfs/CyBRICS/2021/crypto/To_The_Moon/tothemoon_encrypt.py
#!/usr/bin/python3.7 import hashlib import os from Crypto.Cipher import AES NUM_REDUNDANT_BITS = 7 def pos_redundant_bits(data, r): # Place redundancy bits to the positions of the power of 2 j = 0 k = 1 m = len(data) res = '' # Insert '0' to the positions of the power of 2 for i in range(1, m + r + 1): if (i == 2 ** j): res = res + '0' j += 1 else: res = res + data[-1 * k] k += 1 return res[::-1] def calc_parity_bits(arr, r): n = len(arr) # Searching for r parity bit for i in range(r): val = 0 for j in range(1, n + 1): # If position has 1 in ith significant # position then Bitwise OR the array value # to find parity bit value. if (j & (2 ** i) == (2 ** i)): val = val ^ int(arr[-1 * j]) # -1 * j is given since array is reversed # String Concatenation # (0 to n - 2^r) + parity bit + (n - 2^r + 1 to n) arr = arr[:n - (2 ** i)] + str(val) + arr[n - (2 ** i) + 1:] return arr def calc_final_parity(arr): # Add a parity bit to the last bit of 128b string return "0" if arr.count("1") % 2 == 0 else "1" def hamming_encode_block(block): bin_block = ''.join([bin(bt)[2:].zfill(8) for bt in block]) arr = pos_redundant_bits(bin_block, NUM_REDUNDANT_BITS) arr = calc_parity_bits(arr, NUM_REDUNDANT_BITS) arr += calc_final_parity(arr) return arr if __name__ == "__main__": import sys if len(sys.argv) < 4: print("Usage: python tothemoon_encrypt.py <src filename> <dest filename> <password>") exit() flag = open(sys.argv[1], "rb").read() password = hashlib.md5(sys.argv[3].encode()).digest() iv = os.urandom(16) binary_blocks = [] # Encode each 128b block with hamming 120/7 and add a parity bit while len(flag): current_block = flag[:15] if len(flag[15:]) == 0: current_block += b'\x00' * (15 - len(current_block) % 15) flag = flag[15:] binary_blocks.append(hamming_encode_block(current_block)) binary_flag = "".join(binary_blocks) encoded_flag = bytes(int(binary_flag[i : i + 8], 2) for i in range(0, len(binary_flag), 8)) encryptor = AES.new(password, AES.MODE_CBC, IV=iv) encrypted_flag = encryptor.encrypt(encoded_flag) secret_data = iv + encrypted_flag with open(sys.argv[2], "wb") as w: w.write(secret_data)
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/KalmarCTF/2024/misc/A_Blockchain_Challenge/interaction.py
ctfs/KalmarCTF/2024/misc/A_Blockchain_Challenge/interaction.py
from pwn import * from Crypto.Hash import SHA256 # my accounts public_keys = {} private_keys = {} balances = {} # Takes sender name and requested new account name, produces an account on chain. def account_generate(rem, sender, name): assert balances[sender] >= 10 rem.recvuntil(b'what would you like to do?') rem.sendline("create") rem.recvuntil(b'create request (sender name sig):') h = SHA256.new() h.update(sender.encode() + name.encode()) nonce =int(h.hexdigest()*7,16) pk = public_keys[sender] sk = private_keys[sender] sig = pow(nonce,sk,pk) payload = " ".join([sender, name, str(sig)]) rem.sendline(payload) rem.recvuntil("new account created for you!") rem.recvuntil("account name: ") newname = rem.readline().strip().decode() rem.recvuntil("account public key: ") newpk = int(rem.readline().strip().decode()) rem.recvuntil("account private key: ") newsk = int(rem.readline().strip().decode()) public_keys[newname] = newpk private_keys[newname] = newsk balances[newname] = 0 balances[sender] -= 10 return def transfer(rem, sender, receiver, amount): assert balances[sender] >= amount rem.recvuntil(b'what would you like to do?') rem.sendline("send") rem.recvuntil(b'send request (sender receiver amount sig):') h = SHA256.new() h.update(sender.encode() + b':' + receiver.encode() + b':' + str(amount).encode()) nonce = int(h.hexdigest()*7,16) sig = pow(nonce,private_keys[sender], public_keys[sender]) payload = " ".join([sender, receiver, str(amount), str(sig)]) rem.sendline(payload) print("waiting for confirmation of send") rem.recvuntil(f'{sender} sent {amount} to {receiver}'.encode()) print("sending success!") balances[sender] -= amount balances[receiver] += amount - 1 return def mintblock(rem, name): rem.recvuntil(b'what would you like to do?') rem.sendline("mintblock") rem.recvuntil(b'block ticket (name):') rem.sendline(name) balances[name] += 20 return def balance(rem): rem.recvuntil(b'what would you like to do?') rem.sendline("balance") data = rem.recvuntil(b'total float').decode() data += rem.readline().decode() print(data) return def tick(rem): rem.recvuntil(b"what would you like to do?") rem.sendline("tick") return # with remote(ip, port, level="debug") as rem: with process(["python3 chal.py"], shell=True, level="debug") as rem: rem.recvuntil(b'Your name is ') yourname = rem.readline().decode().strip() rem.recvuntil(b'your balance is ') yourbalance = int(rem.readline().decode().strip()) rem.recvuntil(b'your public key is ') yourpk = int(rem.readline().decode().strip()) rem.recvuntil(b'your private key is ') yoursk = int(rem.readline().decode().strip()) public_keys[yourname] = yourpk private_keys[yourname] = yoursk balances[yourname] = yourbalance balance(rem) account_generate(rem, "user", "account1") account_generate(rem, "user", "account2") account_generate(rem, "user", "account3") balance(rem) for i in range(100): tick(rem) balance(rem)
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/KalmarCTF/2024/misc/A_Blockchain_Challenge/chal.py
ctfs/KalmarCTF/2024/misc/A_Blockchain_Challenge/chal.py
from Crypto.Util.number import getStrongPrime from Crypto.Hash import SHA256 e = 65537 # account name to public keys public_keys = {} # account name to balances balances = {} # account name to secret key, for my own accounts foundation_accounts_sk = {} # total value on the blockchain. starts at 10k (9k foundation, 1k you) total_float = 10000 # probability of block per slot (expected every 5th block) block_freq = 0.2 def generate_account(name): p,q = [getStrongPrime(1024,e=65537) for _ in "pq"] d = pow(e,-1,(p-1)*(q-1)) n = p*q pk = n sk = d return name, pk, sk def verify_transfer(transfer_request): global total_float sender, receiver, amount, sig = transfer_request pk = public_keys[sender] h = SHA256.new() h.update(sender.encode() + b':' + receiver.encode() + b':' + str(amount).encode()) nonce = int(h.hexdigest()*7,16) # Some sanity checks assert receiver in public_keys, "who are you sending to?" assert balances[sender] >= amount, "illegal transaction detected, aborting" assert amount >= 1, "please send enough money to pay for the transaction >.>" assert pow(sig,e,pk) == nonce, "invalid signature on transfer request" balances[sender] -= amount balances[receiver] += amount - 1 total_float -= 1 print(f'{sender} sent {amount} to {receiver}') return def verify_generate(generate_request): global total_float sender, name, sig = generate_request # Some sanity checks assert name not in public_keys, "that account already exists! get out of here" assert ":" not in name, "no delimiters in account names pls" assert balances[sender] > 10, "not enough balance to create an account" h = SHA256.new() h.update(sender.encode() + name.encode()) nonce =int(h.hexdigest()*7,16) assert pow(sig,e,public_keys[sender]) == nonce, "invalid signature on account creation request" newname, newpk, newsk = generate_account(name) public_keys[newname] = newpk balances[newname] = 0 # Pay the account fee balances[sender] -= 10 total_float -= 10 print(f'new account created for you!') print(f'account name: {newname}') print(f'account public key: {newpk}') print(f'account private key: {newsk}') # Check a winning lottery ticket to produce a block def check_ticket(name, slot): global total_float # Public Lottery Function, (should probably use a vrf but whatever, no network level attacks here :D) # Saw this in ouroborus praos and it looked smart ^^ winning_prob = 1 - (1 - block_freq)**(balances[name]/total_float) h = SHA256.new() h.update(b'lottery:::' + str(slot).encode() + b':::' + str(public_keys[name]).encode()) lottery_roll =int(h.hexdigest(),16)/2**256 # did they win the lottery this round? if lottery_roll > winning_prob: # print("no lottery win, why submit false ticket?") return False else: print(f'account {name} won a block this slot!') # Heres your block reward for producing a block! balances[name] += 20 total_float += 20 print(f'account {name} gained 20 tokens, and now has balance {balances[name]}') return True def get_balances(): global total_float for name in public_keys: print(f'{name} has pk {public_keys[name]}') print(f'{name} has balance {balances[name]}') print(f"total float = {total_float}") def lottery_foundation_accounts(slot): for foundationaccount in foundation_accounts_sk: check_ticket(foundationaccount, slot) def verify_win(win_claim): name,sig = win_claim h = SHA256.new() h.update(b'I herebye declare myself victorious!!!!!!!') nonce =int(h.hexdigest()*7,16) assert pow(sig,e,public_keys[name]) == nonce, "invalid signature" assert balances[name] > total_float * 0.51, "you don't have >51 percent of the total_float, go away!" print("wow well done! You took over my network!") with open("flag.txt", "r") as f: print(f.read()) exit() if __name__ == "__main__": # Set up foundation accounts for acc in ["foundation 1", "foundation 2", "foundation 3"]: name, pk, sk = generate_account(acc) public_keys[name] = pk foundation_accounts_sk[name] = sk balances[name] = 3000 # Set up your account with 10% of the stake name, pk, sk = generate_account("user") public_keys[name] = pk balances[name] = 1000 print(f'Welcome to my blockchain! Its all proof of state and fancy and stuff!') print(f'Your name is {name}') print(f'your balance is {balances[name]}') print(f'your public key is {public_keys[name]}') print(f'your private key is {sk}') print("lets run a thousand slots!") for i in range(1000): print(f'Welcome to slot {i}') lottery_foundation_accounts(i) while True: command = input("what would you like to do?") if command == "send": sender, receiver, amount, sig = input("send request (sender receiver amount sig):").split() transfer_request = (sender, receiver, int(amount), int(sig)) verify_transfer(transfer_request) elif command == "create": sender, name, sig = input("create request (sender name sig):").split() create_request = (sender, name, int(sig)) verify_generate(create_request) elif command == "balance": get_balances() elif command == "mintblock": winner_name = input("block ticket (name):") if not check_ticket(winner_name, i): print("why did you submit an invalid ticket?") exit() else: break elif command == "win": name, sig = input("win claim (name sig):").split() verify_win((name, int(sig))) elif command == "tick": break print("thank you for using my blockchain :)") exit()
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/KalmarCTF/2024/crypto/Re_Cracking_The_Casino/Pedersen_commitments.py
ctfs/KalmarCTF/2024/crypto/Re_Cracking_The_Casino/Pedersen_commitments.py
from Crypto.Util.number import getStrongPrime from Crypto.Random.random import randint ## Implementation of Pedersen Commitment Scheme ## Computationally binding, information theoreticly hiding # Generate public key for Pedersen Commitments def gen(): q = getStrongPrime(1024) g = randint(1,q-1) s = randint(1,q-1) h = pow(g,s,q) return q,g,h # Create Pedersen Commitment to message x def commit(pk, m): q, g, h = pk r = randint(1,q-1) comm = pow(g,m,q) * pow(h,r,q) comm %= q return comm,r # Verify Pedersen Commitment to message x, with randomness r def verify(param, c, r, x): q, g, h = param if not (x > 1 and x < q): return False return c == (pow(g,x,q) * pow(h,r,q)) % q
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/KalmarCTF/2024/crypto/Re_Cracking_The_Casino/casino.py
ctfs/KalmarCTF/2024/crypto/Re_Cracking_The_Casino/casino.py
#!/usr/bin/python3 from Pedersen_commitments import gen, commit, verify # I want to host a trustworthy online casino! # To implement blackjack and craps in a trustworthy way i need verifiable dice and cards! # I've used information theoretic commitments to prevent players from cheating. # Can you audit these functionalities for me ? # Thanks for the feedback, I'll use secure randomness then! from Crypto.Random.random import randint # Verifiable Dice roll def roll_dice(pk): roll = randint(1,6) comm, r = commit(pk,roll) return comm, roll, r # verifies a dice roll def check_dice(pk,comm,guess,r): res = verify(pk,comm, r, int(guess)) return res # verifiable random card: def draw_card(pk): idx = randint(0,51) # clubs spades diamonds hearts suits = "CSDH" values = "234567890JQKA" value = values[idx%13] suit = suits[idx//13] card = value + suit comm, r = commit(pk, int(card.encode().hex(),16)) return comm, card, r # take a card (as two chars, fx 4S = 4 of spades) and verifies it was the committed card def check_card(pk, comm, guess, r): res = verify(pk, comm, r, int(guess.encode().hex(),16)) return res # Debug testing values for larger values def debug_test(pk): dbg = randint(0,2**32-2) comm, r = commit(pk,dbg) return comm, dbg, r # verify debug values def check_dbg(pk,comm,guess,r): res = verify(pk,comm, r, int(guess)) return res def audit(): print("Welcome to my (Launch day!) Casino!") q,g,h = gen() pk = q,g,h print(f'public key for Pedersen Commitment Scheme is:\nq = {q}\ng = {g}\nh = {h}') chosen = input("what would you like to play?\n[D]ice\n[C]ards") if chosen.lower() == "d": game = roll_dice verif = check_dice elif chosen.lower() == "c": game = draw_card verif = check_card else: game = debug_test verif = check_dbg correct = 0 # Should be secure now :) for _ in range(256): if correct == 250: print("Oh wow, you broke my casino again??!? That's impossible!") with open("flag.txt","r") as f: flag = f.read() print(f"here's that flag you wanted, you earned it! {flag}") exit() comm, v, r = game(pk) print(f'Commitment: {comm}') g = input(f'Are you able to guess the value? [Y]es/[N]o') if g.lower() == "n": print(f'commited value was {v}') print(f'randomness used was {r}') print(f'verifies = {verif(pk,comm,v,r)}') elif g.lower() == "y": guess = input(f'whats your guess?') if verif(pk, comm, guess, r): correct += 1 print("Oh wow! well done!") else: print("That's not right... Why are you wasting my time if you haven't broken anything?") exit() print(f'Guess my system is secure then! Lets go ahead with the launch!') exit() if __name__ == "__main__": audit()
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/KalmarCTF/2024/crypto/poLy1305CG/chal.py
ctfs/KalmarCTF/2024/crypto/poLy1305CG/chal.py
#!/usr/bin/env python3 from Crypto.Hash import Poly1305 from Crypto.Cipher import ChaCha20 import os N = 240 S = 10 L = 3 I = 13 with open("flag.txt", "rb") as f: flag = f.read().strip() # "Poly1305 is a universal hash family designed by Daniel J. Bernstein for use in cryptography." - wikipedia def poly1305_hash(data, Key, Nonce): hsh = Poly1305.new(key=Key, cipher=ChaCha20, nonce=Nonce) hsh.update(data=data) return hsh.digest() # If i just use a hash function instead of a linear function in my LCG, then it should be super secure right? class PolyCG: def __init__(self): self.Key = os.urandom(32) self.Nonce = os.urandom(8) self.State = os.urandom(16) # Oops. print("init = '" + poly1305_hash(b'init', self.Key, self.Nonce)[:I].hex() + "'") def next(self): out = self.State[S:S+L] self.State = poly1305_hash(self.State, self.Key, self.Nonce) return out if __name__ == "__main__": pcg = PolyCG() v = [] for i in range(N): v.append(pcg.next().hex()) print(f'{v = }') key = b"".join([pcg.next() for _ in range(0, 32, L)])[:32] cipher = ChaCha20.new(key=key, nonce=b'\0'*8) flagenc = cipher.encrypt(flag) print(f"flagenc = '{flagenc.hex()}'")
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/KalmarCTF/2024/crypto/Cracking_The_Casino/Pedersen_commitments.py
ctfs/KalmarCTF/2024/crypto/Cracking_The_Casino/Pedersen_commitments.py
from Crypto.Util.number import getStrongPrime from Crypto.Random.random import randint ## Implementation of Pedersen Commitment Scheme ## Computationally binding, information theoreticly hiding # Generate public key for Pedersen Commitments def gen(): q = getStrongPrime(1024) g = randint(1,q-1) s = randint(1,q-1) h = pow(g,s,q) return q,g,h # Create Pedersen Commitment to message x def commit(pk, m): q, g, h = pk r = randint(1,q-1) comm = pow(g,m,q) * pow(h,r,q) comm %= q return comm,r # Verify Pedersen Commitment to message x, with randomness r def verify(param, c, r, x): q, g, h = param if not (x > 1 and x < q): return False return c == (pow(g,x,q) * pow(h,r,q)) % q
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/KalmarCTF/2024/crypto/Cracking_The_Casino/casino.py
ctfs/KalmarCTF/2024/crypto/Cracking_The_Casino/casino.py
#!/usr/bin/python3 from Pedersen_commitments import gen, commit, verify # I want to host a trustworthy online casino! # To implement blackjack and craps in a trustworthy way i need verifiable dice and cards! # I've used information theoretic commitments to prevent players from cheating. # Can you audit these functionalities for me ? from random import randint # Verifiable Dice roll def roll_dice(pk): roll = randint(1,6) comm, r = commit(pk,roll) return comm, roll, r # verifies a dice roll def check_dice(pk,comm,guess,r): res = verify(pk,comm, r, int(guess)) return res # verifiable random card: def draw_card(pk): idx = randint(0,51) # clubs spades diamonds hearts suits = "CSDH" values = "234567890JQKA" value = values[idx%13] suit = suits[idx//13] card = value + suit comm, r = commit(pk, int(card.encode().hex(),16)) return comm, card, r # take a card (as two chars, fx 4S = 4 of spades) and verifies it was the committed card def check_card(pk, comm, guess, r): res = verify(pk, comm, r, int(guess.encode().hex(),16)) return res # Debug testing values for larger values def debug_test(pk): dbg = randint(0,2**32-2) comm, r = commit(pk,dbg) return comm, dbg, r # verify debug values def check_dbg(pk,comm,guess,r): res = verify(pk,comm, r, int(guess)) return res def audit(): print("Welcome to my (beta test) Casino!") q,g,h = gen() pk = q,g,h print(f'public key for Pedersen Commitment Scheme is:\nq = {q}\ng = {g}\nh = {h}') chosen = input("what would you like to play?\n[D]ice\n[C]ards") if chosen.lower() == "d": game = roll_dice verif = check_dice elif chosen.lower() == "c": game = draw_card verif = check_card else: game = debug_test verif = check_dbg correct = 0 # If you can guess the committed values more than i'd expect, then for _ in range(1337): if correct == 100: print("Oh wow, you broke my casino??!? Thanks so much for finding this before launch so i don't lose all my money to cheaters!") with open("flag.txt","r") as f: flag = f.read() print(f"here's that flag you wanted, you earned it! {flag}") exit() comm, v, r = game(pk) print(f'Commitment: {comm}') g = input(f'Are you able to guess the value? [Y]es/[N]o') if g.lower() == "n": print(f'commited value was {v}') print(f'randomness used was {r}') print(f'verifies = {verif(pk,comm,v,r)}') elif g.lower() == "y": guess = input(f'whats your guess?') if verif(pk, comm, guess, r): correct += 1 print("Oh wow! well done!") else: print("That's not right... Why are you wasting my time if you haven't broken anything?") exit() print(f'Guess my system is secure then! Lets go ahead with the launch!') exit() if __name__ == "__main__": audit()
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/KalmarCTF/2023/pwn/mjs/remote.py
ctfs/KalmarCTF/2023/pwn/mjs/remote.py
#!/usr/bin/env python3 import subprocess print("Welcome to mjs.") print("Please give input. End with \"EOF\":") s = "" try: while True: _s = input() if _s == 'EOF': break s += _s except EOFError: pass p = subprocess.Popen(["./mjs", "-e", s]) p.wait()
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/KalmarCTF/2023/crypto/EasyOneTimePad/challenge.py
ctfs/KalmarCTF/2023/crypto/EasyOneTimePad/challenge.py
#!/usr/bin/env python3 import os PASS_LENGTH_BYTES = 128 def encrypt_otp(cleartext): key = os.urandom(len(cleartext)) ciphertext = bytes([key[i % len(key)] ^ x for i,x in enumerate(cleartext.hex().encode())]) return ciphertext, key if __name__ == '__main__': print('According to Wikipedia:') print('"In cryptography, the one-time pad (OTP) is an encryption technique that cannot be cracked, but requires the use of a single-use pre-shared key that is not smaller than the message being sent."') print('So have fun trying to figure out my password!') password = os.urandom(PASS_LENGTH_BYTES) enc, _ = encrypt_otp(password) print(f'Here is my password encrypted with a one-time pad: {enc.hex()}') print('Actually, I will give you my password encrypted another time.') print('This time you are allowed to permute the password first') permutation = input('Permutation: ') try: permutation = [int(x) for x in permutation.strip().split(',')] assert len(permutation) == PASS_LENGTH_BYTES assert set(permutation) == set(range(PASS_LENGTH_BYTES)) enc, _ = encrypt_otp(bytes([password[permutation[i]] for i in range(PASS_LENGTH_BYTES)])) print(f'Here is the permuted password encrypted with another one-time pad: {enc.hex()}') except: print('Something went wrong!') exit(1) password_guess = input('What is my password: ') try: password_guess = bytes.fromhex(password_guess) except: print('Something went wrong!') exit(1) if password_guess == password: with open('flag.txt', 'r') as f: flag = f.read() print(f'The flag is {flag}') else: print('Nope.')
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/KalmarCTF/2023/crypto/BabyOneTimePad/challenge_file.py
ctfs/KalmarCTF/2023/crypto/BabyOneTimePad/challenge_file.py
#!/usr/bin/env python3 import os PASS_LENGTH_BYTES = 128 def encrypt_otp(cleartext, key = os.urandom(PASS_LENGTH_BYTES)): ciphertext = bytes([key[i % len(key)] ^ x for i,x in enumerate(cleartext.hex().encode())]) return ciphertext, key if __name__ == '__main__': print('According to Wikipedia:') print('"In cryptography, the one-time pad (OTP) is an encryption technique that cannot be cracked, but requires the use of a single-use pre-shared key that is not smaller than the message being sent."') print('So have fun trying to figure out my password!') password = os.urandom(PASS_LENGTH_BYTES) enc, _ = encrypt_otp(password) print(f'Here is my password encrypted with a one-time pad: {enc.hex()}') print('Actually, I will give you my password encrypted another time.') print('This time you are allowed to permute the password first') permutation = input('Permutation: ') try: permutation = [int(x) for x in permutation.strip().split(',')] assert set(permutation) == set(range(PASS_LENGTH_BYTES)) enc, _ = encrypt_otp(bytes([password[permutation[i]] for i in range(PASS_LENGTH_BYTES)])) print(f'Here is the permuted password encrypted with another one-time pad: {enc.hex()}') except: print('Something went wrong!') exit(1) password_guess = input('What is my password: ') try: password_guess = bytes.fromhex(password_guess) except: print('Something went wrong!') exit(1) if password_guess == password: with open('flag.txt', 'r') as f: flag = f.read() print(f'The flag is {flag}') else: print('Nope.')
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/KalmarCTF/2023/crypto/DreamHash/challenge_file.py
ctfs/KalmarCTF/2023/crypto/DreamHash/challenge_file.py
#!/usr/bin/env python3 import random import base64 VALUESIZE = 216 BLOCKSIZE = 16 class Value: def __init__(self, n): if isinstance(n, Value): n = n.n if not (isinstance(n, int) and 0 <= n <= VALUESIZE): raise ValueError self.n = n def __eq__(self, other): return self.n == other.n def extract(self): a = self.n % 3 b = ((self.n // 27) + 1) % 3 c = (self.n // 9) % 3 d = (((self.n // 27) + 1) // 3) % 3 if b == 0: f = (self.n // 3) % 3 e = (2 * d) % 3 else: e = (self.n // 3) % 3 f = ((1 + d*e) * b) % 3 return a,b,c,d,e,f @classmethod def assemble(cls, a, b, c, d, e, f): for x in (a,b,c,d,e,f): if not (isinstance(x, int) and 0 <= x <= 2): raise ValueError n = 0 n += a n += 27 * ((b + 3 * d) - 1) n += 9 * c if b == 0: n += 3 * f else: n += 3 * e return Value(n) def __add__(self, other): sa, sb, sc, sd, se, sf = self.extract() oa, ob, oc, od, oe, of = other.extract() a = (sa + sb * oa + sd * oc) % 3 b = (sb * ob + sd * oe) % 3 c = (sc + se * oa + sf * oc) % 3 d = (sb * od + sd * of) % 3 e = (se * ob + sf * oe) % 3 f = (se * od + sf * of) % 3 return Value.assemble(a, b, c, d, e, f) def __str__(self): return str(self.n) def __repr__(self): return repr(self.n) class DreamHash: def __init__(self): # I read that it is important to use nothing-up-my-sleeves-numbers for # constants in cryptosystems, so I generate the template randomly. self.template = [ random.sample( sum([[(i+j) % BLOCKSIZE]*(1 if j == 0 else j*VALUESIZE) for j in range(BLOCKSIZE)], []), k=(1 + VALUESIZE * sum(range(BLOCKSIZE))) ) for i in range(BLOCKSIZE) ] def hash(self, data): unfolded_data = [Value(d) for d in data] unfolded_data += [Value(0)] * (BLOCKSIZE - (len(unfolded_data) % BLOCKSIZE)) folded_data = [sum(unfolded_data[i::BLOCKSIZE], Value(0)) for i in range(BLOCKSIZE)] result = [] for i in range(BLOCKSIZE): result.append(Value(0)) for j in self.template[i]: result[-1] += folded_data[j] return [x.n for x in result] def main(): print('Welcome to the DreamHash testing service.') H = DreamHash() secret = bytes([random.randrange(VALUESIZE) for _ in range(BLOCKSIZE)]) print('I generated a secret. Can you recover it?') for _ in range(4): try: user_bytes = base64.b64decode(input('Your values: ')) h = H.hash(secret + user_bytes) print(f'Hash: {base64.b64encode(bytes(h)).decode()}') except: exit(0) user_bytes = base64.b64decode(input('Your guess at secret: ')) if user_bytes == secret: with open('flag.txt', 'r') as f: print(f.read()) else: print('Wrong.\n') 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/KalmarCTF/2023/web/HealthyCalc/chall.py
ctfs/KalmarCTF/2023/web/HealthyCalc/chall.py
import asyncio, os from random import choice, randint from celery import Celery from flask import Flask, Blueprint, jsonify OPERATION_SYMBOLS = {"add": "+", "sub": "-", "mult": "*"} OPERATIONS = { "add": lambda lhs, rhs: cache_lookup(_add, lhs, rhs), "sub": lambda lhs, rhs: cache_lookup(_sub, lhs, rhs), "mult": lambda lhs, rhs: cache_lookup(_mult, lhs, rhs), # ... } application = Flask(__name__) bp = Blueprint("routes", __name__) celery = Celery(__name__) @bp.route("/") def index(): op = choice(list(OPERATIONS.keys())) op_sym = OPERATION_SYMBOLS[op] a, b = randint(0, 9999), randint(0, 9999) return f'Hello! Want to know the result of <a href="/calc/{op}/{a}/{b}">{a} {op_sym} {b}</a>?<br/>Might take a second or two to calculate first time!' @bp.route("/calc/<operation>/<lhs>/<rhs>") async def calc(operation: str, lhs: int, rhs: int): if operation not in OPERATIONS: return jsonify({"err": f"Unknown operation: {operation}"}) f = OPERATIONS[operation] try: return jsonify({"ans": await f(lhs, rhs)}) except Exception as ex: return str(ex) def gp(n) -> int: """ guess precision """ if str(n).endswith(".0"): return int(n) else: return float(n) async def cache_lookup(operation, lhs: int, rhs: int) -> int: k = f"{operation.name}_{lhs}_{rhs}" try: return gp(celery.backend.get(k)) except: pass # skip cache miss ans = gp(await operation(lhs, rhs)) celery.backend.set(k, ans) return ans @celery.task() async def _add(x: int, y: int) -> int: return gp(x) + gp(y) @celery.task() async def _sub(x: int, y: int) -> int: return gp(x) - gp(y) @celery.task() async def _mult(x: int, y: int) -> int: return gp(x) * gp(y) def configure_app(application, **kwargs): application.secret_key = os.urandom(16) application.config["result_backend"] = "cache+memcached://memcached:11211/" if kwargs.get("celery"): init_celery(kwargs.get("celery"), application) application.register_blueprint(bp) def init_celery(celery, app): celery.conf.update(app.config) TaskBase = celery.Task class ContextTask(TaskBase): async def __call__(self, *args, **kwargs): # pretend to do heavy work await asyncio.sleep(1) with app.app_context(): return await TaskBase.__call__(self, *args, **kwargs) celery.Task = ContextTask configure_app(application, celery=celery) if __name__ == '__main__': application.run(host='0.0.0.0', port=5000, threaded=True)
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/KalmarCTF/2023/web/PasswordHomecoming/handout-app.py
ctfs/KalmarCTF/2023/web/PasswordHomecoming/handout-app.py
from flask import Flask, render_template, make_response app = Flask(__name__) # ... @app.before_request def enable_firewall(): if firewall.is_banned(...): return make_response("Your IP has been reported for abusing this websites functionality. Please behave and wait 60 seconds!") def do_render_template(filename, host, **context): # This is not really the challenge, just showing you this awesome way of translating websites: result = render_template(filename, **context) if 'dansk' in host: result = result.replace("o", "ø").replace("a", "å") elif 'l33t' in host: result = result.replace("e", "3").replace("l", "1").replace("o", "0") elif 'pirate' in host: ... return result @app.route('/change_password', methods=['GET','POST']) def change_password(): ... @app.route('/forgot_password', methods=['GET','POST']) def forgot_password(): ... @app.route('/register', methods=['GET','POST']) def register(): ... @app.route('/login', methods=['GET','POST']) def login_form(): ... @app.route('/abuse') def ban_ip(): ... @app.route('/logout') def logout(): ... @app.route("/") def index(): ... if __name__ == "__main__": app.run(host='0.0.0.0', port=1337, debug=True)
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/KalmarCTF/2025/crypto/Very_Serious_Cryptography/chal.py
ctfs/KalmarCTF/2025/crypto/Very_Serious_Cryptography/chal.py
from Crypto.Cipher import AES from Crypto.Util.Padding import pad import os with open("flag.txt", "rb") as f: flag = f.read() key = os.urandom(16) # Efficient service for pre-generating personal, romantic, deeply heartfelt white day gifts for all the people who sent you valentines gifts for _ in range(1024): # Which special someone should we prepare a truly meaningful gift for? recipient = input("Recipient name: ") # whats more romantic than the abstract notion of a securely encrypted flag? romantic_message = f'Dear {recipient}, as a token of the depth of my feelings, I gift to you that which is most precious to me. A {flag}' aes = AES.new(key, AES.MODE_CBC, iv=b'preprocessedlove') print(f'heres a thoughtful and unique gift for {recipient}: {aes.decrypt(pad(romantic_message.encode(), AES.block_size)).hex()}')
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/KalmarCTF/2025/crypto/basic_sums/chal.py
ctfs/KalmarCTF/2025/crypto/basic_sums/chal.py
with open("flag.txt", "rb") as f: flag = f.read() # I found this super cool function on stack overflow \o/ https://stackoverflow.com/questions/2267362/how-to-convert-an-integer-to-a-string-in-any-base def numberToBase(n, b): if n == 0: return [0] digits = [] while n: digits.append(int(n % b)) n //= b return digits[::-1] assert len(flag) <= 45 flag = int.from_bytes(flag, 'big') base = int(input("Give me a base! ")) if base < 2: print("Base is too small") quit() if base > 256: print("Base is too big") quit() print(f'Here you go! {sum(numberToBase(flag, base))}')
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/KalmarCTF/2025/crypto/MonoDOOM/chal.py
ctfs/KalmarCTF/2025/crypto/MonoDOOM/chal.py
from sage.all import * FLAG = b"kalmar{???}" #Formulae from https://www.hyperelliptic.org/EFD/g1p/auto-montgom-xz.html #dbl-1987-m-3 def double(a24, P): X1, Z1 = P A = X1+Z1 AA = A*A B = X1-Z1 BB = B*B C = AA-BB X3 = AA*BB Z3 = C*(BB+a24*C) return (X3, Z3) #dadd-1987-m-3 def diff_add(P, Q, PmQ): X2, Z2 = P X3, Z3 = Q X1, Z1 = PmQ A = X2+Z2 B = X2-Z2 C = X3+Z3 D = X3-Z3 DA = D*A CB = C*B X5 = Z1*(DA+CB)**2 Z5 = X1*(DA-CB)**2 return (X5, Z5) def ladder(a24, P, n): n = abs(n) P1, P2 = (1, 0), P if n == 0: return P1, P2 for bit in bin(n)[2:]: Q = diff_add(P2, P1, P) if bit == "1": P2 = double(a24, P2) P1 = Q else: P1 = double(a24, P1) P2 = Q return P1 def keygen(A, G, ord_G): s = randint(1, ord_G) a24 = (A + 2)/4 P = ladder(a24, G, s) return s, P def derive_secret(A, Pub, sk): a24 = (A + 2)/4 R = ladder(a24, Pub, sk) return int(R[0]/R[1]) if __name__=="__main__": p = 340824640496360275329125187555879171429601544029719477817787 F = GF(p) A = F(285261811835788437932082156343256480312664037202203048186662) ord_G = 42603080062045034416140648444405950943345472415479119301079 G = (F(2024), F(1)) s_A, p_A = keygen(A, G, ord_G) print(f"Alice sending Bob...\n{p_A}") s_B, p_B = keygen(A, G, ord_G) print(f"Bob sending Alice...\n{p_B}") ss_A = derive_secret(A, p_B, s_A) ss_B = derive_secret(A, p_A, s_B) assert ss_A == ss_B import hashlib import os from Crypto.Cipher import AES from Crypto.Util.Padding import pad, unpad def encrypt_flag(shared_secret: int): sha1 = hashlib.sha1() sha1.update(str(shared_secret).encode('ascii')) key = sha1.digest()[:16] iv = os.urandom(16) cipher = AES.new(key, AES.MODE_CBC, iv) ciphertext = cipher.encrypt(pad(FLAG, 16)) return iv.hex(), ciphertext.hex() print(encrypt_flag(ss_A))
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/KalmarCTF/2025/crypto/ZZKAoK/intarg.py
ctfs/KalmarCTF/2025/crypto/ZZKAoK/intarg.py
import hashlib SEP = 'ZProof' def generate_primes(n): num = 3 primes = [2] while len(primes) < n: is_prime = True for i in range(2, int(num ** 0.5) + 1): if num % i == 0: is_prime = False break if is_prime: primes.append(num) num += 2 return primes NUML = 18 try: with open('PRIMES.cache', 'r') as f: PRIMES = [int(n) for n in f.read().strip().split(' ')] except FileNotFoundError: PRIMES = generate_primes(1 << NUML) open('PRIMES.cache', 'w').write(' '.join(map(str, PRIMES))) TOTAL_PRIME_BITS = 0 for p in PRIMES: TOTAL_PRIME_BITS += p.bit_length() - 1 BITS = 50_000 # maximum norm, bits SECP = 256 # \secpar RATE = (TOTAL_PRIME_BITS + BITS - 1)//BITS # rate SECB = RATE.bit_length() - 1 # security bits per query QUERIES = (SECP + SECB - 1) // SECB # total number of queries assert len(PRIMES) == 1 << NUML def sha256(data): return hashlib.sha256(data.encode('utf-8')).hexdigest() class Merkle: def __init__(self, data): assert len(data) and (len(data) & (len(data) - 1)) == 0 if len(data) == 1: self.size = 1 self.leaf = data[0] self.root = sha256(data[0]) else: mid = len(data)//2 self.lhs = Merkle(data[:mid]) self.rhs = Merkle(data[mid:]) self.leaf = None self.root = sha256(self.lhs.root + self.rhs.root) self.size = len(data) def open(self, pos): assert 0 <= pos < self.size if self.size == 1: return [self.leaf] assert self.size % 2 == 0 mid = self.size // 2 if pos >= mid: prf = self.rhs.open(pos - mid) prf.append((1, self.lhs.root)) return prf else: prf = self.lhs.open(pos) prf.append((0, self.rhs.root)) return prf def verify(root: str, proof: list, pos: int, size: int) -> bytes: assert len(proof) > 0 assert len(proof) < 32 lvls = len(proof) - 1 assert 1 << lvls == size leaf = proof[0] node = sha256(leaf) for i in range(1, lvls+1): (dirc, sibl) = proof[i] assert isinstance(sibl, str) assert isinstance(dirc, int) assert len(sibl) == 64 assert dirc in [0, 1] if dirc == 0: node = sha256(node + sibl) else: node = sha256(sibl + node) assert node == root return leaf class ModVec: def __init__(self, vec, mod): assert len(mod) == len(vec) self.vec = vec self.mod = mod def __add__(self, other): if isinstance(other, int): return ModVec([(a + other) % p for a, p in zip(self.vec, self.mod)], self.mod) elif isinstance(other, ModVec): assert self.mod == other.mod return ModVec([(a + b) % p for a, b, p in zip(self.vec, other.vec, self.mod)], self.mod) else: return NotImplemented def __radd__(self, other): return self.__add__(other) def __sub__(self, other): if isinstance(other, int): return ModVec([(a - other) % p for a, p in zip(self.vec, self.mod)], self.mod) elif isinstance(other, ModVec): assert self.mod == other.mod return ModVec([(a - b) % p for a, b, p in zip(self.vec, other.vec, self.mod)], self.mod) else: return NotImplemented def __rsub__(self, other): return ModVec([(other - a) % p for a, p in zip(self.vec, self.mod)], self.mod) def __mul__(self, other): if isinstance(other, int): return ModVec([(a * other) % p for a, p in zip(self.vec, self.mod)], self.mod) elif isinstance(other, ModVec): assert self.mod == other.mod return ModVec([(a * b) % p for a, b, p in zip(self.vec, other.vec, self.mod)], self.mod) else: return NotImplemented def __rmul__(self, other): return self.__mul__(other) def check_equal(self, v: int): rdc = [v % p for p in self.mod] assert self.vec == rdc, f"Expected {rdc} but got {self.vec}" class Comm(Merkle): def __init__(self, n: int): self.n = n self.cord = [n % p for p in PRIMES] super().__init__([str(n) for n in self.cord]) def eval(self): return self.n class CommExpr: def __init__(self, com, poss, open): assert len(poss) == QUERIES assert len(open) == QUERIES self.poss = poss self.open = open self.root = com # verify all the openings values = [] for pos, pf in zip(poss, open): assert pos < len(PRIMES) values.append(int(verify(com, pf, pos, len(PRIMES)))) self.value = ModVec(values, [PRIMES[i] for i in poss]) def eval(self): return self.value class Mul: def __init__(self, lhs, rhs): self.lhs = lhs self.rhs = rhs def eval(self): if isinstance(self.lhs, int): lhs_val = self.lhs else: lhs_val = self.lhs.eval() if isinstance(self.rhs, int): rhs_val = self.rhs else: rhs_val = self.rhs.eval() return lhs_val * rhs_val def __repr__(self): return f'Mul({self.lhs}, {self.rhs})' class Add: def __init__(self, lhs, rhs): self.lhs = lhs self.rhs = rhs def eval(self): if isinstance(self.lhs, int): lhs_val = self.lhs else: lhs_val = self.lhs.eval() if isinstance(self.rhs, int): rhs_val = self.rhs else: rhs_val = self.rhs.eval() return lhs_val + rhs_val def __repr__(self): return f'Add({self.lhs}, {self.rhs})' class Transcript: def __init__(self, statement): self.hsh = sha256(SEP + ":" + str(statement)) def com(self, com): self.hsh = sha256(self.hsh + com.root) def value(self, n: int): self.hsh = sha256(self.hsh + str(n)) def challenge(self) -> int: self.hsh = sha256(self.hsh) return int(self.hsh, 16) class Prover: def __init__(self, statement): self.tx = Transcript(statement) self.coms = [] self.open = [] self.vals = [] def equal(self, expr, value): assert expr.eval() == value, f"Expected {value} to equal {expr.eval()}" def com(self, n: int): com = Comm(n) self.coms.append(com) self.tx.com(com) return com def value(self, value: int): self.tx.value(value) self.vals.append(int(value)) return value def combine(self): expr = Mul(self.tx.challenge(), self.coms[0]) for com in self.coms[1:]: expr = Add(expr, Mul(self.tx.challenge(), com)) return expr def finalize(self): cmb = self.combine() value = self.value(cmb.eval()) self.equal(cmb, value) # opening proofs positions = [self.tx.challenge() % len(PRIMES) for _ in range(QUERIES)] return { 'root': [com.root for com in self.coms], 'vals': self.vals, 'open': [[com.open(pos) for pos in positions] for com in self.coms], 'poss': positions } class Verifier: def __init__(self, proof, statement): self.tx = Transcript(statement) self.poss = proof['poss'] self.vals = iter(proof['vals']) self.exprs = [] root = proof['root'] open = proof['open'] assert len(open) == len(root) assert len(self.poss) == QUERIES # construct comm expr self.coms = [] for root, open in zip(root, open): assert len(root) == 64 assert len(open) == len(self.poss) self.coms.append(CommExpr(root, self.poss, open)) self.seq_coms = iter(self.coms) def value(self): value = next(self.vals) assert - 2**BITS < value < 2**BITS self.tx.value(value) return value def equal(self, expr, value): self.exprs.append((expr, value)) def com(self): com = next(self.seq_coms) assert isinstance(com, CommExpr) self.tx.com(com) return com def combine(self): expr = Mul(self.tx.challenge(), self.coms[0]) for com in self.coms[1:]: expr = Add(expr, Mul(self.tx.challenge(), com)) return expr def finalize(self): # add the random linear combination cmb = self.combine() value = self.value() self.equal(cmb, value) # check positions assert self.poss == [self.tx.challenge() % len(PRIMES) for _ in range(QUERIES)] # check all expressions for expr, value in self.exprs: expr.eval().check_equal(value) def sub(a, b): return Add(a, Mul(b, -1)) def equal(rel, a, b): rel.equal(sub(a, b), 0) def square(v): return Mul(v, v) def four(v1, v2, v3, v4): return Add( Add( square(v1), square(v2), ), Add( square(v3), square(v4) ) ) # relation to prove: # p \notin {-1, 1} # q \notin {-1, 1} # p * q = N # # via: # a^2 - 4 >= 0 <=> a \notin {-1, 1} # b^2 - 4 >= 0 <=> b \notin {-1, 1} # # arithmetic circuit: # p * q = N # a1^2 + a2^2 + a3^2 + a4^2 = p^2 - 4 # b1^2 + b2^2 + b3^2 + b4^2 = q^2 - 4 def rel_factor( rel, p, a1, a2, a3, a4, q, b1, b2, b3, b4, N, ): rel.equal(Mul(p, q), N) a = Add(square(p), -4) b = Add(square(q), -4) equal(rel, a, four(a1, a2, a3, a4)) equal(rel, b, four(b1, b2, b3, b4))
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/KalmarCTF/2025/crypto/ZZKAoK/server.py
ctfs/KalmarCTF/2025/crypto/ZZKAoK/server.py
import json from intarg import Verifier, rel_factor try: FLAG = open('flag.txt', 'r').read().strip() except: FLAG = "kalmar{testflag}" NUMBER = int(''' 2519590847565789349402718324004839857142928212620403202777713783604366202070 7595556264018525880784406918290641249515082189298559149176184502808489120072 8449926873928072877767359714183472702618963750149718246911650776133798590957 0009733045974880842840179742910064245869181719511874612151517265463228221686 9987549182422433637259085141865462043576798423387184774447920739934236584823 8242811981638150106748104516603773060562016196762561338441436038339044149526 3443219011465754445417842402092461651572335077870774981712577246796292638635 6373289912154831438167899885040445364023527381951378636564391212010397122822 120720357'''.replace('\n', '')) def out(obj): print(json.dumps(obj)) def inp(): try: s = input() return json.loads(s) except Exception as e: out({ 'type': 'error', 'message': 'Invalid JSON: ' + str(e) }) exit(1) def check_proof(msg): N = msg['N'] pf = msg['pf'] vf = Verifier(pf, N) p = vf.com() q = vf.com() a1 = vf.com() a2 = vf.com() a3 = vf.com() a4 = vf.com() b1 = vf.com() b2 = vf.com() b3 = vf.com() b4 = vf.com() rel_factor( vf, p, a1, a2, a3, a4, q, b1, b2, b3, b4, N ) vf.finalize() return N if __name__ == '__main__': out({ 'type': 'hello', 'message': 'Welcome to Kalmar consolidated proof systems.' }) try: N = check_proof(inp()) out({ 'type': 'success', 'flag': FLAG if N == NUMBER else 'great job m8, but not quite' }) except Exception as e: out({ 'type': 'error', 'message': 'Looks like a bad proof to me: ' + str(e) })
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/KalmarCTF/2025/crypto/Not_so_complex_multiplication/chal.py
ctfs/KalmarCTF/2025/crypto/Not_so_complex_multiplication/chal.py
from sage.all import * FLAG = b"kalmar{???}" # Generate secret primes of the form x^2 + 7y^2 ps = [] x = randint(0, 2**100) while gcd(x, 7) > 1: x = randint(0, 2**100) while len(ps) < 10: pi = x**2 + 7*randint(0, 2**100)**2 if is_prime(pi): ps.append(pi) for p in ps: F = GF(p) E = EllipticCurve_from_j(F(int("ff", 16))**3) print(E.order()) print(sum(ps)) # Encrypt the flag import hashlib import os from Crypto.Cipher import AES from Crypto.Util.Padding import pad, unpad def encrypt_flag(secret: int): sha1 = hashlib.sha1() sha1.update(str(secret).encode('ascii')) key = sha1.digest()[:16] iv = os.urandom(16) cipher = AES.new(key, AES.MODE_CBC, iv) ciphertext = cipher.encrypt(pad(FLAG, 16)) return iv.hex(), ciphertext.hex() # Good luck! :^) print(encrypt_flag(prod(ps)))
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/FwordCTF/2021/pwn/Peaky_and_the_Brain/app.py
ctfs/FwordCTF/2021/pwn/Peaky_and_the_Brain/app.py
# -*- coding: utf-8 -*- from flask import Flask, render_template, request from werkzeug.exceptions import RequestEntityTooLarge from PIL import Image import subprocess import os app = Flask(__name__) app.config['UPLOAD_FOLDER'] = os.path.join('static','uploads') app.config['MAX_CONTENT_LENGTH'] = 10 * 1000 app.secret_key = os.urandom(64) def image_to_code(file): colors = {(255,0,0) : '>', (0,255,0) : '.', (0,0,255) : '<', (255,255,0) : '+', (0,255,255) : '-', (255,0,188) : '[', (255,128,0) : ']', (102,0,204) : ','} image = Image.open(file) w, h = image.size pixels = image.load() code = '' for i in range(h): for j in range(w): p = pixels[j,i][:3] if p in colors: code += colors[p] return code def interpret(code, arg): process = subprocess.Popen(['./interpreter', code, arg], stdout=subprocess.PIPE, stderr=subprocess.PIPE) out, err = process.communicate() return out.decode() def save_image(file): im = Image.open(file) filename = os.urandom(20).hex() path = os.path.join(app.config['UPLOAD_FOLDER'], filename) im.save(path, format='PNG') return path @app.route("/", methods=['GET', 'POST']) def upload(): DEFAULT_MSG = 'Pinky: Gee, Brain, what do you want to do tonight? Brain: The same thing we do every night, Pinky - try to take over the world!' DEFAULT_IMG = os.path.join('static', 'images/default.png') try: if request.method == 'POST': file = request.files.get('file') arg = request.form['text'] code = image_to_code(file) img = save_image(file) out = interpret(code, arg) if out != '' : return render_template('index.html', msg=out, img=img) else: return render_template('index.html', msg=DEFAULT_MSG, img=DEFAULT_IMG) return render_template('index.html', msg=DEFAULT_MSG, img=DEFAULT_IMG) except RequestEntityTooLarge: return render_template('error.html', msg='File size exceeds limit.') except Exception as e: print (e) return render_template('error.html', msg='An error has occured.') if __name__ == "__main__": app.run(host="0.0.0.0", port=6969, debug=True)
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/FwordCTF/2021/crypto/Leaky_Blinders/leaky_blinders.py
ctfs/FwordCTF/2021/crypto/Leaky_Blinders/leaky_blinders.py
#!/usr/bin/env python3.8 from Crypto.Cipher import AES from Crypto.Util.Padding import pad, unpad import sys, os FLAG = b"FwordCTF{###############################################################}" WELCOME = ''' Welcome to Enc/Dec Oracle. ''' key = os.urandom(32) def xor(a, b): return bytearray([a[i % len(a)] ^ b[i % len(b)] for i in range(max(len(a), len(b)))]) def encrypt(msg): aes = AES.new(key, AES.MODE_ECB) if len(msg) % 16 != 0: msg = pad(msg, 16) cipher = aes.encrypt(msg) cipher = xor(cipher, key) return cipher def decrypt(cipher, k): aes = AES.new(k, AES.MODE_ECB) cipher = xor(cipher, k) msg = unpad(aes.decrypt(cipher), 16) return msg class Leaky_Blinders: def __init__(self): print(WELCOME + f"Here is the encrypted flag : {encrypt(FLAG).hex()}") def start(self): try: while True: print("\n1- Encrypt") print("2- Decrypt") print("3- Leave") c = input("> ") if c == '1': msg = os.urandom(32) cipher = encrypt(msg) if all(a != b for a, b in zip(cipher, key)): print(cipher.hex()) else: print("Something seems leaked !") elif c == '2': k = bytes.fromhex(input("\nKey : ")) cipher = bytes.fromhex(input("Ciphertext : ")) flag = decrypt(cipher, k) if b"FwordCTF" in flag: print(f"Well done ! Here is your flag : {FLAG}") else: sys.exit("Wrong key.") elif c == '3': sys.exit("Goodbye :)") except Exception: sys.exit("System error.") if __name__ == "__main__": challenge = Leaky_Blinders() challenge.start()
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/FwordCTF/2021/crypto/Boombastic/boombastic.py
ctfs/FwordCTF/2021/crypto/Boombastic/boombastic.py
#!/usr/bin/env python3.8 from Crypto.Util.number import getStrongPrime, inverse from json import loads, dumps import hashlib, sys, os, signal, random FLAG = "FwordCTF{###############################}" WELCOME = ''' ______________ _(______________() ______ _- | || | |_ _- | || | |_|_ | Boombastic || |______| -_ | || /\\ -_|______________|| / \\ / \\ / \\ ''' p = getStrongPrime(1024) secret = random.randint(1, p-1) def get_ticket(code): y = int(hashlib.sha256(code.encode()).hexdigest(),16) r = ((y**2 - 1) * (inverse(secret**2, p))) % p s = ((1 + y) * (inverse(secret, p))) % p return {'s': hex(s), 'r': hex(r), 'p': hex(p)} class Boombastic: def __init__(self): print(WELCOME) def start(self): try: while True: print("\n1- Enter Cinema") print("2- Get a ticket") print("3- Leave") c = input("> ") if c == '1': magic_word = loads(input("\nEnter the magic word : ")) if magic_word == get_ticket("Boombastic"): print(f"Here is your flag : {FLAG}, enjoy the movie sir.") else: print("Sorry, VIPs only.") sys.exit() elif c == '2': word = os.urandom(16).hex() print(f"\nYour ticket : {dumps(get_ticket(word))}") elif c == '3': print("Goodbye :)") sys.exit() except Exception: print("System error.") sys.exit() signal.alarm(360) if __name__ == "__main__": challenge = Boombastic() challenge.start()
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/FwordCTF/2021/crypto/Invincible/invincible.py
ctfs/FwordCTF/2021/crypto/Invincible/invincible.py
#!/usr/bin/env python3.8 from Crypto.Util.number import inverse from Crypto.Cipher import AES from collections import namedtuple import random, sys, os, signal, hashlib FLAG = "FwordCTF{#######################################################}" WELCOME = ''' Welcome to my Invincible Game, let's play. If you can decrypt all my messages that I will give, You win. (( _______ _______ /\O O\ /O /\ / \ \ / O /O \ / O \O____O\ )) ((/_____O/ \ \ /O / \O O\ / \ / O / \O O\ O/ \/_____O/ \O____O\/ )) You get to choose your point first. ''' Point = namedtuple("Point","x y") class EllipticCurve: INF = Point(0, 0) def __init__(self, a, b, Gx, Gy, p): self.a = a self.b = b self.p = p self.G = Point(Gx, Gy) def add(self, P, Q): if P == self.INF: return Q elif Q == self.INF: return P if P.x == Q.x and P.y == (-Q.y % self.p): return self.INF if P != Q: tmp = (Q.y - P.y)*inverse(Q.x - P.x, self.p) % self.p else: tmp = (3*P.x**2 + self.a)*inverse(2*P.y, self.p) % self.p Rx = (tmp**2 - P.x - Q.x) % self.p Ry = (tmp * (P.x - Rx) - P.y) % self.p return Point(Rx, Ry) def multiply(self, P, n): R = self.INF while 0 < n: if n & 1 == 1: R = self.add(R, P) n, P = n >> 1, self.add(P, P) return R p = 0xffffffff00000001000000000000000000000000ffffffffffffffffffffffff a = -0x3 Gx = 0x55b40a88dcabe88a40d62311c6b300e0ad4422e84de36f504b325b90c295ec1a Gy = 0xf8efced5f6e6db8b59106fecc3d16ab5011c2f42b4f8100c77073d47a87299d8 b = 0x5ac635d8aa3a93e7b3ebbd55769886bc651d06b0cc53b0f63bce3c3e27d2604b E = EllipticCurve(a, b, Gx, Gy, p) class RNG: def __init__(self, seed, P, Q): self.seed = seed self.P = P self.Q = Q def next(self): s = E.multiply(self.P, self.seed).x self.seed = s r = E.multiply(self.Q, s).x return r & ((1<<128) - 1) def encrypt(msg, key, iv): aes = AES.new(key, AES.MODE_CBC, iv) cipher = aes.encrypt(msg) return iv + cipher def decrypt(cipher, key, iv): aes = AES.new(key, AES.MODE_CBC, iv) msg = aes.decrypt(cipher) return msg class Invincible: def __init__(self): print(WELCOME) def start(self): try: Px = int(input("Point x : ")) Py = int(input("Point y : ")) P = Point(Px, Py) if (P == E.INF) or (Px == 0) or (Py == 0): print("Don't cheat.") sys.exit() print(f"Your point : ({P.x}, {P.y})") Q = E.multiply(E.G, random.randrange(1, p-1)) print(f"\nMy point : ({Q.x}, {Q.y})") rng = RNG(random.getrandbits(128), P, Q) for _ in range(100): key = hashlib.sha1(str(rng.next()).encode()).digest()[:16] iv = os.urandom(16) msg = os.urandom(64) cipher = encrypt(msg, key, iv) print(f"\nCiphertext : {cipher.hex()}") your_dec = bytes.fromhex(input("What was the message ? : ")) if your_dec == msg: print("Correct.") else: print("You lost.") sys.exit() print(f"Congratulations ! Here's your flag : {FLAG}") except Exception: print("System error.") sys.exit() signal.alarm(360) if __name__ == "__main__": challenge = Invincible() challenge.start()
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/FwordCTF/2021/crypto/Procyon/procyon.py
ctfs/FwordCTF/2021/crypto/Procyon/procyon.py
#!/usr/bin/env python3.8 from Crypto.Util.number import getStrongPrime, bytes_to_long, inverse from json import loads, dumps from time import time import os, sys, hashlib, random, signal FLAG = "FwordCTF{####################################################}" assert len(FLAG) < 1024//8 prime = getStrongPrime(1024) class DiffieHellman: def __init__(self): self.p = prime self.g = 3 self.private_key = random.randrange(2, self.p - 1) self.public_key = pow(self.g, self.private_key, self.p) def shared_secret(self, K): return pow(K, self.private_key, self.p) def proof(msg, secret): m = bytes_to_long(msg) t = int(time()) return t*secret + m*secret % prime class Procyon: def __init__(self): self.Alice = DiffieHellman() self.Bob = DiffieHellman() def start(self): Alice_params = {"g": hex(self.Alice.g), "A": hex(self.Alice.public_key), "p": hex(self.Alice.p)} print(f"Alice sends to Bob : {dumps(Alice_params)}\n") Bob_params = {"g": hex(self.Bob.g), "B": hex(self.Bob.public_key), "p": hex(self.Bob.p)} print(f"Bob sends to Alice : {dumps(Bob_params)}\n") shared_secret = self.Alice.shared_secret(int(Bob_params['B'], 16)) print(f"Intercepted message : {hex(proof(FLAG.encode(), shared_secret))}\n") try: print("Now it's your turn to talk to Bob.") while True: params = loads(input("Send your parameters to Bob : ")) assert int(params['p'], 16) == self.Alice.p assert int(params['g'], 16) == self.Alice.g assert int(params['pub'], 16) != self.Alice.public_key shared_secret = self.Bob.shared_secret(int(params['pub'], 16)) if int(params['pub'], 16) == self.Alice.public_key: print(f"\nIntercepted message : {hex(proof(FLAG.encode(), shared_secret))}\n") else: print(f"\nIntercepted message : {hex(proof(os.urandom(64), shared_secret))}\n") except Exception: print("System error.") sys.exit() signal.alarm(360) if __name__ == "__main__": challenge = Procyon() challenge.start()
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/FwordCTF/2021/crypto/Login/login.py
ctfs/FwordCTF/2021/crypto/Login/login.py
#!/usr/bin/env python3.8 from Crypto.Util.number import bytes_to_long, long_to_bytes, inverse, getPrime, GCD import os, hashlib, sys, signal from time import time FLAG = "FwordCTF{####################################################################}" WELCOME = ''' Welcome to CTFCreators Website. We are a challenges development startup from a team of cybersecurity professionals with diverse backgrounds and skills.''' server_token = os.urandom(16) message_to_sign = b"https://twitter.com/CTFCreators" def H(msg): return hashlib.sha256(msg).digest() def gen_key(): while True: p, q = getPrime(1024), getPrime(1024) N = p * q e = 65537 phi = (p - 1) * (q - 1) if GCD(e, phi) == 1: break d = inverse(e, phi) pinv = inverse(p, q) return N, e, d, pinv def verify(signature, e, N): try: signature = int(signature, 16) msg = bytes_to_long(message_to_sign) verified = pow(signature, e, N) if (verified == msg): return True else: return False except: return False def sign_up(): user = str(input("\nUsername : ")).encode() proof = b'is_admin=false' passwd = H(server_token + b';' + user + b';' + proof) return user.hex(), proof.hex(), passwd.hex() def log_in(username, proof, password): if password == H(server_token + b';' + username + b';' + proof): if b'is_admin=true' in proof: return True return False class Login: def __init__(self): print(WELCOME) def start(self): try: while True: print("\n1- Sign up") print("2- Login") print("3- Leave") c = input("> ") if c == '1': usr, prf, pwd = sign_up() print(f"\nAccount created.\nUsername : {usr}\nPassword : {pwd}\nProof : {prf}") elif c == '2': user = bytes.fromhex(input("\nUsername : ")) passwd = bytes.fromhex(input("Password : ")) proof = bytes.fromhex(input("Proof : ")) if log_in(user, proof, passwd): N, e, d, pinv = gen_key() print(f"Welcome admin, to continue you need to sign this message : '{message_to_sign}'") print(f"e : {hex(e)}") print(f"d : {hex(d)}") print(f"inverse(p, q) : {hex(pinv)}") sig = input("Enter your signature : ") if verify(sig, e, N): print(f"Long time no see. Here is your flag : {FLAG}") else: sys.exit("Disconnect.") else: sys.exit("Username or password is incorrect.") elif c == '3': sys.exit("Goodbye :)") except Exception as e: print(e) sys.exit("System error.") signal.alarm(60) if __name__ == "__main__": challenge = Login() challenge.start()
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/FwordCTF/2021/crypto/Transfer/ed25519.py
ctfs/FwordCTF/2021/crypto/Transfer/ed25519.py
from Crypto.Util.number import long_to_bytes, bytes_to_long, inverse import hashlib b = 256 q = 2**255 - 19 l = 2**252 + 27742317777372353535851937790883648493 d = -121665 * inverse(121666, q) % q I = pow(2, (q-1)//4, q) def H(m): return hashlib.sha512(m).digest() def Hint(m): return bytes_to_long(H(m)) def add(P, Q): x1 = P[0] y1 = P[1] x2 = Q[0] y2 = Q[1] x3 = (x1*y2+x2*y1) * inverse(1+d*x1*x2*y1*y2, q) % q y3 = (y1*y2+x1*x2) * inverse(1-d*x1*x2*y1*y2, q) % q return [x3, y3] def mult(P, e): if e == 0: return [0,1] Q = mult(P, e//2) Q = add(Q, Q) if e & 1: Q = add(Q, P) return Q def isoncurve(P): x = P[0] y = P[1] return (-x**2 + y**2 - 1 - d*x**2*y**2) % q == 0 def recover_x(y): xs = (y**2 - 1) * inverse(d*y**2 + 1, q) % q x = pow(xs, (q+3)//8, q) if (x**2 - xs) % q != 0: x = (x*I) % q if x % 2 != 0: x = q-x return x By = 4 * inverse(5, q) % q Bx = recover_x(By) B = [Bx % q, By % q] def bit(h, i): return (h[i//8] >> (i%8)) & 1 def point_to_bytes(P): x = P[0] y = P[1] bits = [(y >> i) & 1 for i in range(b - 1)] + [x & 1] return ''.join([chr(sum([bits[i * 8 + j] << j for j in range(8)])) for i in range(b//8)]).encode('latin-1') def bytes_to_point(s): y = sum(2**i * bit(s, i) for i in range(0, b-1)) x = recover_x(y) if x & 1 != bit(s, b-1): x = q-x P = [x,y] if not isoncurve(P): raise Exception("Decoding point that is not on curve") return P
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/FwordCTF/2021/crypto/Transfer/transfer.py
ctfs/FwordCTF/2021/crypto/Transfer/transfer.py
#!/usr/bin/env python3.8 from Crypto.Util.number import long_to_bytes, bytes_to_long, inverse from ed25519 import B, l, H, Hint, mult, add, point_to_bytes, bytes_to_point import os, sys, hashlib, hmac, signal FLAG = "FwordCTF{###########################################################}" WELCOME = ''' _____ _____ _| |_______________________| |_ | $ | | $ | | ||| | $$ NATIONAL BANK $$ | ||| | | | | | | [ ] | [ ] [ ] [ ] | [ ] | | |---------------------| | | [ ] | _ _ .---. _ _ | [ ] | | | | | | |_|_| | | | | | |_____|_|_|_|__|_|_|__|_|_|_|_____| /=======\\ ''' sk = os.urandom(32) k = bytes_to_long(H(sk)[:32]) pk = point_to_bytes(mult(B, k)) def sign(m, sk, pk): m = long_to_bytes(m) h = H(sk) a = bytes_to_long(h[:32]) % l r = Hint(h[32:] + hmac.new(m, h, digestmod=hashlib.sha512).digest()) R = mult(B, r) S = (r + Hint(point_to_bytes(R) + pk + m) * a) % l return point_to_bytes(R) + long_to_bytes(S) def verify(s, m, pk): m = long_to_bytes(m) R = bytes_to_point(s[:32]) A = bytes_to_point(pk) S = bytes_to_long(s[32:]) h = Hint(point_to_bytes(R) + pk + m) r1 = mult(B, S) r2 = add(R, mult(A, h)) return r1 == r2 class Transfer: def __init__(self): print(WELCOME) def start(self): try: while True: print("\n1- Transfer") print("2- Verify") print("3- Leave") c = input("> ") if c == '1': money = int(input("\nTransfer some money to your account : ")) assert money > 0 if money >= 2**2048: print("Sorry, I can't sign it for you.") else: print(f"Verification code : {sign(money, sk, pk).hex()}\nPublic Key : {pk.hex()}") if c == '2': m = int(input("\nMoney : ")) s = bytes.fromhex(input("Code : ")) if m < 2**2048: print("Transfer failed.") else: if verify(s, m, pk): print(f"Transfer Succeeded. Here is your flag : {FLAG}") else: sys.exit("Signature incorrect.") elif c == '3': sys.exit("Goodbye :)") except Exception: sys.exit("System error.") signal.alarm(60) if __name__ == "__main__": challenge = Transfer() challenge.start()
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/FwordCTF/2021/web/L33k/app/form.py
ctfs/FwordCTF/2021/web/L33k/app/form.py
from flask_wtf import Form, RecaptchaField from wtforms import StringField, validators class ReportForm(Form): url = StringField('Url To Visit', [validators.DataRequired(), validators.Length(max=255)],render_kw={"placeholder": "http://URL/"}) recaptcha = RecaptchaField()
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/FwordCTF/2021/web/L33k/app/app.py
ctfs/FwordCTF/2021/web/L33k/app/app.py
from flask import Flask,request,render_template,session,redirect from form import ReportForm import os,pymysql import requests,secrets,random,string app= Flask(__name__) app.config["SECRET_KEY"]=os.urandom(15).hex() app.config['RECAPTCHA_USE_SSL']= False app.config['RECAPTCHA_PUBLIC_KEY']= os.getenv("PUBLIC_KEY") app.config['RECAPTCHA_PRIVATE_KEY']=os.getenv("PRIVATE_KEY") app.config['RECAPTCHA_OPTIONS'] = {'theme':'white'} app.config['SESSION_COOKIE_SAMESITE']="None" app.config['SESSION_COOKIE_SECURE']= True def random_string(S): ran = ''.join(random.choices(string.ascii_uppercase + string.digits, k = S)) return ran def get_db(): mydb = pymysql.connect( host="db", user="fword", password=os.getenv("mysql_pass"), database="l33k" ) return mydb.cursor(),mydb def create_paste(paste, username): paste_id = random_string(64) cursor,mydb=get_db() cursor.execute( 'INSERT INTO pastes (id, paste, username) VALUES (%s, %s, %s);', (paste_id, paste, username) ) mydb.commit() return paste_id def get_pastes(username): cursor,mydb=get_db() cursor.execute( 'SELECT id FROM pastes WHERE username = %s', username ) result=cursor.fetchall() mydb.commit() return [paste_id[0] for paste_id in result] def get_paste(paste_id): cursor,mydb=get_db() cursor.execute( 'SELECT paste FROM pastes WHERE id = %s', paste_id ) results=cursor.fetchone() mydb.commit() if len(results) < 1: return 'Paste not found!' return results[0] @app.route("/",methods=["GET"]) def index(): return render_template("index.html") @app.route("/register",methods=["GET","POST"]) def register(): if request.method == "POST": if "username" in session : return redirect("/home") if request.values.get("username") and len(request.values.get("username"))<50 and request.values.get("password"): cursor,mydb = get_db() query = "SELECT * FROM users WHERE username=%s" cursor.execute(query, request.values.get("username")) result = cursor.fetchone() if result is not None: return render_template("register.html",error="Username already exists") try: mydb.commit() cursor.close() cursor,mydb=get_db() query="INSERT INTO users(id,username,password) VALUES(null,%s,%s)" values=(request.values.get("username"),request.values.get("password")) cursor.execute(query,values) mydb.commit() session["username"]=request.values.get("username") cursor.close() return redirect("/home") except Exception: return render_template("register.html",error="Error happened while registering") else: return redirect("/login",302) else: if "username" in session: return redirect("/home") else: return render_template("register.html",error="") @app.route("/home",methods=["GET"]) def home(): if "username" in session : print(get_pastes(session['username'])) return render_template("home.html",username=session["username"],pastes=get_pastes(session['username'])) else: return redirect("/login") @app.route("/login",methods=["GET","POST"]) def login(): if request.method=="GET": if "username" in session: return redirect("/home") else: return render_template("login.html",error="") else: username=request.values.get("username") password=request.values.get("password") if username is None or password is None: return render_template("login.html",error="") else: cursor,mydb = get_db() query = "SELECT * FROM users WHERE username=%s AND password=%s" cursor.execute(query, (username, password)) result = cursor.fetchone() if result is not None: session["username"]=result[1] mydb.commit() cursor.close() return redirect("/home") else: return render_template("login.html",error="Username or password is incorrect") @app.route("/logout",methods=["GET"]) def logout(): session.clear() return redirect("/") @app.route('/create_paste', methods=['POST']) def create(): if 'username' not in session: return redirect('/login') if len(request.form['paste'])<90: paste_id = create_paste( request.form['paste'], session['username'] ) return redirect('/view?id='+paste_id) return redirect('/home') @app.route('/view', methods=['GET']) def view(): paste_id = request.args.get('id') return render_template( 'view.html', paste=get_paste(paste_id) ) @app.route('/search') def search(): if 'username' not in session: return redirect('/login') if 'query' not in request.args: return redirect('/home') query = str(request.args.get('query')) results = ( paste for paste in get_pastes(session['username']) if query in get_paste(paste) ) nonce=random_string(10) try: return render_template("search.html",nonce=nonce,result='Result found: '+next(results),error="") except StopIteration: return render_template("search.html",nonce=nonce,error='No results found.',result="") return redirect('/home') # No vulns here just the bot implementation @app.route("/report",methods=["POST","GET"]) def report(): form= ReportForm() if request.method=="POST": if form.validate_on_submit(): r=requests.get("http://bot?url="+request.form.get("url")) if "successfully" in r.text: return render_template("report.html",form=form,msg="Admin visited your website successfully") else: return render_template("report.html",form=form,msg="An unknown error has occured") else: return render_template("report.html",msg="",form=form) if __name__=="__main__": app.run(host="0.0.0.0",debug=False)
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/FwordCTF/2021/web/Shisui/task/form.py
ctfs/FwordCTF/2021/web/Shisui/task/form.py
from flask_wtf import Form, RecaptchaField from wtforms import StringField, validators class ReportForm(Form): url = StringField('Url To Visit', [validators.DataRequired(), validators.Length(max=255)],render_kw={"placeholder": "http://URL/"}) recaptcha = RecaptchaField()
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/FwordCTF/2021/web/Shisui/task/app.py
ctfs/FwordCTF/2021/web/Shisui/task/app.py
from flask import Flask,request,render_template,session,redirect from flask_wtf.csrf import CSRFProtect from form import ReportForm import os,ipaddress,pymysql import requests app= Flask(__name__) app.config["SECRET_KEY"]=os.urandom(15).hex() app.config['RECAPTCHA_USE_SSL']= False app.config['RECAPTCHA_PUBLIC_KEY']= os.getenv("PUBLIC_KEY") app.config['RECAPTCHA_PRIVATE_KEY']=os.getenv("PRIVATE_KEY") app.config['RECAPTCHA_OPTIONS'] = {'theme':'white'} flag=os.getenv("FLAG") mydb = pymysql.connect( host="db", user="fword", password=os.getenv("mysql_pass"), database="task" ) csrf=CSRFProtect() csrf.init_app(app) def get_db(): return mydb.cursor() @app.route("/",methods=["GET"]) def index(): return render_template("index.html") @app.route("/register",methods=["GET","POST"]) def register(): if request.method == "POST": if "username" in session : return redirect("/home") if request.values.get("username") and len(request.values.get("username"))<50 and request.values.get("password"): cursor = get_db() query = "SELECT * FROM users WHERE username=%s" cursor.execute(query, request.values.get("username")) result = cursor.fetchone() if result is not None: return render_template("register.html",error="Username already exists") try: mydb.commit() cursor.close() cursor=get_db() query="INSERT INTO users(id,username,password) VALUES(null,%s,%s)" values=(request.values.get("username"),request.values.get("password")) cursor.execute(query,values) mydb.commit() session["username"]=request.values.get("username") cursor.close() return redirect("/home") except Exception: return render_template("register.html",error="Error happened while registering") else: return redirect("/login",302) else: if "username" in session: return redirect("/home") else: return render_template("register.html",error="") @app.route("/home",methods=["GET"]) def home(): if "username" in session : return render_template("home.html",username=session["username"]) else: return redirect("/login") @app.route("/login",methods=["GET","POST"]) def login(): if request.method=="GET": if "username" in session: return redirect("/home") else: return render_template("login.html",error="") else: username=request.values.get("username") password=request.values.get("password") if username is None or password is None: return render_template("login.html",error="") else: cursor = get_db() query = "SELECT * FROM users WHERE username=%s AND password=%s" cursor.execute(query, (username, password)) result = cursor.fetchone() if result is not None: session["username"]=result[1] mydb.commit() cursor.close() return redirect("/home") else: return render_template("login.html",error="Username or password is incorrect") @app.route("/logout",methods=["GET"]) def logout(): session.clear() return redirect("/") @app.route("/flag",methods=["GET"]) def flagEndpoint(): if "username" in session: ip=request.remote_addr an_address = ipaddress.ip_address(ip) a_network = ipaddress.ip_network('172.16.0.0/24') if(an_address in a_network): return flag else: return "Damn Hackers Nowadays" else: return redirect("/login") # No vulns here just the bot implementation @app.route("/report",methods=["POST","GET"]) def report(): form= ReportForm() if request.method=="POST": if form.validate_on_submit(): r=requests.get("http://bot?url="+request.form.get("url")) if "successfully" in r.text: return render_template("report.html",form=form,msg="Admin visited your website successfully") else: return render_template("report.html",form=form,msg="An unknown error has occured") else: return render_template("report.html",msg="",form=form) if __name__=="__main__": app.run(host="0.0.0.0",debug=False)
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/FwordCTF/2021/web/SeoFtw/backend/main.py
ctfs/FwordCTF/2021/web/SeoFtw/backend/main.py
from flask import Flask, jsonify,Response, request,g from neo4j import GraphDatabase, basic_auth import os from flask_cors import CORS import ipaddress app = Flask(__name__, static_url_path='/static/') CORS(app) url = os.getenv("NEO4J_URI", "neo4j://neo4j") username = os.getenv("NEO4J_USER", "neo4j") password = os.getenv("NEO4J_PASSWORD", "fword") database = os.getenv("NEO4J_DATABASE", "neo4j") port = os.getenv("PORT", 8080) driver = GraphDatabase.driver(url, auth=basic_auth(username, password),encrypted=False) def get_db(): neo4j_db = driver.session(database=database) return neo4j_db @app.route("/secret") def secret(): ip=request.remote_addr an_address = ipaddress.ip_address(ip) a_network = ipaddress.ip_network('172.16.0.0/24') if(an_address in a_network): db=get_db() result = db.read_transaction(lambda tx: list(tx.run("MATCH (body:Anime) WHERE body.name=\""+request.args.get("name")+"\" RETURN body",{}))) print(result) return jsonify({"result":result}) else: return jsonify({"result":"No No little hacker"}) @app.route("/") def animes(): # implement retrieving best animes from neo4j but now let's just hardcode it x) return jsonify({"animes":["Naruto","HxH","Hyouka","All Isekai Animes :)"]}) if __name__ == '__main__': app.run()
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/FwordCTF/2021/web/SeoFtw/backend/init.py
ctfs/FwordCTF/2021/web/SeoFtw/backend/init.py
import os from neo4j import GraphDatabase, basic_auth url = os.getenv("NEO4J_URI", "neo4j://neo4j") username = os.getenv("NEO4J_USER", "neo4j") password = os.getenv("NEO4J_PASSWORD", "fword") database = os.getenv("NEO4J_DATABASE", "neo4j") driver = GraphDatabase.driver(url, auth=basic_auth(username, password),encrypted=False) def get_db(): neo4j_db = driver.session(database=database) return neo4j_db def init(): db = get_db() result = db.write_transaction(lambda tx: list(tx.run("CREATE (body:Anime) SET body.name = $name RETURN body.name",{"name":"Naruto"}))) print(result) init()
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/FwordCTF/2021/web/SeoFtw_Revenge/backend/main.py
ctfs/FwordCTF/2021/web/SeoFtw_Revenge/backend/main.py
from flask import Flask, jsonify,Response, request,g from neo4j import GraphDatabase, basic_auth import os from flask_cors import CORS import ipaddress app = Flask(__name__, static_url_path='/static/') CORS(app) url = os.getenv("NEO4J_URI", "neo4j://neo4j") username = os.getenv("NEO4J_USER", "neo4j") password = os.getenv("NEO4J_PASSWORD", "fword") database = os.getenv("NEO4J_DATABASE", "neo4j") port = os.getenv("PORT", 8080) driver = GraphDatabase.driver(url, auth=basic_auth(username, password),encrypted=False) def get_db(): neo4j_db = driver.session(database=database) return neo4j_db @app.route("/secret") def secret(): ip=request.remote_addr an_address = ipaddress.ip_address(ip) a_network = ipaddress.ip_network('172.20.0.0/24') if(an_address in a_network): db=get_db() result = db.read_transaction(lambda tx: list(tx.run("MATCH (body:Anime) WHERE body.name=\""+request.args.get("name")+"\" RETURN body",{}))) print(result) return jsonify({"result":result}) else: return jsonify({"result":"No No little hacker"}) @app.route("/") def animes(): # implement retrieving best animes from neo4j but now let's just hardcode it x) return jsonify({"animes":["Naruto","HxH","Hyouka","All Isekai Animes :)"]}) if __name__ == '__main__': app.run()
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/FwordCTF/2021/web/SeoFtw_Revenge/backend/init.py
ctfs/FwordCTF/2021/web/SeoFtw_Revenge/backend/init.py
import os from neo4j import GraphDatabase, basic_auth url = os.getenv("NEO4J_URI", "neo4j://neo4j") username = os.getenv("NEO4J_USER", "neo4j") password = os.getenv("NEO4J_PASSWORD", "fword") database = os.getenv("NEO4J_DATABASE", "neo4j") driver = GraphDatabase.driver(url, auth=basic_auth(username, password),encrypted=False) def get_db(): neo4j_db = driver.session(database=database) return neo4j_db def init(): db = get_db() result = db.write_transaction(lambda tx: list(tx.run("CREATE (body:Anime) SET body.name = $name RETURN body.name",{"name":"Naruto"}))) print(result) init()
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/VolgaCTF/2021/Quals/crypto/Carry/fcsr.py
ctfs/VolgaCTF/2021/Quals/crypto/Carry/fcsr.py
import random import math class FCSR(): def __init__(self, q: int, m: int, a: int): self.m = m self.q = q + 1 self.k = int(math.log(q, 2)) self.a = a @staticmethod def get_i(n: int, i: int) -> int: # right to left return (n & (0b1 << i)) >> i def clock(self) -> int: s = self.m for i in range(1, self.k + 1): s += self.get_i(self.q, i) * self.get_i(self.a, self.k - i) a_k = s % 2 a_0 = self.a & 0b1 self.m = s // 2 self.a = (self.a >> 1) | (a_k << (self.k - 1)) return a_0 def encrypt(self, data: bytes) -> bytes: encrypted = b'' for byte in data: key_byte = 0 for _ in range(8): bit = self.clock() key_byte = (key_byte << 1) | bit encrypted += int.to_bytes(key_byte ^ byte, 1, 'big') return encrypted if __name__ == '__main__': q = 509 k = int(math.log(q + 1, 2)) random.seed() a = random.randint(1, 2 ** k - 1) test = FCSR(q, 0, a)
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/VolgaCTF/2021/Quals/crypto/Carry/task.py
ctfs/VolgaCTF/2021/Quals/crypto/Carry/task.py
from fcsr import FCSR if __name__ == '__main__': q = ??? m = ??? a = ??? generator = FCSR(q, m, a) fd = open('original.png', 'rb') data = fd.read() fd.close() encrypted_png = generator.encrypt(data) fd = open('encrypted_png', 'wb') fd.write(encrypted_png) fd.close()
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/VolgaCTF/2021/Quals/crypto/Knock-Knock/task.py
ctfs/VolgaCTF/2021/Quals/crypto/Knock-Knock/task.py
import os import time class mersenne_rng(object): def __init__(self, seed=5489): self.state = [0] * 624 self.f = 1812433253 self.m = 397 self.u = 11 self.s = 7 self.b = 0x9D2C5680 self.t = 15 self.c = 0xEFC60000 self.l = 18 self.index = 624 self.lower_mask = (1 << 31)-1 self.upper_mask = 1 << 31 # update state self.state[0] = seed for i in range(1, 624): self.state[i] = self.int_32(self.f * (self.state[i-1] ^ (self.state[i-1] >> 30)) + i) def twist(self): for i in range(624): temp = self.int_32((self.state[i] & self.upper_mask) + (self.state[(i+1) % 624] & self.lower_mask)) temp_shift = temp >> 1 if temp % 2 != 0: temp_shift = temp_shift ^ 0x9908b0df self.state[i] = self.state[(i+self.m) % 624] ^ temp_shift self.index = 0 def get_random_number(self): if self.index >= 624: self.twist() y = self.state[self.index] y = y ^ (y >> self.u) y = y ^ ((y << self.s) & self.b) y = y ^ ((y << self.t) & self.c) y = y ^ (y >> self.l) self.index += 1 return self.int_32(y) def int_32(self, number): return int(0xFFFFFFFF & number) def main(): rng = mersenne_rng(???) for i in range(625): number = rng.get_random_number() port1 = (number & (2 ** 32 - 2 ** 16)) >> 16 port2 = number & (2 ** 16 - 1) fd = open('/etc/knockd.conf', 'w') fd.write('[options]\n') fd.write(' UseSyslog\n') fd.write(' interface = enp0s3\n') fd.write('[openSSH]\n') fd.write(' sequence = {0}, {1}\n'.format(port1, port2)) fd.write(' seq_timeout = 5\n') fd.write(' command = /sbin/iptables -A INPUT -s %IP% -p tcp --dport 2222 -j ACCEPT\n') fd.write(' tcpflags = syn\n') fd.write('[closeSSH]\n') fd.write(' sequence = {1}, {0}\n'.format(port1, port2)) fd.write(' seq_timeout = 5\n') fd.write(' command = /sbin/iptables -D INPUT -s %IP% -p tcp --dport 2222 -j ACCEPT\n') fd.write(' tcpflags = syn\n') fd.close() os.system('systemctl restart knockd') assert 'Active: active (running)' in os.popen('systemctl status knockd').read() time.sleep(5) 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/VolgaCTF/2021/Quals/web/flask-admin/routes.py
ctfs/VolgaCTF/2021/Quals/web/flask-admin/routes.py
from app import app, db from flask import render_template, render_template_string, request, flash, redirect, url_for, send_from_directory, make_response, abort import flask_admin as admin from flask_admin import Admin, expose, base from flask_admin.contrib.sqla import ModelView from flask_login import current_user, login_user, logout_user from app.models import User, Role from flask_wtf import FlaskForm from wtforms import StringField, PasswordField, BooleanField, SubmitField, TextAreaField, validators, widgets,fields, SelectMultipleField from wtforms.validators import ValidationError, DataRequired, Email, EqualTo from app.decorators import admin_required, user_required from werkzeug.urls import url_parse import os #-------------------------Admins------------------------- class MyAdmin(admin.AdminIndexView): @expose('/') @admin_required def index(self): return super(MyAdmin, self).index() @expose('/user') @expose('/user/') @admin_required def user(self): return render_template_string('TODO, need create custom view') admin = Admin(app, name='VolgaCTF', template_mode='bootstrap3', index_view=MyAdmin()) admin.add_view(ModelView(User, db.session)) #-------------------------------------------------------- #-------------------------Forms------------------------- class LoginForm(FlaskForm): username = StringField('Username', validators=[DataRequired()],render_kw={"placeholder": "username"}) password = PasswordField('Password', validators=[DataRequired()],render_kw={"placeholder": "password"}) remember_me = BooleanField('Remember Me') submit = SubmitField('Sign In') class RegistrationForm(FlaskForm): username = StringField('Username', validators=[DataRequired()], render_kw={"placeholder": "username"}) email = StringField('Email', validators=[DataRequired(), validators.Length(1, 64), Email()],render_kw={"placeholder": "admin@admin.ru"}) password = PasswordField('Password', validators=[DataRequired()],render_kw={"placeholder": "password"}) password2 = PasswordField( 'Repeat Password', validators=[DataRequired(), EqualTo('password')], render_kw={"placeholder": "password"}) submit = SubmitField('Register') def validate_username(self, field): if User.query.filter_by(username=field.data).first(): raise ValidationError('Username already in use.') def validate_email(self, field): if User.query.filter_by(email=field.data.lower()).first(): raise ValidationError('Email already registered.') #------------------------------------------------------- @app.route('/') def index(): if current_user and current_user.is_authenticated and current_user.role.name == 'Administrator': return os.environ.get('Volga_flag') or 'Error, not found flag' return 'Hello, to get the flag, log in as admin' @app.route('/login', methods=['GET', 'POST']) def login(): form = LoginForm() if form.validate_on_submit(): user = User.query.filter_by(username=form.username.data).first() if user is None or not user.check_password(form.password.data): flash('Invalid username or password') return redirect(url_for('login')) else: # Keep the user info in the session using Flask-Login login_user(user, remember=form.remember_me.data) next_page = request.args.get('next') if not next_page or url_parse(next_page).netloc != '': next_page = url_for('index') return redirect(next_page) return render_template('login.html', title='Sign In', form=form) def permission_check(permission): flag = False try: if current_user.can(permission): return True else: return False except AttributeError: return False return flag @app.route('/logout') def logout(): logout_user() return redirect(url_for('index')) @app.route('/register', methods=['GET', 'POST']) def register(): if current_user.is_authenticated: return redirect(url_for('index')) form = RegistrationForm() if form.validate_on_submit(): user = User(username=form.username.data, email=form.email.data) user.set_password(form.password.data) db.session.add(user) db.session.commit() flash('Congratulations, you are now a registered user!') return redirect(url_for('login')) return render_template('register.html', title='Register', form=form)
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/VolgaCTF/2018/Quals/forbidden/task.py
ctfs/VolgaCTF/2018/Quals/forbidden/task.py
from cryptography.hazmat.backends import default_backend from cryptography.hazmat.primitives.ciphers import ( Cipher, algorithms, modes ) from secret import key def encrypt(iv, key, plaintext, associated_data): encryptor = Cipher( algorithms.AES(key), modes.GCM(iv), backend=default_backend() ).encryptor() encryptor.authenticate_additional_data(associated_data) ciphertext = encryptor.update(plaintext) + encryptor.finalize() return (ciphertext, encryptor.tag) def decrypt(key, associated_data, iv, ciphertext, tag): decryptor = Cipher( algorithms.AES(key), modes.GCM(iv, tag), backend=default_backend() ).decryptor() decryptor.authenticate_additional_data(associated_data) return decryptor.update(ciphertext) + decryptor.finalize() iv = "9313225df88406e555909c5aff5269aa".decode('hex') key = key.decode('hex') ciphertext1, tag1 = encrypt(iv, key, "From: John Doe\nTo: John Doe\nSend 100 BTC", "John Doe") ciphertext2, tag2 = encrypt(iv, key, "From: VolgaCTF\nTo: VolgaCTF\nSend 0.1 BTC", "VolgaCTF") ciphertext3, tag3 = encrypt(iv, key, "From: John Doe\nTo: VolgaCTF\nSend ALL BTC", "John Doe")
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/VolgaCTF/2024/Quals/crypto/Single_R/single_r.py
ctfs/VolgaCTF/2024/Quals/crypto/Single_R/single_r.py
from elliptic_curve import * from secret import flag if __name__ == '__main__': a1 = 0 a3 = 0 p_mod = 116360488056395870563055365435965488415153606823814815615564505122749038681516533 a2 = 7887616263821947558686653170941677360444444810256780630032698031345317313838358 a4 = 96797989774847387504509857489893926962575497188447191529471387551670316582140331 a6 = 90066192920604393834167274731419299471591066103539000277218756197714564706866218 ec = EllipticCurve([a1, a2, a3, a4, a6, p_mod]) P = Point(ec, 42535791201977922181488571956592667532304947801293376812113182276087208310822786, 71152331533310754530614680068197669082982426466348582120767993753731485293472031) # Encrypt flag size = 16 # bytes blocks = [] for i in range(0, len(flag), size): blocks.append(flag[i:i + size]) for i in range(len(blocks)): d = int.from_bytes(blocks[i], 'big') print(f'Q_{i} =', d * P)
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/VolgaCTF/2024/Quals/crypto/PQ/pq.py
ctfs/VolgaCTF/2024/Quals/crypto/PQ/pq.py
from secret import flag import gmpy2 import os e = 65537 def generate_pq(): seed_1 = os.urandom(256) seed_2 = os.urandom(128) p = gmpy2.next_prime(int.from_bytes(seed_1, 'big')) q = gmpy2.next_prime(p + int.from_bytes(seed_2, 'big')) return p, q def crypt(text: bytes, number: int, n: int) -> bytes: encrypted_int = pow(int.from_bytes(text, 'big'), number, n) return int(encrypted_int).to_bytes(n.bit_length() // 8 + 1, 'big').lstrip(b'\x00') def decrypt(ciphertext: bytes, d: int, n: int) -> bytes: decrypted_int = pow(int.from_bytes(ciphertext, 'big'), d, n) return int(decrypted_int).to_bytes(n.bit_length() // 8 + 1, 'big').lstrip(b'\x00') if __name__ == '__main__': p, q = generate_pq() N = p * q print(N) print(crypt(flag, e, N))
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/VolgaCTF/2024/Quals/crypto/QR/qr.py
ctfs/VolgaCTF/2024/Quals/crypto/QR/qr.py
from PIL import Image from secret import flag from lfsr_parameters import register, branches import qrcode QR_FILE = 'qr_flag.png' class LFSR: def __init__(self, register, branches): self.register = register self.branches = branches self.n = len(register) def next_bit(self): ret = self.register[self.n - 1] new = 0 for i in self.branches: new ^= self.register[i - 1] self.register = [new] + self.register[:-1] return ret def qr_text(text: bytes): qr = qrcode.QRCode( version=1, error_correction=qrcode.constants.ERROR_CORRECT_L, box_size=2, border=0, ) qr.add_data(text.decode()) qr.make(fit=True) img = qr.make_image(fill_color='black', back_color='white') img.save(QR_FILE) def encrypt_png(png_path: str, result_path: str): generator = LFSR(register, branches) image = Image.open(png_path) w = image.width h = image.height new_image = Image.new(image.mode, image.size) pixels = image.load() for y in range(h): for x in range(w): pixel = pixels[x, y] // 255 next_bit = generator.next_bit() encrypted = pixel ^ next_bit new_image.putpixel((x, y), encrypted * 255) new_image.save(result_path, image.format) if __name__ == '__main__': qr_text(flag) encrypt_png(QR_FILE, 'qr.png')
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/AmateursCTF/2024/misc/cookie/checker.py
ctfs/AmateursCTF/2024/misc/cookie/checker.py
server_map = open('out.txt').read() player_map = open('player.txt').read() w, l, server_map = server_map.split("/") w2, l2, player_map = player_map.split("/") assert w == w2 and l == l2 and len(server_map) == len(player_map) w, l = int(w), int(l) grid = [[] for i in range(l)] for i in range(len(server_map)//2): idx = slice(2*i, 2*i+2) server, player = server_map[idx], player_map[idx] if server == "^0": assert player_map[2*i:2*i+2] in [";3", "$0"] else: assert player == server grid[i//w].append(player) def neighs(r,c): return sum(grid[r-1+i//3][c-1+i%3] == "$0" for i in range(9)) qq = {"$0": "S", ";3": " ", "g0": "."} for i in range(l): for j in range(w): if grid[i][j] == ";3" and neighs(i,j) == 1: grid[i][j] = "$0" if grid[-4][-4] == "$0": bitstring = "" for i in range(len(server_map)//2): # shut up i know it's inefficient, deal with it. idx = slice(2*i, 2*i+2) if server_map[idx] == "^0": bitstring += str([";3", "$0"].index(player_map[idx])) print("Correct! Your flag is amateursCTF{" + bytes.fromhex(hex(int(bitstring, 2))[2:]).decode() + "}")
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/AmateursCTF/2024/algo/lis/server.py
ctfs/AmateursCTF/2024/algo/lis/server.py
#!/usr/bin/env python3 import secret def check_input(arr): for x in arr: assert 1 <= x <= int(1e9) def check_output(arr, ans): ans.sort() for i in range(len(ans) - 1): assert arr[ans[i]] < arr[ans[i + 1]] def main(): tcs = [] tcs.append(secret.gen(int(9e4), int(1e5))) for _ in range(100): tcs.append(secret.gen(1, 1000)) print(len(tcs)) for arr in tcs: print(*arr) for arr in tcs: check_input(arr) my_ans = secret.solve(arr) your_ans = list(map(int, input().split())) check_output(arr, my_ans) check_output(arr, your_ans) if len(your_ans) < len(my_ans): print("get better lol, maybe worship larry more?") exit(1) print("Good job! Remember to orz larry. Here's your flag", open("flag.txt", "r").read()) if __name__ == "__main__": main()
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/AmateursCTF/2024/rev/dill_with_it/main.py
ctfs/AmateursCTF/2024/rev/dill_with_it/main.py
# Python 3.10.12 from pickle import loads larry = b"\x80\x04ctypes\nFunctionType\n(ctypes\nCodeType\n(I1\nI0\nI0\nI4\nI8\nI67\nCbt\x00\xa0\x01|\x00d\x01\xa1\x02}\x01t\x02|\x01\x83\x01d\x00d\x00d\x02\x85\x03\x19\x00d\x00d\x03\x85\x02\x19\x00}\x00d\x04}\x02t\x03d\x05t\x04|\x00\x83\x01d\x06\x83\x03D\x00]\x11}\x03|\x02t\x05t\x00|\x00|\x03|\x03d\x06\x17\x00\x85\x02\x19\x00d\x07\x83\x02\x83\x017\x00}\x02q\x1d|\x02S\x00(NVbig\nI-1\nI-3\nV\nI0\nI8\nI2\nt(Vint\nVfrom_bytes\nVbin\nVrange\nVlen\nVchr\nt(\x8c\x04\xf0\x9f\x94\xa5\x8c\x04\xf0\x9f\xa4\xab\x8c\x04\xf0\x9f\xa7\x8f\x8c\x04\xf0\x9f\x8e\xb5tVdill-with-it\n\x8c\x04\xf0\x9f\x93\xaeI0\nC\x0c\x00\x01\x0c\x01\x1a\x01\x04\x01\x14\x01 \x01))t\x81cbuiltins\nglobals\n)R\x8c\x04\xf0\x9f\x93\xaet\x81\x940g0\nC\t\x01\xcev\x96.6\x96\xaeF\x85Rg0\nC\x05\x01.\xce\x966\x85R\x93g0\nC\t\x01\xcev\x96.6\x96\xaeF\x85Rg0\nC\x0b\x01\xa6&\xf6\xc6v\xa6tN.\xce\x85R\x93g0\nC\t\x01\xcev\x96.6\x96\xaeF\x85Rg0\nC\x06\x01.v\x96N\x0e\x85R\x93VWhat's the flag? \n\x85R0g0\nC\t\x01\xcev\x96.6\x96\xaeF\x85Rg0\nC\x06\x01.\xae\x0ev\x96\x85R\x93V> \n\x85R\x85R\x85R\x940g0\nC\x07\x01\xb6\xf6&v\x86N\x85Rg0\nC\x05\x01&\xa6\xa6\xce\x85R\x93Vfive nights as freddy\n\x85R0g0\nC\x07\x01\xb6\xf6&v\x86N\x85Rg0\nC\x08\x01\xa66ff\xae\x16\xce\x85R\x93g1\n\x85R0g0\nC\t\x01\xcev\x96.6\x96\xaeF\x85Rg0\nC\x05\x01.\xce\x966\x85R\x93g0\nC\t\x01\xcev\x96.6\x96\xaeF\x85Rg0\nC\x04\x01\x0e\x86\xb6\x85R\x93g0\nC\t\x01\xcev\x96.6\x96\xaeF\x85Rg0\nC\x0c\x01\xfa\xfaN\xf6\x1e\xfa\xfat.v\x96\x85R\x93g0\nC\x07\x01\xb6\xf6&v\x86N\x85Rg0\nC\n\x01\xce\xa6.\x9eF&v\x86N\x85R\x93g0\nC\t\x01\xcev\x96.6\x96\xaeF\x85Rg0\nC\x04\x01v\xa66\x85R\x93g1\n\x85R\x85Rg1\n\x87R\x85R\x940g0\nC\t\x01\xcev\x96.6\x96\xaeF\x85Rg0\nC\x04\x01\x9ev\x86\x85R\x93g0\nC\t\x01\xcev\x96.6\x96\xaeF\x85Rg0\nC\x04\x01\x0e\x86\xb6\x85R\x93g0\nC\t\x01\xcev\x96.6\x96\xaeF\x85Rg0\nC\x0c\x01\xfa\xfaN\xf6\x1e\xfa\xfat.v\x96\x85R\x93(I138\nI13\nI157\nI66\nI68\nI12\nI223\nI147\nI198\nI223\nI92\nI172\nI59\nI56\nI27\nI117\nI173\nI21\nI190\nI210\nI44\nI194\nI23\nI169\nI57\nI136\nI5\nI120\nI106\nI255\nI192\nI98\nI64\nI124\nI59\nI18\nI124\nI97\nI62\nI168\nI181\nI61\nI164\nI22\nI187\nI251\nI110\nI214\nI250\nI218\nI213\nI71\nI206\nI159\nI212\nI169\nI208\nI21\nI236\nlg2\n\x87R\x85R\x940g0\nC\t\x01\xcev\x96.6\x96\xaeF\x85Rg0\nC\x0b\x01\xfa\xfaN\xf6\xfa\xfat.v\x96\x85R\x93g3\ng0\nC\t\x01\xcev\x96.6\x96\xaeF\x85Rg0\nC\x0b\x01\xfa\xfa\xa6v\xfa\xfat.v\x96\x85R\x93g0\nC\t\x01\xcev\x96.6\x96\xaeF\x85Rg0\nC\x04\x01v\xa66\x85R\x93g2\n\x85RI59\n\x86R\x86R\x940g0\nC\t\x01\xcev\x96.6\x96\xaeF\x85Rg0\nC\x11\x01\xfa\xfa\xb6\xa6.\x96.\xa6\xe6\xfa\xfat.\xce\x966\x85R\x93(VLooks like you got it!\nVNah, try again.\nlg4\n\x86R." print(loads(larry))
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/AmateursCTF/2024/rev/typo/mian.py
ctfs/AmateursCTF/2024/rev/typo/mian.py
import random as RrRrRrrrRrRRrrRRrRRrrRr RrRrRrrrRrRRrrRRrRRrRrr = int('1665663c', 20) RrRrRrrrRrRRrrRRrRRrrRr.seed(RrRrRrrrRrRRrrRRrRRrRrr) arRRrrRRrRRrRRRrRrRRrRr = bytearray(open('flag.txt', 'rb').read()) arRRrrRrrRRrRRRrRrRRrRr = '\r'r'\r''r''\\r'r'\\r\r'r'r''r''\\r'r'r\r'r'r\\r''r'r'r''r''\\r'r'\\r\r'r'r''r''\\r'r'rr\r''\r''r''r\\'r'\r''\r''r\\\r'r'r\r''\rr' arRRrrRRrRRrRrRrRrRRrRr = [ b'arRRrrRRrRRrRRrRr', b'aRrRrrRRrRr', b'arRRrrRRrRRrRr', b'arRRrRrRRrRr', b'arRRrRRrRrrRRrRR' b'arRRrrRRrRRRrRRrRr', b'arRRrrRRrRRRrRr', b'arRRrrRRrRRRrRr' b'arRrRrRrRRRrrRrrrR', ] arRRRrRRrRRrRRRrRrRRrRr = lambda aRrRrRrrrRrRRrrRRrRrrRr: bytearray([arRrrrRRrRRrRRRrRrRrrRr + 1 for arRrrrRRrRRrRRRrRrRrrRr in aRrRrRrrrRrRRrrRRrRrrRr]) arRRrrRRrRRrRRRrRrRrrRr = lambda aRrRrRrrrRrRRrrRRrRrrRr: bytearray([arRrrrRRrRRrRRRrRrRrrRr - 1 for arRrrrRRrRRrRRRrRrRrrRr in aRrRrRrrrRrRRrrRRrRrrRr]) def arRRrrRRrRRrRrRRrRrrRrRr(hex): for id in range(0, len(hex) - 1, 2): hex[id], hex[id + 1] = hex[id + 1], hex[id] for list in range(1, len(hex) - 1, 2): hex[list], hex[list + 1] = hex[list + 1], hex[list] return hex arRRRRRRrRRrRRRrRrRrrRr = [arRRrrRRrRRrRrRRrRrrRrRr, arRRRrRRrRRrRRRrRrRRrRr, arRRrrRRrRRrRRRrRrRrrRr] arRRRRRRrRRrRRRrRrRrrRr = [RrRrRrrrRrRRrrRRrRRrrRr.choice(arRRRRRRrRRrRRRrRrRrrRr) for arRrrrRRrRRrRRRrRrRrrRr in range(128)] def RrRrRrrrRrRRrrRRrRRrrRr(arr, ar): for r in ar: arr = arRRRRRRrRRrRRRrRrRrrRr[r](arr) return arr def arRRrrRRrRRrRrRRrRrrRrRr(arr, ar): ar = int(ar.hex(), 17) for r in arr: ar += int(r, 35) return bytes.fromhex(hex(ar)[2:]) arrRRrrrrRRrRRRrRrRRRRr = RrRrRrrrRrRRrrRRrRRrrRr(arRRrrRRrRRrRRRrRrRRrRr, arRRrrRrrRRrRRRrRrRRrRr.encode()) arrRRrrrrRRrRRRrRrRRRRr = arRRrrRRrRRrRrRRrRrrRrRr(arRRrrRRrRRrRrRrRrRRrRr, arrRRrrrrRRrRRRrRrRRRRr) print(arrRRrrrrRRrRRRrRrRRRRr.hex())
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/AmateursCTF/2024/osint/cherry_blossoms/main.py
ctfs/AmateursCTF/2024/osint/cherry_blossoms/main.py
#!/usr/bin/env python3 # modified from HSCTF 10 grader import json with open("locations.json") as f: locations = json.load(f) wrong = False for i, coords in enumerate(locations, start=1): x2, y2 = coords x, y = map(float, input(f"Please enter the lat and long of the location: ").replace(",","").split(" ")) # increase if people have issues if abs(x2 - x) < 0.0010 and abs(y2 - y) < 0.0010: print("Correct! You have successfully determined the position of the camera.") else: print("Wrong! Try again after paying attention to the picture.") wrong = True if not wrong: with open("flag.txt") as f: print("Great job, the flag is ",f.read().strip()) else: print("Better luck next time ʕ·ᴥ·ʔ")
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/AmateursCTF/2024/jail/javajail2/main.py
ctfs/AmateursCTF/2024/jail/javajail2/main.py
#!/usr/local/bin/python3 import subprocess BANNED = ['import', 'throws', 'new'] BANNED += ['File', 'Scanner', 'Buffered', 'Process', 'Runtime', 'ScriptEngine', 'Print', 'Stream', 'Field', 'javax'] BANNED += ['flag.txt', '^', '|', '&', '\'', '\\', '[]', ':'] print(''' Welcome to the Java Jail. Have fun coding in Java! ''') print('''Enter in your code below (will be written to Main.java), end with --EOF--\n''') code = '' while True: line = input() if line == '--EOF--': break code += line + '\n' for word in BANNED: if word in code: print('Not allowed') exit() with open('/tmp/Main.java', 'w') as f: f.write(code) print("Here's your output:") output = subprocess.run(['java', '-Xmx648M', '-Xss32M', '/tmp/Main.java'], capture_output=True) print(output.stdout.decode('utf-8'))
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/AmateursCTF/2024/jail/sansomega/shell.py
ctfs/AmateursCTF/2024/jail/sansomega/shell.py
#!/usr/local/bin/python3 import subprocess BANNED = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz\\"\'`:{}[]' def shell(): while True: cmd = input('$ ') if any(c in BANNED for c in cmd): print('Banned characters detected') exit(1) if len(cmd) >= 20: print('Command too long') exit(1) proc = subprocess.Popen( ["/bin/sh", "-c", cmd], stdout=subprocess.PIPE, stderr=subprocess.STDOUT) print(proc.stdout.read().decode('utf-8'), end='') if __name__ == '__main__': shell()
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/AmateursCTF/2024/jail/zig_jail_2/chal.py
ctfs/AmateursCTF/2024/jail/zig_jail_2/chal.py
#!/usr/local/bin/python3 from tempfile import NamedTemporaryFile, TemporaryDirectory from subprocess import run from os import urandom from string import ascii_letters, digits, punctuation whitelist = [ "import", "bitSizeOf", "sizeOf", "compileError", "TypeOf", "popCount", "clz", "ctz", "as", "intCast", "truncate", "enumFromInt", "floatCast", "floatFromInt", "intFromBool", "intFromFloat", "intFromEnum", "intFromError", "bitCast" ] character_whitelist = " \n\r" + ascii_letters + digits + punctuation def err(code: int, msg: str): print(msg) exit(code) def check(leftover: str): for allow in whitelist: if leftover.startswith(allow): return err(1, f"bad directive found: {leftover}") def round(): size = 1337 + urandom(1)[0] victim = list(urandom(size)) with NamedTemporaryFile("w", suffix=".zig") as zig: repl = str(victim)[1:-1] repl = f"var input = [_]u8{{ {repl} }};" repl = src.replace("var input = [0]u8{};", repl, 1) zig.write(repl) zig.flush() with TemporaryDirectory() as cache: print("compiling...") handle = run(["/app/zig/zig", "build-exe", "-fno-emit-bin", "--cache-dir", cache, "--global-cache-dir", cache, zig.name], capture_output=True) if handle.returncode != 0 and handle.returncode != 1: err(1, "stop crashing my compiler") output = f"{handle.stderr}\n{handle.stdout}" victim = bytes(sorted(victim)).hex() if victim in output: return else: err(1, "no") limit = 4444 src = "" print("code: ") while True: line = ascii(input())[1:-1] assert all([ch in character_whitelist for ch in line]), "character not in whitelist" if line.startswith("EOF"): break src += line + "\n" if len(src) >= limit: err(1, f"input too long by {len(src) - limit} bytes") for i in range(len(src)): if src[i] == '@': check(src[i+1:]) round() print(open("flag.txt", "r").read())
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/AmateursCTF/2024/jail/zig_jail_1/chal.py
ctfs/AmateursCTF/2024/jail/zig_jail_1/chal.py
#!/usr/local/bin/python3 from tempfile import NamedTemporaryFile, TemporaryDirectory from os import urandom, system, mkdir from string import printable from pathlib import Path from shutil import copy blacklist = [ "cInclude", "embedFile", ] character_whitelist = printable def err(code: int, msg: str): print(msg) exit(code) def check(leftover: str): for disallow in blacklist: if leftover.startswith(disallow): err(1, "blacklisted directive found") def round(): with TemporaryDirectory() as cache: cache = Path(cache) with NamedTemporaryFile("w", suffix=".zig", dir=cache) as zig: zig.write(src) zig.flush() cmd = f"/app/zig/zig build-exe -fno-emit-bin -fsingle-threaded -fno-lto -fno-PIC --no-gc-sections --cache-dir {cache} --global-cache-dir /tmp {zig.name}" system(cmd) limit = 1337 src = "" print("code: ") while True: line = input() assert all([ch in character_whitelist for ch in line]), "character not in whitelist" if line.startswith("EOF"): break src += line + "\n" overflow = len(src) - limit if overflow > 0: suffix = "s" if overflow > 1 else "" err(1, f"input too long by {overflow} byte{suffix}") for i in range(len(src)): if src[i] == '@': check(src[i+1:]) round()
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/AmateursCTF/2024/jail/pyquinejailgolf/main.py
ctfs/AmateursCTF/2024/jail/pyquinejailgolf/main.py
#!/usr/local/bin/python3 import time from tempfile import TemporaryDirectory with TemporaryDirectory() as workdir: __import__('os').chdir(workdir) __import__('os').mkdir('runtime') print("Enter a reverse quine. It must print its source code backwards (including any trailing newlines).") print("It must be non-empty and contain 0 quotation marks or dunders. All ascii btw. oh and no builtins.") print("To prove you wrote it yourself, it must contain the string 'pyquinejailgolf', and be ==343 chars.") print("Well...I'm not sure how you're supposed to write a quine without print statements. u can have em.") print("~~~~~~~~~~~~~~~~~~~~~~~~~~~ Type <END> to terminate the program input ~~~~~~~~~~~~~~~~~~~~~~~~~~~") prog = [] while (x := input(">>> ")) != "<END>": prog.append(x) program = "\n".join(i for i in prog) assert x == "<END>", "what did you do this time." assert all(ord(i) < 128 for i in program), "i don't speak foreign languages." assert all(i not in program for i in ['"', "'", '_']), "who uses strings anyway? it's not like quines require strings." assert program != "", "scuse me, just cleaning out the garbage." assert "pyquinejailgolf" in program, "are you sure you wrote this program yourself?" assert len(program) == 343 import sys stdout = sys.stdout with open('runtime/trash.txt', 'w+') as sys.stdout: goal = time.time_ns() + 5000000000 try: with open('runtime/external_run.py', 'w+') as f: f.write(f""" with open('runtime/output.txt', 'w+') as __import__('sys').stdout: {program = } safe_builtins = {{}} for i in dir(__builtins__): if i[0] not in __import__('string').ascii_lowercase: safe_builtins[i] = eval(i) safe_builtins['print'] = print new_builtins = {{'__builtins__':safe_builtins}} try:exec(program, new_builtins, new_builtins) except:pass""") __import__('os').system('timeout 2.5 /usr/local/bin/python3 runtime/external_run.py') except: pass time.sleep(max(0, (goal - time.time_ns())/1e9)) sys.stdout = stdout with open('runtime/output.txt') as f: if (c := f.read()[::-1]) == program: print("good jorb") else: exit("bad") with open('/app/flag.txt') as f: print(f.read())
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/AmateursCTF/2024/jail/javajail1/main.py
ctfs/AmateursCTF/2024/jail/javajail1/main.py
#!/usr/local/bin/python3 import subprocess BANNED = ['import', 'class', 'Main', '{', '}'] # good luck getting anything to run print(''' Welcome to the Java Jail. Have fun coding in Java! ''') print('''Enter in your code below (will be written to Main.java), end with --EOF--\n''') code = '' while True: line = input() if line == '--EOF--': break code += line + '\n' for word in BANNED: if word in code: print('Not allowed') exit() with open('/tmp/Main.java', 'w') as f: f.write(code) print("Here's your output:") output = subprocess.run(['java', '-Xmx648M', '-Xss32M', '/tmp/Main.java'], capture_output=True) print(output.stdout.decode('utf-8'))
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/AmateursCTF/2024/crypto/unsuspicious_rsa/unsuspicious-rsa.py
ctfs/AmateursCTF/2024/crypto/unsuspicious_rsa/unsuspicious-rsa.py
from Crypto.Util.number import * def nextPrime(p, n): p += (n - p) % n p += 1 iters = 0 while not isPrime(p): p += n return p def factorial(n): if n == 0: return 1 return factorial(n-1) * n flag = bytes_to_long(open('flag.txt', 'rb').read().strip()) p = getPrime(512) q = nextPrime(p, factorial(90)) N = p * q e = 65537 c = pow(flag, e, N) print(N, e, c)
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/AmateursCTF/2024/crypto/decryption_as_a_service/decryption-as-a-service.py
ctfs/AmateursCTF/2024/crypto/decryption_as_a_service/decryption-as-a-service.py
#!/usr/local/bin/python3 from Crypto.Util.number import * from math import isqrt flag = bytes_to_long(open('flag.txt', 'rb').read()) p, q = getPrime(1024), getPrime(1024) N = p * q e = getPrime(64) d = pow(e, -1, N - p - q + 1) encrypted_flag = pow(flag, e, N) print(f"{encrypted_flag = }") try: for i in range(10): c = int(input("message? ")) if isqrt(N) < c < N: if c == encrypted_flag or c == (N - encrypted_flag): print("sorry, that looks like the flag") continue print(hex(pow(c, d, N))[2:]) else: print("please pick a number which I can (easily) check does not look like the flag.") except: exit() print("ok bye")
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/AmateursCTF/2024/crypto/drunk_lcg/drunk-lcg.py
ctfs/AmateursCTF/2024/crypto/drunk_lcg/drunk-lcg.py
#!/usr/local/bin/python3 import sys from random import randint from Crypto.Util.number import * m = 150094635296999121 flag = bytes_to_long(open('flag.txt', 'rb').read()) upper = 1 << (flag.bit_length() + 1) bl = upper.bit_length()//4 def print(a): sys.stdout.write(hex(a)[2:].zfill(bl)) sys.stdout.write('\n') def lcg(): a = randint(0, m) c = randint(0, m) seed = randint(0, m) while True: seed = (a * seed + c) % m yield seed def randbelow(n): a = next(x) while a < n: a *= m a += next(x) return a % n def trial(): global x x = iter(lcg()) print(flag ^ randbelow(upper)) print(flag ^ randbelow(upper)) trial() sys.stdout.flush()
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/AmateursCTF/2024/crypto/less_suspicious_rsa/less-suspicious-rsa.py
ctfs/AmateursCTF/2024/crypto/less_suspicious_rsa/less-suspicious-rsa.py
from Crypto.Util.number import * def nextPrime(p, n): p += (n - p) % n p += 1 iters = 0 while not isPrime(p): p += n return p def factorial(n): if n == 0: return 1 return factorial(n-1) * n flag = bytes_to_long(open('flag.txt', 'rb').read().strip()) p = getPrime(512) q = nextPrime(p, factorial(90)) p = getPrime(512) N = p * q e = 65537 c = pow(flag, e, N) print(N, e, c)
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/AmateursCTF/2024/crypto/pilfer_techies/pilfer-techies.py
ctfs/AmateursCTF/2024/crypto/pilfer_techies/pilfer-techies.py
#!/usr/local/bin/python3 import hmac from os import urandom def strxor(a: bytes, b: bytes): return bytes([x ^ y for x, y in zip(a, b)]) class Cipher: def __init__(self, key: bytes): self.key = key self.block_size = 16 self.rounds = 256 def F(self, x: bytes): return hmac.new(self.key, x, 'md5').digest()[:15] def encrypt(self, plaintext: bytes): plaintext = plaintext.ljust(((len(plaintext)-1)//self.block_size)*16+16, b'\x00') ciphertext = b'' for i in range(0, len(plaintext), self.block_size): block = plaintext[i:i+self.block_size] idx = 0 for _ in range(self.rounds): L, R = block[:idx]+block[idx+1:], block[idx:idx+1] L, R = strxor(L, self.F(R)), R block = L + R idx = R[0] % self.block_size ciphertext += block return ciphertext.hex() key = urandom(16) cipher = Cipher(key) flag = open('flag.txt', 'rb').read().strip() print("pilfer techies") while True: choice = input("1. Encrypt a message\n2. Get encrypted flag\n3. Exit\n> ").strip() if choice == '1': pt = input("Enter your message in hex: ").strip() pt = bytes.fromhex(pt) print(cipher.encrypt(pt)) elif choice == '2': print(cipher.encrypt(flag)) else: break print("Goodbye!")
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/AmateursCTF/2024/crypto/faked_onion/faked-onion.py
ctfs/AmateursCTF/2024/crypto/faked_onion/faked-onion.py
#!/usr/local/bin/python3 import hmac from os import urandom def strxor(a: bytes, b: bytes): return bytes([x ^ y for x, y in zip(a, b)]) class Cipher: def __init__(self, key: bytes): self.key = key self.block_size = 16 self.rounds = 1 def F(self, x: bytes): return hmac.new(self.key, x, 'md5').digest()[:15] def encrypt(self, plaintext: bytes): plaintext = plaintext.ljust(self.block_size, b'\x00') ciphertext = b'' for i in range(0, len(plaintext), self.block_size): block = plaintext[i:i+self.block_size] for _ in range(self.rounds): L, R = block[:-1], block[-1:] L, R = R, strxor(L, self.F(R)) block = L + R ciphertext += block return ciphertext key = urandom(16) cipher = Cipher(key) flag = open('flag.txt', 'rb').read().strip() print("faked onion") while True: choice = input("1. Encrypt a message\n2. Get encrypted flag\n3. Exit\n> ").strip() if choice == '1': pt = input("Enter your message in hex: ").strip() pt = bytes.fromhex(pt) print(cipher.encrypt(pt).hex()) elif choice == '2': print(cipher.encrypt(flag).hex()) else: break print("Goodbye!")
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/AmateursCTF/2024/crypto/ecsuses/ecsuses.py
ctfs/AmateursCTF/2024/crypto/ecsuses/ecsuses.py
tr = eval(open('tr').read()) flagtxt = open('flagtxt.py').read() exec(flagtxt) with open('flagtxt', 'w') as f: f.write(flagtxt.translate(tr))
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/AmateursCTF/2024/web/one_shot/app.py
ctfs/AmateursCTF/2024/web/one_shot/app.py
from flask import Flask, request, make_response import sqlite3 import os import re app = Flask(__name__) db = sqlite3.connect(":memory:", check_same_thread=False) flag = open("flag.txt").read() @app.route("/") def home(): return """ <h1>You have one shot.</h1> <form action="/new_session" method="POST"><input type="submit" value="New Session"></form> """ @app.route("/new_session", methods=["POST"]) def new_session(): id = os.urandom(8).hex() db.execute(f"CREATE TABLE table_{id} (password TEXT, searched INTEGER)") db.execute(f"INSERT INTO table_{id} VALUES ('{os.urandom(16).hex()}', 0)") res = make_response(f""" <h2>Fragments scattered... Maybe a search will help?</h2> <form action="/search" method="POST"> <input type="hidden" name="id" value="{id}"> <input type="text" name="query" value=""> <input type="submit" value="Find"> </form> """) res.status = 201 return res @app.route("/search", methods=["POST"]) def search(): id = request.form["id"] if not re.match("[1234567890abcdef]{16}", id): return "invalid id" searched = db.execute(f"SELECT searched FROM table_{id}").fetchone()[0] if searched: return "you've used your shot." db.execute(f"UPDATE table_{id} SET searched = 1") query = db.execute(f"SELECT password FROM table_{id} WHERE password LIKE '%{request.form['query']}%'") return f""" <h2>Your results:</h2> <ul> {"".join([f"<li>{row[0][0] + '*' * (len(row[0]) - 1)}</li>" for row in query.fetchall()])} </ul> <h3>Ready to make your guess?</h3> <form action="/guess" method="POST"> <input type="hidden" name="id" value="{id}"> <input type="text" name="password" placehoder="Password"> <input type="submit" value="Guess"> </form> """ @app.route("/guess", methods=["POST"]) def guess(): id = request.form["id"] if not re.match("[1234567890abcdef]{16}", id): return "invalid id" result = db.execute(f"SELECT password FROM table_{id} WHERE password = ?", (request.form['password'],)).fetchone() if result != None: return flag db.execute(f"DROP TABLE table_{id}") return "You failed. <a href='/'>Go back</a>" @app.errorhandler(500) def ise(error): original = getattr(error, "original_exception", None) if type(original) == sqlite3.OperationalError and "no such table" in repr(original): return "that table is gone. <a href='/'>Go back</a>" return "Internal server error" if __name__ == "__main__": app.run(host="0.0.0.0", port=8080)
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/AmateursCTF/2023/misc/Censorship_Lite/main.py
ctfs/AmateursCTF/2023/misc/Censorship_Lite/main.py
#!/usr/local/bin/python from flag import flag for _ in [flag]: while True: try: code = ascii(input("Give code: ")) if any([i in code for i in "\lite0123456789"]): raise ValueError("invalid input") exec(eval(code)) except Exception as err: print(err)
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/AmateursCTF/2023/misc/q-CHeSHires_game/template.py
ctfs/AmateursCTF/2023/misc/q-CHeSHires_game/template.py
from base64 import b64encode from qiskit import QuantumCircuit # alice_x_0 alice_x_0 = QuantumCircuit(2, 1) ## define your circuit here # alice_x_1 alice_x_1 = QuantumCircuit(2, 1) ## define your circuit here # bob_y_0 bob_y_0 = QuantumCircuit(2, 1) ## define your circuit here # bob_y_1 bob_y_1 = QuantumCircuit(2, 1) ## define your circuit here strategies = [alice_x_0, alice_x_1, bob_y_0, bob_y_1] strategies = [b64encode(qc.qasm().encode()) for qc in strategies] # send strategies to server from pwn import remote r = remote('amt.rs', 31011) for strategy in strategies: r.sendline(strategy) print(r.recvall())
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/AmateursCTF/2023/misc/q-CHeSHires_game/q-cheshires-game.py
ctfs/AmateursCTF/2023/misc/q-CHeSHires_game/q-cheshires-game.py
#!/usr/local/bin/python from base64 import b64decode from tqdm import tqdm from random import randint, shuffle from qiskit import QuantumCircuit, Aer, transpile backend = Aer.get_backend('qasm_simulator') import sys def simulate_round(alice_strategy, bob_strategy): qc = QuantumCircuit(2, 1) qc.h(0) qc.cx(0, 1) qc.barrier() # shuffle the strategies so that the players don't get to decide who goes first strategies = [alice_strategy, bob_strategy] shuffle(strategies) for gate in strategies[0]: qc.append(gate, range(2)) for gate in strategies[1]: qc.append(gate, range(2)) qc.measure_all() try: qc = transpile(qc, backend) res = backend.run(qc, shots=1, memory=True).result().get_memory()[0] a, b = res[0], res[1] except Exception as e: print("Error running your circuit!") print(e) exit(0) return a, b def run_rounds(alice_strategies, bob_strategies, rounds=1000): wins = 0 for _ in tqdm(range(rounds), file=sys.stdout): x, y = (randint(0, 1) for _ in range(2)) alice_strategy = alice_strategies[x] bob_strategy = bob_strategies[y] a, b = simulate_round(alice_strategy, bob_strategy) if (a != b) == (x & y): wins += 1 return wins / rounds def get_circuit(name, bit, value): print(f"Enter in your {name} strategy for {bit} = {value} as an OpenQASM file: ", end="") qasm_str = input() try: qasm_str = b64decode(qasm_str).decode() except: print("Error decoding base64!") exit(0) if "reset" in qasm_str: print("Leave those qubits alone!") exit(0) try: circuit = QuantumCircuit.from_qasm_str(qasm_str) circuit.remove_final_measurements(inplace=True) except: # thanks uiuctf orgs print("Error processing OpenQASM file! Try decomposing your circuit into basis gates using `transpile`.") exit(0) if circuit.num_qubits != 2: print("Your circuit must have exactly two qubits!") exit(0) return circuit TARGET = 0.875 # I want you to be BETTER than optimal ;) def main(): print(f"Welcome to Cheshire's Quantum Game. You'll play as both Alice and Bob, and your goal is to win at least {TARGET * 100}% of the time.") print() print("This game as presented to two players, Alice and Bob, who each return a single bit after being asked a \'question\', which is a single bit as well.") print("To win, Alice and Bob must return bits a and b such that a XOR b == x AND y, where x and y are the bits they are given.") print("Alice only sees x, and Bob only sees y, and neither can communicate with each other.") print("In this simulation you'll be playing as both Alice and Bob.") print("Not to worry though, I've given you a free entangled qubit to be nice!") print("-" * 72) alice_strategies = [get_circuit("Alice", "x", i) for i in range(2)] bob_strategies = [get_circuit("Bob", "y", i) for i in range(2)] win_rate = run_rounds(alice_strategies, bob_strategies) if win_rate >= TARGET: print( f"Congratulations! You won {win_rate * 100}% of the time, which is greater than {TARGET * 100}%!") print("Here's your flag:") print(open("flag.txt").read()) else: print( f"Sorry, you only won {win_rate * 100}% of the time, which is less than {TARGET * 100}%.") 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/AmateursCTF/2023/misc/Censorship/main.py
ctfs/AmateursCTF/2023/misc/Censorship/main.py
#!/usr/local/bin/python from flag import flag for _ in [flag]: while True: try: code = ascii(input("Give code: ")) if "flag" in code or "e" in code or "t" in code or "\\" in code: raise ValueError("invalid input") exec(eval(code)) except Exception as err: print(err)
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/AmateursCTF/2023/misc/q-warmup/q-warmup.py
ctfs/AmateursCTF/2023/misc/q-warmup/q-warmup.py
from qiskit import QuantumCircuit from qiskit import Aer, execute backend = Aer.get_backend('qasm_simulator') def encode(bits): circuit = QuantumCircuit(8) for i, bit in enumerate(bits): if bit == '1': circuit.x(i) for i in range(7, 0, -1): circuit.cx(i, i-1) circuit.measure_all() job = execute(circuit, backend, shots=1) result = job.result() result = list(result.get_counts().keys())[0][::-1] ret = int(bits, 2) ^ int(result, 2) return ret flag = b"amateursCTF{REDACTED}" enc = b"" for i in flag: enc += bytes([encode(bin(i)[2:].zfill(8))]) print(enc, enc.hex()) # b'\xbe\xb6\xbeXF\xa6\\\xa2\x82\x98\x84R\xb4 X\xb0N\xb4\xbaj^f\xd8\xb4X\xa6\xb6j\xd8\xbc \xa6XjX\xb0\xde\xa2j\xd8Xj~HHV' beb6be5846a65ca282988452b42058b04eb4ba6a5e66d8b458a6b66ad8bc20a6586a58b0dea26ad8586a7e484856
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/AmateursCTF/2023/algo/whiteboard/main.py
ctfs/AmateursCTF/2023/algo/whiteboard/main.py
#!/usr/local/bin/python from flag import flag import random def my_very_cool_function(x): return pow(x, 2141, 998244353) successes = 0 prefixes = ["1", "4", "1", "2"] suffixes = ["0533", "0708", "1133"] # skittles1412 birthday Orz... May has 30 days ofc (he claims 12/03 but i call cap) def gen_goal(): goal = random.choice(prefixes) for i in range(140): while (x := random.choice(prefixes)) == goal[-1] and random.randint(1, 5) != 1: pass goal += x goal += random.choice(suffixes) return int(goal) def run_testcase(): goal = gen_goal() print(f"Goal: {goal}") whiteboard = {my_very_cool_function(167289653), my_very_cool_function(68041722)} # stO HBD BRYAN GAO Orz print(whiteboard) for _ in range(1412): try: a, b = map(int, input("Numbers to combine? ").split()) assert a in whiteboard and b in whiteboard x = 2 * a - b whiteboard.add(x) if x == goal: print("Good job") return True except: print("smh bad input *die*") exit("Exiting...") return False for i in range(5): ok = run_testcase() assert ok print("happy birthday to you too!") print(flag)
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false