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/BCACTF/2024/web/MOC_Inc./app.py
ctfs/BCACTF/2024/web/MOC_Inc./app.py
from flask import Flask, request, render_template import datetime import sqlite3 import random import pyotp import sys random.seed(datetime.datetime.today().strftime('%Y-%m-%d')) app = Flask(__name__) @app.get('/') def index(): return render_template('index.html') @app.post('/') def log_in(): with sqlite3.connect('moc-inc.db') as db: result = db.cursor().execute( 'SELECT totp_secret FROM user WHERE username = ? AND password = ?', (request.form['username'], request.form['password']) ).fetchone() if result == None: return render_template('portal.html', message='Invalid username/password.') totp = pyotp.TOTP(result[0]) if totp.verify(request.form['totp']): with open('../flag.txt') as file: return render_template('portal.html', message=file.read()) return render_template('portal.html', message='2FA code is incorrect.') with sqlite3.connect('moc-inc.db') as db: db.cursor().execute('''CREATE TABLE IF NOT EXISTS user ( username TEXT UNIQUE NOT NULL, password TEXT NOT NULL, totp_secret TEXT NOT NULL )''') db.commit() if __name__ == '__main__': if len(sys.argv) == 3: SECRET_ALPHABET = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ234567' totp_secret = ''.join([random.choice(SECRET_ALPHABET) for _ in range(20)]) with sqlite3.connect('moc-inc.db') as db: db.cursor().execute('''INSERT INTO user ( username, password, totp_secret ) VALUES (?, ?, ?)''', (sys.argv[1], sys.argv[2], totp_secret)) db.commit() print('Created user:') print(' Username:\t' + sys.argv[1]) print(' Password:\t' + sys.argv[2]) print(' TOTP Secret:\t' + totp_secret) exit(0) app.run()
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/BCACTF/2023/crypto/Superstitious/superstitious.py
ctfs/BCACTF/2023/crypto/Superstitious/superstitious.py
from Crypto.Util.number import * import math def myGetPrime(): while True: x = getRandomNBitInteger(1024) for i in range(-10,11): if isPrime(x*x+i): return x*x+i p = myGetPrime() q = myGetPrime() n = p * q e = 65537 message = open('flag.txt', 'rb') m = bytes_to_long(message.read()) c = pow(m, e, n) open("superstitious.txt", "w").write(f"n = {n}\ne = {e}\nc = {c}")
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/BCACTF/2023/crypto/Many_Time_Pad/many-time-pad.py
ctfs/BCACTF/2023/crypto/Many_Time_Pad/many-time-pad.py
from Crypto.Util.number import * secret_key = open("secret_key.txt", "rb").read() def enc(bstr): return long_to_bytes(bytes_to_long(bstr) ^ bytes_to_long(secret_key)) # gotta encode my grocery list groceries = b"I need to buy 15 eggs, 1.7 kiloliters of milk, 11000 candles, 12 cans of asbestos-free cereal, and 0.7 watermelons." out = open("grocery-list.out", "wb") out.write(enc(groceries)) out.close() # gotta encode my flag out = open("many-time-pad.out", "wb") out.write(enc(open("flag.txt", "rb").read())) out.close()
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/BCACTF/2023/crypto/Signature_I/signature-i.py
ctfs/BCACTF/2023/crypto/Signature_I/signature-i.py
from Crypto.Util.number import getPrime, bytes_to_long, long_to_bytes from Crypto.Hash import SHA256 import random, string, binascii, re p = getPrime(2048) q = getPrime(2048) n = p*q e = 3 chars = string.digits + string.ascii_letters + string.punctuation t = "".join(random.sample(chars, 20)) h = SHA256.new() h.update(bytes(t, 'utf-8')) print(f'n = {n}') print(f'Provide a signature for the text {t}') try: sig = bytes_to_long(binascii.unhexlify(input(": "))) str = long_to_bytes(pow(sig, e, n)) hash = re.findall(rb'\x01\xff*\x00(.{32})', str)[0] # PKCS padding if hash == h.digest(): with open("flag.txt", "r") as f: print(f.read()) else: print("Incorrect") except: print("Incorrect")
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/BCACTF/2023/crypto/RSA_is_broken/rsa-broken.py
ctfs/BCACTF/2023/crypto/RSA_is_broken/rsa-broken.py
from Crypto.Util.number import * import math p = 892582974910679288224965877067 q = 809674535888980601722190167357 n = p * q e = 65537 message = open('flag.txt', 'rb') m = bytes_to_long(message.read()) c = pow(m, e, n) print(f'c = {c}') # OUTPUT: # c = 36750775360709769054416477187492778112181529855266342655304 d = pow(e, -1, math.lcm(p-1, q-1)) newm = pow(c, d, n) print(long_to_bytes(newm)) # OUTPUT: # b'D\\\x8b\xe3?\x9c\xcd\xa8\xbb(\x80\xa8\xb2\xd8\xffj\x1b\xfbA\x91}\x9e\x89\x00&' # ??? what
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/BCACTF/2023/web/WORD_GAME/app.py
ctfs/BCACTF/2023/web/WORD_GAME/app.py
from flask import Flask, request, jsonify, render_template import sqlite3 as sl import random import string import os import re if os.path.exists("words.db"): os.remove("words.db") app = Flask("wordgame") db = sl.connect("words.db", check_same_thread=False) chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ??????????????????????????????????????????????????????????????????????????????EEEEEETTTTTAAAAAIIIIIOOOONNNNSSSSRRRR" with db: flagTable = "flag"+''.join(random.choices(string.ascii_uppercase + string.digits, k=13)) db.execute("CREATE TABLE IF NOT EXISTS words (word TEXT, nr INT)") db.execute(f"CREATE TABLE IF NOT EXISTS {flagTable} (flag TEXT)") with open("sowpods.txt") as f: for line in f: word = line.strip() if len(word) == 4: db.execute(f"INSERT INTO words VALUES ('{word}', {random.randint(0, 1000000)})") with open("flag.txt") as f: flag = f.read().strip() assert re.search("[^A-Za-z0-9_}{]", flag) == None db.execute(f"INSERT INTO {flagTable} VALUES ('{flag}')") def randPtrn(): return random.choice(chars)+random.choice(chars)+random.choice(chars)+random.choice(chars) def checkWd(word): query = f"SELECT word FROM words WHERE word = '{word}'" ls = db.execute(query).fetchall() return len(ls) > 0 def getAns(ptrn): query = f"SELECT word FROM words WHERE word LIKE '{ptrn.replace('?','_')}' ORDER BY nr DESC" res = db.execute(query).fetchall() if res: return res[0][0] return None @app.route("/", methods=["GET"]) def index(): return render_template("index.html", pattern=randPtrn(), message="") @app.route("/", methods=["POST"]) def ask(): ptrn = request.form.get("ptrn") word = request.form.get("word") regex = re.compile(re.sub("[^A-Za-z.]","",ptrn.replace("?", ".")).upper()) if not regex.match(word.upper()): return render_template("index.html", pattern=randPtrn(), message=f"{word.upper()} ISNT {ptrn}") if checkWd(word.upper()): return render_template("index.html", pattern=randPtrn(), message=f"{word.upper()} DOES WORK") rndAns = getAns(ptrn) if rndAns == None: return render_template("index.html", pattern=randPtrn(), message=f"LMAO ZERO SOLS") padW = word.ljust(max(len(word),len(rndAns))) padR = rndAns.ljust(max(len(word),len(rndAns))) q = [i for i in range(len(padW)) if padW[i] != padR[i]] if len(q) == 0: return render_template("index.html", pattern=randPtrn(), message=f"HUHH WHAT") return render_template("index.html", pattern=randPtrn(), message=f"{word} ISNT WORD. HINT: CHAR {min(q)}") if __name__ == "__main__": app.run(host="0.0.0.0", port=3000)
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/BCACTF/2025/misc/locked_out/server.py
ctfs/BCACTF/2025/misc/locked_out/server.py
#!/usr/bin/env python3 while True: allowed = set("abcdefghijklm") code = input(">>> ") broke_the_rules = False for c in code: if c.lower() not in allowed and c not in "\"'()=+:;. 1234567890": print(f"Character {c} not allowed!") broke_the_rules = True break allowed = set(chr((ord(a) - ord('a') + 1) % 26 + ord('a')) for a in allowed) if not broke_the_rules: exec(code)
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/BCACTF/2025/misc/locked_out_again/server.py
ctfs/BCACTF/2025/misc/locked_out_again/server.py
#!/usr/bin/env python3 class DescriptorTrap: def __init__(self, name): self.name = name self.access_count = 0 def __get__(self, obj, objtype=None): self.access_count += 1 if self.access_count > 3: raise Exception(f"Too many accesses to {self.name}!") return lambda *args, **kwargs: None def __set__(self, obj, value): raise Exception(f"Cannot modify {self.name}!") class MetaTrap(type): def __new__(cls, name, bases, namespace): for attr in ["print", "exec", "eval", "open", "input", "__import__"]: namespace[attr] = DescriptorTrap(attr) # Make all methods return None after 2 calls for key, value in namespace.items(): if callable(value) and not key.startswith("__"): namespace[key] = DescriptorTrap(key) return super().__new__(cls, name, bases, namespace) def __getattribute__(cls, name): if name in ["__dict__", "__class__", "__bases__", "__mro__"]: raise Exception("No metaclass inspection allowed!") return super().__getattribute__(name) class JailCell(metaclass=MetaTrap): # These will be trapped by the metaclass print = print exec = exec eval = eval open = open __import__ = __import__ def escape_attempt(self): return "Nice try!" # Create the jail environment jail = JailCell() # Block access to dangerous builtins blocked_builtins = { "exec", "eval", "compile", "open", "__import__", "input", "breakpoint", "help", "exit", "quit", "copyright", "credits", } if hasattr(__builtins__, "__dict__"): builtin_dict = __builtins__.__dict__ else: builtin_dict = __builtins__ safe_builtins = {k: v for k, v in builtin_dict.items() if k not in blocked_builtins} safe_builtins["print"] = lambda *args, **kwargs: None # Neuter print safe_builtins["open"] = lambda *args, **kwargs: None # Neuter open print("read the contents of ./flag.txt") print("man i LOVE wjat.") user_code = input("enter your escape code: ") try: exec(user_code, {"__builtins__": safe_builtins, "jail": jail}, {}) except Exception as e: print("why are you failing me. come on.")
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/BCACTF/2025/misc/expletive/expletive.py
ctfs/BCACTF/2025/misc/expletive/expletive.py
blacklist = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789" def security_check(s): return any(c in blacklist for c in s) or s.count('_') > 50 BUFFER_SIZE = 36 while True: cmds = input("> ") if security_check(cmds): print("invalid input") else: if len(cmds) > BUFFER_SIZE: print(open("flag.txt", "r").read()) break else: print("nope")
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/BCACTF/2025/algo/codeBusting/server.py
ctfs/BCACTF/2025/algo/codeBusting/server.py
import sys import json import random import time import unicodedata TIME_LIMIT = 15 # 15 seconds to solve em all! def remove_accents_preserve_n(text): """ Remove diacritics from text but preserve Ñ as its own character """ result = [] for char in text: if char in ["Ñ", "ñ"]: # Keep Ñ and ñ as they are result.append(char) else: # Remove accents from other characters # NFD = Normalization Form Decomposed normalized = unicodedata.normalize("NFD", char) # Filter out combining characters (accents) without_accents = "".join( c for c in normalized if unicodedata.category(c) != "Mn" ) result.append(without_accents) return "".join(result) def levenshtein_distance(s1, s2): """ Calculate the Levenshtein distance between two strings """ if len(s1) < len(s2): return levenshtein_distance(s2, s1) if len(s2) == 0: return len(s1) # Create a matrix to store distances previous_row = list(range(len(s2) + 1)) for i, c1 in enumerate(s1): current_row = [i + 1] for j, c2 in enumerate(s2): # Cost of insertions, deletions, or substitutions insertions = previous_row[j + 1] + 1 deletions = current_row[j] + 1 substitutions = previous_row[j] + (c1 != c2) current_row.append(min(insertions, deletions, substitutions)) previous_row = current_row return previous_row[-1] def normalize_text(text): """ Normalize text for comparison by removing spaces and converting to lowercase """ return "".join(text.lower().split()) def is_close(user_answer, correct_answer, max_errors=2): """ Check if user answer is close to correct answer within max_errors """ # Normalize both strings normalized_user = normalize_text(user_answer) normalized_correct = normalize_text(correct_answer) # Calculate edit distance distance = levenshtein_distance(normalized_user, normalized_correct) return distance <= max_errors def key_s2tring_random(xeno): spl = lambda word: [char for char in word] if xeno: A = spl("ABCDEFGHIJKLMNÑOPQRSTUVWXYZ") else: A = spl("ABCDEFGHIJKLMNOPQRSTUVWXYZ") while not test1(A): random.shuffle(A) return "".join(A) def test1(l): # Fixed: should check length properly for both regular and xenocrypt alphabet_size = len(l) for i in range(alphabet_size): if i < 14 and ord(l[i]) - 65 == i: return False elif ( i > 14 and i < alphabet_size and ord(l[i]) - 65 == i - 1 ): # Account for Ñ offset return False elif i == 14 and l[i] == "Ñ": # Ñ shouldn't be in its "natural" position return False return True def getRandWord(minlen, maxlen): with open("words.txt", "r") as f: for _ in range(random.randint(0, 9000)): f.readline() r = "" while len(r) < minlen or len(r) > maxlen: r = f.readline().strip() return r def genQuotes(n): l = open("quotes.txt", "r", encoding="utf-8").read().split("\n") random.shuffle(l) count = 0 loc = 0 r = [] while count < n: if len(l[loc]) > 65 and len(l[loc]) < 160: r.append(l[loc]) count += 1 loc += 1 return r def genQuoteLength(minlen, maxlen): l = open("quotes.txt", "r", encoding="utf-8").read().split("\n") random.shuffle(l) loc = 0 while 1: if len(l[loc]) > minlen and len(l[loc]) < maxlen: return l[loc] loc += 1 def genSpanishQuote(minlen, maxlen): data = json.load(open("spanish.json", "r")) l = [p["Cita"] for p in data["quotes"]] random.shuffle(l) loc = 0 while 1: if len(l[loc]) > minlen and len(l[loc]) < maxlen: return l[loc][1:-1] loc += 1 def gen_rand_mono_pair(quote, pat): key = key_s2tring_random(False) r = {chr(i + 65): key[i] for i in range(26)} plaintext = quote.upper() ciphertext = "".join(r.get(c, c) for c in plaintext) return ciphertext, plaintext def gen_rand_affine_pair(quote): a = random.choice([3, 5, 7, 9, 11, 15, 17, 19, 21, 23]) b = random.randint(3, 24) plaintext = quote.upper() ciphertext = "" for c in plaintext: if "A" <= c <= "Z": ciphertext += chr((a * (ord(c) - 65) + b) % 26 + 65) else: ciphertext += c return ciphertext, plaintext def gen_rand_caesar_pair(quote): a = random.randint(3, 24) plaintext = quote.upper() ciphertext = "" for c in plaintext: if "A" <= c <= "Z": ciphertext += chr((ord(c) - 65 + a) % 26 + 65) else: ciphertext += c return ciphertext, plaintext def gen_rand_vig_pair(quote): key = getRandWord(5, 8).upper() plaintext = quote.upper() ciphertext = "" for i, c in enumerate(plaintext): if "A" <= c <= "Z": k = key[i % len(key)] ciphertext += chr((ord(c) - 65 + ord(k) - 65) % 26 + 65) else: ciphertext += c return ciphertext, plaintext def genRandPorta_pair(quote): key = getRandWord(5, 8).upper() plaintext = quote.upper() ciphertext = "" for i, c in enumerate(plaintext): if "A" <= c <= "Z": k = key[i % len(key)] x = ord(c) - 65 y = ord(k) - 65 if y % 2 == 1: y -= 1 if x < 13: ciphertext += chr(((x + y) % 26) + 65) else: ciphertext += chr(((x - y) % 26) + 65) else: ciphertext += c return ciphertext, plaintext def gen_rand_xeno_pair(): key = key_s2tring_random(True) quote = genSpanishQuote(70, 160) # Remove accents but preserve Ñ normalized_quote = remove_accents_preserve_n(quote) # Create mapping for 27-character Spanish alphabet r = {} # Map A-M to first 14 positions for i in range(14): r[chr(i + 65)] = key[i] # Map Ñ to 15th position (index 14) r["Ñ"] = key[14] # Map N-Z to remaining positions (indices 15-26) for i in range(14, 26): r[chr(i + 65)] = key[i + 1] plaintext = normalized_quote.upper() ciphertext = "".join(r.get(c, c) for c in plaintext) return ciphertext, plaintext def generate_test_pairs(): l = [ "1 2", "1 1", "1 0", "1 1", "2 1", "2 2", "2 1", "2 0", "4 D", "4 E", "4 D", "4 E", "5 C", "8 1", "8 1", "8 1", ] n = len(l) q = genQuotes(n + 1) pairs = [] ct, pt = gen_rand_mono_pair(q[-1], False) pairs.append((ct, pt)) for i in range(n): question = l[i].split(" ") if int(question[0]) <= 2: ct, pt = gen_rand_mono_pair(q[i], question[0] == "2") elif int(question[0]) == 4: ct, pt = gen_rand_caesar_pair(q[i]) elif int(question[0]) == 8: ct, pt = gen_rand_xeno_pair() pairs.append((ct, pt)) return pairs def main(): with open("./flag.txt", "r") as file: FLAG = file.read().strip() pairs = generate_test_pairs() sys.stdout.write("Welcome to the Codebusting Challenge!\n") sys.stdout.write("Note: Answers are accepted with up to 2 character errors.\n") sys.stdout.flush() start_time = time.time() for idx, (ct, pt) in enumerate(pairs): # sys.stdout.write(f"plaintext is {pt}\n") # debugging purposes sys.stdout.write(f"Ciphertext {idx+1}: {ct}\nYour answer: ") sys.stdout.flush() user = sys.stdin.readline().strip() if time.time() - start_time > TIME_LIMIT: sys.stdout.write("Time limit exceeded.\n") sys.exit(1) if is_close(user, pt, max_errors=2): if levenshtein_distance(normalize_text(user), normalize_text(pt)) > 0: sys.stdout.write( f"Close enough! (Distance: {levenshtein_distance(normalize_text(user), normalize_text(pt))})\n" ) continue else: distance = levenshtein_distance(normalize_text(user), normalize_text(pt)) sys.stdout.write( f"Incorrect. Your answer was {distance} errors away (max allowed: 2).\n" ) sys.exit(1) sys.stdout.write(f"Congratulations! Here is your flag: {FLAG}\n") sys.exit(0) if __name__ == "__main__": main()
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/BCACTF/2025/rev/5d_printing/source.py
ctfs/BCACTF/2025/rev/5d_printing/source.py
# oops i accidentally deleted everything except the comments!! you can still figure it out tho: """ Public 5MF Generator for the 5D Printer Challenge This script reads the flag from standard input and generates a scrambled 5MF file. The commands are intentionally output in a random order so that the correct ordering must be recovered by sorting by the extra dimensions. The printer is “5D” because, in addition to X, Y, and Z (only printing the first layer --> Z=0), each command carries: U = (subpath_index * 100) + (t * 100) V = 50 * sin(2*pi*t) where t is the normalized progression along that command segment. """ import sys, math, random import numpy as np from matplotlib.textpath import TextPath from matplotlib.path import Path # Generate a vector outline from the provided flag text. # Group the vertices into subpaths (each starting with MOVETO) # list to store each command (dict with keys: code, X, Y, Z, U, V) # first command, distance is zero # t goes from 0 to 1 along the subpath. (When tot==0, t remains 0.) # Unique twist: use subpath index so that commands from later subpaths always have higher U. # V is a cyclic parameter (represents, a material property over time). # Z is maintained 0 for a 2D layer. # Write out in a custom 5MF format. # Use G5D_MOVE for MOVETO commands, G5D_DRAW otherwise.
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/BCACTF/2025/crypto/Morse_Marsh/morse_encodings.py
ctfs/BCACTF/2025/crypto/Morse_Marsh/morse_encodings.py
MORSE_CODE = { 'A': '.-', 'B': '-...', 'C': '-.-.', 'D': '-..', 'E': '.', 'F': '..-.', 'G': '--.', 'H': '....', 'I': '..', 'J': '.---', 'K': '-.-', 'L': '.-..', 'M': '--', 'N': '-.', 'O': '---', 'P': '.--.', 'Q': '--.-', 'R': '.-.', 'S': '...', 'T': '-', 'U': '..-', 'V': '...-', 'W': '.--', 'X': '-..-', 'Y': '-.--', 'Z': '--..', '0': '-----','1': '.----','2': '..---','3': '...--','4': '....-','5': '.....', '6': '-....','7': '--...','8': '---..','9': '----.', '_': 'x', 'Þ': ';', 'a': ';.-', 'b': ';-...', 'c': ';-.-.', 'd': ';-..', 'e': ';.', 'f': ';..-.', 'g': ';--.', 'h': ';....', 'i': ';..', 'j': ';.---', 'k': ';-.-', 'l': ';.-..', 'm': ';--', 'n': ';-.', 'o': ';---', 'p': ';.--.', 'q': ';--.-', 'r': ';.-.', 's': ';...', 't': ';-', 'u': ';..-', 'v': ';...-', 'w': ';.--', 'x': ';-..-', 'y': ';-.--', 'z': ';--..' } # All lowercase letters have the same encoding as their uppercase versions with a ';' prefix # Spaces in the plaintext are marked by '_'
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/BCACTF/2025/crypto/Q/server.py
ctfs/BCACTF/2025/crypto/Q/server.py
from os import urandom from secrets import randbelow secret_str = urandom(16).hex() secret = [ord(char) for char in secret_str] for _ in range(5000): encoded = [value + randbelow(2000) for value in secret] print(encoded) user_secret = input('What is the secret? ') if user_secret == secret_str: with open('flag.txt', 'r') as file: print(file.read()) else: print('Wrong :(')
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/BCACTF/2022/rev/Ghost_Game/GhostGame.py
ctfs/BCACTF/2022/rev/Ghost_Game/GhostGame.py
########## ########## ########## ########## ########## # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # ########## ########## ########## ########## ########## ### SO MANY DOORS, WHICH ONE TO CHOOSE??? ### import random FLAG = 'REDACTED' REQ_WINS = 10 DOORS = 10 usr_choice = '' random.seed(123049) wins = 0 def play(): comp_choice = random.randint(-10000, 10000) comp_choice %= DOORS print(comp_choice) print(f'\nYou are presented with {DOORS} doors, {DOORS - 1} are haunted and 1 will allow you to pass.') door_choice = int(input('Which will you choose?\n')) print(f'\nYou chose door {door_choice}...') return door_choice == comp_choice print(f'Welcome to Ghost Game! Win {REQ_WINS} times in a row for your reward.') while True: print('\n1. Play\n2. Quit') usr_choice = input() if usr_choice == '1': if play(): print('You chose the right door and survived! Phew.') wins += 1 else: print('That door had a ghost behind it. RIP.') wins = 0 elif usr_choice == '2': break else: print('Invalid input.') if wins >= REQ_WINS: print('You must have insane luck! Here is your treasure:') print(FLAG)
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/BCACTF/2022/rev/Pirates/encode.py
ctfs/BCACTF/2022/rev/Pirates/encode.py
from PIL import Image import numpy as np import cv2 FILE = 'original.png' img = Image.open(FILE) arr = np.asarray(img, dtype=np.float64) grayArr = np.zeros((len(arr), len(arr[0]))) for vert in range(len(arr)): for hori in range(len(arr[0])): grayArr[vert][hori] = arr[vert][hori] nHeight = len(grayArr) - len(grayArr) % 8 nWidth = len(grayArr[0]) - len(grayArr[0]) % 8 cropArr = np.zeros((nHeight, nWidth)) # resize dumb for i in range(0, nHeight): for j in range(0, nWidth): cropArr[i,j] = grayArr[i,j] / 2# - 128 grayArr = cropArr dctArr = np.zeros((nHeight, nWidth)) def dct2(arr): return cv2.dct(arr/255)*255 dctArr = np.zeros((nHeight, nWidth)) for i in range(0, nHeight, 8): for j in range(0, nWidth, 8): dctArr[i:i+8,j:j+8] = dct2(grayArr[i:i+8,j:j+8]) scalar = np.array([16, 11, 10, 16, 24, 40, 51, 61, 12, 12, 14, 19, 26, 58, 60, 55, 14, 13, 16, 24, 40, 57, 69, 56, 14, 17, 22, 29, 51, 87, 80, 62, 18, 22, 37, 56, 68, 109,103,77, 24, 35, 55, 64, 81, 104,113,92, 49, 64, 78, 87, 103,121,120,101, 72, 92, 95, 98, 112,100,103,99]) scalar = scalar.reshape((8, 8)) reduArr = np.zeros((nHeight, nWidth)) for i in range(0, nHeight, 8): for j in range(0, nWidth, 8): block = np.array(dctArr[i:i+8,j:j+8]) reduArr[i:i+8,j:j+8] = np.divide(block, scalar) for i in range(0, nHeight): for j in range(0, nWidth): reduArr[i,j] = reduArr[i,j].round() if reduArr[i,j] == 0: reduArr[i,j] = 0 order = [0, 1, 8, 16, 9, 2, 3, 10, 17, 24, 32, 25, 18, 11, 4, 5, 12, 19, 26, 33, 40, 48, 41, 34, 27, 20, 13, 6, 7, 14, 21, 28, 35, 42, 49, 56, 57, 50, 43, 36, 29, 22, 15, 23, 30, 37, 44, 51, 58, 59, 52, 45, 38, 31, 39, 46, 53, 60, 61, 54, 47, 55, 62, 63] result = '' for i in range(0, nHeight, 8): for j in range(0, nWidth, 8): toBeRead = reduArr[i:i+8, j:j+8].flatten() for index in order: num = toBeRead[index] if num >= 0: sign = '0' else: sign = '1' result += f'{sign}{int(abs(toBeRead[index])):07b}' compressed_value = f'0{nHeight:07b}0{nWidth:07b}{result}' f = open("flag", "wb") f.write(int("".join(compressed_value),2).to_bytes(len(compressed_value)//8, byteorder="big"))
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/BCACTF/2022/rev/Password_Manager/PwdManager.py
ctfs/BCACTF/2022/rev/Password_Manager/PwdManager.py
HASHEDPWD = '111210122915474114123027144625104141324527134638392719373948' key = { 'a':10, 'b':11, 'c':12, 'd':13, 'e':14, 'f':15, 'g':16, 'h':17, 'i':18, 'j':19, 'k':20, 'l':21, 'm':22, 'n':23, 'o':24, 'p':25, 'q':26, 'r':27, 's':28, 't':29, 'u':30, 'v':31, 'w':32, 'x':33, 'y':34, 'z':35, '0':36, '1':37, '2':38, '3':39, '4':40, '5':41, '6':42, '7':43, '8':44, '0':45, '_':46, '{':47, '}':48 } unhashed = input("Enter the password!") result = '' # The Hash for element in unhashed: result += str(key[element]) if result == HASHEDPWD: print("That's Right! The password is the flag.") else: print("That's not right!")
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/BCACTF/2022/rev/Bit_Shuffling/shuffle.py
ctfs/BCACTF/2022/rev/Bit_Shuffling/shuffle.py
# below from https://stackoverflow.com/a/10238140 # (licensed CC BY-SA 3.0, by John Gaines Jr.) def tobits(s): result = [] for c in s: bits = bin(ord(c))[2:] bits = '00000000'[len(bits):] + bits result.extend([b for b in bits]) return result # end copied text txt = open("flag.txt", "r").read() f = open("shuffled", "wb") order = [ 0, 1, 1, 0, 0, 0, 1, 0 ] deck = tobits(txt) for i in order: newdeck = [] for j in range(int(len(deck)/2)): if i == 0: newdeck.append(deck[j]) newdeck.append(deck[j+int(len(deck)/2)]) else: newdeck.append(deck[j+int(len(deck)/2)]) newdeck.append(deck[j]) deck = newdeck f.write(int("".join(deck),2).to_bytes(len(deck)//8, byteorder="big"))
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/BCACTF/2022/rev/Convoluted/convoluted.py
ctfs/BCACTF/2022/rev/Convoluted/convoluted.py
import numpy as np from scipy import ndimage from PIL import Image i = Image.open("flag.png") a = np.array(i) a = np.transpose(a,(2,0,1)) r = a[0] g = a[1] b = a[2] k = np.array([[0,0,0],[0,0.25,0.25],[0,0.25,0.25]]) r2 = ndimage.convolve(r,k,mode="constant",cval=0) g2 = ndimage.convolve(g,k,mode="constant",cval=0) b2 = ndimage.convolve(b,k,mode="constant",cval=0) out = Image.fromarray(np.transpose(np.array([r2,g2,b2]),(1,2,0))) out.save("chall.png")
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/BCACTF/2022/crypto/Ehrenfest/gs1.py
ctfs/BCACTF/2022/crypto/Ehrenfest/gs1.py
#!/usr/bin/env python3 import math import binascii from Crypto.Util.Padding import pad, unpad from Crypto.Util.number import bytes_to_long, long_to_bytes def chunks(l, n): assert(len(l) % n == 0) for i in range(0, len(l), n): yield l[i:i+n] FLAG_LEN = 72 M_SIZE = math.isqrt(FLAG_LEN * 8) flag = input("What is your key? ") assert(len(flag) == FLAG_LEN) # turn flag into a matrix inter_key = bin(int(flag.encode('ascii').hex(), 16))[2:].rjust(FLAG_LEN * 8, '0') key = [[int(c) for c in l] for l in chunks(inter_key, M_SIZE)] def encrypt(ptxt): assert len(ptxt) == M_SIZE enc = [0] * M_SIZE for i in range(M_SIZE): for j in range(M_SIZE): if key[i][j] == 1: enc[i] ^= ptxt[j] return binascii.hexlify(bytes(enc)) def decrypt(ctxt): return "todo" while True: print("Would you like to encrypt (E), decrypt (D), or quit (Q)?", flush=True) l = input(">>> ").strip().upper() if (len(l) > 1): print("You inputted more than one character...", flush=True) elif (l == "Q"): print("Thank you for using the Gray-Scott model of encryption!", flush=True) exit() elif (l == "E"): print("What would you like to encrypt?", flush=True) I = input(">>> ").strip().encode('ascii') c = b''.join([encrypt(i) for i in chunks(pad(I, M_SIZE), M_SIZE)]) print("Your encrypted message is:", c.decode('ascii'), flush=True) elif (l == "D"): print("What was the message?", flush=True) I = input(">>> ").strip() m = b''.join([decrypt(i) for i in chunks(I, 2 * M_SIZE)]) print("Your decrypted message is:", unpad(m, M_SIZE), flush=True)
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/BCACTF/2022/crypto/Gray-Scott/gs1.py
ctfs/BCACTF/2022/crypto/Gray-Scott/gs1.py
#!/usr/bin/env python3 import math import binascii from Crypto.Util.Padding import pad, unpad from Crypto.Util.number import bytes_to_long, long_to_bytes def chunks(l, n): assert(len(l) % n == 0) for i in range(0, len(l), n): yield l[i:i+n] FLAG_LEN = 72 M_SIZE = math.isqrt(FLAG_LEN * 8) flag = input("What is your key? ") assert(len(flag) == FLAG_LEN) # turn flag into a matrix inter_key = bin(int(flag.encode('ascii').hex(), 16))[2:].rjust(FLAG_LEN * 8, '0') key = [[int(c) for c in l] for l in chunks(inter_key, M_SIZE)] def encrypt(ptxt): assert len(ptxt) == M_SIZE enc = [0] * M_SIZE for i in range(M_SIZE): for j in range(M_SIZE): if key[i][j] == 1: enc[i] ^= ptxt[j] return binascii.hexlify(bytes(enc)) def decrypt(ctxt): return "todo" while True: print("Would you like to encrypt (E), decrypt (D), or quit (Q)?", flush=True) l = input(">>> ").strip().upper() if (len(l) > 1): print("You inputted more than one character...", flush=True) elif (l == "Q"): print("Thank you for using the Gray-Scott model of encryption!", flush=True) exit() elif (l == "E"): print("What would you like to encrypt?", flush=True) I = input(">>> ").strip().encode('ascii') c = b''.join([encrypt(i) for i in chunks(pad(I, M_SIZE), M_SIZE)]) print("Your encrypted message is:", c.decode('ascii'), flush=True) elif (l == "D"): print("What was the message?", flush=True) I = input(">>> ").strip() m = b''.join([decrypt(i) for i in chunks(I, 2 * M_SIZE)]) print("Your decrypted message is:", unpad(m, M_SIZE), flush=True)
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/AfricabattleCTF/2023/Quals/crypto/Sahara/generate.py
ctfs/AfricabattleCTF/2023/Quals/crypto/Sahara/generate.py
from cryptography.hazmat.primitives.asymmetric import rsa, padding from cryptography.hazmat.primitives import serialization from cryptography.hazmat.backends import default_backend from base64 import b64encode, b64decode FLAG = open("flag.txt").read() def load_public_key(): with open('pub.pem', 'rb') as pubf: pubkey = serialization.load_pem_public_key(pubf.read(), backend=default_backend()) return pubkey def encrypt(pubkey:rsa.RSAPublicKey, ptxt:str) -> str: enc = pubkey.encrypt(ptxt.encode(), padding.PKCS1v15()) return b64encode(enc).decode() def get_pem(key:rsa.RSAPrivateKey|rsa.RSAPublicKey): if isinstance(key, rsa.RSAPublicKey): pem = key.public_bytes(encoding=serialization.Encoding.PEM, format=serialization.PublicFormat.SubjectPublicKeyInfo) else: pem = key.private_bytes(encoding=serialization.Encoding.PEM, format=serialization.PrivateFormat.PKCS8, encryption_algorithm=serialization.NoEncryption()) return pem if __name__ == '__main__': pub_key = load_public_key() pub_key_pem = get_pem(pub_key).decode() enc_flag = encrypt(pub_key, FLAG) with open('flag.enc', 'w') as f: f.write(enc_flag)
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/AfricabattleCTF/2023/Quals/crypto/ROCYOU/rocyou.py
ctfs/AfricabattleCTF/2023/Quals/crypto/ROCYOU/rocyou.py
from Crypto.Util.number import bytes_to_long FLAG = bytes_to_long(open("flag.txt").read().encode()) n = 14558732569295568217680262946946350946269492093750369718350618000766298342508431492935822827678025952146979183716519987777790434353113812051439651306232101 e = 65537 c = pow(FLAG, e, n) print(f"c = {c}") # c = 10924637845512114669339598787759482373871484619074241479073765261738618851409833137908272858354441670603598700617114497065118363300675413269144392865493504
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/AfricabattleCTF/2023/Quals/crypto/SEA/chall.py
ctfs/AfricabattleCTF/2023/Quals/crypto/SEA/chall.py
from Crypto.Cipher import AES from Crypto.Util.Padding import pad from os import urandom iv = urandom(16) key = urandom(16) FLAG = b"battleCTF{REDACTED}" def encrypt(data): cipher = AES.new(key, AES.MODE_CFB, iv) return cipher.encrypt(pad(data, 16)) print(encrypt(FLAG).hex()) while True: print(encrypt(input("> ").encode()).hex())
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/AfricabattleCTF/2023/Quals/crypto/Gooss/gooss.py
ctfs/AfricabattleCTF/2023/Quals/crypto/Gooss/gooss.py
import random flag = 'battleCTF{******}' a = random.randint(4,9999999999) b = random.randint(4,9999999999) c = random.randint(4,9999999999) d = random.randint(4,9999999999) e = random.randint(4,9999999999) enc = [] for x in flag: res = (2*a*pow(ord(x),4)+b*pow(ord(x),3)+c*pow(ord(x),2)+d*ord(x)+e) enc.append(res) print(enc) #Output: [1245115057305148164, 1195140205147730541, 2441940832124642988, 2441940832124642988, 1835524676869638124, 1404473868033353193, 272777109172255911, 672752034376118188, 324890781330979572, 3086023531811583439, 475309634185807521, 1195140205147730541, 2441940832124642988, 1578661367846445708, 2358921859155462327, 1099718459319293547, 773945458916291731, 78288818574073053, 2441940832124642988, 1578661367846445708, 1099718459319293547, 343816904985468003, 1195140205147730541, 2527132076695959961, 2358921859155462327, 2358921859155462327, 1099718459319293547, 72109063929756364, 2796116718132693772, 72109063929756364, 2796116718132693772, 72109063929756364, 2796116718132693772, 3291439457645322417]
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/AfricabattleCTF/2023/Quals/crypto/Own_e/chall.py
ctfs/AfricabattleCTF/2023/Quals/crypto/Own_e/chall.py
from Crypto.Util.number import getPrime from os import urandom def message(secret, e): m = f'The invite token is {secret.hex()} and it is encrypted with e = {e}.'.encode() return int.from_bytes(m, 'big') def encrypt(data): out = [] i = 0 for pin in data: out.append((int(pin) + 5)^i) i+=1 return out def main(): flag = open("flag.txt").read() p = getPrime(1024) q = getPrime(1024) n = p * q secret = urandom(64) for _ in range(3): e = int(input("\nEnter your e: ")) if e == 1: raise Exception('send me better values!') m = message(secret, e) c = encrypt(str(pow(m, e, n))) print(f'c = {c}') guess = input("Enter your invite code:") if secret != bytes.fromhex(guess): raise Exception('incorrect Invite code!') print(f'\nFLAG :{flag}') if __name__ == '__main__': try: main() except: print('better luck next time!')
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/CyberSpace/2024/misc/Game_with_Rin/server.py
ctfs/CyberSpace/2024/misc/Game_with_Rin/server.py
from basement_of_rin import NanakuraRin, flag, generate_graph import time from random import Random def Server(m): print("Server> " + m) def Rin(m): print("Rin> " + m) def check_subset(_subset, set): subset = sorted(_subset) assert len(subset) != 0 for i in range(len(subset) - 1): subset[i] < subset[i + 1] for x in subset: assert x in set class disjoint_set: def __init__(self, n): self.n = n self.p = [-1] * self.n def root(self, u): if self.p[u] < 0: return u self.p[u] = self.root(self.p[u]) return self.p[u] def share(self, u, v): return self.root(u) == self.root(v) def merge(self, u, v): u, v = self.root(u), self.root(v) if u == v: return False if self.p[u] > self.p[v]: u, v = v, u self.p[u] += self.p[v] self.p[v] = u return True def clear(self): self.p = [-1] * self.n def check_tree(subset, V, edges): assert len(subset) == V - 1 ds = disjoint_set(V) for i in subset: assert isinstance(i, int) and 0 <= i < len(edges) u, v, w = edges[i] assert ds.merge(u, v) def determine_the_winner(piles): # https://en.wikipedia.org/wiki/Nim # Rin-chan is perfect, so she'll always make the optimal move. # You're perfect too, so you'll always make the perfect move as well. # Let's fast-forward the game to the end :) nim = 0 for x in piles: nim ^= x return "first" if nim != 0 else "second" class You: def __init__(self, V, edges): Server(f"{V = }") Server(f"{edges = }") def first_move(self): Server("Please choose S") return sorted(list(map(int, input("You> S = ").strip().split(" ")))) def read_first_move(self, S): Rin(f"I choose S = {' '.join([str(i) for i in S])}") def second_move(self): Server("Please choose T") return sorted(list(map(int, input("You> T = ").strip().split(" ")))) Rin("Do you want this flag?") Rin("I'll consider giving it to you if you defeat me 200 times :)") time.sleep(0.5) Server("-----------------------------------------------------------------------------------------") Server("[Round Manual]") Server("1. The server generates a set of edges with integer weight on vertices 0 ~ V-1.") Server("2. You can either choose to go first or second.") Server("3. First player chooses a subset S of edges of size V-1 which forms a tree.") Server("( For the definition of tree, see https://en.wikipedia.org/wiki/Tree_(graph_theory) )") Server("4. Second player chooses a non-empty subset T of S.") Server("5. Add a pile consisting of w stones for each edge (u, v, w) in T.") Server("6. Winner of the round is the winner of the nim game on those set of piles.") Server("-----------------------------------------------------------------------------------------") time.sleep(0.5) Rin("GLHF!") time.sleep(0.5) for round_number in range(1, 201): Server(f"Round {round_number}") V, edges = generate_graph(round_number) assert isinstance(V, int) assert 30 <= V <= 200 assert len(edges) <= 300 for u, v, w in edges: assert isinstance(u, int) and isinstance(v, int) and isinstance(w, int) assert 0 <= u < V and 0 <= v < V and 0 <= w < 2**(V-1) first, second = You(V, edges), NanakuraRin(V, edges) Rin("Do you want to go [first] or [second]?") resp = input("You> ").strip() if resp not in ["first", "second"]: Rin("That's not an option >:(") exit(0) if resp == "first": Rin("Sure, you go first :D") else: Rin("Ok, I go first :D") first, second = second, first S = first.first_move() second.read_first_move(S) check_subset(S, [i for i in range(len(edges))]) check_tree(S, V, edges) if resp == "first": Rin("My turn!") else: Rin("Your turn!") T = second.second_move() check_subset(T, S) if resp == "first": Rin(f"I choose T = {' '.join([str(i) for i in T])}") winner = determine_the_winner([edges[i][2] for i in T]) r = Random() if winner != resp: Rin(r.choice(["Git gud", "Noob", "Easy"])) exit(0) Rin(r.choice(["Not like this!", "You won :(", "Ouch!", "You got lucky this time."])) Rin("GG Well played!") Rin("I guess I have no choice but to give you the flag.") Rin(f"{flag}")
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/CyberSpace/2024/misc/quantum/quantum-dist.py
ctfs/CyberSpace/2024/misc/quantum/quantum-dist.py
# We ran this challenge on a quantum computer FLAG = "CSCTF{fake_flag_for_testing}" import random def gen(mn, mx): n = random.randint(mn, mx) global p p = [0] * n for i in range(n): p[i] = (random.randint(1, n), random.randint(1, n)) return p def ask(x0, y0): sum = 0 for x, y in p: sum += abs(x - x0) + abs(y - y0) return sum def query(x0, y0, x1, y1): sum = 0 for x in range(x0, x1 + 1): for y in range(y0, y1 + 1): sum += ask(x, y) return sum
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/CyberSpace/2024/misc/quantum/server.py
ctfs/CyberSpace/2024/misc/quantum/server.py
import quantum, random N = 500 def bye(): print("bitset") exit(0) def main(): a = quantum.gen(N - N // 10, N) n = len(a) print(n) print("Ask me anything?") q = 0 while True: m = int(input().strip()) if m == -1: break q += m if q > 1.9 * n: bye() xs = list(map(int, input().split())) ys = list(map(int, input().split())) if len(xs) != m or len(ys) != m: bye() resp = [] for x, y in zip(xs, ys): if 0 > x or x >= n or 0 > y or y >= n: bye() resp.append(quantum.ask(x, y)) print(" ".join([str(x) for x in resp])) print("It is easy to prove that you can answer the following queries!") q = random.randint(N - N // 10, N) print(q) expected = [0] * q for i in range(q): x0 = random.randint(1, n - 1) x1 = random.randint(x0, n - 1) y0 = random.randint(1, n - 1) y1 = random.randint(y0, n - 1) expected[i] = quantum.query(x0, y0, x1, y1) print(x0, y0, x1, y1) output = list(map(int, input("Your answer? ").split())) if output == expected: print("AC") else: bye() print("aeren orz", quantum.FLAG) if __name__ == "__main__": try: main() except: bye()
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/CyberSpace/2024/misc/SKK/chall.py
ctfs/CyberSpace/2024/misc/SKK/chall.py
import numpy as np import cv2 import random from datetime import datetime img = cv2.imread('flag.png') size_x, size_y = img.shape[:2] enc_negpos = np.zeros_like(img) random.seed(datetime.now().timestamp()) for i in range(size_x): for j in range(size_y): for rgb in range(3): negpos = random.random() if negpos < 0.5: enc_negpos[i, j, rgb] = img[i, j, rgb] else: enc_negpos[i, j, rgb] = img[i, j, rgb] ^ 255 enc_shuffle = enc_negpos.copy() for i in range(size_x): for j in range(size_y): shuffle = random.randint(1, 6) if shuffle == 1: enc_shuffle[i, j] = enc_negpos[i, j] elif shuffle == 2: enc_shuffle[i, j] = enc_negpos[i, j][[0, 2, 1]] elif shuffle == 3: enc_shuffle[i, j] = enc_negpos[i, j][[1, 0, 2]] elif shuffle == 4: enc_shuffle[i, j] = enc_negpos[i, j][[1, 2, 0]] elif shuffle == 5: enc_shuffle[i, j] = enc_negpos[i, j][[2, 0, 1]] else: enc_shuffle[i, j] = enc_negpos[i, j][[2, 1, 0]] cv2.imwrite('enc.png', enc_shuffle)
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/CyberSpace/2024/rev/Stubborn_Pickle_Jar/stubborn-pickle-jar.py
ctfs/CyberSpace/2024/rev/Stubborn_Pickle_Jar/stubborn-pickle-jar.py
import pickle from io import BytesIO with open("chall.pkl", 'rb') as f: p = f.read() up = pickle.Unpickler(BytesIO(p)) result = up.load()
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/CyberSpace/2024/rev/Stubborn_Pickle_Jar/pickle.py
ctfs/CyberSpace/2024/rev/Stubborn_Pickle_Jar/pickle.py
# this is a clone of pickle.py. important... ...for reasons :) """Create portable serialized representations of Python objects. See module copyreg for a mechanism for registering custom picklers. See module pickletools source for extensive comments. Classes: Pickler Unpickler Functions: dump(object, file) dumps(object) -> string load(file) -> object loads(bytes) -> object Misc variables: __version__ format_version compatible_formats """ from types import FunctionType from copyreg import dispatch_table from copyreg import _extension_registry, _inverted_registry, _extension_cache from itertools import islice from functools import partial import sys from sys import maxsize from struct import pack, unpack import re import io import codecs import _compat_pickle __all__ = ["PickleError", "PicklingError", "UnpicklingError", "Pickler", "Unpickler", "dump", "dumps", "load", "loads"] try: from _pickle import PickleBuffer __all__.append("PickleBuffer") _HAVE_PICKLE_BUFFER = True except ImportError: _HAVE_PICKLE_BUFFER = False # Shortcut for use in isinstance testing bytes_types = (bytes, bytearray) # These are purely informational; no code uses these. format_version = "4.0" # File format version we write compatible_formats = ["1.0", # Original protocol 0 "1.1", # Protocol 0 with INST added "1.2", # Original protocol 1 "1.3", # Protocol 1 with BINFLOAT added "2.0", # Protocol 2 "3.0", # Protocol 3 "4.0", # Protocol 4 "5.0", # Protocol 5 ] # Old format versions we can read # This is the highest protocol number we know how to read. HIGHEST_PROTOCOL = 5 # The protocol we write by default. May be less than HIGHEST_PROTOCOL. # Only bump this if the oldest still supported version of Python already # includes it. DEFAULT_PROTOCOL = 4 class PickleError(Exception): """A common base class for the other pickling exceptions.""" pass class PicklingError(PickleError): """This exception is raised when an unpicklable object is passed to the dump() method. """ pass class UnpicklingError(PickleError): """This exception is raised when there is a problem unpickling an object, such as a security violation. Note that other exceptions may also be raised during unpickling, including (but not necessarily limited to) AttributeError, EOFError, ImportError, and IndexError. """ pass # An instance of _Stop is raised by Unpickler.load_stop() in response to # the STOP opcode, passing the object that is the result of unpickling. class _Stop(Exception): def __init__(self, value): self.value = value # Jython has PyStringMap; it's a dict subclass with string keys try: from org.python.core import PyStringMap except ImportError: PyStringMap = None # Pickle opcodes. See pickletools.py for extensive docs. The listing # here is in kind-of alphabetical order of 1-character pickle code. # pickletools groups them by purpose. MARK = b'(' # push special markobject on stack STOP = b'.' # every pickle ends with STOP POP = b'0' # discard topmost stack item POP_MARK = b'1' # discard stack top through topmost markobject DUP = b'2' # duplicate top stack item FLOAT = b'F' # push float object; decimal string argument INT = b'I' # push integer or bool; decimal string argument BININT = b'J' # push four-byte signed int BININT1 = b'K' # push 1-byte unsigned int LONG = b'L' # push long; decimal string argument BININT2 = b'M' # push 2-byte unsigned int NONE = b'N' # push None PERSID = b'P' # push persistent object; id is taken from string arg BINPERSID = b'Q' # " " " ; " " " " stack REDUCE = b'R' # apply callable to argtuple, both on stack STRING = b'S' # push string; NL-terminated string argument BINSTRING = b'T' # push string; counted binary string argument SHORT_BINSTRING= b'U' # " " ; " " " " < 256 bytes UNICODE = b'V' # push Unicode string; raw-unicode-escaped'd argument BINUNICODE = b'X' # " " " ; counted UTF-8 string argument APPEND = b'a' # append stack top to list below it BUILD = b'b' # call __setstate__ or __dict__.update() GLOBAL = b'c' # push self.find_class(modname, name); 2 string args DICT = b'd' # build a dict from stack items EMPTY_DICT = b'}' # push empty dict APPENDS = b'e' # extend list on stack by topmost stack slice GET = b'g' # push item from memo on stack; index is string arg BINGET = b'h' # " " " " " " ; " " 1-byte arg INST = b'i' # build & push class instance LONG_BINGET = b'j' # push item from memo on stack; index is 4-byte arg LIST = b'l' # build list from topmost stack items EMPTY_LIST = b']' # push empty list OBJ = b'o' # build & push class instance PUT = b'p' # store stack top in memo; index is string arg BINPUT = b'q' # " " " " " ; " " 1-byte arg LONG_BINPUT = b'r' # " " " " " ; " " 4-byte arg SETITEM = b's' # add key+value pair to dict TUPLE = b't' # build tuple from topmost stack items EMPTY_TUPLE = b')' # push empty tuple SETITEMS = b'u' # modify dict by adding topmost key+value pairs BINFLOAT = b'G' # push float; arg is 8-byte float encoding TRUE = b'I01\n' # not an opcode; see INT docs in pickletools.py FALSE = b'I00\n' # not an opcode; see INT docs in pickletools.py # Protocol 2 PROTO = b'\x80' # identify pickle protocol NEWOBJ = b'\x81' # build object by applying cls.__new__ to argtuple EXT1 = b'\x82' # push object from extension registry; 1-byte index EXT2 = b'\x83' # ditto, but 2-byte index EXT4 = b'\x84' # ditto, but 4-byte index TUPLE1 = b'\x85' # build 1-tuple from stack top TUPLE2 = b'\x86' # build 2-tuple from two topmost stack items TUPLE3 = b'\x87' # build 3-tuple from three topmost stack items NEWTRUE = b'\x88' # push True NEWFALSE = b'\x89' # push False LONG1 = b'\x8a' # push long from < 256 bytes LONG4 = b'\x8b' # push really big long _tuplesize2code = [EMPTY_TUPLE, TUPLE1, TUPLE2, TUPLE3] # Protocol 3 (Python 3.x) BINBYTES = b'B' # push bytes; counted binary string argument SHORT_BINBYTES = b'C' # " " ; " " " " < 256 bytes # Protocol 4 SHORT_BINUNICODE = b'\x8c' # push short string; UTF-8 length < 256 bytes BINUNICODE8 = b'\x8d' # push very long string BINBYTES8 = b'\x8e' # push very long bytes string EMPTY_SET = b'\x8f' # push empty set on the stack ADDITEMS = b'\x90' # modify set by adding topmost stack items FROZENSET = b'\x91' # build frozenset from topmost stack items NEWOBJ_EX = b'\x92' # like NEWOBJ but work with keyword only arguments STACK_GLOBAL = b'\x93' # same as GLOBAL but using names on the stacks MEMOIZE = b'\x94' # store top of the stack in memo FRAME = b'\x95' # indicate the beginning of a new frame # Protocol 5 BYTEARRAY8 = b'\x96' # push bytearray NEXT_BUFFER = b'\x97' # push next out-of-band buffer READONLY_BUFFER = b'\x98' # make top of stack readonly __all__.extend([x for x in dir() if re.match("[A-Z][A-Z0-9_]+$", x)]) class _Framer: _FRAME_SIZE_MIN = 4 _FRAME_SIZE_TARGET = 64 * 1024 def __init__(self, file_write): self.file_write = file_write self.current_frame = None def start_framing(self): self.current_frame = io.BytesIO() def end_framing(self): if self.current_frame and self.current_frame.tell() > 0: self.commit_frame(force=True) self.current_frame = None def commit_frame(self, force=False): if self.current_frame: f = self.current_frame if f.tell() >= self._FRAME_SIZE_TARGET or force: data = f.getbuffer() write = self.file_write if len(data) >= self._FRAME_SIZE_MIN: # Issue a single call to the write method of the underlying # file object for the frame opcode with the size of the # frame. The concatenation is expected to be less expensive # than issuing an additional call to write. write(FRAME + pack("<Q", len(data))) # Issue a separate call to write to append the frame # contents without concatenation to the above to avoid a # memory copy. write(data) # Start the new frame with a new io.BytesIO instance so that # the file object can have delayed access to the previous frame # contents via an unreleased memoryview of the previous # io.BytesIO instance. self.current_frame = io.BytesIO() def write(self, data): if self.current_frame: return self.current_frame.write(data) else: return self.file_write(data) def write_large_bytes(self, header, payload): write = self.file_write if self.current_frame: # Terminate the current frame and flush it to the file. self.commit_frame(force=True) # Perform direct write of the header and payload of the large binary # object. Be careful not to concatenate the header and the payload # prior to calling 'write' as we do not want to allocate a large # temporary bytes object. # We intentionally do not insert a protocol 4 frame opcode to make # it possible to optimize file.read calls in the loader. write(header) write(payload) class _Unframer: def __init__(self, file_read, file_readline, file_tell=None): self.file_read = file_read self.file_readline = file_readline self.current_frame = None def readinto(self, buf): if self.current_frame: n = self.current_frame.readinto(buf) if n == 0 and len(buf) != 0: self.current_frame = None n = len(buf) buf[:] = self.file_read(n) return n if n < len(buf): raise UnpicklingError( "pickle exhausted before end of frame") return n else: n = len(buf) buf[:] = self.file_read(n) return n def read(self, n): if self.current_frame: data = self.current_frame.read(n) if not data and n != 0: self.current_frame = None return self.file_read(n) if len(data) < n: raise UnpicklingError( "pickle exhausted before end of frame") return data else: return self.file_read(n) def readline(self): if self.current_frame: data = self.current_frame.readline() if not data: self.current_frame = None return self.file_readline() if data[-1] != b'\n'[0]: raise UnpicklingError( "pickle exhausted before end of frame") return data else: return self.file_readline() def load_frame(self, frame_size): if self.current_frame and self.current_frame.read() != b'': raise UnpicklingError( "beginning of a new frame before end of current frame") self.current_frame = io.BytesIO(self.file_read(frame_size)) # Tools used for pickling. def _getattribute(obj, name): for subpath in name.split('.'): if subpath == '<locals>': raise AttributeError("Can't get local attribute {!r} on {!r}" .format(name, obj)) try: parent = obj obj = getattr(obj, subpath) except AttributeError: raise AttributeError("Can't get attribute {!r} on {!r}" .format(name, obj)) from None return obj, parent def whichmodule(obj, name): """Find the module an object belong to.""" module_name = getattr(obj, '__module__', None) if module_name is not None: return module_name # Protect the iteration by using a list copy of sys.modules against dynamic # modules that trigger imports of other modules upon calls to getattr. for module_name, module in sys.modules.copy().items(): if (module_name == '__main__' or module_name == '__mp_main__' # bpo-42406 or module is None): continue try: if _getattribute(module, name)[0] is obj: return module_name except AttributeError: pass return '__main__' def encode_long(x): r"""Encode a long to a two's complement little-endian binary string. Note that 0 is a special case, returning an empty string, to save a byte in the LONG1 pickling context. >>> encode_long(0) b'' >>> encode_long(255) b'\xff\x00' >>> encode_long(32767) b'\xff\x7f' >>> encode_long(-256) b'\x00\xff' >>> encode_long(-32768) b'\x00\x80' >>> encode_long(-128) b'\x80' >>> encode_long(127) b'\x7f' >>> """ if x == 0: return b'' nbytes = (x.bit_length() >> 3) + 1 result = x.to_bytes(nbytes, byteorder='little', signed=True) if x < 0 and nbytes > 1: if result[-1] == 0xff and (result[-2] & 0x80) != 0: result = result[:-1] return result def decode_long(data): r"""Decode a long from a two's complement little-endian binary string. >>> decode_long(b'') 0 >>> decode_long(b"\xff\x00") 255 >>> decode_long(b"\xff\x7f") 32767 >>> decode_long(b"\x00\xff") -256 >>> decode_long(b"\x00\x80") -32768 >>> decode_long(b"\x80") -128 >>> decode_long(b"\x7f") 127 """ return int.from_bytes(data, byteorder='little', signed=True) # Pickling machinery class _Pickler: def __init__(self, file, protocol=None, *, fix_imports=True, buffer_callback=None): """This takes a binary file for writing a pickle data stream. The optional *protocol* argument tells the pickler to use the given protocol; supported protocols are 0, 1, 2, 3, 4 and 5. The default protocol is 4. It was introduced in Python 3.4, and is incompatible with previous versions. Specifying a negative protocol version selects the highest protocol version supported. The higher the protocol used, the more recent the version of Python needed to read the pickle produced. The *file* argument must have a write() method that accepts a single bytes argument. It can thus be a file object opened for binary writing, an io.BytesIO instance, or any other custom object that meets this interface. If *fix_imports* is True and *protocol* is less than 3, pickle will try to map the new Python 3 names to the old module names used in Python 2, so that the pickle data stream is readable with Python 2. If *buffer_callback* is None (the default), buffer views are serialized into *file* as part of the pickle stream. If *buffer_callback* is not None, then it can be called any number of times with a buffer view. If the callback returns a false value (such as None), the given buffer is out-of-band; otherwise the buffer is serialized in-band, i.e. inside the pickle stream. It is an error if *buffer_callback* is not None and *protocol* is None or smaller than 5. """ if protocol is None: protocol = DEFAULT_PROTOCOL if protocol < 0: protocol = HIGHEST_PROTOCOL elif not 0 <= protocol <= HIGHEST_PROTOCOL: raise ValueError("pickle protocol must be <= %d" % HIGHEST_PROTOCOL) if buffer_callback is not None and protocol < 5: raise ValueError("buffer_callback needs protocol >= 5") self._buffer_callback = buffer_callback try: self._file_write = file.write except AttributeError: raise TypeError("file must have a 'write' attribute") self.framer = _Framer(self._file_write) self.write = self.framer.write self._write_large_bytes = self.framer.write_large_bytes self.memo = {} self.proto = int(protocol) self.bin = protocol >= 1 self.fast = 0 self.fix_imports = fix_imports and protocol < 3 def clear_memo(self): """Clears the pickler's "memo". The memo is the data structure that remembers which objects the pickler has already seen, so that shared or recursive objects are pickled by reference and not by value. This method is useful when re-using picklers. """ self.memo.clear() def dump(self, obj): """Write a pickled representation of obj to the open file.""" # Check whether Pickler was initialized correctly. This is # only needed to mimic the behavior of _pickle.Pickler.dump(). if not hasattr(self, "_file_write"): raise PicklingError("Pickler.__init__() was not called by " "%s.__init__()" % (self.__class__.__name__,)) if self.proto >= 2: self.write(PROTO + pack("<B", self.proto)) if self.proto >= 4: self.framer.start_framing() self.save(obj) self.write(STOP) self.framer.end_framing() def memoize(self, obj): """Store an object in the memo.""" # The Pickler memo is a dictionary mapping object ids to 2-tuples # that contain the Unpickler memo key and the object being memoized. # The memo key is written to the pickle and will become # the key in the Unpickler's memo. The object is stored in the # Pickler memo so that transient objects are kept alive during # pickling. # The use of the Unpickler memo length as the memo key is just a # convention. The only requirement is that the memo values be unique. # But there appears no advantage to any other scheme, and this # scheme allows the Unpickler memo to be implemented as a plain (but # growable) array, indexed by memo key. if self.fast: return assert id(obj) not in self.memo idx = len(self.memo) self.write(self.put(idx)) self.memo[id(obj)] = idx, obj # Return a PUT (BINPUT, LONG_BINPUT) opcode string, with argument i. def put(self, idx): if self.proto >= 4: return MEMOIZE elif self.bin: if idx < 256: return BINPUT + pack("<B", idx) else: return LONG_BINPUT + pack("<I", idx) else: return PUT + repr(idx).encode("ascii") + b'\n' # Return a GET (BINGET, LONG_BINGET) opcode string, with argument i. def get(self, i): if self.bin: if i < 256: return BINGET + pack("<B", i) else: return LONG_BINGET + pack("<I", i) return GET + repr(i).encode("ascii") + b'\n' def save(self, obj, save_persistent_id=True): self.framer.commit_frame() # Check for persistent id (defined by a subclass) pid = self.persistent_id(obj) if pid is not None and save_persistent_id: self.save_pers(pid) return # Check the memo x = self.memo.get(id(obj)) if x is not None: self.write(self.get(x[0])) return rv = NotImplemented reduce = getattr(self, "reducer_override", None) if reduce is not None: rv = reduce(obj) if rv is NotImplemented: # Check the type dispatch table t = type(obj) f = self.dispatch.get(t) if f is not None: f(self, obj) # Call unbound method with explicit self return # Check private dispatch table if any, or else # copyreg.dispatch_table reduce = getattr(self, 'dispatch_table', dispatch_table).get(t) if reduce is not None: rv = reduce(obj) else: # Check for a class with a custom metaclass; treat as regular # class if issubclass(t, type): self.save_global(obj) return # Check for a __reduce_ex__ method, fall back to __reduce__ reduce = getattr(obj, "__reduce_ex__", None) if reduce is not None: rv = reduce(self.proto) else: reduce = getattr(obj, "__reduce__", None) if reduce is not None: rv = reduce() else: raise PicklingError("Can't pickle %r object: %r" % (t.__name__, obj)) # Check for string returned by reduce(), meaning "save as global" if isinstance(rv, str): self.save_global(obj, rv) return # Assert that reduce() returned a tuple if not isinstance(rv, tuple): raise PicklingError("%s must return string or tuple" % reduce) # Assert that it returned an appropriately sized tuple l = len(rv) if not (2 <= l <= 6): raise PicklingError("Tuple returned by %s must have " "two to six elements" % reduce) # Save the reduce() output and finally memoize the object self.save_reduce(obj=obj, *rv) def persistent_id(self, obj): # This exists so a subclass can override it return None def save_pers(self, pid): # Save a persistent id reference if self.bin: self.save(pid, save_persistent_id=False) self.write(BINPERSID) else: try: self.write(PERSID + str(pid).encode("ascii") + b'\n') except UnicodeEncodeError: raise PicklingError( "persistent IDs in protocol 0 must be ASCII strings") def save_reduce(self, func, args, state=None, listitems=None, dictitems=None, state_setter=None, obj=None): # This API is called by some subclasses if not isinstance(args, tuple): raise PicklingError("args from save_reduce() must be a tuple") if not callable(func): raise PicklingError("func from save_reduce() must be callable") save = self.save write = self.write func_name = getattr(func, "__name__", "") if self.proto >= 2 and func_name == "__newobj_ex__": cls, args, kwargs = args if not hasattr(cls, "__new__"): raise PicklingError("args[0] from {} args has no __new__" .format(func_name)) if obj is not None and cls is not obj.__class__: raise PicklingError("args[0] from {} args has the wrong class" .format(func_name)) if self.proto >= 4: save(cls) save(args) save(kwargs) write(NEWOBJ_EX) else: func = partial(cls.__new__, cls, *args, **kwargs) save(func) save(()) write(REDUCE) elif self.proto >= 2 and func_name == "__newobj__": # A __reduce__ implementation can direct protocol 2 or newer to # use the more efficient NEWOBJ opcode, while still # allowing protocol 0 and 1 to work normally. For this to # work, the function returned by __reduce__ should be # called __newobj__, and its first argument should be a # class. The implementation for __newobj__ # should be as follows, although pickle has no way to # verify this: # # def __newobj__(cls, *args): # return cls.__new__(cls, *args) # # Protocols 0 and 1 will pickle a reference to __newobj__, # while protocol 2 (and above) will pickle a reference to # cls, the remaining args tuple, and the NEWOBJ code, # which calls cls.__new__(cls, *args) at unpickling time # (see load_newobj below). If __reduce__ returns a # three-tuple, the state from the third tuple item will be # pickled regardless of the protocol, calling __setstate__ # at unpickling time (see load_build below). # # Note that no standard __newobj__ implementation exists; # you have to provide your own. This is to enforce # compatibility with Python 2.2 (pickles written using # protocol 0 or 1 in Python 2.3 should be unpicklable by # Python 2.2). cls = args[0] if not hasattr(cls, "__new__"): raise PicklingError( "args[0] from __newobj__ args has no __new__") if obj is not None and cls is not obj.__class__: raise PicklingError( "args[0] from __newobj__ args has the wrong class") args = args[1:] save(cls) save(args) write(NEWOBJ) else: save(func) save(args) write(REDUCE) if obj is not None: # If the object is already in the memo, this means it is # recursive. In this case, throw away everything we put on the # stack, and fetch the object back from the memo. if id(obj) in self.memo: write(POP + self.get(self.memo[id(obj)][0])) else: self.memoize(obj) # More new special cases (that work with older protocols as # well): when __reduce__ returns a tuple with 4 or 5 items, # the 4th and 5th item should be iterators that provide list # items and dict items (as (key, value) tuples), or None. if listitems is not None: self._batch_appends(listitems) if dictitems is not None: self._batch_setitems(dictitems) if state is not None: if state_setter is None: save(state) write(BUILD) else: # If a state_setter is specified, call it instead of load_build # to update obj's with its previous state. # First, push state_setter and its tuple of expected arguments # (obj, state) onto the stack. save(state_setter) save(obj) # simple BINGET opcode as obj is already memoized. save(state) write(TUPLE2) # Trigger a state_setter(obj, state) function call. write(REDUCE) # The purpose of state_setter is to carry-out an # inplace modification of obj. We do not care about what the # method might return, so its output is eventually removed from # the stack. write(POP) # Methods below this point are dispatched through the dispatch table dispatch = {} def save_none(self, obj): self.write(NONE) dispatch[type(None)] = save_none def save_bool(self, obj): if self.proto >= 2: self.write(NEWTRUE if obj else NEWFALSE) else: self.write(TRUE if obj else FALSE) dispatch[bool] = save_bool def save_long(self, obj): if self.bin: # If the int is small enough to fit in a signed 4-byte 2's-comp # format, we can store it more efficiently than the general # case. # First one- and two-byte unsigned ints: if obj >= 0: if obj <= 0xff: self.write(BININT1 + pack("<B", obj)) return if obj <= 0xffff: self.write(BININT2 + pack("<H", obj)) return # Next check for 4-byte signed ints: if -0x80000000 <= obj <= 0x7fffffff: self.write(BININT + pack("<i", obj)) return if self.proto >= 2: encoded = encode_long(obj) n = len(encoded) if n < 256: self.write(LONG1 + pack("<B", n) + encoded) else: self.write(LONG4 + pack("<i", n) + encoded) return if -0x80000000 <= obj <= 0x7fffffff: self.write(INT + repr(obj).encode("ascii") + b'\n') else: self.write(LONG + repr(obj).encode("ascii") + b'L\n') dispatch[int] = save_long def save_float(self, obj): if self.bin: self.write(BINFLOAT + pack('>d', obj)) else: self.write(FLOAT + repr(obj).encode("ascii") + b'\n') dispatch[float] = save_float def save_bytes(self, obj): if self.proto < 3: if not obj: # bytes object is empty self.save_reduce(bytes, (), obj=obj) else: self.save_reduce(codecs.encode, (str(obj, 'latin1'), 'latin1'), obj=obj) return n = len(obj) if n <= 0xff: self.write(SHORT_BINBYTES + pack("<B", n) + obj) elif n > 0xffffffff and self.proto >= 4: self._write_large_bytes(BINBYTES8 + pack("<Q", n), obj) elif n >= self.framer._FRAME_SIZE_TARGET: self._write_large_bytes(BINBYTES + pack("<I", n), obj) else: self.write(BINBYTES + pack("<I", n) + obj) self.memoize(obj) dispatch[bytes] = save_bytes def save_bytearray(self, obj): if self.proto < 5: if not obj: # bytearray is empty self.save_reduce(bytearray, (), obj=obj) else: self.save_reduce(bytearray, (bytes(obj),), obj=obj) return n = len(obj) if n >= self.framer._FRAME_SIZE_TARGET: self._write_large_bytes(BYTEARRAY8 + pack("<Q", n), obj) else: self.write(BYTEARRAY8 + pack("<Q", n) + obj) dispatch[bytearray] = save_bytearray if _HAVE_PICKLE_BUFFER: def save_picklebuffer(self, obj): if self.proto < 5: raise PicklingError("PickleBuffer can only pickled with " "protocol >= 5") with obj.raw() as m: if not m.contiguous: raise PicklingError("PickleBuffer can not be pickled when " "pointing to a non-contiguous buffer") in_band = True if self._buffer_callback is not None: in_band = bool(self._buffer_callback(obj)) if in_band: # Write data in-band # XXX The C implementation avoids a copy here if m.readonly: self.save_bytes(m.tobytes()) else: self.save_bytearray(m.tobytes()) else: # Write data out-of-band self.write(NEXT_BUFFER) if m.readonly: self.write(READONLY_BUFFER) dispatch[PickleBuffer] = save_picklebuffer def save_str(self, obj): if self.bin: encoded = obj.encode('utf-8', 'surrogatepass') n = len(encoded) if n <= 0xff and self.proto >= 4: self.write(SHORT_BINUNICODE + pack("<B", n) + encoded)
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
true
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/CyberSpace/2024/jail/Swimming_to_Escape/fish.py
ctfs/CyberSpace/2024/jail/Swimming_to_Escape/fish.py
#!/usr/local/bin/python3.2 """ Python interpreter for the esoteric language ><> (pronounced /ˈfɪʃ/). Usage: ./fish.py --help More information: http://esolangs.org/wiki/Fish Requires python 2.7/3.2 or higher. """ import sys import time import random from collections import defaultdict # constants NCHARS = "0123456789abcdef" ARITHMETIC = "+-*%" # not division, as it requires special handling COMPARISON = { "=": "==", "(": "<", ")": ">" } DIRECTIONS = { ">": (1,0), "<": (-1,0), "v": (0,1), "^": (0,-1) } MIRRORS = { "/": lambda x,y: (-y, -x), "\\": lambda x,y: (y, x), "|": lambda x,y: (-x, y), "_": lambda x,y: (x, -y), "#": lambda x,y: (-x, -y) } class _Getch: """ Provide cross-platform getch functionality. Shamelessly stolen from http://code.activestate.com/recipes/134892/ """ def __init__(self): try: self._impl = _GetchWindows() except ImportError: self._impl = _GetchUnix() def __call__(self): return self._impl() class _GetchUnix: def __init__(self): import tty, sys def __call__(self): import sys, tty, termios fd = sys.stdin.fileno() old_settings = termios.tcgetattr(fd) try: tty.setraw(sys.stdin.fileno()) ch = sys.stdin.read(1) finally: termios.tcsetattr(fd, termios.TCSADRAIN, old_settings) return ch class _GetchWindows: def __init__(self): import msvcrt def __call__(self): import msvcrt return msvcrt.getch() getch = _Getch() def read_character(): """Read one character from stdin. Returns -1 when no input is available.""" if sys.stdin.isatty(): # we're in console, read a character from the user char = getch() # check for ctrl-c (break) if ord(char) == 3: sys.stdout.write("^C") sys.stdout.flush() raise KeyboardInterrupt else: return char else: # input is redirected using pipes char = sys.stdin.read(1) # return -1 if there is no more input available return char if char != "" else -1 class Interpreter: """ ><> "compiler" and interpreter. """ def __init__(self, code): """ Initialize a new interpreter. Arguments: code -- the code to execute as a string """ # check for hashbang in first line lines = code.split("\n") if lines[0][:2] == "#!": code = "\n".join(lines[1:]) # construct a 2D defaultdict to contain the code self._codebox = defaultdict(lambda: defaultdict(int)) line_n = char_n = 0 for char in code: if char != "\n": self._codebox[line_n][char_n] = 0 if char == " " else ord(char) char_n += 1 else: char_n = 0 line_n += 1 self._position = [-1,0] self._direction = DIRECTIONS[">"] # the register is initially empty self._register_stack = [None] # string mode is initially disabled self._string_mode = None # have we encountered a skip instruction? self._skip = False self._stack = [] self._stack_stack = [self._stack] # is the last outputted character a newline? self._newline = None def move(self): """ Move one step in the execution process, and handle the instruction (if any) at the new position. """ # move one step in the current direction self._position[0] += self._direction[0] self._position[1] += self._direction[1] # wrap around if we reach the borders of the codebox if self._position[1] > max(self._codebox.keys()): # if the current position is beyond the number of lines, wrap to # the top self._position[1] = 0 elif self._position[1] < 0: # if we're above the top, move to the bottom self._position[1] = max(self._codebox.keys()) if self._direction[0] == 1 and self._position[0] > max(self._codebox[self._position[1]].keys()): # wrap to the beginning if we are beyond the last character on a # line and moving rightwards self._position[0] = 0; elif self._position[0] < 0: # also wrap if we reach the left hand side self._position[0] = max(self._codebox[self._position[1]].keys()) # execute the instruction found if not self._skip: instruction = int(self._codebox[self._position[1]][self._position[0]]) # the current position might not be a valid character try: # use space if current cell is 0 instruction = chr(instruction) if instruction > 0 else " " except: instruction = None try: self._handle_instruction(instruction) except StopExecution: raise except KeyboardInterrupt: # avoid catching as error raise KeyboardInterrupt except Exception as e: raise StopExecution("something smells fishy...") return instruction self._skip = False def _handle_instruction(self, instruction): """ Execute an instruction. """ if instruction == None: # error on invalid characters raise Exception # handle string mode if self._string_mode != None and self._string_mode != instruction: self._push(ord(instruction)) return elif self._string_mode == instruction: self._string_mode = None return # instruction is one of ^v><, change direction if instruction in DIRECTIONS: self._direction = DIRECTIONS[instruction] # direction is a mirror, get new direction elif instruction in MIRRORS: self._direction = MIRRORS[instruction](*self._direction) # pick a random direction elif instruction == "x": self._direction = random.choice(list(DIRECTIONS.items()))[1] # portal; move IP to coordinates elif instruction == ".": y, x = self._pop(), self._pop() # IP cannot reach negative codebox if x < 0 or y < 0: raise Exception self._position = [x,y] # instruction is 0-9a-f, push corresponding hex value elif instruction in NCHARS: self._push(int(instruction, len(NCHARS))) # instruction is an arithmetic operator elif instruction in ARITHMETIC: a, b = self._pop(), self._pop() exec("self._push(b{}a)".format(instruction)) # division elif instruction == ",": a, b = self._pop(), self._pop() # try converting them to floats for python 2 compability try: a, b = float(a), float(b) except OverflowError: pass self._push(b/a) # comparison operators elif instruction in COMPARISON: a, b = self._pop(), self._pop() exec("self._push(1 if b{}a else 0)".format(COMPARISON[instruction])) # turn on string mode elif instruction in "'\"": # turn on string parsing self._string_mode = instruction # skip one command elif instruction == "!": self._skip = True # skip one command if popped value is 0 elif instruction == "?": if not self._pop(): self._skip = True # push length of stack elif instruction == "l": self._push(len(self._stack)) # duplicate top of stack elif instruction == ":": self._push(self._stack[-1]) # remove top of stack elif instruction == "~": self._pop() # swap top two values elif instruction == "$": a, b = self._pop(), self._pop() self._push(a) self._push(b) # swap top three values elif instruction == "@": a, b, c = self._pop(), self._pop(), self._pop() self._push(a) self._push(c) self._push(b) # put/get register elif instruction == "&": if self._register_stack[-1] == None: self._register_stack[-1] = self._pop() else: self._push(self._register_stack[-1]) self._register_stack[-1] = None # reverse stack elif instruction == "r": self._stack.reverse() # right-shift stack elif instruction == "}": self._push(self._pop(), index=0) # left-shift stack elif instruction == "{": self._push(self._pop(index=0)) # get value in codebox elif instruction == "g": x, y = self._pop(), self._pop() self._push(self._codebox[x][y]) # set (put) value in codebox elif instruction == "p": x, y, z = self._pop(), self._pop(), self._pop() self._codebox[x][y] = z # pop and output as character elif instruction == "o": self._output(chr(int(self._pop()))) # pop and output as number elif instruction == "n": n = self._pop() # try outputting without the decimal point if possible self._output(int(n) if int(n) == n else n) # get one character from input and push it elif instruction == "i": i = self._input() self._push(ord(i) if isinstance(i, str) else i) # pop x and create a new stack with x members moved from the old stack elif instruction == "[": count = int(self._pop()) if count == 0: self._stack_stack[-1], new_stack = self._stack, [] else: self._stack_stack[-1], new_stack = self._stack[:-count], self._stack[-count:] self._stack_stack.append(new_stack) self._stack = new_stack # create a new register for this stack self._register_stack.append(None) # remove current stack, moving its members to the previous stack. # if this is the last stack, a new, empty stack is pushed elif instruction == "]": old_stack = self._stack_stack.pop() if not len(self._stack_stack): self._stack_stack.append([]) else: self._stack_stack[-1] += old_stack self._stack = self._stack_stack[-1] # register is dropped self._register_stack.pop() if not len(self._register_stack): self._register_stack.append(None) # the end elif instruction == ";": raise StopExecution() # space is NOP elif instruction == " ": pass # invalid instruction else: raise Exception("Invalid instruction", instruction) def _push(self, value, index=None): """ Push a value to the current stack. Keyword arguments: index -- the index to push/insert to. (default: end of stack) """ self._stack.insert(len(self._stack) if index == None else index, value) def _pop(self, index=None): """ Pop and return a value from the current stack. Keyword arguments: index -- the index to pop from (default: end of stack) """ # don't care about exceptions - they are handled at a higher level value = self._stack.pop(len(self._stack)-1 if index == None else index) # convert to int where possible to avoid float overflow if value == int(value): value = int(value) return value def _input(self): """ Return an inputted character. """ return read_character() def _output(self, output): """ Output a string without a newline appended. """ output = str(output) self._newline = output.endswith("\n") sys.stdout.write(output) sys.stdout.flush() class StopExecution(Exception): """ Exception raised when a script has finished execution. """ def __init__(self, message=None): self.message = message if __name__ == "__main__": import argparse parser = argparse.ArgumentParser(description=""" Execute a ><> script. Executing a script is as easy as: %(prog)s <script file> You can also execute code directly using the -c/--code flag: %(prog)s -c '1n23nn;' > 132 The -v and -s flags can be used to prepopulate the stack: %(prog)s echo.fish -s "hello, world" -v 32 49 50 51 -s "456" > hello, world 123456""", usage="""%(prog)s [-h] (<script file> | -c <code>) [<options>]""", formatter_class=argparse.RawDescriptionHelpFormatter) group = parser.add_argument_group("code") # group script file and --code together to only allow one code_group = group.add_mutually_exclusive_group(required=True) code_group.add_argument("script", type=argparse.FileType("r"), nargs="?", help=".fish file to execute") code_group.add_argument("-c", "--code", metavar="<code>", help="string of instructions to execute") options = parser.add_argument_group("options") options.add_argument("-s", "--string", action="append", metavar="<string>", dest="stack") options.add_argument("-v", "--value", type=float, nargs="+", action="append", metavar="<number>", dest="stack", help="push numbers or strings onto the stack before execution starts") options.add_argument("-t", "--tick", type=float, default=0.0, metavar="<seconds>", help="define a tick time, or a delay between the execution of each instruction") options.add_argument("-a", "--always-tick", action="store_true", default=False, dest="always_tick", help="make every instruction cause a tick (delay), even whitespace and skipped instructions") # parse arguments from sys.argv arguments = parser.parse_args() # initialize an interpreter if arguments.script: code = arguments.script.read() arguments.script.close() else: code = arguments.code interpreter = Interpreter(code) # add supplied values to the interpreters stack if arguments.stack: for x in arguments.stack: if isinstance(x, str): interpreter._stack += [float(ord(c)) for c in x] else: interpreter._stack += x # run the script try: while True: try: instr = interpreter.move() except StopExecution as stop: # only print a newline if the script didn't newline = ("\n" if (not interpreter._newline) and interpreter._newline != None else "") parser.exit(message=(newline+stop.message+"\n") if stop.message else newline) if instr and not instr == " " or arguments.always_tick: time.sleep(arguments.tick) except KeyboardInterrupt: # exit cleanly parser.exit(message="\n")
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/CyberSpace/2024/jail/Swimming_to_Escape/server.py
ctfs/CyberSpace/2024/jail/Swimming_to_Escape/server.py
from fish import Interpreter, StopExecution FLAG = open('flag.txt').read().strip() whitelist = r' +-*,%><^v~:&!?=()01\'/|_#l$@r{};"' if __name__ == '__main__': while True: print('Please input your code:') code = input() assert len(code) <= 26 assert all([c in whitelist for c in code]) code = code + 'n;;;\n' + ';' * 30 interpreter = Interpreter(code) interpreter._stack = [ord(c) for c in FLAG] count = 0 while True: try: instr = interpreter.move() count += 1 except: break if count >= 5000: print('Too many moves!!') break print()
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/CyberSpace/2024/crypto/cipher_block_clock/chall.py
ctfs/CyberSpace/2024/crypto/cipher_block_clock/chall.py
import Crypto.Cipher.AES import Crypto.Random import Crypto.Util.Padding f = b"CSCTF{placeholder}" k = Crypto.Random.get_random_bytes(16) def enc(pt): iv = Crypto.Random.get_random_bytes(32) ct = Crypto.Cipher.AES.new(iv, Crypto.Cipher.AES.MODE_CBC, k) return iv.hex(), ct.encrypt(Crypto.Util.Padding.pad(pt, 32)).hex() iv0, ct0 = enc(f) iv1, ct1 = enc(b"Lookie here, someone thinks that this message is unsafe, well I'm sorry to be the bearer of bad news but tough luck; the ciphertext is encrypted with MILITARY grade encryption. You're done kiddo.") print(f"iv0: {iv0}\nct0: {ct0}\n") print(f"iv1: {iv1}\nct1: {ct1}")
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/CyberSpace/2024/crypto/Mask_RSA/chall.py
ctfs/CyberSpace/2024/crypto/Mask_RSA/chall.py
from Crypto.Util.number import getPrime, bytes_to_long FLAG = open('flag.txt', 'rb').read().strip() def mask_expr(expr): global e, n assert '**' not in expr, "My computer is weak, I can't handle this insane calculation" assert len(expr) <= 4, "Too long!" assert all([c in r'pq+-*/%' for c in expr]), "Don't try to break me" res = eval(expr) return str(pow(res, e, n))[::2] if __name__ == '__main__': e = 3 p, q = 1, 1 while p == q: while (p-1) % e == 0: p = getPrime(513) while (q-1) % e == 0: q = getPrime(513) m = bytes_to_long(FLAG) n = p * q c = pow(m, e, n) print(f'{c = }') for _ in range(20): expr = input('Input your expression in terms of p, q and r: ') print(mask_expr(expr))
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/CyberSpace/2024/crypto/super_fnv/chall.py
ctfs/CyberSpace/2024/crypto/super_fnv/chall.py
from pwn import xor from random import randint from hashlib import sha256 from FLAG import flag cc = [randint(-2**67, 2**67) for _ in range(9)] key = sha256("".join(str(i) for i in cc).encode()).digest() enc = xor(key, flag) def superfnv(): x = 2093485720398457109348571098457098347250982735 k = 1023847102938470123847102938470198347092184702 for c in cc: x = k * (x + c) return x % 2**600 print(f"{enc.hex() = }") print(f"{superfnv() = }") # enc.hex() = '4ba8d3d47b0d72c05004ffd937e85408149e13d13629cd00d5bf6f4cb62cf4ca399ea9e20e4227935c08f3d567bc00091f9b15d53e7bca549a' # superfnv() = 2957389613700331996448340985096297715468636843830320883588385773066604991028024933733915453111620652760300119808279193798449958850518105887385562556980710950886428083819728334367280
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/CyberSpace/2024/crypto/ezcoppersmith/chall.py
ctfs/CyberSpace/2024/crypto/ezcoppersmith/chall.py
import os from Crypto.Util.number import bytes_to_long, getPrime from random import getrandbits from sympy import nextprime flag = os.urandom(70)+b"CSCTF{fake_flag}"+os.urandom(70) flag = bytes_to_long(flag) e = 0x10001 p = getPrime(1024) q = nextprime(p+getrandbits(512)) n = p*q ct = pow(flag,e,n) print(f"{n = }") print(f"{ct = }") """ n = 18644771606497209714095542646224677588981048892455227811334258151262006531336794833359381822210403450387218291341636672728427659163488688386134401896278003165147721355406911673373424263190196921309228396204979060454870860816745503197616145647490864293442635906688253552867657780735555566444060335096583505652012496707636862307239874297179019995999007369981828074059533709513179171859521707075639202212109180625048226522596633441264313917276824985895380863669296036099693167611788521865367087640318827068580965890143181999375133385843774794990578010917043490614806222432751894223475655601237073207615381387441958773717 ct = 814602066169451977605898206043894866509050772237095352345693280423339237890197181768582210420699418615050495985283410604981870683596059562903004295804358339676736292824636301426917335460641348021235478618173522948941541432284037580201234570619769478956374067742134884689871240482950578532380612988605675957629342412670503628580284821612200740753343166428553552463950037371300722459849775674636165297063660872395712545246380895584677099483139705934844856029861773030472761407204967590283582345034506802227442338228782131928742229041926847011673393223237610854842559028007551817527116991453411203276872464110797091619 """
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/CyberSpace/2024/crypto/Modulus_RSA/chall.py
ctfs/CyberSpace/2024/crypto/Modulus_RSA/chall.py
from Crypto.Util.number import bytes_to_long from sympy import randprime m = bytes_to_long(b'CSCTF{fake_flag}') p, q, r = sorted([randprime(0, 1<<128) for _ in range(3)]) n = p * q * r e = 65537 c = pow(m, e, n) w, x, y = q % p, r % p, r % q print(f'{w = }') print(f'{x = }') print(f'{y = }') print(f'{c = }') """ w = 115017953136750842312826274882950615840 x = 16700949197226085826583888467555942943 y = 20681722155136911131278141581010571320 c = 2246028367836066762231325616808997113924108877001369440213213182152044731534905739635043920048066680458409222434813 """
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/CyberSpace/2024/crypto/flagprinter/chall.py
ctfs/CyberSpace/2024/crypto/flagprinter/chall.py
from out import enc, R from math import prod flag = '' a = [0] for i in range(355): b = [_+1 for _ in a] c = [_+1 for _ in b] a += b + c if i%5 == 0: flag += chr(enc[i//5] ^ prod([a[_] for _ in R[i//5]])) print(flag)
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/CyberSpace/2024/crypto/flagprinter/out.py
ctfs/CyberSpace/2024/crypto/flagprinter/out.py
enc = [65, 331, 1783, 6186, 6470, 17283, 25622, 49328, 75517, 80689, 148293, 164737, 256906, 285586, 529890, 453524, 486833, 612780, 995834, 1034513, 1164566, 1187257, 1195463, 1481795, 1456512, 2255447, 1918038, 2402807, 3279260, 2958036, 2881150, 3263588, 3820625, 4237730, 5185459, 5233235, 6049254, 6786968, 6183125, 8612625, 8897839, 8945969, 8548390, 9936098, 9754219, 10421226, 12312594, 13139249, 13528562, 13806877, 14378265, 14232673, 17206117, 17924517, 19586568, 21397250, 22214087, 25159893, 25280690, 27657640, 29296934, 29729604, 28262064, 32050040, 32629604, 33546289, 38222149, 38457097, 34401800, 39471481, 41751527] R = [[1, 1, 2], [573, 229, 206], [10885, 41497, 160304], [8839119, 14295644, 29685237], [10280936393, 8467023078, 4707689596], [945960776097, 1031182232283, 69972907378], [137665703218004, 35525403452985, 138350929229224], [122336169683982108, 59224551586149213, 118549674466202725], [13626900512752906569, 3897136862695780183, 35076404995397046345], [163593922657921448706, 2585968319357630198594, 6996211172572711470196], [1433471461923638870900801, 327749274075770619032029, 392888374649818189286143], [19744782485775287314957049, 460634978666194064781998391, 31659469833364582430102473], [6307006601660265171992374053, 98623451654268880809155078560, 64233892285570757739641890442], [29154577259006185142961063158052, 9914420641115443182131036644284, 7279481296300468961689254189816], [1558076296273259698341440069238056, 4310691260512125134140007179935352, 4980109395532057935132560488460615], [1405212213206399714548754108042831062, 147404700816591482365933597995505421, 1687342229905046884455484428290534831], [178231026292428921004703562165525411894, 412963066680488665482944489625497608212, 70340936836695689283893473181751382743], [56698349585950537262338505181144336979587, 52217406711284315435595033610018391654195, 62108893391408870656968514251159189194521], [23893381410382084563262913681592457710903753, 22212431596810321024205206524427117951881276, 19989366146226118433589584982546380299442529], [2889511959527885324209305298200285677701094725, 2606035783027360737177505608659564857175468342, 912571494124990709836860172316232544276438933], [1228504793022169504797984188122406171358072857562, 1363360236293969893605831020276765744813251042404, 297563475302044806097863947023814157856389926467], [175608219147292209879121072264875458914106479644056, 315961037093380016583816358395509380577071641993080, 239337133002097856335802829217431187967280790555618], [86907177537979343798282102958682278554281933300161219, 64317934619982444261646548589166853140812442454915939, 88018844277704099677399755876858185474535387410720445], [7578403250388931197644961338635760720785818764109837460, 3274632430417597288151262115132742324278216710102859849, 21631882539927419463654991077819010737499996516834371896], [1784005907786440158922591109117656913793076162623216189690, 584544132694337139275683959718819628005872667061541957378, 468567183178097211759022580480616535344925394592430209347], [729938520575815549919101929342052441361022063727469070145908, 274550060366659698888268478648666070589265337265466015158929, 816678505785021313430715270084566186204139128920927645737535], [106419295808981221951748024239581079670028738895932201279327601, 228539844398841595052385901358010923608064510380402434702609661, 273988143389250335223734499597874248431371549060210491714569562], [49610527461979411507467246924089752425201348016881391697347424513, 69137173214147289942692162771140621271832934031257876965711710949, 62730418740220882006739225333147856993853932330719923493210890436], [16851730736657444946446580883690706974734423996859949550565127900099, 17020082067082804201146138962045534353417049142267440365496556106646, 8425831360975428058545914350645398599666494245768262308563962500419], [1744457135330206658118333956018617505833961797560206981881297005844650, 2488272677039458908993320500395188112777156174503950549584903141127805, 2025261799014127885373424699982740002932128127330675129998065148842076], [911346406564292964244181957884281723110968676471292861562401898225344617, 515016108655135831997810719937894761768485489577746685305628286718842981, 529790162728531781327256209611140765345349305272432962612449845910133431], [188862868604458670709430534588424053453382627459433615665235632604774195105, 159265669796915366090971144664529549841435257409990033156402470728739515566, 60682317875971312140589380343235690226249919927211583007002668602340443573], [55193706264542603342210130740272648982338137150197933176657775220529084548357, 27195911554042477052963544743968295593780567038751440659821492286699921720191, 29560858927273910749887729332550032054935265811253142815881982028400038247319], [7967504222642156771288173955589952284643390129548188481154174503319661178503072, 1359513209197691298598578835648210368417270153147787219079370527092612752268982, 9230224122977955411941024673666600930203300543850914931726268334960580194164492], [831700796347413410615911772707996893565701575245034815476696517314277469580570895, 348270496636109272924978536225447046371768965881221748966431208037510608509018947, 1374142394998218750798266411208358766099463968207325565770298390782412190916814310], [728134218644001393441390399108789642515528723649320724369274506318570415182986524315, 742827622102241979512100045719273776927502266118292292534558855112165931221386202274, 834896424809769450256618602072325069420072099322355588900296733100469513421816291082], [66657521960797189904538245565000331457185183590890330549573802546986185313721475396700, 156009195280892389693769014846212616019395180017555815307430719390512302340174696802961, 200597453219232827796159650057256671048223063579900089130489322256618558160451930790328], [29037802387828000295889248231258384842641658132563570380131111284295279711886813738722877, 19026977082052219356279509080995574655135318523161839766669049352934239566123435130632269, 39761369983488555876764613607529231297124885693027657193256415982138011913990538842193676], [12561577796321365976754879894302013598558663721653793677134296816829605195336351648166256979, 12838267657320533157115690870383947765475624026880560207257146094964304690365021016825129853, 7495910847481301240802133743653617325920902801350946983901641264085048246865582593139729403], [3041492422855245745694700380550203206979029337703391421024168530121179356261997345191319516771, 640848136862288646629516649150957018999642176847724807173173190110594937936496769080786522049, 2969396567186077593954887271522825649221970125735131131175295619859668697895377679704620087889], [81093296695439965954342113512388849103885378349927499243812089963712022532857570393423108003659, 207270172491583465284894346681199376583340220798632240230546015429407709634891762897301883017884, 190032100106748542252716447896640624640777006597630648586475349805342010386746524668165629317161], [32533344401268273967114633758559931826617665158198522614215035245432490850547861982523840145942074, 63037110804852476247528611221542679314242047661614004564491126914186621243875589339803531182020426, 124951290010810803694525061731704200016278732642269550252996419375511248225453431694350800495944347], [35137716753067452090927097050636563619547995454738820278063768022488025199701346321134314448841872794, 12985633921598678956642044617726801111706054490973834029123104709195008027204480882797267867341064476, 5305727297771409651023243066103178878140492848258919185568928165081859031657272186995329239806104118], [3762249421419366884537098419354305781080227852906891797970952858114351664324268703722577235910347584304, 1550561491002149215075653857319603880429910437941882645815693111090526036411984733619993307966461840126, 9381201201142531265853888435902828303237464579889417263110360168656884858562872253087408205544357087306], [2056899273710648314295675026370994461871817025547273056051947505619792320735406178540815338367649803736698, 2400734502375026278495337239471134511733068748104902082380177269089395799760690047001894688755690156943965, 1732882327457919111959549262162185466220677456316057330624797413276486794416719248300528086966180252303114], [652896416106612920827629685957065255447694536466438605951176120897225559332173369105354682171886992371096271, 454656456599989954897128567415348109820116193092249211381080865675729251399216425900943035094745504751551478, 313462687528796654990235524389154265472701132978608107344549946439400139763799796696708655697709590458851693], [104545083165292290401534689701271365665130721684233823742393188465642248906869971808131422905737188031748198141, 143435659999076222337918882839514881215221734734388221592284254721485478080813955224165205293052195097128579855, 40702920019369144545229507759809584949672965917473112280581406604369595519129367208280022299388654288711154666], [38503581328033455359533847919966468672140392024444493807653196910126532016690751491942280634907485938880904383892, 18884661042488142899588244068961327261179761242819343293800084248732455991582145396596568605394801002264811582913, 9384187667567328792366639242333135973520260966794149958963790153859412473452108461030094493051859371952206600103], [1324740544139254318273253770332855107671134390702432855738006366746449029576545099512912405134518891320718185169513, 303109855383738809002288742946345379428808745080383659457773592835713207285305179350437080179436990935112214270665, 1624316398491836088831202617387140081826145335528105327252325808416312557534737052667304856958627845436851248489907], [1401688155035324575988216421089538478215416341501120197948850057036940982809195355604792139051606198616259749003767965, 2048526767570983439518103534423786218930891544461790174537795037321458400711335285803377717794909411012955744133476255, 1762727028524336180955903313027800157402368747053245589279568985101199159336178410704769284913872366668626620722820001], [50297209609059623442815521181722350352719290856519522344205021656047917502237970917310786375279675448048523557477430805, 15857002182452297197982329375111053201349508644473177012866786518888614594064540203474772864651339444396084341878515576, 403895394397791973760362815402896437377344978600840941064554187621230430084298005374238342732262063840044910975524068949], [20927895257497747238986668613021753703988641935802190249109474260700254931957028009020124444515606174885105200514424695082, 98413334887257200681733050277146006881243886515744398160788872174047591102175251363062934975915162936537446741657116020142, 78051558442599615087309433778145628490452507646127324484751553881813231026055047222156670588293781138503172604228380321976], [16192599784864691180295806644680526068139201230224367938291307055217817451931595148327785761709610349158459120162594696721314, 25611869083247087245152286117827285218210603087717473516754579003267021231851741943325038005987943686029851783456188413428074, 25992180689931116336143095391720658271235318487491891937170995569452091167110261435363933440750176011418320077925229437139441], [1486065074770625241543033346926580865585132960697717056411171079869255497066621227141079321338459582851303823888054029997147496, 3245525951376819329573085322535606750874380802419239054828998013409477579195505568845403155178550250571620183484642153687084244, 112418439871405702093723993558148045955947964355568790237500341233964777308030963124075783317247912243584957552429165175567188], [554414264583315659699674517123338050716408838397305952512626047866746893643260154358369760406409101186772630676890380049965307590, 1043200414999535582462864439522105588377941946109653277868282881800541041225127481024498906645711562172897887223370490480497681412, 1871431105609054802663860414521114349131507818555644333411481724711171594958225200659513765626347213458290656339411867664235748235], [109230492350394219294209686711480148111959062898867460819812302521395700744999727865321098736169431939787056320261942410874757468733, 10946993578608042700991075540593043447808613562525646016983180580734427427599503571629298569725315601140135266559866649733843666727, 246030677678827748651446732888780806311392020007912976339004498361198715345773486325046589103993759763143866861161592823427071675783], [101248109580616294936240676346296891730712143388596188295797877367588968569639645896673577202008557062368850136081432452565741764481780, 72117245758610730163502698117383423435096962164217931641814611037828628449683172552024006212893710709568092586830060674702530720630838, 34156236014950110786479179647875910303316921242375549800567936108514427153840347644258274879993941142366793077681295934860378594097995], [15990838065899635329967108817549304489054566867252353907331052546852811551057811982388652520412231526149334610863159737956306990396908939, 13877638546016696452612797658463979632180424075209018025216464738606223836856974888899865627240196446658442424067555529584318542068829304, 12677775392542654738129436028991703771671470731367401228424534633630663828784099080524940674805885560927768192511268731112718248394226507], [4296188317596592605354429710403045587794207218497978126733577807175844533640562786210144572543925369843724531281548656552721224871306408934, 285081536544994597260307396740776857794705257501212064846291286514459078443374031927697656139361855500907534462182310648076485673416888921, 520400706696766574333742507514386230765824087521995208501834759618645877986879790251385446075750614955038875512629839250118760269191026622], [723122593616548907044099469723004726497190485559641744410070335219249336116342743215201071639802723683990761587106342365181354592623344218801, 1153081974669760235610536228156857408078008322403018213105375405360329083793186764164405226051712297309391269434496643454473313250671026317128, 1045323654864427173281766234316255577186878737208078652772060147922139057153363756199552977634641592432020342677714487371354351937732515340769], [286030080032157831584122660246587223893513399286538292684484068916231408017197370416498756180333020768698170404223092800960480629708274198357766, 100459558673910591509973452243869469674982609364866947220110101686698490657211631881397783562822118029166972210922055667458687955478399421168073, 312292327459064171357951759470882292390813169506242332753018135455390262583056880515441693426982451446980584789275705862372219996047882719285468], [76023080448832255495664889576818310445911073068838354851978140354392238188416337217228905387684862369127475726687990437747210819206251364663178366, 79909535960128750054208617904939309393169970650206619816849976160579698275180034617070788991315683797824856913928470939644467300086993321201275631, 12836987084929344870134687159309348060974294106220115465827408756433486147899850505008319816817057038378975905890624567608788056817845202397527597], [11279020797227306692073405567334400908025941871799432354659652341662205110177284358626006856443935763650221701010232939257999415323818219101323774121, 20701716847360264680448441409193277773473820912500811296314617325114135630274188720845655325935966413579156878391231036040452436356525182168927455769, 11662490076049426720444287570232288256606203670569001212826141005750817611908212326773163654541321013641063180589777301351375281786680265675242915490], [3664976056843244899046405770495243971851225829858688853727255965918845526037369928043768545436855691031033629075777959837838040026954342398365868203284, 4303664923255399627145773380664312302061180145098884815650431155840108262865380991633139788830947418042382178669502102253270206161944686126778721177256, 1329888344611251607206799678158068345794425334107811143951615318094938592491017133110084673083835131542105919726637023746895921675774269854930747391813], [27526396919462446400199857855946211084417698150345843381184345248429342915256383060323038929143521278663384600451962926565632962402403286747322866933186, 832473066824718090282351924757867347117523355595408205531707129191210904495622372227106712804655676416188547356217198716998980216027824443061970459017213, 739285279997382078166992780609222700401048107660954429292420131543662494886151464036035917462960151020457777790199766047230392831072294938389838019192375], [241604036983256570910237563151583734634247804014729497396976621887556420166938734129084585512496813488556852332626724956813515081301022211288671489609624726, 232918625432663776612980648646547430425799068288725384437941544591137340240225694513718939585866852521983294039207611429584316281048886496760692847238475958, 330280356821375777416141788080009583520428720186288496589338440210000394525310148011506810729947920712589385371511611188538783776067961774123574958402713416], [37917177921557913063797063712175107470400149903365012052437848627624556178462092849875066084483410175131191909488280543701737678455574966120683361771538984869, 82285213220068552502977130984079405256046284613100219448045047718647214635424915048365233181766026879765932575837957606566968808956187850661636939764713829757, 54862629754020461190972199219422809877737510603527851047197196675006832975655107720818914451383313987635699626910019975156748775680769393491662354129665564665], [10176770592061494683902022210595838961181896347187166561115555380150487550055091054691083781753046719620211182526622568190117287871224755124378960411817051522347, 20391437792952018079898899709442083666375852061962519735185961685298641965953456220963572734830150545534613384697719780482366933145736561569104130664654552711112, 5184672887185762911825431869653048673959736811735614638077371148686297384863233976741655920190695071107226141719503919502011593827206165497631320711901861412505], [2773806845979032590669908316758838167490410534429658877076115296219751182626553934482865930802051989491312042105845829522334288803990327629270690684487381035735068, 4313397356511833703919769030365821724752420735506938177875096936636635640237756238703789233649487006170963871514071797499791012862391242439315785734249060209905870, 1384521522113584419234026605710886691198760220478447038149301773862983248614505122442941228842319360170622150894552550565168083692478460245750070200793173355915110], [977605605346967027884157812086795195281198128843588844802255600782574072246322450726753867594904637719389010883656117163446600576421636602802273450819657911229092739, 1077122028153411402864595787831545281960357301948562230974263019017587247307938796068349770175005165754271751912679139878240066950583364300243665524428812156594708658, 381071794273313233090141046983124159496192143355842855513220907221649906653471651139682409544512356167912597901893098050357507457603299288858937833673078904758920182], [67062212236285997924209614787534890751009288135227553165998196811919096000885310832052245686810617894345398300182072193678864438410618886008897981904472885367476211057, 159854276414635686128310856355014729303536467044176101830252797765797010129021499806804246440506719099238942904835227939207035449129236215655107335852262007504926605969, 250442077587466213725605597489854467254423721041651218597587608844522479925489283592286145881313894977088155508712509697027472708345579764134359861134589340933375529074]]
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/GreyCatTheFlag/2023/Quals/crypto/QRSA/main.py
ctfs/GreyCatTheFlag/2023/Quals/crypto/QRSA/main.py
from Crypto.Util.number import bytes_to_long from secret import qa, qb, pa, pb FLAG = b'fake_flag' class Q: d = 41 def __init__(self, a, b): self.a = a self.b = b def __add__(self, other): return Q(self.a + other.a, self.b + other.b) def __sub__(self, other): return Q(self.a - other.a, self.b - other.b) def __mul__(self, other): a = self.a * other.a + Q.d * self.b * other.b b = self.b * other.a + self.a * other.b return Q(a, b) def __mod__(self, other): # Implementation Hidden # ... return self def __str__(self) -> str: return f'({self.a}, {self.b})' def power(a, b, m): res = Q(1, 0) while (b > 0): if (b & 1): res = (res * a) % m a = (a * a) % m b //= 2 return res p, q = Q(pa, pb), Q(qa, qb) N = p * q m = Q(bytes_to_long(FLAG[:len(FLAG)//2]), bytes_to_long(FLAG[len(FLAG)//2:])) e = 0x10001 c = power(m, e, N) print(f"N_a = {N.a}") print(f"N_b = {N.b}") print(f"C_a = {c.a}") print(f"C_b = {c.b}") print(f"e = {e}") print(f"D = {Q.d}")
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/GreyCatTheFlag/2023/Quals/crypto/QRSA/secret.py
ctfs/GreyCatTheFlag/2023/Quals/crypto/QRSA/secret.py
# fake placeholder value qa = 1 qb = 1 pa = 1 pb = 1
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/GreyCatTheFlag/2023/Quals/crypto/OT/main.py
ctfs/GreyCatTheFlag/2023/Quals/crypto/OT/main.py
import secrets import hashlib from Crypto.Util.number import isPrime, long_to_bytes FLAG = b'grey{fake_flag}' e = 0x10001 def checkN(N): if (N < 0): return "what?" if (N.bit_length() != 4096): return "N should be 4096 bits" if (isPrime(N) or isPrime(N + 23)): return "Hey no cheating" return None def xor(a, b): return bytes([i ^ j for i,j in zip(a,b)]) def encrypt(key, msg): key = hashlib.shake_256(long_to_bytes(key)).digest(len(msg)) return xor(key, msg) print("This is my new Oblivious transfer protocol built on top of the crypto primitive (factorisation is hard)\n") print("You should first generate a number h which you know the factorisation,\n") print("If you wish to know the first part of the key, send me h") print(f"If you wish to know the second part of the key, send me h - {23}\n") N = int(input(("Now what's your number: "))) check = checkN(N) if check != None: print(check) exit(0) k1, k2 = secrets.randbelow(N), secrets.randbelow(N) k = k1 ^ k2 print("Now I send you these 2 numbers\n") print(f"pow(k1, e, N) = {pow(k1, e, N)}") print(f"pow(k2, e, N+23) = {pow(k2, e, N + 23)}\n") print("Since you only know how to factorise one of them, you can only get one part of the data :D\n") print("This protocol is secure so sending this should not have any problem") print(f"flag = {encrypt(k, FLAG).hex()}") print("Bye bye!")
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/GreyCatTheFlag/2023/Quals/crypto/The_Vault/chall.py
ctfs/GreyCatTheFlag/2023/Quals/crypto/The_Vault/chall.py
from hashlib import sha256 from Crypto.Util.number import long_to_bytes from Crypto.Cipher import AES from Crypto.Random import get_random_bytes from math import log10 FLAG = "grey{fake_flag}" n = pow(10, 128) def check_keys(a, b): if a % 10 == 0: return False # Check if pow(a, b) > n if b * log10(a) > 128: return True return False def encryption(key, plaintext): iv = "Greyhats".encode() cipher = AES.new(key, AES.MODE_CTR, nonce = iv) return cipher.encrypt(plaintext) print("Welcome back, NUS Dean. Please type in the authentication codes to open the vault! \n") a = int(input("Enter the first code: ")) b = int(input("Enter the second code: ")) if not check_keys(a, b): print("Nice try thief! The security are on the way.") exit(0) print("Performing thief checks...\n") thief_check = get_random_bytes(16) # Highly secure double encryption checking system. The thieves stand no chance! x = pow(a, b, n) first_key = sha256(long_to_bytes(x)).digest() second_key = sha256(long_to_bytes(pow(x, 10, n))).digest() if thief_check == encryption(first_key, encryption(second_key, thief_check)): print("Vault is opened.") print(FLAG) else: print("Stealing attempts detected! Initializing lockdown")
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/GreyCatTheFlag/2023/Quals/crypto/GreyCat_Trial/chall.py
ctfs/GreyCatTheFlag/2023/Quals/crypto/GreyCat_Trial/chall.py
from random import randint FLAG = "grey{fake_flag}" print("Lo and behold! The GreyCat Wizard, residing within the Green Tower of PrimeLand, is a wizard of unparalleled prowess") print("The GreyCat wizard hath forged an oracle of equal potency") print("The oracle hath the power to bestow upon thee any knowledge that exists in the world") print("Gather the requisite elements to triumph over the three trials, noble wizard.") print() a = int(input("The first element: ")) b = int(input("The second element: ")) print() all_seeing_number = 23456789 # FIRST TRIAL if b <= 0: print("Verily, those who would cheat possess not the might of true wizards.") exit(0) if pow(all_seeing_number, a - 1, a) != 1: print("Alas, thy weakness hath led to defeat in the very first trial.") exit(0) # SECOND TRIAL trial_numbers = [randint(0, 26) for i in range(26)] for number in trial_numbers: c = a + b * number if pow(all_seeing_number, c - 1, c) != 1: print("Thou art not yet strong enough, and thus hast been vanquished in the second trial") exit(0) # THIRD TRIAL d = a + b * max(trial_numbers) if (d.bit_length() < 55): print("Truly, thou art the paramount wizard. As a reward, we present thee with this boon:") print(FLAG) else: print("Thou art nigh, but thy power falters still.")
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/GreyCatTheFlag/2023/Quals/crypto/EncryptService/chall.py
ctfs/GreyCatTheFlag/2023/Quals/crypto/EncryptService/chall.py
import os from Crypto.Cipher import AES from hashlib import sha256 FLAG = "grey{fake_flag_please_change_this}" assert(len(FLAG) == 40) secret_key = os.urandom(16) def encrypt(plaintext, iv): hsh = sha256(iv).digest()[:8] cipher = AES.new(secret_key, AES.MODE_CTR, nonce=hsh) ciphertext = cipher.encrypt(plaintext) return ciphertext.hex() print("AES is super safe. You have no way to guess my key anyways!!") print("My encryption service is very generous. Indeed, so generous that we will encrypt any plaintext you desire many times") try: plaintext = bytes.fromhex(input("Enter some plaintext (in hex format): ")) except ValueError: print("We are incredibly generous, yet you display such selfishness by failing to provide a proper hex string") exit(0) for i in range(256): ciphertext = encrypt(plaintext, i.to_bytes(1, 'big')) print(f"Ciphertext {i}: {ciphertext}") print() print("We will reward a lot of money for the person that can decipher this encrypted message :)") print("It's impossible to decipher anyways, but here you go: ") print("Flag: ", encrypt(FLAG.encode("ascii"), os.urandom(1)))
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/GreyCatTheFlag/2023/Quals/crypto/PLCG/main.py
ctfs/GreyCatTheFlag/2023/Quals/crypto/PLCG/main.py
import secrets from Crypto.Cipher import AES from Crypto.Util.Padding import pad FLAG = b'grey{fake_flag}' while True: sample = [3, 80] + [secrets.randbelow(256) for _ in range(2)] if len(sample) == len(set(sample)) and 0 not in sample: break def getBiasRandomByte(): return secrets.choice(sample) def getRandomByte(): n = 0; g = 0 for _ in range(20): n += getBiasRandomByte() * getBiasRandomByte() for _ in range(20): g = (g + getBiasRandomByte()) % 256 for _ in range(n): g = (getBiasRandomByte() * g + getBiasRandomByte()) % 256 return g def encrypt(msg): key = bytes([getRandomByte() for _ in range(6)]) cipher = AES.new(pad(key, 16), AES.MODE_CTR, nonce=b'\xc1\xc7\xcc\xd1D\xfbI\x10') return cipher.encrypt(msg) print("Hello there, this is our lucky numbers") print(" ".join(map(str,sample))) s = int(input("Send us your lucky number! ")) if not (0 <= s <= 10): print("I dont like your number :(") exit(0) for i in range(s): print("Here's your lucky flag:", encrypt(FLAG).hex())
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/GreyCatTheFlag/2023/Quals/crypto/Encrypt/main.py
ctfs/GreyCatTheFlag/2023/Quals/crypto/Encrypt/main.py
from Crypto.Util.number import bytes_to_long from secrets import randbits FLAG = b'fake_flag' p = randbits(1024) q = randbits(1024) def encrypt(msg, key): m = bytes_to_long(msg) return p * m + q * m**2 + (m + p + q) * key n = len(FLAG) s = randbits(1024) print(f'n = {n}') print(f'p = {p}') print(f'q = {q}') print(f'c1 = {encrypt(FLAG[:n//2], s)}') print(f'c2 = {encrypt(FLAG[n//2:], s)}')
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/GreyCatTheFlag/2023/Quals/web/Microservices/admin_page/app.py
ctfs/GreyCatTheFlag/2023/Quals/web/Microservices/admin_page/app.py
from fastapi import FastAPI, Request, Response from dotenv import load_dotenv from requests import get import os load_dotenv() admin_cookie = os.environ.get("ADMIN_COOKIE", "FAKE_COOKIE") app = FastAPI() @app.get("/") async def index(request: Request): """ The base service for admin site """ # Currently Work in Progress requested_service = request.query_params.get("service", None) if requested_service is None: return {"message": "requested service is not found"} # Filter external parties who are not local if requested_service == "admin_page": return {"message": "admin page is currently not a requested service"} # Legit admin on localhost requested_url = request.query_params.get("url", None) if requested_url is None: return {"message": "URL is not found"} # Testing the URL with admin response = get(requested_url, cookies={"cookie": admin_cookie}) return Response(response.content, response.status_code)
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/GreyCatTheFlag/2023/Quals/web/Microservices/gateway/constant.py
ctfs/GreyCatTheFlag/2023/Quals/web/Microservices/gateway/constant.py
routes = {"admin_page": "http://admin_page", "home_page": "http://home_page"} excluded_headers = [ "content-encoding", "content-length", "transfer-encoding", "connection", ]
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/GreyCatTheFlag/2023/Quals/web/Microservices/gateway/app.py
ctfs/GreyCatTheFlag/2023/Quals/web/Microservices/gateway/app.py
from flask import Flask, request, abort, Response from requests import get from constant import routes, excluded_headers import sys app = Flask(__name__) @app.route("/", methods=["GET"]) def route_traffic() -> Response: """Route the traffic to upstream""" microservice = request.args.get("service", "home_page") route = routes.get(microservice, None) if route is None: return abort(404) # Fetch the required page with arguments appended raw_query_param = request.query_string.decode() print(f"Requesting {route} with q_str {raw_query_param}", file=sys.stderr) res = get(f"{route}/?{raw_query_param}") headers = [ (k, v) for k, v in res.raw.headers.items() if k.lower() not in excluded_headers ] return Response(res.content, res.status_code, headers) @app.errorhandler(400) def not_found(e) -> Response: """404 error""" return Response(f"""Error 404: This page is not found: {e}""", 404)
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/GreyCatTheFlag/2023/Quals/web/Microservices/homepage/app.py
ctfs/GreyCatTheFlag/2023/Quals/web/Microservices/homepage/app.py
from flask import Flask, request, render_template, Response, make_response from dotenv import load_dotenv import os load_dotenv() admin_cookie = os.environ.get("ADMIN_COOKIE", "FAKE_COOKIE") FLAG = os.environ.get("FLAG", "greyctf{This_is_fake_flag}") app = Flask(__name__) @app.route("/") def homepage() -> Response: """The homepage for the app""" cookie = request.cookies.get("cookie", "Guest Pleb") # If admin, give flag if cookie == admin_cookie: return render_template("flag.html", flag=FLAG, user="admin") # Otherwise, render normal page response = make_response(render_template("index.html", user=cookie)) response.set_cookie("cookie", cookie) return response if __name__ == "__main__": app.run(debug=True)
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/GreyCatTheFlag/2023/Quals/web/100_Questions/app.py
ctfs/GreyCatTheFlag/2023/Quals/web/100_Questions/app.py
from flask import Flask, render_template, request import sqlite3 app = Flask(__name__) @app.route("/", methods=["GET"]) def index(): qn_id, ans= request.args.get("qn_id", default="1"), request.args.get("ans", default="") # id check, i don't want anyone to pollute the inputs >:( if not (qn_id and qn_id.isdigit() and int(qn_id) >= 1 and int(qn_id) <= 100): # invalid!!!!! qn_id = 1 # get question db = sqlite3.connect("database.db") cursor = db.execute(f"SELECT Question FROM QNA WHERE ID = {qn_id}") qn = cursor.fetchone()[0] # check answer cursor = db.execute(f"SELECT * FROM QNA WHERE ID = {qn_id} AND Answer = '{ans}'") result = cursor.fetchall() correct = True if result != [] else False return render_template("index.html", qn_id=qn_id, qn=qn, ans=ans, correct=correct) 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/GreyCatTheFlag/2023/Quals/web/Microservices_Revenge/admin_page/app.py
ctfs/GreyCatTheFlag/2023/Quals/web/Microservices_Revenge/admin_page/app.py
from flask import Flask, Response, render_template_string, request app = Flask(__name__) @app.get("/") def index() -> Response: """ The base service for admin site """ user = request.cookies.get("user", "user") # Currently Work in Progress return render_template_string( f"Sorry {user}, the admin page is currently not open." )
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/GreyCatTheFlag/2023/Quals/web/Microservices_Revenge/gateway/constant.py
ctfs/GreyCatTheFlag/2023/Quals/web/Microservices_Revenge/gateway/constant.py
routes = { "adminpage": "http://radminpage", "homepage": "http://rhomepage", "flagpage": "http://rflagpage/construction", } excluded_headers = [ "content-encoding", "content-length", "transfer-encoding", "connection", ]
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/GreyCatTheFlag/2023/Quals/web/Microservices_Revenge/gateway/app.py
ctfs/GreyCatTheFlag/2023/Quals/web/Microservices_Revenge/gateway/app.py
from flask import Flask, request, abort, Response from requests import Session from constant import routes, excluded_headers app = Flask(__name__) # Extra protection for my page. banned_chars = { "\\", "_", "'", "%25", "self", "config", "exec", "class", "eval", "get", } def is_sus(microservice: str, cookies: dict) -> bool: """Check if the arguments are sus""" acc = [val for val in cookies.values()] acc.append(microservice) for word in acc: for char in word: if char in banned_chars: return True return False @app.route("/", methods=["GET"]) def route_traffic() -> Response: """Route the traffic to upstream""" microservice = request.args.get("service", "homepage") route = routes.get(microservice, None) if route is None: return abort(404) # My WAF if is_sus(request.args.to_dict(), request.cookies.to_dict()): return Response("Why u attacking me???\nGlad This WAF is working!", 400) # Fetch the required page with arguments appended with Session() as s: for k, v in request.cookies.items(): s.cookies.set(k, v) res = s.get(route, params={k: v for k, v in request.args.items()}) headers = [ (k, v) for k, v in res.raw.headers.items() if k.lower() not in excluded_headers ] return Response(res.content.decode(), res.status_code, headers)
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/GreyCatTheFlag/2023/Quals/web/Microservices_Revenge/flag_page/app.py
ctfs/GreyCatTheFlag/2023/Quals/web/Microservices_Revenge/flag_page/app.py
from flask import Flask, Response, jsonify import os app = Flask(__name__) app.secret_key = os.environ.get("SECRET_KEY", os.urandom(512).hex()) FLAG = os.environ.get("FLAG", "greyctf{fake_flag}") @app.route("/") def index() -> Response: """Main page of flag service""" # Users can't see this anyways so there is no need to beautify it # TODO Create html for the page return jsonify({"message": "Welcome to the homepage"}) @app.route("/flag") def flag() -> Response: """Flag endpoint for the service""" return jsonify({"message": f"This is the flag: {FLAG}"}) @app.route("/construction") def construction() -> Response: return jsonify({"message": "The webpage is still under construction"})
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/GreyCatTheFlag/2023/Quals/web/Microservices_Revenge/homepage/app.py
ctfs/GreyCatTheFlag/2023/Quals/web/Microservices_Revenge/homepage/app.py
from flask import Flask, request, render_template, Response, make_response app = Flask(__name__) @app.route("/") def homepage() -> Response: """The homepage for the app""" cookie = request.cookies.get("cookie", "") # Render normal page response = make_response(render_template("index.html", user=cookie)) response.set_cookie("cookie", cookie if len(cookie) > 0 else "user") return response if __name__ == "__main__": app.run(debug=True)
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/GreyCatTheFlag/2023/Quals/web/Baby_Web/adminbot.py
ctfs/GreyCatTheFlag/2023/Quals/web/Baby_Web/adminbot.py
from selenium import webdriver from constants import COOKIE import multiprocessing from webdriver_manager.chrome import ChromeDriverManager options = webdriver.ChromeOptions() options.add_argument("--headless") options.add_argument("--incognito") options.add_argument("--disable-dev-shm-usage") options.add_argument("--no-sandbox") def visit(baseUrl: str, link: str) -> str: """Visit the website""" p = multiprocessing.Process(target=_visit, args=(baseUrl, link)) p.start() return f"Visiting {link}" def _visit(baseUrl:str, link: str) -> str: """Visit the website""" with webdriver.Chrome(ChromeDriverManager().install(), options=options) as driver: try: driver.get(f'{baseUrl}/') cookie = {"name": "flag", "value": COOKIE["flag"]} driver.add_cookie(cookie) driver.get(link) return f"Visited {link}" except: return f"Connection Error: {link}"
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/GreyCatTheFlag/2023/Quals/web/Baby_Web/constants.py
ctfs/GreyCatTheFlag/2023/Quals/web/Baby_Web/constants.py
import os FLAG = os.getenv('FLAG', r'grey{fake_flag}') COOKIE = {"flag": FLAG}
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/GreyCatTheFlag/2023/Quals/web/Baby_Web/server.py
ctfs/GreyCatTheFlag/2023/Quals/web/Baby_Web/server.py
from flask import Flask, request, render_template, redirect, flash from adminbot import visit from urllib.parse import quote app = Flask(__name__) BASE_URL = "http://localhost:5000/" @app.route('/', methods=['GET', 'POST']) def index(): if request.method == "GET": return render_template('index.html') message = request.form.get('message') if len(message) == 0: flash("Please enter a message") return render_template('index.html') link = f"/ticket?message={quote(message)}" # Admin vists the link here visit(BASE_URL, f"{BASE_URL}{link}") return redirect(link) @app.route('/ticket', methods=['GET']) def ticket_display(): message = request.args.get('message') return render_template('ticket.html', message=message)
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/GreyCatTheFlag/2023/Quals/web/Login_Bot/login/utils.py
ctfs/GreyCatTheFlag/2023/Quals/web/Login_Bot/login/utils.py
from urllib.parse import urlparse, urljoin from flask import request def is_safe_url(target): """Check if the target URL is safe to redirect to. Only works for within Flask request context.""" ref_url = urlparse(request.host_url) test_url = urlparse(urljoin(request.host_url, target)) return test_url.scheme in ('http', 'https') and \ ref_url.netloc == test_url.netloc
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/GreyCatTheFlag/2023/Quals/web/Login_Bot/login/app.py
ctfs/GreyCatTheFlag/2023/Quals/web/Login_Bot/login/app.py
from flask import Flask, render_template, request, redirect, url_for, flash, Response from flask_sqlalchemy import SQLAlchemy from sqlalchemy import Column, Integer, String import re import os import sys from utils import is_safe_url from os import urandom, getenv import requests ## Constants ## URL_REGEX = r'(https?:\/\/(www\.)?[-a-zA-Z0-9@:%._\+~#=]{1,256}\.[a-zA-Z0-9()]{1,6}\b([-a-zA-Z0-9()@:%_\+.~#?&//=]*))' BASE_URL = f"http://localhost:5000" ## Init Application ## app = Flask(__name__) app.secret_key = urandom(512).hex() app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///database.db' app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False db = SQLAlchemy(app) ### These are secure :D, Please do not waste time brute forcing ### FLAG = getenv('FLAG', 'grey{this_is_a_fake_flag}') #Also the password ADMIN_COOKIE = getenv('ADMIN_COOKIE', 'this_is_fake_cookie') ####################################################################### #### Models #### class Post(db.Model): id = Column(Integer, primary_key=True) title = Column(String(100), nullable=False) content = Column(String(1000), nullable=False) def __repr__(self): return f"Post('{self.title}', '{self.content[:20]}...')" class Url(db.Model): id = Column(Integer, primary_key=True, autoincrement=True) url = Column(String(100), nullable=False) def is_admin() -> bool: """Check if the user is an admin""" return request.cookies.get('cookie') == ADMIN_COOKIE #### Before First Request #### if os.path.exists('database.db'): os.remove('database.db') with app.app_context(): db.create_all() #### Routes #### @app.route('/') def index() -> Response: if not is_admin(): flash('You are not an admin. Please login to continue', 'danger') return redirect(f'/login?next={request.path}') posts = Post.query.all() return render_template('index.html', posts=posts) @app.route('/login', methods=['GET', 'POST']) def login() -> Response: if request.method == 'GET': return render_template('login.html') username = request.form.get('username', '') password = request.form.get('password', '') if password != FLAG or username != 'admin': flash('Wrong password', 'danger') return redirect(url_for('index')) # If user is admin, set cookie next = request.args.get('next', '/') response = redirect('/') if is_safe_url(next): response = redirect(next) response.set_cookie('cookie', ADMIN_COOKIE) return response @app.route('/post', methods=['POST']) def post() -> Response: if not is_admin(): flash('You are not an admin. Please login to continue', 'danger') return redirect(f'/login?next={request.path}') title = request.form['title'] content = request.form['content'] sanitized_content = sanitize_content(content) if title and content: post = Post(title=title, content=sanitized_content) db.session.add(post) db.session.commit() flash('Post created successfully', 'success') return redirect(url_for('index')) flash('Please fill all fields', 'danger') return redirect(url_for('index')) @app.route('/url/<int:id>') def url(id: int) -> Response: """Redirect to the url in post if its sanitized""" url = Url.query.get_or_404(id) return redirect(url.url) def sanitize_content(content: str) -> str: """Sanitize the content of the post""" # Replace URLs with in house url tracker urls = re.findall(URL_REGEX, content) for url in urls: url = url[0] url_obj = Url(url=url) db.session.add(url_obj) content = content.replace(url, f"/url/{url_obj.id}") return content @app.route('/send_post', methods=['GET', 'POST']) def send_post() -> Response: """Send a post to the admin""" if request.method == 'GET': return render_template('send_post.html') url = request.form.get('url', '/') title = request.form.get('title', None) content = request.form.get('content', None) if None in (url, title, content): flash('Please fill all fields', 'danger') return redirect(url_for('send_post')) # Bot visit url_value = make_post(url, title, content) flash('Post sent successfully', 'success') flash('Url id: ' + str(url_value), 'info') return redirect('/send_post') def make_post(url: str, title: str, user_content: str) -> int: """Make a post to the admin""" with requests.Session() as s: visit_url = f"{BASE_URL}/login?next={url}" resp = s.get(visit_url, timeout=10) content = resp.content.decode('utf-8') # Login routine (If website is buggy we run it again.) for _ in range(2): print('Logging in... at:', resp.url, file=sys.stderr) if "bot_login" in content: # Login routine resp = s.post(resp.url, data={ 'username': 'admin', 'password': FLAG, }) # Make post resp = s.post(f"{resp.url}/post", data={ 'title': title, 'content': user_content, }) return db.session.query(Url).count() 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/GreyCatTheFlag/2022/crypto/Baby/main.py
ctfs/GreyCatTheFlag/2022/crypto/Baby/main.py
from Crypto.Util.number import getPrime, bytes_to_long FLAG = <REDACTED> p = getPrime(1024); q = getPrime(1024) r = getPrime(4086); s = getPrime(4086) N = p * q e = 0x10001 m = bytes_to_long(FLAG) c = pow(m, e, N) print(c) print(r * p - s * q) print(r) print(s) # c = 8755361716037050593786802368740593505819541985087751465246316611208654712808851039985566950771569219005474679214890773248679686452291791926024778938667161954201119658253063645930886986362437085401598314742279109631478572452731396671691672092589080935682736804089015740009401298581639291193682963105747576715867254889247753788661315475189523656612126700002888122729034598825641796362628516626027115516263101484541445062801096777586863144812446160024700491104414848804200440962708078212109059521089126401730984744470907608297401873174614500873021527030728187991640911253978614160956515292658729861625177800745954684779 # r * p - s * q = -34384571636542682732993801408238567193071079747335767504994340801608381182708103244757509021281874449800069281009810023907313154391464668542796187787092864913072601227852655851070468919417844230689008922504112542853587185699616544272977753830325804164014338601030700848859059311067280180340700746209053062443574270773642918163909645688335979566572624221870500744676835269869601108253139361167400301626751736498534338162228764111438600887057835670459016374249012923832476577336962810182684197767760519515721734005603313785840044947657687083840236225406435252382559823958066573244309719575485706011861244028446996920249519039258733914177844818916938491744948605478385399858626470926733928838196963004350577779862247581837961536832869640531493345914188439519605065799034864280428993112773164769200946009507688445375319097127445639570984261253620532620742924894113105707671949166533244311479026914960105181835442456417671355468402543233569770391833669600663695797387468169339523234585262610811933566181920470444240902853887724615316068488136323539979229581225786468457662315990029857258798124732280829662164932213109363870409335054243794586400741357324161913978437694775195815062757093213325952057171001722380372888748256174953952360070118846290246140793770694204401164960742113068366766928707670654861609748340943116513275092360152185494867472310293656556031756417497249251872489238008435654320326489069126549344443700948553988405022863350434081213995337512472150109078421242823877306926652997021828653860169896336216359386864067959578257760 # r = 936281797755031261848169861788419286242500155122743234286943102853441400861252708389579924384747328538959760271792565686537791395731078897913727180911468908585976003090733895007958447959094383445975201070786043510921764921108055952715166472860417830673976831707347242236348495245218675030438657044803590841511241481934488468486944285639180440843969944429852785215880499136631346605823164121032336218990671202212953326203467124685189344280256775009299633701974115736573067349919745244858804283455071851912194286160784172943301316083821185405338610368688605358644365423958890024208974121167171384473118059281816494356755844809173265412809337423995268268663119244396063406978295035815869788202375167281450339517979957331467143500209528727150295191004885385839900735810500718557821053671052959432831767663810090095379231750412744076404163742435544440795801122979274805554706606583599755007872912935576369508808550677885164226933064726817359773399072956113665969905205606138989373281554161008535232454798115570092928010969726174633824544610380764744958638537085759378694993737437724201369828812993239842742165386297807164278219508640684529837977445571884153238673179892479261196341148157129952993380440229458239746064451443526116917519 # s = 834939575457003657728171346390813480312906155291642219227936205156714217262322467739149680558607905413429343953514849176130680023475055635457415545359365246681638783469216604913252838569701559353464582588062109434066644004845623203772527840551656611501677400844706770270825409839625738792427657150026307314821780392251524458037197655903343177131336842583042394801173673131588262961636245185030505564613639234805815677902379543111678201103954034310087231196210755934978052370451876638256180762443170329319207101581789208664345386093469896758682416555125087939413443536267912794750486701814941395277218714280572422080584205069255289731982911845911942205319661268893590368592905932152208108183590473584581786595300724772852979382943318977777850080673301763071986653891789753006523321672813311922284194072995019342531330632536316816984745914614649167801364562670569095961614178729268507876040470655722687777049415470890053491272405716858536141212596151075134173517337948569646361076821140748265156759845142133374048339524320025708823936755215461004080494169096216330198356553864601197456450193436851885342802515269136267023694614035998000939158575602883575921465198767978819627846523739073812562683002815460930245515210169007766320597
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/GreyCatTheFlag/2022/crypto/Block/main.py
ctfs/GreyCatTheFlag/2022/crypto/Block/main.py
from Crypto.Util.Padding import pad FLAG = <REDACTED> SUB_KEY = [ 0x11,0x79,0x76,0x8b,0xb8,0x40,0x02,0xec,0x52,0xb5,0x78,0x36,0xf7,0x19,0x55,0x62, 0xaa,0x9a,0x34,0xbb,0xa4,0xfc,0x73,0x26,0x4b,0x21,0x60,0xd2,0x9e,0x10,0x67,0x2c, 0x32,0x17,0x87,0x1d,0x7e,0x57,0xd1,0x48,0x3c,0x1b,0x3f,0x37,0x1c,0x93,0x16,0x24, 0x13,0xe1,0x1f,0x91,0xb3,0x81,0x1e,0x3d,0x5b,0x6c,0xb9,0xf2,0x83,0x4c,0xd5,0x5a, 0xd0,0xe7,0xca,0xed,0x29,0x90,0x6f,0x8f,0xe4,0x2f,0xab,0xbe,0xfe,0x07,0x71,0x6b, 0x59,0xa3,0x8a,0x5e,0xd7,0x30,0x2a,0xa0,0xac,0xbd,0xd4,0x08,0x4f,0x06,0x31,0x72, 0x0d,0x9f,0xad,0x0b,0x23,0x80,0xe6,0xda,0x75,0xa8,0x18,0xe2,0x04,0xeb,0x8e,0x15, 0x64,0x00,0x2b,0x03,0xa1,0x5d,0xb4,0xb1,0xf0,0x97,0xe3,0xe8,0xb0,0x05,0x86,0x38, 0x56,0xef,0xfa,0x43,0x94,0xcb,0xb6,0x69,0x5f,0xc7,0x27,0x7c,0x44,0x8d,0xf3,0xc8, 0x99,0xc2,0xbc,0x82,0x65,0xdb,0xaf,0x51,0x20,0x7f,0xc3,0x53,0xf4,0x33,0x4d,0x50, 0xee,0xc5,0x12,0x63,0x9b,0x7b,0x39,0x45,0xa9,0x2d,0x54,0xdc,0xdf,0xd6,0xfd,0xa7, 0x5c,0x0c,0xe9,0xb2,0xa2,0xc1,0x49,0x77,0xae,0xea,0x58,0x6d,0xce,0x88,0xf8,0x96, 0xde,0x1a,0x0f,0x89,0xd3,0x7a,0x46,0x22,0xc6,0xf9,0xd9,0x84,0x2e,0x6a,0xc9,0x95, 0xa5,0xdd,0xe0,0x74,0x25,0xb7,0xfb,0xbf,0x9c,0x4a,0x92,0x0e,0x09,0x9d,0xf6,0x70, 0x61,0x66,0xc0,0xcf,0x35,0x98,0xf5,0x68,0x8c,0xd8,0x01,0x3e,0xba,0x6e,0x41,0xf1, 0xa6,0x85,0x3a,0x7d,0xff,0x0a,0x14,0xe5,0x47,0xcd,0x28,0x3b,0xcc,0x4e,0xc4,0x42 ] def xor(block): for i in range(4): for j in range(4): block[i][j] ^= block[(i + 2) % 4][(j + 1) % 4] def add(block): for i in range(4): for j in range(4): block[i][j] += 2 * block[(i * 3) % 4][(i + j) % 4] block[i][j] &= 0xFF def sub(block): for i in range(4): for j in range(4): block[i][j] = SUB_KEY[block[i][j]] def rotate(row): row[0], row[1], row[2], row[3] = row[3], row[0], row[1], row[2] def transpose(block): copyBlock = [[block[i][j] for j in range(4)] for i in range(4)] for i in range(4): for j in range(4): block[i][j] = copyBlock[j][i] def swap(block): block[0], block[2] = block[2], block[0] block[3], block[2] = block[2], block[3] block[0], block[1] = block[1], block[0] block[3], block[0] = block[3], block[0] block[2], block[1] = block[1], block[2] block[2], block[0] = block[0], block[2] rotate(block[0]); rotate(block[0]) rotate(block[1]); rotate(block[1]); rotate(block[1]) rotate(block[2]) rotate(block[3]); rotate(block[3]); rotate(block[3]) for i in range(3): for j in range(4): ii = ((block[i][j] & 0XFC) + i) % 4 jj = (j + 3) % 4 block[i][j], block[ii][jj] = block[ii][jj], block[i][j] s = 0 for i in range(4): for j in range(4): s += block[i][j] if (s % 2): transpose(block) def round(block): sub(block) add(block) swap(block) xor(block) def encryptBlock(block): mat = [[block[i * 4 + j] for j in range(4)] for i in range(4)] for _ in range(30): round(mat) return [mat[i][j] for i in range(4) for j in range(4)] def encrypt(msg): msg = list(pad(msg, 16)) enc = [] for i in range(0, len(msg), 16): enc += encryptBlock(msg[i : i + 16]) return bytes(enc) print(encrypt(FLAG).hex()) # 1333087ba678a43ecc697247e2dde06e1d78cb20d8d9326e7c4b01674a46647674afc1e7edd930828e40af60b998b4500361e3a2a685c5515babe4e9ff1fe882
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/GreyCatTheFlag/2022/crypto/Equation/main.py
ctfs/GreyCatTheFlag/2022/crypto/Equation/main.py
from Crypto.Util.number import bytes_to_long FLAG = <REDACTED> n = len(FLAG) m1 = bytes_to_long(FLAG[:n//2]) m2 = bytes_to_long(FLAG[n//2:]) print(13 * m2 ** 2 + m1 * m2 + 5 * m1 ** 7) print(7 * m2 ** 3 + m1 ** 5) # 13 * m2 ** 2 + m1 * m2 + 5 * m1 ** 7 == 6561821624691895712873377320063570390939946639950635657527777521426768466359662578427758969698096016398495828220393137128357364447572051249538433588995498109880402036738005670285022506692856341252251274655224436746803335217986355992318039808507702082316654369455481303417210113572142828110728548334885189082445291316883426955606971188107523623884530298462454231862166009036435034774889739219596825015869438262395817426235839741851623674273735589636463917543863676226839118150365571855933 # 7 * m2 ** 3 + m1 ** 5 == 168725889275386139859700168943249101327257707329805276301218500736697949839905039567802183739628415354469703740912207864678244970740311284556651190183619972501596417428866492657881943832362353527907371181900970981198570814739390259973631366272137756472209930619950549930165174231791691947733834860756308354192163106517240627845889335379340460495043
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/GreyCatTheFlag/2022/crypto/Cube/main.py
ctfs/GreyCatTheFlag/2022/crypto/Cube/main.py
from Crypto.Util.number import bytes_to_long, getPrime, isPrime FLAG = <REDACTED> def gen(n): while True: p = getPrime(n - 1) * 2 + 1 if (isPrime(p)): return p def cube(m, n, p): res = m for i in range(n): res = (res * res * res) % p return res p = gen(1024) m = bytes_to_long(FLAG) c = cube(m, 2 ** 100, p) print(p) print(c) # p = 147271787827929374875021125075644322658199797362157810465584602627709052665153637157027284239972360505065250939071494710661089022260751215312981674288246413821920620065721158367282080824823494257083257784305248518512283466952090977840589689160607681176791401729705268519662036067738830529129470059752131312559 # c = 117161008971867369525278118431420359590253064575766275058434686951139287312472337733007748860692306037011621762414693540474268832444018133392145498303438944989809563579460392165032736630619930502524106312155019251740588974743475569686312108671045987239439227420716606411244839847197214002961245189316124796380
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/GreyCatTheFlag/2022/crypto/Catino/main.py
ctfs/GreyCatTheFlag/2022/crypto/Catino/main.py
from secrets import randbits from decimal import Decimal, getcontext FLAG = <REDACTED> ind = 100 randarr = [] maxRound = 5000 winTarget = 100000 winIncr = 1000 getcontext().prec = maxRound + 1000 def prep(): global randarr print("\nGenerating random numbers....", flush=True) n = Decimal(randbits(2048)) p = Decimal(1/4) k = str(n**p).split('.')[1] randarr = list(k) print("Generation complete!\n", flush=True) def nextRand(): global ind assert ind < len(randarr) res = int(randarr[ind]) ind += 1 return res def menu(): print(''' & #&&& & .&&&&&. (((((.((((((((. #&&& &&&&&&&& (((((((((((((((/(( ,&&&&&&& &&& &&&&/ ((( ((((((((((((((&&&/@&&& &&& ((((((((/ ((( &&& &&& ((((((((((((((((((((((((((((@&&& &&& @&&&&&/((((((((((((((((((((((((((& &&&&&&&&&&&&&&&&&&@/((((((((((((((%&&& &&&&&&&&&&&&&&&&&&&&& &&&&&&&&& &&&&&&&&&% @&&&&& &&&&&&&& &&&&&&&&% &&& @&&&&&&&. &&&&&&&&& @&& && &&& @ .&&&&&&&& &&&&&&&&&& &&&& &&& &&&&&. &&&&&&&&&& &&&&&&&&&&&@ &&&&&&& *&&&&&&&&&&& &&&&&&&&&&&&&&&&&&,,,,,,&&&&&#@&&&&&&&&&&&&&& &&&&&&&&&&&&&&&&&&& &&&&&&&&&&&&&&&&&&&&&&& &&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&& &&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&& &&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&& &&&&&&&&&&&&&&&&&&&&&&&&&&&&&. %&&&&&&&&&&&&&&&&&&&& &&&&&&&&&&&&&&&&&&&&& &&&&&&&&&&&&&&&&&&&&& &&&&&&&&&&&&&&&&&&&&& &&&&&&&&&&&&&&&&&&&&& &&&&&&&&&&&&&&&&&&&&&&&&&,s ''') print("Hey there, I am catino! Meowww ~uwu~") print("Play a game with me and win the flag!\n") print("Game rule:") print("1. You start with $0") print("2. On each round, Catino choose a single digit secret number (0-9)") print("3. You try to guess Catino secret's number") print(f"4. If the guessed number matches the secret, then you earn ${winIncr}") print("5. If the guessed number does not match the secret, then you lose all of your money!") print(f"6. You win when you have ${winTarget}!") print(f"7. The game ends forcefully when the number of round exceeds {maxRound}", flush=True) if __name__ == "__main__": menu() prep() round = 0; wrong = 0; player = 0 while (player < winTarget and round < maxRound): round += 1 print(f"Round: {round}") userIn = int(input("Guess the number (0-9): ")) num = nextRand() if (num == userIn): print(f"You got it right! it was {num}") player += winIncr else: print(f"You got it wrong... it was {num}") player = 0 print(f"You have ${player} left") if (player >= winTarget): print("Congratulations you are now rich! \(★ω★)/") print(FLAG) else: print("Sokay.. Try again next time (っ´ω`)ノ(╥ω╥)")
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/GreyCatTheFlag/2022/crypto/Permutation/main.py
ctfs/GreyCatTheFlag/2022/crypto/Permutation/main.py
from secrets import randbits from hashlib import shake_256 import random import perm FLAG = <REDACTED> def encrypt(key : str) -> str: otp = shake_256(key.encode()).digest(len(FLAG)) return xor(otp, FLAG).hex() def xor(a : bytes, b : bytes) -> bytes: return bytes([ x ^ y for x, y in zip(a, b)]) n = 5000 h = 2048 arr = [i for i in range(n)] random.shuffle(arr) g = perm.Perm(arr) a = randbits(h); b = randbits(h) A = g ** a; B = g ** b S = A ** b key = str(S) print(f"g = [{g}]"); print(f"A = [{A}]"); print(f"B = [{B}]"); print(f"c = {encrypt(key)}")
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/GreyCatTheFlag/2022/crypto/Permutation/perm.py
ctfs/GreyCatTheFlag/2022/crypto/Permutation/perm.py
class Perm(): def __init__(self, arr): assert self.valid(arr) self.internal = arr self.n = len(arr) def valid(self, arr): x = sorted(arr) n = len(arr) for i in range(n): if (x[i] != i): return False return True def __str__(self): return ",".join(map(str, self.internal)) def __mul__(self, other): assert other.n == self.n res = [] for i in other.internal: res.append(self.internal[i]) return Perm(res) def __pow__(self, a): res = Perm([i for i in range(self.n)]) g = Perm(self.internal) while (a > 0): if (a & 1): res = res * g g = g * g a //= 2 return res
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/GreyCatTheFlag/2022/crypto/Entry/main.py
ctfs/GreyCatTheFlag/2022/crypto/Entry/main.py
import secrets FLAG = b'grey{...}' assert len(FLAG) == 40 key = secrets.token_bytes(4) def encrypt(m): return bytes([x ^ y for x, y in zip(m,key)]) c = b'' for i in range(0, len(FLAG), 4): c += encrypt(bytes(FLAG[i : i + 4])) print(c.hex()) # 982e47b0840b47a59c334facab3376a19a1b50ac861f43bdbc2e5bb98b3375a68d3046e8de7d03b4
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/GreyCatTheFlag/2022/web/Quotes/server.py
ctfs/GreyCatTheFlag/2022/web/Quotes/server.py
import random from threading import Thread import os import requests import time from secrets import token_hex from flask import Flask, render_template, make_response, request from flask_sockets import Sockets from gevent import pywsgi from geventwebsocket.handler import WebSocketHandler from selenium.webdriver.firefox.options import Options from selenium.webdriver.firefox.service import Service from selenium import webdriver app = Flask(__name__, static_url_path='', static_folder='static', template_folder='templates') sockets = Sockets(app) auth_token = token_hex(64) quotes=requests.get("https://gist.githubusercontent.com/robatron/a66acc0eed3835119817/raw/0e216f8b6036b82de5fdd93526e1d496d8e1b412/quotes.txt").text.rstrip().split("\n") # best way to get rid of chromium Ndays is to use firefox instead DRIVER_PATH = "/app/geckodriver" options = Options() options.headless = True class Bot(Thread): def __init__(self, url): Thread.__init__(self) self.url = url def run(self): driver = webdriver.Firefox(service=Service(DRIVER_PATH), options=options) driver.get(self.url) time.sleep(3) driver.quit() @app.route('/') def start(): return render_template('index.html') # authenticate localhost only @app.route('/auth') def auth(): print('/auth', flush=True) print(request.remote_addr, flush=True) if request.remote_addr == "127.0.0.1": resp = make_response("authenticated") # I heard httponly defend against XSS(what is that?) resp.set_cookie("auth", auth_token, httponly=True) else: resp = make_response("unauthenticated") return resp @sockets.route('/quote') def echo_socket(ws): print('/quote', flush=True) while not ws.closed: try: try: cookie = dict(i.split('=') for i in ws.handler.headers.get('Cookie').split('; ')) except: cookie = {} # only admin from localhost can get the GreyCat's quote if ws.origin.startswith("http://localhost") and cookie.get('auth') == auth_token: ws.send(f"{os.environ['flag']}") else: ws.send(f"{quotes[random.randint(0,len(quotes))]}") ws.close() except Exception as e: print('error:',e, flush=True) @app.route('/share', methods=['GET','POST']) def share(): if request.method == "GET": return render_template("share.html") else: if not request.form.get('url'): return "yes?" else: thread_a = Bot(request.form.get('url')) thread_a.start() return "nice quote, thanks for sharing!" if __name__ == "__main__": try: server = pywsgi.WSGIServer(('0.0.0.0', 7070), application=app, handler_class=WebSocketHandler) print("web server start ... ", flush=True) server.serve_forever() except Exception as e: print('error:',e, flush=True)
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/CircleCityCon/2021/pwn/worm_2/instance/build.py
ctfs/CircleCityCon/2021/pwn/worm_2/instance/build.py
import os import random import subprocess import shutil max_depth = int(os.environ["MAX_DEPTH"]) name = lambda i: i % 2 left_index = lambda i: 2 * i + 1 right_index = lambda i: 2 * i + 2 parent = lambda i: (i - 1) // 2 depth = lambda i: (i + 1).bit_length() def build_node(i): d = depth(i) os.chmod(".", 0o550) if d == max_depth: shutil.chown(".", f"user{d}", f"user{d}") else: shutil.chown(".", f"user{d}", f"user{d + 1}") shutil.copyfile(f"/keys/key{d + 1}", "./key") shutil.chown("./key", f"user{d + 1}", f"user{d}") os.chmod("./key", 0o4550) subprocess.run(["setcap", "cap_setuid,cap_setgid=ep", "./key"]) def build_tree(i=0): if depth(i) > max_depth: return os.mkdir(f"room{name(i)}") os.chdir(f"room{name(i)}") build_tree(left_index(i)) build_tree(right_index(i)) build_node(i) os.chdir("..") def plant_flag(): os.chdir("room0") while len(os.listdir()) > 0: os.chdir(f"room{random.randint(0, 1)}") os.rename("/flag.txt", "./flag.txt") print(f"[*] Building tree with {2 ** max_depth - 1} nodes ...") build_tree() print("[*] Planting flag in a random leaf node ...") plant_flag() print("[+] Ready")
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/CircleCityCon/2021/pwn/worm/instance/build.py
ctfs/CircleCityCon/2021/pwn/worm/instance/build.py
import os import random import subprocess import shutil max_depth = int(os.environ["MAX_DEPTH"]) name = lambda i: i % 2 left_index = lambda i: 2 * i + 1 right_index = lambda i: 2 * i + 2 parent = lambda i: (i - 1) // 2 depth = lambda i: (i + 1).bit_length() def build_node(i): d = depth(i) os.chmod(".", 0o550) if d == max_depth: shutil.chown(".", f"user{d}", f"user{d}") else: shutil.chown(".", f"user{d}", f"user{d + 1}") shutil.copyfile(f"/keys/key{d + 1}", "./key") shutil.chown("./key", f"user{d + 1}", f"user{d}") os.chmod("./key", 0o4550) subprocess.run(["setcap", "cap_setuid,cap_setgid=ep", "./key"]) def build_tree(i=0): if depth(i) > max_depth: return os.mkdir(f"room{name(i)}") os.chdir(f"room{name(i)}") build_tree(left_index(i)) build_tree(right_index(i)) build_node(i) os.chdir("..") def plant_flag(): os.chdir("room0") while len(os.listdir()) > 0: os.chdir(f"room{random.randint(0, 1)}") os.rename("/flag.txt", "./flag.txt") print(f"[*] Building tree with {2 ** max_depth - 1} nodes ...") build_tree() print("[*] Planting flag in a random leaf node ...") plant_flag() print("[+] Ready")
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/CircleCityCon/2021/rev/Lonk/flag-674073a02c07184baaa6973219490ef3.py
ctfs/CircleCityCon/2021/rev/Lonk/flag-674073a02c07184baaa6973219490ef3.py
from lib import * 覺(非(67)) 覺(要(非(34), 非(33))) 覺(要(放(非(105), 非(58)), 非(20))) 覺(屁(非(3), 非(41))) 覺(然(非(811), 非(234))) 覺(睡(非(3), 非(5), 非(191))) 覺( 放( 然( 屁( 屁( 屁( 屁( 屁( 屁( 屁( 屁( 屁( 屁( 屁(非(2), 非(2)), 非(2), ), 非(2), ), 非(2), ), 非(2), ), 非(2), ), 非(2), ), 非(2), ), 非(2), ), 非(2), ), 非(2), ), 非(1337), ), 非(1), ) ) 覺( 屁( 放( 屁(然(後(非(3), 非(9)), 非(555)), 非(2)), 非(464), ), 非(2), ) ) 覺(睡(非(2020), 非(451813409), 非(2350755551))) 覺( 睡( 非(1234567890), 非(9431297343284265593), 要(非(119), 非(17017780892086357584)), ) ) 覺( 屁( 睡(非(3), 放(非(60437), 非(1024)), 非(151553)), 睡( 非(3), 要( 屁( 非(5), 然( 屁( 屁( 屁(屁(非(10), 非(10)), 非(10)), 非(10), ), 非(10), ), 非(1337), ), ), 非(54103), ), 非(151553), ), ) ) 覺( 要( 睡( 非(111111111111111111111111111111111111), 非(222222222222222222222222222222222222), 非(333333333333333333333333333333333333), ), 屁(屁(非(2), 非(2)), 非(29)), ) ) 覺( 屁( 放( 後( 屁(要(非(1), 非(1)), 要(非(1), 非(1))), 非(2), ), 非(8), ), 睡(非(2), 非(7262490), 非(98444699)), ) ) 覺( 放( 屁(屁(屁(非(1337), 非(1337)), 非(1337)), 非(1337)), 非(3195402929666), ) ) 覺( 放( 然( 放( 非( 1000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000 ), 非(1), ), 非(100), ), 非(23), ) ) 覺( 放( 然(放(後(非(100), 非(100)), 非(1)), 非(100)), 非(50), ) ) 覺( 然( 要( 要( 要( 要( 要( 要( 要( 要( 要( 要( 要( 要( 要( 要( 要( 要( 要( 要( 要( 非( 1 ), 非( 2 ), ), 非( 3 ), ), 非(4), ), 非(5), ), 非(6), ), 非(7), ), 非(8), ), 非(9), ), 非(10), ), 非(11), ), 非(12), ), 非(13), ), 非(14), ), 非(15), ), 非(16), ), 非(17), ), 非(18), ), 非(19), ), 非(20), ), 非(132), ) ) 覺( 要( 放( 睡(非(1337), 非(1337), 要(非(1337), 非(1337))), 非(1336), ), 非(106), ) ) 覺(要(非(50), 非(1))) 覺( 要( 然( 放( 後( 後(後(非(10), 非(10)), 非(10)), 非(10) ), 非(1), ), 非(100), ), 非(1), ) ) 覺( 要( 放( 然( 放( 後(非(55555), 非(5)), 屁( 屁( 屁( 屁( 屁( 屁( 屁( 屁( 屁( 屁( 屁( 屁( 屁( 屁( 屁( 屁( 屁( 屁( 屁( 屁( 屁( 屁( 非( 1 ), 非( 2 ), ), 非( 3 ), ), 非( 4 ), ), 非( 5 ), ), 非( 6 ), ), 非( 7 ), ), 非( 8 ), ), 非( 9 ), ), 非( 10 ), ), 非(11), ), 非(12), ), 非(13), ), 非(14), ), 非(15), ), 非(16), ), 非(17), ), 非(18), ), 非(19), ), 非(20), ), 非(21), ), 非(22), ), 非(23), ), ), 非(1337), ), 非(200), ), 非(45), ) ) 覺(睡(非(6), 非(11333), 非(29959))) 覺( 放( 屁( 屁( 屁( 屁( 非(4), 非(4), ), 非(4), ), 非(4), ), 非(4), ), 非(975), ) ) 覺( 屁( 放( 要(放(要(非(3), 非(3)), 非(1)), 非(4)), 非(3), ), 放( 要(放(要(非(3), 非(3)), 非(1)), 非(4)), 非(3), ), ) ) 覺( 放( 睡( 睡(非(12345), 非(12345), 非(54321)), 非(12345), 非(54321), ), 非(3037), ) ) 覺(要(非(50), 非(3))) 覺(非(125)) print()
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/CircleCityCon/2021/rev/Lonk/lib-7f31611a11cc4383f173fae857587a59.py
ctfs/CircleCityCon/2021/rev/Lonk/lib-7f31611a11cc4383f173fae857587a59.py
class 我: def __init__(self, n=None): self.n = n def 非(a): h = 我() c = h while a > 0: c.n = 我() c = c.n a -= 1 return h.n def 常(a): i = 0 while a: i += 1 a = a.n return i def 需(a): h = 我() b = h while a: b.n = 我() b = b.n a = a.n return h.n def 要(a, b): h = 需(a) c = h while c.n: c = c.n c.n = 需(b) return h def 放(a, b): h = 需(a) c = h d = b while d: c = c.n d = d.n return c def 屁(a, b): h = 我() c = a while c: h = 要(h, b) c = c.n return h.n def 然(a, b): r = 需(b) c = r while c.n: c = c.n c.n = r d = r c = a while c.n: d = d.n c = c.n if id(d.n) == id(r): r = None else: d.n = None return r def 後(a, b): h = 我() c = b while c: h = 屁(h, a) c = c.n return h def 睡(a, b, m): return 然(後(a, b), m) def 覺(n): print(chr(常(n)), end="", flush=True)
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/CircleCityCon/2021/crypto/No_Stone_Left_Unturned/no-stone-left-unturned.py
ctfs/CircleCityCon/2021/crypto/No_Stone_Left_Unturned/no-stone-left-unturned.py
from gmpy2 import next_prime, is_prime import random, os, sys if __name__ == "__main__": random.seed(os.urandom(32)) p = next_prime(random.randrange((1<<1024), (1<<1024) + (1<<600))) pp = (p * 7) // 11 q = next_prime(random.randrange(pp - (1<<520), pp + (1 << 520))) with open(sys.argv[1], "rb") as f: flag = int.from_bytes(f.read(), "big") assert is_prime(p) assert is_prime(q) N = p * q assert flag < N e = 0x10001 c = pow(flag, e, N) with open("out.txt", "w") as f: f.write(f"N = {hex(N)}\n") f.write(f"e = {hex(e)}\n") f.write(f"c = {hex(c)}\n")
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/CircleCityCon/2021/crypto/Poison_Prime/server.py
ctfs/CircleCityCon/2021/crypto/Poison_Prime/server.py
import Crypto.Util.number as cun import Crypto.Random.random as crr import Crypto.Util.Padding as cup from Crypto.Cipher import AES import os import hashlib class DiffieHellman: def __init__(self, p: int): self.p = p self.g = 8 self.private_key = crr.getrandbits(128) def public_key(self) -> int: return pow(self.g, self.private_key, self.p) def shared_key(self, other_public_key: int) -> int: return pow(other_public_key, self.private_key, self.p) def get_prime() -> int: p = int(input("Please help them choose p: ")) q = int( input( "To prove your p isn't backdoored, " + "give me a large prime factor of (p - 1): " ) ) if ( cun.size(q) > 128 and p > q and (p - 1) % q == 0 and cun.isPrime(q) and cun.isPrime(p) ): return p else: raise ValueError("Invalid prime") def main(): print("Note: Your session ends in 30 seconds") message = "My favorite food is " + os.urandom(32).hex() print("Alice wants to send Bob a secret message") p = get_prime() alice = DiffieHellman(p) bob = DiffieHellman(p) shared_key = bob.shared_key(alice.public_key()) assert shared_key == alice.shared_key(bob.public_key()) aes_key = hashlib.sha1(cun.long_to_bytes(shared_key)).digest()[:16] cipher = AES.new(aes_key, AES.MODE_ECB) ciphertext = cipher.encrypt(cup.pad(message.encode(), 16)) print("Here's their encrypted message: " + ciphertext.hex()) guess = input("Decrypt it and I'll give you the flag: ") if guess == message: print("Congrats! Here's the flag: " + os.environ["FLAG"]) else: print("That's wrong dingus") if __name__ == "__main__": try: main() except ValueError as e: print(e)
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/CircleCityCon/2021/crypto/Baby_Meadows/baby-meadows.py
ctfs/CircleCityCon/2021/crypto/Baby_Meadows/baby-meadows.py
from Crypto.Util.number import getStrongPrime import sys, random; random.seed(0x1337) def generate_key(): p = getStrongPrime(2048) q = (p - 1) // 2 for g in range(2, p - 1): if pow(g, 2, p) != 1 and pow(g, q, p) != 1: return g, p def encrypt(msg): g, p = generate_key() yield (g, p) for m in msg: yield (m * pow(g, random.randrange(2, p - 1), p)) % p if __name__ == "__main__": with open(sys.argv[1], "rb") as f: flag = f.read() print(list(encrypt(flag)))
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/CircleCityCon/2021/web/Sticky_Notes/apps/web/notes.py
ctfs/CircleCityCon/2021/web/Sticky_Notes/apps/web/notes.py
import socket from socketserver import ThreadingTCPServer, StreamRequestHandler import time from email.utils import formatdate from pathlib import Path import re import os port = 3101 header_template = """HTTP/1.1 {status_code} OK\r Date: {date}\r Content-Length: {content_length}\r Connection: keep-alive\r Content-Type: text/plain; charset="utf-8"\r \r """ filepath_re = re.compile(r"[^a-z0-9-/]") def http_header(s: str, status_code: int): return header_template.format( status_code=status_code, date=formatdate(timeval=None, localtime=False, usegmt=True), content_length=len(s), ).encode() def client_str(req): ip = req.client_address[0] port = req.client_address[1] return f"{ip}:{port}" def iter_chunks(xs, n=1448): """Yield successive n-sized chunks from xs""" for i in range(0, len(xs), n): yield xs[i : i + n] class MyTCPServer(ThreadingTCPServer): def server_bind(self): self.socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) self.socket.setsockopt(socket.SOL_SOCKET, socket.SO_KEEPALIVE, 1) self.socket.setsockopt(socket.IPPROTO_TCP, socket.TCP_KEEPIDLE, 10) self.socket.setsockopt(socket.IPPROTO_TCP, socket.TCP_KEEPINTVL, 3) self.socket.setsockopt(socket.IPPROTO_TCP, socket.TCP_KEEPCNT, 5) self.socket.bind(self.server_address) class TcpHandler(StreamRequestHandler): def on_disconnect(self): print(f"[*] Disconnected {client_str(self)}") def send_401(self): error = "Unauthorized" self.wfile.write(http_header(error, 401)) self.wfile.write(error.encode()) def send_404(self): error = "Not Found" self.wfile.write(http_header(error, 404)) self.wfile.write(error.encode()) def send_file(self, filepath): if not filepath.is_file(): self.send_404() return content = open(filepath, "rb").read() self.wfile.write(http_header(content.decode(), 200)) for chunk in iter_chunks(content): self.wfile.write(chunk) time.sleep(0.1) def has_token(self): ans = False while True: header = self.rfile.readline().decode().strip() if len(header) == 0: break elif header.startswith("Cookie:"): ans = os.environ["TOKEN"] in header return ans def route_flag(self): if self.has_token(): flag = os.environ["FLAG"] self.wfile.write(http_header(flag, 200)) self.wfile.write(flag.encode()) else: self.send_401() def route_note(self, route): # Discard the rest of the request while len(self.rfile.readline().strip()) != 0: pass filepath = Path("/tmp/boards") / route self.send_file(filepath) def handle(self): try: while True: line = self.rfile.readline().strip().decode() if len(line) == 0: self.on_disconnect() return print(f"[*] {line} {client_str(self)}") route = line.split()[1] route = filepath_re.sub("", route).strip("/") if route == "flag": self.route_flag() else: self.route_note(route) except ConnectionError as e: print(f"[-] {e} {client_str(self)}") self.on_disconnect() return if __name__ == "__main__": tcp = MyTCPServer(("0.0.0.0", port), TcpHandler) print(f"[*] Listening on port {port} ...") tcp.serve_forever()
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/CircleCityCon/2021/web/Sticky_Notes/apps/web/boards.py
ctfs/CircleCityCon/2021/web/Sticky_Notes/apps/web/boards.py
import uvicorn from fastapi import FastAPI, Request, HTTPException from fastapi.staticfiles import StaticFiles from fastapi.responses import FileResponse, RedirectResponse, JSONResponse from slowapi import Limiter, _rate_limit_exceeded_handler from slowapi.util import get_remote_address from slowapi.errors import RateLimitExceeded from pydantic import BaseModel, BaseSettings, Field from pathlib import Path import uuid import os import requests app = FastAPI() static_path = Path(__file__).parent.absolute() / "static" app.mount("/static", StaticFiles(directory=str(static_path)), name="static") tmp_path = Path("/tmp/boards/") limiter = Limiter(key_func=get_remote_address) app.state.limiter = limiter app.add_exception_handler(RateLimitExceeded, _rate_limit_exceeded_handler) @app.get("/") def index(): return FileResponse(str(static_path / "index.html")) @app.get("/create_board") def create_board(): board_id = uuid.uuid4() os.mkdir(tmp_path / str(board_id)) url = app.url_path_for("board", id=str(board_id)) return RedirectResponse(url=url) @app.get("/board/{id}") def board(id: uuid.UUID): if (tmp_path / str(id)).is_dir(): return FileResponse(str(static_path / "board.html")) else: raise HTTPException(status_code=404, detail="That board doesn't exist") @app.exception_handler(OSError) def os_error_handler(request: Request, e: OSError): return JSONResponse(status_code=400, content={"message": str(e)}) @app.get("/board/{id}/notes") def notes(id: uuid.UUID): return sorted(os.listdir(tmp_path / str(id))) class NoteForm(BaseModel): id: uuid.UUID body: str = Field(None, min_length=1, max_length=20480) @app.post("/board/add_note") def add_note(form: NoteForm): data = notes(form.id) or [] if len(data) >= 9: raise HTTPException( status_code=400, detail="You can't have more than 9 notes on a board" ) filename = "note" + str(len(data)) filepath = tmp_path / str(form.id) / filename open(filepath, "w").write(form.body) return filename @app.get("/board/{id}/report") @limiter.limit("3/minute") def report(request: Request, id: uuid.UUID): bot_res = requests.get(f"http://127.0.0.1:3102/visit/{id}") if bot_res.status_code != 200: raise HTTPException( status_code=400, detail="The admin bot had issues reviewing the board" ) if __name__ == "__main__": uvicorn.run("boards:app", host="0.0.0.0", port=3100, workers=4)
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/Tenable/2022/crypto/DIY_Crypto/crypt.py
ctfs/Tenable/2022/crypto/DIY_Crypto/crypt.py
# We wrote our own crypto... They won't even know where to begin! import random # AES is supposed to be good? We can steal their sbox then. sbox = ( 0x63, 0x7C, 0x77, 0x7B, 0xF2, 0x6B, 0x6F, 0xC5, 0x30, 0x01, 0x67, 0x2B, 0xFE, 0xD7, 0xAB, 0x76, 0xCA, 0x82, 0xC9, 0x7D, 0xFA, 0x59, 0x47, 0xF0, 0xAD, 0xD4, 0xA2, 0xAF, 0x9C, 0xA4, 0x72, 0xC0, 0xB7, 0xFD, 0x93, 0x26, 0x36, 0x3F, 0xF7, 0xCC, 0x34, 0xA5, 0xE5, 0xF1, 0x71, 0xD8, 0x31, 0x15, 0x04, 0xC7, 0x23, 0xC3, 0x18, 0x96, 0x05, 0x9A, 0x07, 0x12, 0x80, 0xE2, 0xEB, 0x27, 0xB2, 0x75, 0x09, 0x83, 0x2C, 0x1A, 0x1B, 0x6E, 0x5A, 0xA0, 0x52, 0x3B, 0xD6, 0xB3, 0x29, 0xE3, 0x2F, 0x84, 0x53, 0xD1, 0x00, 0xED, 0x20, 0xFC, 0xB1, 0x5B, 0x6A, 0xCB, 0xBE, 0x39, 0x4A, 0x4C, 0x58, 0xCF, 0xD0, 0xEF, 0xAA, 0xFB, 0x43, 0x4D, 0x33, 0x85, 0x45, 0xF9, 0x02, 0x7F, 0x50, 0x3C, 0x9F, 0xA8, 0x51, 0xA3, 0x40, 0x8F, 0x92, 0x9D, 0x38, 0xF5, 0xBC, 0xB6, 0xDA, 0x21, 0x10, 0xFF, 0xF3, 0xD2, 0xCD, 0x0C, 0x13, 0xEC, 0x5F, 0x97, 0x44, 0x17, 0xC4, 0xA7, 0x7E, 0x3D, 0x64, 0x5D, 0x19, 0x73, 0x60, 0x81, 0x4F, 0xDC, 0x22, 0x2A, 0x90, 0x88, 0x46, 0xEE, 0xB8, 0x14, 0xDE, 0x5E, 0x0B, 0xDB, 0xE0, 0x32, 0x3A, 0x0A, 0x49, 0x06, 0x24, 0x5C, 0xC2, 0xD3, 0xAC, 0x62, 0x91, 0x95, 0xE4, 0x79, 0xE7, 0xC8, 0x37, 0x6D, 0x8D, 0xD5, 0x4E, 0xA9, 0x6C, 0x56, 0xF4, 0xEA, 0x65, 0x7A, 0xAE, 0x08, 0xBA, 0x78, 0x25, 0x2E, 0x1C, 0xA6, 0xB4, 0xC6, 0xE8, 0xDD, 0x74, 0x1F, 0x4B, 0xBD, 0x8B, 0x8A, 0x70, 0x3E, 0xB5, 0x66, 0x48, 0x03, 0xF6, 0x0E, 0x61, 0x35, 0x57, 0xB9, 0x86, 0xC1, 0x1D, 0x9E, 0xE1, 0xF8, 0x98, 0x11, 0x69, 0xD9, 0x8E, 0x94, 0x9B, 0x1E, 0x87, 0xE9, 0xCE, 0x55, 0x28, 0xDF, 0x8C, 0xA1, 0x89, 0x0D, 0xBF, 0xE6, 0x42, 0x68, 0x41, 0x99, 0x2D, 0x0F, 0xB0, 0x54, 0xBB, 0x16 ) # easy key scheduling def rotate_key_left(key): tmp = bytearray(key[1:]) tmp.append(key[0]) return bytes(tmp) # easy crypto def crypt_block(block, key): global sbox retval = bytearray() for i in range(0,16): retval.append(sbox[block[i] ^ key[i]]) return bytes(retval) fh = open("plaintext.txt", 'rb') plaintext = fh.read() fh.close() BLOCK_SIZE = 16 plaintext_padded = plaintext + (BLOCK_SIZE - (len(plaintext) % BLOCK_SIZE)) * b'\x00' random_key = bytes([random.randrange(0, 256) for _ in range(0, 16)]) block_count = int(len(plaintext_padded) / 16) print("encrypting %d blocks..." % block_count) print("using key %s" % random_key.hex()) cur_key = random_key crypted = b"" for i in range(block_count): block = plaintext_padded[i*16:i*16 + 16] crypted += crypt_block(block, cur_key) cur_key = rotate_key_left(cur_key) print("writing crypted to file...") fh = open("crypted.txt", 'wb') fh.write(crypted) fh.close()
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/Tenable/2022/crypto/Wifi_Password_of_The_Day/wifi.py
ctfs/Tenable/2022/crypto/Wifi_Password_of_The_Day/wifi.py
import zlib import json from Crypto.Cipher import AES import logging from twisted.internet.protocol import Protocol, Factory from twisted.internet import reactor import base64 # wifi password current_wifi_password = "flag{test_123}" # 128 bit key encryption_key = b'testing123456789' def encrypt_wifi_data(user): global current_wifi_password, encryption_key wifi_data = {"user:": user, "pass:": current_wifi_password} to_send = json.dumps(wifi_data) msg = zlib.compress(to_send.encode('utf-8')) text_padded = msg + (AES.block_size - (len(msg) % AES.block_size)) * b'\x00' logging.info("sending wifi password to user %s" + user) iv = 16 * b'\x00' cipher = AES.new(encryption_key, AES.MODE_CBC, iv) cipher_enc = cipher.encrypt(text_padded) return cipher_enc class Challenge(Protocol): def dataReceived(self, data): username = data.strip() data = encrypt_wifi_data(username.decode('utf-8')) self.transport.write(base64.b64encode(data) + b'\r\n') self.transport.write(b"Enter username: ") def connectionMade(self): self.transport.write(b"Welcome to Wifi Password of the Day Server\r\n") self.transport.write(b"Enter username: ") def __init__(self, factory): self.factory = factory self.debug = True class ChallengeFactory(Factory): protocol = Challenge def buildProtocol(self, addr): return Challenge(self) reactor.listenTCP(1234, ChallengeFactory()) reactor.run()
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/HackersPlayground/2023/misc/pyJail/jail.py
ctfs/HackersPlayground/2023/misc/pyJail/jail.py
import string flag = open("./flag.txt").read() code = input("makeflag> ")[:100] if any(c not in string.printable for c in code): print("🙅") elif "__" in code: print("__nope__") else: if flag == eval(code, {"__builtins__": {}}, {"__builtins__": {}}): print("Oh, you know flag") else: print("Nope")
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/HackersPlayground/2023/crypto/meaas/montgomery.py
ctfs/HackersPlayground/2023/crypto/meaas/montgomery.py
from math import gcd from functools import reduce from logger import Logger, noLog class Montgomery: def __init__(self, modulus, log=noLog): self.n = modulus self.R = (1 << modulus.bit_length())# % modulus if gcd(self.n, self.R) != 1: raise Exception("[Err] Invalid modulus.") self.np = self.R - pow(self.n, -1, self.R) #N': NN' = -1 mod R self.log=log def reduce(self, x): u = ((x % self.R) * self.np) % self.R t = (x + u * self.n) // self.R if t >= self.n: self.log.Verbose("[Montgomery] Extra reduction") return t - self.n else: return t def toMontgo(self, i): return (i * self.R) % self.n def redc(self, i): return self.reduce(i) def mul(self, x, y): return self.reduce(x*y) def modExp(b, e, n, log=noLog): log.Info("[modExp] Normal -> Montgomery form...") m = Montgomery(n, log) r0 = m.toMontgo(1) r1 = m.toMontgo(b) l = e.bit_length() log.Info("[modExp] Repeated squaring") for i in range(l - 1, -1, -1): r0 = m.mul(r0, r0) if (e >> i) & 1 == 1: r0 = m.mul(r0, r1) log.Info("[modExp] Montgomery form -> Normal...") res = m.redc(r0) return res def _modInv(a, b, log=noLog): if b == 1: return 1 b0 = b x0, x1 = 0, 1 while a > 1: q = a // b a, b = b, a % b x0, x1 = x1 - q * x0, x0 if x1 < 0: x1 += b0 return x1 def _crt(n, a, log=noLog): res = 0 prod = reduce(lambda a, b: a* b, n) for ni, ai in zip(n, a): p = prod // ni log.Info("CRT: modular inverse") res += ai * _modInv(p, ni, log) * p return res % prod def rsa_crt(c, d, p, q, log=noLog): log.Info("RSA CRT start.") log.Info("c1 = pow(c, d, p)") c1 = modExp(c % p, d % (p - 1), p, log) log.Info("c2 = pow(c, d, q)") c2 = modExp(c % q, d % (q - 1), q, log) log.Info("Applying CRT operation..") res = _crt([p, q], [c1, c2], log) return res
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/HackersPlayground/2023/crypto/meaas/logger.py
ctfs/HackersPlayground/2023/crypto/meaas/logger.py
from sys import stdout, stderr class Logger: verbose, info, warning, error, none = 0, 1, 2, 3, 4 def __init__(self, loglevel=0, output=None): if type(output) is str: self.fp = open(output, "w") self.isStrPath = True else: self.fp = output self.isStrPath = False self.loglevel = loglevel def Log(self, level, msg, prefix=None): if self.loglevel <= level: if prefix: self.fp.write(prefix) if type(msg) is str: self.fp.write(msg + '\n') else: self.fp.write(msg.decode() + '\n') def Error(self, msg): self.Log(self.error, msg, prefix = "[Err] ") def Warning(self, msg): self.Log(self.warning, msg, prefix = "[Warn] ") def Info(self, msg): self.Log(self.info, msg, prefix = "[Info] ") def Verbose(self, msg): self.Log(self.verbose, msg, prefix = "[Verbose] ") def Close(self): if self.isStrPath: self.fp.close() noLog = Logger(Logger.none, "/dev/null")
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/HackersPlayground/2023/crypto/meaas/app.py
ctfs/HackersPlayground/2023/crypto/meaas/app.py
from flask import Flask, request, render_template, jsonify from tempfile import NamedTemporaryFile from types import SimpleNamespace from os import remove from Crypto.Util.number import getPrime, long_to_bytes from hashlib import sha512 from logger import Logger from montgomery import rsa_crt, modExp import json rsa_keysize = 1024 flag = open('flag.txt', "rb").read() app = Flask(__name__, static_url_path='', static_folder='static') ## RSA parameter setup try: with open("/secret/rsaparams", "r") as f: rsa = json.load(f, object_hook = lambda x: SimpleNamespace(**x)) if (rsa.n.bit_length() != rsa_keysize): raise Exception() except Exception: rsa = SimpleNamespace() rsa.p = getPrime(rsa_keysize // 2) rsa.q = getPrime(rsa_keysize // 2) rsa.e = getPrime(rsa_keysize // 2) rsa.n = rsa.p * rsa.q rsa.d = pow(rsa.e, -1, (rsa.p - 1) * (rsa.q - 1)) ## treasure and hint! xor = lambda a, b: bytes([x^y for x, y in zip(a, b)]) rsa.treasure = int(xor(sha512(long_to_bytes(rsa.d)).digest(), flag).hex(), 16) hint = bin(rsa.p)[2:5] ## index page @app.route('/') def index(): return render_template('index.html', rsa=rsa, hint=hint) ## modular exponentiation request handler @app.route('/modexp', methods=['POST']) def modexp(): try: data = request.json base = int(data["base"]) exp = rsa.d if data["use_d"] else int(data["exp"]) mod = rsa.n if data["use_n"] else int(data["mod"]) loglevel = int(data["loglevel"]) logfile = NamedTemporaryFile(prefix="modexp", mode="w", delete=False) logger = Logger(loglevel, logfile) if mod == rsa.n: result = rsa_crt(base, exp, rsa.p, rsa.q, logger) else: #chcek modulus size to prevent DoS attack if mod.bit_length() > rsa_keysize: raise Exception() result = modExp(base, exp, mod, logger) logfile.close() log = open(logfile.name).read() remove(logfile.name) return jsonify({"status": "success", "res": str(result), "log": log}) except Exception: return jsonify({"status": "fail", "res": "Something wrong", "log": ""}) if __name__ == "__main__": app.run(debug=False)
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/HackersPlayground/2023/crypto/RC_four/challenge.py
ctfs/HackersPlayground/2023/crypto/RC_four/challenge.py
from Crypto.Cipher import ARC4 from secret import key, flag from binascii import hexlify #RC4 encrypt function with "key" variable. def encrypt(data): #check the key is long enough assert(len(key) > 128) #make RC4 instance cipher = ARC4.new(key) #We don't use the first 1024 bytes from the key stream. #Actually this is not important for this challenge. Just ignore. cipher.encrypt("0"*1024) #encrypt given data, and return it. return cipher.encrypt(data) msg = "RC4 is a Stream Cipher, which is very simple and fast." print (hexlify(encrypt(msg)).decode()) print (hexlify(encrypt(flag)).decode())
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/HackersPlayground/2023/crypto/RSA_101/challenge.py
ctfs/HackersPlayground/2023/crypto/RSA_101/challenge.py
from base64 import b64encode, b64decode from Crypto.Util.number import getStrongPrime, bytes_to_long, long_to_bytes from os import system p = getStrongPrime(512) q = getStrongPrime(512) n = p * q e = 65537 d = pow(e, -1, (p - 1) * (q - 1)) print("[RSA parameters]") print("n =", hex(n)) print("e =", hex(e)) def sign(msg): m = bytes_to_long(msg) s = pow(m, d, n) return long_to_bytes(s) def verify(s): s = bytes_to_long(s) v = pow(s, e, n) return long_to_bytes(v) def welcome(): print("\nWelcome to command signer/executor.") print("Menu : 1. Verify and run the signed command") print(" 2. Generate a signed command") print(" 3. Base64 encoder") print(" 4. Exit") while True: welcome() sel = input(" > ").strip() if sel == "1": sgn = input("Signed command: ").strip() sgn = b64decode(sgn) cmd = verify(sgn) commands = ["ls -l", "pwd", "id", "cat flag"] if cmd.decode() in commands: system(cmd) else: print("Possible commands: ", commands) elif sel == "2": cmd = input("Base64 encoded command to sign: ") cmd = b64decode(cmd) if cmd == b"cat flag": print("It's forbidden.") else: print("Signed command:", b64encode(sign(cmd)).decode()) elif sel == "3": cmd = input("String to encode: ").strip().encode() print("Base64 encoded string:", b64encode(cmd).decode()) elif sel == "4": print("bye.") exit() else: print("Invalid selection.")
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/BlueHens/2021/crypto/aHead_Of_The_curve/secdsa.py
ctfs/BlueHens/2021/crypto/aHead_Of_The_curve/secdsa.py
#Elliptic curve basics, tools for finding rational points, and ECDSA implementation. #Brendan Cordy, 2015 from fractions import Fraction from math import ceil, sqrt from random import SystemRandom, randrange from hashlib import sha256 from time import time import pyotp import datetime #Affine Point (+Infinity) on an Elliptic Curve --------------------------------------------------- class Point(object): #Construct a point with two given coordindates. def __init__(self, x, y): self.x, self.y = x, y self.inf = False #Construct the point at infinity. @classmethod def atInfinity(cls): P = cls(0, 0) P.inf = True return P #The secp256k1 generator. @classmethod def secp256k1(cls): return cls(55066263022277343669578718895168534326250603453777594175500187360389116729240, 32670510020758816978083085130507043184471273380659243275938904335757337482424) def __str__(self): if self.inf: return 'Inf' else: return '(' + str(self.x) + ',' + str(self.y) + ')' def __eq__(self,other): if self.inf: return other.inf elif other.inf: return self.inf else: return self.x == other.x and self.y == other.y def is_infinite(self): return self.inf #Elliptic Curves over any Field ------------------------------------------------------------------ class Curve(object): #Set attributes of a general Weierstrass cubic y^2 = x^3 + ax^2 + bx + c over any field. def __init__(self, a, b, c, char, exp): self.a, self.b, self.c = a, b, c self.char, self.exp = char, exp print(self) f = open("otp_seed.txt", "r") seed = f.readline().strip() f.close() self.hotp = pyotp.HOTP(seed) def __str__(self): #Cases for 0, 1, -1, and general coefficients in the x^2 term. if self.a == 0: aTerm = '' elif self.a == 1: aTerm = ' + x^2' elif self.a == -1: aTerm = ' - x^2' elif self.a < 0: aTerm = " - " + str(-self.a) + 'x^2' else: aTerm = " + " + str(self.a) + 'x^2' #Cases for 0, 1, -1, and general coefficients in the x term. if self.b == 0: bTerm = '' elif self.b == 1: bTerm = ' + x' elif self.b == -1: bTerm = ' - x' elif self.b < 0: bTerm = " - " + str(-self.b) + 'x' else: bTerm = " + " + str(self.b) + 'x' #Cases for 0, 1, -1, and general coefficients in the constant term. if self.c == 0: cTerm = '' elif self.c < 0: cTerm = " - " + str(-self.c) else: cTerm = " + " + str(self.c) #Write out the nicely formatted Weierstrass equation. self.eq = 'y^2 = x^3' + aTerm + bTerm + cTerm #Print prettily. if self.char == 0: return self.eq + ' over Q' elif self.exp == 1: return self.eq + ' over ' + 'F_' + str(self.char) else: return self.eq + ' over ' + 'F_' + str(self.char) + '^' + str(self.exp) #Compute the discriminant. def discriminant(self): a, b, c = self.a, self.b, self.c return -4*a*a*a*c + a*a*b*b + 18*a*b*c - 4*b*b*b - 27*c*c #Compute the order of a point on the curve. def order(self, P): Q = P orderP = 1 #Add P to Q repeatedly until obtaining the identity (point at infinity). while not Q.is_infinite(): Q = self.add(P,Q) orderP += 1 return orderP #List all multiples of a point on the curve. def generate(self, P): Q = P orbit = [str(Point.atInfinity())] #Repeatedly add P to Q, appending each (pretty printed) result. while not Q.is_infinite(): orbit.append(str(Q)) Q = self.add(P,Q) return orbit #Double a point on the curve. def double(self, P): return self.add(P,P) #Add P to itself k times. def mult(self, P, k): if P.is_infinite(): return P elif k == 0: return Point.atInfinity() elif k < 0: return self.mult(self.invert(P), -k) else: #Convert k to a bitstring and use peasant multiplication to compute the product quickly. b = bin(k)[2:] return self.repeat_additions(P, b, 1) #Add efficiently by repeatedly doubling the given point, and adding the result to a running #total when, after the ith doubling, the ith digit in the bitstring b is a one. def repeat_additions(self, P, b, n): if b == '0': return Point.atInfinity() elif b == '1': return P elif b[-1] == '0': return self.repeat_additions(self.double(P), b[:-1], n+1) elif b[-1] == '1': return self.add(P, self.repeat_additions(self.double(P), b[:-1], n+1)) #Returns a pretty printed list of points. def show_points(self): return [str(P) for P in self.get_points()] #Generate a secure OTP based on minutes and seconds with a 10 second slack def getRandomOTP(self): now = datetime.datetime.now() return int(self.hotp.at( (now.minute + 1) * (now.second // 10) )) #Elliptic Curves over Prime Order Fields --------------------------------------------------------- class CurveOverFp(Curve): #Construct a Weierstrass cubic y^2 = x^3 + ax^2 + bx + c over Fp. def __init__(self, a, b, c, p): Curve.__init__(self, a, b, c, p, 1) #The secp256k1 curve. @classmethod def secp256k1(cls): return cls(0, 0, 7, 2**256-2**32-2**9-2**8-2**7-2**6-2**4-1) def contains(self, P): if P.is_infinite(): return True else: # print('\t', (P.y*P.y) % self.char) # print('\t', (P.x*P.x*P.x + self.a*P.x*P.x + self.b*P.x + self.c) % self.char ) return (P.y*P.y) % self.char == (P.x*P.x*P.x + self.a*P.x*P.x + self.b*P.x + self.c) % self.char def get_points(self): #Start with the point at infinity. points = [Point.atInfinity()] #Just brute force the rest. for x in range(self.char): for y in range(self.char): P = Point(x,y) if (y*y) % self.char == (x*x*x + self.a*x*x + self.b*x + self.c) % self.char: points.append(P) return points def invert(self, P): if P.is_infinite(): return P else: return Point(P.x, -P.y % self.char) def add(self, P_1, P_2): #Adding points over Fp and can be done in exactly the same way as adding over Q, #but with of the all arithmetic now happening in Fp. y_diff = (P_2.y - P_1.y) % self.char x_diff = (P_2.x - P_1.x) % self.char if P_1.is_infinite(): return P_2 elif P_2.is_infinite(): return P_1 elif x_diff == 0 and y_diff != 0: return Point.atInfinity() elif x_diff == 0 and y_diff == 0: if P_1.y == 0: return Point.atInfinity() else: ld = ((3*P_1.x*P_1.x + 2*self.a*P_1.x + self.b) * mult_inv(2*P_1.y, self.char)) % self.char else: ld = (y_diff * mult_inv(x_diff, self.char)) % self.char nu = (P_1.y - ld*P_1.x) % self.char x = (ld*ld - self.a - P_1.x - P_2.x) % self.char y = (-ld*x - nu) % self.char return Point(x,y) #Extended Euclidean algorithm. def euclid(sml, big): #When the smaller value is zero, it's done, gcd = b = 0*sml + 1*big. if sml == 0: return (big, 0, 1) else: #Repeat with sml and the remainder, big%sml. g, y, x = euclid(big % sml, sml) #Backtrack through the calculation, rewriting the gcd as we go. From the values just #returned above, we have gcd = y*(big%sml) + x*sml, and rewriting big%sml we obtain #gcd = y*(big - (big//sml)*sml) + x*sml = (x - (big//sml)*y)*sml + y*big. return (g, x - (big//sml)*y, y) #Compute the multiplicative inverse mod n of a with 0 < a < n. def mult_inv(a, n): g, x, y = euclid(a, n) #If gcd(a,n) is not one, then a has no multiplicative inverse. if g != 1: raise ValueError('multiplicative inverse does not exist') #If gcd(a,n) = 1, and gcd(a,n) = x*a + y*n, x is the multiplicative inverse of a. else: return x % n #ECDSA functions --------------------------------------------------------------------------------- #Use sha256 to hash a message, and return the hash value as an interger. def hash(message): # return int(sha256(message).hexdigest(), 16) return int(sha256(str(message).encode('utf-8')).hexdigest(), 16) #Hash the message and return integer whose binary representation is the the L leftmost bits #of the hash value, where L is the bit length of n. def hash_and_truncate(message, n): h = hash(message) b = bin(h)[2:len(bin(n))] return int(b, 2) #Generate a keypair using the point P of order n on the given curve. The private key is a #positive integer d smaller than n, and the public key is Q = dP. def generate_keypair(curve, P, n): sysrand = SystemRandom() d = sysrand.randrange(1, n) Q = curve.mult(P, d) return (d, Q) #Create a digital signature for the string message using a given curve with a distinguished #point P which generates a prime order subgroup of size n. def sign(message, curve, P, n, keypair): #Extract the private and public keys, and compute z by hashing the message. d, Q = keypair # 130,(1341,1979) z = hash_and_truncate(message, n) # 0xfb #Choose a randomly selected secret point kP then compute r and s. r, s = 0, 0 while r == 0 or s == 0: k = curve.getRandomOTP() R = curve.mult(P, k) r = R.x % n s = (mult_inv(k, n) * (z + r*d)) % n print('ECDSA sig of \"' + message+ '\" : (Q, r, s) = (' + str(Q) + ', ' + str(r) + ', ' + str(s) + ')') return (Q, r, s) #Verify the string message is authentic, given an ECDSA signature generated using a curve with #a distinguished point P that generates a prime order subgroup of size n. def verify(message, curve, P, n, sig): Q, r, s = sig #Confirm that Q is on the curve. if Q.is_infinite() or not curve.contains(Q): return False #Confirm that Q has order that divides n. if not curve.mult(Q,n).is_infinite(): return False #Confirm that r and s are at least in the acceptable range. if r > n or s > n: return False #Compute z in the same manner used in the signing procedure, #and verify the message is authentic. z = hash_and_truncate(message, n) w = mult_inv(s, n) % n u_1, u_2 = z * w % n, r * w % n C_1, C_2 = curve.mult(P, u_1), curve.mult(Q, u_2) C = curve.add(C_1, C_2) return r % n == C.x % n
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/BlueHens/2021/crypto/hot_diggity_dog_2/unbreakable.py
ctfs/BlueHens/2021/crypto/hot_diggity_dog_2/unbreakable.py
from Crypto.Util.number import * from os import urandom from gmpy2 import iroot def getKey(): e = 3 t = 3 N = 3 while not GCD(e,t) == 1 or (inverse(e,t)**4)*3 < N or inverse(e,t) < iroot(N,3)[0]: p = getStrongPrime(1024) q = getStrongPrime(1024) N = p*q t = (p-1)*(q-1) e = bytes_to_long(urandom(256)) return N,e def encrypt(pt,N,e): try: pt = bytes(pt,'utf-8') except: pass assert bytes(pt) == pt,"ERROR: plaintext must be string or byte string!" pt = bytes_to_long(pt) return pow(pt,e,N) N,e = getKey() f = open("flag.txt") pt = f.read() f.close() f = open("output.txt",'w') ct = encrypt(pt,N,e) output = "ct="+ str(ct) + "\n\ne="+str(e) + "\n\nN=" + str(N) f.write(output) f.close()
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/BlueHens/2021/crypto/hot_diggity_dog/hot_diggity_dog.py
ctfs/BlueHens/2021/crypto/hot_diggity_dog/hot_diggity_dog.py
from Crypto.Util.number import * from os import urandom def getKey(): e = 3 t = 3 while not GCD(e,t) == 1: p = getStrongPrime(1024) q = getStrongPrime(1024) N = p*q t = (p-1)*(q-1) e = bytes_to_long(urandom(256)) return N,e def encrypt(pt,N,e): try: pt = bytes(pt,'utf-8') except: pass assert bytes(pt) == pt,"ERROR: plaintext must be string or byte string!" pt = bytes_to_long(pt) return pow(pt,e,N) N,e = getKey() f = open("flag.txt") pt = f.read() f.close() f = open("output.txt",'w') ct = encrypt(pt,N,e) output = "ct="+ str(ct) + "\n\ne="+str(e) + "\n\nN=" + str(N) f.write(output) f.close()
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/BlueHens/2023/misc/Python_Jail/chall.py
ctfs/BlueHens/2023/misc/Python_Jail/chall.py
#!/usr/bin/env python blacklist = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789" security_check = lambda s: any(c in blacklist for c in s) and s.count('_') < 50 def main(): while True: cmds = input("> ") if security_check(cmds): print("nope.") else: exec(cmds, {'__builtins__': None}, {}) 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/BlueHens/2023/misc/Defective_Client/graph.py
ctfs/BlueHens/2023/misc/Defective_Client/graph.py
import typing import json import functools from random import SystemRandom import itertools import base64 class UndirectedAdjacencyMatrix(): matrix: typing.Tuple[typing.Tuple[int, ...], ...] _len: int = 0 @classmethod def from_compressed(cls, vertices: int, compressed: typing.Tuple[bool, ...])->"UndirectedAdjacencyMatrix": matrix = [] idx = 0 for v in range(vertices): matrix.append(compressed[idx:idx+(vertices - v)]) idx += (vertices - v) matrix = tuple(map(tuple,matrix)) output = cls(vertices,[]) output.matrix = matrix output._len = sum(map(int,compressed)) return output def __init__(self, vertices: int, edges: typing.Iterable[typing.Tuple[int,int]]): matrix = [] for v in range(vertices): matrix.append([False for _ in range(v,vertices)]) for u, v in edges: row, col = min((u, v)), max((u, v)) matrix[row][col - row] = True self._len += 1 self.matrix = tuple(map(tuple,matrix)) def compressed(self)->typing.Tuple[int, typing.Tuple[bool,...]]: output = [] for row in self.matrix: output.extend(row) return len(self.matrix), tuple(output) def __contains__(self, item: typing.Tuple[int,int])->bool: row, col = min(item), max(item) - min(item) if row < len(self.matrix) and col < len(self.matrix[row]): return self.matrix[row][col] else: raise ValueError(f"Edge {(row, col + row)} cannot exist in graph with {len(self.matrix)} vertices!") def __iter__(self)->"UndirectedAdjacencyMatrix": self._row = 0 self._col = 0 return self def __next__(self)->int: if self._row >= len(self.matrix): raise StopIteration() while not self.matrix[self._row][self._col]: if self._col >= len(self.matrix[self._row])-1: self._col = 0 self._row += 1 else: self._col += 1 if self._row >= len(self.matrix): raise StopIteration() row, col = self._row, self._col if self._col >= len(self.matrix[self._row])-1: self._col = 0 self._row += 1 else: self._col += 1 return (row, col + row) def __len__(self)->int: return self._len def __eq__(self,other: "UndirectedAdjacencyMatrix"): if len(self.matrix) != len(other.matrix): return False output = True for row1, row2 in zip(self.matrix,other.matrix): output = output and functools.reduce(lambda x, y: x and y,[i == j for i, j in zip(row1,row2)]) return output def __repr__(self): return repr(self.matrix) def __getitem__(self, idx: int)->typing.Iterable[int]: for b, i in zip(self.matrix[idx],itertools.count()): if b: yield (idx, idx+i) for row, i in zip(self.matrix[:idx],range(idx)): if row[idx-i]: yield (idx, i) class Graph(): vertices: range edges: UndirectedAdjacencyMatrix @classmethod def from_dict(cls, dct: dict)->"Graph": vertices = dct["V"] E = [] decoded_E = int.from_bytes(base64.urlsafe_b64decode(dct['E']),'big') for edge in range(((vertices * (vertices - 1))//2) + vertices): E.insert(0,bool(decoded_E & 1<<edge)) adj = UndirectedAdjacencyMatrix.from_compressed(vertices, E) output = cls(len(adj.matrix),[]) output.edges = adj return output @classmethod def loads(cls,serialized: str)->"Graph": return cls.from_dict(json.loads(serialized)) def __init__(self,vertices: int, edges: typing.Iterable[typing.Tuple[int,int]]): self.vertices = range(vertices) self.edges = UndirectedAdjacencyMatrix(vertices,edges) def isomorphism(self, mapping: typing.Dict[int,int])->"Isomorphism": return Isomorphism(self.vertices,mapping) def map_vertices(self, mapping: "Isomorphism")->"Graph": new_edges = set() for edge in self.edges: new_edges.add((mapping[edge[0]],mapping[edge[1]])) return Graph(len(self.vertices),new_edges) def check_mapping(self, other: "Graph", mapping: "Isomorphism")->bool: return self.map_vertices(mapping) == other def neighbors(self, idx: int)->typing.Set[int]: return set(map(lambda t: t[1],self.edges[idx])) def is_automorphism(self, mapping: "Isomorphism")->bool: return self.map_vertices(mapping) == self def to_dict(self)->dict: sz, lst = self.edges.compressed() x = 0 for b, i in zip(lst[::-1],itertools.count()): x |= int(b)<<i #I sincerely apologize for the bit math. This is the most efficient way by far to store this information. return { "V": sz, 'E': base64.urlsafe_b64encode(x.to_bytes((x.bit_length() // 8 + int(x.bit_length() % 8)),'big')).decode("utf-8") } def dumps(self)->str: return json.dumps(self.to_dict()) def __eq__(self, other: "Graph")->bool: return self.edges == other.edges def __repr__(self): return repr({"V": self.vertices, "E": self.edges}) def __contains__(self, item: typing.Union[typing.Tuple[int,int],int]): if isinstance(item,int): return item in self.vertices elif isinstance(item, tuple) and len(item) == 2 and isinstance(item[0],int) and isinstance(item[1],int): return item in self.edges elif isinstance(item,tuple): raise ValueError("Expected an int or tuple of two ints!") else: raise TypeError("Graph can only contain a numeric vertex or an edge between them") class Isomorphism(): vertices: typing.Set[int] _mapping: typing.Dict[int,int] @classmethod def loads(cls, graph: Graph, data: str)->"Isomorphism": data = json.loads(data) if not isinstance(data,dict): raise ValueError("Isomorphisms are supposed to be in dictionary format.") mapping = {} for key in data.keys(): if not isinstance(key,str) or not isinstance(data[key],int): raise ValueError("Could not decode isomorphism") mapping[int(key)] = data[key] return cls(graph.vertices,mapping) def __init__(self, vertices: typing.Set[int], mapping: typing.Dict[int,int]): self.vertices = set(vertices) for vertex in vertices: if vertex == None: raise TypeError("Vertices cannot be labeled with None.") self._mapping = dict(mapping) for v in self._mapping.keys(): if not v in self.vertices: raise ValueError(f"Mapping contains nonexistent vertex {v}") found = set() for vertex in self.vertices: if vertex in self._mapping.keys() and self._mapping[vertex] == vertex: self._mapping.pop(vertex) elif vertex in self._mapping.keys(): if self._mapping[vertex] in found: raise ValueError(f"Invalid permutation: {self._mapping[vertex]} has multiple vertices mapped to it!") found.add(self._mapping[vertex]) def __getitem__(self, key: int)->int: if key in self._mapping.keys(): return self._mapping[key] elif key in self.vertices: return key else: raise KeyError(key) def _check_vertices(self, other: "Isomorphism")->None: for vertex in self.vertices: if not vertex in other.vertices: raise ValueError("Cannot create composition from isomorphisms with different vertex sets") for vertex in other.vertices: if not vertex in self.vertices: raise ValueError("Cannot create composition from isomorphisms with different vertex sets") def __add__(self, other: "Isomorphism")->"Isomorphism": self._check_vertices(other) new_mapping = dict() for v in self.vertices: new_mapping[v] = other[self[v]] return Isomorphism(self.vertices,new_mapping) def __neg__(self)->"Isomorphism": new_mapping = dict() for v in self.vertices: new_mapping[self[v]] = v return Isomorphism(self.vertices,new_mapping) def __sub__(self, other: "Isomorphism")->"Isomorphism": self._check_vertices(other) return self + (-other) def __eq__(self, other: "Isomorphism")->"Isomorphism": for vertex in self.vertices: if not vertex in other.vertices: return False for vertex in other.vertices: if not vertex in self.vertices: return False for vertex in self.vertices: if self[vertex] != other[vertex]: return False return True def __str__(self): return json.dumps(self._mapping) def random_graph(min_vertices: int = 256, max_vertices: int = 512)->Graph: r = SystemRandom() num_vertices = r.randint(min_vertices,max_vertices) edge_space = [] edges = set() for i in range(num_vertices): for j in range(i,num_vertices): edge_space.append((i,j)) edges = set(r.sample(edge_space,r.randint(min_vertices,len(edge_space)))) return Graph(num_vertices,edges) def random_isomorphism(graph: Graph)->Isomorphism: r = SystemRandom() vertices = list(graph.vertices) newVertices = list(vertices) r.shuffle(newVertices) transformation = dict([(u, v) for u, v in zip(vertices,newVertices)]) return graph.isomorphism(transformation) if __name__ == "__main__": g = Graph(4,set([(0,1),(0,2),(2,3),(1,2)])) assert 0 in g assert 1 in g assert 2 in g assert 3 in g assert 4 not in g assert (0, 1) in g assert (0, 2) in g assert (2, 3) in g assert (1, 2) in g assert (1, 3) not in g assert (1, 0) in g assert (2, 0) in g assert (3, 2) in g assert (2, 1) in g assert (3, 1) not in g Ne = g.neighbors(0) assert 1 in Ne assert 2 in Ne assert 3 not in Ne Ne = g.neighbors(2) assert 0 in Ne assert 2 in Ne assert 1 in Ne try: "1" in g raise AssertionError("Graphs should not accept strings!") except TypeError: pass assert len(g.edges) == 4 print(g) tst = g.edges.from_compressed(*g.edges.compressed()) assert len(tst) == 4 assert tst == g.edges g2 = Graph.loads(g.dumps()) print(g2) assert g == g2 assert g.is_automorphism(g.isomorphism({0: 1, 1: 0})) #Check that it correctly detects an automorphism g3 = g.map_vertices(g.isomorphism({0: 1, 1: 2, 2: 3, 3: 0})) #generate an isomorphic graph print(g3) assert g.check_mapping(g3,g.isomorphism({0: 1, 1: 2, 2: 3, 3: 0})) #validate the isomorphism assert g.check_mapping(g3,g.isomorphism({0:1, 1:0}) + g.isomorphism({0: 1, 1: 2, 2: 3, 3: 0})) #The same as the automorphism above followed by the isomorphism. G = random_graph(128,256) print(len(G.dumps())) print(len(json.dumps(G.edges.matrix)))
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/BlueHens/2023/misc/Defective_Client/alice.py
ctfs/BlueHens/2023/misc/Defective_Client/alice.py
from graph import * import json with open("private_key.json","r") as f: key = json.loads(f.read()) G0 = Graph.from_dict(key["base"]) d = Isomorphism.loads(G0,key["transformation"]) G1 = G0.map_vertices(d) print(G0.dumps()) print(G1.dumps()) G2 = Graph.loads(input().strip()) i = Isomorphism.loads(G2,input().strip()) if G2.is_automorphism(i): raise ValueError("Nice try!") if not G2.check_mapping(G0,i): raise ValueError("The given mapping does not map the provided graph to G0!") m = i + d print(m) auth = input().strip() if auth == "y": print("give me the flag")
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/BlueHens/2023/misc/Defective_Client/gen_key.py
ctfs/BlueHens/2023/misc/Defective_Client/gen_key.py
from graph import * import json G0 = random_graph(128,256) i = random_isomorphism(G0) while G0.is_automorphism(i): G0 = random_graph(128,256) i = random_isomorphism(G0) with open("private_key.json","w") as f: f.write(json.dumps({ "base": G0.to_dict(), "transformation": str(i) })) G1 = G0.map_vertices(i) with open("public_key.json","w") as f: f.write(json.dumps( [ G0.to_dict(), G1.to_dict() ] ))
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/BlueHens/2023/misc/Defective_Client/server.py
ctfs/BlueHens/2023/misc/Defective_Client/server.py
import json from graph import Graph, Isomorphism import typing import os ROUNDS = 16 with open("public_key.json",'r') as f: key = list(map(Graph.from_dict,json.load(f))) with open("flag.txt",'r') as f: flag = f.read() def authenticate(key: typing.List[Graph]): Graphs = [Graph.from_dict(json.loads(input().strip())) for _ in range(ROUNDS)] challenges = os.urandom((ROUNDS//8)+1 if ROUNDS % 8 != 0 else ROUNDS//8) print(challenges.hex()) challenges = int.from_bytes(challenges,'big') for G2 in Graphs: challenge = challenges % 2 tau = Isomorphism.loads(G2,input().strip()) if not key[challenge].check_mapping(G2,tau): return False challenges >>= 1 return True try: if authenticate(key): print("y") print(flag) else: print("n") except: print("n")
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/BlueHens/2023/misc/Defective_Server/server.py
ctfs/BlueHens/2023/misc/Defective_Server/server.py
import enum import json CHALLENGES = [1, 1, 1, 1, 0, 0, 1, 1, 1, 0, 1, 0, 1, 1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 1, 1, 1, 0, 1, 1, 1, 0, 0, 1, 0, 0, 0, 0, 1, 0, 1, 1, 0, 1, 1, 1, 0, 1, 1, 1, 1, 0, 1, 0, 1, 0, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 0, 0, 0, 0, 1, 0, 1, 1, 0, 0, 0, 1, 1, 1, 0, 1, 0, 0, 1, 0, 1, 0, 0, 1, 1, 0, 1, 0, 0, 1, 1, 1, 0, 0, 0, 1, 1, 0, 1, 0, 0, 1, 1, 0, 1, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 0, 1, 1, 0] class Challenge(enum.Enum): RS = 0 R = 1 CHALLENGES = [Challenge(c) for c in CHALLENGES] class Authenticator(): N: int e: int ssq: int def __init__(self, e: int, N: int, ssq: int): self.e = e self.N = N self.ssq = ssq def round(self, rsq: int, ans: int, chal: Challenge)->bool: if chal == Challenge.RS and pow(ans,self.e,self.N) == (rsq * self.ssq) % self.N: return True elif chal == Challenge.R and pow(ans,self.e,self.N) == rsq: return True else: return False def main(): with open("public_key.json",'r') as f: key = json.loads(f.read()) ssq = key["s^e"] e = key['e'] N = key['N'] auth = Authenticator(e,N,ssq) for challenge in CHALLENGES: rsq = int(input().strip()) print(challenge.value) answer = int(input().strip()) if not auth.round(rsq,answer,challenge): return with open("flag.txt",'r') as f: print(f.read()) if __name__ == "__main__": main()
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/BlueHens/2023/misc/Forest_For_The_Trees/graph.py
ctfs/BlueHens/2023/misc/Forest_For_The_Trees/graph.py
import typing import json import functools from random import SystemRandom import itertools import base64 class UndirectedAdjacencyMatrix(): matrix: typing.List[typing.List[int]] @classmethod def from_compressed(cls, vertices: int, compressed: typing.List[bool])->"UndirectedAdjacencyMatrix": matrix = [] idx = 0 for v in range(vertices): matrix.append(compressed[idx:idx+(vertices - v)]) idx += (vertices - v) output = cls(vertices,[]) output.matrix = matrix return output @classmethod def loads(cls, vertices: int, serialized: str)->"UndirectedAdjacencyMatrix": raw = int.from_bytes(base64.urlsafe_b64decode(serialized),'big') compressed = [] for i in range((vertices*(vertices+1))//2): compressed.insert(0,bool(1<<i & raw)) return cls.from_compressed(vertices,compressed) def __init__(self, vertices: int, edges: typing.Iterable[typing.Tuple[int,int]]): matrix = [] for v in range(vertices): matrix.append([False for _ in range(v,vertices)]) for u, v in edges: row, col = min((u, v)), max((u, v)) matrix[row][col - row] = True self.matrix = matrix def pop_edge(self, e: typing.Tuple[int,int]): if e in self: row, col = min(e), max(e) - min(e) self.matrix[row][col] = False else: raise KeyError(e) def pop_vertex(self, v: int): if v >= 0 and v < len(self.matrix): self.matrix.pop(v) for row, idx in zip(self.matrix[:v],itertools.count()): row.pop(v-idx) else: raise KeyError(v) def compressed(self)->typing.Tuple[int, typing.List[bool]]: output = [] for row in self.matrix: output.extend(row) return len(self.matrix), tuple(output) def dumps(self)->str: x = 0 for b, i in zip(self.compressed()[1][::-1],itertools.count()): x |= int(b)<<i return base64.urlsafe_b64encode(x.to_bytes((x.bit_length() // 8 + int(x.bit_length() % 8)),'big')).decode("utf-8") def __contains__(self, item: typing.Tuple[int,int])->bool: row, col = min(item), max(item) - min(item) if row < len(self.matrix) and col < len(self.matrix[row]): return self.matrix[row][col] else: raise ValueError(f"Edge {(row, col + row)} cannot exist in graph with {len(self.matrix)} vertices!") def __iter__(self)->"UndirectedAdjacencyMatrix": self._row = 0 self._col = 0 return self def __next__(self)->int: if self._row >= len(self.matrix): raise StopIteration() while not self.matrix[self._row][self._col]: if self._col >= len(self.matrix[self._row])-1: self._col = 0 self._row += 1 else: self._col += 1 if self._row >= len(self.matrix): raise StopIteration() row, col = self._row, self._col if self._col >= len(self.matrix[self._row])-1: self._col = 0 self._row += 1 else: self._col += 1 return (row, col + row) def __len__(self)->int: return len(self.matrix) def __eq__(self,other: "UndirectedAdjacencyMatrix"): if len(self.matrix) != len(other.matrix): return False output = True for row1, row2 in zip(self.matrix,other.matrix): output = output and functools.reduce(lambda x, y: x and y,[i == j for i, j in zip(row1,row2)]) return output def __repr__(self): return repr(self.matrix) def __getitem__(self, idx: int)->typing.Iterable[int]: for b, i in zip(self.matrix[idx],itertools.count()): if b: yield (idx, idx+i) for row, i in zip(self.matrix[:idx],range(idx)): if row[idx-i]: yield (idx, i) class Graph(): _vertices: range _edges: UndirectedAdjacencyMatrix _labels: typing.Dict[int, int] _unlabels: typing.Dict[int, int] @classmethod def from_dict(cls, dct: dict)->"Graph": vertices = dct["V"] adj = UndirectedAdjacencyMatrix.loads(len(vertices), dct['E']) slf = cls(vertices,[]) slf._edges = adj return slf @classmethod def loads(cls,serialized: str)->"Graph": return cls.from_dict(json.loads(serialized)) @property def vertices(self)->typing.Iterable[int]: return self._labels.keys() @property def edges(self)->typing.Iterable[typing.Tuple[int,int]]: for edge in self._edges: yield (self._unlabels[edge[0]], self._unlabels[edge[1]]) def __init__(self,vertices: typing.Iterable[int], edges: typing.Iterable[typing.Tuple[int, int]]): self._labels = {} self._unlabels = {} for v, i in zip(vertices,itertools.count()): if type(v) == tuple: raise TypeError("Vertex labels cannot be tuples.") self._labels[v] = i self._unlabels[i] = v new_edges = [] for edge in edges: new_edges.append((self._labels[edge[0]], self._labels[edge[1]])) num_vertices = len(self._labels.keys()) self._vertices = range(num_vertices) self._edges = UndirectedAdjacencyMatrix(num_vertices,new_edges) def map_vertices(self, mapping: "Isomorphism")->"Graph": new_edges = [] for edge in self.edges: new_edges.append((mapping[edge[0]],mapping[edge[1]])) return Graph(mapping.vertices,new_edges) def check_mapping(self, other: "Graph", mapping: "Isomorphism")->bool: return self.map_vertices(mapping) == other def neighbors(self, idx: int)->typing.Set[int]: return set(map(lambda t: self._unlabels[t[1]],self._edges[self._labels[idx]])) def is_automorphism(self, mapping: "Isomorphism")->bool: return self.map_vertices(mapping) == self def pop(self, item: typing.Union[int,typing.Tuple[int,int]]): if isinstance(item,tuple) and len(item) == 2: self._edges.pop_edge((self._labels[item[0]], self._labels[item[1]])) elif isinstance(item,tuple): raise ValueError(f"Edge must have exactly two endpoints, not {len(item)}!") else: x = self._labels[item] self._edges.pop_vertex(x) self._unlabels.pop(x) self._labels.pop(item) new_unlabels = {} new_labels = {} for idx in self._unlabels.keys(): label = self._unlabels[idx] new_idx = idx if idx < x else idx-1 new_unlabels[new_idx] = label new_labels[label] = new_idx self._unlabels = new_unlabels self._labels = new_labels def to_dict(self)->dict: lst = list(self._unlabels.keys()) lst.sort() V = list(map(lambda v: self._unlabels[v],lst)) return { "V": V, 'E': self._edges.dumps() } def dumps(self)->str: return json.dumps(self.to_dict()) def __eq__(self, other: "Graph")->bool: for v in self.vertices: if v not in other: return False for v in other.vertices: if v not in self: return False for edge in self.edges: if edge not in other: return False for edge in other.edges: if edge not in self: return False return True def copy(self)->"Graph": return Graph(self.vertices,self.edges) def isomorphism(self, mapping: typing.Dict[int,int])->"Isomorphism": return Isomorphism(self.vertices,mapping) def __repr__(self)->str: return repr({"V": self.vertices, "E": list(self.edges)}) def __contains__(self, item: any)->bool: if isinstance(item, tuple) and len(item) == 2: return (self._labels[item[0]], self._labels[item[1]]) in self._edges elif isinstance(item,tuple): raise ValueError("An edge can only have two end points!") return item in self.vertices class Isomorphism(): vertices: typing.Set[int] _mapping: typing.Dict[int,int] @classmethod def loads(cls, graph: Graph, data: str)->"Isomorphism": data = json.loads(data) if not isinstance(data,dict): raise ValueError("Isomorphisms are supposed to be in dictionary format.") mapping = {} for key in data.keys(): if not isinstance(key,str) or not isinstance(data[key],int): raise ValueError("Could not decode isomorphism") mapping[int(key)] = data[key] return cls(graph.vertices,mapping) def __init__(self, vertices: typing.Set[int], mapping: typing.Dict[int,int]): self.vertices = set(vertices) for vertex in vertices: if vertex == None: raise TypeError("Vertices cannot be labeled with None.") self._mapping = dict(mapping) for v in self._mapping.keys(): if not v in self.vertices: raise ValueError(f"Mapping contains nonexistent vertex {v}") found = set() for vertex in self.vertices: if vertex in self._mapping.keys() and self._mapping[vertex] == vertex: self._mapping.pop(vertex) elif vertex in self._mapping.keys(): if self._mapping[vertex] in found: raise ValueError(f"Invalid permutation: {self._mapping[vertex]} has multiple vertices mapped to it!") found.add(self._mapping[vertex]) def __getitem__(self, key: int)->int: if key in self._mapping.keys(): return self._mapping[key] elif key in self.vertices: return key else: raise KeyError(key) def _check_vertices(self, other: "Isomorphism")->None: for vertex in self.vertices: if not vertex in other.vertices: raise ValueError("Cannot create composition from isomorphisms with different vertex sets") for vertex in other.vertices: if not vertex in self.vertices: raise ValueError("Cannot create composition from isomorphisms with different vertex sets") def __add__(self, other: "Isomorphism")->"Isomorphism": self._check_vertices(other) new_mapping = dict() for v in self.vertices: new_mapping[v] = other[self[v]] return Isomorphism(self.vertices,new_mapping) def __neg__(self)->"Isomorphism": new_mapping = dict() for v in self.vertices: new_mapping[self[v]] = v return Isomorphism(self.vertices,new_mapping) def __sub__(self, other: "Isomorphism")->"Isomorphism": self._check_vertices(other) return self + (-other) def __eq__(self, other: "Isomorphism")->"Isomorphism": for vertex in self.vertices: if not vertex in other.vertices: return False for vertex in other.vertices: if not vertex in self.vertices: return False for vertex in self.vertices: if self[vertex] != other[vertex]: return False return True def __str__(self)->str: return str(self._mapping) def __repr__(self)->str: return repr(self._mapping) def dumps(self)->str: return json.dumps(self._mapping) def random_graph(min_vertices: int = 256, max_vertices: int = 512)->Graph: r = SystemRandom() num_vertices = r.randint(min_vertices,max_vertices) edge_space = [] edges = set() for i in range(num_vertices): for j in range(i,num_vertices): edge_space.append((i,j)) edges = set(r.sample(edge_space,r.randint(min_vertices,len(edge_space)))) return Graph(num_vertices,edges) def random_isomorphism(graph: Graph)->Isomorphism: r = SystemRandom() vertices = list(graph.vertices) newVertices = list(vertices) r.shuffle(newVertices) transformation = dict([(u, v) for u, v in zip(vertices,newVertices)]) return graph.isomorphism(transformation)
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/BlueHens/2023/misc/Forest_For_The_Trees/gen_key.py
ctfs/BlueHens/2023/misc/Forest_For_The_Trees/gen_key.py
import graph import json import random RAND = random.SystemRandom() def generate_tree(depth: int, root, vertices, edges): if depth == 0: return else: size = RAND.randint(0,4) if size > len(vertices): return children = random.sample(list(vertices),size) for child in children: vertices.remove(child) edges.add((root, child)) for child in children: generate_tree(depth-1,child,vertices,edges) def random_graph(size: int = 128, max_depth = 3): vertices = set(range(size)) edges = set() for _ in range(RAND.randint(2,size//10)): if len(vertices) == 0: break root = random.choice(list(vertices)) vertices.remove(root) generate_tree(RAND.randint(1,max_depth),root,vertices,edges) return graph.Graph(range(size),edges) G0 = random_graph() i = graph.random_isomorphism(G0) while G0.is_automorphism(i): G0 = random_graph() i = graph.random_isomorphism(G0) with open("private_key.json","w") as f: f.write(json.dumps({ "base": G0.to_dict(), "transformation": i._mapping })) G1 = G0.map_vertices(i) with open("public_key.json","w") as f: f.write(json.dumps( [ G0.to_dict(), G1.to_dict() ] ))
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false