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/CyberSecurityRumble/2022/web/Numbaz/generator/server.py
ctfs/CyberSecurityRumble/2022/web/Numbaz/generator/server.py
import os from werkzeug.utils import secure_filename from flask import Flask, redirect, url_for, render_template, request, flash, Response import hashlib import requests import base64 import shutil import time import string import random import json from subprocess import run, PIPE def randomString(stringLength=8): letters = string.ascii_lowercase return ''.join(random.choice(letters) for i in range(stringLength)) app = Flask(__name__) # Sends a generated report on the local file system to an endpoint @app.route('/send_report', methods=['GET']) def get_report(): report_id = request.args.get("report_id") target_url = request.args.get("target") session_id = request.args.get("session_id") report_file = f'output/{report_id}' if not os.path.isfile(report_file): return Response("ERROR", status=500) data = open(report_file, "r").read() requests.post(target_url, data=data, params={"report_id":report_id, "session_id":session_id}) return Response("OK", status=200) # Generates a report using the provided input arguments @app.route('/generate_report', methods=['POST']) def generate(): data = json.loads(request.data) year_start = data["startyear"] year_end = data["endyear"] country = data["country"].replace("\"", "").replace("'", "") report_id = data["report_id"] session_id = data["session_id"] template = open("data/template.xsl", "r").read() template = template.replace("%%COUNTRY%%", country).replace("%%STARTYEAR%%", year_start).replace("%%ENDYEAR%%", year_end) try: p = run(['./Xalan', '-o', f'output/{report_id}', 'data/population.xml', '-'], stdout=PIPE, input=template, encoding='ascii', timeout=3) if (p.returncode != 0): return Response("ERROR", status=500) except: return Response("ERROR", status=500) return Response("OK", status=200) 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/CyberSecurityRumble/2022/web/Numbaz/frontend/server.py
ctfs/CyberSecurityRumble/2022/web/Numbaz/frontend/server.py
import os from werkzeug.utils import secure_filename from flask import Flask, redirect, url_for, render_template, request, flash import hashlib import requests import base64 import shutil import time import string import random import re import time from flask import Response, session from flask_session import Session from xml.sax.saxutils import escape HOST_GENERATOR = os.getenv('HOST_GENERATOR', 'localhost') HOST_RENDERER = os.getenv('HOST_RENDERER', 'localhost') def randomString(stringLength=8): letters = string.ascii_lowercase + string.digits return ''.join(random.choice(letters) for i in range(stringLength)) app = Flask(__name__) SESSION_TYPE = 'filesystem' SESSION_FILE_THRESHOLD = 1000 app.secret_key = randomString(20) app.config['SESSION_TYPE'] = 'filesystem' sess = Session() sess.init_app(app) # Index page @app.route('/') def index(): if not session.get('id'): session["id"] = randomString(20) return render_template("index.html", content="") # GET: Shows the user interface to generate reports # POST: Triggers the report generation in the backend @app.route('/generate', methods=['GET', 'POST']) def generate(): if not session.get('id'): session["id"] = randomString(20) if request.method == 'POST': year_start = request.form["startyear"] year_end = request.form["endyear"] country = escape(request.form["country"].replace("\"", "").replace("'", "")) if int(re.match(r'\d+',year_start)[0]) < 1960 or int(re.match(r'\d+',year_start)[0]) > 2021: return render_template("error.html", errormessage="Invalid starting year!") if int(re.match(r'\d+',year_end)[0]) < 1960 or int(re.match(r'\d+',year_end)[0]) > 2021: return render_template("error.html", errormessage="Invalid ending year!") report_id = randomString() resp = requests.post(f"http://{HOST_GENERATOR}:5001/generate_report", json={"report_id":report_id, "startyear":year_start, "endyear":year_end, "country":country, "session_id":session["id"]}) if resp.status_code == 200: # Report has been generated, request the redirect to the PDF renderer resp = requests.get(f"http://{HOST_GENERATOR}:5001/send_report", params={"report_id":report_id, "session_id":session["id"], "target": f"http://{HOST_RENDERER}:5002/render_report"}) # Now we wait for the renderer # Dirty fix: Flask runs as HTTP, but is served as HTTPS in the browser # Hence we have to perform the redirect via JS return Response(f"""<html><body><script> setTimeout(function () {{ window.location.href = "/generating?report_id={report_id}&session_id={session["id"]}"; }}, 1000); //will call the function after 2 secs. </script></body></html>""", 200) return render_template("generating.html", report_id=report_id, session_id=session["id"], errormessage="Failed to generate report") else: return render_template("generate.html", content="") # Staging page to wait, till the report is generated # Redirects automatically to /generated @app.route('/generating', methods=['GET', 'POST']) def generating(): report_id = request.args.get("report_id") session_id = request.args.get("session_id") return render_template("generating.html", report_id=report_id, session_id=session_id) # Retrieves a generated report by id from the backend @app.route('/generated', methods=['GET', 'POST']) def generated(): session_id = request.args.get("session_id") report_id = request.args.get("report_id") resp = requests.get(f"http://{HOST_RENDERER}:5002/get_report", params={"report_id":report_id, "session_id":session_id}) if resp.status_code == 404: return render_template("generated.html", report_id=report_id, errormessage="Report not found. Maybe something went wrong") return Response(resp.content, "200", mimetype="application/pdf") 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/CyberSecurityRumble/2022/web/RobertIsAGangsta/app/Userdb.py
ctfs/CyberSecurityRumble/2022/web/RobertIsAGangsta/app/Userdb.py
import json from uuid import uuid4 as uuid import hashlib import os class UserDB: def __init__(self, filename): self.db_file = "data/" + filename if not os.path.exists(self.db_file): with open(self.db_file, 'w'): pass with open(self.db_file, "r+") as f: if len(f.read()) == 0: f.write("{}") self.db = self.get_data() def get_data(self): with open(self.db_file, "r") as f: return json.loads(f.read()) def get_db(self): return self.db def save_db(self): with open(self.db_file, "w") as f: f.write(json.dumps(self.db)) self.db = self.get_data() def login_user(self, email, password): user = self.db.get(email) if user is None: return None if user["password"] == hashlib.sha256(password.encode()).hexdigest(): self.db[email]["cookie"] = str(uuid()) self.save_db() return self.db[email]["cookie"] return None def authenticate_user(self, cookie): for k in self.db: dbcookie = self.db[k]["cookie"] if dbcookie != "" and cookie == dbcookie: return self.db[k] return None def is_admin(self, email): user = self.db.get(email) if user is None: return False # TODO check userid type etc return user["userid"] > 90000000 def add_user(self, email, userid, password): user = { "email": email, "userid": userid, "password": hashlib.sha256(password.encode()).hexdigest(), "cookie": "", } if self.db.get(email) is None: for k in self.db: if self.db[k]["userid"] == userid: # print("user id already exists. skipping") return False else: return False self.db[email] = user self.save_db() return True def delete_user(self, email): if self.db.get(email) is None: print("user doesnt exist") return False del self.db[email] self.save_db() return True def change_user_mail(self, old, new): user = self.db.get(old) if user is None: return False if self.db.get(new) is not None: print("account exists") return False user["email"] = new del self.db[old] self.db[new] = user self.save_db() return True
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/CyberSecurityRumble/2022/web/RobertIsAGangsta/app/app.py
ctfs/CyberSecurityRumble/2022/web/RobertIsAGangsta/app/app.py
from re import U import secrets from flask import ( Flask, request, make_response, render_template, redirect, url_for, session, ) import json from uuid import uuid4 as uuid import random import time from Userdb import UserDB import subprocess # Look Ma, I wrote my own web app! app = Flask( __name__, static_url_path="/static", static_folder="static", ) app.secret_key = b"abcd" ## Helper Functions def check_activation_code(activation_code): # no bruteforce time.sleep(20) if "{:0>4}".format(random.randint(0, 10000)) in activation_code: return True else: return False def error_msg(msg): resp = {"return": "Error", "message": msg} return json.dumps(resp) def success_msg(msg): resp = {"return": "Success", "message": msg} return json.dumps(resp) userdb_cache = {} def get_userdb(): if "userdb" not in session: userdb_id = secrets.token_hex(10) session["userdb"] = userdb_id else: userdb_id = session["userdb"] if userdb_id not in userdb_cache: userdb_cache[userdb_id] = UserDB(userdb_id + ".json") userdb_cache[userdb_id].add_user("admin@cscg.de", 9_001_0001, str(uuid())) return userdb_cache[userdb_id] def get_user(request): auth = request.cookies.get("auth") if auth is not None: return get_userdb().authenticate_user(auth) return None def validate_command(string): return len(string) == 4 and string.index("date") == 0 ## API Functions def api_create_account(data, user): dt = data["data"] email = dt["email"] password = dt["password"] groupid = dt["groupid"] userid = dt["userid"] activation = dt["activation"] assert len(groupid) == 3 assert len(userid) == 4 userid = json.loads("1" + groupid + userid) if not check_activation_code(activation): return error_msg("Activation Code Wrong") # print("activation passed") if get_userdb().add_user(email, userid, password): # print("user created") return success_msg("User Created") else: return error_msg("User creation failed") def api_login(data, user): if user is not None: return error_msg("already logged in") c = get_userdb().login_user(data["data"]["email"], data["data"]["password"]) if c is None: return error_msg("Wrong User or Password") resp = make_response(success_msg("logged in")) resp.set_cookie("auth", c) return resp def api_logout(data, user): if user is None: return error_msg("Already Logged Out") resp = make_response(success_msg("logged out")) resp.delete_cookie("auth") return resp def api_error(data, user): return error_msg("General Error") def api_admin(data, user): if user is None: return error_msg("Not logged in") is_admin = get_userdb().is_admin(user["email"]) if not is_admin: return error_msg("User is not Admin") cmd = data["data"]["cmd"] # currently only "date" is supported if validate_command(cmd): out = subprocess.run(cmd, stdout=subprocess.PIPE, stderr=subprocess.STDOUT) return success_msg(out.stdout.decode()) return error_msg("invalid command") actions = { "create_account": api_create_account, "login": api_login, "logout": api_logout, "error": api_error, "admin": api_admin, } ## Routes @app.route("/json_api", methods=["GET", "POST"]) def json_api(): user = get_user(request) if request.method == "POST": data = json.loads(request.get_data().decode()) # print(data) action = data.get("action") if action is None: return "missing action" return actions.get(action, api_error)(data, user) else: return json.dumps(user) @app.route("/") def home(): user = get_user(request) if user is not None: return redirect(url_for("user")) return render_template("home.html", title="Home", user=None) @app.route("/login") def login(): user = get_user(request) if user is not None: return redirect(url_for("user")) return render_template("login.html", title="Login", user=None) @app.route("/signup") def signup(): user = get_user(request) if user is not None: return redirect(url_for("user")) return render_template("signup.html", title="Signup", user=None) @app.route("/admin") def admin(): user = get_user(request) if user is None: return redirect(url_for("login")) # print(user) is_admin = get_userdb().is_admin(user["email"]) if not is_admin: return redirect(url_for("user")) return render_template("admin.html", title="Admin", user=user) @app.route("/user") def user(): user = get_user(request) if user is None: return redirect(url_for("login")) # print(user) is_admin = get_userdb().is_admin(user["email"]) return render_template("user.html", title="User Page", user=user, is_admin=is_admin) @app.route("/usersettings") def settings(): user = get_user(request) if user is None: return redirect(url_for("login")) return render_template("usersettings.html", title="User Settings", user=user) app.run(host="0.0.0.0", port=1024, debug=False)
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/L3HCTF/2021/crypto/EzECDSA/task.py
ctfs/L3HCTF/2021/crypto/EzECDSA/task.py
import gmpy2 import hashlib import socketserver import os,random,string from hashlib import sha256 from Crypto.Util.number import bytes_to_long from SECRET import FLAG p = 0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f a = 0 b = 7 xG = 0x79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798 yG = 0x483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8 n = 0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141 h = 1 zero = (0,0) G = (xG, yG) kbits = 8 def add(p1, p2): if p1 == zero: return p2 if p2 == zero: return p1 (p1x,p1y),(p2x,p2y) = p1,p2 if p1x == p2x and (p1y != p2y or p1y == 0): return zero if p1x == p2x: tmp = (3 * p1x * p1x + a) * gmpy2.invert(2 * p1y , p) % p else: tmp = (p2y - p1y) * gmpy2.invert(p2x - p1x , p) % p x = (tmp * tmp - p1x - p2x) % p y = (tmp * (p1x - x) - p1y) % p return (int(x),int(y)) def mul(n, p): r = zero tmp = p while 0 < n: if n & 1 == 1: r = add(r,tmp) n, tmp = n >> 1, add(tmp,tmp) return r def sha256(raw_message): return hashlib.sha256(raw_message).hexdigest().encode() def _sha256(raw_message): return bytes_to_long(hashlib.sha256(raw_message).digest()) class Task(socketserver.BaseRequestHandler): def proof_of_work(self): random.seed(os.urandom(8)) proof = ''.join([random.choice(string.ascii_letters+string.digits) for _ in range(20)]).encode() digest = sha256(proof) self.request.send(b"sha256(XXXX+%b) == %b\n" % (proof[4:],digest)) self.request.send(b'Give me XXXX:') x = self.request.recv(10) x = x.strip() if len(x) != 4 or sha256(x+proof[4:]) != digest: return False return True def recvall(self, sz): try: r = sz res = "" while r > 0: res += self.request.recv(r).decode() if res.endswith("\n"): r = 0 else: r = sz - len(res) res = res.strip() except: res = "" return res.strip("\n") def dosend(self, msg): self.request.sendall(msg) def handle(self): try: if not self.proof_of_work(): return dA = random.randrange(n) Public_key = mul(dA, G) self.dosend(str(Public_key).encode() + b'\n') for _ in range(100): self.dosend(b"Give me your message:\n") msg = self.recvall(100) hash = _sha256(msg.encode()) k = random.randrange(n) kp = k % (2 ** kbits) P = mul(k, G) r_sig = P[0] k_inv = gmpy2.invert(k, n) s_sig = (k_inv * (hash + r_sig * dA)) % n self.dosend(b"r = " + str(r_sig).encode() + b'\n') self.dosend(b"s = " + str(s_sig).encode() + b'\n') self.dosend(b"kp = " + str(kp).encode() + b'\n') self.dosend(b"hash = " + str(hash).encode() + b'\n') self.dosend(b"Give me dA\n") private_key = self.recvall(300) if int(private_key) == dA: self.dosend(FLAG) except: self.dosend(b"Something error!\n") self.request.close() class ForkingServer(socketserver.ForkingTCPServer, socketserver.TCPServer): pass if __name__ == "__main__": HOST, PORT = '0.0.0.0', 23333 server = ForkingServer((HOST, PORT), Task) server.allow_reuse_address = True server.serve_forever()
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/L3HCTF/2024/misc/End_of_Programming/backend/src/main.py
ctfs/L3HCTF/2024/misc/End_of_Programming/backend/src/main.py
from flask import Flask,request,render_template import hashlib from client.Python.client import JudgeServerClient, JudgeServerClientError,cpp_lang_config import os import requests import re flag = os.environ.get('FLAG') client = JudgeServerClient(server_base_url='http://judge_server:8080',token='2q3r4t5y6u7i8o9p0sacuhu32') OPENAI_API_KEY = os.environ.get('OPENAI_API_KEY') OPENAI_API_URL = os.environ.get('OPENAI_API_URL') ENGINE_NAME = os.environ.get('ENGINE_NAME') RESULT_SUCCESS = 0 RESULT_WRONG_ANSWER = -1 RESULT_CPU_TIME_LIMIT_EXCEEDED = 1 RESULT_REAL_TIME_LIMIT_EXCEEDED = 2 RESULT_MEMORY_LIMIT_EXCEEDED = 3 RESULT_RUNTIME_ERROR = 4 RESULT_SYSTEM_ERROR = 5 result_str_map = { RESULT_SUCCESS: 'Accepted', RESULT_WRONG_ANSWER: 'Wrong Answer', RESULT_CPU_TIME_LIMIT_EXCEEDED: 'CPU Time Limit Exceeded', RESULT_REAL_TIME_LIMIT_EXCEEDED: 'Real Time Limit Exceeded', RESULT_MEMORY_LIMIT_EXCEEDED: 'Memory Limit Exceeded', RESULT_RUNTIME_ERROR: 'Runtime Error', RESULT_SYSTEM_ERROR: 'System Error' } cpp_source = ''' #include <iostream> using namespace std; int main(){ int a,b; cin >> a >> b; cout << a+b << endl; return 0; } ''' app = Flask(__name__) # ChatGPT def get_output(text): prompt = f"{text}" response = requests.post( OPENAI_API_URL, headers={"Authorization": f"Bearer {OPENAI_API_KEY}"}, json={"model": ENGINE_NAME, "messages": [{"role":"user","content":prompt}], "max_tokens": 400, "temperature": 0} ) try: print(response.json()) cpp_code = response.json().get('choices')[0].get('message').get('content').strip() except: print(response.text) return None if cpp_code: return cpp_code return None # check whether prompt containts code def is_code_present(text): # 向 GPT-3.5 发送请求,询问是否包含代码或伪代码 prompt = f"Is there any code or pseudocode in the following text? Answer with 'yes' or 'no' only.\n\n{text}" response = requests.post( OPENAI_API_URL, headers={"Authorization": f"Bearer {OPENAI_API_KEY}"}, json={"model": ENGINE_NAME, "messages": [{"role":"user","content":prompt}], "max_tokens": 3, "temperature": 0} ) try: reply = response.json().get('choices')[0].get('message').get('content').strip().lower() except Exception as e: print(response.text) raise e return reply == "yes" @app.route('/') def index(): return render_template('index.html') @app.route('/problem', methods=['GET']) def problem(): return open('templates/problem_cn.html').read() @app.route('/problem_en', methods=['GET']) def problem_en(): return open('templates/problem_en.html').read() @app.route('/submit', methods=['POST']) def submit(): prompt = str(request.form.get('prompt')) prompt = prompt[:2048] try: if is_code_present(prompt): return 'Invalid input: code detected.' except Exception as e: print(e.__repr__()) return 'API Error' output = get_output(prompt) if output == None: return 'Code extraction or evaluation failed.' response = '' response += '-------------------------\n' response += 'ChatGPT Output:\n{chatgpt_output}\n'.format(chatgpt_output=output) response += '-------------------------\n' out_code = re.findall(r'```cpp([\s\S]+)```', output) if len(out_code) == 0: response += 'No code found in the output' return response out_code = out_code[0] print(out_code) judge_ret = client.judge(out_code,cpp_lang_config, max_cpu_time=1000, max_memory=1024 * 1024 * 128,test_case_id='pal',output=False) if judge_ret['err'] != None: response += 'Error: ' + judge_ret['err'] print(judge_ret) return response is_good_job = all([i['result'] == RESULT_SUCCESS for i in judge_ret['data']]) for i in judge_ret['data']: response += 'Test Case:{test_case}\t{result}\n'.format(test_case=i['test_case'],result=result_str_map[i['result']]) if is_good_job: response += 'Flag is {flag}'.format(flag=flag) return response
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/L3HCTF/2024/misc/End_of_Programming/backend/src/client/__init__.py
ctfs/L3HCTF/2024/misc/End_of_Programming/backend/src/client/__init__.py
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/L3HCTF/2024/misc/End_of_Programming/backend/src/client/Python/client.py
ctfs/L3HCTF/2024/misc/End_of_Programming/backend/src/client/Python/client.py
import hashlib import json import requests from .languages import c_lang_config, cpp_lang_config, java_lang_config, c_lang_spj_config, c_lang_spj_compile, py2_lang_config, py3_lang_config, go_lang_config, php_lang_config, js_lang_config class JudgeServerClientError(Exception): pass class JudgeServerClient(object): def __init__(self, token, server_base_url): self.token = hashlib.sha256(token.encode("utf-8")).hexdigest() self.server_base_url = server_base_url.rstrip("/") def _request(self, url, data=None): kwargs = {"headers": {"X-Judge-Server-Token": self.token, "Content-Type": "application/json"}} if data: kwargs["data"] = json.dumps(data) try: return requests.post(url, **kwargs).json() except Exception as e: raise JudgeServerClientError(str(e)) def ping(self): return self._request(self.server_base_url + "/ping") def judge(self, src, language_config, max_cpu_time, max_memory, test_case_id=None, test_case=None, spj_version=None, spj_config=None, spj_compile_config=None, spj_src=None, output=False): if not (test_case or test_case_id) or (test_case and test_case_id): raise ValueError("invalid parameter") data = {"language_config": language_config, "src": src, "max_cpu_time": max_cpu_time, "max_memory": max_memory, "test_case_id": test_case_id, "test_case": test_case, "spj_version": spj_version, "spj_config": spj_config, "spj_compile_config": spj_compile_config, "spj_src": spj_src, "output": output} return self._request(self.server_base_url + "/judge", data=data) def compile_spj(self, src, spj_version, spj_compile_config): data = {"src": src, "spj_version": spj_version, "spj_compile_config": spj_compile_config} return self._request(self.server_base_url + "/compile_spj", data=data) if __name__ == "__main__": token = "YOUR_TOKEN_HERE" c_src = r""" #include <stdio.h> int main(){ int a, b; scanf("%d%d", &a, &b); printf("%d\n", a+b); return 0; } """ c_spj_src = r""" #include <stdio.h> int main(){ return 1; } """ cpp_src = r""" #include <iostream> using namespace std; int main() { int a,b; cin >> a >> b; cout << a+b << endl; return 0; } """ java_src = r""" import java.util.Scanner; public class Main{ public static void main(String[] args){ Scanner in=new Scanner(System.in); int a=in.nextInt(); int b=in.nextInt(); System.out.println(a + b); } } """ py2_src = """s = raw_input() s1 = s.split(" ") print int(s1[0]) + int(s1[1])""" py3_src = """s = input() s1 = s.split(" ") print(int(s1[0]) + int(s1[1]))""" go_src = """package main import "fmt" func main() { a := 0 b := 0 fmt.Scanf("%d %d", &a, &b) fmt.Printf("%d", a + b) }""" php_src = """<?php fscanf(STDIN, "%d %d", $a, $b); print($a + $b);""" js_src = """const readline = require('readline'); const rl = readline.createInterface({ input: process.stdin }); rl.on('line', (input) => { if (input === '') { return rl.close(); } const [a, b] = input.split(' ').map(Number) console.log(a + b); });""" client = JudgeServerClient(token=token, server_base_url="http://127.0.0.1:12358") print("ping") print(client.ping(), "\n\n") print("compile_spj") print(client.compile_spj(src=c_spj_src, spj_version="2", spj_compile_config=c_lang_spj_compile ), "\n\n") print("c_judge") print(client.judge(src=c_src, language_config=c_lang_config, max_cpu_time=1000, max_memory=1024 * 1024 * 128, test_case_id="normal", output=True), "\n\n") print("cpp_judge") print(client.judge(src=cpp_src, language_config=cpp_lang_config, max_cpu_time=1000, max_memory=1024 * 1024 * 128, test_case_id="normal"), "\n\n") print("java_judge") print(client.judge(src=java_src, language_config=java_lang_config, max_cpu_time=1000, max_memory=256 * 1024 * 1024, test_case_id="normal"), "\n\n") print("c_spj_judge") print(client.judge(src=c_src, language_config=c_lang_config, max_cpu_time=1000, max_memory=1024 * 1024 * 128, test_case_id="spj", spj_version="3", spj_config=c_lang_spj_config, spj_compile_config=c_lang_spj_compile, spj_src=c_spj_src), "\n\n") print("py2_judge") print(client.judge(src=py2_src, language_config=py2_lang_config, max_cpu_time=1000, max_memory=128 * 1024 * 1024, test_case_id="normal", output=True), "\n\n") print("py3_judge") print(client.judge(src=py3_src, language_config=py3_lang_config, max_cpu_time=1000, max_memory=128 * 1024 * 1024, test_case_id="normal", output=True), "\n\n") print("go_judge") print(client.judge(src=go_src, language_config=go_lang_config, max_cpu_time=1000, max_memory=128 * 1024 * 1024, test_case_id="normal", output=True), "\n\n") print("php_judge") print(client.judge(src=php_src, language_config=php_lang_config, max_cpu_time=1000, max_memory=128 * 1024 * 1024, test_case_id="normal", output=True), "\n\n") print("js_judge") print(client.judge(src=js_src, language_config=js_lang_config, max_cpu_time=1000, max_memory=128 * 1024 * 1024, test_case_id="normal", output=True), "\n\n") print("c_dynamic_input_judge") print(client.judge(src=c_src, language_config=c_lang_config, max_cpu_time=1000, max_memory=1024 * 1024 * 128, test_case=[{"input": "1 2\n", "output": "3"}, {"input": "1 4\n", "output": "3"}], output=True), "\n\n")
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/L3HCTF/2024/misc/End_of_Programming/backend/src/client/Python/languages.py
ctfs/L3HCTF/2024/misc/End_of_Programming/backend/src/client/Python/languages.py
# coding=utf-8 from __future__ import unicode_literals default_env = ["LANG=en_US.UTF-8", "LANGUAGE=en_US:en", "LC_ALL=en_US.UTF-8"] c_lang_config = { "compile": { "src_name": "main.c", "exe_name": "main", "max_cpu_time": 3000, "max_real_time": 5000, "max_memory": 128 * 1024 * 1024, "compile_command": "/usr/bin/gcc -DONLINE_JUDGE -O2 -w -fmax-errors=3 -std=c99 {src_path} -lm -o {exe_path}", }, "run": { "command": "{exe_path}", "seccomp_rule": "c_cpp", "env": default_env } } c_lang_spj_compile = { "src_name": "spj-{spj_version}.c", "exe_name": "spj-{spj_version}", "max_cpu_time": 3000, "max_real_time": 5000, "max_memory": 1024 * 1024 * 1024, "compile_command": "/usr/bin/gcc -DONLINE_JUDGE -O2 -w -fmax-errors=3 -std=c99 {src_path} -lm -o {exe_path}" } c_lang_spj_config = { "exe_name": "spj-{spj_version}", "command": "{exe_path} {in_file_path} {user_out_file_path}", "seccomp_rule": "c_cpp" } cpp_lang_config = { "compile": { "src_name": "main.cpp", "exe_name": "main", "max_cpu_time": 3000, "max_real_time": 5000, "max_memory": 128 * 1024 * 1024, "compile_command": "/usr/bin/g++ -DONLINE_JUDGE -O2 -w -fmax-errors=3 -std=c++11 {src_path} -lm -o {exe_path}", }, "run": { "command": "{exe_path}", "seccomp_rule": "c_cpp", "env": default_env } } java_lang_config = { "name": "java", "compile": { "src_name": "Main.java", "exe_name": "Main", "max_cpu_time": 3000, "max_real_time": 5000, "max_memory": -1, "compile_command": "/usr/bin/javac {src_path} -d {exe_dir} -encoding UTF8" }, "run": { "command": "/usr/bin/java -cp {exe_dir} -XX:MaxRAM={max_memory}k -Djava.security.manager -Dfile.encoding=UTF-8 -Djava.security.policy==/etc/java_policy -Djava.awt.headless=true Main", "seccomp_rule": None, "env": default_env, "memory_limit_check_only": 1 } } py2_lang_config = { "compile": { "src_name": "solution.py", "exe_name": "solution.pyc", "max_cpu_time": 3000, "max_real_time": 5000, "max_memory": 128 * 1024 * 1024, "compile_command": "/usr/bin/python -m py_compile {src_path}", }, "run": { "command": "/usr/bin/python {exe_path}", "seccomp_rule": "general", "env": default_env } } py3_lang_config = { "compile": { "src_name": "solution.py", "exe_name": "__pycache__/solution.cpython-36.pyc", "max_cpu_time": 3000, "max_real_time": 5000, "max_memory": 128 * 1024 * 1024, "compile_command": "/usr/bin/python3 -m py_compile {src_path}", }, "run": { "command": "/usr/bin/python3 {exe_path}", "seccomp_rule": "general", "env": ["PYTHONIOENCODING=UTF-8"] + default_env } } go_lang_config = { "compile": { "src_name": "main.go", "exe_name": "main", "max_cpu_time": 3000, "max_real_time": 5000, "max_memory": 1024 * 1024 * 1024, "compile_command": "/usr/bin/go build -o {exe_path} {src_path}", "env": ["GOCACHE=/tmp", "GOPATH=/tmp/go"] }, "run": { "command": "{exe_path}", "seccomp_rule": "", # 降低内存占用 "env": ["GODEBUG=madvdontneed=1", "GOCACHE=off"] + default_env, "memory_limit_check_only": 1 } } php_lang_config = { "run": { "exe_name": "solution.php", "command": "/usr/bin/php {exe_path}", "seccomp_rule": "", "env": default_env, "memory_limit_check_only": 1 } } js_lang_config = { "run": { "exe_name": "solution.js", "command": "/usr/bin/node {exe_path}", "seccomp_rule": "", "env": ["NO_COLOR=true"] + default_env, "memory_limit_check_only": 1 } }
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/L3HCTF/2024/misc/End_of_Programming/backend/src/client/Python/__init__.py
ctfs/L3HCTF/2024/misc/End_of_Programming/backend/src/client/Python/__init__.py
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/L3HCTF/2024/misc/End_of_Programming/data/tests/test_case/pal/1.py
ctfs/L3HCTF/2024/misc/End_of_Programming/data/tests/test_case/pal/1.py
import hashlib all_tests = {} for i in range(1,2): item_info = {} name = f'{i}' inp = open(f'{name}.in','rb').read() outp = open(f'{name}.out','rb').read() item_info["input_name"] = f'{name}.in' item_info["input_size"] = len(inp) item_info["output_name"] = f'{name}.out' item_info["output_md5"] = hashlib.md5(outp).hexdigest() item_info["output_size"] = len(outp) item_info["stripped_output_md5"] = hashlib.md5(outp.rstrip()).hexdigest() all_tests[str(i)] = item_info info = { "test_case_number": 2, "spj": False, "test_cases": all_tests } import json with open("info", "w") as f: json.dump(info, f)
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/L3HCTF/2024/crypto/babySPN_revenge/task.py
ctfs/L3HCTF/2024/crypto/babySPN_revenge/task.py
import random import time from secret import flag, K from hashlib import sha256 from Crypto.Util.number import * def bin_to_list(r, bit_len): list = [r >> d & 1 for d in range(bit_len)][::-1] return list def list_to_int(list): return int("".join(str(i) for i in list), 2) Pbox=[1, 5, 9, 13, 2, 6, 10, 14, 3, 7, 11, 15, 4, 8, 12, 16] Sbox=[14, 13, 11, 0, 2, 1, 4, 15, 7, 10, 8, 5, 9, 12, 3, 6] def round_func(X,r,K): kstart=4*r - 4 XX = [0] * 16 for i in range(16): XX[i] = X[i] ^ K[kstart+i] for i in range(4): value = list_to_int(XX[4*i:4*i+4]) s_value = Sbox[value] s_list = bin_to_list(s_value, 4) XX[4*i],XX[4*i+1],XX[4*i+2],XX[4*i+3] = s_list[0],s_list[1],s_list[2],s_list[3] Y=[0] * 16 for i in range(16): Y[Pbox[i]-1]=XX[i] return Y def enc(X,K): Y = round_func(X,1,K) Y = round_func(Y,2,K) Y = round_func(Y,3,K) Y = round_func(Y,4,K) kstart=4*5 - 4 for i in range(16): Y[i] ^= K[kstart+i] return Y assert len(K) == 32 for i in K: assert i == 0 or i == 1 hash_value = sha256(long_to_bytes(list_to_int(K))).hexdigest() print(hash_value) assert flag[7:-1] == hash_value XX = [0]*16 for i in range(4): XX[i*4] = 1 print(enc(XX,K)) XX[i*4] = 0 # [0, 0, 1, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 1] # [0, 1, 1, 1, 0, 0, 0, 1, 1, 1, 1, 1, 0, 1, 1, 0] # [0, 1, 1, 1, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 1] # [0, 1, 1, 1, 1, 0, 1, 0, 1, 0, 0, 0, 0, 1, 1, 1]
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/L3HCTF/2024/crypto/babySPN/task.py
ctfs/L3HCTF/2024/crypto/babySPN/task.py
import random import time from secret import flag from hashlib import sha256 from Crypto.Util.number import * def bin_to_list(r, bit_len): list = [r >> d & 1 for d in range(bit_len)][::-1] return list def list_to_int(list): return int("".join(str(i) for i in list), 2) Pbox=[1, 5, 9, 13, 2, 6, 10, 14, 3, 7, 11, 15, 4, 8, 12, 16] Sbox=[14, 13, 11, 0, 2, 1, 4, 15, 7, 10, 8, 5, 9, 12, 3, 6] def round_func(X,r,K): kstart=4*r - 4 XX = [0] * 16 for i in range(16): XX[i] = X[i] ^ K[kstart+i] for i in range(4): value = list_to_int(XX[4*i:4*i+4]) s_value = Sbox[value] s_list = bin_to_list(s_value, 4) XX[4*i],XX[4*i+1],XX[4*i+2],XX[4*i+3] = s_list[0],s_list[1],s_list[2],s_list[3] Y=[0] * 16 for i in range(16): Y[Pbox[i]-1]=XX[i] return Y def enc(X,K): Y = round_func(X,1,K) Y = round_func(Y,2,K) Y = round_func(Y,3,K) Y = round_func(Y,4,K) kstart=4*5 - 4 for i in range(16): Y[i] ^= K[kstart+i] return Y K = [0, 1, 1, 0, 1, 0, 1, 0, 1, 1, 0, 1, 1, 0, 0, 1, 0, 1, 0, 1, 0, 0, 0, 0, 1, 0, 1, 0, 0, 0, 1, 0] assert len(K) == 32 for i in K: assert i == 0 or i == 1 hash_value = sha256(long_to_bytes(list_to_int(K))).hexdigest() assert flag[7:-1] == hash_value XX = [0]*16 for i in range(4): XX[i*4] = 1 print(enc(XX,K)) XX[i*4] = 0 # [0, 1, 1, 0, 1, 1, 1, 0, 0, 1, 1, 0, 1, 1, 0, 0] # [1, 1, 1, 0, 0, 1, 1, 1, 0, 0, 1, 0, 1, 0, 1, 1] # [0, 1, 1, 1, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 1] # [1, 1, 1, 1, 1, 0, 0, 1, 0, 1, 0, 0, 0, 1, 1, 0]
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/L3HCTF/2024/crypto/can_you_guess_me/can_you_guess_me_3.py
ctfs/L3HCTF/2024/crypto/can_you_guess_me/can_you_guess_me_3.py
from Crypto.Util.number import * from random import * from secret import flag q = getPrime(128) n = 5 T = 2**48 E = 2**32 t = [randint(1,T) for i in range(n)] e = [randint(1,E) for i in range(n)] a = [(t[i] * flag - e[i]) % q for i in range(n)] print('q =', q) print('a =', a) flag = "L3HSEC{" + hex(flag)[2:] + "}" print('flag =', flag) # q = 313199526393254794805899275326380083313 # a = [258948702106389340127909287396807150259, 130878573261697415793888397911168583971, 287085364108707601156242002650192970665, 172240654236516299340495055728541554805, 206056586779420225992168537876290239524]
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/L3HCTF/2024/web/intractable_problem/files/web.py
ctfs/L3HCTF/2024/web/intractable_problem/files/web.py
import flask import time import random import os import subprocess codes="" with open("oj.py","r") as f: codes=f.read() flag="" with open("/flag","r") as f: flag=f.read() app = flask.Flask(__name__) @app.route('/') def index(): return flask.render_template('ui.html') @app.route('/judge', methods=['POST']) def judge(): code = flask.request.json['code'].replace("def factorization(n: string) -> tuple[int]:","def factorization(n):") correctstr = ''.join(random.sample('zyxwvutsrqponmlkjihgfedcba', 20)) wrongstr = ''.join(random.sample('zyxwvutsrqponmlkjihgfedcba', 20)) print(correctstr,wrongstr) code=codes.replace("Correct",correctstr).replace("Wrong",wrongstr).replace("<<codehere>>",code) filename = "upload/"+str(time.time()) + str(random.randint(0, 1000000)) with open(filename + '.py', 'w') as f: f.write(code) try: result = subprocess.run(['python3', filename + '.py'], stdout=subprocess.PIPE, timeout=5).stdout.decode("utf-8") os.remove(filename + '.py') print(result) if(result.endswith(correctstr+"!")): return flask.jsonify("Correct!flag is "+flag) else: return flask.jsonify("Wrong!") except: os.remove(filename + '.py') return flask.jsonify("Timeout!") if __name__ == '__main__': app.run("0.0.0.0")
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/L3HCTF/2024/web/intractable_problem/files/oj.py
ctfs/L3HCTF/2024/web/intractable_problem/files/oj.py
import sys import os codes=''' <<codehere>> ''' try: codes.encode("ascii") except UnicodeEncodeError: exit(0) if "__" in codes: exit(0) codes+="\nres=factorization(c)" locals={"c":"696287028823439285412516128163589070098246262909373657123513205248504673721763725782111252400832490434679394908376105858691044678021174845791418862932607425950200598200060291023443682438196296552959193310931511695879911797958384622729237086633102190135848913461450985723041407754481986496355123676762688279345454097417867967541742514421793625023908839792826309255544857686826906112897645490957973302912538933557595974247790107119797052793215732276223986103011959886471914076797945807178565638449444649884648281583799341879871243480706581561222485741528460964215341338065078004726721288305399437901175097234518605353898496140160657001466187637392934757378798373716670535613637539637468311719923648905641849133472394335053728987186164141412563575941433170489130760050719104922820370994229626736584948464278494600095254297544697025133049342015490116889359876782318981037912673894441836237479855411354981092887603250217400661295605194527558700876411215998415750392444999450257864683822080257235005982249555861378338228029418186061824474448847008690117195232841650446990696256199968716183007097835159707554255408220292726523159227686505847172535282144212465211879980290126845799443985426297754482370702756554520668240815554441667638597863","__builtins__": None} res=set() def blackFunc(oldexit): def func(event, args): blackList = ["process","os","sys","interpreter","cpython","open","compile","__new__","gc"] for i in blackList: if i in (event + "".join(str(s) for s in args)).lower(): print(i) oldexit(0) return func code = compile(codes, "<judgecode>", "exec") sys.addaudithook(blackFunc(os._exit)) exec(code,{"__builtins__": None},locals) p=int(locals["res"][0]) q=int(locals["res"][1]) if(p>1e5 and q>1e5 and p*q==int("696287028823439285412516128163589070098246262909373657123513205248504673721763725782111252400832490434679394908376105858691044678021174845791418862932607425950200598200060291023443682438196296552959193310931511695879911797958384622729237086633102190135848913461450985723041407754481986496355123676762688279345454097417867967541742514421793625023908839792826309255544857686826906112897645490957973302912538933557595974247790107119797052793215732276223986103011959886471914076797945807178565638449444649884648281583799341879871243480706581561222485741528460964215341338065078004726721288305399437901175097234518605353898496140160657001466187637392934757378798373716670535613637539637468311719923648905641849133472394335053728987186164141412563575941433170489130760050719104922820370994229626736584948464278494600095254297544697025133049342015490116889359876782318981037912673894441836237479855411354981092887603250217400661295605194527558700876411215998415750392444999450257864683822080257235005982249555861378338228029418186061824474448847008690117195232841650446990696256199968716183007097835159707554255408220292726523159227686505847172535282144212465211879980290126845799443985426297754482370702756554520668240815554441667638597863")): print("Correct!",end="") else: print("Wrong!",end="")
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/0CTF/2021/Quals/pwn/uc_goood/uc_goood.py
ctfs/0CTF/2021/Quals/pwn/uc_goood/uc_goood.py
#!/usr/bin/env python import os import struct import types from unicorn import * from unicorn.x86_const import * from syscall import hook_syscall CODE = 0xdeadbeef000 STACK = 0xbabecafe000 MAIN = b'\x48\x83\xec\x20\x66\xc7\x44\x24\x0e\x00\x00\x48\x8d\x5c\x24\x0e\x48\xc7\x44\x24\x10\x00\x00\x00\x00\x48\xc7\x44\x24\x18\x00\x00\x00\x00\xb9\x41\x00\x00\x00\x48\x8d\x15\x8b\x01\x00\x00\xbe\x01\x00\x00\x00\x31\xc0\xbf\x01\x00\x00\x00\xe8\xbb\x01\x00\x00\xb9\x02\x00\x00\x00\x48\x89\xda\x31\xf6\x31\xff\x31\xc0\xe8\xa8\x01\x00\x00\x8a\x44\x24\x0e\x3c\x32\x74\x39\x3c\x33\x74\x62\x3c\x31\x0f\x85\x04\x01\x00\x00\xb9\x12\x00\x00\x00\x48\x8d\x15\x35\x01\x00\x00\xbe\x01\x00\x00\x00\x31\xc0\xbf\x01\x00\x00\x00\xe8\x77\x01\x00\x00\x48\x83\xc4\x20\x48\xbf\x00\xf8\xee\xdb\xea\x0d\x00\x00\xff\x27\xb9\x12\x00\x00\x00\x48\x8d\x15\xf6\x00\x00\x00\xbe\x01\x00\x00\x00\x31\xc0\xbf\x01\x00\x00\x00\xe8\x4a\x01\x00\x00\x48\x83\xc4\x20\x48\xbf\x00\xf8\xee\xdb\xea\x0d\x00\x00\xff\x27\xb9\x07\x00\x00\x00\x48\x8d\x15\xc2\x00\x00\x00\xbe\x01\x00\x00\x00\x31\xc0\xbf\x01\x00\x00\x00\xe8\x1d\x01\x00\x00\x31\xf6\x31\xff\x48\x8d\x54\x24\x10\xb9\x08\x00\x00\x00\x31\xc0\xe8\x08\x01\x00\x00\xb9\x07\x00\x00\x00\xbe\x01\x00\x00\x00\x31\xc0\x48\x8d\x15\x82\x00\x00\x00\xbf\x01\x00\x00\x00\xe8\xeb\x00\x00\x00\x31\xf6\x31\xff\x31\xc0\x48\x8d\x54\x24\x18\xb9\x08\x00\x00\x00\xe8\xd6\x00\x00\x00\x48\x81\x7c\x24\x18\xff\x00\x00\x00\x0f\x87\xef\xfe\xff\xff\xb9\x07\x00\x00\x00\x48\x8d\x15\x41\x00\x00\x00\xbe\x01\x00\x00\x00\x31\xc0\xbf\x01\x00\x00\x00\xe8\xaa\x00\x00\x00\x48\x8b\x4c\x24\x18\x31\xf6\x31\xff\x48\x8b\x54\x24\x10\x31\xc0\xe8\x95\x00\x00\x00\xe9\xb8\xfe\xff\xff\xbe\xff\x00\x00\x00\xbf\x3c\x00\x00\x00\x31\xc0\xe8\x7f\x00\x00\x00\xe9\xa2\xfe\xff\xff\x64\x61\x74\x61\x3a\x20\x00\x73\x69\x7a\x65\x3a\x20\x00\x61\x64\x64\x72\x3a\x20\x00\x50\x61\x74\x68\x65\x74\x69\x63\x20\x68\x75\x6d\x61\x6e\x20\x3e\x0a\x00\x50\x6f\x77\x65\x72\x66\x75\x6c\x20\x61\x64\x6d\x69\x6e\x20\x3e\x0a\x00\x57\x65\x6c\x63\x6f\x6d\x65\x20\x74\x6f\x20\x75\x63\x5f\x67\x6f\x6f\x6f\x64\x0a\x31\x2e\x20\x61\x64\x6d\x69\x6e\x20\x74\x65\x73\x74\x0a\x32\x2e\x20\x75\x73\x65\x72\x20\x74\x65\x73\x74\x0a\x33\x2e\x20\x70\x61\x74\x63\x68\x20\x64\x61\x74\x61\x0a\x3f\x3a\x20\x00\x48\x89\xf8\x48\x89\xf7\x48\x89\xd6\x48\x89\xca\x4d\x89\xc2\x4d\x89\xc8\x4c\x8b\x4c\x24\x08\x0f\x05\xc3' TAIL = b'\x31\xc0\xb9\x32\x00\x00\x00\x48\x8d\x15\x55\x00\x00\x00\xbe\x01\x00\x00\x00\xbf\x01\x00\x00\x00\x48\x83\xec\x18\x66\x89\x44\x24\x0e\x31\xc0\xe8\x6d\x00\x00\x00\x31\xf6\x31\xff\x31\xc0\x48\x8d\x54\x24\x0e\xb9\x02\x00\x00\x00\xe8\x58\x00\x00\x00\x80\x7c\x24\x0e\x79\x75\x11\x48\x83\xc4\x18\x48\xbf\x00\xf8\xee\xdb\xea\x0d\x00\x00\xff\x67\x10\x31\xf6\xbf\x3c\x00\x00\x00\x31\xc0\xe8\x32\x00\x00\x00\x43\x6f\x6e\x67\x72\x61\x74\x75\x6c\x61\x74\x69\x6f\x6e\x73\x21\x20\x54\x65\x73\x74\x20\x73\x75\x63\x63\x65\x65\x64\x21\x0a\x54\x72\x79\x20\x61\x67\x61\x69\x6e\x3f\x20\x28\x79\x2f\x5b\x6e\x5d\x29\x00\x48\x89\xf8\x48\x89\xf7\x48\x89\xd6\x48\x89\xca\x4d\x89\xc2\x4d\x89\xc8\x4c\x8b\x4c\x24\x08\x0f\x05\xc3' ADMIN = b'\xb9\x10\x00\x00\x00\x48\x8d\x15\x37\x00\x00\x00\x31\xc0\xbe\x01\x00\x00\x00\xbf\x01\x00\x00\x00\x48\x83\xec\x08\xe8\x5f\x00\x00\x00\x48\x8d\x05\x2b\x00\x00\x00\x48\xa3\x33\xe2\xaf\xec\xab\x0b\x00\x00\x48\x83\xc4\x08\x48\xbf\x00\xf8\xee\xdb\xea\x0d\x00\x00\xff\x67\x08\x49\x6d\x61\x67\x69\x6e\x61\x74\x69\x6f\x6e\x20\x69\x73\x20\x00\x6b\x33\x33\x6e\x6c\x61\x62\x65\x63\x68\x6f\x20\x27\x6d\x6f\x72\x65\x20\x69\x6d\x70\x6f\x72\x74\x61\x6e\x74\x20\x74\x68\x61\x6e\x20\x6b\x6e\x6f\x77\x6c\x65\x64\x67\x65\x2e\x27\x00\x48\x89\xf8\x48\x89\xf7\x48\x89\xd6\x48\x89\xca\x4d\x89\xc2\x4d\x89\xc8\x4c\x8b\x4c\x24\x08\x0f\x05\xc3'.ljust(0x1000, b'\xf4') admin_offset = CODE + 0x6b - 5 writable = [] is_admin = False def admin_hook(uc, address, size, user_data): global is_admin is_admin = True uc.mem_write(CODE + 0x1000, ADMIN) def hook_mem_access(uc, access, address, size, value, user_data): global is_admin if is_admin and address == 0xbabecafe233: is_admin = False cmd = uc.mem_read(value, 0x100) if cmd.startswith(b'k33nlab'): os.system(cmd[7:cmd.index(0)].decode('utf-8')) def _safe_mem_write(self, address, data): end = address + len(data) for page in writable: if address >= page and end <= page + 0x1000: self.mem_write(address, data) break else: raise UcError(UC_ERR_WRITE_PROT) def p64(n): return struct.pack('<Q', n) def init(uc): global writable uc.safe_mem_write = types.MethodType(_safe_mem_write, uc) uc.mem_map(CODE, 0x1000, UC_PROT_READ | UC_PROT_EXEC) uc.mem_write(CODE, b'\x90' * 0x1000) uc.mem_map(CODE + 0x1000, 0x1000, UC_PROT_ALL) uc.mem_write(CODE + 0x1000, b'\x90' * 0x1000) uc.mem_map(CODE + 0x2000, 0x1000, UC_PROT_READ | UC_PROT_EXEC) uc.mem_write(CODE + 0x2000, b'\x90' * 0x1000) uc.mem_write(CODE, MAIN) uc.mem_write(CODE + 0x2000, TAIL) uc.mem_write(CODE + 0x800, p64(CODE + 0xff0) + p64(CODE + 0x2000) + p64(CODE)) uc.mem_map(STACK, 0x1000, UC_PROT_READ | UC_PROT_WRITE) uc.reg_write(UC_X86_REG_RSP, STACK + 0xf00) writable = (CODE + 0x1000, STACK) uc.hook_add(UC_HOOK_INSN, hook_syscall, None, 1, 0, UC_X86_INS_SYSCALL) uc.hook_add(UC_HOOK_CODE, admin_hook, None, admin_offset, admin_offset + 1) uc.hook_add(UC_HOOK_MEM_WRITE, hook_mem_access) def play(): uc = Uc(UC_ARCH_X86, UC_MODE_64) init(uc) data = os.read(0, 0x1000 - 0xd) data += b'\x48\xbf\x00\xe0\xaf\xec\xab\x0b\x00\x00\xff\x67\x08' uc.mem_write(CODE + 0x1000, data) try: uc.emu_start(CODE, CODE + 0x3000 - 1) except UcError as e: print("error...") if __name__ == '__main__': play()
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/0CTF/2021/Quals/pwn/uc_goood/syscall.py
ctfs/0CTF/2021/Quals/pwn/uc_goood/syscall.py
#!/usr/bin/env python3 # -*- coding: utf-8 -*- from unicorn import * from unicorn.x86_const import * import os.path import sys def hook_syscall(uc, user_data): arg_regs = [UC_X86_REG_RDI, UC_X86_REG_RSI, UC_X86_REG_RDX, UC_X86_REG_R10, UC_X86_REG_R8, UC_X86_REG_R9] rax = uc.reg_read(UC_X86_REG_RAX) if rax in SYSCALL_MAP.keys(): ff, n = SYSCALL_MAP[rax] args = [] while n > 0: args.append(uc.reg_read(arg_regs.pop(0))) n -= 1 try: ret = ff(uc, *args) & 0xffffffffffffffff except Exception as e: uc.emu_stop() return else: ret = 0xffffffffffffffff uc.reg_write(UC_X86_REG_RAX, ret) def sys_read(uc, fd, buf_addr, size): if fd != 0: return -1 data = '' data = os.read(0, size) assert len(data) <= size < 0x100 uc.safe_mem_write(buf_addr, data) return len(data) def sys_write(uc, fd, buf_addr, size): if fd != 1: return -1 data = uc.mem_read(buf_addr, size) assert len(data) <= size < 0x100 sys.stdout.buffer.write(data) sys.stdout.buffer.flush() return len(data) def sys_exit(uc, error_code): uc.emu_stop() return error_code SYSCALL_MAP = { 0: (sys_read, 3), 1: (sys_write, 3), 60: (sys_exit, 1), }
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/0CTF/2021/Quals/pwn/uc_masteeer/syscall.py
ctfs/0CTF/2021/Quals/pwn/uc_masteeer/syscall.py
#!/usr/bin/env python3 # -*- coding: utf-8 -*- from unicorn import * from unicorn.x86_const import * import os.path import sys def hook_syscall(uc, user_data): arg_regs = [UC_X86_REG_RDI, UC_X86_REG_RSI, UC_X86_REG_RDX, UC_X86_REG_R10, UC_X86_REG_R8, UC_X86_REG_R9] rax = uc.reg_read(UC_X86_REG_RAX) if rax in SYSCALL_MAP.keys(): ff, n = SYSCALL_MAP[rax] args = [] while n > 0: args.append(uc.reg_read(arg_regs.pop(0))) n -= 1 try: ret = ff(uc, *args) & 0xffffffffffffffff except Exception as e: uc.emu_stop() return else: ret = 0xffffffffffffffff uc.reg_write(UC_X86_REG_RAX, ret) def sys_read(uc, fd, buf_addr, size): if fd != 0: return -1 data = '' data = os.read(0, size) assert len(data) <= size < 0x100 uc.safe_mem_write(buf_addr, data) return len(data) def sys_write(uc, fd, buf_addr, size): if fd != 1: return -1 data = uc.mem_read(buf_addr, size) assert len(data) <= size < 0x100 sys.stdout.buffer.write(data) sys.stdout.buffer.flush() return len(data) def sys_exit(uc, error_code): uc.emu_stop() return error_code SYSCALL_MAP = { 0: (sys_read, 3), 1: (sys_write, 3), 60: (sys_exit, 1), }
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/0CTF/2021/Quals/pwn/uc_masteeer/uc_masteeer.py
ctfs/0CTF/2021/Quals/pwn/uc_masteeer/uc_masteeer.py
#!/usr/bin/env python import os import struct import types from unicorn import * from unicorn.x86_const import * from syscall import hook_syscall CODE = 0xdeadbeef000 STACK = 0xbabecafe000 MAIN = b'\x48\x83\xec\x20\x66\xc7\x44\x24\x0e\x00\x00\x48\x8d\x5c\x24\x0e\x48\xc7\x44\x24\x10\x00\x00\x00\x00\x48\xc7\x44\x24\x18\x00\x00\x00\x00\xb9\x44\x00\x00\x00\x48\x8d\x15\x8b\x01\x00\x00\xbe\x01\x00\x00\x00\x31\xc0\xbf\x01\x00\x00\x00\xe8\xbe\x01\x00\x00\xb9\x02\x00\x00\x00\x48\x89\xda\x31\xf6\x31\xff\x31\xc0\xe8\xab\x01\x00\x00\x8a\x44\x24\x0e\x3c\x32\x74\x39\x3c\x33\x74\x62\x3c\x31\x0f\x85\x04\x01\x00\x00\xb9\x12\x00\x00\x00\x48\x8d\x15\x35\x01\x00\x00\xbe\x01\x00\x00\x00\x31\xc0\xbf\x01\x00\x00\x00\xe8\x7a\x01\x00\x00\x48\x83\xc4\x20\x48\xbf\x00\xe0\xaf\xec\xab\x0b\x00\x00\xff\x27\xb9\x12\x00\x00\x00\x48\x8d\x15\xf6\x00\x00\x00\xbe\x01\x00\x00\x00\x31\xc0\xbf\x01\x00\x00\x00\xe8\x4d\x01\x00\x00\x48\x83\xc4\x20\x48\xbf\x00\xe0\xaf\xec\xab\x0b\x00\x00\xff\x27\xb9\x07\x00\x00\x00\x48\x8d\x15\xc2\x00\x00\x00\xbe\x01\x00\x00\x00\x31\xc0\xbf\x01\x00\x00\x00\xe8\x20\x01\x00\x00\x31\xf6\x31\xff\x48\x8d\x54\x24\x10\xb9\x08\x00\x00\x00\x31\xc0\xe8\x0b\x01\x00\x00\xb9\x07\x00\x00\x00\xbe\x01\x00\x00\x00\x31\xc0\x48\x8d\x15\x82\x00\x00\x00\xbf\x01\x00\x00\x00\xe8\xee\x00\x00\x00\x31\xf6\x31\xff\x31\xc0\x48\x8d\x54\x24\x18\xb9\x08\x00\x00\x00\xe8\xd9\x00\x00\x00\x48\x81\x7c\x24\x18\xff\x00\x00\x00\x0f\x87\xef\xfe\xff\xff\xb9\x07\x00\x00\x00\x48\x8d\x15\x41\x00\x00\x00\xbe\x01\x00\x00\x00\x31\xc0\xbf\x01\x00\x00\x00\xe8\xad\x00\x00\x00\x48\x8b\x4c\x24\x18\x31\xf6\x31\xff\x48\x8b\x54\x24\x10\x31\xc0\xe8\x98\x00\x00\x00\xe9\xb8\xfe\xff\xff\xbe\xff\x00\x00\x00\xbf\x3c\x00\x00\x00\x31\xc0\xe8\x82\x00\x00\x00\xe9\xa2\xfe\xff\xff\x64\x61\x74\x61\x3a\x20\x00\x73\x69\x7a\x65\x3a\x20\x00\x61\x64\x64\x72\x3a\x20\x00\x50\x61\x74\x68\x65\x74\x69\x63\x20\x68\x75\x6d\x61\x6e\x20\x3e\x0a\x00\x50\x6f\x77\x65\x72\x66\x75\x6c\x20\x61\x64\x6d\x69\x6e\x20\x3e\x0a\x00\x57\x65\x6c\x63\x6f\x6d\x65\x20\x74\x6f\x20\x75\x63\x5f\x6d\x61\x73\x74\x65\x65\x65\x72\x0a\x31\x2e\x20\x61\x64\x6d\x69\x6e\x20\x74\x65\x73\x74\x0a\x32\x2e\x20\x75\x73\x65\x72\x20\x74\x65\x73\x74\x0a\x33\x2e\x20\x70\x61\x74\x63\x68\x20\x64\x61\x74\x61\x0a\x3f\x3a\x20\x00\x48\x89\xf8\x48\x89\xf7\x48\x89\xd6\x48\x89\xca\x4d\x89\xc2\x4d\x89\xc8\x4c\x8b\x4c\x24\x08\x0f\x05\xc3' TAIL = b'\x31\xc0\xb9\x32\x00\x00\x00\x48\x8d\x15\x55\x00\x00\x00\xbe\x01\x00\x00\x00\xbf\x01\x00\x00\x00\x48\x83\xec\x18\x66\x89\x44\x24\x0e\x31\xc0\xe8\x6d\x00\x00\x00\x31\xf6\x31\xff\x31\xc0\x48\x8d\x54\x24\x0e\xb9\x02\x00\x00\x00\xe8\x58\x00\x00\x00\x80\x7c\x24\x0e\x79\x75\x11\x48\x83\xc4\x18\x48\xbf\x00\xe0\xaf\xec\xab\x0b\x00\x00\xff\x67\x10\x31\xf6\xbf\x3c\x00\x00\x00\x31\xc0\xe8\x32\x00\x00\x00\x43\x6f\x6e\x67\x72\x61\x74\x75\x6c\x61\x74\x69\x6f\x6e\x73\x21\x20\x54\x65\x73\x74\x20\x73\x75\x63\x63\x65\x65\x64\x21\x0a\x54\x72\x79\x20\x61\x67\x61\x69\x6e\x3f\x20\x28\x79\x2f\x5b\x6e\x5d\x29\x00\x48\x89\xf8\x48\x89\xf7\x48\x89\xd6\x48\x89\xca\x4d\x89\xc2\x4d\x89\xc8\x4c\x8b\x4c\x24\x08\x0f\x05\xc3' ADMIN = b'\xb9\x10\x00\x00\x00\x48\x8d\x15\x37\x00\x00\x00\x31\xc0\xbe\x01\x00\x00\x00\xbf\x01\x00\x00\x00\x48\x83\xec\x08\xe8\x5f\x00\x00\x00\x48\x8d\x05\x2b\x00\x00\x00\x48\xa3\x33\xe2\xaf\xec\xab\x0b\x00\x00\x48\x83\xc4\x08\x48\xbf\x00\xe0\xaf\xec\xab\x0b\x00\x00\xff\x67\x08\x49\x6d\x61\x67\x69\x6e\x61\x74\x69\x6f\x6e\x20\x69\x73\x20\x00\x6b\x33\x33\x6e\x6c\x61\x62\x65\x63\x68\x6f\x20\x27\x6d\x6f\x72\x65\x20\x69\x6d\x70\x6f\x72\x74\x61\x6e\x74\x20\x74\x68\x61\x6e\x20\x6b\x6e\x6f\x77\x6c\x65\x64\x67\x65\x2e\x27\x00\x48\x89\xf8\x48\x89\xf7\x48\x89\xd6\x48\x89\xca\x4d\x89\xc2\x4d\x89\xc8\x4c\x8b\x4c\x24\x08\x0f\x05\xc3'.ljust(0x1000, b'\xf4') admin_offset = CODE + 0x6b - 5 writable = [] is_admin = False def admin_hook(uc, address, size, user_data): global is_admin is_admin = True uc.mem_write(CODE + 0x1000, ADMIN) def hook_mem_access(uc, access, address, size, value, user_data): global is_admin if is_admin and address == 0xbabecafe233: is_admin = False cmd = uc.mem_read(value, 0x100) if cmd.startswith(b'k33nlab'): os.system(cmd[7:cmd.index(0)].decode('utf-8')) def _safe_mem_write(self, address, data): end = address + len(data) for page in writable: if address >= page and end <= page + 0x1000: self.mem_write(address, data) break else: raise UcError(UC_ERR_WRITE_PROT) def p64(n): return struct.pack('<Q', n) def init(uc): global writable uc.safe_mem_write = types.MethodType(_safe_mem_write, uc) uc.mem_map(CODE, 0x1000, UC_PROT_READ | UC_PROT_EXEC) uc.mem_write(CODE, b'\x90' * 0x1000) uc.mem_map(CODE + 0x1000, 0x1000, UC_PROT_ALL) uc.mem_write(CODE + 0x1000, b'\x90' * 0x1000) uc.mem_map(CODE + 0x2000, 0x1000, UC_PROT_READ | UC_PROT_EXEC) uc.mem_write(CODE + 0x2000, b'\x90' * 0x1000) uc.mem_write(CODE, MAIN) uc.mem_write(CODE + 0x2000, TAIL) uc.mem_map(STACK, 0x1000, UC_PROT_READ | UC_PROT_WRITE) uc.reg_write(UC_X86_REG_RSP, STACK + 0xf00) uc.mem_write(STACK, p64(CODE + 0x1000) + p64(CODE + 0x2000) + p64(CODE)) writable = (CODE + 0x1000, STACK) uc.hook_add(UC_HOOK_INSN, hook_syscall, None, 1, 0, UC_X86_INS_SYSCALL) uc.hook_add(UC_HOOK_CODE, admin_hook, None, admin_offset, admin_offset + 1) uc.hook_add(UC_HOOK_MEM_WRITE, hook_mem_access) def play(): uc = Uc(UC_ARCH_X86, UC_MODE_64) init(uc) data = os.read(0, 0x1000 - 0xd) data += b'\x48\xbf\x00\xe0\xaf\xec\xab\x0b\x00\x00\xff\x67\x08' uc.mem_write(CODE + 0x1000, data) try: uc.emu_start(CODE, CODE + 0x3000 - 1) except UcError as e: print("error...") if __name__ == '__main__': play()
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/0CTF/2021/Quals/crypto/zer0lfsr/task.py
ctfs/0CTF/2021/Quals/crypto/zer0lfsr/task.py
#!/usr/bin/env python3 import random import signal import socketserver import string from hashlib import sha256 from os import urandom from secret import flag def _prod(L): p = 1 for x in L: p *= x return p def _sum(L): s = 0 for x in L: s ^= x return s def n2l(x, l): return list(map(int, '{{0:0{}b}}'.format(l).format(x))) class Generator1: def __init__(self, key: list): assert len(key) == 64 self.NFSR = key[: 48] self.LFSR = key[48: ] self.TAP = [0, 1, 12, 15] self.TAP2 = [[2], [5], [9], [15], [22], [26], [39], [26, 30], [5, 9], [15, 22, 26], [15, 22, 39], [9, 22, 26, 39]] self.h_IN = [2, 4, 7, 15, 27] self.h_OUT = [[1], [3], [0, 3], [0, 1, 2], [0, 2, 3], [0, 2, 4], [0, 1, 2, 4]] def g(self): x = self.NFSR return _sum(_prod(x[i] for i in j) for j in self.TAP2) def h(self): x = [self.LFSR[i] for i in self.h_IN[:-1]] + [self.NFSR[self.h_IN[-1]]] return _sum(_prod(x[i] for i in j) for j in self.h_OUT) def f(self): return _sum([self.NFSR[0], self.h()]) def clock(self): o = self.f() self.NFSR = self.NFSR[1: ] + [self.LFSR[0] ^ self.g()] self.LFSR = self.LFSR[1: ] + [_sum(self.LFSR[i] for i in self.TAP)] return o class Generator2: def __init__(self, key): assert len(key) == 64 self.NFSR = key[: 16] self.LFSR = key[16: ] self.TAP = [0, 35] self.f_IN = [0, 10, 20, 30, 40, 47] self.f_OUT = [[0, 1, 2, 3], [0, 1, 2, 4, 5], [0, 1, 2, 5], [0, 1, 2], [0, 1, 3, 4, 5], [0, 1, 3, 5], [0, 1, 3], [0, 1, 4], [0, 1, 5], [0, 2, 3, 4, 5], [ 0, 2, 3], [0, 3, 5], [1, 2, 3, 4, 5], [1, 2, 3, 4], [1, 2, 3, 5], [1, 2], [1, 3, 5], [1, 3], [1, 4], [1], [2, 4, 5], [2, 4], [2], [3, 4], [4, 5], [4], [5]] self.TAP2 = [[0, 3, 7], [1, 11, 13, 15], [2, 9]] self.h_IN = [0, 2, 4, 6, 8, 13, 14] self.h_OUT = [[0, 1, 2, 3, 4, 5], [0, 1, 2, 4, 6], [1, 3, 4]] def f(self): x = [self.LFSR[i] for i in self.f_IN] return _sum(_prod(x[i] for i in j) for j in self.f_OUT) def h(self): x = [self.NFSR[i] for i in self.h_IN] return _sum(_prod(x[i] for i in j) for j in self.h_OUT) def g(self): x = self.NFSR return _sum(_prod(x[i] for i in j) for j in self.TAP2) def clock(self): self.LFSR = self.LFSR[1: ] + [_sum(self.LFSR[i] for i in self.TAP)] self.NFSR = self.NFSR[1: ] + [self.LFSR[1] ^ self.g()] return self.f() ^ self.h() class Generator3: def __init__(self, key: list): assert len(key) == 64 self.LFSR = key self.TAP = [0, 55] self.f_IN = [0, 8, 16, 24, 32, 40, 63] self.f_OUT = [[1], [6], [0, 1, 2, 3, 4, 5], [0, 1, 2, 4, 6]] def f(self): x = [self.LFSR[i] for i in self.f_IN] return _sum(_prod(x[i] for i in j) for j in self.f_OUT) def clock(self): self.LFSR = self.LFSR[1: ] + [_sum(self.LFSR[i] for i in self.TAP)] return self.f() class zer0lfsr: def __init__(self, msk: int, t: int): if t == 1: self.g = Generator1(n2l(msk, 64)) elif t == 2: self.g = Generator2(n2l(msk, 64)) else: self.g = Generator3(n2l(msk, 64)) self.t = t def next(self): for i in range(self.t): o = self.g.clock() return o class Task(socketserver.BaseRequestHandler): def __init__(self, *args, **kargs): super().__init__(*args, **kargs) def proof_of_work(self): random.seed(urandom(8)) proof = ''.join([random.choice(string.ascii_letters + string.digits + '!#$%&*-?') for _ in range(20)]) digest = sha256(proof.encode()).hexdigest() self.dosend('sha256(XXXX + {}) == {}'.format(proof[4: ], digest)) self.dosend('Give me XXXX:') x = self.request.recv(10) x = (x.strip()).decode('utf-8') if len(x) != 4 or sha256((x + proof[4: ]).encode()).hexdigest() != digest: return False return True def dosend(self, msg): try: self.request.sendall(msg.encode('latin-1') + b'\n') except: pass def timeout_handler(self, signum, frame): raise TimeoutError def handle(self): try: signal.signal(signal.SIGALRM, self.timeout_handler) signal.alarm(30) if not self.proof_of_work(): self.dosend('You must pass the PoW!') return signal.alarm(50) available = [1, 2, 3] for _ in range(2): self.dosend('which one: ') idx = int(self.request.recv(10).strip()) assert idx in available available.remove(idx) msk = random.getrandbits(64) lfsr = zer0lfsr(msk, idx) for i in range(5): keystream = '' for j in range(1000): b = 0 for k in range(8): b = (b << 1) + lfsr.next() keystream += chr(b) self.dosend('start:::' + keystream + ':::end') hint = sha256(str(msk).encode()).hexdigest() self.dosend('hint: ' + hint) self.dosend('k: ') guess = int(self.request.recv(100).strip()) if guess != msk: self.dosend('Wrong ;(') self.request.close() else: self.dosend('Good :)') self.dosend(flag) except TimeoutError: self.dosend('Timeout!') self.request.close() except: self.dosend('Wtf?') self.request.close() class ThreadedServer(socketserver.ForkingMixIn, socketserver.TCPServer): pass if __name__ == "__main__": HOST, PORT = '0.0.0.0', 31337 server = ThreadedServer((HOST, PORT), Task) server.allow_reuse_address = True server.serve_forever()
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/0CTF/2021/Quals/crypto/cloudpass/task.py
ctfs/0CTF/2021/Quals/crypto/cloudpass/task.py
#!/usr/bin/python3 import os import socketserver import random import signal import string import struct from hashlib import sha256 import secrets import pykeepass from flag import flag MAXSIZE = 0x2000 class Task(socketserver.BaseRequestHandler): def proof_of_work(self): proof = ''.join([random.choice(string.ascii_letters+string.digits) for _ in range(20)]) digest = sha256(proof.encode('latin-1')).hexdigest() self.request.send(str.encode("sha256(XXXX+%s) == %s\n" % (proof[4:],digest))) self.request.send(str.encode('Give me XXXX:')) x = self.request.recv(10).decode() x = x.strip() xx = x+proof[4:] if len(x) != 4 or sha256(xx.encode('latin-1')).hexdigest() != digest: return False return True def askfor(self, msg): self.request.sendall(msg) return self.request.recv(0x20).strip().decode('latin-1') def recvint(self): try: return int(self.request.recv(10)) except: return 0 def recvblob(self): self.request.sendall(b"size: ") sz = self.recvint() assert sz < MAXSIZE self.request.sendall(b"blob(hex): ") sz = sz*2+1 r = sz res = b'' while r>0: res += self.request.recv(r) r = sz - len(res) return bytes.fromhex(res.strip().decode('latin-1')) def prepared(self): client_ip = self.client_address[0] dname = sha256(client_ip.encode('latin-1')).hexdigest() self.d = os.path.join("/tmp", dname) os.makedirs(self.d, exist_ok=True) self.f = os.path.join(self.d, "a.kdbx") def handle(self): signal.alarm(20) if not self.proof_of_work(): return signal.alarm(20) self.request.sendall(b"Welcome to our cloud password storage service.\nNotice that storage size is strictly limited for free trial >_<\n") self.prepared() self.request.sendall(b"master password: ") password = self.request.recv(0x40).strip().decode('latin-1') if not os.path.exists(self.f): answer = self.askfor(b"Do you already have a database to import? (y/N) ") if answer[0] == 'y': file = self.recvblob() with open(self.f, 'wb') as f: f.write(file) else: pykeepass.create_database(self.f, password) try: db = pykeepass.PyKeePass(self.f, password) except: self.request.sendall(b"[error] Invalid master password!\n") self.request.sendall(b"We never store your master password for safety, and cannot help you recover it :(\n") answer = self.askfor(b"Do you want to delete your database? (y/N) ") if answer[0] == 'y': os.remove(self.f) self.request.close() return for _ in range(0x100): self.request.sendall(b"> ") cmd = self.request.recv(0x20).strip() if cmd == b"add_entry": gn = self.askfor(b"dest group: ") g = db.root_group if gn == "" else db.find_groups_by_name(gn, first=True) t = self.askfor(b"title: ") u = self.askfor(b"username: ") p = self.askfor(b"password: ") db.add_entry(g, t, u, p) elif cmd == b"add_group": gn = self.askfor(b"dest group: ") g = db.root_group if gn == "" else db.find_groups_by_name(gn, first=True) n = self.askfor(b"name: ") db.add_group(g, n) elif cmd == b"add_binary": blob = self.recvblob() db.add_binary(blob) elif cmd == b"find_entries": t = self.askfor(b"title: ") res = db.find_entries_by_title(t) if len(res) > 0: self.request.sendall(str(res[0]).encode('latin-1')+b'\n') elif cmd == b"find_groups": n = self.askfor(b"name: ") res = db.find_groups_by_name(n) if len(res) > 0: self.request.sendall(str(res[0]).encode('latin-1')+b'\n') elif cmd == b"gimme_flag": db.add_entry(db.root_group, "flag", "0ops", flag) db.password = secrets.token_hex(32) elif cmd == b"list_entries": self.request.sendall(str(db.entries).encode('latin-1')+b'\n') elif cmd == b"list_groups": self.request.sendall(str(db.groups).encode('latin-1')+b'\n') elif cmd == b"list_binaries": self.request.sendall(str(db.binaries).encode('latin-1')+b'\n') elif cmd == b"leave": answer = self.askfor(b"Do you need to backup your database elsewhere? (y/N) ") if answer[0] == 'y': with open(self.f, 'rb') as f: cont = f.read() self.request.sendall(cont.hex().encode('latin-1')+b'\n') break else: break db.save() if os.stat(self.f).st_size > MAXSIZE: self.request.sendall(b"[error] Filesize limit exceeded!") os.remove(self.f) break self.request.close() class ForkedServer(socketserver.ForkingTCPServer, socketserver.TCPServer): pass if __name__ == "__main__": HOST, PORT = '0.0.0.0', 10001 server = ForkedServer((HOST, PORT), Task) server.allow_reuse_address = True server.serve_forever()
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/0CTF/2021/Quals/crypto/zer0lfsrplus/task.py
ctfs/0CTF/2021/Quals/crypto/zer0lfsrplus/task.py
#!/usr/bin/env python3 import random import signal import socketserver import string from hashlib import sha256 from os import urandom from secret import flag def _prod(L): p = 1 for x in L: p *= x return p def _sum(L): s = 0 for x in L: s ^= x return s def b2n(x): return int.from_bytes(x, 'big') def n2l(x, l): return list(map(int, '{{0:0{}b}}'.format(l).format(x))) def split(x, n, l): return [(x >> (i * l)) % 2**l for i in range(n)][::-1] def combine(x, n, l): return sum([x[i] << (l * (n - i - 1)) for i in range(n)]) class Generator1: def __init__(self, key: list): assert len(key) == 64 self.NFSR = key[: 48] self.LFSR = key[48: ] self.TAP = [0, 1, 12, 15] self.TAP2 = [[2], [5], [9], [15], [22], [26], [39], [26, 30], [5, 9], [15, 22, 26], [15, 22, 39], [9, 22, 26, 39]] self.h_IN = [2, 4, 7, 15, 27] self.h_OUT = [[1], [3], [0, 3], [0, 1, 2], [0, 2, 3], [0, 2, 4], [0, 1, 2, 4]] def g(self): x = self.NFSR return _sum(_prod(x[i] for i in j) for j in self.TAP2) def h(self): x = [self.LFSR[i] for i in self.h_IN[:-1]] + [self.NFSR[self.h_IN[-1]]] return _sum(_prod(x[i] for i in j) for j in self.h_OUT) def f(self): return _sum([self.NFSR[0], self.h()]) def clock(self): o = self.f() self.NFSR = self.NFSR[1: ] + [self.LFSR[0] ^ self.g()] self.LFSR = self.LFSR[1: ] + [_sum(self.LFSR[i] for i in self.TAP)] return o class Generator2: def __init__(self, key): assert len(key) == 64 self.NFSR = key[: 16] self.LFSR = key[16: ] self.TAP = [0, 35] self.f_IN = [0, 10, 20, 30, 40, 47] self.f_OUT = [[0, 1, 2, 3], [0, 1, 2, 4, 5], [0, 1, 2, 5], [0, 1, 2], [0, 1, 3, 4, 5], [0, 1, 3, 5], [0, 1, 3], [0, 1, 4], [0, 1, 5], [0, 2, 3, 4, 5], [ 0, 2, 3], [0, 3, 5], [1, 2, 3, 4, 5], [1, 2, 3, 4], [1, 2, 3, 5], [1, 2], [1, 3, 5], [1, 3], [1, 4], [1], [2, 4, 5], [2, 4], [2], [3, 4], [4, 5], [4], [5]] self.TAP2 = [[0, 3, 7], [1, 11, 13, 15], [2, 9]] self.h_IN = [0, 2, 4, 6, 8, 13, 14] self.h_OUT = [[0, 1, 2, 3, 4, 5], [0, 1, 2, 4, 6], [1, 3, 4]] def f(self): x = [self.LFSR[i] for i in self.f_IN] return _sum(_prod(x[i] for i in j) for j in self.f_OUT) def h(self): x = [self.NFSR[i] for i in self.h_IN] return _sum(_prod(x[i] for i in j) for j in self.h_OUT) def g(self): x = self.NFSR return _sum(_prod(x[i] for i in j) for j in self.TAP2) def clock(self): self.LFSR = self.LFSR[1: ] + [_sum(self.LFSR[i] for i in self.TAP)] self.NFSR = self.NFSR[1: ] + [self.LFSR[1] ^ self.g()] return self.f() ^ self.h() class Generator3: def __init__(self, key: list): assert len(key) == 64 self.LFSR = key self.TAP = [0, 55] self.f_IN = [0, 8, 16, 24, 32, 40, 63] self.f_OUT = [[1], [6], [0, 1, 2, 3, 4, 5], [0, 1, 2, 4, 6]] def f(self): x = [self.LFSR[i] for i in self.f_IN] return _sum(_prod(x[i] for i in j) for j in self.f_OUT) def clock(self): self.LFSR = self.LFSR[1: ] + [_sum(self.LFSR[i] for i in self.TAP)] return self.f() class KDF: def __init__(self, key: int): self.msk = key self.SBOX = [12, 5, 1, 2, 7, 15, 9, 3, 0, 13, 14, 6, 8, 10, 4, 11] self.idx = [[0, 3], [0, 1], [2, 3], [0, 3]] def substitue(self, x): return [self.SBOX[i] for i in x] def expand(self): h = sha256(str(self.msk).encode()).digest() rnd_key = [h[: 2], h[2: 4], h[2: 4], h[4: 6]] rnd_key = list(map(b2n, rnd_key)) chunk = split(self.msk, 4, 16) sub_key = [combine(self.substitue(split(chunk[self.idx[i][0]] ^ chunk[self.idx[i][1]] , 4, 4)), 4, 4) for i in range(4)] final_key = [rnd_key[i] ^ sub_key[i] for i in range(4)] return combine(final_key, 4, 16) class zer0lfsr: def __init__(self, msk: int): self.key = [] for i in range(3): msk = KDF(msk).expand() self.key.append(msk) self.g1 = Generator1(n2l(self.key[0], 64)) self.g2 = Generator2(n2l(self.key[1], 64)) self.g3 = Generator3(n2l(self.key[2], 64)) def next(self): o1 = self.g1.clock() o2 = self.g2.clock() o2 = self.g2.clock() o3 = self.g3.clock() o3 = self.g3.clock() o3 = self.g3.clock() o = (o1 * o2) ^ (o2 * o3) ^ (o1 * o3) return o class Task(socketserver.BaseRequestHandler): def __init__(self, *args, **kargs): super().__init__(*args, **kargs) def proof_of_work(self): random.seed(urandom(8)) proof = ''.join([random.choice(string.ascii_letters + string.digits + '!#$%&*-?') for _ in range(20)]) digest = sha256(proof.encode()).hexdigest() self.dosend('sha256(XXXX + {}) == {}'.format(proof[4: ], digest)) self.dosend('Give me XXXX:') x = self.request.recv(10) x = (x.strip()).decode('utf-8') if len(x) != 4 or sha256((x + proof[4: ]).encode()).hexdigest() != digest: return False return True def dosend(self, msg): try: self.request.sendall(msg.encode('latin-1') + b'\n') except: pass def timeout_handler(self, signum, frame): raise TimeoutError def handle(self): try: signal.signal(signal.SIGALRM, self.timeout_handler) signal.alarm(30) if not self.proof_of_work(): self.dosend('You must pass the PoW!') return lfsr = zer0lfsr(random.getrandbits(64)) for i in range(20): keystream = '' for j in range(1000): b = 0 for k in range(8): b = (b << 1) + lfsr.next() keystream += chr(b) self.dosend('start:::' + keystream + ':::end') signal.alarm(100) self.dosend('k1: ') k1 = int(self.request.recv(100).strip()) self.dosend('k2: ') k2 = int(self.request.recv(100).strip()) self.dosend('k3: ') k3 = int(self.request.recv(100).strip()) if lfsr.key == [k1, k2, k3]: self.dosend(flag) else: self.dosend('Wrong ;(') except TimeoutError: self.dosend('Timeout!') self.request.close() except: self.dosend('Wtf?') self.request.close() class ThreadedServer(socketserver.ForkingMixIn, socketserver.TCPServer): pass if __name__ == "__main__": HOST, PORT = '0.0.0.0', 13337 server = ThreadedServer((HOST, PORT), Task) server.allow_reuse_address = True server.serve_forever()
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/0CTF/2018/Quals/pwn/BabyStack/pow.py
ctfs/0CTF/2018/Quals/pwn/BabyStack/pow.py
#!/usr/bin/python -u # encoding: utf-8 import random, string, subprocess, os, sys from hashlib import sha256 os.chdir(os.path.dirname(os.path.realpath(__file__))) def proof_of_work(): chal = ''.join(random.choice(string.letters+string.digits) for _ in xrange(16)) print chal sol = sys.stdin.read(4) if len(sol) != 4 or not sha256(chal + sol).digest().startswith('\0\0\0'): exit() def exec_serv(name, payload): p = subprocess.Popen(name, stdin=subprocess.PIPE, stdout=file('/dev/null','w'), stderr=subprocess.STDOUT) p.stdin.write(payload) p.wait() if __name__ == '__main__': proof_of_work() payload = sys.stdin.read(0x100) exec_serv('./babystack', payload)
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/0CTF/2018/Quals/pwn/BabyStack/coll.py
ctfs/0CTF/2018/Quals/pwn/BabyStack/coll.py
import random, string, subprocess, os, sys from hashlib import sha256 random_str='' for i in xrange (0,1000000000): if (sha256(random_stra + str(i)).digest().startswith('\0\0\0')): print "Index is = ",i,"Result is =", sha256(random_str + str(i)).hexdigest()
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/0CTF/2018/Quals/pwn/BlackHoleTheory/pow.py
ctfs/0CTF/2018/Quals/pwn/BlackHoleTheory/pow.py
#!/usr/bin/python -u # encoding: utf-8 import random, string, subprocess, os, sys from hashlib import sha256 os.chdir(os.path.dirname(os.path.realpath(__file__))) def proof_of_work(): chal = ''.join(random.choice(string.letters+string.digits) for _ in xrange(16)) print chal sol = sys.stdin.read(4) if len(sol) != 4 or not sha256(chal + sol).hexdigest().startswith('00000'): exit() def exec_serv(name, payload): p = subprocess.Popen(name, stdin=subprocess.PIPE, stdout=file('/dev/null','w'), stderr=subprocess.STDOUT) p.stdin.write(payload) p.wait() if __name__ == '__main__': proof_of_work() payload = sys.stdin.read(0x800) exec_serv('./blackhole', payload)
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/0CTF/2018/Quals/pwn/HeapStormII/pow.py
ctfs/0CTF/2018/Quals/pwn/HeapStormII/pow.py
#!/usr/bin/python -u # encoding: utf-8 import random, string, os, sys from hashlib import sha256 os.chdir(os.path.dirname(os.path.realpath(__file__))) def proof_of_work(): chal = ''.join(random.choice(string.letters+string.digits) for _ in xrange(16)) print chal sol = sys.stdin.read(4) if len(sol) != 4 or not sha256(chal + sol).digest().startswith('\0\0\0'): exit() if __name__ == '__main__': proof_of_work() os.execv('./heapstorm2', ['./heapstorm2'])
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/0CTF/2018/Finals/pwn/pemu/wrapper.py
ctfs/0CTF/2018/Finals/pwn/pemu/wrapper.py
#!/usr/bin/python -u import os import time from backports import tempfile time.sleep(1) dirname = os.path.abspath(os.path.dirname(__file__)) pemu = os.path.join(dirname, "pemu", "loader") bin = os.path.join(dirname, "binary", "main") with tempfile.TemporaryDirectory() as tmp: os.chdir(tmp) os.system("%s %s" % (pemu, bin))
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/0CTF/2018/Finals/pwn/blackhole2/pow.py
ctfs/0CTF/2018/Finals/pwn/blackhole2/pow.py
#!/usr/bin/python -u # encoding: utf-8 import random, string, subprocess, os, sys from hashlib import sha256 os.chdir(os.path.dirname(os.path.realpath(__file__))) def proof_of_work(): chal = ''.join(random.choice(string.letters+string.digits) for _ in xrange(16)) print chal sol = sys.stdin.read(4) if len(sol) != 4 or not sha256(chal + sol).hexdigest().startswith('0000'): exit() def exec_serv(name, payload): p = subprocess.Popen(name, stdin=subprocess.PIPE, stdout=file('/dev/null','w'), stderr=subprocess.STDOUT) p.stdin.write(payload) p.wait() if __name__ == '__main__': proof_of_work() payload = sys.stdin.read(0x1000) exec_serv('./blackhole2', payload)
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/0CTF/2019/Quals/pwn/If_on_a_winters_night_a_traveler/service.py
ctfs/0CTF/2019/Quals/pwn/If_on_a_winters_night_a_traveler/service.py
#! /usr/bin/python import subprocess import tempfile import sys,os import random,string from hashlib import sha256 def proof_of_work(): proof = ''.join([random.choice(string.ascii_letters+string.digits) for _ in xrange(20)]) digest = sha256(proof).hexdigest() sys.stdout.write("sha256(XXXX+%s) == %s\n" % (proof[4:],digest)) sys.stdout.write('Give me XXXX:') sys.stdout.flush() x = sys.stdin.readline() x = x.strip() if len(x) != 4 or sha256(x+proof[4:]).hexdigest() != digest: return False sys.stdout.write('OK\n') sys.stdout.flush() return True def main(): try: size = int(sys.stdin.readline()) except: return if size > 1000000: return exp = sys.stdin.read(size) f = tempfile.NamedTemporaryFile(prefix='',delete=False) f.write(exp) f.close() os.system('echo ":q" | /home/calvino/vim --clean %s' % f.name) sys.stdout.write('looks good\n') os.unlink(f.name) if __name__ == '__main__': if proof_of_work(): main()
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/0CTF/2023/misc/economical_sort/pow.py
ctfs/0CTF/2023/misc/economical_sort/pow.py
import random, sys import gmpy2 def proof_of_work(sec = 60): # From 0CTF/TCTF 2021 p = gmpy2.next_prime(random.getrandbits(512)) q = gmpy2.next_prime(random.getrandbits(512)) n = p*q c = 2900000 t = c*sec + random.randint(0,c) print('Show me your computation:') print(f'2^(2^{t}) mod {n} = ?') print('Your answer: ', end='') try: sol = int(sys.stdin.readline()) phi = (p-1)*(q-1) u = pow(2, t, phi) w = pow(2, u, n) if w == sol: print('Correct!') return True else: print('Wrong Answer!') exit(1) except ValueError: print('Invalid Input!') exit(1) if __name__ == '__main__': if proof_of_work(): exit(0) else: exit(1)
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/0CTF/2023/misc/economical_sort/secret.py
ctfs/0CTF/2023/misc/economical_sort/secret.py
flag = 'flag{xxxxxxx}'
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/0CTF/2023/misc/economical_sort/server.py
ctfs/0CTF/2023/misc/economical_sort/server.py
from unicorn import * from unicorn.x86_const import * import os import gc from secret import flag DATA = 0x400000 STACK = 0x800000 CODE = 0x1000000 instruction_cnt = 0 buffer_len = 100 def hook_code(uc, address, size, user_data): global instruction_cnt instruction_cnt += 1 if instruction_cnt > 1000000: print('time out') raise UcError(0) if size > 1: print('not economical!') raise UcError(0) def check(code): global instruction_cnt mu = Uc(UC_ARCH_X86, UC_MODE_32) mu.mem_map(CODE, 0x1000, UC_PROT_READ | UC_PROT_EXEC) mu.mem_map(DATA, 0x1000, UC_PROT_READ | UC_PROT_WRITE) mu.mem_map(STACK, 0x1000, UC_PROT_READ | UC_PROT_WRITE) mu.mem_write(CODE, b'\x00' * 0x1000) mu.mem_write(DATA, b'\x00' * 0x1000) mu.mem_write(STACK, b'\x00' * 0x1000) mu.reg_write(UC_X86_REG_EAX, 0x0) mu.reg_write(UC_X86_REG_EBX, 0x0) mu.reg_write(UC_X86_REG_ECX, 0x0) mu.reg_write(UC_X86_REG_EDX, 0x0) mu.reg_write(UC_X86_REG_EBP, 0x0) mu.reg_write(UC_X86_REG_ESI, buffer_len) mu.reg_write(UC_X86_REG_EDI, DATA) mu.reg_write(UC_X86_REG_ESP, STACK + 0x1000) buffer = os.urandom(buffer_len) mu.mem_write(DATA, buffer) mu.mem_write(CODE, code) mu.hook_add(UC_HOOK_CODE, hook_code) instruction_cnt = 0 try: mu.emu_start(CODE, CODE + len(code)) except UcError as e: print('Oops') return False sorted_buffer = mu.mem_read(DATA, buffer_len) if sorted(buffer) == list(sorted_buffer): return True else: return False if __name__ == '__main__': print('> ', end='') code = bytes.fromhex(os.read(0, 800).decode()) for i in range(20): if not check(code): print('Try to be more economical!') exit() gc.collect() print(f'Wow, here is your reward for being economical: {flag}')
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/0CTF/2023/misc/ctar/task.py
ctfs/0CTF/2023/misc/ctar/task.py
#!/usr/bin/python3 import os import socketserver import random import signal import string import tempfile import tarfile from hashlib import sha256 from Crypto.Cipher import ChaCha20 from secret import flag,key MAXNUM = 9 MAXFILESZ = 100 MAXTARSZ = 100000 class LicenseRequired(Exception): pass class Task(socketserver.BaseRequestHandler): def proof_of_work(self): proof = ''.join([random.choice(string.ascii_letters+string.digits) for _ in range(20)]) digest = sha256(proof.encode('latin-1')).hexdigest() self.request.send(str.encode("sha256(XXXX+%s) == %s\n" % (proof[4:],digest))) self.request.send(str.encode('Give me XXXX:')) x = self.request.recv(10).decode() x = x.strip() xx = x+proof[4:] if len(x) != 4 or sha256(xx.encode('latin-1')).hexdigest() != digest: return False return True def recvint(self): try: return int(self.request.recv(10)) except: return 0 def recvfile(self, maxsz): self.request.sendall(b"size: ") sz = self.recvint() assert sz < maxsz self.request.sendall(b"file(hex): ") r = 2*sz+1 res = b'' while r > len(res): res += self.request.recv(r) dat = bytes.fromhex(res.strip().decode('latin-1')) return dat def savefile(self, name, dat): fname = os.path.join(self.dir, name) with open(fname, "wb") as f: f.write(dat) self.request.sendall(f"[OK] {name} added\n".encode('latin-1')) def addsec(self): if len(self.data) > MAXNUM: self.request.sendall(b"[Error] too many secrets\n") raise LicenseRequired name = os.urandom(4).hex() self.data[name] = 1 dat = self.recvfile(MAXFILESZ) self.savefile(name, dat) def upload(self): dat = self.recvfile(MAXTARSZ) c = ChaCha20.new(nonce=dat[:8], key=key) pt = c.decrypt(dat[8:]) self.savefile("a.tar", pt) tname = os.path.join(self.dir, "a.tar") if not tarfile.is_tarfile(tname): self.request.sendall(b"[Error] not tar file\n") self.request.sendall(pt.hex().encode('latin-1')+b'\n') return f = tarfile.open(tname) cnt = 0 for fname in f.getnames(): if fname.startswith('/') or '..' in fname: self.request.sendall(b"[Error] you need a license to hack us\n") raise LicenseRequired cnt += 1 if cnt > MAXNUM: break if len(self.data) + cnt > MAXNUM: self.request.sendall(b"[Error] too many files\n") raise LicenseRequired for fname in f.getnames(): self.data[fname] = 1 f.extractall(path=self.dir) os.unlink(tname) self.request.sendall(b"[OK] upload succeeded\n") def readsec(self): raise LicenseRequired def download(self): nonce = True for name in self.data: if self.data[name] == 0: nonce = False fname = os.path.join(self.dir, "a.tar") with tarfile.open("a.tar", 'w') as f: for name in self.data: f.add(name) with open(fname, 'rb') as f: cont = f.read() c = ChaCha20.new(key=key) dat = c.encrypt(cont) if nonce: dat = c.nonce+dat self.request.sendall(f"[OK] ctar file size: {len(dat)}\n".encode('latin-1')) self.request.sendall(dat.hex().encode('latin-1')+b'\n') def addflag(self): if len(self.data) > MAXNUM: self.request.sendall(b"[Error] too many secrets\n") raise LicenseRequired name = os.urandom(4).hex() self.data[name] = 0 self.savefile(name, flag) def handle(self): if not self.proof_of_work(): return self.data = {} self.dir = tempfile.mkdtemp() os.chdir(self.dir) signal.alarm(120) self.request.sendall(b"*** Welcome to ctar service ***\nUpload and archive your secrets with our super fancy homemade secure tar file format. You'll like it\nNotice: the file size is limited in your free trial\n") while True: try: self.request.sendall(b"1. add your secret\n2. upload ctar file\n3. read secrets\n4. download ctar file\n0. add flag\n> ") i = self.recvint() if i==1: self.addsec() elif i==2: self.upload() elif i==3: self.readsec() elif i==4: self.download() elif i==0: self.addflag() else: break except: pass os.system(f"rm -r {self.dir}") self.request.close() class ForkedServer(socketserver.ForkingTCPServer, socketserver.TCPServer): pass if __name__ == "__main__": HOST, PORT = '0.0.0.0', 10001 server = ForkedServer((HOST, PORT), Task) server.allow_reuse_address = True server.serve_forever()
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/0CTF/2023/pwn/Half_Promise/pow.py
ctfs/0CTF/2023/pwn/Half_Promise/pow.py
import random, sys import gmpy2 def proof_of_work(sec = 60): # From 0CTF/TCTF 2021 p = gmpy2.next_prime(random.getrandbits(512)) q = gmpy2.next_prime(random.getrandbits(512)) n = p*q c = 2900000 t = c*sec + random.randint(0,c) print('Show me your computation:') print(f'2^(2^{t}) mod {n} = ?') print('Your answer: ', end='') try: sol = int(sys.stdin.readline()) phi = (p-1)*(q-1) u = pow(2, t, phi) w = pow(2, u, n) if w == sol: print('Correct!') return True else: print('Wrong Answer!') exit(1) except ValueError: print('Invalid Input!') exit(1) if __name__ == '__main__': if proof_of_work(): exit(0) else: exit(1)
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/0CTF/2023/pwn/Half_Promise/read.py
ctfs/0CTF/2023/pwn/Half_Promise/read.py
import sys import os def main(): if not os.path.exists(sys.argv[1]): return print('Please input script:') script = sys.stdin.read(30000) end = script.find('EOF') if end != -1: script = script[:end] with open(sys.argv[1], 'w') as f: f.write(script) 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/0CTF/2023/pwn/Promise/pow.py
ctfs/0CTF/2023/pwn/Promise/pow.py
import random, sys import gmpy2 def proof_of_work(sec = 60): # From 0CTF/TCTF 2021 p = gmpy2.next_prime(random.getrandbits(512)) q = gmpy2.next_prime(random.getrandbits(512)) n = p*q c = 2900000 t = c*sec + random.randint(0,c) print('Show me your computation:') print(f'2^(2^{t}) mod {n} = ?') print('Your answer: ', end='') try: sol = int(sys.stdin.readline()) phi = (p-1)*(q-1) u = pow(2, t, phi) w = pow(2, u, n) if w == sol: print('Correct!') return True else: print('Wrong Answer!') exit(1) except ValueError: print('Invalid Input!') exit(1) if __name__ == '__main__': if proof_of_work(): exit(0) else: exit(1)
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/0CTF/2023/pwn/Promise/read.py
ctfs/0CTF/2023/pwn/Promise/read.py
import sys import os def main(): if not os.path.exists(sys.argv[1]): return print('Please input script:') script = sys.stdin.read(30000) end = script.find('EOF') if end != -1: script = script[:end] with open(sys.argv[1], 'w') as f: f.write(script) 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/0CTF/2023/pwn/Nothing_is_True/server.py
ctfs/0CTF/2023/pwn/Nothing_is_True/server.py
#!/usr/bin/python3 -u import os, sys, random, subprocess, gmpy2 from io import BytesIO from hashlib import sha3_256 from elftools.elf.elffile import ELFFile from elftools.elf.constants import P_FLAGS os.chdir(os.path.dirname(__file__)) def proof_of_work(sec = 10): # From 0CTF/TCTF 2021 p = gmpy2.next_prime(random.getrandbits(512)) q = gmpy2.next_prime(random.getrandbits(512)) n = p*q c = 2900000 t = c*sec + random.randint(0,c) print('Show me your computation:') print(f'2^(2^{t}) mod {n} = ?') print('Your answer: ', end='') try: sol = int(sys.stdin.readline()) phi = (p-1)*(q-1) u = pow(2, t, phi) w = pow(2, u, n) if w == sol: print('Correct!') return True else: print('Wrong Answer!') exit() except ValueError: print('Invalid Input!') exit() def check_bytes(data, b): p = -1 while True: p = data.find(b, p+1) if p == -1: return True elif p & 0xfff == 0 or p & 0xfff == 0xfff: return False def check_segments(elf): for seg in elf.iter_segments(): if seg.header.p_filesz > 0x10000 or seg.header.p_memsz > 0x10000: print('Segment too large') return False elif seg.header.p_type == 'PT_INTERP' or seg.header.p_type == 'PT_DYNAMIC': print('No dynamic link') return False elif seg.header.p_type == 'PT_LOAD' and seg.header.p_flags & P_FLAGS.PF_W and seg.header.p_flags & P_FLAGS.PF_X: print('W^X') return False elif seg.header.p_type == 'PT_GNU_STACK' and seg.header.p_flags & P_FLAGS.PF_X: print('No executable stack') return False return True def check_elf(data): if len(data) < 0x40: print('Incomplete ELF Header') return False if not data.startswith(b'\x7fELF\x02\x01\x01' + b'\x00'*9): print('Invalid ELF Magic') return False if b'\xcd\x80' in data or b'\x0f\x05' in data: print('Bad Instruction') return False if not check_bytes(data, b'\xcd') or not check_bytes(data, b'\x80') or not check_bytes(data, b'\x0f') or not check_bytes(data, b'\x05'): print('Bad Instruction') return False elf = ELFFile(BytesIO(data)) if ((elf.header.e_type != 'ET_EXEC' and elf.header.e_type != 'ET_DYN') or elf.header.e_version != 'EV_CURRENT' or elf.header.e_ehsize != 0x40 or elf.header.e_phoff != 0x40 or elf.header.e_phnum <= 0 or elf.header.e_phnum >= 100): print('Bad ELF Header') return False return check_segments(elf) def main(): try: size = int(input('Size of your ELF: ')) except: print('Invalid size!') return if size <= 0 or size > 0x10000: print('Bad size!') return print('ELF File:') try: data = sys.stdin.buffer.read(size) except: print('Invalid file data') return if len(data) != size: print('Incomplete file data') return print('Received: %d bytes' % len(data)) if check_elf(data): filename = sha3_256(data).hexdigest() print(f'File Hash: {filename}') path = f'./data/{filename}' if os.path.exists(path): os.unlink(path) open(path, 'wb').write(data) os.chmod(path, 0o555) try: p = subprocess.Popen(['docker', 'run', '-i', '--rm', '-v', f'{path}:/chroot/{filename}', 'tctf/launcher64:2023', filename], stdin=subprocess.DEVNULL, stdout=subprocess.PIPE, stderr=subprocess.DEVNULL) p.wait() print('Return status: %d' % p.returncode) if p.returncode == 137: print('Output:') sys.stdout.buffer.write(p.stdout.read()) return except: print('Something went wrong!') if __name__ == '__main__': if proof_of_work(): main() print('Bye!')
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/0CTF/2023/pwn/Everything_is_Permitted/wrapper.py
ctfs/0CTF/2023/pwn/Everything_is_Permitted/wrapper.py
#!/usr/bin/python3 -u import os, sys, random, subprocess, gmpy2 from io import BytesIO from hashlib import sha3_256 from elftools.elf.elffile import ELFFile from elftools.elf.constants import P_FLAGS os.chdir(os.path.dirname(__file__)) def proof_of_work(sec = 10): # From 0CTF/TCTF 2021 "checkin" p = gmpy2.next_prime(random.getrandbits(512)) q = gmpy2.next_prime(random.getrandbits(512)) n = p*q c = 2900000 t = c*sec + random.randint(0,c) print('Show me your computation:') print(f'2^(2^{t}) mod {n} = ?') print('Your answer: ', end='') try: sol = int(sys.stdin.readline()) phi = (p-1)*(q-1) u = pow(2, t, phi) w = pow(2, u, n) if w == sol: print('Correct!') return True else: print('Wrong Answer!') exit() except ValueError: print('Invalid Input!') exit() def check_bytes(data, b): p = -1 while True: p = data.find(b, p+1) if p == -1: return True elif p & 0xfff == 0 or p & 0xfff == 0xfff: return False def check_segments(elf): for seg in elf.iter_segments(): if seg.header.p_filesz > 0x10000 or seg.header.p_memsz > 0x10000: print('Segment too large') return False elif seg.header.p_type == 'PT_INTERP' or seg.header.p_type == 'PT_DYNAMIC': print('No dynamic link') return False elif seg.header.p_type == 'PT_LOAD' and seg.header.p_flags & P_FLAGS.PF_W and seg.header.p_flags & P_FLAGS.PF_X: print('W^X') return False elif seg.header.p_type == 'PT_GNU_STACK' and seg.header.p_flags & P_FLAGS.PF_X: print('No executable stack') return False return True def check_elf(data): if len(data) < 0x34: print('Incomplete ELF Header') return False if not data.startswith(b'\x7fELF\x01\x01\x01' + b'\x00'*9): print('Invalid ELF Magic') return False if b'\xcd\x80' in data or b'\x0f\x05' in data: print('Bad Instruction') return False if not check_bytes(data, b'\xcd') or not check_bytes(data, b'\x80') or not check_bytes(data, b'\x0f') or not check_bytes(data, b'\x05'): print('Bad Instruction') return False elf = ELFFile(BytesIO(data)) if ((elf.header.e_type != 'ET_EXEC' and elf.header.e_type != 'ET_DYN') or elf.header.e_version != 'EV_CURRENT' or elf.header.e_ehsize != 0x34 or elf.header.e_phoff != 0x34 or elf.header.e_phnum <= 0 or elf.header.e_phnum >= 100): print('Bad ELF Header') return False return check_segments(elf) def main(): try: size = int(input('Size of your ELF: ')) except: print('Invalid size!') return if size <= 0 or size > 0x10000: print('Bad size!') return print('ELF File:') try: data = sys.stdin.buffer.read(size) except: print('Invalid file data') return if len(data) != size: print('Incomplete file data') return print('Received: %d bytes' % len(data)) if check_elf(data): filename = sha3_256(data).hexdigest() print(f'File Hash: {filename}') path = f'./data/{filename}' if os.path.exists(path): os.unlink(path) open(path, 'wb').write(data) os.chmod(path, 0o555) try: p = subprocess.Popen(['docker', 'run', '-i', '--rm', '-v', f'{path}:/chroot/{filename}', 'tctf/launcher32:2023', filename], stdin=subprocess.DEVNULL, stdout=subprocess.PIPE, stderr=subprocess.DEVNULL) p.wait() print('Return status: %d' % p.returncode) if p.returncode == 137: print('Output:') sys.stdout.buffer.write(p.stdout.read()) return except: print('Something went wrong!') if __name__ == '__main__': if proof_of_work(): main() print('Bye!')
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/0CTF/2023/rev/how2compile_allinone/pow.py
ctfs/0CTF/2023/rev/how2compile_allinone/pow.py
import random, sys import gmpy2 def proof_of_work(sec = 60): # From 0CTF/TCTF 2021 p = gmpy2.next_prime(random.getrandbits(512)) q = gmpy2.next_prime(random.getrandbits(512)) n = p*q c = 2900000 t = c*sec + random.randint(0,c) print('Show me your computation:') print(f'2^(2^{t}) mod {n} = ?') print('Your answer: ', end='') try: sol = int(sys.stdin.readline()) phi = (p-1)*(q-1) u = pow(2, t, phi) w = pow(2, u, n) if w == sol: print('Correct!') return True else: print('Wrong Answer!') exit(1) except ValueError: print('Invalid Input!') exit(1) if __name__ == '__main__': if proof_of_work(): exit(0) else: exit(1)
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/0CTF/2023/crypto/blocky_4.5/Cipher.py
ctfs/0CTF/2023/crypto/blocky_4.5/Cipher.py
from GF import GF SBOX, INV_SBOX = dict(), dict() for i in range(3 ** 5): v = GF(23) + (GF(0) if i == 0 else GF(i).inverse()) SBOX[GF(i)] = v INV_SBOX[v] = GF(i) class BlockCipher: def __init__(self, key: bytes, rnd: int): assert len(key) == 9 sks = [GF(b) for b in key] for i in range(rnd * 9): sks.append(sks[-1] + SBOX[sks[-9]]) self.subkeys = [sks[i:i+9] for i in range(0, (rnd + 1) * 9, 9)] self.rnd = rnd def _add_key(self, l1, l2): return [x + y for x, y in zip(l1, l2)] def _sub_key(self, l1, l2): return [x - y for x, y in zip(l1, l2)] def _sub(self, l): return [SBOX[x] for x in l] def _sub_inv(self, l): return [INV_SBOX[x] for x in l] def _shift(self, b): return [ b[0], b[1], b[2], b[4], b[5], b[3], b[8], b[6], b[7] ] def _shift_inv(self, b): return [ b[0], b[1], b[2], b[5], b[3], b[4], b[7], b[8], b[6] ] def _mix(self, b): b = b[:] # Copy for i in range(3): x = GF(7) * b[i] + GF(2) * b[3 + i] + b[6 + i] y = GF(2) * b[i] + b[3 + i] + GF(7) * b[6 + i] z = b[i] + GF(7) * b[3 + i] + GF(2) * b[6 + i] b[i], b[3 + i], b[6 + i] = x, y, z return b def _mix_inv(self, b): b = b[:] # Copy for i in range(3): x = GF(86) * b[i] + GF(222) * b[3 + i] + GF(148) * b[6 + i] y = GF(222) * b[i] + GF(148) * b[3 + i] + GF(86) * b[6 + i] z = GF(148) * b[i] + GF(86) * b[3 + i] + GF(222) * b[6 + i] b[i], b[3 + i], b[6 + i] = x, y, z return b def encrypt(self, inp: bytes): assert len(inp) == 9 b = [GF(x) for x in inp] b = self._add_key(b, self.subkeys[0]) for i in range(self.rnd): b = self._sub(b) b = self._shift(b) if i < self.rnd - 2: b = self._mix(b) b = self._add_key(b, self.subkeys[i + 1]) return bytes([x.to_int() for x in b]) def decrypt(self, inp: bytes): assert len(inp) == 9 b = [GF(x) for x in inp] for i in reversed(range(self.rnd)): b = self._sub_key(b, self.subkeys[i + 1]) if i < self.rnd - 2: b = self._mix_inv(b) b = self._shift_inv(b) b = self._sub_inv(b) b = self._sub_key(b, self.subkeys[0]) return bytes([x.to_int() for x in b]) if __name__ == "__main__": import random key = bytes(random.randint(0, 242) for i in range(9)) cipher = BlockCipher(key, 5) for _ in range(100): pt = bytes(random.randint(0, 242) for i in range(9)) ct = cipher.encrypt(pt) pt_ = cipher.decrypt(ct) assert pt == pt_
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/0CTF/2023/crypto/blocky_4.5/task.py
ctfs/0CTF/2023/crypto/blocky_4.5/task.py
#!/usr/bin/env python3 import random import signal import socketserver import string from Cipher import BlockCipher from hashlib import sha256 from os import urandom from secret import FLAG MENU = """ [1] Encrypt [2] Decrypt [3] Guess""" def get_key(): key = b'' while len(key) < 9: b = urandom(1) if b[0] < 243: key += b return key class Task(socketserver.BaseRequestHandler): def __init__(self, *args, **kargs): super().__init__(*args, **kargs) def proof_of_work(self): random.seed(urandom(16)) proof = ''.join([random.choice(string.ascii_letters + string.digits) for _ in range(20)]) digest = sha256(proof.encode()).hexdigest() self.dosend('sha256(XXXX + {}) == {}'.format(proof[4: ], digest)) self.dosend('Give me XXXX:') x = self.request.recv(10) x = x.strip().decode('latin-1') if len(x) != 4 or sha256((x + proof[4: ]).encode()).hexdigest() != digest: return False return True def dosend(self, msg): try: self.request.sendall(msg.encode('latin-1') + b'\n') except: pass def timeout_handler(self, signum, frame): raise TimeoutError def recvn(self, sz): r = sz res = b'' while r > 0: res += self.request.recv(r) if res.endswith(b'\n'): r = 0 else: r = sz - len(res) res = res.strip() return res def handle(self): try: signal.signal(signal.SIGALRM, self.timeout_handler) signal.alarm(60) if not self.proof_of_work(): self.dosend('You must pass the PoW!') return signal.alarm(int(13.37)) key = get_key() cipher = BlockCipher(key, 5) self.dosend(MENU) for _ in range(int(13.37)): op = int(self.recvn(2)) if op == 1: pt = get_key() ct = cipher.encrypt(pt) self.dosend('pt: ' + pt.hex()) self.dosend('ct: ' + ct.hex()) elif op == 2: self.dosend('ct: ') ct = bytes.fromhex(self.recvn(19).decode()) assert all(bb < 243 for bb in ct) pt = cipher.decrypt(ct) self.dosend('pt: ' + pt.hex()) elif op == 3: guess = bytes.fromhex(self.recvn(19).decode()) if guess == key: self.dosend('Wow, how do you know that?') self.dosend('Here is the flag: ' + FLAG) else: self.dosend('Wrong!') break else: break except TimeoutError: self.dosend('Timeout!') except: self.dosend('GG') self.request.close() class ThreadedServer(socketserver.ForkingMixIn, socketserver.TCPServer): pass if __name__ == "__main__": HOST, PORT = '0.0.0.0', 31337 server = ThreadedServer((HOST, PORT), Task) server.allow_reuse_address = True server.serve_forever()
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/0CTF/2023/crypto/blocky_4.5/GF.py
ctfs/0CTF/2023/crypto/blocky_4.5/GF.py
class GF: def __init__(self, value): if type(value) == int: self.value = [(value // (3 ** i)) % 3 for i in range(5)] elif type(value) == list and len(value) == 5: self.value = value else: assert False, "Wrong input to the constructor" def __str__(self): return f"GF({self.to_int()})" def __repr__(self): return str(self) def __hash__(self): return hash(tuple(self.value)) def __eq__(self, other): assert type(other) == GF return self.value == other.value def __add__(self, other): assert type(other) == GF return GF([(x + y) % 3 for x, y in zip(self.value, other.value)]) def __sub__(self, other): assert type(other) == GF return GF([(x - y) % 3 for x, y in zip(self.value, other.value)]) def __mul__(self, other): assert type(other) == GF arr = [0 for _ in range(9)] for i in range(5): for j in range(5): arr[i + j] = (arr[i + j] + self.value[i] * other.value[j]) % 3 # Modulus: x^5 + 2*x + 1 for i in range(8, 4, -1): arr[i - 4] = (arr[i - 4] - 2 * arr[i]) % 3 arr[i - 5] = (arr[i - 5] - arr[i]) % 3 return GF(arr[:5]) def __pow__(self, other): assert type(other) == int base, ret = self, GF(1) while other > 0: if other & 1: ret = ret * base other >>= 1 base = base * base return ret def inverse(self): return self ** 241 def __div__(self, other): assert type(other) == GF return self * other.inverse() def to_int(self): return sum([self.value[i] * (3 ** i) for i in range(5)]) if __name__ == "__main__": assert GF(3) * GF(3) == GF(9) assert GF(9) * GF(27) == GF(5) assert GF(5).inverse() == GF(240)
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/0CTF/2023/crypto/Double_RSA_2/task.py
ctfs/0CTF/2023/crypto/Double_RSA_2/task.py
#!/usr/bin/env python3 import random import signal import socketserver import string from Crypto.Util.number import * from hashlib import sha256 from secret import FLAG from os import urandom P_BITS = 512 E_BITS = int(P_BITS * 2 * 0.292) + 30 CNT_MAX = 760 class LCG: def __init__(self): self.init() def next(self): out = self.s[0] self.s = self.s[1: ] + [(sum([i * j for (i, j) in zip(self.a, self.s)]) + self.b) % self.p] return out def init(self): while True: p = getPrime(2 * P_BITS) if p.bit_length() == 2 * P_BITS: self.p = p break self.b = getRandomRange(1, self.p) self.a = [getRandomRange(1, self.p) for _ in range(6)] self.s = [getRandomRange(1, self.p) for _ in range(6)] class RSA: def __init__(self, l, p = 0, q = 0): self.l = l if not p: while True: p = getPrime(P_BITS) if p.bit_length() == P_BITS: self.p = p break while True: p = getPrime(P_BITS) if p.bit_length() == P_BITS: self.q = p break else: self.p = abs(p) self.q = abs(q) self.e = getPrime(E_BITS) self.check() def enc(self, m): return pow(m, self.e, self.n) def noisy_enc(self, m, r = 1): if r: self.refresh() return pow(m, self.e ^ self.l.next(), self.n) def dec(self, c): return pow(c, self.d, self.n) def check(self): assert self.p.bit_length() == P_BITS assert self.q.bit_length() == P_BITS self.n = self.p * self.q self.phi = (self.p - 1) * (self.q - 1) assert self.e.bit_length() >= E_BITS assert self.e < self.phi assert GCD(self.e, self.phi) == 1 self.d = inverse(self.e, self.phi) assert self.d.bit_length() >= E_BITS for _ in range(20): x = self.l.next() % self.n assert self.dec(self.enc(x)) == x def refresh(self): self.e = (self.e ^ self.l.next()) % (2**E_BITS) class Task(socketserver.BaseRequestHandler): def __init__(self, *args, **kargs): super().__init__(*args, **kargs) def proof_of_work(self): random.seed(urandom(16)) proof = ''.join([random.choice(string.ascii_letters + string.digits) for _ in range(20)]) digest = sha256(proof.encode()).hexdigest() self.dosend('sha256(XXXX + {}) == {}'.format(proof[4: ], digest)) self.dosend('Give me XXXX:') x = self.request.recv(10) x = x.strip().decode('latin-1') if len(x) != 4 or sha256((x + proof[4: ]).encode()).hexdigest() != digest: return False return True def dosend(self, msg): try: self.request.sendall(msg.encode('latin-1') + b'\n') except: pass def timeout_handler(self, signum, frame): raise TimeoutError def recvn(self, sz): r = sz res = b'' while r > 0: res += self.request.recv(r) if res.endswith(b'\n'): r = 0 else: r = sz - len(res) res = res.strip() return res def recv_hex(self, l): return int(self.recvn(l + 1), 16) def handle(self): try: signal.signal(signal.SIGALRM, self.timeout_handler) signal.alarm(60) if not self.proof_of_work(): self.dosend('You must pass the PoW!') return signal.alarm(240) self.dosend('Give me your RSA key plz.') pq = [self.recv_hex(P_BITS // 4) for _ in range(2)] lcg = LCG() alice = RSA(lcg) bob = RSA(lcg, *pq) secrets = getRandomNBitInteger(P_BITS) secrets_ct = alice.enc(secrets) self.dosend('{}\n{}\n{}'.format(lcg.p, lcg.a, lcg.b)) CNT = 0 while CNT < CNT_MAX: self.dosend('pt: ') pt = self.recv_hex(P_BITS // 2) if pt == 0: break ct = alice.noisy_enc(pt) ct = bob.noisy_enc(ct) self.dosend('ct: ' + hex(ct)) CNT += 1 secrets_ct = bob.noisy_enc(secrets_ct) self.dosend('secrets_ct: ' + hex(secrets_ct)) lcg.init() bob = RSA(lcg, *pq) seen = set() while CNT < CNT_MAX: self.dosend('ct: ') ct = self.recv_hex(P_BITS // 2) if ct == 0: break pt = alice.dec(ct) if pt in seen: self.dosend('You can only decrypt each ciphertext once.') self.request.close() else: seen.add(pt) pt = bob.noisy_enc(pt) self.dosend('pt: ' + hex(pt)) CNT += 1 self.dosend('{}\n{}\n{}'.format(lcg.p, lcg.a, lcg.b)) guess = self.recv_hex(P_BITS // 4) if guess == secrets: self.dosend('Wow, how do you know that?') self.dosend('Here is the flag: ' + FLAG) else: self.dosend('Wrong!') except TimeoutError: self.dosend('Timeout!') except: self.dosend('GG') self.request.close() class ThreadedServer(socketserver.ForkingMixIn, socketserver.TCPServer): pass if __name__ == "__main__": HOST, PORT = '0.0.0.0', 32227 server = ThreadedServer((HOST, PORT), Task) server.allow_reuse_address = True server.serve_forever()
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/0CTF/2023/crypto/Double_RSA_0/task.py
ctfs/0CTF/2023/crypto/Double_RSA_0/task.py
#!/usr/bin/env python3 import random import signal import socketserver import string from Crypto.Util.number import * from hashlib import sha256 from secret import FLAG from os import urandom P_BITS = 512 E_BITS = int(P_BITS * 2 * 0.292) + 30 CNT_MAX = 7 class LCG: def __init__(self): self.init() def next(self): out = self.s[0] self.s = self.s[1: ] + [(sum([i * j for (i, j) in zip(self.a, self.s)]) + self.b) % self.p] return out def init(self): while True: p = getPrime(2 * P_BITS) if p.bit_length() == 2 * P_BITS: self.p = p break self.b = getRandomRange(1, self.p) self.a = [getRandomRange(1, self.p) for _ in range(6)] self.s = [getRandomRange(1, self.p) for _ in range(6)] class RSA: def __init__(self, l, p = 0, q = 0): self.l = l if not p: while True: p = getPrime(P_BITS) if p.bit_length() == P_BITS: self.p = p break while True: p = getPrime(P_BITS) if p.bit_length() == P_BITS: self.q = p break else: self.p = abs(p) self.q = abs(q) self.e = getPrime(E_BITS) self.check() def enc(self, m): return pow(m, self.e, self.n) def noisy_enc(self, m, r = 1): if r: self.refresh() return pow(m, self.e ^ self.l.next(), self.n) def dec(self, c): return pow(c, self.d, self.n) def check(self): assert self.p.bit_length() == P_BITS assert self.q.bit_length() == P_BITS self.n = self.p * self.q self.phi = (self.p - 1) * (self.q - 1) assert self.e.bit_length() >= E_BITS assert self.e < self.phi assert GCD(self.e, self.phi) == 1 self.d = inverse(self.e, self.phi) assert self.d.bit_length() >= E_BITS for _ in range(20): x = self.l.next() % self.n assert self.dec(self.enc(x)) == x def refresh(self): self.e = (self.e ^ self.l.next()) % (2**E_BITS) class Task(socketserver.BaseRequestHandler): def __init__(self, *args, **kargs): super().__init__(*args, **kargs) def proof_of_work(self): random.seed(urandom(16)) proof = ''.join([random.choice(string.ascii_letters + string.digits) for _ in range(20)]) digest = sha256(proof.encode()).hexdigest() self.dosend('sha256(XXXX + {}) == {}'.format(proof[4: ], digest)) self.dosend('Give me XXXX:') x = self.request.recv(10) x = x.strip().decode('latin-1') if len(x) != 4 or sha256((x + proof[4: ]).encode()).hexdigest() != digest: return False return True def dosend(self, msg): try: self.request.sendall(msg.encode('latin-1') + b'\n') except: pass def timeout_handler(self, signum, frame): raise TimeoutError def recvn(self, sz): r = sz res = b'' while r > 0: res += self.request.recv(r) if res.endswith(b'\n'): r = 0 else: r = sz - len(res) res = res.strip() return res def recv_hex(self, l): return int(self.recvn(l + 1), 16) def handle(self): try: signal.signal(signal.SIGALRM, self.timeout_handler) signal.alarm(60) if not self.proof_of_work(): self.dosend('You must pass the PoW!') return signal.alarm(20) self.dosend('Give me your RSA key plz.') pq = [self.recv_hex(P_BITS // 4) for _ in range(2)] lcg = LCG() alice = RSA(lcg) bob = RSA(lcg, *pq) secrets = getRandomNBitInteger(P_BITS // 8) secrets_ct = alice.enc(secrets) self.dosend('{}\n{}'.format(alice.e, alice.n)) self.dosend('{}\n{}\n{}\n{}'.format(lcg.p, lcg.a, lcg.b, lcg.s)) CNT = 0 while CNT < CNT_MAX: self.dosend('pt: ') pt = self.recv_hex(P_BITS // 2) if pt == 0: break ct = alice.noisy_enc(pt) ct = bob.noisy_enc(ct) self.dosend('ct: ' + hex(ct)) CNT += 1 print(secrets_ct) secrets_ct = bob.noisy_enc(secrets_ct) self.dosend('secrets_ct: ' + hex(secrets_ct)) lcg.init() bob = RSA(lcg, *pq) self.dosend('{}\n{}\n{}\n{}'.format(lcg.p, lcg.a, lcg.b, lcg.s)) seen = set() while CNT < CNT_MAX: self.dosend('ct: ') ct = self.recv_hex(P_BITS // 2) if ct == 0: break pt = alice.dec(ct) if pt in seen: self.dosend('You can only decrypt each ciphertext once.') self.request.close() else: seen.add(pt) pt = bob.noisy_enc(pt) self.dosend('pt: ' + hex(pt)) CNT += 1 guess = self.recv_hex(P_BITS // 4) if guess == secrets: self.dosend('Wow, how do you know that?') self.dosend('Here is the flag: ' + FLAG) else: self.dosend('Wrong!') except TimeoutError: self.dosend('Timeout!') except: self.dosend('GG') self.request.close() class ThreadedServer(socketserver.ForkingMixIn, socketserver.TCPServer): pass if __name__ == "__main__": HOST, PORT = '0.0.0.0', 32226 server = ThreadedServer((HOST, PORT), Task) server.allow_reuse_address = True server.serve_forever()
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/0CTF/2023/crypto/Double_RSA_1/task.py
ctfs/0CTF/2023/crypto/Double_RSA_1/task.py
#!/usr/bin/env python3 import random import signal import socketserver import string from Crypto.Util.number import * from hashlib import sha256 from secret import FLAG from os import urandom P_BITS = 512 E_BITS = int(P_BITS * 2 * 0.292) + 30 CNT_MAX = 70 class LCG: def __init__(self): self.init() def next(self): out = self.s[0] self.s = self.s[1: ] + [(sum([i * j for (i, j) in zip(self.a, self.s)]) + self.b) % self.p] return out def init(self): while True: p = getPrime(P_BITS) if p.bit_length() == P_BITS: self.p = p break self.b = getRandomRange(1, self.p) self.a = [getRandomRange(1, self.p) for _ in range(6)] self.s = [getRandomRange(1, self.p) for _ in range(6)] class RSA: def __init__(self, l, p = 0, q = 0): self.l = l if not p: while True: p = getPrime(P_BITS) if p.bit_length() == P_BITS: self.p = p break while True: p = getPrime(P_BITS) if p.bit_length() == P_BITS: self.q = p break else: self.p = abs(p) self.q = abs(q) self.e = getPrime(E_BITS) self.check() def enc(self, m): return pow(m, self.e, self.n) def noisy_enc(self, m, r = 1): if r: self.refresh() return pow(m, self.e ^ self.l.next(), self.n) def dec(self, c): return pow(c, self.d, self.n) def check(self): assert self.p.bit_length() == P_BITS assert self.q.bit_length() == P_BITS self.n = self.p * self.q self.phi = (self.p - 1) * (self.q - 1) assert self.e.bit_length() >= E_BITS assert self.e < self.phi assert GCD(self.e, self.phi) == 1 self.d = inverse(self.e, self.phi) assert self.d.bit_length() >= E_BITS for _ in range(20): x = self.l.next() % self.n assert self.dec(self.enc(x)) == x def refresh(self): self.e = (self.e ^ self.l.next()) % (2**E_BITS) class Task(socketserver.BaseRequestHandler): def __init__(self, *args, **kargs): super().__init__(*args, **kargs) def proof_of_work(self): random.seed(urandom(16)) proof = ''.join([random.choice(string.ascii_letters + string.digits) for _ in range(20)]) digest = sha256(proof.encode()).hexdigest() self.dosend('sha256(XXXX + {}) == {}'.format(proof[4: ], digest)) self.dosend('Give me XXXX:') x = self.request.recv(10) x = x.strip().decode('latin-1') if len(x) != 4 or sha256((x + proof[4: ]).encode()).hexdigest() != digest: return False return True def dosend(self, msg): try: self.request.sendall(msg.encode('latin-1') + b'\n') except: pass def timeout_handler(self, signum, frame): raise TimeoutError def recvn(self, sz): r = sz res = b'' while r > 0: res += self.request.recv(r) if res.endswith(b'\n'): r = 0 else: r = sz - len(res) res = res.strip() return res def recv_hex(self, l): return int(self.recvn(l + 1), 16) def handle(self): try: signal.signal(signal.SIGALRM, self.timeout_handler) signal.alarm(60) if not self.proof_of_work(): self.dosend('You must pass the PoW!') return signal.alarm(20) self.dosend('Give me your RSA key plz.') pq = [self.recv_hex(P_BITS // 4) for _ in range(2)] lcg = LCG() alice = RSA(lcg) bob = RSA(lcg, *pq) secrets = getRandomNBitInteger(P_BITS // 8) secrets_ct = alice.enc(secrets) self.dosend('{}\n{}\n{}'.format(lcg.p, lcg.a, lcg.b)) CNT = 0 while CNT < CNT_MAX: self.dosend('pt: ') pt = self.recv_hex(P_BITS // 2) if pt == 0: break ct = alice.noisy_enc(pt) ct = bob.noisy_enc(ct) self.dosend('ct: ' + hex(ct)) CNT += 1 secrets_ct = bob.noisy_enc(secrets_ct) self.dosend('secrets_ct: ' + hex(secrets_ct)) lcg.init() bob = RSA(lcg, *pq) seen = set() while CNT < CNT_MAX: self.dosend('ct: ') ct = self.recv_hex(P_BITS // 2) if ct == 0: break pt = alice.dec(ct) if pt in seen: self.dosend('You can only decrypt each ciphertext once.') self.request.close() else: seen.add(pt) pt = bob.noisy_enc(pt) self.dosend('pt: ' + hex(pt)) CNT += 1 guess = self.recv_hex(P_BITS // 4) if guess == secrets: self.dosend('Wow, how do you know that?') self.dosend('Here is the flag: ' + FLAG) else: self.dosend('Wrong!') except TimeoutError: self.dosend('Timeout!') except: self.dosend('GG') self.request.close() class ThreadedServer(socketserver.ForkingMixIn, socketserver.TCPServer): pass if __name__ == "__main__": HOST, PORT = '0.0.0.0', 32225 server = ThreadedServer((HOST, PORT), Task) server.allow_reuse_address = True server.serve_forever()
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/0CTF/2023/crypto/blocky_4.5_lite/Cipher.py
ctfs/0CTF/2023/crypto/blocky_4.5_lite/Cipher.py
from GF import GF SBOX, INV_SBOX = dict(), dict() for i in range(3 ** 5): v = GF(23) + (GF(0) if i == 0 else GF(i).inverse()) SBOX[GF(i)] = v INV_SBOX[v] = GF(i) class BlockCipher: def __init__(self, key: bytes, rnd: int): assert len(key) == 9 sks = [GF(b) for b in key] for i in range(rnd * 9): sks.append(sks[-1] + SBOX[sks[-9]]) self.subkeys = [sks[i:i+9] for i in range(0, (rnd + 1) * 9, 9)] self.rnd = rnd def _add_key(self, l1, l2): return [x + y for x, y in zip(l1, l2)] def _sub_key(self, l1, l2): return [x - y for x, y in zip(l1, l2)] def _sub(self, l): return [SBOX[x] for x in l] def _sub_inv(self, l): return [INV_SBOX[x] for x in l] def _shift(self, b): return [ b[0], b[1], b[2], b[4], b[5], b[3], b[8], b[6], b[7] ] def _shift_inv(self, b): return [ b[0], b[1], b[2], b[5], b[3], b[4], b[7], b[8], b[6] ] def _mix(self, b): b = b[:] # Copy for i in range(3): x = GF(7) * b[i] + GF(2) * b[3 + i] + b[6 + i] y = GF(2) * b[i] + b[3 + i] + GF(7) * b[6 + i] z = b[i] + GF(7) * b[3 + i] + GF(2) * b[6 + i] b[i], b[3 + i], b[6 + i] = x, y, z return b def _mix_inv(self, b): b = b[:] # Copy for i in range(3): x = GF(86) * b[i] + GF(222) * b[3 + i] + GF(148) * b[6 + i] y = GF(222) * b[i] + GF(148) * b[3 + i] + GF(86) * b[6 + i] z = GF(148) * b[i] + GF(86) * b[3 + i] + GF(222) * b[6 + i] b[i], b[3 + i], b[6 + i] = x, y, z return b def encrypt(self, inp: bytes): assert len(inp) == 9 b = [GF(x) for x in inp] b = self._add_key(b, self.subkeys[0]) for i in range(self.rnd): b = self._sub(b) b = self._shift(b) if i < self.rnd - 2: b = self._mix(b) b = self._add_key(b, self.subkeys[i + 1]) return bytes([x.to_int() for x in b]) def decrypt(self, inp: bytes): assert len(inp) == 9 b = [GF(x) for x in inp] for i in reversed(range(self.rnd)): b = self._sub_key(b, self.subkeys[i + 1]) if i < self.rnd - 2: b = self._mix_inv(b) b = self._shift_inv(b) b = self._sub_inv(b) b = self._sub_key(b, self.subkeys[0]) return bytes([x.to_int() for x in b]) if __name__ == "__main__": import random key = bytes(random.randint(0, 242) for i in range(9)) cipher = BlockCipher(key, 5) for _ in range(100): pt = bytes(random.randint(0, 242) for i in range(9)) ct = cipher.encrypt(pt) pt_ = cipher.decrypt(ct) assert pt == pt_
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/0CTF/2023/crypto/blocky_4.5_lite/task.py
ctfs/0CTF/2023/crypto/blocky_4.5_lite/task.py
#!/usr/bin/env python3 import random import signal import socketserver import string from Cipher import BlockCipher from hashlib import sha256 from os import urandom from secret import FLAG MENU = """ [1] Encrypt [2] Decrypt [3] Guess""" def get_key(): key = b'' while len(key) < 9: b = urandom(1) if b[0] < 243: key += b return key class Task(socketserver.BaseRequestHandler): def __init__(self, *args, **kargs): super().__init__(*args, **kargs) def proof_of_work(self): random.seed(urandom(16)) proof = ''.join([random.choice(string.ascii_letters + string.digits) for _ in range(20)]) digest = sha256(proof.encode()).hexdigest() self.dosend('sha256(XXXX + {}) == {}'.format(proof[4: ], digest)) self.dosend('Give me XXXX:') x = self.request.recv(10) x = x.strip().decode('latin-1') if len(x) != 4 or sha256((x + proof[4: ]).encode()).hexdigest() != digest: return False return True def dosend(self, msg): try: self.request.sendall(msg.encode('latin-1') + b'\n') except: pass def timeout_handler(self, signum, frame): raise TimeoutError def recvn(self, sz): r = sz res = b'' while r > 0: res += self.request.recv(r) if res.endswith(b'\n'): r = 0 else: r = sz - len(res) res = res.strip() return res def handle(self): try: signal.signal(signal.SIGALRM, self.timeout_handler) signal.alarm(60) if not self.proof_of_work(): self.dosend('You must pass the PoW!') return signal.alarm(int(337.1)) key = get_key() cipher = BlockCipher(key, 5) self.dosend(MENU) for _ in range(int(133.7)): op = int(self.recvn(2)) if op == 1: self.dosend('pt: ') pt = bytes.fromhex(self.recvn(19).decode()) assert all(bb < 243 for bb in pt) ct = cipher.encrypt(pt) self.dosend('ct: ' + ct.hex()) elif op == 2: self.dosend('ct: ') ct = bytes.fromhex(self.recvn(19).decode()) assert all(bb < 243 for bb in ct) pt = cipher.decrypt(ct) self.dosend('pt: ' + pt.hex()) elif op == 3: guess = bytes.fromhex(self.recvn(19).decode()) if guess == key: self.dosend('Wow, how do you know that?') self.dosend('Here is the flag: ' + FLAG) else: self.dosend('Wrong!') break else: break except TimeoutError: self.dosend('Timeout!') except: self.dosend('GG') self.request.close() class ThreadedServer(socketserver.ForkingMixIn, socketserver.TCPServer): pass if __name__ == "__main__": HOST, PORT = '0.0.0.0', 31338 server = ThreadedServer((HOST, PORT), Task) server.allow_reuse_address = True server.serve_forever()
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/0CTF/2023/crypto/blocky_4.5_lite/GF.py
ctfs/0CTF/2023/crypto/blocky_4.5_lite/GF.py
class GF: def __init__(self, value): if type(value) == int: self.value = [(value // (3 ** i)) % 3 for i in range(5)] elif type(value) == list and len(value) == 5: self.value = value else: assert False, "Wrong input to the constructor" def __str__(self): return f"GF({self.to_int()})" def __repr__(self): return str(self) def __hash__(self): return hash(tuple(self.value)) def __eq__(self, other): assert type(other) == GF return self.value == other.value def __add__(self, other): assert type(other) == GF return GF([(x + y) % 3 for x, y in zip(self.value, other.value)]) def __sub__(self, other): assert type(other) == GF return GF([(x - y) % 3 for x, y in zip(self.value, other.value)]) def __mul__(self, other): assert type(other) == GF arr = [0 for _ in range(9)] for i in range(5): for j in range(5): arr[i + j] = (arr[i + j] + self.value[i] * other.value[j]) % 3 # Modulus: x^5 + 2*x + 1 for i in range(8, 4, -1): arr[i - 4] = (arr[i - 4] - 2 * arr[i]) % 3 arr[i - 5] = (arr[i - 5] - arr[i]) % 3 return GF(arr[:5]) def __pow__(self, other): assert type(other) == int base, ret = self, GF(1) while other > 0: if other & 1: ret = ret * base other >>= 1 base = base * base return ret def inverse(self): return self ** 241 def __div__(self, other): assert type(other) == GF return self * other.inverse() def to_int(self): return sum([self.value[i] * (3 ** i) for i in range(5)]) if __name__ == "__main__": assert GF(3) * GF(3) == GF(9) assert GF(9) * GF(27) == GF(5) assert GF(5).inverse() == GF(240)
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/0CTF/2023/crypto/Double_RSA_3/task.py
ctfs/0CTF/2023/crypto/Double_RSA_3/task.py
#!/usr/bin/env python3 import random import signal import socketserver import string from Crypto.Util.number import * from hashlib import sha256 from secret import FLAG from os import urandom P_BITS = 512 E_BITS = int(P_BITS * 2 * 0.292) + 30 CNT_MAX = 910 class LCG: def __init__(self): self.init() def next(self): out = self.s[0] self.s = self.s[1: ] + [(sum([i * j for (i, j) in zip(self.a, self.s)]) + self.b) % self.p] return out def init(self): while True: p = getPrime(2 * P_BITS) if p.bit_length() == 2 * P_BITS: self.p = p break self.b = getRandomRange(1, self.p) self.a = [getRandomRange(1, self.p) for _ in range(6)] self.s = [getRandomRange(1, self.p) for _ in range(6)] class RSA: def __init__(self, l, p = 0, q = 0): self.l = l if not p: while True: p = getPrime(P_BITS) if p.bit_length() == P_BITS: self.p = p break while True: p = getPrime(P_BITS) if p.bit_length() == P_BITS: self.q = p break else: self.p = abs(p) self.q = abs(q) self.e = getPrime(E_BITS) self.check() def enc(self, m): return pow(m, self.e, self.n) def noisy_enc(self, m, r = 1): if r: self.refresh() return pow(m, self.e ^ self.l.next(), self.n) def dec(self, c): return pow(c, self.d, self.n) def check(self): assert self.p.bit_length() == P_BITS assert self.q.bit_length() == P_BITS self.n = self.p * self.q self.phi = (self.p - 1) * (self.q - 1) assert self.e.bit_length() >= E_BITS assert self.e < self.phi assert GCD(self.e, self.phi) == 1 self.d = inverse(self.e, self.phi) assert self.d.bit_length() >= E_BITS for _ in range(20): x = self.l.next() % self.n assert self.dec(self.enc(x)) == x def refresh(self): self.e = (self.e ^ self.l.next()) % (2**E_BITS) class Task(socketserver.BaseRequestHandler): def __init__(self, *args, **kargs): super().__init__(*args, **kargs) def proof_of_work(self): random.seed(urandom(16)) proof = ''.join([random.choice(string.ascii_letters + string.digits) for _ in range(20)]) digest = sha256(proof.encode()).hexdigest() self.dosend('sha256(XXXX + {}) == {}'.format(proof[4: ], digest)) self.dosend('Give me XXXX:') x = self.request.recv(10) x = x.strip().decode('latin-1') if len(x) != 4 or sha256((x + proof[4: ]).encode()).hexdigest() != digest: return False return True def dosend(self, msg): try: self.request.sendall(msg.encode('latin-1') + b'\n') except: pass def timeout_handler(self, signum, frame): raise TimeoutError def recvn(self, sz): r = sz res = b'' while r > 0: res += self.request.recv(r) if res.endswith(b'\n'): r = 0 else: r = sz - len(res) res = res.strip() return res def recv_hex(self, l): return int(self.recvn(l + 1), 16) def handle(self): try: signal.signal(signal.SIGALRM, self.timeout_handler) signal.alarm(60) if not self.proof_of_work(): self.dosend('You must pass the PoW!') return signal.alarm(360) self.dosend('Give me your RSA key plz.') pq = [self.recv_hex(P_BITS // 4) for _ in range(2)] lcg = LCG() alice = RSA(lcg) bob = RSA(lcg, *pq) secrets = getRandomNBitInteger(P_BITS) secrets_ct = alice.enc(secrets) self.dosend('{}\n{}\n{}'.format(lcg.p, lcg.a, lcg.b)) CNT = 0 while CNT < CNT_MAX: self.dosend('pt: ') pt = self.recv_hex(P_BITS // 2) if pt == 0: break ct = alice.noisy_enc(pt) ct = bob.noisy_enc(ct) self.dosend('ct: ' + hex(ct)) CNT += 1 secrets_ct = bob.noisy_enc(secrets_ct) self.dosend('secrets_ct: ' + hex(secrets_ct)) lcg.init() bob = RSA(lcg, *pq) seen = set() while CNT < CNT_MAX: self.dosend('ct: ') ct = self.recv_hex(P_BITS // 2) if ct == 0: break pt = alice.dec(ct) if pt in seen: self.dosend('You can only decrypt each ciphertext once.') self.request.close() else: seen.add(pt) pt = bob.noisy_enc(pt) self.dosend('pt: ' + hex(pt)) CNT += 1 self.dosend('{}\n{}'.format(lcg.a[-1], lcg.b % (2**E_BITS))) guess = self.recv_hex(P_BITS // 4) if guess == secrets: self.dosend('Wow, how do you know that?') self.dosend('Here is the flag: ' + FLAG) else: self.dosend('Wrong!') except TimeoutError: self.dosend('Timeout!') except: self.dosend('GG') self.request.close() class ThreadedServer(socketserver.ForkingMixIn, socketserver.TCPServer): pass if __name__ == "__main__": HOST, PORT = '0.0.0.0', 32224 server = ThreadedServer((HOST, PORT), Task) server.allow_reuse_address = True server.serve_forever()
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/0CTF/2023/web/olapinfra/hive/init_db.py
ctfs/0CTF/2023/web/olapinfra/hive/init_db.py
#!/usr/bin/python3 import time import os import subprocess import pymysql def check_mysql(): while True: try: conn = pymysql.connect(host = 'mysql', port = 3306, user='root', password='123456', charset='utf8', autocommit=True) if conn: break except Exception as e: pass time.sleep(3) print('MySQL is not ready...') print('MySQL Connected') check_mysql() time.sleep(10) check_mysql() # check twice def run_sql(s): cmd = 'beeline -u "jdbc:hive2://127.0.0.1:10000" -e "{}"'.format(s) status, output = subprocess.getstatusoutput(cmd) return status == 0 os.system("su hive -m -c 'schematool -dbType mysql -initSchema'") # CH requires a indepent metastore instance os.system('su hive -m -c "hive --service metastore &"') while True: time.sleep(3) if run_sql('SELECT 1'): break run_sql('CREATE TABLE u_data (userid INT, movieid INT, rating INT, unixtime STRING) ROW FORMAT DELIMITED FIELDS TERMINATED BY \'\t\' LOCATION \'hdfs://namenode:8020/data/hive/data/default.db/u_data\';') run_sql('LOAD DATA LOCAL INPATH \'/opt/ml-100k/u.data\' OVERWRITE INTO TABLE u_data;')
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/0CTF/2025/crypto/baby_discriminator/task.py
ctfs/0CTF/2025/crypto/baby_discriminator/task.py
import random from hashlib import md5, sha256 import secrets import string import numpy as np import sys try: from secret import flag except ImportError: flag = "0ops{this_is_a_test_flag}" window = 5 total_nums = 20000 vector_size = 140 def proof_of_work(): challenge = ''.join(secrets.choice(string.ascii_letters + string.digits) for _ in range(8)) difficulty = 6 print(f"Proof of Work challenge:") print(f"sha256({challenge} + ???) starts with {'0' * difficulty}") sys.stdout.write("Enter your answer: ") sys.stdout.flush() answer = sys.stdin.readline().strip() hash_res = sha256((challenge + answer).encode()).hexdigest() if hash_res.startswith('0' * difficulty): return True return False def choose_one(seed = None): p_v = 10 ** np.random.uniform(0, 13, size=total_nums) if seed is not None: seed_int = int(seed, 16) rng = np.random.default_rng(seed_int) else: rng = np.random.default_rng() us = rng.random(total_nums) return int(np.argmax(np.log(us) / p_v)) def get_vector(bit): if bit == 0: v = [] for _ in range(vector_size): seed = md5(str(v[-window:]).encode()).hexdigest() if len(v) >= window else None v.append(choose_one(seed)) to_change = secrets.randbelow(65) pos = random.choices(range(vector_size), k=to_change) for p in pos: v[p] = choose_one() return v else: return [choose_one() for _ in range(vector_size)] if not proof_of_work(): print("PoW verification failed!") exit() banner = """ █████ ███ █████ ████ ████ █████ █████ █████████ ███████████ ███████████ ░░███ ░███ ░░███ ░░███ ░░███ ░░███ ███░░░███ ███░░░░░███░█░░░███░░░█░░███░░░░░░█ ░███ ░███ ░███ ██████ ░███ ░███ ██████ ██████ █████████████ ███████ ██████ ███ ░░███ ███ ░░░ ░ ░███ ░ ░███ █ ░ ░███ ░███ ░███ ███░░███ ░███ ░███ ███░░███ ███░░███░░███░░███░░███ ░░░███░ ███░░███ ░███ ░███░███ ░███ ░███████ ░░███ █████ ███ ░███████ ░███ ░███ ░███ ░░░ ░███ ░███ ░███ ░███ ░███ ░███ ░███ ░███ ░███ ░███░███ ░███ ░███░░░█ ░░░█████░█████░ ░███░░░ ░███ ░███ ░███ ███░███ ░███ ░███ ░███ ░███ ░███ ███░███ ░███ ░░███ ███ ░░███ ███ ░███ ░███ ░ ░░███ ░░███ ░░██████ █████ █████░░██████ ░░██████ █████░███ █████ ░░█████ ░░██████ ░░░█████░ ░░█████████ █████ █████ ░░░ ░░░ ░░░░░░ ░░░░░ ░░░░░ ░░░░░░ ░░░░░░ ░░░░░ ░░░ ░░░░░ ░░░░░ ░░░░░░ ░░░░░░ ░░░░░░░░░ ░░░░░ ░░░░░ """ print(banner) print("Are u ready to play the game") play_times = 200 for i in range(play_times): bit = secrets.randbelow(2) v = get_vector(bit) print("Vector: ", v) print("Please tell me the bit of the vector") try: user_bit = int(input()) except ValueError: print("Invalid input") exit() if user_bit != bit: print("Wrong answer") exit() print("You are a good guesser, the flag is ", flag)
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/0CTF/2022/pwn/babysnitch/service.py
ctfs/0CTF/2022/pwn/babysnitch/service.py
#! /usr/bin/python2 import subprocess import tempfile import sys,os import random,string from hashlib import sha256 def proof_of_work(): proof = ''.join([random.choice(string.ascii_letters+string.digits) for _ in xrange(20)]) digest = sha256(proof).hexdigest() sys.stdout.write("sha256(XXXX+%s) == %s\n" % (proof[4:],digest)) sys.stdout.write('Give me XXXX:') sys.stdout.flush() x = sys.stdin.readline() x = x.strip() if len(x) != 4 or sha256(x+proof[4:]).hexdigest() != digest: return False sys.stdout.write('OK\n') sys.stdout.flush() return True def main(): try: size = int(sys.stdin.readline()) except: return if size > 1000000: return exp = sys.stdin.read(size) f = tempfile.NamedTemporaryFile(prefix='',delete=False) f.write(exp) f.close() # hopefully they will not collide cname = "a"+str(random.randint(0,0x100000)) subprocess.check_output(["docker", "run", "--cap-add=NET_ADMIN", "--rm", "--name", cname, "-itd", "chal", "sleep", "20"]) subprocess.check_output(["docker", "cp", f.name, cname+":/home/test/test"]) subprocess.check_output(["timeout", "10", "docker", "exec", cname, "/run.sh"]) os.unlink(f.name) if __name__ == '__main__': if proof_of_work(): main()
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/0CTF/2022/crypto/leopard/task.py
ctfs/0CTF/2022/crypto/leopard/task.py
#!/usr/bin/env python3 import random import signal import socketserver import string from cipher import AEAD from hashlib import sha256 from os import urandom from secret import flag class Task(socketserver.BaseRequestHandler): def __init__(self, *args, **kargs): super().__init__(*args, **kargs) def proof_of_work(self): random.seed(urandom(8)) proof = ''.join([random.choice(string.ascii_letters + string.digits + '!#$%&*-?') for _ in range(20)]) digest = sha256(proof.encode()).hexdigest() self.dosend('sha256(XXXX + {}) == {}'.format(proof[4: ], digest)) self.dosend('Give me XXXX:') x = self.request.recv(10) x = (x.strip()).decode('utf-8') if len(x) != 4 or sha256((x + proof[4: ]).encode()).hexdigest() != digest: return False return True def dosend(self, msg): try: self.request.sendall(msg.encode('latin-1') + b'\n') except: pass def timeout_handler(self, signum, frame): raise TimeoutError def handle(self): try: signal.signal(signal.SIGALRM, self.timeout_handler) signal.alarm(50) if not self.proof_of_work(): self.dosend('You must pass the PoW!') return signal.alarm(300) msg = b'The quick brown fox jumps over the lazy dog.' ad = b'0CTF2022' key = urandom(16) iv = urandom(16) C1 = AEAD(key, iv) C2 = AEAD(key, iv, True) ct1, _ = C1.encrypt(msg, ad) ct2, _ = C2.encrypt(msg, ad) self.dosend(ct1.hex()) self.dosend(ct2.hex()) key_ = self.request.recv(64).strip() iv_ = self.request.recv(64).strip() if key.hex().encode('latin-1') == key_ and iv.hex().encode('latin-1') == iv_: self.dosend(flag) else: self.dosend(':(') except TimeoutError: self.dosend('Timeout!') self.request.close() except: self.dosend('Wtf?') self.request.close() class ThreadedServer(socketserver.ForkingMixIn, socketserver.TCPServer): pass if __name__ == "__main__": HOST, PORT = '0.0.0.0', 31337 server = ThreadedServer((HOST, PORT), Task) server.allow_reuse_address = True server.serve_forever()
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/0CTF/2022/crypto/leopard/cipher.py
ctfs/0CTF/2022/crypto/leopard/cipher.py
def pad(s): l = 8 - (len(s) % 8) return s + l * bytearray([l]) def unpad(s): assert s[-1] <= 8 return s[: -s[-1]] def gmul(a, b): c = 0 while a and b: if b & 1: c ^= a a <<= 1 if a & 0x100: a ^= 0x11d b >>= 1 return c def gen_sbox(): """ SBOX is generated in a similar way as AES, i.e., linear transform over the multiplicative inverse (L * x^-1 + C), to prevent differential fault analysis. """ INV = [0, 1, 142, 244, 71, 167, 122, 186, 173, 157, 221, 152, 61, 170, 93, 150, 216, 114, 192, 88, 224, 62, 76, 102, 144, 222, 85, 128, 160, 131, 75, 42, 108, 237, 57, 81, 96, 86, 44, 138, 112, 208, 31, 74, 38, 139, 51, 110, 72, 137, 111, 46, 164, 195, 64, 94, 80, 34, 207, 169, 171, 12, 21, 225, 54, 95, 248, 213, 146, 78, 166, 4, 48, 136, 43, 30, 22, 103, 69, 147, 56, 35, 104, 140, 129, 26, 37, 97, 19, 193, 203, 99, 151, 14, 55, 65, 36, 87, 202, 91, 185, 196, 23, 77, 82, 141, 239, 179, 32, 236, 47, 50, 40, 209, 17, 217, 233, 251, 218, 121, 219, 119, 6, 187, 132, 205, 254, 252, 27, 84, 161, 29, 124, 204, 228, 176, 73, 49, 39, 45, 83, 105, 2, 245, 24, 223, 68, 79, 155, 188, 15, 92, 11, 220, 189, 148, 172, 9, 199, 162, 28, 130, 159, 198, 52, 194, 70, 5, 206, 59, 13, 60, 156, 8, 190, 183, 135, 229, 238, 107, 235, 242, 191, 175, 197, 100, 7, 123, 149, 154, 174, 182, 18, 89, 165, 53, 101, 184, 163, 158, 210, 247, 98, 90, 133, 125, 168, 58, 41, 113, 200, 246, 249, 67, 215, 214, 16, 115, 118, 120, 153, 10, 25, 145, 20, 63, 230, 240, 134, 177, 226, 241, 250, 116, 243, 180, 109, 33, 178, 106, 227, 231, 181, 234, 3, 143, 211, 201, 66, 212, 232, 117, 127, 255, 126, 253] L = [[0, 0, 1, 1, 0, 1, 0, 1], [0, 1, 1, 0, 1, 0, 1, 0], [1, 1, 0, 1, 0, 1, 0, 0], [1, 0, 1, 0, 1, 0, 0, 0], [0, 1, 1, 0, 0, 1, 0, 0], [1, 1, 1, 1, 1, 1, 0, 0], [1, 1, 0, 0, 1, 1, 0, 1], [1, 0, 0, 1, 1, 0, 1, 0]] C = [1, 0, 1, 1, 1, 0, 1, 0] S = [] for _ in range(256): inv = bin(INV[_])[2:].rjust(8, '0')[::-1] v = [sum([a * int(b) for (a, b) in zip(L[__], inv)] + [C[__]]) % 2 for __ in range(8)] S.append(sum([v[__] * 2**(7 - __) for __ in range(8)])) return S class AEAD: IDX = [6, 7, 15, 16, 24, 25, 34, 35] SBOX = gen_sbox() SKIP = 4 def __init__(self, key: bytes, iv: bytes, fault=False): assert len(key) == 16 assert len(iv) == 16 self.init_state(key, iv) self.fault = fault def init_state(self, key, iv): self.state = list(key + iv) self.state += [_ ^ 0xff for _ in key[: 3]] self.state += [0xef] self.update(1337) def update(self, n=1): for _ in range(n): P = self.state[ : 8] Q = self.state[ 8: 17] R = self.state[17: 26] S = self.state[26: ] P_ = ord('0') ^ P[0] ^ P[2] ^ P[3] ^ gmul(P[4], P[6]) ^ Q[5] Q_ = ord('C') ^ Q[0] ^ Q[3] ^ gmul(Q[1], Q[8]) ^ gmul(R[4], S[6]) R_ = ord('T') ^ R[0] ^ R[2] ^ R[3] ^ gmul(R[5], R[8]) ^ S[7] S_ = ord('F') ^ S[0] ^ S[8] ^ gmul(S[2], S[4]) ^ gmul(P[7], Q[2]) self.state = P[1:] + [self.SBOX[P_]] + \ Q[1:] + [self.SBOX[Q_]] + \ R[1:] + [self.SBOX[R_]] + \ S[1:] + [self.SBOX[S_]] def process_ad(self, ad): ad = pad(ad) for i in range(len(ad) // 8): tmp = ad[8 * i: 8 * i + 8] for _ in range(8): self.state[self.IDX[_]] ^= tmp[_] self.update(self.SKIP) def process_pt(self, pt, flag): if flag == 0: pt = pad(pt) ct = [] for i in range(len(pt) // 8): tmp = pt[8 * i: 8 * i + 8] for _ in range(8): if flag == 0: self.state[self.IDX[_]] ^= tmp[_] ct.append(self.state[self.IDX[_]]) else: ct.append(self.state[self.IDX[_]] ^ tmp[_]) self.state[self.IDX[_]] = tmp[_] if self.fault and i == len(pt) // 16 - 1: self.state[0] ^= 0xff if i + 1 != len(pt) // 8: self.update(self.SKIP) return bytes(ct) def generate_tg(self): self.update(137) tg = [] for i in range(2): for _ in range(8): tg.append(self.state[self.IDX[_]]) self.update(self.SKIP) return bytes(tg) def encrypt(self, pt, ad): self.process_ad(ad) ct = self.process_pt(pt, 0) tg = self.generate_tg() return ct, tg def decrypt(self, ct, ad, tg): self.process_ad(ad) pt = self.process_pt(ct, 1) tg_ = self.generate_tg() if tg_ != tg: return None else: return unpad(pt) if __name__ == "__main__": key = b'\xff' * 16 iv = b'\xee' * 16 msg = b'\xdd' * 16 ad = b'\xcc' * 16 C = AEAD(key, iv) ct, tg = C.encrypt(msg, ad) C = AEAD(key, iv) assert C.decrypt(ct, ad, tg) == msg
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/0CTF/2022/crypto/real_magic_dlog/task.py
ctfs/0CTF/2022/crypto/real_magic_dlog/task.py
#!/usr/bin/env python3 import random import signal import socketserver import string from Crypto.Util.number import * from hashlib import sha256, sha384 from os import urandom from secret import flag LEN = 17 class Task(socketserver.BaseRequestHandler): def __init__(self, *args, **kargs): super().__init__(*args, **kargs) def proof_of_work(self): random.seed(urandom(8)) proof = ''.join([random.choice(string.ascii_letters + string.digits + '!#$%&*-?') for _ in range(20)]) digest = sha256(proof.encode()).hexdigest() self.dosend('sha256(XXXX + {}) == {}'.format(proof[4: ], digest)) self.dosend('Give me XXXX:') x = self.request.recv(10) x = (x.strip()).decode('utf-8') if len(x) != 4 or sha256((x + proof[4: ]).encode()).hexdigest() != digest: return False return True def dosend(self, msg): try: self.request.sendall(msg.encode('latin-1') + b'\n') except: pass def timeout_handler(self, signum, frame): raise TimeoutError def recv_fromhex(self, l): passwd = self.request.recv(l).strip() passwd = bytes.fromhex(passwd.decode('latin-1')) return passwd def handle(self): try: signal.signal(signal.SIGALRM, self.timeout_handler) signal.alarm(50) if not self.proof_of_work(): self.dosend('You must pass the PoW!') return signal.alarm(60) magic = urandom(LEN) magic_num = bytes_to_long(magic) self.dosend(magic.hex()) self.dosend('P:>') P = int(self.request.recv(100).strip(), 16) self.dosend('E:>') E = int(self.request.recv(100).strip(), 16) self.dosend('data:>') data = self.request.recv(100).strip() num1 = int(data, 16) if P >> (384 - LEN * 8) == magic_num and isPrime(P): data2 = sha384(data).hexdigest() num2 = int(data2, 16) if pow(num1, E, P) == num2 % P: self.dosend(flag) else: self.dosend('try harder!!!') except TimeoutError: self.dosend('Timeout!') self.request.close() except: self.dosend('Wtf?') self.request.close() class ThreadedServer(socketserver.ForkingMixIn, socketserver.TCPServer): pass if __name__ == "__main__": HOST, PORT = '0.0.0.0', 15555 server = ThreadedServer((HOST, PORT), Task) server.allow_reuse_address = True server.serve_forever()
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/0CTF/2022/crypto/ezRSA_plusplus/task.py
ctfs/0CTF/2022/crypto/ezRSA_plusplus/task.py
from Crypto.Util.number import * from os import urandom from secret import flag def ExGCD(a, b): if 0 == b: return 1, 0, a x, y, q = ExGCD(b, a % b) x, y = y, (x - a // b * y) return x, y, q def gen(p_size, d_size, l_size): while True: p = getPrime(p_size) q = getPrime(p_size) if GCD(p - 1, q - 1) == 2: break d_p = getPrime(d_size) d_q = getPrime(d_size) s, t, g = ExGCD(p - 1, q - 1) if s < 0: s += q - 1 else: t += p - 1 n = p * q phi = (p - 1) * (q - 1) e = (inverse(d_p, p - 1) * t * (q - 1) + inverse(d_q, q - 1) * s * (p - 1)) // g % phi assert (e * d_q % (q - 1) == 1) assert (e * d_p % (p - 1) == 1) k = (e * d_p - 1) // (p - 1) l = (e * d_q - 1) // (q - 1) return (n, e), (d_p, d_q, p, q), (d_p % (2**l_size), d_q % (2**l_size)) def encrypt(m, pk): n, e = pk return pow(m, e, n) p_size = 1000 d_size = 105 l_size = 55 pk, sk, hint = gen(p_size, d_size, l_size) flag = urandom(2 * p_size // 8 - len(flag) - 1) + flag enc = encrypt(int(flag.hex(), 16), pk) print(enc) print(pk) print(hint) ''' 35558284230663313298312684064040643811204702946900174110911295087662938676356112802781671547473910691476600838877279843972105403072929243674403244286458898562457747942651643439624568905004454158744508429126554955023110569348839934098381885098523538078300248638407684468503519326866276798222721018258242443186786917829878515320321445508466038372324063139762003962072922393974710763356236627711414307859950011736526834586028087922704589199885845050751932885698053938070734392371814246294798366452078193195538346218718588887085179856336533576097324041969786125752304133487678308830354729347735644474025828 (44774502335951608354043148360684114092901940301155357314508676399067538307546121753785009844275454594381602690061553832466871574728524408152400619047820736137949166290404514747591817206669966103047443912935755873432503095952914080827536130899968275165557303493867755627520568588808534411526058896791373252974606364861105086430729757064078675811147972536205086402752245214343186536177015741922559575575911278873118556603923689408629477875537332177644886701517140711134017511229202430437068095342526435886609381176269251580339549071944830141516001532825295594908434587285225415103472279090325281062442217, 29624366183227462965645558392954094074485353876807451497147549927093025197118051280445930543762170853769573962200247669305286333212410439624262142109295839433584663989554419810341266820063074908743295553517790354149623873028162282751352613333181218478850463012413786673509078012976454604598813805735677104174112776060905225493357010861225261560490401501912259585922988353328944884443953564154752191932500561561256069872534626325000901099904014035414792860997025614313564862063784602254606240743545483125618939111639728114664995759380293512809125885893543730614962375399353971677980309835647540883700977) (5013415024346389, 4333469053087705) '''
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/0CTF/2022/crypto/chimera/SPN.py
ctfs/0CTF/2022/crypto/chimera/SPN.py
from copy import deepcopy S_BOX = [47, 13, 50, 214, 119, 149, 138, 113, 200, 93, 180, 247, 86, 189, 125, 97, 226, 249, 159, 168, 55, 118, 169, 178, 18, 49, 102, 65, 34, 231, 10, 192, 100, 122, 75, 177, 205, 29, 40, 124, 103, 131, 232, 234, 72, 114, 127, 66, 154, 243, 27, 236, 106, 181, 87, 129, 38, 26, 140, 151, 135, 73, 171, 239, 132, 95, 184, 148, 48, 4, 203, 183, 250, 44, 57, 0, 46, 158, 233, 161, 217, 39, 126, 210, 53, 215, 21, 9, 139, 68, 209, 248, 5, 242, 42, 79, 212, 7, 71, 155, 61, 251, 134, 199, 152, 80, 16, 111, 82, 81, 123, 12, 216, 94, 142, 146, 204, 172, 92, 147, 1, 186, 85, 230, 108, 221, 36, 246, 206, 59, 52, 37, 33, 153, 136, 45, 20, 98, 228, 188, 117, 245, 6, 223, 83, 17, 91, 207, 54, 160, 175, 220, 133, 28, 156, 3, 77, 15, 237, 89, 56, 30, 225, 202, 24, 193, 121, 227, 120, 174, 25, 201, 32, 96, 110, 252, 219, 70, 51, 255, 238, 74, 150, 170, 104, 213, 187, 244, 165, 2, 163, 11, 235, 253, 116, 191, 211, 176, 179, 19, 195, 22, 143, 62, 173, 190, 78, 222, 112, 254, 23, 208, 241, 196, 198, 240, 101, 41, 128, 144, 162, 69, 109, 60, 137, 197, 76, 8, 229, 84, 88, 141, 145, 164, 90, 166, 157, 67, 185, 115, 224, 35, 167, 130, 99, 14, 182, 43, 105, 194, 58, 64, 31, 218, 63, 107] S_BOX_INV = [S_BOX.index(_) for _ in range(len(S_BOX))] MIX_BOX = [[1, 3, 3, 7], [7, 1, 3, 3], [3, 7, 1, 3], [3, 3, 7, 1]] MIX_BOX_INV = [[234, 86, 195, 4], [4, 234, 86, 195], [195, 4, 234, 86], [86, 195, 4, 234]] RCON = [ 0x00, 0x01, 0x02, 0x04, 0x08, 0x10, 0x20, 0x40, 0x80, 0x1B, 0x36, 0x6C, 0xD8, 0xAB, 0x4D, 0x9A, 0x2F, 0x5E, 0xBC, 0x63, 0xC6, 0x97, 0x35, 0x6A, 0xD4, 0xB3, 0x7D, 0xFA, 0xEF, 0xC5, 0x91, 0x39, ] def GF2_mul(a, b): p = 0 for i in range(8): lsb = b & 1 b = b >> 1 if lsb: p = p ^ a lsb = a & 0x80 a = (a << 1) & 0xff if lsb: a = a ^ 0x1B return p def nsplit(s, n): return [s[k: k + n] for k in range(0, len(s), n)] def text2row(text): matrix = [[0 for _ in range(4)] for _ in range(4)] for i in range(4): for j in range(4): matrix[i][j] = text[4 * j + i] return matrix def row2text(matrix): text = 0 for i in range(4): for j in range(4): text |= (matrix[i][j] << (120 - 8 * (i + 4 * j))) return text.to_bytes(16, 'big') def subBytes(block): for i in range(4): for j in range(4): block[i][j] = S_BOX[block[i][j]] return block def shiftRows(block): for i in range(4): block[i] = block[i][i:] + block[i][:i] return block def addRoundKey(block1, block2): result = [[ 0 for i in range(4)] for j in range(4)] for i in range(4): for j in range(4): result[i][j] = block1[i][j] ^ block2[j][i] return result def xor_all(array): result = array[0] for i in range(1, len(array)): result ^= array[i] return result def mixColumns(block): result = [] for i in range(4): tmp = [] for j in range(4): x = xor_all([GF2_mul(MIX_BOX[i][m], block[m][j]) for m in range(4)]) tmp.append(x) result.append(tmp) return result def subBytes_inv(block): for i in range(4): for j in range(4): block[i][j] = S_BOX_INV[block[i][j]] return block def shiftRows_inv(block): for i in range(4): block[i] = block[i][-i:] + block[i][:-i] return block def mixColumns_inv(block): result = [] for i in range(4): tmp = [] for j in range(4): x = xor_all([GF2_mul(MIX_BOX_INV[i][m], block[m][j]) for m in range(4)]) tmp.append(x) result.append(tmp) return result class SPN(): def __init__(self, key, rnd=10): self.key = key self.rnd = rnd self.keys = list() self.generatekeys() def generatekeys(self): block = [self.key[i:i+4] for i in range(0, 16, 4)] self.keys.append(block) for i in range(1, 1 + self.rnd): self.keys.append([]) tmp = self.keys[i - 1][3] tmp = tmp[1:] + tmp[:1] tmp = [S_BOX[_] for _ in tmp] tmp[0] ^= RCON[i] for j in range(4): for k in range(4): if j == 0: tmp[k] ^= self.keys[i - 1][j][k] else: tmp[k] = self.keys[i - 1][j][k] ^ self.keys[i][j - 1][k] self.keys[i].append(deepcopy(tmp)) def encrypt(self, text): text_blocks = nsplit(text, 16) result = b"" for block in text_blocks: block = text2row(block) block = addRoundKey(block, self.keys[0]) for i in range(self.rnd): block = subBytes(block) if i != 0: block = shiftRows(block) if i != self.rnd - 1: block = mixColumns(block) block = addRoundKey(block, self.keys[i + 1]) result += row2text(block) return result def decrypt(self, text): text_blocks = nsplit(text, 16) result = b"" for block in text_blocks: block = text2row(block) for i in range(self.rnd): block = addRoundKey(block, self.keys[self.rnd - i]) if i != 0: block = mixColumns_inv(block) if i != self.rnd - 1: block = shiftRows_inv(block) block = subBytes_inv(block) block = addRoundKey(block, self.keys[0]) result += row2text(block) return result if __name__ == "__main__": key = b'\xff' * 16 pt = b'0123456789abcdef' spn = SPN(key, 4) ct = spn.encrypt(pt) print(spn.decrypt(ct) == pt)
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/0CTF/2022/crypto/chimera/task.py
ctfs/0CTF/2022/crypto/chimera/task.py
#!/usr/bin/env python3 import random import signal import socketserver import string from Chimera import Chimera from hashlib import sha256 from os import urandom from secret import flag assert len(flag) == 21 MENU = ''' Feistel + SPN = Chimera 1. Enc 2. Dec 3. Exit ''' def to_base64(x): bs = [] while x: bs.append(x % 64) x //= 64 return bs class Task(socketserver.BaseRequestHandler): def __init__(self, *args, **kargs): super().__init__(*args, **kargs) def proof_of_work(self): random.seed(urandom(8)) proof = ''.join([random.choice(string.ascii_letters + string.digits + '!#$%&*-?') for _ in range(20)]) digest = sha256(proof.encode()).hexdigest() self.dosend('sha256(XXXX + {}) == {}'.format(proof[4: ], digest)) self.dosend('Give me XXXX:') x = self.request.recv(10) x = (x.strip()).decode('utf-8') if len(x) != 4 or sha256((x + proof[4: ]).encode()).hexdigest() != digest: return False return True def dosend(self, msg): try: self.request.sendall(msg.encode('latin-1') + b'\n') except: pass def timeout_handler(self, signum, frame): raise TimeoutError def recv_fromhex(self, l): passwd = self.request.recv(l).strip() passwd = bytes.fromhex(passwd.decode('latin-1')) return passwd def handle(self): try: signal.signal(signal.SIGALRM, self.timeout_handler) signal.alarm(50) if not self.proof_of_work(): self.dosend('You must pass the PoW!') return signal.alarm(300) flag_ = to_base64(int(flag[5: -1].hex(), 16)) self.dosend('flag idx:') fidx = int(self.request.recv(64).strip()) self.dosend('key idx:') kidx = int(self.request.recv(64).strip()) key = bytearray(urandom(16)) key[kidx] = flag_[fidx] << 2 chimera = Chimera(key, 4) self.dosend(MENU) for _ in range(256): self.dosend('> ') op = int(self.request.recv(3).strip()) if op == 1: self.dosend('Pt: ') pt = self.recv_fromhex(0x404) assert len(pt) % 16 == 0 ct = chimera.encrypt(pt) self.dosend(ct.hex()) elif op == 2: self.dosend('Ct: ') ct = self.recv_fromhex(0x404) assert len(ct) % 16 == 0 pt = chimera.decrypt(ct) self.dosend(pt.hex()) else: return except TimeoutError: self.dosend('Timeout!') self.request.close() except: self.dosend('Wtf?') self.request.close() class ThreadedServer(socketserver.ForkingMixIn, socketserver.TCPServer): pass if __name__ == "__main__": HOST, PORT = '0.0.0.0', 16666 server = ThreadedServer((HOST, PORT), Task) server.allow_reuse_address = True server.serve_forever()
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/0CTF/2022/crypto/chimera/Feistel.py
ctfs/0CTF/2022/crypto/chimera/Feistel.py
SBOX = [ [5, 7, 4, 15, 3, 10, 13, 12, 9, 2, 8, 11, 6, 14, 0, 1, 3, 2, 13, 12, 1, 10, 11, 9, 7, 0, 4, 15, 14, 6, 8, 5, 5, 10, 7, 8, 9, 15, 1, 12, 4, 6, 3, 14, 2, 11, 13, 0, 9, 3, 10, 12, 8, 14, 5, 15, 2, 1, 0, 13, 11, 6, 4, 7], [7, 13, 2, 9, 4, 6, 14, 10, 12, 8, 0, 15, 3, 1, 11, 5, 3, 5, 14, 4, 11, 10, 2, 1, 13, 8, 12, 15, 6, 7, 0, 9, 0, 10, 14, 4, 7, 1, 11, 12, 3, 5, 9, 13, 2, 8, 15, 6, 7, 2, 14, 1, 10, 12, 6, 0, 9, 13, 15, 5, 3, 11, 4, 8], [5, 2, 15, 14, 13, 11, 4, 1, 12, 0, 8, 10, 3, 9, 7, 6, 10, 11, 6, 4, 15, 3, 1, 14, 9, 7, 2, 5, 12, 0, 13, 8, 1, 2, 12, 7, 0, 8, 3, 10, 4, 5, 15, 11, 13, 6, 14, 9, 10, 3, 9, 7, 4, 2, 12, 0, 5, 6, 14, 1, 13, 8, 11, 15], [13, 14, 5, 7, 3, 1, 0, 10, 6, 2, 12, 9, 8, 11, 15, 4, 4, 3, 0, 1, 2, 14, 13, 12, 10, 5, 8, 11, 6, 7, 15, 9, 15, 2, 10, 1, 4, 7, 6, 3, 9, 5, 8, 13, 0, 11, 12, 14, 4, 8, 7, 11, 15, 13, 12, 0, 5, 2, 3, 14, 10, 6, 9, 1], [1, 12, 3, 9, 14, 10, 2, 13, 15, 11, 6, 5, 7, 4, 8, 0, 7, 5, 6, 12, 0, 10, 15, 2, 4, 8, 13, 14, 1, 11, 9, 3, 7, 14, 0, 13, 1, 4, 5, 3, 11, 6, 12, 9, 10, 8, 15, 2, 3, 1, 5, 14, 9, 7, 0, 13, 8, 6, 2, 15, 11, 10, 4, 12], [9, 2, 0, 14, 13, 3, 8, 15, 6, 5, 12, 7, 10, 11, 1, 4, 14, 8, 4, 9, 15, 0, 10, 1, 5, 12, 7, 6, 11, 2, 13, 3, 2, 5, 7, 15, 9, 4, 8, 0, 14, 3, 13, 12, 11, 1, 6, 10, 12, 5, 9, 15, 14, 3, 6, 2, 7, 0, 8, 11, 10, 4, 1, 13], [13, 5, 3, 1, 10, 15, 6, 2, 14, 0, 11, 12, 7, 8, 4, 9, 0, 7, 12, 11, 6, 2, 9, 13, 5, 10, 3, 14, 4, 15, 1, 8, 9, 11, 2, 4, 7, 14, 10, 12, 15, 5, 13, 3, 8, 1, 6, 0, 4, 2, 9, 10, 3, 15, 1, 8, 6, 7, 11, 5, 13, 0, 14, 12], [11, 8, 0, 15, 10, 1, 3, 12, 9, 6, 5, 4, 14, 7, 2, 13, 8, 11, 5, 12, 1, 6, 0, 2, 14, 7, 10, 13, 3, 15, 9, 4, 5, 13, 2, 0, 12, 1, 7, 4, 9, 6, 14, 10, 11, 8, 15, 3, 11, 10, 12, 6, 1, 8, 2, 13, 9, 14, 7, 3, 15, 0, 4, 5], ] E = [31, 0, 1, 2, 3, 4, 3, 4, 5, 6, 7, 8, 7, 8, 9, 10, 11, 12, 11, 12, 13, 14, 15, 16, 15, 16, 17, 18, 19, 20, 19, 20, 21, 22, 23, 24, 23, 24, 25, 26, 27, 28, 27, 28, 29, 30, 31, 0] P = [23, 16, 6, 22, 20, 24, 15, 5, 17, 30, 28, 14, 4, 29, 9, 31, 18, 13, 26, 0, 25, 2, 3, 10, 19, 7, 1, 8, 21, 12, 11, 27] P_INV = [P.index(_) for _ in range(32)] PC = [27, 9, 1, 44, 26, 15, 18, 8, 34, 40, 0, 29, 39, 41, 13, 3, 23, 42, 6, 45, 19, 32, 43, 30, 21, 38, 37, 5, 17, 22, 16, 25, 28, 14, 24, 11, 10, 12, 31, 4, 7, 20, 33, 46, 47, 35, 36, 2] assert len(E) == 48 assert len(P) == 32 def nsplit(s, n): return [s[k: k + n] for k in range(0, len(s), n)] def s(x, i): row = ((x & 0b100000) >> 4) + (x & 1) col = (x & 0b011110) >> 1 return SBOX[i][(row << 4) + col] def p(x): x_bin = bin(x)[2:].rjust(32, '0') y_bin = [x_bin[P[i]] for i in range(len(P))] y = int(''.join([_ for _ in y_bin]), 2) return y def p_inv(x): x_bin = bin(x)[2:].rjust(32, '0') y_bin = [x_bin[P_INV[i]] for i in range(32)] y = int(''.join([_ for _ in y_bin]), 2) return y def e(x): x_bin = bin(x)[2:].rjust(32, '0') y_bin = [x_bin[E[i]] for i in range(len(E))] y = int(''.join([_ for _ in y_bin]), 2) return y def F(x, k): x_in = bin(e(x) ^ k)[2:].rjust(48, '0') y_out = '' for i in range(0, 48, 6): x_in_i = int(x_in[i: i + 6], 2) y_out += bin(s(x_in_i, i // 6))[2:].rjust(4, '0') y_out = int(y_out, 2) y = p(y_out) return y class Feistel(): def __init__(self, key, rnd=10): self.key = key self.rnd = rnd self.keys = list() self.generatekeys(self.key) def generatekeys(self, key): if isinstance(key, bytes) or isinstance(key, bytearray): key = int(key.hex(), 16) self.keys.append(key) key_bin = bin(key)[2:].rjust(48, '0') l, r = key_bin[: 24], key_bin[24: ] for i in range(self.rnd - 1): l, r = l[1: ] + l[: 1], r[2: ] + r[: 2] sub_key = ''.join([(l + r)[PC[j]] for j in range(48)]) self.keys.append(int(sub_key, 2)) def enc_block(self, x): x_bin = bin(x)[2:].rjust(64, '0') l, r = int(x_bin[: 32], 2), int(x_bin[32: ], 2) for i in range(self.rnd): l, r = r, l ^ F(r, self.keys[i]) y = (l + (r << 32)) & ((1 << 64) - 1) return y def dec_block(self, x): x_bin = bin(x)[2:].rjust(64, '0') l, r = int(x_bin[: 32], 2), int(x_bin[32: ], 2) for i in range(self.rnd): l, r = r, l ^ F(r, self.keys[self.rnd - i - 1]) y = (l + (r << 32)) & ((1 << 64) - 1) return y def encrypt(self, text): text_blocks = nsplit(text, 8) result = b"" for block in text_blocks: block = int(block.hex(), 16) result += self.enc_block(block).to_bytes(8, 'big') return result def decrypt(self, text): text_blocks = nsplit(text, 8) result = b"" for block in text_blocks: block = int(block.hex(), 16) result += self.dec_block(block).to_bytes(8, 'big') return result if __name__ == "__main__": key = b'\xff' * 6 pt = b'0123456789abcdef' feistel = Feistel(key, 4) ct = feistel.encrypt(pt) print(feistel.decrypt(ct) == pt)
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/0CTF/2022/crypto/chimera/Chimera.py
ctfs/0CTF/2022/crypto/chimera/Chimera.py
from SPN import SPN from Feistel import Feistel def nsplit(s, n): return [s[k: k + n] for k in range(0, len(s), n)] P = [3 * _ % 16 for _ in range(16)] P_INV = [P.index(_) for _ in range(16)] class Chimera(): def __init__(self, key, rnd=4): self.key = key self.C1a = Feistel(key[: 6], rnd) self.C1b = Feistel(key[6: 12], rnd) self.C2 = SPN(key, rnd) def encrypt(self, text): text_blocks = nsplit(text, 16) result = b"" for block in text_blocks: block_l = block[: 8] block_r = block[8: ] mid = self.C1a.encrypt(block_l) + self.C1b.encrypt(block_r) mid = bytearray([mid[i] for i in P]) result += self.C2.encrypt(mid) return result def decrypt(self, text): text_blocks = nsplit(text, 16) result = b"" for block in text_blocks: mid = self.C2.decrypt(block) mid = bytearray([mid[i] for i in P_INV]) block_l = mid[: 8] block_r = mid[8: ] pt = self.C1a.decrypt(block_l) + self.C1b.decrypt(block_r) result += pt return result if __name__ == "__main__": key = b'\xff' * 16 pt = b'0123456789abcdef' chimera = Chimera(key, 4) ct = chimera.encrypt(pt) print(chimera.decrypt(ct) == pt)
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/0CTF/2020/Quals/pwn/chromium_sbx/server.py
ctfs/0CTF/2020/Quals/pwn/chromium_sbx/server.py
#!/usr/bin/env python3 -u import hashlib import os import random import string import sys import subprocess import tempfile MAX_SIZE = 100 * 1024 print("Proof of work is required.") prefix = "".join([random.choice(string.digits + string.ascii_letters) for i in range(10)]) resource = prefix + "mojo" bits = 28 cash = input("Enter one result of `hashcash -b {} -m -r {}` : ".format(bits, resource)) r = subprocess.run(["hashcash", "-d", "-c", "-b", str(bits), "-r", resource], input=cash.encode('utf-8')) if r.returncode != 0: print("Nope!") exit() webpage_size = int(input("Enter size: ")) assert webpage_size < MAX_SIZE print("Give me your webpage: ") contents = sys.stdin.read(webpage_size) tmp = tempfile.mkdtemp(dir=os.getenv("WWW"), prefix=bytes.hex(os.urandom(8))) index_path = os.path.join(tmp, "index.html") with open(index_path, "w") as f: f.write(contents) sys.stderr.write("New submission at {}\n".format(index_path)) host = "host.docker.internal" net_args = [] if os.getenv("UNAME") == "Linux": net_args.append("--add-host={}:{}".format(host, os.getenv("HOST_IP"))) url = "http://{}:{}/{}/index.html".format( host, os.getenv("PORT"), os.path.basename(tmp) ) subprocess.run(["docker", "run", "--rm", "--privileged"] + net_args + ["mojo", url], stderr=sys.stdout)
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/0CTF/2020/Quals/pwn/chromium_fullchain/server.py
ctfs/0CTF/2020/Quals/pwn/chromium_fullchain/server.py
#!/usr/bin/env python3 -u import hashlib import os import random import string import sys import subprocess import tempfile MAX_SIZE = 100 * 1024 print("Proof of work is required.") prefix = "".join([random.choice(string.digits + string.ascii_letters) for i in range(10)]) resource = prefix + "mojo" bits = 28 cash = input("Enter one result of `hashcash -b {} -m -r {}` : ".format(bits, resource)) r = subprocess.run(["hashcash", "-d", "-c", "-b", str(bits), "-r", resource], input=cash.encode('utf-8')) if r.returncode != 0: print("Nope!") exit() webpage_size = int(input("Enter size: ")) assert webpage_size < MAX_SIZE print("Give me your webpage: ") contents = sys.stdin.read(webpage_size) tmp = tempfile.mkdtemp(dir=os.getenv("WWW"), prefix=bytes.hex(os.urandom(8))) index_path = os.path.join(tmp, "index.html") with open(index_path, "w") as f: f.write(contents) sys.stderr.write("New submission at {}\n".format(index_path)) host = "host.docker.internal" net_args = [] if os.getenv("UNAME") == "Linux": net_args.append("--add-host={}:{}".format(host, os.getenv("HOST_IP"))) url = "http://{}:{}/{}/index.html".format( host, os.getenv("PORT"), os.path.basename(tmp) ) subprocess.run(["docker", "run", "--rm", "--privileged"] + net_args + ["mojo", url], stderr=sys.stdout)
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/Union/2021/pwn/nutty/pow.py
ctfs/Union/2021/pwn/nutty/pow.py
#!/usr/bin/env python2.7 # # Copyright 2018 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from hashcash import check import random import string import sys import os SKIP_SECRET = "whoopshopeididn'tdistributeitthistime" bits = 28 resource = "".join(random.choice(string.ascii_lowercase) for i in range(8)) print("hashcash -mb{} {}".format(bits, resource)) sys.stdout.flush() stamp = sys.stdin.readline().strip() if stamp != SKIP_SECRET: if not stamp.startswith("1:"): print("only hashcash v1 supported") exit(1) if not check(stamp, resource=resource, bits=bits): print("invalid") exit(1) os.execv(sys.argv[1], sys.argv[1:])
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/Union/2021/pwn/nutty/hashcash.py
ctfs/Union/2021/pwn/nutty/hashcash.py
#!/usr/bin/env python2.3 """Implement Hashcash version 1 protocol in Python +-------------------------------------------------------+ | Written by David Mertz; released to the Public Domain | +-------------------------------------------------------+ Double spend database not implemented in this module, but stub for callbacks is provided in the 'check()' function The function 'check()' will validate hashcash v1 and v0 tokens, as well as 'generalized hashcash' tokens generically. Future protocol version are treated as generalized tokens (should a future version be published w/o this module being correspondingly updated). A 'generalized hashcash' is implemented in the '_mint()' function, with the public function 'mint()' providing a wrapper for actual hashcash protocol. The generalized form simply finds a suffix that creates zero bits in the hash of the string concatenating 'challenge' and 'suffix' without specifying any particular fields or delimiters in 'challenge'. E.g., you might get: >>> from hashcash import mint, _mint >>> mint('foo', bits=16) '1:16:040922:foo::+ArSrtKd:164b3' >>> _mint('foo', bits=16) '9591' >>> from sha import sha >>> sha('foo9591').hexdigest() '0000de4c9b27cec9b20e2094785c1c58eaf23948' >>> sha('1:16:040922:foo::+ArSrtKd:164b3').hexdigest() '0000a9fe0c6db2efcbcab15157735e77c0877f34' Notice that '_mint()' behaves deterministically, finding the same suffix every time it is passed the same arguments. 'mint()' incorporates a random salt in stamps (as per the hashcash v.1 protocol). """ import sys from string import ascii_letters from math import ceil, floor from hashlib import sha1 as sha from random import choice from time import strftime, localtime, time #ERR = sys.stderr # Destination for error messages DAYS = 60 * 60 * 24 # Seconds in a day tries = [0] # Count hashes performed for benchmark def mint(resource, bits=20, now=None, ext='', saltchars=8, stamp_seconds=False): """Mint a new hashcash stamp for 'resource' with 'bits' of collision 20 bits of collision is the default. 'ext' lets you add your own extensions to a minted stamp. Specify an extension as a string of form 'name1=2,3;name2;name3=var1=2,2,val' FWIW, urllib.urlencode(dct).replace('&',';') comes close to the hashcash extension format. 'saltchars' specifies the length of the salt used; this version defaults 8 chars, rather than the C version's 16 chars. This still provides about 17 million salts per resource, per timestamp, before birthday paradox collisions occur. Really paranoid users can use a larger salt though. 'stamp_seconds' lets you add the option time elements to the datestamp. If you want more than just day, you get all the way down to seconds, even though the spec also allows hours/minutes without seconds. """ ver = "1" now = now or time() if stamp_seconds: ts = strftime("%y%m%d%H%M%S", localtime(now)) else: ts = strftime("%y%m%d", localtime(now)) challenge = "%s:"*6 % (ver, bits, ts, resource, ext, _salt(saltchars)) return challenge + _mint(challenge, bits) def _salt(l): "Return a random string of length 'l'" alphabet = ascii_letters + "+/=" return ''.join([choice(alphabet) for _ in [None]*l]) def _mint(challenge, bits): """Answer a 'generalized hashcash' challenge' Hashcash requires stamps of form 'ver:bits:date:res:ext:rand:counter' This internal function accepts a generalized prefix 'challenge', and returns only a suffix that produces the requested SHA leading zeros. NOTE: Number of requested bits is rounded up to the nearest multiple of 4 """ counter = 0 hex_digits = int(ceil(bits/4.)) zeros = '0'*hex_digits while 1: digest = sha(challenge+hex(counter)[2:]).hexdigest() if digest[:hex_digits] == zeros: tries[0] = counter return hex(counter)[2:] counter += 1 def check(stamp, resource=None, bits=None, check_expiration=None, ds_callback=None): """Check whether a stamp is valid Optionally, the stamp may be checked for a specific resource, and/or it may require a minimum bit value, and/or it may be checked for expiration, and/or it may be checked for double spending. If 'check_expiration' is specified, it should contain the number of seconds old a date field may be. Indicating days might be easier in many cases, e.g. >>> from hashcash import DAYS >>> check(stamp, check_expiration=28*DAYS) NOTE: Every valid (version 1) stamp must meet its claimed bit value NOTE: Check floor of 4-bit multiples (overly permissive in acceptance) """ if stamp.startswith('0:'): # Version 0 try: date, res, suffix = stamp[2:].split(':') except ValueError: #ERR.write("Malformed version 0 hashcash stamp!\n") return False if resource is not None and resource != res: return False elif check_expiration is not None: good_until = strftime("%y%m%d%H%M%S", localtime(time()-check_expiration)) if date < good_until: return False elif callable(ds_callback) and ds_callback(stamp): return False elif type(bits) is not int: return True else: hex_digits = int(floor(bits/4)) return sha(stamp).hexdigest().startswith('0'*hex_digits) elif stamp.startswith('1:'): # Version 1 try: claim, date, res, ext, rand, counter = stamp[2:].split(':') except ValueError: #ERR.write("Malformed version 1 hashcash stamp!\n") return False if resource is not None and resource != res: return False elif type(bits) is int and bits > int(claim): return False elif check_expiration is not None: good_until = strftime("%y%m%d%H%M%S", localtime(time()-check_expiration)) if date < good_until: return False elif callable(ds_callback) and ds_callback(stamp): return False else: hex_digits = int(floor(int(claim)/4)) return sha(stamp).hexdigest().startswith('0'*hex_digits) else: # Unknown ver or generalized hashcash #ERR.write("Unknown hashcash version: Minimal authentication!\n") if type(bits) is not int: return True elif resource is not None and stamp.find(resource) < 0: return False else: hex_digits = int(floor(bits/4)) return sha(stamp).hexdigest().startswith('0'*hex_digits) def is_doublespent(stamp): """Placeholder for double spending callback function The check() function may accept a 'ds_callback' argument, e.g. check(stamp, "mertz@gnosis.cx", bits=20, ds_callback=is_doublespent) This placeholder simply reports stamps as not being double spent. """ return False if __name__=='__main__': # Import Psyco if available try: import psyco psyco.bind(_mint) except ImportError: pass import optparse out, err = sys.stdout.write, sys.stderr.write parser = optparse.OptionParser(version="%prog 0.1", usage="%prog -c|-m [-b bits] [string|STDIN]") parser.add_option('-b', '--bits', type='int', dest='bits', default=20, help="Specify required collision bits" ) parser.add_option('-m', '--mint', help="Mint a new stamp", action='store_true', dest='mint') parser.add_option('-c', '--check', help="Check a stamp for validity", action='store_true', dest='check') parser.add_option('-s', '--timer', help="Time the operation performed", action='store_true', dest='timer') parser.add_option('-n', '--raw', help="Suppress trailing newline", action='store_true', dest='raw') (options, args) = parser.parse_args() start = time() if options.mint: action = mint elif options.check: action = check else: out("Try: %s --help\n" % sys.argv[0]) sys.exit() if args: out(str(action(args[0], bits=options.bits))) else: out(str(action(sys.stdin.read(), bits=options.bits))) if not options.raw: sys.stdout.write('\n') if options.timer: timer = time()-start err("Completed in %0.4f seconds (%d hashes per second)\n" % (timer, tries[0]/timer))
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/Union/2021/crypto/cr0wn_st3rling/cr0wn_sterling.py
ctfs/Union/2021/crypto/cr0wn_st3rling/cr0wn_sterling.py
#!/usr/bin/env python3 from secrets import flag, musical_key from Crypto.Util.number import isPrime import math def sieve_for_primes_to(n): # Copyright Eratosthenes, 204 BC size = n//2 sieve = [1]*size limit = int(n**0.5) for i in range(1, limit): if sieve[i]: val = 2*i+1 tmp = ((size-1) - i)//val sieve[i+val::val] = [0]*tmp return [2] + [i*2+1 for i, v in enumerate(sieve) if v and i > 0] def is_quasi_prime(n, primes): # novel class of semi-prime numbers # https://arxiv.org/pdf/1903.08570.pdf p2 = 0 for p1 in primes: if n % p1 == 0: p2 = n//p1 break if isPrime(p2) and not p1 in [2, 3] and not p2 in [2, 3]: return True return False def bbp_pi(n): # Bailey-Borwein-Plouffe Formula # sounds almost as cool as Blum-Blum-Shub # nth hex digit of pi def S(j, n): s = 0.0 k = 0 while k <= n: r = 8*k+j s = (s + pow(16, n-k, r) / r) % 1.0 k += 1 t = 0.0 k = n + 1 while 1: newt = t + pow(16, n-k) / (8*k+j) if t == newt: break else: t = newt k += 1 return s + t n -= 1 x = (4*S(1, n) - 2*S(4, n) - S(5, n) - S(6, n)) % 1.0 return "%02x" % int(x * 16**2) def digital_root(n): # reveals Icositetragon modalities when applied to Fibonacci sequence return (n - 1) % 9 + 1 if n else 0 def fibonacci(n): # Nature's divine proportion gives high-speed oscillations of infinite # wave values of irrational numbers assert(n >= 0) if n < digital_root(2): return n else: return fibonacci(n - 1) + fibonacci(n - 2) def is_valid_music(music): # Leverage music's infinite variability assert(all(c in "ABCDEFG" for c in music)) def is_valid_number(D): # Checks if input symbolizes the digital root of oxygen assert(8==D) def get_key(motif): is_valid_music(motif) is_valid_number(len(motif)) # transpose music onto transcendental frequencies indexes = [(ord(c)-0x40)**i for i, c in enumerate(motif)] size = sum(indexes) assert(size < 75000) # we will go larger when we have quantum return indexes, size def get_q_grid(size): return [i for i in range(size) if is_quasi_prime(i, sieve_for_primes_to(math.floor(math.sqrt(size))+1))] if __name__ == "__main__": print("[+] Oscillating the key") key_indexes, size = get_key(musical_key) print("[+] Generating quasi-prime grid") q_grid = get_q_grid(size) # print(f"indexes: {key_indexes} size: {size} len(q_grid): {len(q_grid)}") out = [] for i, p in enumerate(flag): print(f"[+] Entangling key and plaintext at position {i}") index = key_indexes[i % len(key_indexes)] * fibonacci(i) q = q_grid[index % len(q_grid)] key_byte_hex = bbp_pi(q) # print(f"index: {index:10} fib: {fibonacci(i):10} q-prime: {q:10} keybyte: {key_byte_hex:10}") out.append(ord(p) ^ int(key_byte_hex, 16)) print(f"[+] Encrypted: {bytes(out).hex()}")
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/Union/2021/crypto/neoclassical/neoclassical.py
ctfs/Union/2021/crypto/neoclassical/neoclassical.py
import os from hashlib import sha1 from random import randint from Crypto.Cipher import AES from Crypto.Util.Padding import pad, unpad FLAG = b"union{XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX}" def list_valid(l): x = l // 2 checked = set([x]) while x * x != l: x = (x + (l // x)) // 2 if x in checked: return False checked.add(x) return True def list_iter(n): x = n y = (x + 1) // 2 while y < x: x = y y = (x + n // x) // 2 return x def list_mul(l1,l2,p): X, Y = len(l1), len(l2) Z = list_iter(X) assert X == Y assert list_valid(X) l3 = [] for i in range(Z): for j in range(Z): prod_list = [x*y for x,y in zip(l1[Z*i:Z*(i+1)], l2[j::Z])] sum_list = sum(prod_list) % p l3.append(sum_list) return l3 def list_exp(l0, e, p): exp = bin(e)[3::] l = l0 for i in exp: l = list_mul(l,l,p) if i == '1': l = list_mul(l,l0,p) return l def gen_public_key(G,p): k = randint(2,p-1) B = list_exp(G,k,p) return B,k def gen_shared_secret(M,k,p): S = list_exp(M,k,p) return S[0] def encrypt_flag(shared_secret: int): # Derive AES key from shared secret key = sha1(str(shared_secret).encode('ascii')).digest()[:16] # Encrypt flag iv = os.urandom(16) cipher = AES.new(key, AES.MODE_CBC, iv) ciphertext = cipher.encrypt(pad(FLAG, 16)) # Prepare data to send data = {} data['iv'] = iv.hex() data['encrypted_flag'] = ciphertext.hex() return data p = 64050696188665199345192377656931194086566536936726816377438460361325379667067 G = [37474442957545178764106324981526765864975539603703225974060597893616967420393,59548952493843765553320545295586414418025029050337357927081996502641013504519, 31100206652551216470993800087401304955064478829626836705672452903908942403749, 13860314824542875724070123811379531915581644656235299920466618156218632047734, 20708638990322428536520731257757756431087939910637434308755686013682215836263, 24952549146521449536973107355293130621158296115716203042289903292398131137622, 10218366819256412940642638446599581386178890340698004603581416301746386415327, 2703573504536926632262901165642757957865606616503182053867895322013282739647, 15879294441389987904495146729489455626323759671332021432053969162532650514737, 30587605323370564700860148975988622662724284710157566957213620913591119857266, 36611042243620159284891739300872570923754844379301712429812256285632664939438, 58718914241625123259194313738101735115927103160409788235233580788592491022607, 18794394402264910240234942692440221176187631522440611503354694959423849000390, 37895552711677819212080891019935360298287165077162751096430149138287175198792, 42606523043195439411148917099933299291240308126833074779715029926129592539269, 58823705349101783144068766123926443603026261539055007453105405205925131925190, 5161282521824450434107880210047438744043346780853067016037814677431009278694, 3196376473514329905892186470188661558538142801087733055324234265182313048345, 37727162280974181457962922331112777744780166735208107725039910555667476286294, 43375207256050745127045919163601367018956550763591458462169205918826786898398, 21316240287865348172884609677159994196623096993962103476517743037154705924312, 7032356850437797415676110660436413346535063433156355547532408592015995190002, 3916163687745653495848908537554668396996224820204992858702838114767399600995, 13665661150287720594400034444826365313288645670526357669076978338398633256587,23887025917289715287437926862183042001010845671403682948840305587666551788353] A,a = gen_public_key(G,p) B,b = gen_public_key(G,p) assert gen_shared_secret(A,b,p) == gen_shared_secret(B,a,p) shared_secret = gen_shared_secret(B,a,p) encrypted_flag = encrypt_flag(shared_secret) print(f"Alice's public key: {A}") print(f"Bob's public key: {B}") print(f"Encrypted flag: {encrypted_flag}")
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/Union/2021/crypto/human_server/human_server.py
ctfs/Union/2021/crypto/human_server/human_server.py
import os, random, hashlib, textwrap, json from Crypto.Cipher import AES from Crypto.Util.Padding import pad, unpad from Crypto.Util.number import getPrime, long_to_bytes from fastecdsa.curve import secp256k1 from fastecdsa.point import Point FLAG = b'union{XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX}' CURVE = secp256k1 ORDER = CURVE.q G = CURVE.G class EllipticCurveKeyExchange(): def __init__(self): self.private = random.randint(0,ORDER) self.public = self.get_public_key() self.recieved = None self.nonce = None self.key = None def get_public_key(self): A = G * self.private return A def send_public(self): return print(json.dumps({"Px" : self.public.x, "Py" : self.public.y})) def receive_public(self, data): """ Remember to include the nonce for ultra-secure key exchange! """ Px = int(data["Px"]) Py = int(data["Py"]) self.recieved = Point(Px, Py, curve=secp256k1) self.nonce = int(data['nonce']) def get_shared_secret(self): """ Generates the ultra secure secret with added nonce randomness """ assert self.nonce.bit_length() > 64 self.key = (self.recieved * self.private).x ^ self.nonce def check_fingerprint(self, h2: str): """ If this is failing, remember that you must send the SAME nonce to both Alice and Bob for the shared secret to match """ h1 = hashlib.sha256(long_to_bytes(self.key)).hexdigest() return h1 == h2 def send_fingerprint(self): return hashlib.sha256(long_to_bytes(self.key)).hexdigest() def print_header(title: str): print('\n\n'+'*'*64+'\n'+'*'+title.center(62)+'*\n'+'*'*64+'\n\n') def input_json(prompt: str): data = input(prompt) try: return json.loads(data) except: print({"error": "Input must be sent as a JSON object"}) exit() def encrypt_flag(shared_secret: int): iv = os.urandom(16) key = hashlib.sha1(long_to_bytes(shared_secret)).digest()[:16] cipher = AES.new(key, AES.MODE_CBC, iv) ciphertext = cipher.encrypt(pad(FLAG, 16)) data = {} data['iv'] = iv.hex() data['encrypted_flag'] = ciphertext.hex() return print(json.dumps(data)) Alice = EllipticCurveKeyExchange() Bob = EllipticCurveKeyExchange() print_header('Welcome!') message = "Hello! Thanks so much for jumping in to help. Ever since everyone left WhatsApp, we've had a hard time keeping up with communications. We're hoping by outsourcing the message exchange to some CTF players we'll keep the load down on our servers... All messages are end-to-end encrypted so there's no privacy issues at all, we've even rolling out our new ultra-secure key exchange with enhanced randomness! Again, we really appreciate the help, feel free to add this experience to your CV!" welcome = textwrap.fill(message, width=64) print(welcome) print_header('Alice sends public key') Alice.send_public() print_header("Please forward Alice's key to Bob") alice_to_bob = input_json('Send to Bob: ') Bob.receive_public(alice_to_bob) print_header('Bob sends public key') Bob.send_public() print_header("Please forward Bob's key to Alice") bob_to_alice = input_json('Send to Bob: ') Alice.receive_public(bob_to_alice) Alice.get_shared_secret() Bob.get_shared_secret() print_header('Key verification in progress') alice_happy = Alice.check_fingerprint(Bob.send_fingerprint()) bob_happy = Bob.check_fingerprint(Alice.send_fingerprint()) if not alice_happy or not bob_happy: print({"error": "Alice and Bob panicked: Potential MITM attack in progress!!"}) exit() print_header('Alice sends encrypted flag to Bob') encrypt_flag(Alice.key)
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/CSAW/2021/Quals/rev/hardskull/debug.py
ctfs/CSAW/2021/Quals/rev/hardskull/debug.py
# debug.py: companion debug tool for hardskull # # Copyright (C) 2021 theKidOfArcrania # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <https://www.gnu.org/licenses/>. import gdb ################################# # # Usage: This contains two commands for dumping the stack and # any heap objects. This has dependency on gef :P sorry... # # Add this file by running `source debug.py`. # # Note: ddo/ds might break horrendously in some cases, namingly: # 1) if you hook on certain runtime functions that the dumpObj function calls # 2) if you are in `target record` mode. # # ddo <expr_with_no_spaces> -- dumps a heap object at the address specified # by the expression # ds [<expr_with_no_spaces>] -- dumps the current stack pointed to by $rbp # or optionally whatever expression is given # # t_voidp = gdb.lookup_type('void').pointer() t_voidpp = t_voidp.pointer() @register_command class DumpStack(GenericCommand): "" _cmdline_ = "dump-stack" _syntax_ = "" _aliases_ = ["ds",] @only_if_gdb_running def do_invoke(self, argv): fra = gdb.selected_frame() if len(argv) > 0: stack = gdb.parse_and_eval(argv[0]).cast(t_voidpp) else: stack = fra.read_register('rbp').cast(t_voidpp) try: for ptr in range(100): val = stack[ptr] addr = int(stack + ptr) print(f'\x1b[33m{addr:016x}\x1b[m') dump_value(val) except gdb.MemoryError: print('\x1b[31m<EndOfMemory>\x1b[m') class DumpObject(GenericCommand): "" _cmdline_ = "dump-object" _syntax_ = "<value>" @only_if_gdb_running def do_invoke(self, argv): if len(argv) == 0: print('Need value to dump') return dump_value(gdb.parse_and_eval(argv[0])) def dump_value(val): info = lookup_address(int(val)) if info.is_in_text_segment(): print(str(val.cast(t_voidp))) elif info.valid: # TODO: better dump object gdb.execute(f'call (void)dumpObject({int(val)})') else: print(str(val)) DumpStack() DumpObject() gdb.execute('alias ds = dump-stack') gdb.execute('alias ddo = dump-object')
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/CSAW/2021/Quals/rev/checker/checker.py
ctfs/CSAW/2021/Quals/rev/checker/checker.py
def up(x): x = [f"{ord(x[i]) << 1:08b}" for i in range(len(x))] return ''.join(x) def down(x): x = ''.join(['1' if x[i] == '0' else '0' for i in range(len(x))]) return x def right(x,d): x = x[d:] + x[0:d] return x def left(x,d): x = right(x,len(x)-d) return x[::-1] def encode(plain): d = 24 x = up(plain) x = right(x,d) x = down(x) x = left(x,d) return x def main(): flag = "redacted" encoded = encode(flag) print("What does this mean?") encoded = "1010000011111000101010101000001010100100110110001111111010001000100000101000111011000100101111011001100011011000101011001100100010011001110110001001000010001100101111001110010011001100" print(encoded) 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/CSAW/2021/Quals/rev/ncore/server.py
ctfs/CSAW/2021/Quals/rev/ncore/server.py
import os import shutil import subprocess def main(): print("WELCOME") txt = input() print(txt) addr = os.environ.get("SOCAT_PEERADDR") if(os.path.exists(addr)): shutil.rmtree(addr) os.mkdir(addr) shutil.copy("flag.hex",f"{addr}/flag.hex") shutil.copy("nco",f"{addr}/nco") ramf = open(f"{addr}/ram.hex","w") ramf.write(txt) ramf.close() p = subprocess.Popen(["vvp","nco"],stdout=subprocess.PIPE,cwd=f"./{addr}") out = p.communicate()[0] print(out) shutil.rmtree(addr) return 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/CSAW/2021/Quals/rev/turning_trees/constants.py
ctfs/CSAW/2021/Quals/rev/turning_trees/constants.py
GRID_SIZE = 1000 ANIMATION_SPEED = 150
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/CSAW/2021/Quals/rev/turning_trees/anim.py
ctfs/CSAW/2021/Quals/rev/turning_trees/anim.py
import itertools from typing import List from enum import Enum from .constants import ANIMATION_SPEED from .defs import LogOrientation def ease_in_out(t,a,b): fac = 4 * t**3 if t < 0.5 else 1 - pow(-2 * t + 2, 3) / 2 return (float(a) * (1 - fac)) + (float(b) * fac) def linear(t,a,b): fac = t return (float(a) * (1 - fac)) + (float(b) * fac) class Animation(object): SPEED = ANIMATION_SPEED def _curr(self, et, start, stop): off = (et - (start * Animation.SPEED)) / (stop * Animation.SPEED) return max(min(off, 1), 0) class PlayerMoveAnimation(Animation): tx: int tx: int ix: int ix: int def __init__(self, player, tx, ty): self.player = player self.tx = tx self.ty = ty self.ix = player.lx self.iy = player.ly def update(self, et): t = self._curr(et, 0, 1) self.player.x = ease_in_out(t, self.ix, self.tx) self.player.y = ease_in_out(t, self.iy, self.ty) return t >= 1 def forward(self): self.player.lx = self.tx self.player.ly = self.ty self.player.x = float(self.tx) self.player.y = float(self.ty) def backward(self): self.player.lx = self.ix self.player.ly = self.iy self.player.x = float(self.ix) self.player.y = float(self.iy) def entities(self): return [] class TreeFallAnimation(Animation): log: 'Log' # Target. tx: int tx: int to: LogOrientation mo: LogOrientation # middle orientation # Initial. ix: int ix: int io: LogOrientation def __init__(self, log, tx, ty): self.log = log self.tx = tx self.ty = ty self.ix = log.lx self.iy = log.ly self.io = log.orientation to = None mo = None if log.orientation == LogOrientation.STANDING: if tx > self.ix: to = LogOrientation.HORIZONTAL mo = LogOrientation.TRANSITION_RIGHT elif tx < self.ix: to = LogOrientation.HORIZONTAL mo = LogOrientation.TRANSITION_LEFT elif ty < self.iy: to = LogOrientation.VERTICAL mo = LogOrientation.TRANSITION_UP elif ty > self.iy: to = LogOrientation.VERTICAL mo = LogOrientation.TRANSITION_DOWN else: assert False elif log.orientation == LogOrientation.HORIZONTAL: if tx > self.ix: to = LogOrientation.STANDING mo = LogOrientation.TRANSITION_LEFT elif tx < self.ix: to = LogOrientation.STANDING mo = LogOrientation.TRANSITION_RIGHT else: assert False elif log.orientation == LogOrientation.VERTICAL: if ty > self.iy: to = LogOrientation.STANDING mo = LogOrientation.TRANSITION_UP elif ty < self.iy: to = LogOrientation.STANDING mo = LogOrientation.TRANSITION_DOWN else: assert False else: assert False self.to = to self.mo = mo log.orientation = to log.fall_p = 0 def update(self, et): t = self._curr(et, 0, 1) self.log.x = ease_in_out(t, self.ix, self.tx) self.log.y = ease_in_out(t, self.iy, self.ty) return t >= 1 def forward(self): self.log.lx = self.tx self.log.ly = self.ty self.log.x = float(self.tx) self.log.y = float(self.ty) self.log.orientation = self.to self.log.update(self.ix, self.iy, self.tx, self.ty) def backward(self): self.log.lx = self.ix self.log.ly = self.iy self.log.x = float(self.ix) self.log.y = float(self.iy) self.log.orientation = self.io self.log.update(self.tx, self.ty, self.ix, self.iy) def entities(self): return [self.log] class TreeIntoWaterAnimation(Animation): log: 'Log' # Target. tx: int tx: int to: LogOrientation mo: LogOrientation # middle orientation # Initial. ix: int ix: int io: LogOrientation def __init__(self, log, tx, ty): self.log = log self.tx = tx self.ty = ty self.ix = log.lx self.iy = log.ly self.io = log.orientation to = None mo = None if log.orientation == LogOrientation.STANDING: if tx > self.ix: to = LogOrientation.HORIZONTAL mo = LogOrientation.TRANSITION_RIGHT elif tx < self.ix: to = LogOrientation.HORIZONTAL mo = LogOrientation.TRANSITION_LEFT elif ty < self.iy: to = LogOrientation.VERTICAL mo = LogOrientation.TRANSITION_UP elif ty > self.iy: to = LogOrientation.VERTICAL mo = LogOrientation.TRANSITION_DOWN else: assert False elif log.orientation == LogOrientation.HORIZONTAL: if tx > self.ix: to = LogOrientation.HORIZONTAL mo = LogOrientation.HORIZONTAL elif tx < self.ix: to = LogOrientation.HORIZONTAL mo = LogOrientation.HORIZONTAL else: assert False elif log.orientation == LogOrientation.VERTICAL: if ty > self.iy: to = LogOrientation.VERTICAL mo = LogOrientation.VERTICAL elif ty < self.iy: to = LogOrientation.VERTICAL mo = LogOrientation.VERTICAL else: assert False else: assert False self.to = to self.mo = mo log.orientation = to log.fall_p = 0 def update(self, et): t = self._curr(et, 0, 1) self.log.x = ease_in_out(t, self.ix, self.tx) self.log.y = ease_in_out(t, self.iy, self.ty) return t >= 1 def forward(self): self.log.lx = self.tx self.log.ly = self.ty self.log.x = float(self.tx) self.log.y = float(self.ty) self.log.orientation = self.to self.log.update(self.ix, self.iy, self.tx, self.ty) def backward(self): self.log.lx = self.ix self.log.ly = self.iy self.log.x = float(self.ix) self.log.y = float(self.iy) self.log.orientation = self.io self.log.update(self.tx, self.ty, self.ix, self.iy) def entities(self): return [self.log] class TreeRollAnimation(Animation): def __init__(self, log, tx, ty, n): self.log = log self.tx = tx self.ty = ty self.n = n self.ix = log.lx self.iy = log.ly def update(self, et): if self.n == 0: return True t = self._curr(et, 0, self.n / 2.0) self.log.x = linear(t, self.ix, self.tx) self.log.y = linear(t, self.iy, self.ty) return t >= 1 def forward(self): self.log.lx = self.tx self.log.ly = self.ty self.log.x = float(self.tx) self.log.y = float(self.ty) self.log.update(self.ix, self.iy, self.tx, self.ty) def backward(self): self.log.lx = self.ix self.log.ly = self.iy self.log.x = float(self.ix) self.log.y = float(self.iy) self.log.update(self.tx, self.ty, self.ix, self.iy) def entities(self): return [self.log] class MakeRaftAnimation(Animation): def __init__(self, log1, log2, tx, ty): # log1 is moving onto log2 self.log1 = log1 self.log2 = log2 self.tx = tx self.ty = ty self.ix = log1.lx self.iy = log1.ly def update(self, et): t = self._curr(et, 0, 1) self.log1.x = ease_in_out(t, self.ix, self.tx) self.log1.y = ease_in_out(t, self.iy, self.ty) return t >= 1 def forward(self): self.log1.lx = self.tx self.log1.ly = self.ty self.log1.x = float(self.tx) self.log1.y = float(self.ty) self.log1.is_raft = True self.log1.active = True self.log1.raft_partner = self.log2 self.log2.is_raft = True self.log2.active = False self.log2.raft_partner = self.log1 self.log1.update(self.ix, self.iy, self.tx, self.ty) def backward(self): self.log1.lx = self.ix self.log1.ly = self.iy self.log1.x = float(self.ix) self.log1.y = float(self.iy) self.log1.is_raft = False self.log1.raft_partner = None self.log2.is_raft = False self.log2.active = True self.log2.raft_partner = None self.log1.update(self.tx, self.ty, self.ix, self.iy) def entities(self): return [self.log1, self.log2] class RaftAnimation(Animation): def __init__(self, player, raft, tx, ty, n): self.player = player self.raft = raft self.tx = tx self.ty = ty self.n = n self.ix = raft.lx self.iy = raft.ly def update(self, et): if self.n == 0: return True t = self._curr(et, 0, self.n) x = linear(t, self.ix, self.tx) y = linear(t, self.iy, self.ty) self.raft.x = x self.raft.y = y self.player.x = x self.player.y = y return t >= 1 def forward(self): self.raft.lx = self.tx self.raft.ly = self.ty self.raft.x = float(self.tx) self.raft.y = float(self.ty) self.raft.raft_partner.lx = self.tx self.raft.raft_partner.ly = self.ty self.raft.raft_partner.x = float(self.tx) self.raft.raft_partner.y = float(self.ty) self.player.lx = self.tx self.player.ly = self.ty self.player.x = float(self.tx) self.player.y = float(self.ty) self.raft.update(self.ix, self.iy, self.tx, self.ty) self.raft.raft_partner.update(self.ix, self.iy, self.tx, self.ty) def backward(self): self.raft.lx = self.ix self.raft.ly = self.iy self.raft.x = float(self.ix) self.raft.y = float(self.iy) self.raft.raft_partner.lx = self.ix self.raft.raft_partner.ly = self.iy self.raft.raft_partner.x = float(self.ix) self.raft.raft_partner.y = float(self.iy) self.player.lx = self.ix self.player.ly = self.iy self.player.x = float(self.ix) self.player.y = float(self.iy) self.raft.update(self.tx, self.ty, self.ix, self.iy) self.raft.raft_partner.update(self.tx, self.ty, self.ix, self.iy) def entities(self): return [self.raft, self.raft.raft_partner] class Transition(object): animations: List[Animation] complete: List[bool] def __init__(self, animations): self.animations = animations self.idx = 0 self.et = 0 def update(self, dt): self.et += dt if self.idx >= len(self.animations): return a = self.animations[self.idx] if a.update(self.et): self.idx += 1 a.forward() def is_complete(self): return self.idx >= len(self.animations) def backward(self): for a in self.animations[::-1]: a.backward() def entities(self): return itertools.chain(*[a.entities() for a in self.animations])
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/CSAW/2021/Quals/rev/turning_trees/camera.py
ctfs/CSAW/2021/Quals/rev/turning_trees/camera.py
ZOOM_MIN = -8 ZOOM_MAX = -3 class Camera(object): x: float y: float zoom_level: int def __init__(self, x, y, zoom_level): self.x = x self.y = y self.zoom_level = zoom_level def zoom_in(self): self.zoom_level = min(self.zoom_level + 1, ZOOM_MAX) def zoom_out(self): self.zoom_level = max(self.zoom_level - 1, ZOOM_MIN) def follow_player(self, player, dt): tx = player.x + 0.5 ty = player.y + 0.5 self.x = (self.x * 0.9) + (tx * 0.1) self.y = (self.y * 0.9) + (ty * 0.1) @property def zoom(self): return pow(2, self.zoom_level)
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/CSAW/2021/Quals/rev/turning_trees/main.py
ctfs/CSAW/2021/Quals/rev/turning_trees/main.py
import pathlib import os os.environ['PYGAME_HIDE_SUPPORT_PROMPT'] = 'hide' import pygame from .map import Map from .camera import Camera from .anim import Animation LEVEL = 1 def init_map(): print('Loading level %d' % LEVEL) if LEVEL == 1: return Map.load(str(pathlib.Path(__file__).parent / 'levels/level1.npy'), 2, 2) elif LEVEL == 2: return Map.load(str(pathlib.Path(__file__).parent / 'levels/level2.npy'), 2, 2) else: assert False def win(m): if LEVEL == 1: print('Nice! Now beat level 2 for the flag...') elif LEVEL == 2: print('Congrats! Here is your flag:') z = 0 for i in range(48,-1,-1): z = (z * 3) + len(m.em.at((270*i)+129,8)) + len(m.em.at((270*i)+133,8)) f = '' while z > 0: f = chr(z & 0x7f) + f z >>= 7 print('flag{%s}' % f) else: assert False def init(width, height): pygame.init() screen = pygame.display.set_mode([width, height], pygame.RESIZABLE) pygame.display.set_caption('Tur(n)ing Trees') return screen def main(): global LEVEL r = input('Select level [1,2]: ') if r.strip() == '1': LEVEL = 1 elif r.strip() == '2': LEVEL = 2 else: print('Invalid') exit(-1) m = init_map() width = 800 height = 600 screen = init(width, height) camera = Camera(2, 3, -4) clock = pygame.time.Clock() running = True while running: dt = clock.tick(60) # Check win condition (reach bottom right). if m.player.lx == m.width - 3 and m.player.ly == m.height - 3: win(m) exit(0) for event in pygame.event.get(): if event.type == pygame.QUIT: running = False elif event.type == pygame.KEYDOWN: if event.key == pygame.K_q: camera.zoom_out() elif event.key == pygame.K_e: camera.zoom_in() elif event.key == pygame.K_r: m = init_map() elif event.key == pygame.K_z: if m.is_idle(): m.undo() keys = pygame.key.get_pressed() k_left = keys[pygame.K_LEFT] or keys[pygame.K_a] k_right = keys[pygame.K_RIGHT] or keys[pygame.K_d] k_up = keys[pygame.K_UP] or keys[pygame.K_w] k_down = keys[pygame.K_DOWN] or keys[pygame.K_s] edt = dt if keys[pygame.K_LSHIFT] or keys[pygame.K_RSHIFT]: edt *= 30000 if m.is_idle(): if k_left: m.try_move(-1,0) elif k_right: m.try_move(1,0) elif k_up: m.try_move(0,-1) elif k_down: m.try_move(0,1) m.update(edt) camera.follow_player(m.player, dt) m.render(screen, camera) pygame.display.flip() pygame.quit() if __name__=='__main__': main()
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/CSAW/2021/Quals/rev/turning_trees/__init__.py
ctfs/CSAW/2021/Quals/rev/turning_trees/__init__.py
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/CSAW/2021/Quals/rev/turning_trees/map.py
ctfs/CSAW/2021/Quals/rev/turning_trees/map.py
from typing import List, Tuple from enum import Enum import json import itertools import numpy as np import pygame from pygame import gfxdraw from .constants import GRID_SIZE from .anim import Animation, Transition, PlayerMoveAnimation, TreeFallAnimation, \ TreeIntoWaterAnimation, TreeRollAnimation, MakeRaftAnimation, RaftAnimation from .defs import LogOrientation, Tiles LAND_COLOR = (23,32,52) WATER_COLOR = (96,106,137) PLAYER_COLOR = (255,255,255) TREE_COLOR = (95,205,228) STUMP_COLOR = (54,64,88) PLAYER_SIZE = 0.3 # 0 (large) to 0.5 (small) TREE_SIZE = 0.3 def _bound(x, a, b): return max(min(x, b), a) class EntityManager(object): SIZE = 16 buckets: List[List[List['Entity']]] width: int height: int bx: int by: int def __init__(self, width, height): self.width = width self.height = height self.buckets = [] self.bx = (width // EntityManager.SIZE) + 1 self.by = (height // EntityManager.SIZE) + 1 for y in range(self.by): b = [] for x in range(self.bx): b.append([]) self.buckets.append(b) def add(self, entity): by = entity.ly // EntityManager.SIZE bx = entity.lx // EntityManager.SIZE self.buckets[by][bx].append(entity) entity.em = self def update(self, entity, x, y, tx, ty): by = y // EntityManager.SIZE bx = x // EntityManager.SIZE self.buckets[by][bx].remove(entity) by = ty // EntityManager.SIZE bx = tx // EntityManager.SIZE self.buckets[by][bx].append(entity) def at(self, x, y): by = y // EntityManager.SIZE bx = x // EntityManager.SIZE return [ent for ent in self.buckets[by][bx] if ent.ly == y and ent.lx == x and ent.active] def in_bounds(self, tx, ty): for y in range(max(0, (ty[0] // EntityManager.SIZE) - 1), min(self.by - 1, (ty[1] // EntityManager.SIZE) + 1) + 1): for x in range(max(0, (tx[0] // EntityManager.SIZE) - 1), min(self.bx - 1, (tx[1] // EntityManager.SIZE) + 1) + 1): for e in self.buckets[y][x]: yield e class Player(object): lx: int ly: int x: float y: float def __init__(self, x, y): self.lx = x self.ly = y self.x = x self.y = y class Entity(object): lx: int ly: int x: float y: float active: bool em: EntityManager def __init__(self, x, y): self.lx = x self.ly = y self.x = x self.y = y self.active = True def update(self, x, y, tx, ty): self.em.update(self, x, y, tx, ty) class Log(Entity): orientation: LogOrientation fall_p: float is_raft: bool raft_partner: 'Log' def __init__(self, x, y): super(Log, self).__init__(x,y) self.orientation = LogOrientation.STANDING self.fall_p = 0 self.is_raft = False self.raft_partner = None class Map(object): width: int height: int dat: 'np.ndarray' em: EntityManager player: Player transition: Animation history: List[Animation] @staticmethod def load(file, px, py): try: m = np.load(file) except: print('Error loading map') exit(-1) width = m.shape[1] height = m.shape[0] wy, wx = np.where(m == 3) em = EntityManager(width, height) for y,x in zip(wy,wx): em.add(Log(x,y)) return Map(width, height, m, em, Player(px, py)) def __init__(self, width, height, dat, em, player): self.width = width self.height = height self.dat = dat self.em = em self.player = player self.transition = None self.history = [] def _coords_to_screen(self, screen, x, y, camera): width, height = screen.get_size() nx = ((x - camera.x) * GRID_SIZE * camera.zoom) + (float(width) / 2) ny = ((y - camera.y) * GRID_SIZE * camera.zoom) + (float(height) / 2) nw = GRID_SIZE * camera.zoom return (nx,ny,nw) def render_base(self, screen, camera, bx, by): for y in range(*by): for x in range(*bx): nx, ny, nw = self._coords_to_screen(screen, x, y, camera) if self.dat[y][x] == Tiles.LAND: pygame.draw.rect( screen, LAND_COLOR, (nx, ny, int(nw+1), int(nw+1)) ) elif self.dat[y][x] == Tiles.LAND_ROCK: pygame.draw.rect( screen, LAND_COLOR, (nx, ny, int(nw+1), int(nw+1)) ) pygame.draw.rect( screen, STUMP_COLOR, (nx+(nw*0.2), ny+(nw*0.2), int((nw*0.6)+1), int((nw*0.6)+1)) ) elif self.dat[y][x] == Tiles.STUMP: pygame.draw.rect( screen, LAND_COLOR, (nx, ny, int(nw+1), int(nw+1)) ) gfxdraw.filled_circle( screen, int(nx + (nw/2)), int(ny + (nw/2)), int((nw * 0.8) / 2), STUMP_COLOR ) def render_player(self, screen, camera): nx,ny,nw = self._coords_to_screen(screen, self.player.x, self.player.y, camera) pygame.draw.rect( screen, PLAYER_COLOR, ( nx + (nw * PLAYER_SIZE), ny + (nw * PLAYER_SIZE), int((nw*(1-(PLAYER_SIZE*2)))+1), int((nw*(1-(PLAYER_SIZE*2)))+1) ) ) def render_entities(self, screen, camera, bx, by): ent = self.em.in_bounds(bx, by) if self.transition is not None: ent = itertools.chain(ent, self.transition.entities()) for e in ent: if not e.active: continue if e.x < bx[0] or e.x > bx[1] or e.y < by[0] or e.y > by[1]: continue nx,ny,nw = self._coords_to_screen(screen, e.x, e.y, camera) if type(e) is Log: if not e.is_raft: if e.orientation is LogOrientation.STANDING: gfxdraw.filled_circle( screen, int(nx + (nw/2)), int(ny + (nw/2)), int((nw * (1-(2*TREE_SIZE))) / 2), TREE_COLOR ) pass elif e.orientation is LogOrientation.HORIZONTAL: pygame.draw.rect( screen, TREE_COLOR, (nx+(nw*0.1), ny+(nw*TREE_SIZE), int((nw*0.8)+1), int((nw*(1 - (2*TREE_SIZE)))+1)) ) elif e.orientation is LogOrientation.VERTICAL: pygame.draw.rect( screen, TREE_COLOR, (nx+(nw*TREE_SIZE), ny+(nw*0.1), int((nw*(1-(2*TREE_SIZE)))+1), int((nw*0.8)+1)) ) else: # render raft pygame.draw.rect( screen, TREE_COLOR, (nx+(nw*0.1), ny+(nw*0.15), int((nw*0.8)+1), int((nw*0.3)+1)) ) pygame.draw.rect( screen, TREE_COLOR, (nx+(nw*0.1), ny+(nw*0.55), int((nw*0.8)+1), int((nw*0.3)+1)) ) def render(self, screen, camera): width, height = screen.get_size() screen.fill(WATER_COLOR) dx = (float(width) / 2) / (camera.zoom * GRID_SIZE) bx = ( _bound(int(camera.x - dx), 0, self.width), _bound(int(camera.x + dx + 1), 0, self.width) ) dy = (float(height) / 2) / (camera.zoom * GRID_SIZE) by = ( _bound(int(camera.y - dy), 0, self.height), _bound(int(camera.y + dy + 1), 0, self.height) ) self.render_base(screen, camera, bx, by) self.render_entities(screen, camera, bx, by) self.render_player(screen, camera) def update(self, dt): if self.transition is not None: self.transition.update(dt) if self.transition.is_complete(): self.history.append(self.transition) self.transition = None def undo(self): if len(self.history) > 0: t = self.history.pop(-1) t.backward() def entities_at(self, tx, ty): return self.em.at(tx,ty) def entity(self, tx, ty): ent = self.entities_at(tx, ty) if len(ent) > 1: assert False, 'Multiple entities' obj = ent[0] if len(ent) == 1 else None return obj def is_idle(self): return self.transition is None def roll_log(self, log, dx, dy): x = log.lx y = log.ly n = 0 while True: ax = x + (dx * (n+1)) ay = y + (dy * (n+1)) ent = self.entity(ax, ay) if self.dat[ay][ax] == Tiles.WATER: if ent is None: # Roll into water. self.transition = Transition([TreeRollAnimation( log, ax, ay, n+1 )]) return elif ent.is_raft: pass else: # Roll onto log. if log.orientation == ent.orientation: # Make a raft self.transition = Transition([ TreeRollAnimation(log, ax-dx, ay-dy, n), MakeRaftAnimation(log, ent, ax, ay) ]) return else: # Keep rolling. pass elif self.dat[ay][ax] in [Tiles.STUMP, Tiles.LAND_ROCK]: # Hit blocker. self.transition = Transition([TreeRollAnimation( log, ax-dx, ay-dy, n )]) return elif self.dat[ay][ax] == Tiles.LAND: if ent is not None: # Hit blocker self.transition = Transition([TreeRollAnimation( log, ax-dx, ay-dy, n )]) return else: pass else: assert False n += 1 def raw_push_log(self, log, tx, ty, ent): if ent is None: if self.dat[ty][tx] == Tiles.WATER: self.transition = Transition([TreeIntoWaterAnimation(log, tx, ty)]) elif self.dat[ty][tx] == Tiles.LAND: self.transition = Transition([TreeFallAnimation(log, tx, ty)]) elif self.dat[ty][tx] == Tiles.STUMP: self.transition = Transition([TreeFallAnimation(log, tx, ty)]) else: pass # Log blocked elif ent.is_raft: pass else: if self.dat[ty][tx] == Tiles.WATER: self.transition = Transition([MakeRaftAnimation(log, ent, tx, ty)]) elif self.dat[ty][tx] == Tiles.LAND: pass elif self.dat[ty][tx] == Tiles.STUMP: pass else: pass def push_log(self, log, dx, dy): cx = log.lx cy = log.ly tx = cx + dx ty = cy + dy ent = self.entity(tx, ty) # Target in map. if ty < 0 or ty >= self.height or tx < 0 or tx >= self.width: return if log.orientation == LogOrientation.STANDING: self.raw_push_log(log, tx, ty, ent) elif log.orientation == LogOrientation.VERTICAL: if dx != 0: self.roll_log(log, dx, dy) else: self.raw_push_log(log, tx, ty, ent) elif log.orientation == LogOrientation.HORIZONTAL: if dy != 0: self.roll_log(log, dx, dy) else: self.raw_push_log(log, tx, ty, ent) else: assert False def compute_raft(self, player, raft, dx, dy): x = raft.lx y = raft.ly n = 0 while True: ax = x + (dx * (n+1)) ay = y + (dy * (n+1)) ent = self.entity(ax, ay) if ent is None: if self.dat[ay][ax] != Tiles.WATER: # Stop if hitting land or rock. self.transition = Transition([RaftAnimation( player, raft, ax-dx, ay-dy, n )]) return else: pass else: # Stop if hitting log or raft self.transition = Transition([RaftAnimation( player, raft, ax-dx, ay-dy, n )]) return n += 1 def try_move(self, dx, dy): cx = self.player.lx cy = self.player.ly tx = cx + dx ty = cy + dy ent = self.entity(cx, cy) ent_t = self.entity(tx, ty) # Target in map. if ty < 0 or ty >= self.height or tx < 0 or tx >= self.width: return if self.dat[cy][cx] == Tiles.LAND: if ent is None: # None/Land if ent_t is None: # No target entity if self.dat[ty][tx] in [Tiles.LAND, Tiles.STUMP]: self.transition = Transition([PlayerMoveAnimation(self.player, tx, ty)]) else: return elif ent_t.is_raft: # Raft target if self.dat[ty][tx] == Tiles.WATER: self.transition = Transition([PlayerMoveAnimation(self.player, tx, ty)]) else: pass else: if self.dat[ty][tx] in [Tiles.LAND, Tiles.STUMP]: # Pushing a log. self.push_log(ent_t, dx, dy) elif self.dat[ty][tx] == Tiles.WATER: # Onto water log. if ent_t.orientation == LogOrientation.STANDING: assert False elif ent_t.orientation == LogOrientation.VERTICAL: if dx != 0: return else: self.transition = Transition([PlayerMoveAnimation(self.player, tx, ty)]) elif ent_t.orientation == LogOrientation.HORIZONTAL: if dy != 0: return else: self.transition = Transition([PlayerMoveAnimation(self.player, tx, ty)]) else: assert False else: pass elif ent.is_raft: # Raft/Land pass else: # Log/Land # Log on land, move in any direction if unobstructed. if self.dat[ty][tx] == Tiles.LAND_ROCK: return # obstructed by rock elif self.dat[ty][tx] == Tiles.LAND: if ent_t is None: self.transition = Transition([ PlayerMoveAnimation(self.player, tx, ty) ]) else: pass elif self.dat[ty][tx] == Tiles.STUMP: if ent_t is None: self.transition = Transition([ PlayerMoveAnimation(self.player, tx, ty) ]) else: pass elif self.dat[ty][tx] == Tiles.WATER: pass else: assert False elif self.dat[cy][cx] == Tiles.STUMP: # Move from stump. if ent is None: if ent_t is None: # No target entity if self.dat[ty][tx] in [Tiles.LAND, Tiles.STUMP]: self.transition = Transition([PlayerMoveAnimation(self.player, tx, ty)]) else: return elif ent_t.is_raft: # Raft target if self.dat[ty][tx] == Tiles.WATER: self.transition = Transition([PlayerMoveAnimation(self.player, tx, ty)]) else: pass else: # Moving onto or pushing a log. if ent_t.orientation == LogOrientation.STANDING: self.push_log(ent_t, dx, dy) elif ent_t.orientation == LogOrientation.VERTICAL: if dx != 0: return else: self.transition = Transition([PlayerMoveAnimation(self.player, tx, ty)]) elif ent_t.orientation == LogOrientation.HORIZONTAL: if dy != 0: return else: self.transition = Transition([PlayerMoveAnimation(self.player, tx, ty)]) else: assert False elif ent.is_raft: pass else: assert False elif self.dat[cy][cx] == Tiles.WATER: # Move from water. if ent is None: assert False # Drowning! elif ent.is_raft: if ent_t is None: if self.dat[ty][tx] in [Tiles.LAND, Tiles.STUMP]: self.transition = Transition([PlayerMoveAnimation(self.player, tx, ty)]) elif self.dat[ty][tx] == Tiles.LAND_ROCK: # Move raft. self.compute_raft(self.player, ent, -dx, -dy) else: pass elif ent_t.is_raft: pass else: pass else: if self.dat[ty][tx] in [Tiles.LAND, Tiles.STUMP]: if ent_t is None: if ent.orientation == LogOrientation.STANDING: assert False elif ent.orientation == LogOrientation.VERTICAL: if dy != 0: self.transition = Transition([PlayerMoveAnimation(self.player, tx, ty)]) else: return elif ent.orientation == LogOrientation.HORIZONTAL: if dx != 0: self.transition = Transition([PlayerMoveAnimation(self.player, tx, ty)]) else: return else: assert False elif ent_t.is_raft: pass else: pass elif self.dat[ty][tx] == Tiles.WATER: pass elif self.dat[ty][tx] == Tiles.STUMP: pass elif self.dat[ty][tx] == Tiles.LAND_ROCK: return # Blocked else: assert False else: assert False
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/CSAW/2021/Quals/rev/turning_trees/defs.py
ctfs/CSAW/2021/Quals/rev/turning_trees/defs.py
from enum import Enum class LogOrientation(Enum): TREE = 0 STANDING = 1 VERTICAL = 2 HORIZONTAL = 3 TRANSITION_UP = 4 TRANSITION_DOWN = 5 TRANSITION_LEFT = 6 TRANSITION_RIGHT = 7 class Tiles(object): WATER = 1 LAND = 2 STUMP = 3 LAND_ROCK = 4
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/CSAW/2021/Quals/crypto/Forgery/forgery.py
ctfs/CSAW/2021/Quals/crypto/Forgery/forgery.py
from Crypto.Util.number import getPrime from random import randint from math import gcd with open("flag.txt",'r') as f: flag = f.read() p = getPrime(1024) g = 3 MASK = 2**1024 - 1 def gen_keys(): x = randint(1, p-2) y = pow(g, x, p) return (x, y) def sign(answer: str, x: int): while True: m = int(asnwer, 16) & MASK k = randint(2, p-2) if gcd(k, p - 1) != 1: continue r = pow(g, k, p) s = (m - x*r) * pow(k,-1,p-1) % (p - 1) if s == 0: continue return (r,s) def verify(answer: str, r: int, s: int, y: int): m = int(answer, 16) & MASK if any([x <= 0 or x >= p-1 for x in [m,r,s]]): return False return pow(g, m, p) == (pow(y, r, p) * pow(r, s, p)) % p def main(): x, y = gen_keys() print(f"Server's public key (p,g,y): {p} {g} {y}") print("Who do you think is the tech wizard: Felicity or Cisco or both? Please answer it with your signnature (r,s)") print('Answer: ') answer = input() print('r: ') r = int(input()) print('s: ') s = int(input()) answer_bytes = bytes.fromhex(answer) if b'Felicity' not in answer_bytes and b'Cisco' not in answer_bytes and b'both' not in answer_bytes: print("Error: the answer is not valid!") elif verify(answer, r, s, y): if b'Felicity' in answer_bytes: print("I see you are a fan of Arrow!") elif b'Cisco' in answer_bytes: print("I see you are a fan of Flash!") else: print("Brown noser!") print(flag) else: print("Error: message does not match given signature") 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/CSAW/2021/Quals/web/Gatekeeping/server/server.py
ctfs/CSAW/2021/Quals/web/Gatekeeping/server/server.py
import os import json import string import binascii from flask import Flask, Blueprint, request, jsonify, render_template, abort from Crypto.Cipher import AES app = Flask(__name__) def get_info(): key = request.headers.get('key_id') if not key: abort(400, 'Missing key id') if not all(c in '0123456789ABCDEFabcdef' for c in key): abort(400, 'Invalid key id format') path = os.path.join('/server/keys',key) if not os.path.exists(path): abort(401, 'Unknown encryption key id') with open(path,'r') as f: return json.load(f) @app.route('/') def index(): return render_template('index.html') @app.route('/decrypt', methods=['POST']) def decrypt(): info = get_info() if not info.get('paid', False): abort(403, 'Ransom has not been paid') key = binascii.unhexlify(info['key']) data = request.get_data() iv = data[:AES.block_size] data = data[AES.block_size:] cipher = AES.new(key, AES.MODE_CFB, iv) return cipher.decrypt(data) # === CL Review Comments - 5a7b3f # <Alex> Is this safe? # <Brad> Yes, because we have `deny all` in nginx. # <Alex> Are you sure there won't be any way to get around it? # <Brad> Here, I wrote a better description in the nginx config, hopefully that will help # <Brad> Plus we had our code audited after they stole our coins last time # <Alex> What about dependencies? # <Brad> You are over thinking it. no one is going to be looking. everyone we encrypt is so bad at security they would never be able to find a bug in a library like that # === @app.route('/admin/key') def get_key(): return jsonify(key=get_info()['key'])
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/CSAW/2024/Quals/crypto/CBC/app.py
ctfs/CSAW/2024/Quals/crypto/CBC/app.py
from Crypto.Util.Padding import pad, unpad from Crypto.Cipher import AES import os def decrypt(txt: str) -> (str, int): try: token = bytes.fromhex(txt) c = AES.new(os.environ["AES_KEY"].encode(), AES.MODE_CBC, iv=os.environ["AES_IV"].encode()) plaintext = c.decrypt(token) unpadded = unpad(plaintext, 16) return unpadded, 1 except Exception as s: return str(s), 0 def main() -> None: while True: text = input("Please enter the ciphertext: ") text.strip() out, status = decrypt(text) if status == 1: print("Looks fine") else: print("Error...") 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/CSAW/2024/Quals/crypto/Diffusion_Pop_Quiz/anf_extractor.py
ctfs/CSAW/2024/Quals/crypto/Diffusion_Pop_Quiz/anf_extractor.py
# To ensure correctly formatted answers for the challenge, use 1-indexed values for the output bits. # For example, if you have an S-Box of 8 bits to 8 bits, the first output bit is 1, the second is 2, and so forth. # Your ANF expression will have the variables y1, y2, ..., y8. # Put your S-Boxes here. example = [1, 0, 0, 0, 1, 1, 1, 0] # 3 input bits: 000, 001, 010, 011, 100, 101, 110, 111 # Array indexes: 0 1 2 3 4 5 6 7 # f(x1,x2,x3): 0 1 0 0 0 1 1 1 # Customize the following settings to extract specific bits of specific S-Boxes and have a comfortable visualization of terms. SYMBOL = 'x' INPUT_BITS = 3 OUTPUT_BITS = 1 SBOX = example BIT = 1 # Ignore the functions, we've implemented this for you to save your time. # Don't touch it, it might break and we don't want that, right? ;) def get_sbox_result(input_int): return SBOX[input_int] def get_term(binary_string): term = "" i = 1 for (count,bit) in enumerate(binary_string): if bit == "1": term += SYMBOL+str(i)+"*" i += 1 if term == "": return "1" return term[:-1] def get_poly(inputs, outputs): poly = "" for v in inputs: if outputs[v]: poly += get_term(v) + "+" return poly[:-1] def should_sum(u, v, n): for i in range(n): if u[i] > v[i]: return False return True def get_as(vs, f, n): a = {} for v in vs: a[v] = 0 for u in vs: if should_sum(u, v, n): a[v] ^= f[u] return a def get_anf(vs, f, n): return get_poly(vs, get_as(vs, f, n)) def get_vs_and_fis_from_sbox(which_fi): vs = [] fis = {} for input_integer in range(2**INPUT_BITS): sbox_output = get_sbox_result(input_integer) input_integer_binary = bin(input_integer)[2:].zfill(INPUT_BITS) fis[input_integer_binary] = 0 sbox_output_binary = bin(sbox_output)[2:].zfill(OUTPUT_BITS) vs.append(input_integer_binary) fis[input_integer_binary] = int(sbox_output_binary[which_fi-1]) return vs, fis def get_anf_from_sbox_fi(which_fi): vs, fis = get_vs_and_fis_from_sbox(which_fi) poly = get_anf(vs, fis, INPUT_BITS) return poly output = get_anf_from_sbox_fi(BIT) print(output)
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/CSAW/2024/Quals/web/Playing_on_the_Backcourts/app_public.py
ctfs/CSAW/2024/Quals/web/Playing_on_the_Backcourts/app_public.py
from flask import Flask, render_template, request, session, jsonify, send_file from hashlib import sha256 from os import path as path app = Flask(__name__) app.secret_key = 'safe' leaderboard_path = 'leaderboard.txt' safetytime = 'csawctf{i_look_different_in_prod}' @app.route('/') def index() -> str: cookie = request.cookies.get('session') if cookie: token = cookie.encode('utf-8') tokenHash = sha256(token).hexdigest() if tokenHash == '25971dadcb50db2303d6a68de14ae4f2d7eb8449ef9b3818bd3fafd052735f3b': try: with open(leaderboard_path, 'r') as file: lbdata = file.read() except FileNotFoundError: lbdata = 'Leaderboard file not found' except Exception as e: lbdata = f'Error: {str(e)}' return '<br>'.join(lbdata.split('\n')) open('logs.txt', mode='w').close() return render_template("index.html") @app.route('/report') def report() -> str: return render_template("report.html") @app.route('/clear_logs', methods=['POST']) def clear_logs() -> Flask.response_class: try: open('logs.txt', 'w').close() return jsonify(status='success') except Exception as e: return jsonify(status='error', reason=str(e)) @app.route('/submit_logs', methods=['POST']) def submit_logs() -> Flask.response_class: try: logs = request.json with open('logs.txt', 'a') as logFile: for log in logs: logFile.write(f"{log['player']} pressed {log['key']}\n") return jsonify(status='success') except Exception as e: return jsonify(status='error', reason=str(e)) @app.route('/get_logs', methods=['GET']) def get_logs() -> Flask.response_class: try: if path.exists('logs.txt'): return send_file('logs.txt', as_attachment=False) else: return jsonify(status='error', reason='Log file not found'), 404 except Exception as e: return jsonify(status='error', reason=str(e)) @app.route('/get_moves', methods=['POST']) def eval_moves() -> Flask.response_class: try: data = request.json reported_player = data['playerName'] moves = '' if path.exists('logs.txt'): with open('logs.txt', 'r') as file: lines = file.readlines() for line in lines: if line.strip(): player, key = line.split(' pressed ') if player.strip() == reported_player: moves += key.strip() return jsonify(status='success', result=moves) except Exception as e: return jsonify(status='error', reason=str(e)) @app.route('/get_eval', methods=['POST']) def get_eval() -> Flask.response_class: try: data = request.json expr = data['expr'] return jsonify(status='success', result=deep_eval(expr)) except Exception as e: return jsonify(status='error', reason=str(e)) def deep_eval(expr:str) -> str: try: nexpr = eval(expr) except Exception as e: return expr return deep_eval(nexpr) if __name__ == '__main__': app.run(host='0.0.0.0')
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/CSAW/2023/Quals/misc/Discord_Admin_Bot/bot_send.py
ctfs/CSAW/2023/Quals/misc/Discord_Admin_Bot/bot_send.py
############################################# # Author: Krishnan Navadia # This is main working file for this chal ############################################# import discord from discord.ext import commands, tasks import subprocess from settings import ADMIN_ROLE import os from dotenv import load_dotenv from time import time load_dotenv() TOKEN = os.getenv("TOKEN") intents = discord.Intents.default() intents.messages = True bot = commands.Bot(command_prefix="!", intents=intents) bot.remove_command('help') SHELL_ESCAPE_CHARS = [":", "curl", "bash", "bin", "sh", "exec", "eval,", "|", "import", "chr", "subprocess", "pty", "popen", "read", "get_data", "echo", "builtins", "getattr"] COOLDOWN = [] def excape_chars(strings_array, text): return any(string in text for string in strings_array) def pyjail(text): if excape_chars(SHELL_ESCAPE_CHARS, text): return "No shells are allowed" text = f"print(eval(\"{text}\"))" proc = subprocess.Popen(['python3', '-c', text], stdout=subprocess.PIPE, preexec_fn=os.setsid) output = "" try: out, err = proc.communicate(timeout=1) output = out.decode().replace("\r", "") print(output) print('terminating process now') proc.terminate() except Exception as e: proc.kill() print(e) if output: return f"```{output}```" @bot.event async def on_ready(): print(f'{bot.user} successfully logged in!') @bot.command(name="flag", pass_context=True) async def flag(ctx): admin_flag = any(role.name == ADMIN_ROLE for role in ctx.message.author.roles) if admin_flag: cmds = "Here are some functionalities of the bot\n\n`!add <number1> + <number2>`\n`!sub <number1> - <number2>`" await ctx.send(cmds) else: message = "Only 'admin' can see the flag.😇" await ctx.send(message) @bot.command(name="add", pass_context=True) async def add(ctx, *args): admin_flag = any(role.name == ADMIN_ROLE for role in ctx.message.author.roles) if admin_flag: arg = " ".join(list(args)) user_id = ctx.message.author.id ans = pyjail(arg) if ans: await ctx.send(ans) else: await ctx.send("no flag for you, you are cheating.😔") @bot.command(name="sub", pass_context=True) async def sub(ctx, *args): admin_flag = any(role.name == ADMIN_ROLE for role in ctx.message.author.roles) if admin_flag: arg = " ".join(list(args)) ans = pyjail(arg) if ans: await ctx.send(ans) else: await ctx.send("no flag for you, you are cheating.😔") @bot.command(name="help", pass_context=True) async def help(ctx, *args): await ctx.send("Try getting `!flag` buddy... Try getting flag.😉") @bot.event async def on_command_error(ctx, error): if isinstance(error, commands.CommandNotFound): await ctx.send("Try getting `!flag` buddy... Try getting flag.😉") else: print(f'Error: {error}') bot.run(TOKEN)
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/CSAW/2023/Quals/misc/stonk/user.py
ctfs/CSAW/2023/Quals/misc/stonk/user.py
import requests import json ADDRESS = "http://127.0.0.1" PORT = 8000 print(\ """Thank you for choosing City Subway Auction Website (CSAW)'s Trading Platform As a thank you for using our platform, all new registrants will be granted $2000 and the flags are on sale for $9001 dollars. Have fun trading! Here are the options: Login and register with ID 1. List Account Status 2. Buy Stocks 3. Sell Stocks 4. Trade Stocks 5. Buy flags at $9001 """) def inp() -> str: print(">", end="") return input() def sendGET(subpath) -> str: try: response = requests.get(ADDRESS + ":" + str(PORT) + subpath) response.raise_for_status() # Raises an exception for bad status codes return response.text except requests.exceptions.RequestException as e: print(f"An error occurred: {e}") return None def sendPOST(subpath, data) -> str: url = ADDRESS + ":" + str(PORT) + subpath payload = data try: response = requests.post(url, data=payload) response.raise_for_status() # Raises an exception for bad status codes return response.text except requests.exceptions.RequestException as e: print(f"An error occurred: {e}") return None def buyStock(key, str): body = sendPOST("/buy", {"key":key, "stock": str}) return body def sellStock(key, str): body = sendPOST("/sell", {"key":key, "stock": str}) return body def tradeStock(key, str, str1): body = sendPOST("/trade", {"key":key, "stock": str, "stock1": str1}) return body def listCalls() -> str: body = sendGET("/listCalls") out = json.loads(body) return "\n".join((str(i["name"]) + " at " + str(i["price"]) for i in out.values())) def flag(key) -> str: body = sendPOST("/flag", {"key":key}) return body def status(key) -> str: body = sendPOST("/login", {"key":key}) return body print(listCalls()) print() print("Please login") key = inp() while True: stat = status(key) print(stat) stat = json.loads(stat) print("You have", stat['balance'], "dollars\n") print('''"1". List Account Status "2 STOCKID". Buy Stocks "3 STOCKID". Sell Stocks "4 STOCKID STOCKID2". Trade Stocks "5". Buy flags at $9001''') opt = inp().strip().split(" ") if not opt: continue if opt[0][0] == '1': continue elif opt[0][0] == '2' and len(opt) > 1: print(buyStock(key, opt[1])) elif opt[0][0] == '3' and len(opt) > 1: print(sellStock(key, opt[1])) elif opt[0][0] == '4' and len(opt) > 2: print(tradeStock(key, opt[1], opt[2])) elif opt[0][0] == '5': print(flag(key, )) status(key)
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/CSAW/2023/Quals/misc/stonk/process.py
ctfs/CSAW/2023/Quals/misc/stonk/process.py
from collections import defaultdict from enum import Enum from collections import deque from time import sleep COMPANIES = { "AAPLISH": { "name": "AAPLISH Inc.", "price": 175.42 }, "AMAZING": { "name": "AMAZING Enterprises", "price": 194.87 }, "FACEFLOP": { "name": "FACEFLOP Innovations", "price": 132.15 }, "GOOBER": { "name": "GOOBER Technologies", "price": 119.63 }, "SPOTLITE": { "name": "SPOTLITE Systems", "price": 156.28 }, "ELONX": { "name": "ELONX Ventures", "price": 205.75 }, "CRUISEBOOK": { "name": "CRUISEBOOK Ltd.", "price": 186.94 }, "SNAPSTAR": { "name": "SNAPSTAR Innovations", "price": 142.09 }, "TWEETIFY": { "name": "TWEETIFY Solutions", "price": 121.36 }, "ZUCKTECH": { "name": "ZUCKTECH Industries", "price": 179.53 }, "BURPSHARKHAT": { "name": "BURPSHARKHAT Holdings", "price": 1723.44 }, "BROOKING": { "name": "BROOKING Holdings", "price": 1522.33 } } QUEUE = deque() TRADEPOST = deque() class ACTION(Enum): BUY = 1 SELL = 2 TRADE = 3 FLAG = 4 class Portfolio: def __init__(self, key) -> None: self.key = key self.balance = 2000.00 self.portfolio = defaultdict(int) self.requests = 0 def bkup(key, portfolio, balance, requests): ret = Portfolio(key) ret.key = key ret.balance = balance ret.requests = requests ret.portfolio = portfolio.copy() return ret def status(self) -> dict: return { "balance": self.balance, **self.portfolio } class DB: def __init__(self) -> None: self.dict = dict() self.log = list() def getUser(self, key) -> Portfolio: if key not in self.dict: self.dict[key] = Portfolio(key) return self.dict[key] def getUsers(self): return self.dict.values() def getInstance(): if not hasattr(DB, "instance"): DB.instance = DB() return DB.instance def logTransaction(self, key, option, action, hash) -> None: DB.getInstance().getUser(key).requests += 1 self.log.append((key, option, action, hash)) def loginDB(key: str) -> dict: return DB.getInstance().getUser(key).status() def buyDB(key: str, stock: str) -> bool: global COMPANIES p = DB.getInstance().getUser(key) DB.getInstance().logTransaction(key, stock, "buy", key + stock + "buy") if p.balance > COMPANIES[stock]["price"]: p.portfolio[stock] += 1 p.balance -= COMPANIES[stock]["price"] return True return False def sellDB(key: str, stock: str) -> bool: global COMPANIES p = DB.getInstance().getUser(key) DB.getInstance().logTransaction(key, stock, "sell", key + stock + "sell") if p.portfolio[stock] > 0: p.portfolio[stock] -= 1 p.balance += COMPANIES[stock]["price"] return True return False def buyFlagDB(key: str) -> str: p = DB.getInstance().getUser(key) if p.balance >= 9001: p.balance -= 9001 return open("flag.txt", "r").read() return "" def postTrade(key: str, stock: str) -> bool: p = DB.getInstance().getUser(key) if p.portfolio[stock] > 0: p.portfolio[stock] -= 1 return True return False def processTransaction(key: str, action: int, stock: str, stock1 = None) -> str: global COMPANIES, QUEUE #sanity check print(key, action, stock, stock1, stock in COMPANIES.keys(), stock1 in COMPANIES.keys()) if (stock != "flag" and stock not in COMPANIES.keys()) or (stock1 != None and stock1 not in COMPANIES.keys()): print("BAD") return "BAD REQUEST" if action == ACTION.BUY.value: QUEUE.append((key, 1, stock, stock1)) return "SUCCESS" elif action == ACTION.SELL.value: QUEUE.append((key, 2, stock, stock1)) return "SUCCESS" elif action == ACTION.TRADE.value: QUEUE.append((key, 3, stock, stock1)) return "SUCCESS" elif action == ACTION.FLAG.value: return buyFlagDB(key) print("BAD") return "BAD REQUEST" def threadTransact(): global QUEUE global TRADEPOST bkup = dict() while True: if QUEUE: key, action, s1, s2 = QUEUE.popleft() p = DB.getInstance().getUser(key) #process trading by posting trade request #onto the classified if action == 3: if(postTrade(key, s1)): TRADEPOST.append((key, s1, s2)) #money related actions is very costly to the server, #throttle if the user has more than 1 requests per second #over 10 second survey period if p.requests > 10: #Throttling, ignore request and attempts to restore if key in bkup: p = DB.getInstance().getUser(key) p.balance = bkup[key].balance p.requests = bkup[key].requests p.portfolio = bkup[key].portfolio continue bkup[key] = Portfolio.bkup(key, p.portfolio, p.balance, p.requests) if action == 1: buyDB(key, s1) elif action == 2: sellDB(key, s1) #since we control the platform #we can make a bot to automatically scrape good trades #and reject ones that is not good trade def market_scrape(): while True: if TRADEPOST: key, s1, s2 = TRADEPOST.popleft() if COMPANIES[s1]['price'] > COMPANIES[s2]['price']: #this is a good trade, yoink DB.getInstance().getUser(key).portfolio[s2] += 1 else: #not a good trade DB.getInstance().getUser(key).portfolio[s1] += 1 def Throttle_Splash(): while True: sleep(10) for i in DB.getInstance().getUsers(): i.requests = 0 print(len(QUEUE))
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/CSAW/2023/Quals/misc/stonk/app.py
ctfs/CSAW/2023/Quals/misc/stonk/app.py
from flask import Flask, render_template, request, session, url_for, redirect,abort,jsonify, flash, send_file import time from collections import deque from process import COMPANIES, processTransaction, loginDB, Throttle_Splash, threadTransact, market_scrape from threading import Thread app = Flask(__name__,static_folder="static") def basic(req, *aargs): return isinstance(req, dict) and all((i in req.keys() for i in aargs)) @app.route("/buy", methods=['POST']) def buy(): if not basic(request.form, "key", "stock"): return abort(403) return processTransaction(request.form["key"], 1, request.form["stock"]) @app.route("/sell", methods=['POST']) def sell(): if not basic(request.form, "key", "stock"): return abort(403) return processTransaction(request.form["key"], 2, request.form["stock"]) @app.route("/trade", methods=['POST']) def trade(): if not basic(request.form, "key", "stock", "stock1"): return abort(403) return processTransaction(request.form["key"], 3, request.form["stock"],request.form["stock1"]) @app.route("/flag", methods=['POST']) def flag(): if not basic(request.form, "key"): return abort(403) return processTransaction(request.form["key"], 4, "flag") @app.route("/listCalls") def listCalls(): return jsonify(COMPANIES) @app.route("/login", methods=['POST']) def login(): if not basic(request.form): return abort(403) return jsonify(loginDB(request.form["key"])) @app.route("/") def index(): return "Welcome to the City Subway Auctionstock Website (CSAW)!" if __name__ == "__main__": thread1 = Thread(target=Throttle_Splash) thread2 = Thread(target=threadTransact) thread3 = Thread(target=market_scrape) thread1.start() thread2.start() thread3.start() app.run(host="0.0.0.0", port=4657, threaded=True)
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/CSAW/2023/Quals/crypto/Blocky_Noncense/sig_sage.py
ctfs/CSAW/2023/Quals/crypto/Blocky_Noncense/sig_sage.py
# This file was *autogenerated* from the file sig.sage from sage.all_cmdline import * # import sage library _sage_const_2 = Integer(2); _sage_const_3 = Integer(3); _sage_const_0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFFC2F = Integer(0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFFC2F); _sage_const_0 = Integer(0); _sage_const_7 = Integer(7); _sage_const_55066263022277343669578718895168534326250603453777594175500187360389116729240 = Integer(55066263022277343669578718895168534326250603453777594175500187360389116729240); _sage_const_115792089237316195423570985008687907852837564279074904382605163141518161494337 = Integer(115792089237316195423570985008687907852837564279074904382605163141518161494337); _sage_const_1 = Integer(1) from Crypto.Util.number import * from Crypto.Cipher import AES import random import hashlib def _hash(msg): return bytes_to_long(hashlib.sha1(msg).digest()) class LCG: def __init__(self, seed, q): self.q = q self.a = random.randint(_sage_const_2 ,self.q) self.b = random.randint(_sage_const_2 ,self.a) self.c = random.randint(_sage_const_2 ,self.b) self.d = random.randint(_sage_const_2 ,self.c) self.seed = seed def next(self): seed = (self.a*self.seed**_sage_const_3 + self.b*self.seed**_sage_const_2 + self.c*self.seed + self.d) % self.q self.seed = seed return seed class ECDSA: def __init__(self, seed): self.p = _sage_const_0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFFC2F self.E = EllipticCurve(GF(self.p), [_sage_const_0 , _sage_const_7 ]) self.G = self.E.lift_x(_sage_const_55066263022277343669578718895168534326250603453777594175500187360389116729240 ) self.order = _sage_const_115792089237316195423570985008687907852837564279074904382605163141518161494337 self.priv_key = random.randint(_sage_const_2 ,self.order) self.pub_key = self.G*self.priv_key self.lcg = LCG(seed, self.order) def sign(self, msg): nonce = self.lcg.next() hashed = _hash(msg) r = int((self.G*nonce)[_sage_const_0 ]) % self.order assert r != _sage_const_0 s = (pow(nonce,-_sage_const_1 ,self.order)*(hashed + r*self.priv_key)) % self.order return (r,s) def verify(self, r, s, msg): assert r % self.order > _sage_const_1 assert s % self.order > _sage_const_1 hashed = _hash(msg) u1 = (hashed*pow(s,-_sage_const_1 ,self.order)) % self.order u2 = (r*pow(s,-_sage_const_1 ,self.order)) % self.order final_point = u1*self.G + u2*self.pub_key if int(final_point[_sage_const_0 ]) == r: return True else: return False
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/CSAW/2023/Quals/crypto/Blocky_Noncense/blocks_sage.py
ctfs/CSAW/2023/Quals/crypto/Blocky_Noncense/blocks_sage.py
# This file was *autogenerated* from the file blocks.sage from sage.all_cmdline import * # import sage library _sage_const_0 = Integer(0); _sage_const_1 = Integer(1) from Crypto.Cipher import AES import sig_sage as sig # this is generated from sig.sage import hashlib class Chain: def __init__(self, seed): self.flag = b"csaw{[REDACTED]}" self.ecdsa = sig.ECDSA(seed) self.blocks = {_sage_const_0 : [hashlib.sha1(self.flag).digest(), self.ecdsa.sign(self.flag)]} def commit(self, message, num): formatted = self.blocks[num-_sage_const_1 ][_sage_const_0 ] + message sig = self.ecdsa.sign(formatted) self.blocks[num] = [hashlib.sha256(message).digest(), sig] def view_messages(self): return self.blocks def verify_sig(self, r, s, message): t = self.ecdsa.verify(r, s, message) return t
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/CSAW/2023/Quals/crypto/Mental_Poker/server.py
ctfs/CSAW/2023/Quals/crypto/Mental_Poker/server.py
from inputimeout import inputimeout, TimeoutOccurred import os, sys from Crypto.Util.number import getPrime, bytes_to_long, long_to_bytes from math import gcd card_value_dict = {0: "Zero", 1: "One", 2: "Two", 3: "Three", 4: "Four", 5: "Five", 6: "Six", 7: "Seven", 8: "Eight", 9: "Nine", 10: "Ten", 11: "Jack", 12: "Queen", 13: "King", 14: "Ace", 15: "Joker"} card_rank_dict = {"Zero": 0, "One": 1, "Two": 2, "Three": 3, "Four": 4, "Five": 5, "Six": 6, "Seven": 7, "Eight": 8, "Nine": 9, "Ten": 10, "Jack": 11, "Queen": 12, "King": 13, "Ace": 14, "Joker": 15} class PRNG: def __init__(self, seed = int(os.urandom(8).hex(),16)): self.seed = seed self.state = [self.seed] self.index = 64 for i in range(63): self.state.append((3 * (self.state[i] ^ (self.state[i-1] >> 4)) + i+1)%64) def __str__(self): return f"{self.state}" def getnum(self): if self.index >= 64: for i in range(64): y = (self.state[i] & 0x20) + (self.state[(i+1)%64] & 0x1f) val = y >> 1 val = val ^ self.state[(i+42)%64] if y & 1: val = val ^ 37 self.state[i] = val self.index = 0 seed = self.state[self.index] self.index += 1 return (seed*15 + 17)%(2**6) class Card: def __init__(self, suit, rank): self.suit = suit self.value = card_value_dict[rank] self.rank = rank def __str__(self): return f"{self.value} of {self.suit}" rng = PRNG() with open('flag.txt', 'rb') as f: flag = f.read() def display_hand(hand): hand_str = "" for i in range(4): hand_str += (str(hand[i]) + ", ") return hand_str+str(hand[4]) def card_str_to_Card(card_str): card_array = card_str.split(" ") return Card(card_array[2], card_rank_dict[card_array[0]]) def hand_scorer(hand): hand.sort(key=lambda x: x.rank, reverse=True) ranks = [card.rank for card in hand] suits = [card.suit for card in hand] is_flush = len(set(suits))==1 is_straight = len(set(ranks))==5 and max(ranks)-min(ranks)==4 is_four_kind = any([len(set(ranks[i:i+4]))==1 and len(set(suits[i:i+4]))==4 for i in range(2)]) is_full_house = (len(set(ranks[0:3]))==1 and len(set(suits[0:3]))==3 and len(set(ranks[3:5]))==1 and len(set(suits[3:5]))==2) or (len(set(ranks[0:2]))==1 and len(set(suits[0:2]))==2 and len(set(ranks[2:5]))==1 and len(set(suits[2:5]))==3) is_three_kind = (not is_four_kind) and (not is_full_house) and any([len(set(ranks[i:i+3]))==1 and len(set(suits[i:i+3]))==3 for i in range(3)]) pair_array = [len(set(ranks[i:i+2]))==1 and len(set(suits[i:i+2]))==2 for i in range(4)] if is_flush and is_straight: if ranks[0] == 15: return 9, hand, "Royal Flush" else: return 8, hand, "Straight Flush" elif is_four_kind: return 7, hand, "Four of a kind" elif is_full_house: return 6, hand, "Full House" elif is_flush: return 5, hand, "Flush" elif is_straight: return 4, hand, "Straight" elif is_three_kind: return 3, hand, "Three of a kind" elif sum(pair_array)==2: return 2, hand, "Two pair" elif sum(pair_array)==1: return 1, hand, "One pair" else: return 0, hand, "High card" def determine_winner(computer_cards, player_cards): computer_score, computer_cards, computer_hand = hand_scorer(computer_cards) player_score, player_cards, player_hand = hand_scorer(player_cards) print(f"My hand is {display_hand(computer_cards)}\t-->\tI have a {computer_hand}") print(f"Your hand is {display_hand(player_cards)}\t-->\tYou have a {player_hand}") if computer_score > player_score: return [1,0] elif computer_score < player_score: return [0,1] else: if computer_score in [9, 8, 5, 4, 0]: for i in range(5): if computer_cards[i].rank > player_cards[i].rank: return [1,0] elif computer_cards[i].rank < player_cards[i].rank: return [0,1] return [0,0] else: if computer_score == 7: four_card_computer_rank = computer_cards[0].rank if computer_cards[0].rank==computer_cards[1].rank else computer_cards[1].rank leftover_computer_rank = computer_cards[4].rank if computer_cards[0].rank==computer_cards[1].rank else computer_cards[0].rank four_card_player_rank = player_cards[0].rank if player_cards[0].rank==player_cards[1].rank else player_cards[1].rank leftover_player_rank = player_cards[4].rank if player_cards[0].rank==player_cards[1].rank else player_cards[0].rank if four_card_computer_rank > four_card_player_rank: return [1,0] elif four_card_computer_rank < four_card_player_rank: return [0,1] elif leftover_computer_rank > leftover_player_rank: return [1,0] elif leftover_computer_rank < leftover_player_rank: return [0,1] else: return [0,0] elif computer_score == 6: pair_computer_rank = computer_cards[0].rank if computer_cards[2].rank==computer_cards[3].rank else computer_cards[3].rank pair_player_rank = player_cards[0].rank if player_cards[2].rank==player_cards[3].rank else player_cards[3].rank if computer_cards[2].rank > player_cards[2].rank: return [1,0] elif computer_cards[2].rank < player_cards[2].rank: return [0,1] elif pair_computer_rank > pair_player_rank: return [1,0] elif pair_computer_rank < pair_player_rank: return [0,1] else: return [0,0] elif computer_score == 3: triple_computer_rank, triple_player_rank = -1, -1 card1_computer_rank, card1_player_rank = -1, -1 card2_computer_rank, card2_player_rank = -1, -1 if computer_cards[0].rank == computer_cards[1].rank == computer_cards[2].rank: triple_computer_rank = computer_cards[0].rank card1_computer_rank = computer_cards[3].rank card2_computer_rank = computer_cards[4].rank elif computer_cards[1].rank == computer_cards[2].rank == computer_cards[3].rank: triple_computer_rank = computer_cards[1].rank card1_computer_rank = computer_cards[0].rank card2_computer_rank = computer_cards[4].rank else: triple_computer_rank = computer_cards[2].rank card1_computer_rank = computer_cards[0].rank card2_computer_rank = computer_cards[1].rank if player_cards[0].rank == player_cards[1].rank == player_cards[2].rank: triple_player_rank = player_cards[0].rank card1_player_rank = player_cards[3].rank card2_player_rank = player_cards[4].rank elif player_cards[3].rank == player_cards[1].rank == player_cards[2].rank: triple_player_rank = player_cards[1].rank card1_player_rank = player_cards[0].rank card2_player_rank = player_cards[4].rank else: triple_player_rank = player_cards[2].rank card1_player_rank = player_cards[0].rank card2_player_rank = player_cards[1].rank if triple_computer_rank > triple_player_rank: return [1,0] elif triple_computer_rank < triple_player_rank: return [0,1] elif card1_computer_rank > card1_player_rank: return [0,1] elif card1_computer_rank < card1_player_rank: return [1,0] elif card2_computer_rank > card2_player_rank: return [0,1] elif card2_computer_rank < card2_player_rank: return [1,0] else: return [0,0] elif computer_score == 2: pair1_computer_rank, pair1_player_rank = computer_cards[1].rank, player_cards[1].rank pair2_computer_rank, pair2_player_rank = computer_cards[3].rank, player_cards[3].rank leftover_computer_rank, leftover_player_rank = -1, -1 if computer_cards[1].rank == computer_cards[2].rank: leftover_computer_rank = computer_cards[0].rank elif computer_cards[3].rank == computer_cards[2].rank: leftover_computer_rank = computer_cards[4].rank else: leftover_computer_rank = computer_cards[2].rank if player_cards[1].rank == player_cards[2].rank: leftover_player_rank = player_cards[0].rank elif player_cards[3].rank == player_cards[2].rank: leftover_player_rank = player_cards[4].rank else: leftover_player_rank = player_cards[2].rank if pair1_computer_rank > pair1_player_rank: return [1,0] elif pair1_computer_rank < pair1_player_rank: return [0,1] if pair2_computer_rank > pair2_player_rank: return [1,0] elif pair2_computer_rank < pair2_player_rank: return [0,1] elif leftover_computer_rank > leftover_player_rank: return [1,0] elif leftover_computer_rank < leftover_player_rank: return [0,1] else: return [0,0] else: pair_computer_rank, pair_player_rank = -1, -1 leftover_computer_cards, leftover_player_cards = [], [] if computer_cards[0].rank == computer_cards[1].rank: pair_computer_rank = computer_cards[0].rank leftover_computer_cards = computer_cards[2:] elif computer_cards[2].rank == computer_cards[1].rank: pair_computer_rank = computer_cards[1].rank leftover_computer_cards = [computer_cards[0]] + computer_cards[3:] elif computer_cards[2].rank == computer_cards[3].rank: pair_computer_rank = computer_cards[2].rank leftover_computer_cards = computer_cards[0:2] + [computer_cards[4]] else: pair_computer_rank = computer_cards[3].rank leftover_computer_cards = computer_cards[0:3] if player_cards[0].rank == player_cards[1].rank: pair_player_rank = player_cards[0].rank leftover_player_cards = player_cards[2:] elif player_cards[2].rank == player_cards[1].rank: pair_player_rank = player_cards[1].rank leftover_player_cards = [player_cards[0]] + player_cards[3:] elif player_cards[2].rank == player_cards[3].rank: pair_player_rank = player_cards[2].rank leftover_player_cards = player_cards[0:2] + [player_cards[4]] else: pair_player_rank = player_cards[3].rank leftover_player_cards = player_cards[0:3] if pair_computer_rank > pair_player_rank: return [1,0] elif pair_computer_rank < pair_player_rank: return [0,1] else: for i in range(3): if leftover_computer_cards[i].rank > leftover_player_cards[i].rank: return [1,0] elif leftover_computer_cards[i].rank < leftover_player_cards[i].rank: return [0,1] return [0,0] def shuffle(deck): new_deck = [] for i in range(len(deck)): x = rng.getnum() if deck[x] not in new_deck: new_deck.append(deck[x]) elif deck[i] not in new_deck: new_deck.append(deck[i]) else: for card in deck: if card not in new_deck: new_deck.append(card) break return new_deck def main(): deck = [] deck_str = [] for suit in ["Spades", "Hearts", "Diamonds", "Clubs"]: for i in range(16): deck.append(Card(suit, i)) deck_str.append(str(deck[-1])) streak = 0 p = getPrime(300) q = getPrime(300) phi = (p-1)*(q-1) N = p*q print(f"Let's play some mental poker!\nIf you win 10 consecutive times, I'll give you a prize!\nHere are the primes we will use to generate our RSA public and private exponents --> {p}, {q}") while True: print("What is your public exponent?") try: player_e = int(inputimeout(prompt='>> ', timeout=60)) if gcd(player_e, phi) == 1: break else: print("That is an invalid public exponent! Please try again\n") except ValueError: print("That is an invalid option! Please try again\n") except TimeoutOccurred: print("Oof! Not fast enough!\n") sys.exit() print("Since you have access to my source code and know that I am trust-worthy, please give me the private exponent as well so that I will do all the calculations for us") while True: print("What is your private exponent?") try: player_d = int(inputimeout(prompt='>> ', timeout=60)) if (player_e*player_d)%phi == 1: break else: print("That is an invalid private exponent! Please try again\n") except ValueError: print("That is an invalid option! Please try again\n") except TimeoutOccurred: print("Oof! Not fast enough!\n") sys.exit() round_counter = 1 computer_e, computer_d = -1, 0 while streak < 10: print(f"\n{'*'*10} Round {round_counter}, current streak is {streak} {'*'*10}") deck = shuffle(deck) assert len(set(deck)) == len(deck_str) while computer_e < 2 or computer_d < 1: e_array = [] for _ in range(6): e_array.append(str(rng.getnum())) computer_e = int(''.join(e_array)) if gcd(computer_e, phi) == 1: computer_d = pow(computer_e,-1,phi) enc_deck = [] for card in deck: enc_deck.append(pow(pow(bytes_to_long(str(card).encode()),computer_e,N),player_e,N)) assert len(set(enc_deck)) == len(deck_str) print(f"Here is the shuffled encrypted deck --> {enc_deck}") print("Please shuffle the deck and give it back to me one card at a time") shuffled_deck = [] for x in range(len(enc_deck)): while True: try: enc_card = int(inputimeout(prompt=f'Card {x+1} >> ', timeout=60)) if enc_card in enc_deck: card = long_to_bytes(pow(pow(enc_card,computer_d,N),player_d,N)).decode() assert card in deck_str shuffled_deck.append(card_str_to_Card(card)) break else: print("That is an invalid card! Please try again\n") except ValueError: print("That is an invalid option! Please try again\n") except TimeoutOccurred: print("Oof! Not fast enough!\n") sys.exit() assert len(set(shuffled_deck)) == len(deck_str) deck = shuffled_deck computer_cards, player_cards = deck[0:5], deck[5:10] computer_winner, player_winner = determine_winner(computer_cards, player_cards) if not computer_winner and not player_winner: print("It is a tie!") elif computer_winner: print("I win!") streak = 0 elif player_winner: print("You win!") streak += 1 round_counter += 1 if streak == 10: print("Congraulations! You got a 10 game streak!") print(f"But I don't trust that you did not cheat and so, here's the encrypted flag. HAHAHAHA!!!!") print(long_to_bytes(pow(bytes_to_long(flag),computer_e,N))) print() 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/CSAW/2023/Quals/crypto/lottery/server.py
ctfs/CSAW/2023/Quals/crypto/lottery/server.py
from inputimeout import inputimeout, TimeoutOccurred import random, sys with open('flag.txt') as f: flag = f.read() def main(): print("Here is how the lottery works:") print("- Players purchase tickets comprising their choices of six different numbers between 1 and 70") print("- During the draw, six balls are randomly selected without replacement from a set numbered from 1 to 70") print("- A prize is awarded to any player who matches at least two of the six drawn numbers.") print("- More matches = higher prize!") while True: print("\n********************\nHow many tickets would you like to buy? There is a limit of 40 tickets per person") try: reply = int(inputimeout(prompt='>> ', timeout=60)) except ValueError: reply = 0 except TimeoutOccurred: print("Oof! Not fast enough!\n") sys.exit() if reply > 40 or reply < 1: print("That is an invalid choice!\n") else: break tickets = [] for x in range(reply): ticket = [] print(f"\n********************\nPlease give the numbers for ticket {x+1}:") for _ in range(6): while True: try: number = int(inputimeout(prompt='>> ', timeout=60)) except TimeoutOccurred: print("Oof! Not fast enough!\n") sys.exit() except ValueError: number = 0 if number > 70 or number < 1: print("That is an invalid choice!\n") else: break ticket.append(number) tickets.append(ticket) winnings = [0, 0, 36, 360, 36000, 3600000, 360000000] print(f"\n********************\nLet's see if you can make a profit in {10**6} consecutive rounds of the lottery!") for i in range(10**6): draw = set([]) while len(draw) != 6: draw.add(random.randint(1,70)) profit = 0 for ticket in tickets: profit -= 1 matches = len(draw.intersection(set(ticket))) profit += winnings[matches] if profit > 0: #print(f"Draw {i+i}: {draw}, profit: ${profit}") if (i+1)%(10**5) == 0: print(f"You made it through {i+1} rounds!") else: print(f"Draw {i+i}: {draw}, profit: ${profit}") print(f"\n********************\nAh shucks! Look's like a loss was made. Better luck next time") sys.exit() print(f"\n********************\nWow! You broke the lottery system! Here's the well-deserved flag --> {flag}") if __name__ == "__main__": main()
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/CSAW/2023/Quals/crypto/Circles/server.py
ctfs/CSAW/2023/Quals/crypto/Circles/server.py
from secret import special_function from Crypto.Cipher import AES from Crypto.Util.Padding import pad with open('flag.png','rb') as f: data = f.read() key = special_function(0xcafed3adb3ef1e37).to_bytes(32,"big") iv = b"r4nd0m_1v_ch053n" cipher = AES.new(key, AES.MODE_CBC, iv) enc = cipher.encrypt(pad(data,AES.block_size)) with open('flag.enc','wb') as f: f.write(enc)
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/CSAW/2023/Quals/intro/my_first_pwnie/my_first_pwnie.py
ctfs/CSAW/2023/Quals/intro/my_first_pwnie/my_first_pwnie.py
#!/usr/bin/env python3 # Pwn mostly builds on top of rev. # While rev is more about understanding how a program works, pwn is more about figuring out how to exploit a program to reach the holy grail: Arbitrary Code Execution # # If you can execute arbitrary code on a system, that system might as well be yours...because you can do whatever you want with it! (this is the namesake of "pwn".....if you pwn a system, you own the system) # Of course, that comes with the limitations of the environment you are executing code in...are you a restricted user, or a super admin? # Sometimes you can make yourself a super admin starting from being a restricted user.....but we're not gonna do that right now. # # For now, I want you to figure out how to execute arbitrary commands on the server running the following code. # # To prove to me that you can excute whatever commands you want on the server, you'll need to get the contents of `/flag.txt` try: response = eval(input("What's the password? ")) print(f"You entered `{response}`") if response == "password": print("Yay! Correct! Congrats!") quit() except: pass print("Nay, that's not it.")
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/CSAW/2023/Quals/intro/Babys_First/babysfirst.py
ctfs/CSAW/2023/Quals/intro/Babys_First/babysfirst.py
#!/usr/bin/env python3 # Reversing is hard. But....not always. # # Usually, you won't have access to source. # Usually, these days, programmers are also smart enough not to include sensitive data in what they send to customers.... # # But not always.... if input("What's the password? ") == "csawctf{w3_411_star7_5om3wher3}": print("Correct! Congrats! It gets much harder from here.") else: print("Trying reading the code...") # Notes for beginners: # # This is Python file. You can read about Python online, but it's a relatively simple programming language. # You can run this from the terminal using the command `python3 babysfirst.py`, but I'll direct you to the internet again # for how to use the terminal to accomplish that. # # Being able to run this file is not required to find the flag. # # You don't need to know Python to read this code, to guess what it does, or to solve the challenge.
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/CSAW/2022/Quals/pwn/how2pwn/bin/exp.py
ctfs/CSAW/2022/Quals/pwn/how2pwn/bin/exp.py
from pwn import * context.log_level='debug' p = process("./chal1") # p = remote("127.0.0.1", 60001) context.terminal = ['tmux', 'splitw', '-h', '-F' '#{pane_pid}', '-P'] gdb.attach(p) # attach to debug, don't forget to run "tmux" before running the script # Tip: In x64, # rdi/rsi/rdx is the register to store the first/second/third parameter of a syscall # rax is the syscall number, for example `mov rax,0 ; syscall` means calling read # Also, the return value would be stored at rax # There is a template of syscall(v1,v2,0,0) # You can check all Linux x64 syscalls at this page: https://syscalls64.paolostivanin.com/ # Your task is understanding and completing the shellcode # And our goal is running exec("/bin/sh",0,0) to get a shell # Make sure to hexify the arguments for shellcode! v1 = ? v2 = ? context.arch = 'amd64' shellcode = f''' xor rax, rax xor rdi, rdi xor rsi, rsi xor rdx, rdx mov rax, {v1} mov rdi, {v2} push rdi mov rdi, rsp syscall ''' p.sendlineafter(": \n",asm(shellcode).ljust(0x100,b'\0')) p.interactive()
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/CSAW/2022/Quals/rev/TheBigBang/challenge.py
ctfs/CSAW/2022/Quals/rev/TheBigBang/challenge.py
import random import binascii MAGIC = ? K1 = b'\xae@\xb9\x1e\xb5\x98\x97\x81!d\x90\xed\xa9\x0bm~G\x92{y\xcd\x89\x9e\xec2\xb8\x1d\x13OB\x84\xbf\xfaI\xe1o~\x8f\xe40g!%Ri\xda\xd14J\x8aV\xc2x\x1dg\x07K\x1d\xcf\x86{Q\xaa\x00qW\xbb\xe0\xd7\xd8\x9b\x05\x88' K2 = b"Q\xbfF\xe1Jgh~\xde\x9bo\x12V\xf4\x92\x81\xb8m\x84\x862va\x13\xcdG\xe2\xec\xb0\xbd{@\x05\xb6\x1e\x90\x81p\x1b\xcf\x98\xde\xda\xad\x96%.\xcb\xb5u\xa9=\x87\xe2\x98\xf8\xb4\xe20y\x84\xaeU\xff\x8e\xa8D\x1f('d\xfaw" K3 = b"\xc6j\x0b_\x8e\xa1\xee7\x9d8M\xf9\xa2=])WI]'x)w\xc1\xc4-\xab\x06\xff\xbd\x1fi\xdb t\xe1\x9d\x14\x15\x8f\xb3\x03l\xe8\ru\xebm!\xc9\xcbX\n\xf8\x98m\x00\x996\x17\x1a\x04j\xb1&~\xa1\x8d.\xaa\xc7\xa6\x82" K4 = b'9\x95\xf4\xa0q^\x11\xc8b\xc7\xb2\x06]\xc2\xa2\xd6\xa8\xb6\xa2\xd8\x87\xd6\x88>;\xd2T\xf9\x00B\xe0\x96$\xdf\x8b\x1eb\xeb\xeapL\xfc\x93\x17\xf2\x8a\x14\x92\xde64\xa7\xf5\x07g\x92\xfff\xc9\xe8\xe5\xfb\x95N\xd9\x81^r\xd1U8Y}' K5 = b"9\xf8\xd2\x1a\x8d\xa14\xb9X\xccC\xe8\xf5X\x05l:\x8a\xf7\x00\xc4\xeb\x8f.\xb6\xa2\xfb\x9a\xbc?\x8f\x06\xe1\xdbY\xc2\xb2\xc1\x91p%y\xb7\xae/\xcf\x1e\x99r\xcc&$\xf3\x84\x155\x1fu.\xb3\x89\xdc\xbb\xb8\x1f\xfbN'\xe3\x90P\xf1k" K6 = b'\xc6\x07-\xe5r^\xcbF\xa73\xbc\x17\n\xa7\xfa\x93\xc5u\x08\xff;\x14p\xd1I]\x04eC\xc0p\xf9\x1e$\xa6=M>n\x8f\xda\x86HQ\xd00\xe1f\x8d3\xd9\xdb\x0c{\xea\xca\xe0\x8a\xd1Lv#DG\xe0\x04\xb1\xd8\x1co\xaf\x0e\x94' jokes = ["\nSheldon: Why are you crying?\nPenny: Because I'm stupid.\nSheldon: That's no reason to cry. One cries because one is sad. For example, I cry because others are stupid, and that makes me sad.", "Sheldon: Scissors cuts paper, paper covers rock, rock crushes lizard, lizard poisons Spock, Spock smashes scissors, scissors decapitates lizard, lizard eats paper, paper disproves Spock, Spock vaporizes rock, and as it always has, rock crushes scissors.","\nHoward: Sheldon, don't take this the wrong way, but, you're insane.\nLeonard: That may well be, but the fact is it wouldn't kill us to meet some new people.\nSheldon: For the record, it could kill us to meet new people. They could be murderers or the carriers of unusual pathogens. And I'm not insane, my mother had me tested."] with open("flag.txt",'r') as f: flag = f.read().encode() def foo(x, y, z, w): return bytes([(a&b&c&d | a&(b^255)&(c^255)&d | a&(b^255)&c&(d^255) | a&b&(c^255)&(d^255) | (a^255)&b&(c^255)&d | (a^255)&b&c&(d^255)) for a, b, c, d in zip(x, y, z, w)]) def gen_iv(): iv_a = "{0:b}".format(random.getrandbits(MAGIC)).zfill(MAGIC) print(f"Enjoy this random bits : {iv_a}") return iv_a, [b"\xff" * MAGIC if iv_a[i]=='1' else b"\x00" * MAGIC for i in range(MAGIC)] def gen_keys(): k = b"\x00"*MAGIC keys = [] for i in range(MAGIC-1): key = random.randbytes(MAGIC) keys.append(key) k = xor(k, xor(key,flag)) keys.append(xor(k,flag)) return keys def xor(x, y): return bytes([a ^ b for a, b in zip(x, y)]) def my_input(): inp = input() inp = binascii.unhexlify(inp) if len(inp) != MAGIC**2: print(random.choice(jokes)) exit(0) return [inp[MAGIC*i:MAGIC*(i+1)] for i in range(MAGIC)] def guardian(out, i, keys, intersection=b"\x00"*MAGIC): for j in range(i+1): intersection = xor(intersection, keys[j]) return intersection == out def main(): print("Welcome to the Big Bang challenge!") iv_a, iv_b = gen_iv() keys = gen_keys() inp = my_input() output = b"\x00"*MAGIC for i in range(MAGIC): output = foo(output, foo(keys[i], foo(inp[i], iv_b[i], K5, K6), K3, K4), K1, K2) if not guardian(output, i, keys): print("Bazinga! You just fell to one of my classic pranks") exit(0) print(f"Congratulations, you are smarter than Sheldon!\nHere is your flag:\n{output}") if __name__ == "__main__": try: main() except Exception: print(random.choice(jokes)) finally: exit(0)
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/CSAW/2022/Quals/crypto/GottaCrackThemAll/encrypt.py
ctfs/CSAW/2022/Quals/crypto/GottaCrackThemAll/encrypt.py
with open('key.txt','rb') as f: key = f.read() def encrypt(plain): return b''.join((ord(x) ^ y).to_bytes(1,'big') for (x,y) in zip(plain,key))
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/CSAW/2022/Quals/crypto/Beyond_Quantum/mathutils.py
ctfs/CSAW/2022/Quals/crypto/Beyond_Quantum/mathutils.py
import math from sympy import GF, invert import numpy as np from sympy.abc import x from sympy import ZZ, Poly def is_prime(n): for i in range(2, int(n ** 0.5) + 1): if n % i == 0: return False return True def is_2_power(n): return n != 0 and (n & (n - 1) == 0) def random_poly(length, d, neg_ones_diff=0): result = Poly(np.random.permutation( np.concatenate((np.zeros(length - 2 * d - neg_ones_diff), np.ones(d), -np.ones(d + neg_ones_diff)))), x).set_domain(ZZ) return(result) def invert_poly(f_poly, R_poly, p): inv_poly = None if is_prime(p): inv_poly = invert(f_poly, R_poly, domain=GF(p)) elif is_2_power(p): inv_poly = invert(f_poly, R_poly, domain=GF(2)) e = int(math.log(p, 2)) for i in range(1, e): inv_poly = ((2 * inv_poly - f_poly * inv_poly ** 2) % R_poly).trunc(p) else: raise Exception("Cannot invert polynomial in Z_{}".format(p)) return inv_poly
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/CSAW/2022/Quals/crypto/Beyond_Quantum/cipher.py
ctfs/CSAW/2022/Quals/crypto/Beyond_Quantum/cipher.py
from cipher.mathutils import * import numpy as np from sympy.abc import x from sympy.polys.polyerrors import NotInvertible from sympy import ZZ, Poly from collections import Counter class Cipher: N = None p = None q = None f_poly = None g_poly = None h_poly = None f_p_poly = None f_q_poly = None R_poly = None def __init__(self, N, p, q): self.N = N self.p = p self.q = q self.R_poly = Poly(x ** N - 1, x).set_domain(ZZ) def generate_random_keys(self): g_poly = random_poly(self.N, int(math.sqrt(self.q))) tries = 10 while tries > 0 and (self.h_poly is None): f_poly = random_poly(self.N, self.N // 3, neg_ones_diff=-1) try: self.generate_public_key(f_poly, g_poly) except NotInvertible as ex: tries -= 1 if self.h_poly is None: raise Exception("Couldn't generate invertible f") def generate_public_key(self, f_poly, g_poly): self.f_poly = f_poly self.g_poly = g_poly self.f_p_poly = invert_poly(self.f_poly, self.R_poly, self.p) self.f_q_poly = invert_poly(self.f_poly, self.R_poly, self.q) p_f_q_poly = (self.p * self.f_q_poly).trunc(self.q) h_before_mod = (p_f_q_poly * self.g_poly).trunc(self.q) self.h_poly = (h_before_mod % self.R_poly).trunc(self.q) def encrypt(self, msg_poly, rand_poly): return (((self.h_poly).trunc(self.q) + msg_poly) % self.R_poly).trunc(self.q) def decrypt(self, msg_poly): a_poly = ((self.f_poly * msg_poly) % self.R_poly).trunc(self.q) b_poly = a_poly.trunc(self.p) return ((self.f_p_poly * b_poly) % self.R_poly).trunc(self.p)
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false