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/hxp/2020/crypto/minithorpe/executor.py
ctfs/hxp/2020/crypto/minithorpe/executor.py
#!/usr/bin/env python3 from subprocess import run from sys import stdin, stdout from struct import pack command = stdin.buffer.readline().rstrip(b'\n') result = run(command, shell=True, capture_output=True, timeout=0.5) header = pack('III', result.returncode, len(result.stdout), len(result.stderr)) message = header + result.stdout + result.stderr stdout.buffer.write(message)
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/hxp/2020/crypto/minithorpe/octothorpe.py
ctfs/hxp/2020/crypto/minithorpe/octothorpe.py
#!/usr/bin/env python3 import math class octothorpe: digest_size = 16 block_size = 64 name = "octothorpe" state_size = 16 shift_count = 64 round_count = 20 initial_state = bytearray.fromhex('00112233445566778899aabbccddeeff') function = lambda i: math.cos(i ** 3) sbox = sorted(range(256), key=function) shift = [int(8 * s) % 8 for s in map(function, range(shift_count))] new = classmethod(lambda cls, data: cls(data)) copy = lambda self: octothorpe(_cache=self._cache[:], _length=self._length, _state=self._state[:]) digest = lambda self: bytes(self._finalize()) hexdigest = lambda self: self.digest().hex() def __init__(self, data: bytes = None, *, _cache: bytes = None, _length: int = None, _state: bytearray = None) -> None: self._cache = _cache or b'' self._length = _length or 0 self._state = _state or self.initial_state[:] assert len(self._state) == self.state_size, 'Invalid state size' if data: self.update(data) def update(self, data: bytes) -> None: self._cache += data while len(self._cache) >= self.block_size: block, self._cache = self._cache[:self.block_size], self._cache[self.block_size:] self._compress(block) self._length += self.block_size def _finalize(self) -> bytearray: clone = self.copy() clone._length += len(clone._cache) clone.update(b'\x80' + b'\x00' * ((self.block_size - 9 - clone._length) % self.block_size) + (8 * clone._length).to_bytes(8, 'little')) return clone._state def _compress(self, block: bytes) -> None: prev_state = lambda index: (index - 1) % self.state_size next_state = lambda index: (index + 1) % self.state_size rol = lambda value, shift, size: ((value << (shift % size)) | (value >> (size - (shift % size)))) & ((1 << size) - 1) ror = lambda value, shift, size: ((value >> (shift % size)) | (value << (size - (shift % size)))) & ((1 << size) - 1) for r in range(self.round_count): state = self._state[:] for i in range(self.block_size): j, jj = (i * r) % self.state_size, (i * r) % self.shift_count self._state[prev_state(j)] ^= self.sbox[block[i] ^ rol(state[j], self.shift[jj], 8)] self._state[next_state(j)] ^= self.sbox[block[i] ^ ror(state[j], self.shift[jj], 8)] if __name__ == '__main__': assert octothorpe(b'hxp').hexdigest() == '4e072c7a1872f7cdf3cb2cfc676b0311'
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/hxp/2020/web/hackme/admin.py
ctfs/hxp/2020/web/hackme/admin.py
#!/usr/bin/env python3 from selenium import webdriver from selenium.webdriver.common.by import By from selenium.webdriver.common.keys import Keys from selenium.webdriver.chrome.options import Options from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support.expected_conditions import visibility_of import urllib.parse import re import sys import traceback # HTTP request from stdin (ynetd), ignoring any headers or really anything else query = sys.stdin.readline(1024).strip() match = re.match(r'\AGET\s+/report\?url=([a-zA-Z0-9/_.-]+)\s+HTTP/\d\.\d\Z', query) if not match: print('Invalid query:', urllib.parse.quote(query, safe='/?= '), file=sys.stderr, flush=True) print('HTTP/1.1 400 Bad Request\r\nContent-Length: 0\r\n\r\n') exit(0) # Visit URL endpoint = 'http://127.0.0.1/' admin = '__ADMIN_EMAIL__' password = '__ADMIN_PASSWORD__' url = endpoint + match.group(1).lstrip('/') print('Visiting', url, file=sys.stderr, flush=True) chrome_options = Options() chrome_options.add_argument('--disable-gpu') chrome_options.add_argument('--headless') chrome_options.add_argument('--no-sandbox') try: driver = webdriver.Chrome('/usr/bin/chromedriver', options=chrome_options) wait = WebDriverWait(driver, 1) # Log in driver.get(endpoint) driver.find_element_by_css_selector('button.ui-signin').click() email_input = driver.find_element_by_name('email') password_input = driver.find_element_by_name('password') wait.until(visibility_of(email_input)) email_input.send_keys(admin) password_input.send_keys(password) driver.find_element_by_css_selector('button[formaction="/login"]').click() # Fetch URL and wait for complete page load driver.get(url) wait.until(lambda driver: driver.execute_script("return document.readyState") == "complete") print('HTTP/1.1 204 No Content\r\nContent-Length: 0\r\n\r\n') except: traceback.print_stack(file=sys.stderr) print('HTTP/1.1 500 Internal Server Error\r\nContent-Length: 0\r\n\r\n') finally: driver.quit() print('Done visiting', url, file=sys.stderr, flush=True)
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/ByteBandits/2023/blockchain/GuessTheName/get_ticket.py
ctfs/ByteBandits/2023/blockchain/GuessTheName/get_ticket.py
import hashlib,random x = 100000000+random.randint(0,200000000000) for i in range(x,x+20000000000): m = hashlib.sha256() ticket = str(i) m.update(ticket.encode('ascii')) digest1 = m.digest() m = hashlib.sha256() m.update(digest1 + ticket.encode('ascii')) if m.hexdigest().startswith('0000000'): print(i) break
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/ByteBandits/2023/crypto/CryptoMasquerade/chal.py
ctfs/ByteBandits/2023/crypto/CryptoMasquerade/chal.py
import base64 import random import math from Crypto.Util import number from cryptography.fernet import Fernet from cryptography.hazmat.backends import default_backend from cryptography.hazmat.primitives import hashes from cryptography.hazmat.primitives.kdf.pbkdf2 import PBKDF2HMAC BIT_L = 2**8 with open("flag.txt", "r") as f: FLAG = f.read() def generate_secrets(): p = number.getPrime(BIT_L) g = number.getPrime(BIT_L) h = (p - 1) * (g - 1) a = 0 while number.GCD(a, h) != 1: a = number.getRandomRange(3, h) b = pow(a, -1, h) return p * g, g, a, b def main(): p, g, a, b = generate_secrets() A = pow(g, a, p) B = pow(g, b, p) key = pow(A, b, p) print("p :", p) print("g :", g) print("A :", A) print("B :", B) print("key :", key) assert key == g password = key.to_bytes((key.bit_length() + 7) // 8, "big") kdf = PBKDF2HMAC( algorithm=hashes.SHA256, length=32, salt=b"\x00" * 8, iterations=100000, backend=default_backend(), ) key = base64.urlsafe_b64encode(kdf.derive(password)) f = Fernet(key) token = f.encrypt(FLAG.encode("ascii")) print("message : ", token.decode()) 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/ByteBandits/2023/crypto/VisionaryCipher/chal.py
ctfs/ByteBandits/2023/crypto/VisionaryCipher/chal.py
from string import ascii_lowercase, digits from random import choices from hashlib import md5 with open("flag.txt", "r") as f: FLAG = f.read() alphabets = ascii_lowercase + digits + "_{}" key = "".join(choices(alphabets, k=10)) def pos(ch): return alphabets.find(ch) def encrypt(text, key): k, n, l = len(key), len(text), len(alphabets) return "".join([alphabets[(pos(text[i]) + pos(key[i % k])) % l] for i in range(n)]) print("c :", encrypt(FLAG, key)) print("hash :", md5(FLAG.encode("ascii")).hexdigest())
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/BreakTheSyntax/2024/crypto/leaky_prime/de1fc7e127672e610447b36afe96d7db.py
ctfs/BreakTheSyntax/2024/crypto/leaky_prime/de1fc7e127672e610447b36afe96d7db.py
from secret import flag from Crypto.Util.number import getPrime, bytes_to_long, long_to_bytes PRIMESIZE = 512 e = 65537 p = getPrime(PRIMESIZE) q = getPrime(PRIMESIZE) n = p*q c = bytes_to_long(flag) ct = pow(c,e,n) msb = bin(p >> 20)[2:] print(ct) print(n) print(msb)
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/BreakTheSyntax/2024/crypto/letter/005d5290c5e960026765cf5cabd55176.py
ctfs/BreakTheSyntax/2024/crypto/letter/005d5290c5e960026765cf5cabd55176.py
from string import ascii_uppercase, digits from itertools import permutations from random import sample, seed, randint, choice from os import urandom from letter import letter alphabet = ascii_uppercase + digits seed(urandom(32)) keys_s = ["".join(sample(alphabet, len(alphabet))) for _ in range(3)] key_x = "".join([choice(alphabet) for _ in range(5)]) keys_l = [randint(10, 20) for _ in range(4)] def encrypt(text): text = text.upper() ct1 = "" i = 0 ii = 0 k1 = 0 k2 = 0 for c in text: if c in alphabet: if ii >= keys_l[k1]: ii = 0 k1 = (k1 + 1) % len(keys_l) k2 = (k2 + 1) % len(keys_s) ct1 += keys_s[k2][alphabet.index(c)] i += 1 ii += 1 else: ct1 += c ct2 = "" i = 0 for c in ct1: if c in alphabet: ix = (alphabet.index(c) + alphabet.index(key_x[i % len(key_x)])) % len(alphabet) ct2 += alphabet[ix] i += 1 else: ct2 += c return ct2 print(encrypt(letter))
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/BreakTheSyntax/2024/crypto/backup/8e1cc9f39494494b81d5dd876ec6c1ad.py
ctfs/BreakTheSyntax/2024/crypto/backup/8e1cc9f39494494b81d5dd876ec6c1ad.py
from sage.all import * from hashlib import sha256 as sha from Crypto.Cipher import AES from Crypto.Util.Padding import pad from secrets import token_bytes from time import time # preshared secret preshared_secret = token_bytes(16) # generate a strong prime def strong_prime(bits): while True: p = random_prime(2**bits) q = (p - 1)//2 if is_prime(q): return p p = strong_prime(256) # order of the subgroup q = (p - 1)//2 # cyclic subgroup of quadratic residues g1 = pow(randint(2, p - 1), 2, p) g2 = pow(randint(2, p - 1), 2, p) assert pow(g1, q, p) == 1 and pow(g2, q, p) == 1 and g1 != g2 print(f"p = {p}\nq = {q}\ng1 = {g1}\ng2 = {g2}") def hash(inputs): if not hasattr(inputs, "__iter__"): m = inputs else: m = "".join(map(str, inputs)).encode() return int(sha(m).hexdigest(), 16) % q with open("flag") as f: flag = f.read().strip() # private key # I dont trust the PRNG on this machine x1 = hash([preshared_secret, flag, "x1"]) x2 = hash([preshared_secret, flag, "x2"]) # public key Y = (pow(g1, x1, p) * pow(g2, x2, p)) % p print(f"Y = {Y}") def sign(m): r = hash([m, x1, x2, time()]) # add some untrusted entropy entropy = randint(1, 2 ** 250) l = entropy.bit_length() a = entropy & ((1 << ((l // 2) - 1)) - 1) b = entropy >> ((l // 2) - 1) r1 = (r + a) % q r2 = (r + b) % q R = (pow(g1, r1, p) * pow(g2, r2, p)) % p h = hash([m, R]) s1 = (r1 + x1*h) % q s2 = (r2 + x2*h) % q return s1, s2, R def verify(m, s1, s2, R): h = hash([m, R]) return (pow(g1, s1, p) * pow(g2, s2, p)) % p == (R * pow(Y, h, p)) % p assert verify("hello", *sign("hello")) def encrypt(m): key = hash([(x1 - x2) % q]).to_bytes(32, "big") cipher = AES.new(key, AES.MODE_CBC) ct = cipher.encrypt(pad(m, 16)) iv = cipher.iv return iv.hex() + ct.hex() print("") m1 = "Hi! Can you store the encrypted flag for me for a second? I will need it later." sig1 = sign(m1) print(f"MESSAGE\nA:>{m1}\nSIG\n({sig1[0]},{sig1[1]},{sig1[2]})\n") m2 = "Here's the flag: " + encrypt(flag.encode()) sig2 = sign(m2) print(f"MESSAGE\nA:>{m2}\nSIG\n({sig2[0]},{sig2[1]},{sig2[2]})\n")
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/BreakTheSyntax/2023/pwn/Build-A-Jail/challenge.py
ctfs/BreakTheSyntax/2023/pwn/Build-A-Jail/challenge.py
#!/usr/bin/env python from mesonbuild.ast.visitor import AstVisitor from mesonbuild.mparser import Parser, FunctionNode, StringNode from tempfile import TemporaryDirectory from os import system, chdir from shutil import copytree from pathlib import Path from sys import stdin FORBIDDEN_FUNCTIONS = ["run_command", "files", "find_program", "configure_file"] DANGEROUS_STRINGS = ["/bin", "sh", "bash", "zsh", "ksh", "cat", "tac"] class MyVisitor(AstVisitor): def visit_FunctionNode(self, node: FunctionNode) -> None: if node.func_name in FORBIDDEN_FUNCTIONS: print(f"{node.func_name} is a FORBIDDEN FUNCTION\nExiting...") exit() def visit_StringNode(self, node: StringNode) -> None: if any(map(lambda danger: danger in node.value, DANGEROUS_STRINGS)): print(f"'{node.value}' contains a DANGEROUS STRINGS\nExiting...") exit() def main(): with TemporaryDirectory() as dir: chdir(dir) copytree("/home/user/", dir, dirs_exist_ok=True) print("We will setup jail according to your instructions.") print("Please provide build instructions.") # user_input = "".join(line for line in stdin) user_input = "" while (line := input()) != "EOF": user_input += line + "\n" p = Parser(user_input, '').parse() p.accept(MyVisitor()) Path("meson.build").write_text(user_input) system(f"meson setup builddir") main()
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/BreakTheSyntax/2023/crypto/Guacamole/8b66f23496e6a5602419991de934bd43.py
ctfs/BreakTheSyntax/2023/crypto/Guacamole/8b66f23496e6a5602419991de934bd43.py
from guacamole import * from hashlib import md5 from os import urandom with open('flag', 'r') as f: flag = f.read() destinations = [] key = urandom(16) iv_len = 96 flag_iv = urandom(96//8) flag_ct, flag_t = aes_gua_encrypt(pt=flag.encode(), key=key, iv=flag_iv, additional_data=b"flag", t=136) def connect(destination: bytes): if destination in destinations: print("CONNECTION REQUEST FAILED: ALREADY CONNECTED") return destinations.append(destination) for i in range(5): # I've read in the standard that IV should # be generated deterministically, don't know # why tho iv = md5(destination + i.to_bytes(2, 'big')).digest()[:iv_len//8] ct, flag_t = aes_gua_encrypt(pt=urandom(4), key=key, iv=iv, additional_data=b"handshake", t=136) print("ct =", ct.hex()) print("iv =", iv.hex()) print("t =", flag_t.hex()) def parse_message(ct: bytes, t: bytes, A: bytes, iv: bytes): try: pt = aes_gua_decrypt(ct=ct, key=key, iv=iv, additional_data=A, t=136, tag=t) except Exception as E: print("Decryption error") return try: pt = pt.decode("ascii") except: print("Parsing error") return if pt == flag and flag_t != t and A == b"You're mine.": print("flag =", flag) if __name__ == "__main__": print("We've intercepted this important message. Forge a new signature for it!") print("flag ct =", flag_ct.hex()) print("flag iv =", flag_iv.hex()) print("flag t =", flag_t.hex()) while True: print("You're in their walls. What do you want to do?") print("[1] Send connection request", "[2] Forge message", "[3] exit",sep="\n") sel = int(input(">")) if sel == 1: dest = bytes.fromhex(input("Destination:\n(hex)>")) connect(dest) if sel == 2: ct = bytes.fromhex(input("ct:\n(hex)>")) add = bytes.fromhex(input("add. data:\n(hex)>")) iv = bytes.fromhex(input("iv:\n(hex)>")) t = bytes.fromhex(input("tag:\n(hex)>")) parse_message(ct=ct, t=t, A=add, iv=iv) if sel == 3: exit(0)
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/BreakTheSyntax/2023/crypto/Guacamole/1221ef33d9f955fedde3496c3212ea39.py
ctfs/BreakTheSyntax/2023/crypto/Guacamole/1221ef33d9f955fedde3496c3212ea39.py
from Crypto.Cipher import AES import math def xor(bytes_a: bytes, bytes_b: bytes, block_len: int = 128) -> bytes: return bytes([a ^ b for (a, b) in zip(bytes_a, bytes_b)]) def b_and(bytes_a: bytes, bytes_b: bytes, block_len: int = 128) -> bytes: return bytes([a & b for (a, b) in zip(bytes_a, bytes_b)]) def degree(poly) -> list: while poly and poly[-1] == 0: poly.pop() # normalize return len(poly)-1 def lead(poly) -> list: while poly and poly[-1] == 0: poly.pop() # normalize return poly[-1] def mul_poly(poly1, poly2) -> list: out = [0 for _ in range(len(poly1) + len(poly2) - 1)] for x,i in enumerate(poly1): for y,j in enumerate(poly2): out[x+y] = (out[x+y]+(i*j)) % 3 return out def add(X: int, Y: int): # add two numbers in GF(3^81) # x represented in GF(3^81) x = [(X // (3 ** i)) % 3 for i in range(81)] # y represented in GF(3^81) y = [(Y // (3 ** i)) % 3 for i in range(81)] r = [(a + b) % 3 for a,b in zip(x, y)] Z = sum([r[i] * (3 ** i) for i in range(len(r))]) return Z def sub(X: int, Y: int): # subtract two numbers in GF(3^81) # x represented in GF(3^81) x = [(X // (3 ** i)) % 3 for i in range(81)] # y represented in GF(3^81) y = [(Y // (3 ** i)) % 3 for i in range(81)] r = [(a - b) % 3 for a,b in zip(x, y)] Z = sum([r[i] * (3 ** i) for i in range(len(r))]) return Z def mul(X: int, Y: int): # I'm using a custom field, its all homebrew # We're working in GF(3^81) coz were cool B) # its slightly bigger than 2^128 # modulus of the field modulus = [1,2,1,2,2,2,1,1,1,1,1,2,2,2,1,0,2,2,0,2,2,0,1,2,1,1,1,2,2,1,1,0,0,2,2,0,2,0,1,0,0,1,2,2,0,2,1,2,2,0,0,2,0,0,1,0,2,1,0,1,2,1,0,0,1,2,0,1,2,0,0,1,0,0,1,1,0,0,0,2,0,1] # x represented in GF(3^81) x = [(X // (3 ** i)) % 3 for i in range(81)] # y represented in GF(3^81) y = [(Y // (3 ** i)) % 3 for i in range(81)] # calculate product mul_res = mul_poly(x, y) # long division by modulus r = mul_res while r.count(0) != len(r) and degree(r) >= degree(modulus): d = [0] * (degree(r) - degree(modulus)) + modulus mult = (lead(r) * pow(lead(d), -1 , 3)) % 3 d2 = ([(mult * coeff) % 3 for coeff in d]) r = [(a - b) % 3 for a,b in zip(r, d2)] Z = sum([r[i] * (3 ** i) for i in range(len(r))]) return Z def ghash(H: bytes, X: bytes, block_len: int=128) -> bytes: block_len_b = (block_len//8) m = len(X) // block_len_b X_blocks = [int.from_bytes(X[i*block_len_b:(i+1)*block_len_b], 'big') for i in range(m)] H_int = int.from_bytes(H, 'big') # 0th block Y_i = 0 # iterate through the blocks Y_prev = Y_i for i in range(m): X_i = X_blocks[i] # each round is then Y_i = (X_i + Y_i-1) * H in GF(3^81) Y_i = mul(add(X_i, Y_prev), H_int) Y_prev = Y_i return (Y_i).to_bytes(block_len_b + 1, 'big') def inc(Y, ctr_len): Y = int.from_bytes(Y, 'big') # 0xffffff.... mask = 2 ** (ctr_len) - 1 # Y = iv || ctr # ignore iv, increment ctr Y_inc = ((Y >> ctr_len) << ctr_len) ^ (((Y & mask) + 1) & mask) return Y_inc.to_bytes(16, 'big') def gctr(cipher, icb: bytes, X: bytes, operation: str, block_len = 128, ctr_len = 32): if not X: return b'' # our ciphertext blocks are 16 + 1 byte long # bcs our |GF| is bigger than 16 bytes # but the plaintext blocks have to be 16 bytes # as the |GF| is still smaller than 17 bytes # and we don't want to overflow if operation == 'enc': block_len_input = block_len // 8 block_len_output = block_len // 8 + 1 elif operation == 'dec': block_len_input = block_len // 8 + 1 block_len_output = block_len // 8 elif operation == 'tag': block_len_input = block_len // 8 + 1 block_len_output = block_len // 8 + 1 n = math.ceil(len(X) / block_len_input) X_blocks = [int.from_bytes(X[i*block_len_input:(i+1)*block_len_input], 'big') for i in range(n)] # counter block cb = [icb] # generate counter blocks for i in range(1, n): cb_next = inc(cb[i-1], ctr_len) cb.append(cb_next) # calculate ciphertexts Y_blocks = [] for i in range(n): X_next = X_blocks[i] assert X_next < 3 ** 81 cb_next = cb[i] if operation == 'dec': Y_next = sub(X_next, int.from_bytes(cipher.encrypt(cb_next), 'big')) else: Y_next = add(X_next, int.from_bytes(cipher.encrypt(cb_next), 'big')) Y_blocks.append(Y_next) if operation == 'dec': Y = b''.join([(x).to_bytes(block_len_output, 'big').strip(b"\x00") for x in Y_blocks]) else: Y = b''.join([(x).to_bytes(block_len_output, 'big') for x in Y_blocks]) return Y def aes_gua_decrypt(ct: bytes, key: bytes, iv: bytes, additional_data: bytes, tag: bytes, t: int, block_len = 128): assert block_len == len(key) * 8 assert 0 < len(iv) * 8 < block_len assert t == len(tag) * 8 ctr_len = block_len - len(iv) * 8 cipher = AES.new(key, AES.MODE_ECB) # mac subkey H = cipher.encrypt(b'\x00' * (block_len // 8)) # first keystream block J_0 = iv + b'\x01'.rjust((ctr_len) // 8, b'\x00') # first decrypted block pt = gctr(cipher, inc(J_0, ctr_len), ct, 'dec') ct_len, A_len = len(ct) * 8, len(additional_data) * 8 u = 128 * math.ceil(ct_len / 128) - ct_len v = 128 * math.ceil(A_len / 128) - A_len # calculate hash zero_vector_v = b'\x00' * (v // 8) zero_vector_u = b'\x00' * (u // 8) A_64_len = int.to_bytes(A_len, 8, 'big') ct_64_len = int.to_bytes(ct_len, 8, 'big') S = ghash(H, additional_data + zero_vector_v + ct + zero_vector_u + A_64_len + ct_64_len) mask = b'\xff' * (t // 8) tag_prim = b_and(gctr(cipher, J_0, S, 'tag'), mask) if tag == tag_prim: return pt else: raise Exception("Invalid tag") def aes_gua_encrypt(pt: bytes, key: bytes, iv: bytes, additional_data: bytes, t: int, block_len = 128) -> (bytes, bytes): assert block_len == len(key) * 8 assert 0 < len(iv) * 8 <= block_len ctr_len = block_len - len(iv) * 8 cipher = AES.new(key, AES.MODE_ECB) # mac subkey H = cipher.encrypt(b'\x00' * (block_len // 8)) # first keystream block J_0 = iv + b'\x01'.rjust((ctr_len) // 8, b'\x00') # first encrypted block ct = gctr(cipher, inc(J_0, ctr_len), pt, 'enc') ct_len, A_len = len(ct) * 8, len(additional_data) * 8 u = 128 * math.ceil(ct_len / 128) - ct_len v = 128 * math.ceil(A_len / 128) - A_len # calculate hash zero_vector_v = b'\x00' * (v // 8) zero_vector_u = b'\x00' * (u // 8) A_64_len = int.to_bytes(A_len, 8, 'big') ct_64_len = int.to_bytes(ct_len, 8, 'big') S = ghash(H, additional_data + zero_vector_v + ct + zero_vector_u + A_64_len + ct_64_len) # Calculate mac tag T = gctr(cipher, J_0, S, 'tag')[:t // 8] return ct, T if __name__ == "__main__": # NIST test vector 2 key = bytearray.fromhex('fe47fcce5fc32665d2ae399e4eec72ba') iv = bytearray.fromhex('5adb9609dbaeb58cbd6e7275') #plaintext = bytearray.fromhex('7c0e88c88899a779228465074797cd4c2e1498d259b54390b85e3eef1c02df60e743f1b840382c4bccaf' # '3bafb4ca8429bea063') plaintext = b'test12345678mnbvcxzdsadasdadas3123r123312312adskadkadk222' associated_data = bytearray.fromhex('88319d6e1d3ffa5f987199166c8a9b56c2aeba5a') t = 128 ciphertext, auth_tag = aes_gua_encrypt(plaintext, key, iv, associated_data, t) pt = aes_gua_decrypt(ciphertext, key, iv, associated_data, auth_tag, t) print(pt) assert (aes_gua_decrypt(ciphertext, key, iv, associated_data, auth_tag, t).hex() == plaintext.hex()) try: (aes_gua_decrypt(b'\x01' + ciphertext[:1], key, iv, associated_data, auth_tag, t).hex() == plaintext.hex()) print('tag failed') exit(1) except Exception as E: pass print("tests ok")
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/BreakTheSyntax/2023/crypto/Ed_Edd_n_Eddy/2f111c615d12391545a7ec07082a84dc.py
ctfs/BreakTheSyntax/2023/crypto/Ed_Edd_n_Eddy/2f111c615d12391545a7ec07082a84dc.py
from sympy import GF from hashlib import sha256 from dataclasses import dataclass from hashlib import sha512 def H(message: str) -> bytes: return int.from_bytes(sha512(message.encode()).digest(), 'big') % q # Ed448 curve p = 2 ** 448 - 2 ** 224 - 1 # group order q = 2 ** 446 - 0x8335dc163bb124b65129c96fde933d8d723a70aadc873d6d54a7bb0d # field definition GFp = GF(p) GFq = GF(q) # curve param d = GFp(-39081) # generator B_x = GFp(224580040295924300187604334099896036246789641632564134246125461686950415467406032909029192869357953282578032075146446173674602635247710) B_y = GFp(298819210078481492676017930443930673437544040154080242095928241372331506189835876003536878655418784733982303233503462500531545062832660) def check_if_on_curve(x, y): a = 1 return (a * x ** 2 + y ** 2) == (1 + d*x ** 2*y ** 2) @dataclass class Point(): x: int y: int def _point_add(self, P, Q): # https://eprint.iacr.org/2008/522.pdf # check if both points are on the curve if not check_if_on_curve(P.x, P.y): raise Exception(f"Point {(P.x, P.y)} is not on the curve!") if not check_if_on_curve(Q.x, Q.y): raise Exception(f"Point {(Q.x, Q.y)} is not on the curve!") #if they are equal, double if (Q == P): return self._point_double(P) # projective coordinate Z = 1 for all points (coz we're working on affine :)) A = GFp(1) B = A ** 2 C = P.x * Q.x D = P.y * Q.y E = d * C * D F = B - E G = B + E H = (P.x + P.y) * (Q.x + Q.y) X = A * F * (H - C - D) Y = A * G * (D - C) Z = F * G # the result is in projective coords, switch to affine x = X / Z y = Y / Z return self.__class__(x, y) def _point_double(self, P): # https://eprint.iacr.org/2008/522.pdf # check if point is on the curve if not check_if_on_curve(P.x, P.y): raise Exception(f"Point {(P.x, P.y)} is not on the curve!") B = (P.x + P.y) ** 2 C = P.x ** 2 D = P.y ** 2 E = C + D # projective coordinate Z = 1 for all points (coz we're working on affine :)) H = GFp(1) J = E - 2 * H X = (B - E) * J Y = E * (C - D) Z = E * J # the result is in projective coords, switch to affine x = X / Z y = Y / Z return self.__class__(x, y) def _point_multiply(self, x, P): # check if point is on the curve if not check_if_on_curve(P.x, P.y): raise Exception(f"Point {(P.x, P.y)} is not on the curve!") Q = Point(GFp(0), GFp(1)) # Neutral element while x > 0: if x & 1: Q = Q + P P = P + P x >>= 1 return Q def __repr__(self): return f'({self.x}, {self.y})' def __neg__(self): return self.__class__(self.x, -self.y) def __add__(self, other): return self._point_add(self, other) def __mul__(self, other: int): return self._point_multiply(other, self) def __rmul__(self, other: int): return self._point_multiply(other, self) def check_if_on_twisted_curve(x, y): a = -1 d_twisted = (d - 1) return (a * x ** 2 + y ** 2) == (1 + d_twisted * x ** 2 * y ** 2) class EddysPoint(Point): # heh, I stole the idea to use isogeny from OpenSSL, # my implemention is so much better than Edd's. NO DOWNSIDES!!! # And he's supposed to be the smart guy, lol # https://eprint.iacr.org/2014/027.pdf def __init__(self, x, y, twist = True): if twist: self.x, self.y = self.isogeny(1, Point(x, y)) else: self.x, self.y = (x, y) def untwisted(self): x, y = self.isogeny(-1, self) return (x, y) def isogeny(self, a, P): x = (2 * P.x * P.y) / (P.y ** 2 - a * P.x ** 2) y = (P.y ** 2 + a * P.x ** 2) / (2 - P.y ** 2 - a * P.x ** 2) return (x, y) def _point_add_twisted(self, P, Q): # https://eprint.iacr.org/2008/522.pdf # check if both points are on the curve if not check_if_on_twisted_curve(P.x, P.y): raise Exception(f"Point {(P.x, P.y)} is not on the curve!") if not check_if_on_twisted_curve(Q.x, Q.y): raise Exception(f"Point {(Q.x, Q.y)} is not on the curve!") #if they are equal, double if (Q == P): return self._point_double_twisted(P) Tp = P.x * P.y Tq = Q.x * Q.y # we can use a faster formula without d now! A = (P.y - P.x) * (Q.y + Q.x) B = (P.y + P.x) * (Q.y - Q.x) C = 2 * Tq D = 2 * Tp E = D + C F = B - A G = B + A H = D - C X = E * F Y = G * H Z = F * G # switch to affine x = X / Z y = Y / Z return self.__class__(x, y, False) def _point_double_twisted(self, P): # https://eprint.iacr.org/2008/522.pdf if not check_if_on_twisted_curve(P.x, P.y): raise Exception(f"Point {(P.x, P.y)} is not on the curve!") A = P.x ** 2 B = P.y ** 2 C = 2 # twisted curve a = -1 D = a * A E = (P.x + P.y) ** 2 - A - B G = D + B F = G - C H = D - B X = E * F Y = G * H Z = F * G # the result is in projective coords, switch to affine x = X / Z y = Y / Z return self.__class__(x, y, False) def _point_multiply_twisted(self, x, P): # check if point is on the curve if not check_if_on_twisted_curve(P.x, P.y): raise Exception(f"Point {(P.x, P.y)} is not on the curve!") Q = EddysPoint(GFp(0), GFp(1)) # Neutral element while x > 0: if x & 1: Q = self._point_add_twisted(P, Q) P = self._point_double_twisted(P) x >>= 1 return Q def __add__(self, other): return self._point_add_twisted(self, other) def __mul__(self, other: int): return self._point_multiply_twisted(other, self) def __rmul__(self, other: int): return self._point_multiply_twisted(other, self) if __name__ == "__main__": B = Point(B_x, B_y) assert not 3 * B == B + B, "Assertion error, (P * 3) = (P + P)" assert (B + (B)) + (B + B + B) == B * 5, "Assertion error, (P + P) + (P + P + P) != 5P" assert (B + B) + (B + B) == B * 2 + B * 2, "Assertion error, (P + P) + (P + P) != 2P + 2P" assert B * 2 + B * 3 == (B * 2) * 2 + B, "Assertion error, P*2 + P*3 != (P*2)*2 + 1" B = EddysPoint(B_x, B_y) assert not 3 * B == B + B, "Assertion error, (P * 3) = (P + P)" assert (B + (B)) + (B + B + B) == B * 5, "Assertion error, (P + P) + (P + P + P) != 5P" assert (B + B) + (B + B) == B * 2 + B * 2, "Assertion error, (P + P) + (P + P) != 2P + 2P" assert B * 2 + B * 3 == (B * 2) * 2 + B, "Assertion error, P*2 + P*3 != (P*2)*2 + 1" print("ok")
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/BreakTheSyntax/2023/crypto/Ed_Edd_n_Eddy/fdfaf30d47a2ce2be09a240b5e4361cf.py
ctfs/BreakTheSyntax/2023/crypto/Ed_Edd_n_Eddy/fdfaf30d47a2ce2be09a240b5e4361cf.py
from ed448 import * from os import urandom # important with open('ed', 'r') as f: eds_face = f.read() with open('flag', 'r') as f: flag = f.read() def generate_key(): sk = int(H(urandom(114).hex())) B = Point(B_x, B_y) pk = sk * B return sk, pk class EddyVerifier: def __init__(self, pk): # we need those untwisted for hash self.pk_x = int(pk.x) % p # mod p because casting sympy's GF to int returns negative values sometimes self.pk_y = int(pk.y) % p self.pk = EddysPoint(pk.x, pk.y) def verify(self, m, R_x, R_y, s): if s != s % q: return False R = EddysPoint(GFp(R_x), GFp(R_y)) B = EddysPoint(B_x, B_y) k = H(str(R_x) + str(R_y) + str(self.pk_x) + str(self.pk_y) + m) return s * B == R + k * (self.pk) class EddVerifier: def __init__(self, pk): self.pk_x = int(pk.x) % p # mod p because casting sympy's GF to int returns negative values sometimes self.pk_y = int(pk.y) % p self.pk = Point(pk.x, pk.y) def verify(self, m, R_x, R_y, s): if s != s % q: return False R = Point(GFp(R_x), GFp(R_y)) B = Point(B_x, B_y) k = H(str(R_x) + str(R_y) + str(self.pk_x) + str(self.pk_y) + m) return s * B == R + k * (self.pk) if __name__=="__main__": sk, pk = generate_key() eddy_verifier = EddyVerifier(pk) edd_verifier = EddVerifier(pk) print(eds_face) eds_message = "Lets grab edds funny electronic device and sell it for GRAVY!!!" print("-" * 50) print("Ed: HELP!!! I NEED TO PASS AN IMPORTANT MESSAGE TO EDDY, BUT DOUBLE D \ CANNOT KNOW ITS FROM ME!!!! AT THE SAME TIME, EDDY MUST KNOW ITS FROM ME!!! I DON'T KNOW \ WHAT TO DO!!!!! my brain is hurting...") print("HERE, HAVE MY SIGNING KEY AND DO SOMETHING, QUICKLY!!!") print("-" * 50) print("message to sign:", eds_message) print("signing key:", sk) input("Got it?\n>") print("-" * 50) print("Eddy: HEY, what are you two doing here? We need to find a way to get money!") print("Edd: Yeah, and lets do it fast. I can't wait to get home and play with my newest TI-84 Graphic Calculatorβ„’") print("Eddy: Is this some kind of secret message? Show me!") print("-" * 50) m = input("Show message:\n>") print("And the signature") R_x = int(input("Rx:\n>")) R_y = int(input("Ry:\n>")) s = int(input("s:\n>")) print("-" * 50) if m != eds_message: print("Eddy: I don't get it...") exit(0) print("Edd: WHAT?! FOR GRAVY?! IS THIS YOUR MESSAGE ED?! I NEED TO CHECK") if edd_verifier.verify(m, R_x, R_y, s): print("--- EDDS VERIFICATION SUCCESSFUL ---") print("Edd: ED, IM GONNA TELL YOUR MUM!") print("Ed: NOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOO") exit(0) print("--- EDDS VERIFICATION FAILED ---") print("Edd: You're lucky the signature is not yours... it must be Kevins idea then!") if not eddy_verifier.verify(m, R_x, R_y, s): print("--- EDDYS VERIFICATION FAILED ---") print("Eddy: What a stupid idea as well! Who would want to buy something so boring anyway") exit(0) print("--- EDDYS VERIFICATION SUCCESSFUL ---") print("Eddy: Yeah you should leave it with us, we will take care of it while you look for him! (( you know a buyer Ed???? ))") print("** Edd leaves his calc and goes to find Kevin **") print("Eddy: Nice job. Here's your cut:") print("-" * 50) print("flag =", flag)
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/BreakTheSyntax/2023/crypto/Textbook/f4254d3801a2b78e272bda65abd9c887.py
ctfs/BreakTheSyntax/2023/crypto/Textbook/f4254d3801a2b78e272bda65abd9c887.py
from Crypto.Util.number import getPrime, GCD, getRandomRange from collections import namedtuple with open('flag', 'r') as f: flag = f.read() public = namedtuple('public', 'n g') secret = namedtuple('secret', 'n phi mu') sig = namedtuple('sig', 's1 s2') b = 1024 p = getPrime(b) q = getPrime(b) assert p != q n = p * q phi = (p - 1) * (q - 1) g = n + 1 mu = pow(phi, -1, n) pk = public(n, g) sk = secret(n, phi, mu) # mask for additional security!!! mask = getRandomRange(2 ** (n.bit_length() * 2 - 2), (2 ** (n.bit_length() * 2 - 1))) def h(s: bytes) -> int: return int.from_bytes(s, 'big', signed=True) def int_to_bytes(n: int) -> bytes: return n.to_bytes(n.bit_length() // 8 + 1, 'big', signed=True) def encrypt(m: bytes, pk: public) -> bytes: n, g = pk r = getRandomRange(1, n) assert GCD(r, n) == 1 mh = h(m) c = (pow(g, mh, n ** 2) * pow(r, n, n ** 2)) % (n ** 2) return pow(c, mask, n ** 2) def sign(m: bytes, sk: secret) -> sig: n, phi, mi = sk mh = (h(m) * mask) % (n ** 2) d = pow(mh, phi, n ** 2) e = (d - 1) // n s1 = (e * mi) % n n_inv = pow(n, -1, phi) s2 = pow(mh * pow(g, -s1, n), n_inv, n) return sig(s1, s2) def verify(m: bytes, sig: sig, pk: public) -> bool: s1, s2 = sig n, g = pk mh = (h(m) * mask) % (n ** 2) m_prim = pow(g, s1, n ** 2) * pow(s2, n, n ** 2) % (n ** 2) return m_prim == mh if __name__=="__main__": flag_enc = encrypt(flag.encode(), pk) flag_enc = int_to_bytes(flag_enc) print("Hello to my signing service ^^\n") print("My public key:") print("n =", pk.n) print("g =", pk.g) print("\nHere, have flag. It's encrypted and masked anyways, so who cares.\n") print("flag =", (flag_enc.hex()), "\n") while True: print("What do you want to do?") print("[1] Sign something", "[2] Verify signature", "[3] Exit", sep="\n") function = input(">") if function == "1": message = bytes.fromhex(input("Give me something to sign!\n(hex)>")) signature = sign(message, sk) print(f"s1 = {signature.s1}\ns2 = {signature.s2}") if function == "2": message = bytes.fromhex(input("Message to verify\n(hex)>")) print("Signature:") signature = sig(int(input("s1:\n(int)>")), int(input("s2:\n(int)>"))) if verify(message, signature, pk): print("verified!") else: print("not verified!") if function == "3": exit()
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/BreakTheSyntax/2023/crypto/Textbook_2/6fc5ec8da17d4fff885e6d4dd52f78d3.py
ctfs/BreakTheSyntax/2023/crypto/Textbook_2/6fc5ec8da17d4fff885e6d4dd52f78d3.py
from Crypto.Util.number import getPrime, GCD, getRandomRange from collections import namedtuple with open('flag', 'r') as f: flag = f.read() public = namedtuple('public', 'n g') secret = namedtuple('secret', 'n phi mu') sig = namedtuple('sig', 's1 s2') b = 1024 p = getPrime(b) q = getPrime(b) assert p != q n = p * q phi = (p - 1) * (q - 1) g = n + 1 mu = pow(phi, -1, n) pk = public(n, g) sk = secret(n, phi, mu) # masks for additional security!!! mask1 = getRandomRange(2 ** (n.bit_length() * 2 - 2), (2 ** (n.bit_length() * 2 - 1))) mask2 = getRandomRange(2 ** (n.bit_length() * 2 - 2), (2 ** (n.bit_length() * 2 - 1))) def h(s: bytes) -> int: return int.from_bytes(s, 'big', signed=True) def int_to_bytes(n: int) -> bytes: return n.to_bytes(n.bit_length() // 8 + 1, 'big', signed=True) def encrypt(m: bytes, pk: public) -> bytes: n, g = pk r = getRandomRange(1, n) assert GCD(r, n) == 1 mh = h(m) c = (pow(g, mh, n ** 2) * pow(r, n, n ** 2)) % (n ** 2) return pow(c, mask1, n ** 2) def sign(m: bytes, sk: secret) -> sig: n, phi, mu = sk mh = (h(m) * mask2) % (n ** 2) d = pow(mh, phi, n ** 2) e = (d - 1) // n s1 = (e * mu) % n n_inv = pow(n, -1, phi) s2 = pow(mh * pow(g, -s1, n), n_inv, n) return sig(s1, s2) def verify(m: bytes, sig: sig, pk: public) -> bool: s1, s2 = sig n, g = pk mh = (h(m) * mask2) % (n ** 2) m_prim = pow(g, s1, n ** 2) * pow(s2, n, n ** 2) % (n ** 2) return m_prim == mh if __name__=="__main__": flag_enc = encrypt(flag.encode(), pk) flag_enc = int_to_bytes(flag_enc) print("Hello to my signing service. You don't need any keys, all is handled by me ^^\n") #print("My public key:") #print("n =", pk.n) #print("g =", pk.g) print("\nHere, have flag. It's encrypted and masked anyways, so who cares.\n") print("flag =", (flag_enc.hex()), "\n") while True: print("What do you want to do?") print("[1] Sign something", "[2] Verify signature", "[3] Encrypt something", "[4] Exit", sep="\n") function = input(">") if function == "1": message = bytes.fromhex(input("Give me something to sign!\n(hex)>")) signature = sign(message, sk) print(f"s1 = {signature.s1}\ns2 = {signature.s2}") if function == "2": message = bytes.fromhex(input("Message to verify\n(hex)>")) print("Signature:") signature = sig(int(input("s1:\n(int)>")), int(input("s2:\n(int)>"))) if verify(message, signature, pk): print("verified!") else: print("not verified!") if function == "3": message = bytes.fromhex(input("Message to encrypt\n(hex)>")) ciphertext = encrypt(message, pk) print("c =", int_to_bytes(ciphertext).hex()) if function == "4": exit()
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/BreakTheSyntax/2023/crypto/Break_PSI/2e0f6f7b0a5c6e6e3430484ebbefa819.py
ctfs/BreakTheSyntax/2023/crypto/Break_PSI/2e0f6f7b0a5c6e6e3430484ebbefa819.py
from Crypto.Hash import SHA256 from Crypto.Util.number import long_to_bytes import random FLAG = open("flag", "r") A = [] B = [] Ahash = [] Bhash = [] Ainv = {} Binv = {} limit = 32 setSize = 17 reps = 8 def intersection(A, B): return [v for v in A if v in B] def F(x): h = SHA256.new(data=long_to_bytes(x)) return h.digest().hex() def hash_list(l): h = SHA256.new(data=bytes(str(l), "utf-8")) return h.digest() def is_valid(Asi, Bsi): if Asi == [] or Bsi == []: return 0 if hash_list(Asi) != hash_list(Bsi): return 0 cnt = {} for a in Asi: if Ainv[a] in cnt: cnt[Ainv[a]] += 1 else: cnt[Ainv[a]] = 1 for v in cnt.values(): if v != reps + 1: return 0 cnt = {} for b in Bsi: if Binv[b] in cnt: cnt[Binv[b]] += 1 else: cnt[Binv[b]] = 1 for v in cnt.values(): if v != reps + 1: return 0 return 1 for i in range(420): A = random.sample(range(limit), setSize) B = random.sample(range(limit), setSize) Ahash = [] Bhash = [] Ainv = {} Binv = {} for i in range(setSize): for j in range(1, reps + 1): A.append(A[i] + limit * j) B.append(B[i] + limit * j) for a in A: h = F(a) Ahash.append(h) Ainv[h] = a % limit for b in B: h = F(b) Bhash.append(h) Binv[h] = b % limit print("Alice:", Ahash) print("Bob:", Bhash) Asi = input("Send PSI to Alice: ").split() Bsi = input("Send PSI to Bob: ").split() if is_valid(Asi, Bsi): if intersection(Ahash, Bhash) == Asi and intersection(Ahash, Bhash) == Bsi: print("Honesty is not a way to solve this challenge") exit() else: print("Cheater!") exit() print("You got me! Here is your flag:", FLAG.read())
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/BreakTheSyntax/2023/web/Curly_Fries/c4b482fe51bcf8c5dd986580cfc87569.py
ctfs/BreakTheSyntax/2023/web/Curly_Fries/c4b482fe51bcf8c5dd986580cfc87569.py
import datetime import functools import random import subprocess from urllib.parse import quote_plus, urlencode from .db import get_tasks, get_user, register_user from flask import redirect, render_template, request, url_for, Blueprint from flask_jwt_extended import create_access_token, jwt_required from flask_jwt_extended.exceptions import NoAuthorizationError from . import jwt """ Challenge description: Welcome to Curly Fries Restaurant! We love our fries curly and we hope you will too. Just place your order, sit back, relax and watch as our team runs around the kitchen to quickly deliver your meal! """ bp = Blueprint("app_1", __name__) def localhost_only(f): @functools.wraps(f) def decorated_function(*args, **kwargs): if request.remote_addr != "127.0.0.1": return render_template( "info.html", info="This page can only be accessed locally!" ) return f(*args, **kwargs) return decorated_function @bp.route("/") def index(): return render_template("index.html") # Reports say some customers tried to smuggle something extra in their order ... @bp.route("/order", methods=["POST"]) def order(): form = request.form params = [k + "=" + v for k, v in form.items()] command = "curl -X POST http://127.0.0.1:1337/kitchen -d " + "&".join(params) try: return subprocess.check_output(command.split(" ")) except: return render_template( "info.html", info="Oops ... there was a problem processing your order :(" ) @bp.route("/kitchen", methods=["POST"]) @localhost_only def kitchen(): order_items = ", ".join([k + ": " + v for k, v in request.form.items()]) order_id = random.randint(13, 37) order_time = ( datetime.datetime.now() + datetime.timedelta(minutes=random.randint(5, 10)) ).strftime("%H:%M") return render_template( "info.html", info="Your order has been placed!", items=order_items, id=order_id, time=order_time, ) @bp.route("/register", methods=["GET", "POST"]) @localhost_only def register(): if request.method == "POST": username = request.form["username"] password = request.form["password"] if register_user(username, password): return render_template( "info.html", info="Success! Thank you for registering at Curly Fries Restaurant.", ) else: return render_template("info.html", info="This user already exists!") return render_template("register.html") @bp.route("/login", methods=["GET", "POST"]) def login(): if request.method == "POST": username = request.form["username"] password = request.form["password"] user = get_user(username, password) if user: token = create_access_token(identity=username) resp = redirect(url_for("dashboard")) resp.set_cookie("access_token_cookie", token) return resp else: return render_template("info.html", info="Invalid credentials!") return render_template("login.html") @bp.route("/dashboard") @jwt_required() def dashboard(): tasks = get_tasks() return render_template("dashboard.html", tasks=tasks) # JWT error handling @jwt.unauthorized_loader def handle_unauthorized(error): if isinstance(error, NoAuthorizationError): return render_template("info.html", info="Missing access token cookie"), 401 else: return render_template("info.html", info="Unauthorized"), 401
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/BreakTheSyntax/2022/crypto/identity3/server.py
ctfs/BreakTheSyntax/2022/crypto/identity3/server.py
#!/ust/bin/env python3 import random import json import signal prime_p = 136062877477772021443963986821466822423928306636725705955189295265171531194630539497933022412421177627488716473227275120023271715397034546804175879349877168981582602251424924699340785448683074807806407936267383798949594772365085169340683942944085482956202789355681500477966677233789310292180313638378062381719 prime_q = 68031438738886010721981993410733411211964153318362852977594647632585765597315269748966511206210588813744358236613637560011635857698517273402087939674938584490791301125712462349670392724341537403903203968133691899474797386182542584670341971472042741478101394677840750238983338616894655146090156819189031190859 generator = 68695322546411990097618816719880607069395444393834268960741680054974511660271970026150039567236118658479679444015844573677880347686810169165388385685914903968147097279757787122753390447954112451193808647256026282821032909814441591222220915875289906762225085266354556177943238500761050758957943922408034634359 pubkey = 36991800195284720665844271720947930981390989677197504667186660329002236402308726349324091955441781822949964937615015455023644196915268032941399396215222246260792225979887225009692399584709504066456654354497353988045808198493705842231370889778472138080706702885925221219949367522908916161488494916365255595354 def verify_identity(x,y,c): r = ( pow(generator,y,prime_p) * pow(pubkey,c,prime_p) ) % prime_p return r == x def main(): signal.alarm(60) print("Hello") x = input() x = json.loads(x) challenge = { 'c' : random.randrange(1,2**512) } print(json.dumps(challenge)) y = input() y = json.loads(y) if verify_identity(x['x'],y['y'],challenge['c']) : print("Verification success") with open("./flag.txt","r") as flag: print(flag.read()) else: print("Verification failure") 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/BreakTheSyntax/2022/crypto/identity2/server.py
ctfs/BreakTheSyntax/2022/crypto/identity2/server.py
#!/ust/bin/env python3 import random import json import signal prime_p = 136062877477772021443963986821466822423928306636725705955189295265171531194630539497933022412421177627488716473227275120023271715397034546804175879349877168981582602251424924699340785448683074807806407936267383798949594772365085169340683942944085482956202789355681500477966677233789310292180313638378062381719 prime_q = 68031438738886010721981993410733411211964153318362852977594647632585765597315269748966511206210588813744358236613637560011635857698517273402087939674938584490791301125712462349670392724341537403903203968133691899474797386182542584670341971472042741478101394677840750238983338616894655146090156819189031190859 generator = 68695322546411990097618816719880607069395444393834268960741680054974511660271970026150039567236118658479679444015844573677880347686810169165388385685914903968147097279757787122753390447954112451193808647256026282821032909814441591222220915875289906762225085266354556177943238500761050758957943922408034634359 pubkey = 36991800195284720665844271720947930981390989677197504667186660329002236402308726349324091955441781822949964937615015455023644196915268032941399396215222246260792225979887225009692399584709504066456654354497353988045808198493705842231370889778472138080706702885925221219949367522908916161488494916365255595354 def verify_identity(x,y,c): r = ( pow(generator,y,prime_p) * pow(pubkey,c,prime_p) ) % prime_p return r == x def main(): signal.alarm(60) challenge = { 'c' : random.randrange(1,2**512) } print(json.dumps(challenge)) proof = input() proof = json.loads(proof) if verify_identity(proof['x'],proof['y'],challenge['c']) : print("Verification success") with open("./flag.txt","r") as flag: print(flag.read()) else: print("Verification failure") 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/BreakTheSyntax/2022/crypto/identity/chal.py
ctfs/BreakTheSyntax/2022/crypto/identity/chal.py
#!/ust/bin/env python3 import json import signal prime_p = 177722061268479172618036265876397003509269048504268861767046046115994443156284488651055714387194800232244730303458489864174073986896097610603558449505871398422283548997781783328299833985053166443389417018452145117134522568709774729520563358860355765070837814475957567869527710749697252440829860298572991179307 prime_q = 88861030634239586309018132938198501754634524252134430883523023057997221578142244325527857193597400116122365151729244932087036993448048805301779224752935699211141774498890891664149916992526583221694708509226072558567261284354887364760281679430177882535418907237978783934763855374848626220414930149286495589653 generator = 155023513036247948265047543654868687396096131010469506673664792405197011708229660714554316186573661708325589755749538173765363486885279182722265095526282277543504738661074255038508180451933144124775391105622347889120007632958758010276343139080391061202699695556814560529729431091459632136589488173063954346793 pubkey = 93091921640159468106305784288442650651946378295897246569419220256788465679993825629909743857075454596032445144833173746431710294553277863156332557755414563641361390587128850058131535616906913180516458195808877783654160132170722826553007632858895507833301845277489859624212766615307390655119628578839365223546 def verify_identity(x,y): r = (pow(generator,y,prime_p) * pubkey) % prime_p return r == x def main(): signal.alarm(60) proof = input("send proof in json format: ") proof = json.loads(proof) if verify_identity(proof['x'],proof['y']) : print("Verification success") with open("./flag.txt","r") as flag: print(flag.read()) else: print("Verification failure") 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/NewportBlakeCTF/2023/misc/Myjail/chall.py
ctfs/NewportBlakeCTF/2023/misc/Myjail/chall.py
#!/usr/bin/env python3 # Thanks CSAW2023 for the inspiration import ast import sys BANNED = { #def not ast.Import, ast.ImportFrom, ast.With, ast.alias, ast.Attribute, ast.Constant, #should be fine? ast.Subscript, ast.Assign, ast.AnnAssign, ast.AugAssign, ast.For, ast.Try, ast.ExceptHandler, ast.With, ast.withitem, ast.FunctionDef, ast.Lambda, ast.ClassDef, #prob overkill but should be fine ast.If, ast.And, ast.comprehension, ast.In, ast.Await, ast.Global, ast.Gt, ast.ListComp, ast.Slice, ast.Return, ast.List, ast.Dict, ast.Lt, ast.AsyncFunctionDef, ast.Eq, ast.keyword, ast.Mult, ast.arguments, ast.FormattedValue, ast.Not, ast.BoolOp, ast.Or, ast.Compare, ast.GtE, ast.ImportFrom, ast.Tuple, ast.NotEq, ast.IfExp, ast.alias, ast.arg, ast.JoinedStr, # Patch some more >:) ast.Match, ast.Del, ast.Starred, ast.Is, ast.NamedExpr, } def hook(event, args): if not hook.exec and 'exec' in event: hook.exec = True return strr = event + " ".join(f"{x}" for x in args) strr = strr.lower() if any(i in strr for i in [ 'exec', 'print', 'import', 'system', 'flag', 'spawn', 'fork', 'open', 'subprocess', 'sys', 'ast', 'os', 'audit', 'hook' 'compile', '__new__', 'frame']): print("BONK audit!", event + " " + " ".join(f"{x}" for x in args)) exit() # print("audit!", event + " " + " ".join(f"{x}" for x in args)) hook.exec = False def banner(): print("Hello world! Please input your program here: ") code = input() for n in ast.walk(ast.parse(code)): if type(n) in BANNED: print("BAD CODE! BONK!: " + str(type(n))) exit() return code code = banner() code = compile(code, "<code>", "exec") safer_builtins = __builtins__.__dict__.copy() banned_builtins = [ 'exec', 'eval', 'compile', 'type', 'globals', 'dir', 'callable', 'type', 'all', 'any', 'int', 'input', 'breakpoint', 'print', 'quit', 'exit', 'copyright', 'credits', 'license', 'help', ] for banned in banned_builtins: safer_builtins.pop(banned, None) # safer sys.addaudithook(hook) exec(code, {"__builtins__": safer_builtins})
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/NewportBlakeCTF/2023/algo/sudoku_revenge/sudoku-revenge.py
ctfs/NewportBlakeCTF/2023/algo/sudoku_revenge/sudoku-revenge.py
#!/usr/local/bin/python from random import * from flag import flag t = 20 print(t) min_n = 100 for _ in range(t): n = randint(min_n, min_n * 2) print(n) a = [] for i in range(n): a.append(i + 1) shuffle(a) for i in range(n): print(a[i], end="") if i < n - 1: print(" ", end="") print() arr = [] for i in range(n): ar = input().split(" ") for j in range(n): ar[j] = int(ar[j]) arr.append(ar) for i in range(n): if arr[i][a[i] - 1] != i + 1: print("WA") exit() for i in range(n): rw = [] cl = [] for j in range(n): if min(arr[i][j], arr[j][i]) < 1 or max(arr[i][j], arr[j][i]) > n: print("WA") exit() if arr[i][j] not in rw: rw.append(arr[i][j]) if arr[j][i] not in cl: cl.append(arr[j][i]) if len(rw) < n or len(cl) < n: print("WA") exit() print("AC", flag)
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/NewportBlakeCTF/2023/algo/sudoku/sudoku.py
ctfs/NewportBlakeCTF/2023/algo/sudoku/sudoku.py
#!/usr/local/bin/python from random import * from flag import flag t = 20 print(t) min_n = 100 for _ in range(t): n = randint(min_n, min_n * 2) print(n) a = [] for i in range(n): a.append(i + 1) shuffle(a) for i in range(n): print(a[i], end="") if i < n - 1: print(" ", end="") print() arr = [] for i in range(n): ar = input().split(" ") for j in range(n): ar[j] = int(ar[j]) arr.append(ar) for i in range(n): if arr[i][a[i] - 1] != i + 1: print("WA") exit() for i in range(n): rw = [] cl = [] for j in range(n): if arr[i][j] not in rw: rw.append(arr[i][j]) if arr[j][i] not in cl: cl.append(arr[j][i]) if len(rw) < n or len(cl) < n: print("WA") exit() print("AC", flag)
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/NewportBlakeCTF/2023/rev/Crisscross/main.py
ctfs/NewportBlakeCTF/2023/rev/Crisscross/main.py
import random key1 = random.choices(range(256), k=20) key2 = list(range(256)) random.shuffle(key2) flag = open('flag.txt', 'rb').read() def enc(n): q = key2[n] w = key1[q % 20] n ^= q return n, w x = 0 for i, c in enumerate(flag): x <<= 8 n, w = enc(c) if i % 2: n, w = w, n x |= n x |= w << ((2 * i + 1) * 8) print(key1) print(key2) print(x)
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/NewportBlakeCTF/2023/crypto/Spinning_my_way_to_Straight_Lines_REVENGE/chall.py
ctfs/NewportBlakeCTF/2023/crypto/Spinning_my_way_to_Straight_Lines_REVENGE/chall.py
from Crypto.Util.number import * import os def xor(a, b): return bytes(i^j for i, j in zip(a,b)) sbox = [239, 209, 87, 244, 56, 155, 29, 190, 230, 69, 8, 96, 172, 15, 137, 42, 52, 154, 28, 191, 115, 208, 86, 245, 173, 14, 136, 43, 231, 134, 194, 97, 228, 71, 193, 98, 174, 13, 139, 40, 112, 211, 85, 246, 58, 2, 31, 188, 175, 12, 138, 41, 229, 70, 192, 99, 59, 152, 30, 189, 113, 210, 84, 247, 61, 158, 24, 187, 119, 212, 82, 249, 169, 10, 140, 47, 227, 64, 198, 101, 118, 213, 83, 240, 60, 159, 25, 186, 226, 65, 199, 100, 168, 11, 141, 46, 171, 195, 142, 45, 225, 66, 196, 0, 63, 156, 26, 185, 117, 214, 80, 243, 224, 67, 197, 102, 170, 9, 143, 44, 116, 215, 81, 242, 62, 157, 27, 184, 236, 79, 201, 106, 166, 5, 131, 32, 120, 219, 93, 254, 50, 145, 23, 180, 167, 4, 130, 33, 75, 78, 200, 107, 51, 144, 22, 181, 121, 218, 92, 255, 122, 217, 95, 252, 48, 147, 21, 182, 238, 77, 203, 104, 164, 7, 129, 34, 49, 146, 20, 183, 123, 216, 94, 253, 165, 6, 128, 35, 114, 76, 202, 105, 163, 103, 68, 37, 233, 74, 204, 111, 55, 148, 18, 177, 125, 222, 88, 251, 232, 237, 205, 110, 162, 1, 135, 36, 124, 223, 89, 250, 54, 149, 19, 176, 53, 150, 16, 179, 127, 220, 90, 241, 161, 153, 132, 39, 235, 72, 206, 109, 126, 221, 91, 248, 57, 151, 17, 178, 234, 73, 207, 108, 160, 3, 133, 38] permute = [10, 11, 5, 6, 2, 4, 8, 0, 12, 9, 3, 13, 14, 15, 1, 7] bit_permute = [117, 31, 57, 48, 67, 44, 13, 39, 77, 84, 63, 123, 76, 19, 103, 75, 37, 100, 102, 46, 120, 0, 127, 118, 122, 110, 93, 21, 3, 16, 80, 27, 45, 66, 73, 89, 61, 41, 52, 79, 108, 109, 121, 26, 68, 7, 58, 43, 126, 83, 53, 32, 18, 96, 14, 107, 98, 29, 105, 22, 65, 72, 119, 101, 6, 112, 34, 92, 12, 60, 20, 51, 30, 99, 1, 64, 94, 42, 15, 116, 4, 74, 10, 115, 40, 87, 9, 111, 81, 11, 124, 106, 49, 86, 23, 78, 88, 56, 62, 114, 33, 91, 97, 69, 8, 95, 25, 17, 90, 24, 50, 70, 125, 47, 104, 71, 36, 55, 5, 2, 85, 28, 35, 113, 59, 82, 38, 54] BLOCK_LEN = 16 class SPN: def __init__(self, key, iv): self.master_key = key self.iv = iv self.round_keys = self.expand_key() def expand_key(self): round_keys = [self.master_key] for i in range(42): round_keys.append(round_keys[-1][2:] + round_keys[-1][:2]) return round_keys def pad(self, plaintext): return plaintext + b"\x00"*(BLOCK_LEN - (len(plaintext) % BLOCK_LEN)) def permute(self, block): permuted = b"" for i in permute: permuted += block[i].to_bytes(1, 'little') return permuted def bit_permute(self, block): bits = list(bin(int(block.hex(), 16))[2:].zfill(16*8)) new_bits = ["0"]*128 for i in range(len(bits)): new_bits[i] = bits[bit_permute[i]] blockies = long_to_bytes(int(''.join(new_bits), 2), 8) return blockies def add_key(self, block, round_key): return xor(block, round_key) def substitute(self, block): subbed = b"" for i in block: subbed += sbox[i].to_bytes(1, 'little') return subbed def encrypt_block(self, block): for i in range(42): block = self.add_key(block, self.round_keys[i]) block = self.substitute(block) block = self.permute(block) block = self.bit_permute(block) block = self.add_key(block, self.round_keys[42]) return block def encrypt(self, plaintext): padded = self.pad(plaintext) blocks = [padded[i:i+BLOCK_LEN] for i in range(0,len(padded),BLOCK_LEN)] ct = self.iv for i in range(len(blocks)): temp = self.encrypt_block(blocks[i]) ct += xor(temp, ct[16*i:16*i+16]) return ct key = os.urandom(16) iv = os.urandom(16) spn = SPN(key, iv) flag = b"nbctf{[REDACTED]}" print("Encrypted flag: " + spn.encrypt(flag).hex()) for _ in range(len("01234567")): a,b = list(map(int, input("Pick 2 indexes to swap for values in SBOX (x,y): ").split(","))) sbox[a], sbox[b] = sbox[b], sbox[a] plaintext = bytes.fromhex(input("I'll let you encrypt one block of plaintext(hex): ")) assert len(plaintext) == 16, "NO NO NO NO NO" print("Ciphertext: " + spn.encrypt(plaintext).hex())
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/NewportBlakeCTF/2023/crypto/Too_Little_Information/chall.py
ctfs/NewportBlakeCTF/2023/crypto/Too_Little_Information/chall.py
from Crypto.Util.number import * p = getPrime(512) q = getPrime(512) n = p*q e = 65537 m = bytes_to_long(b"nbctf{[REDACTED]}") ct = pow(m,e,n) print(f"{ct = }") print(f"{e = }") print(f"{n = }") hint = (p+q) >> 200 # I can't be giving you that much! print(f"{hint = }")
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/NewportBlakeCTF/2023/crypto/Spinning_my_way_to_Straight_Lines/chall.py
ctfs/NewportBlakeCTF/2023/crypto/Spinning_my_way_to_Straight_Lines/chall.py
from Crypto.Util.number import * import os def xor(a, b): return bytes(i^j for i, j in zip(a,b)) sbox = [239, 209, 87, 244, 56, 155, 29, 190, 230, 69, 8, 96, 172, 15, 137, 42, 52, 154, 28, 191, 115, 208, 86, 245, 173, 14, 136, 43, 231, 134, 194, 97, 228, 71, 193, 98, 174, 13, 139, 40, 112, 211, 85, 246, 58, 2, 31, 188, 175, 12, 138, 41, 229, 70, 192, 99, 59, 152, 30, 189, 113, 210, 84, 247, 61, 158, 24, 187, 119, 212, 82, 249, 169, 10, 140, 47, 227, 64, 198, 101, 118, 213, 83, 240, 60, 159, 25, 186, 226, 65, 199, 100, 168, 11, 141, 46, 171, 195, 142, 45, 225, 66, 196, 0, 63, 156, 26, 185, 117, 214, 80, 243, 224, 67, 197, 102, 170, 9, 143, 44, 116, 215, 81, 242, 62, 157, 27, 184, 236, 79, 201, 106, 166, 5, 131, 32, 120, 219, 93, 254, 50, 145, 23, 180, 167, 4, 130, 33, 75, 78, 200, 107, 51, 144, 22, 181, 121, 218, 92, 255, 122, 217, 95, 252, 48, 147, 21, 182, 238, 77, 203, 104, 164, 7, 129, 34, 49, 146, 20, 183, 123, 216, 94, 253, 165, 6, 128, 35, 114, 76, 202, 105, 163, 103, 68, 37, 233, 74, 204, 111, 55, 148, 18, 177, 125, 222, 88, 251, 232, 237, 205, 110, 162, 1, 135, 36, 124, 223, 89, 250, 54, 149, 19, 176, 53, 150, 16, 179, 127, 220, 90, 241, 161, 153, 132, 39, 235, 72, 206, 109, 126, 221, 91, 248, 57, 151, 17, 178, 234, 73, 207, 108, 160, 3, 133, 38] permute = [10, 11, 5, 6, 2, 4, 8, 0, 12, 9, 3, 13, 14, 15, 1, 7] BLOCK_LEN = 16 class SPN: def __init__(self, key, iv): self.master_key = key self.iv = iv self.round_keys = self.expand_key() def expand_key(self): round_keys = [self.master_key] for i in range(42): round_keys.append(round_keys[-1][2:] + round_keys[-1][:2]) return round_keys def pad(self, plaintext): return plaintext + b"\x00"*(BLOCK_LEN - (len(plaintext) % BLOCK_LEN)) def permute(self, block): permuted = b"" for i in permute: permuted += block[i].to_bytes(1, 'little') return permuted def add_key(self, block, round_key): return xor(block, round_key) def substitute(self, block): subbed = b"" for i in block: subbed += sbox[i].to_bytes(1, 'little') return subbed def encrypt_block(self, block): for i in range(42): block = self.add_key(block, self.round_keys[i]) block = self.substitute(block) block = self.permute(block) block = self.add_key(block, self.round_keys[42]) return block def encrypt(self, plaintext): padded = self.pad(plaintext) blocks = [padded[i:i+BLOCK_LEN] for i in range(0,len(padded),BLOCK_LEN)] ct = self.iv for i in range(len(blocks)): temp = self.encrypt_block(blocks[i]) ct += xor(temp, ct[16*i:16*i+16]) return ct key = os.urandom(16) iv = os.urandom(16) spn = SPN(key, iv) flag = b"nbctf{[REDACTED]}" print("Encrypted flag: " + spn.encrypt(flag).hex()) for _ in range(len("01234567")): a,b = list(map(int, input("Pick 2 indexes to swap for values in SBOX (x,y): ").split(","))) sbox[a], sbox[b] = sbox[b], sbox[a] plaintext = bytes.fromhex(input("I'll let you encrypt one block of plaintext(hex): ")) assert len(plaintext) == 16, "NO NO NO NO NO" print("Ciphertext: " + spn.encrypt(plaintext).hex())
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/NewportBlakeCTF/2023/crypto/SBG_ABWs_Insanity/chall.py
ctfs/NewportBlakeCTF/2023/crypto/SBG_ABWs_Insanity/chall.py
from Crypto.Util.number import getPrime, bytes_to_long, isPrime, long_to_bytes from Crypto.Cipher import AES from Crypto.Util.Padding import pad import hashlib m = bytes_to_long(b'we give you this as a gift!') p = getPrime(1096) q1 = getPrime(1096) q2 = getPrime(1096) n1 = p*q1 n2 = p*q2 e = 11 ct1 = pow(m,e,n1) ct2 = pow(m,e,n2) key = hashlib.sha256(long_to_bytes(q1)).digest() cipher = AES.new(key, AES.MODE_ECB) enc_flag = cipher.encrypt(pad(b"nbctf{[REDACTED]}", 16)) print("ct1 =", ct1) print("ct2 =", ct2) print("enc_flag =", enc_flag.hex())
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/NewportBlakeCTF/2023/crypto/Rivest_Shamir_forgot_Adleman/chall.py
ctfs/NewportBlakeCTF/2023/crypto/Rivest_Shamir_forgot_Adleman/chall.py
from Crypto.Util.number import * p = getPrime(1024) q = getPrime(1024) n = p*q e = 123589168751396275896312856328164328381265978316578963271231567137825613822284638216416 m = bytes_to_long(b"nbctf{[REDACTED]}") ct = (m^e) % n print("n = ", n) print("e = ", e) print("ct = ", ct)
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/NewportBlakeCTF/2023/web/secret_tunnel/main.py
ctfs/NewportBlakeCTF/2023/web/secret_tunnel/main.py
#!/usr/local/bin/python from flask import Flask, render_template, request, Response import requests app = Flask(__name__, static_url_path='', static_folder="static") @app.route("/fetchdata", methods=["POST"]) def fetchdata(): url = request.form["url"] if "127" in url: return Response("No loopback for you!", mimetype="text/plain") if url.count('.') > 2: return Response("Only 2 dots allowed!", mimetype="text/plain") if "x" in url: return Response("I don't like twitter >:(" , mimetype="text/plain") if "flag" in url: return Response("It's not gonna be that easy :)", mimetype="text/plain") try: res = requests.get(url) except Exception as e: return Response(str(e), mimetype="text/plain") return Response(res.text[:32], mimetype="text/plain") @app.route("/", methods=["GET"]) def index(): return render_template("index.html") 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/NewportBlakeCTF/2023/web/secret_tunnel/flag.py
ctfs/NewportBlakeCTF/2023/web/secret_tunnel/flag.py
from flask import Flask, Response app = Flask(__name__) flag = open("flag.txt", "r").read() @app.route("/flag", methods=["GET"]) def index(): return Response(flag, mimetype="text/plain") if __name__ == "__main__": app.run(port=1337)
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/NewportBlakeCTF/2023/web/Galleria/app.py
ctfs/NewportBlakeCTF/2023/web/Galleria/app.py
from flask import Flask, render_template, request, redirect, url_for, send_file import os from pathlib import Path from werkzeug.utils import secure_filename app = Flask(__name__) app.config['UPLOAD_FOLDER'] = 'uploads' @app.route('/') def index(): return render_template('index.html') def allowed_file(filename): allowed_extensions = {'jpg', 'jpeg', 'png', 'gif'} return '.' in filename and filename.rsplit('.', 1)[1].lower() in allowed_extensions @app.route('/upload', methods=['POST']) def upload(): file = request.files['image'] if file and allowed_file(file.filename): file.seek(0, os.SEEK_END) if file.tell() > 1024 * 1024 * 2: return "File is too large", 413 file.seek(0) filename = secure_filename(os.path.basename(file.filename)) file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename)) return redirect(url_for('gallery')) def check_file_path(path): _path = Path(path) parts = [*Path.cwd().parts][1:] for part in _path.parts: if part == '.': continue if part == '..': parts.pop() else: parts.append(part) if len(parts) == 0: return False _path = os.path.join(os.getcwd(), path) _path = Path(_path) return _path.exists() and _path.is_file() @app.route('/gallery') def gallery(): if request.args.get('file'): filename = os.path.join('uploads', request.args.get('file')) if not check_file_path(filename): return redirect(url_for('gallery')) return send_file(filename) image_files = [f for f in os.listdir( app.config['UPLOAD_FOLDER'])] return render_template('gallery.html', images=image_files) if __name__ == '__main__': app.run(debug=False, port=5000, host='0.0.0.0')
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/Engineer/2022/pwn/HeckerBeluga/pass_validator.py
ctfs/Engineer/2022/pwn/HeckerBeluga/pass_validator.py
def ValidatePassword(password): valid = False print("Attempting to validate password...") if(len(password[::-2]) != 8): print("Nah, you're not even close!!") return False pwlen = len(password) chunk1 = 'key'.join([chr(0x98 - ord(password[c])) for c in range(0, int(pwlen / 2))]) if "".join([c for c in chunk1[::4]]) != '&e"3&Ew*': print("Seems you're a terrible reverse engineer, come back after gaining some skills!") return False chunk2 = [ord(c) - 0x1F if ord(c) > 0x60 else (ord(c) + 0x1F if ord(c) > 0x40 else ord(c)) for c in password[int(pwlen / 2) : int(2 * pwlen / 2)]] rand = [54, -45, 9, 25, -42, -25, 31, -79] for i in range(0, len(chunk2)): if(0 if i == len(chunk2) - 1 else chunk2[i + 1]) != chunk2[i] + rand[i]: print("You're not a real hecker, try again! " + str(i)) return False print("Password accepted!") return True print("\n************** Password Validator ***************") print("Please enter password") while True: if ValidatePassword(input()): exit() else: print("Try again!")
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/3kCTF/2021/pwn/klibrary/upload.py
ctfs/3kCTF/2021/pwn/klibrary/upload.py
#!/usr/bin/python3.8 from pwn import * EXPLOIT_PATH = '/tmp/exploit' SERVER = 178.62.107.48 PORT = 9994 SHELL_PROMPT = '$ ' def get_splitted_encoded_exploit(): split_every = 256 # Change the name to your exploit path with open('exploit', 'rb') as exploit_file: exploit = base64.b64encode(exploit_file.read()) return [exploit[i:i+split_every] for i in range(0, len(exploit), split_every)] def upload_exploit(sh): chunks_sent = 0 splitted_exploit = get_splitted_encoded_exploit() for exploit_chunk in splitted_exploit: print(f'[*] Sending a chunk ({chunks_sent}/{len(splitted_exploit)})') sh.sendlineafter( SHELL_PROMPT, f'echo {exploit_chunk.decode()} | base64 -d >> {EXPLOIT_PATH}') chunks_sent += 1 r = remote(SERVER, PORT) upload_exploit(r) # When finished, your exploit will be in /tmp directory. Good luck. r.interactive()
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/3kCTF/2021/pwn/echo/upload.py
ctfs/3kCTF/2021/pwn/echo/upload.py
#!/usr/bin/python3.8 from pwn import * EXPLOIT_PATH = '/tmp/exploit' SERVER = 167.99.39.211 PORT = 9995 SHELL_PROMPT = '$ ' def get_splitted_encoded_exploit(): split_every = 256 # Change the name to your exploit path with open('exploit', 'rb') as exploit_file: exploit = base64.b64encode(exploit_file.read()) return [exploit[i:i+split_every] for i in range(0, len(exploit), split_every)] def upload_exploit(sh): chunks_sent = 0 splitted_exploit = get_splitted_encoded_exploit() for exploit_chunk in splitted_exploit: print(f'[*] Sending a chunk ({chunks_sent}/{len(splitted_exploit)})') sh.sendlineafter( SHELL_PROMPT, f'echo {exploit_chunk.decode()} | base64 -d >> {EXPLOIT_PATH}') chunks_sent += 1 r = remote(SERVER, PORT) upload_exploit(r) # When finished, your exploit will be in /tmp directory. Good luck. r.interactive()
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/3kCTF/2021/crypto/crypto_warmup/challenge.py
ctfs/3kCTF/2021/crypto/crypto_warmup/challenge.py
import random import math n = 24 def make_stuff(): A = []; b = [1, 10] for i in range(n): A.append(random.randint(*b)) b[False] = sum(A) + 1 b[True] = int(b[False] << 1) c = random.randint(sum(A), sum(A) << 1) while True: d = random.randint(sum(A), sum(A) << 1) if math.gcd(c, d) == 1: break return [(d*w) % c for w in A] def weird_function_1(s): return sum([list(map(int,bin(ord(c))[2:].zfill(8))) for c in s], []) def do_magic(OooO, B): return sum(m * b for m, b in zip(weird_function_1(OooO), B)) B = make_stuff() with open("flag") as fd: flag = fd.read().strip() print(B) for i in range(0, len(flag), 3): print(do_magic(flag[i:i+3], B)) ##[4267101277, 4946769145, 6306104881, 7476346548, 7399638140, 1732169972, 1236242271, 5109093704, 2163850849, 6552199249, 3724603395, 3738679916, 5211460878, 642273320, 3810791811, 761851628, 1552737836, 4091151711, 1601520107, 3117875577, 2485422314, 1983900485, 6150993150, 2045278518] ##34451302951 ##58407890177 ##49697577713 ##45443775595 ##38537028435 ##47069056666 ##49165602815 ##43338588490 ##32970122390
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/3kCTF/2021/crypto/ASR/app.py
ctfs/3kCTF/2021/crypto/ASR/app.py
import binascii import hashlib import random import os import string import OpenSSL.crypto as crypto rsa_p_not_prime_pem = """\n-----BEGIN RSA PRIVATE KEY-----\nMBsCAQACAS0CAQcCAQACAQ8CAQMCAQACAQACAQA=\n-----END RSA PRIVATE KEY-----\n""" invalid_key = crypto.load_privatekey(crypto.FILETYPE_PEM, rsa_p_not_prime_pem) error_msg = "Pycrypto needs to be patched!" try: invalid_key.check() raise RuntimeError(error_msg) except crypto.Error: pass # proof of work to prevent any kind of bruteforce :-) prefix = "".join(random.choice(string.ascii_lowercase) for _ in range(6)) print("Find a string s such that sha256(prefix + s) has 24 binary leading zeros. Prefix = '{}'".format(prefix)) pow_answer = input("Answer: ") assert hashlib.sha256((prefix + pow_answer).encode()).digest()[:3] == b"\x00\x00\x00" # v v v challenge starts here v v v print("\n\nHello, i hope you can help me out. I might reward you something in return :D") key = "" # read in key while True: buffer = input() if buffer: key += buffer + "\n" else: break key = crypto.load_privatekey(crypto.FILETYPE_PEM, key) private_numbers = key.to_cryptography_key().private_numbers() assert key.check() d = private_numbers.d p = private_numbers.p q = private_numbers.q N = p * q # i dont like small numbers assert d > 1337 * 1337 * 1337 * 1337 * 1337 # and i dont like even numbers assert N % 2 != 0 if pow(820325443930302277, d, N) == 4697802211516556112265788623731306453433385478626600383507434404846355593172244102208887127168181632320398894844742461440572092476461783702169367563712341297753907259551040916637774047676943465204638648293879569: with open("flag") as fd: print(fd.read()) else: print("Nop. :(")
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/3kCTF/2021/crypto/SMS/sms.py
ctfs/3kCTF/2021/crypto/SMS/sms.py
SBOX = [0xb9, 0xb3, 0x49, 0x94, 0xf9, 0x3, 0xd0, 0xfc, 0x67, 0xa3, 0x72, 0xb5, 0x45, 0x82, 0x54, 0x93, 0x5b, 0x88, 0x5c, 0xe0, 0x96, 0x41, 0xc7, 0xa, 0xdb, 0x7f, 0x77, 0x29, 0x9, 0xb, 0x8d, 0x80, 0x2d, 0xaf, 0xe1, 0x4a, 0x38, 0x73, 0x3a, 0x6a, 0xf2, 0xb6, 0xdc, 0xbd, 0x79, 0x2a, 0xcb, 0x55, 0x10, 0x61, 0x63, 0x68, 0x13, 0x95, 0x9f, 0x1c, 0x4f, 0x35, 0x5f, 0xae, 0x37, 0xb8, 0xfe, 0xea, 0x7a, 0x4b, 0xc3, 0xe8, 0xc6, 0x44, 0x60, 0xb2, 0x5a, 0x2e, 0xeb, 0x47, 0x1e, 0x4d, 0x9a, 0x98, 0x36, 0xe7, 0x48, 0x3e, 0x42, 0x6b, 0xa1, 0x65, 0xb1, 0x57, 0x6c, 0x4, 0xff, 0xfd, 0x34, 0x40, 0x31, 0x8c, 0xbe, 0xda, 0x2c, 0x1b, 0x7c, 0x64, 0x3f, 0xd1, 0xc9, 0x9b, 0x25, 0x87, 0xaa, 0xd, 0x15, 0x1f, 0xce, 0x30, 0xfb, 0xd5, 0xef, 0xbb, 0x24, 0x28, 0x90, 0x2f, 0x85, 0xc5, 0x4c, 0x97, 0xa8, 0x16, 0x43, 0xac, 0x74, 0xc0, 0x8b, 0xc4, 0xe9, 0x7e, 0xf5, 0xd2, 0xab, 0x12, 0xd8, 0xdd, 0xa9, 0xad, 0x21, 0xd7, 0xed, 0x1, 0x32, 0xbf, 0xa6, 0x8a, 0xe3, 0x6f, 0xde, 0x84, 0xc8, 0x6d, 0x92, 0x99, 0x51, 0x39, 0xe5, 0x46, 0x9c, 0xf0, 0x0, 0x8e, 0xbc, 0xa2, 0x22, 0x9d, 0xc2, 0xfa, 0xb0, 0x33, 0x56, 0xec, 0xdf, 0x89, 0x52, 0x8, 0x62, 0x7, 0x59, 0xb7, 0xe4, 0x14, 0x9e, 0x70, 0xd9, 0xe, 0x3d, 0x26, 0x1d, 0x66, 0x71, 0xe2, 0x5, 0x6e, 0x5d, 0xf6, 0x18, 0xf, 0xcf, 0xd6, 0xe6, 0xba, 0x1a, 0x78, 0xf8, 0x76, 0xd3, 0x50, 0xf7, 0x58, 0x17, 0x91, 0x11, 0x86, 0xf1, 0xa4, 0x19, 0x4e, 0x6, 0xa0, 0xca, 0xa5, 0xf3, 0xee, 0xcd, 0x53, 0x5e, 0xa7, 0xc, 0xb4, 0x2, 0xc1, 0x3b, 0x27, 0x69, 0x7d, 0x8f, 0xcc, 0x20, 0x7b, 0x81, 0x2b, 0x83, 0x23, 0xd4, 0x3c, 0xf4, 0x75] def pad(data): if len(data) == 0: return b"\x00" * 8 while len(data) % 8 != 0: data += b"\x00" return data def sub(state): return [SBOX[x] for x in state] def mix(block, state): for i in range(8): state[i] ^= block[7 - i] & 0x1f state[i] ^= block[i] & 0xe0 return state def shift(state): t = 0 for s in state: t ^= s u = state[0] for i in range(7): state[i] ^= t ^ state[i] ^ state[i+1] state[7] ^= t ^ state[7] ^ u return state def hash(data): assert len(data) % 8 == 0 state = [2**i-1 for i in range(1, 9)] for i in range(0, len(data), 8): block = data[i: i+8] state = sub(state) state = mix(block, state) state = shift(state) state = sub(state) return bytes(state).hex() Banner = """ ____ __ __ ____ _ _ _ ____ _ _ / ___|| \/ / ___| | | | | / \ / ___|| | | | \___ \| |\/| \___ \ _____| |_| | / _ \ \___ \| |_| | ___) | | | |___) |_____| _ |/ ___ \ ___) | _ | |____/|_| |_|____/ |_| |_/_/ \_\____/|_| |_| """ print(Banner, end= "\n\n") print("Can you even Collide?") MSG1 = bytes.fromhex(input("First message : ").strip()) MSG2 = bytes.fromhex(input("Second message : ").strip()) MSG1 = pad(MSG1) MSG2 = pad(MSG2) H1 = hash(MSG1) H2 = hash(MSG2) print("H(MSG1) = {}".format(H1)) print("H(MSG2) = {}".format(H2)) if MSG1 == MSG2: print("Really ?") elif H1 == H2 : if H1 == "0000000000000000": print("Good job, Here's your reward: ") print(open("flag.txt","r").read()) else: print("So close, yet so far :(") else: print("Not even close :(")
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/3kCTF/2021/crypto/Digital/digital.py
ctfs/3kCTF/2021/crypto/Digital/digital.py
from Crypto.Util.number import inverse import hashlib import os rol = lambda val, r_bits, max_bits: (val << r_bits%max_bits) & (2**max_bits-1) | ((val & (2**max_bits-1)) >> (max_bits-(r_bits%max_bits))) class Random(): def __init__(self, seed): self.state = seed self.bits = self.state.bit_length() def next(self): self.state ^= self.state << 76 self.state = rol(self.state, 32, self.bits) self.state ^= self.state >> 104 self.state = rol(self.state, 20, self.bits) self.state ^= self.state << 116 self.state = rol(self.state, 12, self.bits) return self.state def sign(message): h = int(hashlib.sha256(message).hexdigest(), 16) k = random.next() r = pow(g, k, p) % q s = inverse(k, q) * (h + x*r) % q return (r, s) def verify(message, r, s): h = int(hashlib.sha256(message).hexdigest(), 16) w = inverse(s, q) u1 = h * w % q u2 = r * w % q v = (pow(g, u1, p) * pow(y, u2, p) % p ) % q return v == r random = Random(int(os.urandom(16).hex(), 16)) p = 0x433fd29e6352ba4f433aaf05634348bf2fa7df007861ec24e1088b4105307a9af5645fff0bb561f31210b463346f6d2990a8395e51f0abf6f0affad2364a09ef3ab2cfa66497ebb9d6ac7ed98710634c5a39ddc9d423294911cfa787e28ac2943df345ed6b979ed9a383e1be05e35b305c797f826c9502280dd5b8af4ff532527eed2e91d290b145fac6d647c81127ed06eaa580d64bcf2740ee8ed2aa158cc297ca9315172df731f149927ba7b6e72adf88bde00d13cc7784c717ce1d042cbc3bd8db1549a75fb5c4d586ed1d67fe0129e522f394236b8053513905277b8e930101b0660807598039a4796e66018113fbf3f1703303bb3808779e3613995cb9 q = 0xc313d1a2bf3516a555c54875798a59a3d219ea76179b712886beec177263cec7 g = 0x21ac05c17f3cc476fa34ea77b5e2252e848f2ab35cf4e1f6cc53f15349af6e56f1c5ad36fe7cdf0a00c8162032b623d1271b4f586d26dba704706c32d0cefa01937e82d8af632596e9d27ff10a7cad23766ae97c07bb7dc3b2e24a482ab30c02435c8ce99b0cc356146c371bda04582ee1b40b2f29227ba8225aa490b4bd788662168929fdd2cfbce0e0dc59da3db76651ee91fbc654d36f277003f96ff6b045b2ab5187b0d4024a32281672c606206aebb1f3fe9b75877e38dcd38c73aa588ec01ae3fca344befbdf745a47f7a45b4d06643fea5e4e9b02f763cc5b2e7e8488945b0fe12b56b83a29cbe47ec9d276197d0245d11abc8833f88d114f3a897f81 x = int(open("flag.txt",'rb').read().hex(), 16) y = pow(g, x, p) MSG1 = b'Joe made the sugar cookies.' MSG2 = b'Susan decorated them.' r1, s1 = sign(MSG1) r2, s2 = sign(MSG2) assert verify(MSG1, r1, s1) assert verify(MSG2, r2, s2) print ("y = ", y) print ("r1 = ", r1) print ("s1 = ", s1) print ("r2 = ", r2) print ("s2 = ", s2) """ y = 5624204323708883762857532177093000216929823277043458966645372679201025592769376026088466517180933057673841523705217308006821461505613041092599344214921758292705684588442147606413017270932589190682167865180010809895170865252326994825400330559172774619220024016595462686075240147992717554220738390033531322461011161893179173499597221230442911598574630392043521768535083211677909300720125573266145560294501586465872618003220096582182816143583907903491981432622413089428363003509954017358820731242558636829588468685964348899875705345969463735608144901602683917246879183938340727739626879210712728113625391485513623273477 r1 = 53670875511938152371853380079923244962420018116685861532166510031799178241334 s1 = 6408272343562387170976380346088007488778435579509591484022774936598892550745 r2 = 3869108664885100909066777013479452895407563047995298582999261416732594613401 s2 = 63203374922611188872786277873252648960215993219301469335034797776590362136211 """
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/3kCTF/2021/crypto/secure_roots/app.py
ctfs/3kCTF/2021/crypto/secure_roots/app.py
from Crypto.Util.number import getPrime, long_to_bytes import hashlib, os, signal def xgcd(a, b): if a == 0: return (b, 0, 1) else: g, y, x = xgcd(b % a, a) return (g, x - (b // a) * y, y) def getprime(): while True: p = getPrime(1024) if p % 4 == 3: return p class Server(): def __init__(self): self.private , self.public = self.gen() print("Prove your identity to get your message!\n") print("Public modulus : {}\n".format(self.public)) def gen(self): p = getprime() q = getprime() return (p, q), p*q def decrypt(self, c): p, q = self.private mp = pow(c, (p+1)//4, p) mq = pow(c, (q+1)//4, q) _, yp, yq = xgcd(p, q) r = (yp * p * mq + yq * q * mp) % (self.public) return r def sign(self, m): U = os.urandom(20) c = int(hashlib.sha256(m + U).hexdigest(), 16) r = self.decrypt(c) return (r, int(U.hex(), 16)) def verify(self, m, r, u): U = long_to_bytes(u) c = int(hashlib.sha256(m + U).hexdigest(), 16) return c == pow(r, 2, self.public) def get_flag(self): flag = int(open("flag.txt","rb").read().hex(), 16) return pow(flag, 0x10001, self.public) def login(self): m = input("Username : ").strip().encode() r = int(input("r : ").strip()) u = int(input("u : ").strip()) if self.verify(m, r, u): if m == b"Guest": print ("\nWelcome Guest!") elif m == b"3k-admin": print ("\nMessage : {}".format(self.get_flag())) else : print ("This user is not in our db yet.") else: print("\nERROR : Signature mismatch.") if __name__ == '__main__': signal.alarm(10) S = Server() r, u = S.sign(b"Guest") print("Username : Guest\nr : {0}\nu : {1}\n".format(r , u)) S.login()
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/3kCTF/2021/web/3K_SIGNER/app.py
ctfs/3kCTF/2021/web/3K_SIGNER/app.py
from flask import Flask, request, jsonify, make_response from flask_sqlalchemy import SQLAlchemy from werkzeug.security import generate_password_hash, check_password_hash import uuid import jwt import datetime from functools import wraps import os import time import re import argparse import tempfile import PyPDF2 import string import random import datetime from subprocess import PIPE, Popen from reportlab.pdfgen import canvas app = Flask(__name__) ALLOWED_EXTENSIONS = {'pdf', 'png', 'jpg', 'jpeg'} UPLOAD_FOLDER = './static/' app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER app.config['SECRET_KEY']='censored' app.config['SQLALCHEMY_DATABASE_URI']='sqlite://///app/library.db' app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = True reg=re.compile('[0-9a_f]{32}\Z', re.I) db = SQLAlchemy(app) class Users(db.Model): id = db.Column(db.Integer, primary_key=True) public_id = db.Column(db.Integer) name = db.Column(db.String(50)) password = db.Column(db.String(50)) admin = db.Column(db.Boolean) class Tokens(db.Model): id = db.Column(db.Integer, primary_key=True) token = db.Column(db.String(32)) db.create_all() def check_valid_token(intoken): if bool(reg.match(intoken)): rez=Tokens.query.filter(Tokens.token.ilike(intoken)).first() print(rez) if rez: return True else: return False else: return False def allowed_file(filename): return '.' in filename and \ filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS def get_random_string(length): letters = string.ascii_lowercase result_str = ''.join(random.choice(letters) for i in range(length)) return result_str def _get_tmp_filename(suffix=".pdf"): with tempfile.NamedTemporaryFile(suffix=".pdf") as fh: return fh.name coords='1x100x100x150x40' path='./static/' date=False output=None pdf='pf.pdf' signature='3k.png' def sign_pdf(inputfile): infile=path+inputfile pdf=path+get_random_string(8)+'.pdf' cmd='unoconv -v -o '+pdf+' -f pdf '+infile p = Popen(cmd, shell=True, stdout=PIPE, stderr=PIPE) stdout, stderr = p.communicate() page_num, x1, y1, width, height = [int(a) for a in coords.split("x")] page_num -= 1 output_filename = output or "{}_signed{}".format( *os.path.splitext(pdf) ) pdf_fh = open(pdf, 'rb') sig_tmp_fh = None pdf = PyPDF2.PdfFileReader(pdf_fh) writer = PyPDF2.PdfFileWriter() sig_tmp_filename = None for i in range(0, pdf.getNumPages()): page = pdf.getPage(i) if i == page_num: sig_tmp_filename = _get_tmp_filename() c = canvas.Canvas(sig_tmp_filename, pagesize=page.cropBox) c.drawImage(signature, x1, y1, width, height, mask='auto') if date: c.drawString(x1 + width, y1, datetime.datetime.now().strftime("%Y-%m-%d")) c.showPage() c.save() sig_tmp_fh = open(sig_tmp_filename, 'rb') sig_tmp_pdf = PyPDF2.PdfFileReader(sig_tmp_fh) sig_page = sig_tmp_pdf.getPage(0) sig_page.mediaBox = page.mediaBox page.mergePage(sig_page) writer.addPage(page) with open(output_filename, 'wb') as fh: writer.write(fh) for handle in [pdf_fh, sig_tmp_fh]: if handle: handle.close() if sig_tmp_filename: os.remove(sig_tmp_filename) return output_filename def token_required(f): @wraps(f) def decorator(*args, **kwargs): token = None if 'x-access-tokens' in request.headers: token = request.headers['x-access-tokens'] if not token: return jsonify({'message': 'a valid token is missing'}) try: data = jwt.decode(token, app.config['SECRET_KEY']) current_user = Users.query.filter_by(public_id=data['public_id']).first() except: return jsonify({'message': 'token is invalid'}) return f(current_user, *args, **kwargs) return decorator @app.route('/', methods=['GET', 'POST']) def home(): return jsonify({'message': 'Welcome \O// '}) @app.route('/register', methods=['GET', 'POST']) def signup_user(): data = request.get_json() hashed_password = generate_password_hash(data['password'], method='sha256') new_user = Users(public_id=str(uuid.uuid4()), name=data['name'], password=hashed_password, admin=False) db.session.add(new_user) db.session.commit() return jsonify({'message': 'registered successfully'}) @app.route('/login', methods=['GET', 'POST']) def login_user(): auth = request.authorization if not auth or not auth.username or not auth.password: return make_response('could not verify', 401, {'WWW.Authentication': 'Basic realm: "login required"'}) user = Users.query.filter_by(name=auth.username).first() if check_password_hash(user.password, auth.password): token = jwt.encode({'public_id': user.public_id, 'exp' : datetime.datetime.utcnow() + datetime.timedelta(minutes=30)}, app.config['SECRET_KEY']) return jsonify({'token' : token.decode('UTF-8')}) return make_response('could not verify', 401, {'WWW.Authentication': 'Basic realm: "login required"'}) @app.route('/users', methods=['GET']) @token_required def get_all_users(current_user): if current_user.admin: users = Users.query.all() result = [] for user in users: user_data = {} user_data['public_id'] = user.public_id user_data['name'] = user.name user_data['admin'] = user.admin result.append(user_data) else: return jsonify({'error': "not admin"}) return jsonify({'users': result}) @app.route('/role_user', methods=['GET']) @token_required def role(current_user): if not(current_user.admin): return jsonify({'role': "ROLE_USER"}) else: return jsonify({'role': "ROLE_ADMIN"}) @app.route('/share_file', methods=['GET', 'POST']) @token_required def upload_file(current_user): if request.method == 'POST': if 'file' not in request.files: return jsonify({'error': "upload file..."}) file = request.files['file'] if file.filename == '': return jsonify({'error': "no filename !!"}) if file and allowed_file(file.filename): ext=file.filename.rsplit('.', 1)[1] relfile=get_random_string(8)+'.'+ext file.save(os.path.join(app.config['UPLOAD_FOLDER'], relfile)) if not(request.args.get('sign_token')) or (not(check_valid_token(request.args.get('sign_token')))): return jsonify({'file': "/static/"+relfile}) else: signed_file=sign_pdf(relfile) return jsonify({'signed_file':signed_file}) else: return jsonify({'error': "go away!!"}) @app.route('/sign_tokens', methods=['GET']) @token_required def sign_tokens(current_user): if current_user.admin: tokens = Tokens.query.all() result = [] for tok in tokens: token_data = {} token_data['id'] = tok.id token_data['token'] = tok.token result.append(token_data) else: return jsonify({'error': "not admin"}) return jsonify({'users': result}) @app.route('/add_tokens', methods=['PUT']) @token_required def add_tok(current_user): if current_user.admin: try: data = request.get_json() new_token = Tokens(token=data['token']) db.session.add(new_token) db.session.commit() except: return jsonify({'error': "//"}) return jsonify({'message': "Added successfully"}) else: return jsonify({'error': "not admin"}) if __name__ == '__main__': app.run(host="0.0.0.0")
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/3kCTF/2021/web/online_compiler/app.py
ctfs/3kCTF/2021/web/online_compiler/app.py
from flask import Flask, redirect, url_for, request from flask_cors import CORS, cross_origin from pathlib import Path from subprocess import PIPE, Popen import string import random def get_random_string(length): letters = string.ascii_lowercase result_str = ''.join(random.choice(letters) for i in range(length)) return result_str def check_file(filename): if Path(filename).is_file(): return True else: return False app = Flask(__name__) cors = CORS(app) @app.route('/save',methods = ['POST']) @cross_origin() def save(): c_type=request.form['c_type'] print('ctype-(>'+c_type) if (c_type == 'php'): code=request.form['code'] if (len(code)<100): filename=get_random_string(6)+'.php' path='/home/app/test/'+filename f=open(path,'w') f.write(code) f.close() return filename else: return 'failed' """elif (c_type == 'python'): code=request.args.get('code') if (len(code)<30): filename=get_random_string(6)+'.py' path='/home/app/testpy/'+filename f=open(path,'w') f.write(code) f.close() return filename else: return 'failed'""" @app.route('/compile',methods = ['POST']) @cross_origin() def compile(): c_type=request.form['c_type'] filename=request.form['filename'] if (c_type == 'php'): if (filename[-3:]=='php'): if (check_file('/home/app/test/'+filename)): path='/home/app/test/'+filename cmd='php -c php.ini '+path p = Popen(cmd, shell=True, stdout=PIPE, stderr=PIPE) stdout, stderr = p.communicate() return stdout else: return 'failed' else: return 'noop' elif (c_type == 'python'): if (filename[-2:]=='py'): if (check_file('/home/app/test/'+filename)): cmd='python3 '+filename p = Popen(cmd, shell=True, stdout=PIPE, stderr=PIPE) stdout, stderr = p.communicate() return stdout else: return 'failed' else: return 'noop' 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/3kCTF/2021/web/pawnshop/apache/elastic_init.py
ctfs/3kCTF/2021/web/pawnshop/apache/elastic_init.py
from elasticsearch import Elasticsearch import random import string def id_generator(size=6, chars=string.ascii_lowercase+ string.digits): return ''.join(random.choice(chars) for _ in range(size)) es_client = Elasticsearch(['http://172.30.0.7:9200']) FLAG = '3k{*REDACTED*}' entries=[] entries.append({"id":1,"picture":"axe.png","seller":id_generator()+"@pawnshop.2021.3k.ctf.to","item":"Memory leak Axe","value":id_generator(10)}) entries.append({"id":2,"picture":"drill.png","seller":id_generator()+"@pawnshop.2021.3k.ctf.to","item":"SUID drill","value":id_generator(10)}) entries.append({"id":3,"picture":"rifle.png","seller":id_generator()+"@pawnshop.2021.3k.ctf.to","item":"ROP rifle","value":id_generator(10)}) entries.append({"id":4,"picture":"bullets.png","seller":id_generator()+"@pawnshop.2021.3k.ctf.to","item":"Syscall bullets","value":id_generator(10)}) entries.append({"id":5,"picture":"flag.png","seller":id_generator()+"@pawnshop.2021.3k.ctf.to","item":"Flag","value":FLAG}) entries.append({"id":6,"picture":"hammer.png","seller":id_generator()+"@pawnshop.2021.3k.ctf.to","item":"0day hammer","value":id_generator(10)}) body = [] for entry in entries: body.append({'index': {'_id': entry['id']}}) body.append(entry) response = es_client.bulk(index='pawnshop', body=body) print(response)
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/3kCTF/2021/web/pawnshop/apache/src/admin.py
ctfs/3kCTF/2021/web/pawnshop/apache/src/admin.py
#!/usr/bin/python3 from funcs import * form = cgi.FieldStorage() action = form.getvalue('action') if action=='list': list_items() elif action=='lookup': mail = form.getvalue('mail') if(mail != None): verify_email(mail) api({'msg':lookupSeller(mail)}) api({'msg':'error'}) elif action=='edit': api({'msg':'not implemented'}) else: api(False)
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/3kCTF/2021/web/pawnshop/apache/src/funcs.py
ctfs/3kCTF/2021/web/pawnshop/apache/src/funcs.py
#!/usr/bin/python3 import cgi, cgitb ,json from elasticsearch import Elasticsearch from email.utils import parseaddr import json import re es_client = Elasticsearch(['http://172.30.0.7:9200']) def api(jsonv): print("Content-type: application/json\r\n\r\n") print(json.dumps(jsonv)) exit() def verify_email(mail): parsedEmail = parseaddr(mail)[1] if parsedEmail == '' or parsedEmail != mail or not re.findall(r'.+@.+\..+',parsedEmail): api({'msg':'invalid email'}) def save_bid(tbid): save_file = open("/dev/null","w") save_file.write(tbid) save_file.close() def list_items(): body = { "query": { "match_all": {} } } res = es_client.search(index="pawnshop", body=body) printout={} if(len(res['hits']['hits'])>0): for i in res['hits']['hits']: printout[i['_id']]={'seller':i['_source']['seller'],'item':i['_source']['item'],"picture":i['_source']['picture']} api({"list":printout}) api({"msg":"error"}) def lookupSeller(emailAddr): body = { 'query': { 'query_string': { 'query': 'id:>0 AND seller:"'+emailAddr+'"', "default_field":"seller" } } } res = es_client.search(index="pawnshop", body=body) if(len(res['hits']['hits'])>0): return emailAddr+' found' return 'not found'
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/3kCTF/2021/web/pawnshop/apache/src/index.py
ctfs/3kCTF/2021/web/pawnshop/apache/src/index.py
#!/usr/bin/python3 from funcs import * form = cgi.FieldStorage() action = form.getvalue('action') if action=='list': list_items() elif action=='bid': mail = form.getvalue('mail') item_id = form.getvalue('item_id') amount = form.getvalue('amount') if(mail != None and item_id != None and amount != None): verify_email(mail) save_bid(mail+"|"+item_id+"|"+amount+"\n\n") api({'msg':'bid saved, we will contact winners when auction ends'}) api({'msg':'error'}) else: api(False)
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/SEETF/2023/rev/Linear_Programming/crackme.py
ctfs/SEETF/2023/rev/Linear_Programming/crackme.py
import re # https://python-mip.readthedocs.io/en/latest/ # Change SCIP to CBC if you don't have it, it's slower but this script # can still run to completion from mip import Model, SCIP, BINARY ALLOWED_CHARS = set([*b"0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!?#$%&-_"]) def bytes_to_bits(pt): return [*map(int, "".join(format(c, "08b") for c in pt))] flag = input("Input password: ") m = re.match(r"^SEE\{(.+)\}$", flag) assert m and len(flag) == 25, "uwu" password = m.groups()[0].encode() assert all(c in ALLOWED_CHARS for c in password), "owo" Y = bytes_to_bits(password) model = Model(solver_name=SCIP) X = [model.add_var(var_type=BINARY) for _ in range(7792)] # Initialise model model += X[270] - Y[66] - Y[2] <= 0 model += X[270] + Y[66] + Y[2] <= 2 model += X[727] - Y[67] - Y[3] <= 0 model += X[727] + Y[67] + Y[3] <= 2 model += X[830] - Y[71] - Y[7] <= 0 model += X[830] + Y[71] + Y[7] <= 2 model += X[7295] - Y[64] - Y[0] <= 0 model += X[7295] + Y[64] + Y[0] <= 2 model += X[6981] - Y[65] - Y[1] <= 0 model += X[6981] + Y[65] + Y[1] <= 2 model += -X[270] + Y[66] - Y[2] <= 0 model += -X[270] - Y[66] + Y[2] <= 0 model += -X[727] + Y[67] - Y[3] <= 0 model += -X[727] - Y[67] + Y[3] <= 0 model += X[4494] - Y[68] - Y[4] <= 0 model += X[4494] + Y[68] + Y[4] <= 2 model += X[6588] - Y[69] - Y[5] <= 0 model += X[6588] + Y[69] + Y[5] <= 2 model += X[2093] - Y[70] - Y[6] <= 0 model += X[2093] + Y[70] + Y[6] <= 2 model += -X[830] + Y[71] - Y[7] <= 0 model += -X[830] - Y[71] + Y[7] <= 0 model += X[4196] - Y[72] - Y[8] <= 0 model += X[4196] + Y[72] + Y[8] <= 2 model += X[3284] - Y[73] - Y[9] <= 0 model += X[3284] + Y[73] + Y[9] <= 2 model += X[672] - Y[77] - Y[13] <= 0 model += X[672] + Y[77] + Y[13] <= 2 model += X[497] - Y[78] - Y[14] <= 0 model += X[497] + Y[78] + Y[14] <= 2 model += X[947] - Y[73] - Y[25] <= 0 model += X[947] + Y[73] + Y[25] <= 2 model += X[391] - Y[78] - Y[30] <= 0 model += X[391] + Y[78] + Y[30] <= 2 model += X[236] - Y[68] - Y[36] <= 0 model += X[236] + Y[68] + Y[36] <= 2 model += X[16] - Y[72] - X[468] <= 0 model += X[16] + Y[72] + X[468] <= 2 model += X[56] - Y[68] - X[905] <= 0 model += X[56] + Y[68] + X[905] <= 2 model += X[19] - Y[154] - Y[90] <= 0 model += X[19] + Y[154] + Y[90] <= 2 model += -X[7295] + Y[64] - Y[0] <= 0 model += -X[7295] - Y[64] + Y[0] <= 0 model += -X[6981] + Y[65] - Y[1] <= 0 model += -X[6981] - Y[65] + Y[1] <= 0 model += -X[4494] + Y[68] - Y[4] <= 0 model += -X[4494] - Y[68] + Y[4] <= 0 model += -X[6588] + Y[69] - Y[5] <= 0 model += -X[6588] - Y[69] + Y[5] <= 0 model += -X[2093] + Y[70] - Y[6] <= 0 model += -X[2093] - Y[70] + Y[6] <= 0 model += -X[4196] + Y[72] - Y[8] <= 0 model += -X[4196] - Y[72] + Y[8] <= 0 model += -X[3284] + Y[73] - Y[9] <= 0 model += -X[3284] - Y[73] + Y[9] <= 0 model += X[2992] - Y[74] - Y[10] <= 0 model += X[2992] + Y[74] + Y[10] <= 2 model += X[2212] - Y[75] - Y[11] <= 0 model += X[2212] + Y[75] + Y[11] <= 2 model += X[4604] - Y[76] - Y[12] <= 0 model += X[4604] + Y[76] + Y[12] <= 2 model += -X[672] + Y[77] - Y[13] <= 0 model += -X[672] - Y[77] + Y[13] <= 0 model += -X[497] + Y[78] - Y[14] <= 0 model += -X[497] - Y[78] + Y[14] <= 0 model += X[4926] - Y[79] - Y[15] <= 0 model += X[4926] + Y[79] + Y[15] <= 2 model += X[4547] - Y[64] - Y[16] <= 0 model += X[4547] + Y[64] + Y[16] <= 2 model += X[1059] - Y[65] - Y[17] <= 0 model += X[1059] + Y[65] + Y[17] <= 2 model += X[4628] - Y[66] - Y[18] <= 0 model += X[4628] + Y[66] + Y[18] <= 2 model += X[6651] - Y[67] - Y[19] <= 0 model += X[6651] + Y[67] + Y[19] <= 2 model += X[5733] - Y[68] - Y[20] <= 0 model += X[5733] + Y[68] + Y[20] <= 2 model += X[2846] - Y[69] - Y[21] <= 0 model += X[2846] + Y[69] + Y[21] <= 2 model += X[3525] - Y[70] - Y[22] <= 0 model += X[3525] + Y[70] + Y[22] <= 2 model += X[5914] - Y[71] - Y[23] <= 0 model += X[5914] + Y[71] + Y[23] <= 2 model += X[3945] - Y[72] - Y[24] <= 0 model += X[3945] + Y[72] + Y[24] <= 2 model += -X[947] + Y[73] - Y[25] <= 0 model += -X[947] - Y[73] + Y[25] <= 0 model += X[1397] - Y[74] - Y[26] <= 0 model += X[1397] + Y[74] + Y[26] <= 2 model += X[6258] - Y[75] - Y[27] <= 0 model += X[6258] + Y[75] + Y[27] <= 2 model += X[3439] - Y[76] - Y[28] <= 0 model += X[3439] + Y[76] + Y[28] <= 2 model += X[6077] - Y[77] - Y[29] <= 0 model += X[6077] + Y[77] + Y[29] <= 2 model += -X[391] + Y[78] - Y[30] <= 0 model += -X[391] - Y[78] + Y[30] <= 0 model += X[1119] - Y[79] - Y[31] <= 0 model += X[1119] + Y[79] + Y[31] <= 2 model += X[1532] - Y[64] - Y[32] <= 0 model += X[1532] + Y[64] + Y[32] <= 2 model += X[3894] - Y[65] - Y[33] <= 0 model += X[3894] + Y[65] + Y[33] <= 2 model += X[4561] - Y[66] - Y[34] <= 0 model += X[4561] + Y[66] + Y[34] <= 2 model += X[3531] - Y[67] - Y[35] <= 0 model += X[3531] + Y[67] + Y[35] <= 2 model += -X[236] + Y[68] - Y[36] <= 0 model += -X[236] - Y[68] + Y[36] <= 0 model += X[2333] - Y[69] - Y[37] <= 0 model += X[2333] + Y[69] + Y[37] <= 2 model += X[4293] - Y[70] - Y[38] <= 0 model += X[4293] + Y[70] + Y[38] <= 2 model += X[6294] - Y[71] - Y[39] <= 0 model += X[6294] + Y[71] + Y[39] <= 2 model += X[6841] - Y[72] - Y[40] <= 0 model += X[6841] + Y[72] + Y[40] <= 2 model += X[5873] - Y[73] - Y[41] <= 0 model += X[5873] + Y[73] + Y[41] <= 2 model += X[3705] - Y[74] - Y[42] <= 0 model += X[3705] + Y[74] + Y[42] <= 2 model += X[7463] - Y[75] - Y[43] <= 0 model += X[7463] + Y[75] + Y[43] <= 2 model += X[6278] - Y[76] - Y[44] <= 0 model += X[6278] + Y[76] + Y[44] <= 2 model += X[3070] - Y[77] - Y[45] <= 0 model += X[3070] + Y[77] + Y[45] <= 2 model += X[1968] - Y[78] - Y[46] <= 0 model += X[1968] + Y[78] + Y[46] <= 2 model += X[1194] - Y[79] - Y[47] <= 0 model += X[1194] + Y[79] + Y[47] <= 2 model += X[2570] - Y[64] - Y[48] <= 0 model += X[2570] + Y[64] + Y[48] <= 2 model += X[1044] - Y[65] - Y[49] <= 0 model += X[1044] + Y[65] + Y[49] <= 2 model += X[3998] - Y[66] - Y[50] <= 0 model += X[3998] + Y[66] + Y[50] <= 2 model += X[1415] - Y[67] - Y[51] <= 0 model += X[1415] + Y[67] + Y[51] <= 2 model += X[7380] - Y[68] - Y[52] <= 0 model += X[7380] + Y[68] + Y[52] <= 2 model += X[7201] - Y[69] - Y[53] <= 0 model += X[7201] + Y[69] + Y[53] <= 2 model += X[7674] - Y[70] - Y[54] <= 0 model += X[7674] + Y[70] + Y[54] <= 2 model += X[1300] - Y[71] - Y[55] <= 0 model += X[1300] + Y[71] + Y[55] <= 2 model += X[2615] - Y[72] - Y[56] <= 0 model += X[2615] + Y[72] + Y[56] <= 2 model += X[4740] - Y[73] - Y[57] <= 0 model += X[4740] + Y[73] + Y[57] <= 2 model += X[3568] - Y[74] - Y[58] <= 0 model += X[3568] + Y[74] + Y[58] <= 2 model += X[6236] - Y[75] - Y[59] <= 0 model += X[6236] + Y[75] + Y[59] <= 2 model += X[3500] - Y[76] - Y[60] <= 0 model += X[3500] + Y[76] + Y[60] <= 2 model += X[5773] - Y[77] - Y[61] <= 0 model += X[5773] + Y[77] + Y[61] <= 2 model += X[7036] - Y[78] - Y[62] <= 0 model += X[7036] + Y[78] + Y[62] <= 2 model += X[7065] - Y[79] - Y[63] <= 0 model += X[7065] + Y[79] + Y[63] <= 2 model += X[834] - Y[79] - X[593] <= 0 model += X[834] + Y[79] + X[593] <= 2 model += X[413] - Y[72] - X[346] <= 0 model += X[413] + Y[72] + X[346] <= 2 model += X[977] - Y[68] - X[268] <= 0 model += X[977] + Y[68] + X[268] <= 2 model += X[1627] - Y[72] - X[50] <= 0 model += X[1627] + Y[72] + X[50] <= 2 model += -X[16] + Y[72] - X[468] <= 0 model += -X[16] - Y[72] + X[468] <= 0 model += X[1703] - Y[78] - X[21] <= 0 model += X[1703] + Y[78] + X[21] <= 2 model += X[765] - Y[65] - X[985] <= 0 model += X[765] + Y[65] + X[985] <= 2 model += X[6751] - Y[71] - X[26] <= 0 model += X[6751] + Y[71] + X[26] <= 2 model += X[553] - Y[71] - X[479] <= 0 model += X[553] + Y[71] + X[479] <= 2 model += X[616] - Y[73] - X[992] <= 0 model += X[616] + Y[73] + X[992] <= 2 model += X[1428] - Y[70] - X[13] <= 0 model += X[1428] + Y[70] + X[13] <= 2 model += X[66] - Y[73] - X[1228] <= 0 model += X[66] + Y[73] + X[1228] <= 2 model += X[742] - Y[66] - X[984] <= 0 model += X[742] + Y[66] + X[984] <= 2 model += X[6868] - Y[72] - X[83] <= 0 model += X[6868] + Y[72] + X[83] <= 2 model += X[5495] - X[44] - X[59] <= 0 model += X[5495] + X[44] + X[59] <= 2 model += X[578] - Y[75] - X[759] <= 0 model += X[578] + Y[75] + X[759] <= 2 model += X[6852] - Y[65] - X[74] <= 0 model += X[6852] + Y[65] + X[74] <= 2 model += -X[56] + Y[68] - X[905] <= 0 model += -X[56] - Y[68] + X[905] <= 0 model += X[974] - Y[66] - X[421] <= 0 model += X[974] + Y[66] + X[421] <= 2 model += X[2239] - Y[76] - X[58] <= 0 model += X[2239] + Y[76] + X[58] <= 2 model += X[1191] - Y[64] - X[54] <= 0 model += X[1191] + Y[64] + X[54] <= 2 model += X[6295] - Y[65] - X[91] <= 0 model += X[6295] + Y[65] + X[91] <= 2 model += X[38] - Y[68] - X[1784] <= 0 model += X[38] + Y[68] + X[1784] <= 2 model += X[532] - X[799] - X[35] <= 0 model += X[532] + X[799] + X[35] <= 2 model += X[665] - Y[148] - Y[84] <= 0 model += X[665] + Y[148] + Y[84] <= 2 model += -X[19] + Y[154] - Y[90] <= 0 model += -X[19] - Y[154] + Y[90] <= 0 model += X[167] - Y[157] - Y[93] <= 0 model += X[167] + Y[157] + Y[93] <= 2 model += X[950] - Y[144] - Y[96] <= 0 model += X[950] + Y[144] + Y[96] <= 2 model += X[93] - Y[151] - Y[103] <= 0 model += X[93] + Y[151] + Y[103] <= 2 model += X[127] - Y[153] - X[64] <= 0 model += X[127] + Y[153] + X[64] <= 2 model += X[41] - Y[147] - X[387] <= 0 model += X[41] + Y[147] + X[387] <= 2 model += X[28] - X[68] - X[6859] <= 0 model += X[28] + X[68] + X[6859] <= 2 model += X[5737] - X[873] - X[6] <= 0 model += X[5737] + X[873] + X[6] <= 2 model += -X[2992] + Y[74] - Y[10] <= 0 model += -X[2992] - Y[74] + Y[10] <= 0 model += -X[2212] + Y[75] - Y[11] <= 0 model += -X[2212] - Y[75] + Y[11] <= 0 model += -X[4604] + Y[76] - Y[12] <= 0 model += -X[4604] - Y[76] + Y[12] <= 0 model += -X[4926] + Y[79] - Y[15] <= 0 model += -X[4926] - Y[79] + Y[15] <= 0 model += -X[4547] + Y[64] - Y[16] <= 0 model += -X[4547] - Y[64] + Y[16] <= 0 model += -X[1059] + Y[65] - Y[17] <= 0 model += -X[1059] - Y[65] + Y[17] <= 0 model += -X[4628] + Y[66] - Y[18] <= 0 model += -X[4628] - Y[66] + Y[18] <= 0 model += -X[6651] + Y[67] - Y[19] <= 0 model += -X[6651] - Y[67] + Y[19] <= 0 model += -X[5733] + Y[68] - Y[20] <= 0 model += -X[5733] - Y[68] + Y[20] <= 0 model += -X[2846] + Y[69] - Y[21] <= 0 model += -X[2846] - Y[69] + Y[21] <= 0 model += -X[3525] + Y[70] - Y[22] <= 0 model += -X[3525] - Y[70] + Y[22] <= 0 model += -X[5914] + Y[71] - Y[23] <= 0 model += -X[5914] - Y[71] + Y[23] <= 0 model += -X[3945] + Y[72] - Y[24] <= 0 model += -X[3945] - Y[72] + Y[24] <= 0 model += -X[1397] + Y[74] - Y[26] <= 0 model += -X[1397] - Y[74] + Y[26] <= 0 model += -X[6258] + Y[75] - Y[27] <= 0 model += -X[6258] - Y[75] + Y[27] <= 0 model += -X[3439] + Y[76] - Y[28] <= 0 model += -X[3439] - Y[76] + Y[28] <= 0 model += -X[6077] + Y[77] - Y[29] <= 0 model += -X[6077] - Y[77] + Y[29] <= 0 model += -X[1119] + Y[79] - Y[31] <= 0 model += -X[1119] - Y[79] + Y[31] <= 0 model += -X[1532] + Y[64] - Y[32] <= 0 model += -X[1532] - Y[64] + Y[32] <= 0 model += -X[3894] + Y[65] - Y[33] <= 0 model += -X[3894] - Y[65] + Y[33] <= 0 model += -X[4561] + Y[66] - Y[34] <= 0 model += -X[4561] - Y[66] + Y[34] <= 0 model += -X[3531] + Y[67] - Y[35] <= 0 model += -X[3531] - Y[67] + Y[35] <= 0 model += -X[2333] + Y[69] - Y[37] <= 0 model += -X[2333] - Y[69] + Y[37] <= 0 model += -X[4293] + Y[70] - Y[38] <= 0 model += -X[4293] - Y[70] + Y[38] <= 0 model += -X[6294] + Y[71] - Y[39] <= 0 model += -X[6294] - Y[71] + Y[39] <= 0 model += -X[6841] + Y[72] - Y[40] <= 0 model += -X[6841] - Y[72] + Y[40] <= 0 model += -X[5873] + Y[73] - Y[41] <= 0 model += -X[5873] - Y[73] + Y[41] <= 0 model += -X[3705] + Y[74] - Y[42] <= 0 model += -X[3705] - Y[74] + Y[42] <= 0 model += -X[7463] + Y[75] - Y[43] <= 0 model += -X[7463] - Y[75] + Y[43] <= 0 model += -X[6278] + Y[76] - Y[44] <= 0 model += -X[6278] - Y[76] + Y[44] <= 0 model += -X[3070] + Y[77] - Y[45] <= 0 model += -X[3070] - Y[77] + Y[45] <= 0 model += -X[1968] + Y[78] - Y[46] <= 0 model += -X[1968] - Y[78] + Y[46] <= 0 model += -X[1194] + Y[79] - Y[47] <= 0 model += -X[1194] - Y[79] + Y[47] <= 0 model += -X[2570] + Y[64] - Y[48] <= 0 model += -X[2570] - Y[64] + Y[48] <= 0 model += -X[1044] + Y[65] - Y[49] <= 0 model += -X[1044] - Y[65] + Y[49] <= 0 model += -X[3998] + Y[66] - Y[50] <= 0 model += -X[3998] - Y[66] + Y[50] <= 0 model += -X[1415] + Y[67] - Y[51] <= 0 model += -X[1415] - Y[67] + Y[51] <= 0 model += -X[7380] + Y[68] - Y[52] <= 0 model += -X[7380] - Y[68] + Y[52] <= 0 model += -X[7201] + Y[69] - Y[53] <= 0 model += -X[7201] - Y[69] + Y[53] <= 0 model += -X[7674] + Y[70] - Y[54] <= 0 model += -X[7674] - Y[70] + Y[54] <= 0 model += -X[1300] + Y[71] - Y[55] <= 0 model += -X[1300] - Y[71] + Y[55] <= 0 model += -X[2615] + Y[72] - Y[56] <= 0 model += -X[2615] - Y[72] + Y[56] <= 0 model += -X[4740] + Y[73] - Y[57] <= 0 model += -X[4740] - Y[73] + Y[57] <= 0 model += -X[3568] + Y[74] - Y[58] <= 0 model += -X[3568] - Y[74] + Y[58] <= 0 model += -X[6236] + Y[75] - Y[59] <= 0 model += -X[6236] - Y[75] + Y[59] <= 0 model += -X[3500] + Y[76] - Y[60] <= 0 model += -X[3500] - Y[76] + Y[60] <= 0 model += -X[5773] + Y[77] - Y[61] <= 0 model += -X[5773] - Y[77] + Y[61] <= 0 model += -X[7036] + Y[78] - Y[62] <= 0 model += -X[7036] - Y[78] + Y[62] <= 0 model += -X[7065] + Y[79] - Y[63] <= 0 model += -X[7065] - Y[79] + Y[63] <= 0 model += X[604] - Y[68] - X[6847] <= 0 model += X[604] + Y[68] + X[6847] <= 2 model += X[2140] - Y[70] - X[841] <= 0 model += X[2140] + Y[70] + X[841] <= 2 model += X[2699] - Y[71] - X[970] <= 0 model += X[2699] + Y[71] + X[970] <= 2 model += -X[834] + Y[79] - X[593] <= 0 model += -X[834] - Y[79] + X[593] <= 0 model += X[3185] - Y[66] - X[359] <= 0 model += X[3185] + Y[66] + X[359] <= 2 model += X[3786] - Y[73] - X[500] <= 0 model += X[3786] + Y[73] + X[500] <= 2 model += -X[413] + Y[72] - X[346] <= 0 model += -X[413] - Y[72] + X[346] <= 0 model += X[2130] - Y[66] - X[777] <= 0 model += X[2130] + Y[66] + X[777] <= 2 model += X[419] - Y[70] - X[2418] <= 0 model += X[419] + Y[70] + X[2418] <= 2 model += X[7648] - Y[79] - X[138] <= 0 model += X[7648] + Y[79] + X[138] <= 2 model += -X[977] + Y[68] - X[268] <= 0 model += -X[977] - Y[68] + X[268] <= 0 model += X[192] - Y[67] - X[2266] <= 0 model += X[192] + Y[67] + X[2266] <= 2 model += X[608] - Y[68] - X[4520] <= 0 model += X[608] + Y[68] + X[4520] <= 2 model += X[1577] - Y[71] - X[881] <= 0 model += X[1577] + Y[71] + X[881] <= 2 model += X[4995] - Y[73] - X[924] <= 0 model += X[4995] + Y[73] + X[924] <= 2 model += X[718] - Y[76] - X[6079] <= 0 model += X[718] + Y[76] + X[6079] <= 2 model += X[7485] - Y[66] - X[231] <= 0 model += X[7485] + Y[66] + X[231] <= 2 model += X[103] - Y[67] - X[7377] <= 0 model += X[103] + Y[67] + X[7377] <= 2 model += X[2151] - Y[68] - X[104] <= 0 model += X[2151] + Y[68] + X[104] <= 2 model += -X[1627] + Y[72] - X[50] <= 0 model += -X[1627] - Y[72] + X[50] <= 0 model += X[414] - Y[78] - X[7202] <= 0 model += X[414] + Y[78] + X[7202] <= 2 model += X[3940] - Y[79] - X[365] <= 0 model += X[3940] + Y[79] + X[365] <= 2 model += X[313] - Y[64] - X[6115] <= 0 model += X[313] + Y[64] + X[6115] <= 2 model += X[567] - Y[64] - X[1768] <= 0 model += X[567] + Y[64] + X[1768] <= 2 model += X[354] - Y[75] - X[6669] <= 0 model += X[354] + Y[75] + X[6669] <= 2 model += X[662] - Y[76] - X[1890] <= 0 model += X[662] + Y[76] + X[1890] <= 2 model += X[3476] - Y[72] - X[772] <= 0 model += X[3476] + Y[72] + X[772] <= 2 model += X[1975] - Y[64] - X[132] <= 0 model += X[1975] + Y[64] + X[132] <= 2 model += X[1777] - Y[66] - X[707] <= 0 model += X[1777] + Y[66] + X[707] <= 2 model += X[474] - Y[75] - X[3702] <= 0 model += X[474] + Y[75] + X[3702] <= 2 model += X[7592] - Y[67] - X[322] <= 0 model += X[7592] + Y[67] + X[322] <= 2 model += X[185] - Y[75] - X[2019] <= 0 model += X[185] + Y[75] + X[2019] <= 2 model += -X[1703] + Y[78] - X[21] <= 0 model += -X[1703] - Y[78] + X[21] <= 0 model += X[889] - Y[79] - X[3502] <= 0 model += X[889] + Y[79] + X[3502] <= 2 model += -X[765] + Y[65] - X[985] <= 0 model += -X[765] - Y[65] + X[985] <= 0 model += X[934] - Y[70] - X[6937] <= 0 model += X[934] + Y[70] + X[6937] <= 2 model += X[6608] - Y[72] - X[523] <= 0 model += X[6608] + Y[72] + X[523] <= 2 model += X[7530] - Y[78] - X[312] <= 0 model += X[7530] + Y[78] + X[312] <= 2 model += X[174] - Y[66] - X[1040] <= 0 model += X[174] + Y[66] + X[1040] <= 2 model += X[907] - Y[68] - X[2455] <= 0 model += X[907] + Y[68] + X[2455] <= 2 model += -X[6751] + Y[71] - X[26] <= 0 model += -X[6751] - Y[71] + X[26] <= 0 model += X[540] - Y[67] - X[3898] <= 0 model += X[540] + Y[67] + X[3898] <= 2 model += X[1671] - Y[70] - X[361] <= 0 model += X[1671] + Y[70] + X[361] <= 2 model += -X[553] + Y[71] - X[479] <= 0 model += -X[553] - Y[71] + X[479] <= 0 model += X[292] - Y[76] - X[1740] <= 0 model += X[292] + Y[76] + X[1740] <= 2 model += X[475] - Y[64] - X[1729] <= 0 model += X[475] + Y[64] + X[1729] <= 2 model += X[989] - Y[75] - X[4361] <= 0 model += X[989] + Y[75] + X[4361] <= 2 model += X[679] - Y[65] - X[2296] <= 0 model += X[679] + Y[65] + X[2296] <= 2 model += X[918] - Y[75] - X[2442] <= 0 model += X[918] + Y[75] + X[2442] <= 2 model += X[4335] - Y[76] - X[215] <= 0 model += X[4335] + Y[76] + X[215] <= 2 model += X[6699] - Y[67] - X[668] <= 0 model += X[6699] + Y[67] + X[668] <= 2 model += X[3351] - Y[72] - X[337] <= 0 model += X[3351] + Y[72] + X[337] <= 2 model += X[96] - X[2575] - X[798] <= 0 model += X[96] + X[2575] + X[798] <= 2 model += X[2767] - Y[78] - X[115] <= 0 model += X[2767] + Y[78] + X[115] <= 2 model += X[7703] - Y[64] - X[464] <= 0 model += X[7703] + Y[64] + X[464] <= 2 model += X[4801] - Y[67] - X[501] <= 0 model += X[4801] + Y[67] + X[501] <= 2 model += X[674] - Y[68] - X[3822] <= 0 model += X[674] + Y[68] + X[3822] <= 2 model += X[726] - Y[75] - X[5602] <= 0 model += X[726] + Y[75] + X[5602] <= 2 model += X[522] - Y[66] - X[3601] <= 0 model += X[522] + Y[66] + X[3601] <= 2 model += X[245] - Y[73] - X[3794] <= 0 model += X[245] + Y[73] + X[3794] <= 2 model += X[239] - Y[76] - X[6183] <= 0 model += X[239] + Y[76] + X[6183] <= 2 model += X[783] - Y[65] - X[1450] <= 0 model += X[783] + Y[65] + X[1450] <= 2 model += X[355] - Y[68] - X[7287] <= 0 model += X[355] + Y[68] + X[7287] <= 2 model += X[7292] - Y[75] - X[788] <= 0 model += X[7292] + Y[75] + X[788] <= 2 model += X[3398] - Y[77] - X[175] <= 0 model += X[3398] + Y[77] + X[175] <= 2 model += X[778] - Y[79] - X[1290] <= 0 model += X[778] + Y[79] + X[1290] <= 2 model += X[4793] - Y[64] - X[463] <= 0 model += X[4793] + Y[64] + X[463] <= 2 model += X[495] - Y[66] - X[1453] <= 0 model += X[495] + Y[66] + X[1453] <= 2 model += -X[616] + Y[73] - X[992] <= 0 model += -X[616] - Y[73] + X[992] <= 0 model += X[769] - Y[68] - X[5882] <= 0 model += X[769] + Y[68] + X[5882] <= 2 model += X[1359] - Y[69] - X[318] <= 0 model += X[1359] + Y[69] + X[318] <= 2 model += -X[1428] + Y[70] - X[13] <= 0 model += -X[1428] - Y[70] + X[13] <= 0 model += X[155] - Y[71] - X[3410] <= 0 model += X[155] + Y[71] + X[3410] <= 2 model += -X[66] + Y[73] - X[1228] <= 0 model += -X[66] - Y[73] + X[1228] <= 0 model += X[482] - Y[74] - X[6421] <= 0 model += X[482] + Y[74] + X[6421] <= 2 model += X[484] - Y[64] - X[3003] <= 0 model += X[484] + Y[64] + X[3003] <= 2 model += -X[742] + Y[66] - X[984] <= 0 model += -X[742] - Y[66] + X[984] <= 0 model += X[755] - Y[79] - X[4544] <= 0 model += X[755] + Y[79] + X[4544] <= 2 model += X[5440] - Y[66] - X[803] <= 0 model += X[5440] + Y[66] + X[803] <= 2 model += X[3424] - Y[71] - X[711] <= 0 model += X[3424] + Y[71] + X[711] <= 2 model += X[894] - Y[72] - X[1104] <= 0 model += X[894] + Y[72] + X[1104] <= 2 model += X[715] - Y[73] - X[6825] <= 0 model += X[715] + Y[73] + X[6825] <= 2 model += X[694] - Y[66] - X[4667] <= 0 model += X[694] + Y[66] + X[4667] <= 2 model += X[2399] - Y[67] - X[373] <= 0 model += X[2399] + Y[67] + X[373] <= 2 model += -X[6868] + Y[72] - X[83] <= 0 model += -X[6868] - Y[72] + X[83] <= 0 model += X[109] - Y[69] - X[3469] <= 0 model += X[109] + Y[69] + X[3469] <= 2 model += X[5691] - Y[71] - X[377] <= 0 model += X[5691] + Y[71] + X[377] <= 2 model += X[7598] - Y[74] - X[968] <= 0 model += X[7598] + Y[74] + X[968] <= 2 model += X[240] - Y[65] - X[3178] <= 0 model += X[240] + Y[65] + X[3178] <= 2 model += X[5823] - Y[67] - X[272] <= 0 model += X[5823] + Y[67] + X[272] <= 2 model += X[888] - Y[77] - X[4316] <= 0 model += X[888] + Y[77] + X[4316] <= 2 model += X[4630] - Y[64] - X[274] <= 0 model += X[4630] + Y[64] + X[274] <= 2 model += X[634] - Y[70] - X[5359] <= 0 model += X[634] + Y[70] + X[5359] <= 2 model += X[5040] - Y[79] - X[699] <= 0 model += X[5040] + Y[79] + X[699] <= 2 model += X[6671] - Y[66] - X[806] <= 0 model += X[6671] + Y[66] + X[806] <= 2 model += X[483] - Y[67] - X[3149] <= 0 model += X[483] + Y[67] + X[3149] <= 2 model += X[160] - Y[71] - X[5616] <= 0 model += X[160] + Y[71] + X[5616] <= 2 model += X[710] - Y[73] - X[3273] <= 0 model += X[710] + Y[73] + X[3273] <= 2 model += -X[5495] + X[44] - X[59] <= 0 model += -X[5495] - X[44] + X[59] <= 0 model += X[358] - Y[67] - X[1654] <= 0 model += X[358] + Y[67] + X[1654] <= 2 model += X[408] - Y[68] - X[1732] <= 0 model += X[408] + Y[68] + X[1732] <= 2 model += X[689] - Y[72] - X[5622] <= 0 model += X[689] + Y[72] + X[5622] <= 2 model += -X[578] + Y[75] - X[759] <= 0 model += -X[578] - Y[75] + X[759] <= 0 model += X[257] - Y[76] - X[6554] <= 0 model += X[257] + Y[76] + X[6554] <= 2 model += X[6020] - X[3433] - X[8] <= 0 model += X[6020] + X[3433] + X[8] <= 2 model += X[5] - X[7566] - X[5129] <= 0 model += X[5] + X[7566] + X[5129] <= 2 model += X[2134] - X[695] - X[37] <= 0 model += X[2134] + X[695] + X[37] <= 2 model += X[802] - Y[78] - X[1436] <= 0 model += X[802] + Y[78] + X[1436] <= 2 model += X[3980] - Y[79] - X[859] <= 0 model += X[3980] + Y[79] + X[859] <= 2 model += X[5972] - Y[66] - X[507] <= 0 model += X[5972] + Y[66] + X[507] <= 2 model += X[598] - Y[66] - X[3580] <= 0 model += X[598] + Y[66] + X[3580] <= 2 model += X[1479] - Y[67] - X[648] <= 0 model += X[1479] + Y[67] + X[648] <= 2 model += X[382] - Y[69] - X[2337] <= 0 model += X[382] + Y[69] + X[2337] <= 2 model += -X[6852] + Y[65] - X[74] <= 0 model += -X[6852] - Y[65] + X[74] <= 0 model += X[7239] - Y[72] - X[829] <= 0 model += X[7239] + Y[72] + X[829] <= 2 model += X[9] - X[2103] - X[1467] <= 0 model += X[9] + X[2103] + X[1467] <= 2 model += X[340] - Y[72] - X[6096] <= 0 model += X[340] + Y[72] + X[6096] <= 2 model += X[3024] - Y[74] - X[485] <= 0 model += X[3024] + Y[74] + X[485] <= 2 model += X[814] - Y[74] - X[7394] <= 0 model += X[814] + Y[74] + X[7394] <= 2 model += X[808] - Y[66] - X[4303] <= 0 model += X[808] + Y[66] + X[4303] <= 2 model += X[1957] - Y[76] - X[502] <= 0 model += X[1957] + Y[76] + X[502] <= 2 model += X[207] - Y[78] - X[6879] <= 0 model += X[207] + Y[78] + X[6879] <= 2 model += X[993] - Y[64] - X[7028] <= 0 model += X[993] + Y[64] + X[7028] <= 2 model += X[417] - Y[65] - X[2159] <= 0 model += X[417] + Y[65] + X[2159] <= 2 model += X[642] - Y[67] - X[7559] <= 0 model += X[642] + Y[67] + X[7559] <= 2 model += X[2360] - X[2011] - X[7] <= 0 model += X[2360] + X[2011] + X[7] <= 2 model += X[3238] - Y[68] - X[446] <= 0 model += X[3238] + Y[68] + X[446] <= 2 model += X[1951] - Y[71] - X[944] <= 0 model += X[1951] + Y[71] + X[944] <= 2 model += X[4525] - Y[72] - X[782] <= 0 model += X[4525] + Y[72] + X[782] <= 2 model += X[7373] - Y[75] - X[930] <= 0 model += X[7373] + Y[75] + X[930] <= 2 model += X[1239] - Y[79] - X[804] <= 0 model += X[1239] + Y[79] + X[804] <= 2 model += X[3703] - Y[66] - X[227] <= 0 model += X[3703] + Y[66] + X[227] <= 2 model += X[6097] - Y[65] - X[319] <= 0 model += X[6097] + Y[65] + X[319] <= 2 model += -X[974] + Y[66] - X[421] <= 0 model += -X[974] - Y[66] + X[421] <= 0 model += X[276] - Y[70] - X[1674] <= 0 model += X[276] + Y[70] + X[1674] <= 2 model += -X[2239] + Y[76] - X[58] <= 0 model += -X[2239] - Y[76] + X[58] <= 0 model += X[572] - X[695] - X[293] <= 0 model += X[572] + X[695] + X[293] <= 2 model += X[3497] - Y[78] - X[831] <= 0 model += X[3497] + Y[78] + X[831] <= 2 model += X[3428] - Y[66] - X[943] <= 0 model += X[3428] + Y[66] + X[943] <= 2 model += -X[1191] + Y[64] - X[54] <= 0 model += -X[1191] - Y[64] + X[54] <= 0 model += -X[6295] + Y[65] - X[91] <= 0 model += -X[6295] - Y[65] + X[91] <= 0 model += X[3788] - Y[68] - X[840] <= 0 model += X[3788] + Y[68] + X[840] <= 2 model += X[650] - Y[70] - X[6220] <= 0 model += X[650] + Y[70] + X[6220] <= 2 model += X[3737] - Y[66] - X[624] <= 0 model += X[3737] + Y[66] + X[624] <= 2 model += X[4248] - Y[64] - X[168] <= 0 model += X[4248] + Y[64] + X[168] <= 2 model += X[2427] - Y[68] - X[503] <= 0 model += X[2427] + Y[68] + X[503] <= 2 model += X[2244] - Y[73] - X[400] <= 0 model += X[2244] + Y[73] + X[400] <= 2 model += X[0] - X[1039] - X[3384] <= 0 model += X[0] + X[1039] + X[3384] <= 2 model += X[891] - X[544] - X[605] <= 0 model += X[891] + X[544] + X[605] <= 2 model += X[366] - Y[66] - X[5771] <= 0 model += X[366] + Y[66] + X[5771] <= 2 model += X[1900] - X[6685] - X[1] <= 0 model += X[1900] + X[6685] + X[1] <= 2 model += X[454] - X[44] - X[6503] <= 0 model += X[454] + X[44] + X[6503] <= 2 model += -X[38] + Y[68] - X[1784] <= 0 model += -X[38] - Y[68] + X[1784] <= 0 model += X[6552] - Y[70] - X[557] <= 0 model += X[6552] + Y[70] + X[557] <= 2 model += X[254] - Y[71] - X[6019] <= 0 model += X[254] + Y[71] + X[6019] <= 2 model += X[2246] - Y[72] - X[551] <= 0 model += X[2246] + Y[72] + X[551] <= 2 model += X[573] - X[44] - X[1537] <= 0 model += X[573] + X[44] + X[1537] <= 2 model += X[2157] - X[2102] - X[3] <= 0 model += X[2157] + X[2102] + X[3] <= 2 model += X[7573] - Y[70] - X[457] <= 0 model += X[7573] + Y[70] + X[457] <= 2 model += -X[532] + X[799] - X[35] <= 0 model += -X[532] - X[799] + X[35] <= 0 model += X[1678] - Y[67] - X[620] <= 0 model += X[1678] + Y[67] + X[620] <= 2 model += X[5740] - X[23] - X[835] <= 0 model += X[5740] + X[23] + X[835] <= 2 model += X[18] - X[6186] - X[700] <= 0 model += X[18] + X[6186] + X[700] <= 2 model += X[2] - X[7039] - X[6743] <= 0 model += X[2] + X[7039] + X[6743] <= 2 model += X[4169] - Y[144] - Y[80] <= 0 model += X[4169] + Y[144] + Y[80] <= 2 model += X[1730] - Y[145] - Y[81] <= 0 model += X[1730] + Y[145] + Y[81] <= 2 model += X[7621] - Y[146] - Y[82] <= 0 model += X[7621] + Y[146] + Y[82] <= 2 model += X[5142] - Y[147] - Y[83] <= 0 model += X[5142] + Y[147] + Y[83] <= 2 model += -X[665] + Y[148] - Y[84] <= 0 model += -X[665] - Y[148] + Y[84] <= 0 model += X[2156] - Y[149] - Y[85] <= 0 model += X[2156] + Y[149] + Y[85] <= 2 model += X[2539] - Y[150] - Y[86] <= 0 model += X[2539] + Y[150] + Y[86] <= 2 model += X[3343] - Y[151] - Y[87] <= 0 model += X[3343] + Y[151] + Y[87] <= 2 model += X[7625] - Y[152] - Y[88] <= 0 model += X[7625] + Y[152] + Y[88] <= 2 model += X[1860] - Y[153] - Y[89] <= 0 model += X[1860] + Y[153] + Y[89] <= 2 model += X[7006] - Y[155] - Y[91] <= 0 model += X[7006] + Y[155] + Y[91] <= 2 model += X[4940] - Y[156] - Y[92] <= 0 model += X[4940] + Y[156] + Y[92] <= 2 model += -X[167] + Y[157] - Y[93] <= 0 model += -X[167] - Y[157] + Y[93] <= 0 model += X[5374] - Y[158] - Y[94] <= 0 model += X[5374] + Y[158] + Y[94] <= 2 model += X[7009] - Y[159] - Y[95] <= 0 model += X[7009] + Y[159] + Y[95] <= 2 model += -X[950] + Y[144] - Y[96] <= 0 model += -X[950] - Y[144] + Y[96] <= 0 model += X[6313] - Y[145] - Y[97] <= 0 model += X[6313] + Y[145] + Y[97] <= 2 model += X[7339] - Y[146] - Y[98] <= 0 model += X[7339] + Y[146] + Y[98] <= 2 model += X[1612] - Y[147] - Y[99] <= 0 model += X[1612] + Y[147] + Y[99] <= 2 model += -X[93] + Y[151] - Y[103] <= 0 model += -X[93] - Y[151] + Y[103] <= 0 model += X[927] - Y[158] - Y[110] <= 0 model += X[927] + Y[158] + Y[110] <= 2 model += X[972] - Y[144] - Y[112] <= 0 model += X[972] + Y[144] + Y[112] <= 2 model += X[149] - Y[158] - Y[126] <= 0 model += X[149] + Y[158] + Y[126] <= 2 model += X[139] - Y[146] - Y[130] <= 0 model += X[139] + Y[146] + Y[130] <= 2 model += X[341] - Y[149] - Y[133] <= 0 model += X[341] + Y[149] + Y[133] <= 2 model += X[420] - Y[153] - Y[137] <= 0 model += X[420] + Y[153] + Y[137] <= 2 model += X[909] - Y[147] - X[187] <= 0 model += X[909] + Y[147] + X[187] <= 2 model += -X[127] + Y[153] - X[64] <= 0 model += -X[127] - Y[153] + X[64] <= 0 model += X[80] - Y[159] - X[2224] <= 0 model += X[80] + Y[159] + X[2224] <= 2 model += X[15] - Y[148] - X[2512] <= 0 model += X[15] + Y[148] + X[2512] <= 2 model += X[867] - Y[156] - X[781] <= 0 model += X[867] + Y[156] + X[781] <= 2 model += -X[41] + Y[147] - X[387] <= 0 model += -X[41] - Y[147] + X[387] <= 0 model += X[981] - Y[151] - X[363] <= 0 model += X[981] + Y[151] + X[363] <= 2 model += X[7435] - X[68] - X[156] <= 0 model += X[7435] + X[68] + X[156] <= 2 model += X[6771] - Y[148] - X[98] <= 0 model += X[6771] + Y[148] + X[98] <= 2 model += X[511] - Y[150] - X[429] <= 0 model += X[511] + Y[150] + X[429] <= 2 model += X[345] - Y[151] - X[559] <= 0 model += X[345] + Y[151] + X[559] <= 2 model += X[3339] - Y[154] - X[72] <= 0 model += X[3339] + Y[154] + X[72] <= 2 model += X[2692] - Y[144] - X[92] <= 0 model += X[2692] + Y[144] + X[92] <= 2 model += X[1186] - Y[149] - X[11] <= 0 model += X[1186] + Y[149] + X[11] <= 2 model += X[76] - Y[150] - X[6332] <= 0 model += X[76] + Y[150] + X[6332] <= 2 model += X[4523] - Y[150] - X[27] <= 0 model += X[4523] + Y[150] + X[27] <= 2 model += X[6328] - X[179] - X[29] <= 0 model += X[6328] + X[179] + X[29] <= 2 model += X[153] - Y[157] - X[632] <= 0 model += X[153] + Y[157] + X[632] <= 2 model += X[4035] - X[68] - X[331] <= 0 model += X[4035] + X[68] + X[331] <= 2 model += X[4] - X[1143] - X[5265] <= 0 model += X[4] + X[1143] + X[5265] <= 2 model += X[79] - X[2562] - X[456] <= 0 model += X[79] + X[2562] + X[456] <= 2 model += X[24] - Y[156] - X[5806] <= 0 model += X[24] + Y[156] + X[5806] <= 2 model += X[983] - X[539] - X[214] <= 0 model += X[983] + X[539] + X[214] <= 2 model += X[1554] - Y[149] - X[39] <= 0 model += X[1554] + Y[149] + X[39] <= 2 model += X[52] - Y[150] - X[1877] <= 0 model += X[52] + Y[150] + X[1877] <= 2 model += X[67] - Y[151] - X[7632] <= 0 model += X[67] + Y[151] + X[7632] <= 2 model += X[5426] - X[68] - X[770] <= 0 model += X[5426] + X[68] + X[770] <= 2 model += X[290] - Y[145] - X[280] <= 0 model += X[290] + Y[145] + X[280] <= 2 model += X[2958] - X[68] - X[467] <= 0 model += X[2958] + X[68] + X[467] <= 2 model += -X[28] + X[68] - X[6859] <= 0 model += -X[28] - X[68] + X[6859] <= 0 model += -X[5737] + X[873] - X[6] <= 0 model += -X[5737] - X[873] + X[6] <= 0 model += X[599] - X[173] - X[515] <= 0 model += X[599] + X[173] + X[515] <= 2 model += X[69] - X[310] - X[3969] <= 0 model += X[69] + X[310] + X[3969] <= 2 model += X[2453] - Y[65] - X[1418] <= 0 model += X[2453] + Y[65] + X[1418] <= 2 model += X[5639] - Y[66] - X[3716] <= 0 model += X[5639] + Y[66] + X[3716] <= 2 model += X[6593] - Y[67] - X[2674] <= 0 model += X[6593] + Y[67] + X[2674] <= 2 model += -X[604] + Y[68] - X[6847] <= 0 model += -X[604] - Y[68] + X[6847] <= 0 model += X[7459] - Y[69] - X[1902] <= 0 model += X[7459] + Y[69] + X[1902] <= 2 model += -X[2140] + Y[70] - X[841] <= 0 model += -X[2140] - Y[70] + X[841] <= 0 model += -X[2699] + Y[71] - X[970] <= 0 model += -X[2699] - Y[71] + X[970] <= 0 model += X[3902] - Y[72] - X[1007] <= 0 model += X[3902] + Y[72] + X[1007] <= 2 model += X[7224] - Y[73] - X[6659] <= 0 model += X[7224] + Y[73] + X[6659] <= 2 model += X[3231] - Y[74] - X[1887] <= 0 model += X[3231] + Y[74] + X[1887] <= 2 model += X[6402] - Y[75] - X[5535] <= 0 model += X[6402] + Y[75] + X[5535] <= 2 model += X[4232] - Y[76] - X[3921] <= 0 model += X[4232] + Y[76] + X[3921] <= 2 model += X[7038] - Y[77] - X[7001] <= 0 model += X[7038] + Y[77] + X[7001] <= 2 model += X[2105] - Y[78] - X[7131] <= 0 model += X[2105] + Y[78] + X[7131] <= 2 model += X[5497] - Y[64] - X[1166] <= 0 model += X[5497] + Y[64] + X[1166] <= 2 model += X[5046] - Y[65] - X[5612] <= 0 model += X[5046] + Y[65] + X[5612] <= 2 model += -X[3185] + Y[66] - X[359] <= 0 model += -X[3185] - Y[66] + X[359] <= 0 model += X[6423] - Y[67] - X[5955] <= 0 model += X[6423] + Y[67] + X[5955] <= 2 model += X[5751] - Y[68] - X[4127] <= 0 model += X[5751] + Y[68] + X[4127] <= 2 model += X[2180] - Y[69] - X[7289] <= 0 model += X[2180] + Y[69] + X[7289] <= 2 model += X[2234] - Y[70] - X[6350] <= 0 model += X[2234] + Y[70] + X[6350] <= 2 model += X[6232] - Y[71] - X[3643] <= 0 model += X[6232] + Y[71] + X[3643] <= 2 model += X[6548] - Y[72] - X[6835] <= 0 model += X[6548] + Y[72] + X[6835] <= 2 model += -X[3786] + Y[73] - X[500] <= 0 model += -X[3786] - Y[73] + X[500] <= 0 model += X[2540] - Y[74] - X[1519] <= 0 model += X[2540] + Y[74] + X[1519] <= 2 model += X[5091] - Y[75] - X[6384] <= 0 model += X[5091] + Y[75] + X[6384] <= 2 model += X[4217] - Y[76] - X[2532] <= 0
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
true
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/SEETF/2023/rev/Woodchecker/cpu.py
ctfs/SEETF/2023/rev/Woodchecker/cpu.py
# https://github.com/radical-semiconductor/woodpecker#processor-description class CPU: def __init__(self): self.mem = bytearray(1 << 29) self.addr = 0 self.store = 0 def execute(self, instr): match instr.strip().upper(): case 'INC': self.addr += 1 case 'INV': self.mem[self.addr // 8] ^= 1 << (self.addr % 8) case 'LOAD': self.store = self.mem[self.addr // 8] >> (self.addr % 8) & 1 case 'CDEC': self.addr -= self.store case other: raise ValueError(f'Unknown instruction "{other}"') if __name__ == '__main__': flag = input('Enter flag: ').encode('ascii') assert len(flag) == 20, 'Incorrect length' cpu = CPU() cpu.mem[:len(flag)] = flag for instr in open('woodchecker.wpk').readlines(): cpu.execute(instr) print('Correct!' if cpu.store else '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/SEETF/2023/crypto/OpenEndedRSA/chall.py
ctfs/SEETF/2023/crypto/OpenEndedRSA/chall.py
from Crypto.Util.number import * from gmpy2 import iroot # this helps with super accurate square root calculations! flag = b'????????????????????????' m = bytes_to_long(flag) e = 0x10001 pp = bytes_to_long(b'????????????????') s = 1 assert isPrime(pp) while not isPrime(s): p = getPrime(512) s = p**2 + pp**2 assert iroot(s-pp**2,2) == (p, True) # quick demo on how to use iroot() assert s%2 == 1 # duh, s is a prime number after all! q = getPrime(512) n = p*q c = pow(m,e,n) print(f'n = {n}') print(f'e = {e}') print(f'c = {c}') print(f's = {s}') """ n = 102273879596517810990377282423472726027460443064683939304011542123196710774901060989067270532492298567093229128321692329740628450490799826352111218401958040398966213264648582167008910307308861267119229380385416523073063233676439205431787341959762456158735901628476769492808819670332459690695414384805355960329 e = 65537 c = 51295852362773645802164495088356504014656085673555383524516532497310520206771348899894261255951572784181072534252355368923583221684536838148556235818725495078521334113983852688551123368250626610738927980373728679163439512668552165205712876265795806444660262239275273091657848381708848495732343517789776957423 s = 128507372710876266809116441521071993373501360950301439928940005102517141449185048274058750442578112761334152960722557830781512085114879670147631965370048855192288440768620271468214898335819263102540763641617908275932788291551543955368740728922769245855304034817063220790250913667769787523374734049532482184053 """
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/SEETF/2023/crypto/Non-neutrality/non-neutrality.py
ctfs/SEETF/2023/crypto/Non-neutrality/non-neutrality.py
from secrets import randbits from Crypto.Util.number import bytes_to_long import os flag = os.environ.get('FLAG', 'SEE{not_the_real_flag}').encode() # get a one-time-pad in which not exactly half the bits are set def get_xorpad(bitlength): xorpad = randbits(bitlength) return xorpad if bin(xorpad).count('1') != bitlength // 2 else get_xorpad(bitlength) def leak_encrypted_flag(): return bytes_to_long(flag) ^ get_xorpad(len(flag) * 8) # I managed to leak the encrypted flag a lot of times if __name__ == '__main__': for _ in range(2**16): print(leak_encrypted_flag())
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/SEETF/2023/crypto/Shard/shard.py
ctfs/SEETF/2023/crypto/Shard/shard.py
from Crypto.Util.number import getPrime from Crypto.Util.Padding import pad from Crypto.Cipher import AES from secrets import randbelow from hashlib import sha256 from math import isqrt import os flag = os.environ.get('FLAG', 'SEE{not_the_real_flag}').encode() p, q = getPrime(512), getPrime(512) n = (p * q)**3 a = randbelow(3**1337); A = pow(3, a, n) b = randbelow(3**1337); B = pow(3, b, n) shared = pow(A, b, n) assert shared == pow(B, a, n) key = sha256(str(shared).encode()).digest() ct = AES.new(key, AES.MODE_ECB).encrypt(pad(flag, 16)).hex() hint = isqrt(p) ^ isqrt(q) print(f'{n=}') print(f'{A=}') print(f'{B=}') print(f'{ct=}') print(f'{hint=}') # Code ends here. The output is printed below. ''' n=1161015060421173249378489750696141214060303995923395409949869627290702414711037093526198110777404654144671511905235970901959421941338918435310121680847960495861908297742489794351582662630349642895448557106366299469185588064602696326307097833183222618147069201840931225638628664922527925446087898861911362296363707119536526988582293048832383727953537307881230552636876712648271763176414090693303330350561279137776236795557842517619318238674985177929118712632535276039722205485150858981762083451832198822805690978929644453571222056709020149454001970560788598661970600271777421115525813743829030780059906217282681595452585004568419042410526300322447735538760602735954395278435630672731534059367618977970735807007280799837797901568012970516722520855615007870137859951477843419061096544616574048523021228941390127574301951810764886209442755752935524998421986069973124626502475162497047801043794416002937577783146899612599092388787 A=876856141867292541860323607264082069255499862749334652735605729433263443804539762724150146934351375350393080114923847779749893293139584686005392355141769986430382993358683972707818914126482354483753880940178023315634960922958253129075068286464920817560904484085316514309721680971508734869398801188634461566010739991385436551918949592308754421274535616460564680136888906568520377323715782357509089190820453332054156572172466552802449761288220780274972832498692580255837884665986978378035841349843031182334647618147782842049846153066181892449539407745486014499636387858777511312613142984882310305184710764200146570459723866686802492176613030166678729173421755638026624369502464133911152877741923335829863164896950580382969467402969579748979746430740394953571425965962087121649198611419063708096301382847206823372253864792103755888994838934565521982402277844450137390594607102522657031671082063652219166034186562490760814532579 B=287632227917624654212614562649343874383417428057330805237209169637026908557410569116739444108514384266685475678850601667911684150076525797991252031688869217089950247006850937786118259851817500044754131047963987707992467875713170336353659270924179467464836139578541900688370920519460119004845929450828524305499363274758459994420143563155593544731412056092492994042903315707705208959629847419957728142635524372296868834143016326096908127353866551528921319266146109788458033229140227479625927790051152685157231719361353398932500869549791514313894503151218196435978062246049426212499132086244127866741759522252412600587230711377821184153990120408229678096104763349842116878130234588134513252819344719559051734230776027339643260314327324982833200026332745447375624996928647322777183407239934048172826864244183355762705665502558087550433846102991894817404579682993484842986669591555105822532717319110007844731813526601115030730216 ct='fc8c67c8c451db0277fdc0b3ee6cd8e4d6584e00079a3326413450a1e816f4b463fa6e58148e25145cbdd0703847bc48' hint=27232338411805533611504752479750933666365962695083952636081656664814520651947 '''
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/SEETF/2023/crypto/No_Subbox/element.py
ctfs/SEETF/2023/crypto/No_Subbox/element.py
import numpy as np from functools import reduce _cache = { "mul": {}, "add": {} } class Element: A,B,C,D = [*map(lambda x: np.matrix(x, dtype=np.uint32), ([[1,0,0,0], [0,1,0,0], [0,0,0,1], [297,0,336,336]], [[1,269,0,0], [5,335,0,0], [0,8,0,1], [297,8,336,336]], [[8,0,0,0], [40,329,0,0], [232,0,295,0], [227,0,42,42]], [[329,0,269,0], [0,0,336,1], [105,0,8,0], [110,336,8,0]] ))] ID = np.matrix([[1,0,0,0], [0,1,0,0], [0,0,1,0], [0,0,0,1]], dtype=np.uint32) sz = 252 mod = 337 def __init__(self, x, _is_v = False): self._bytecache = None self._cachehash = None if _is_v: self.v = x return assert 0 <= x < self.sz a, x = x % 3, x // 3 b, x = x % 3, x // 3 c, x = x % 7, x // 7 d = x self.v = reduce(lambda a,b: Element._mulmat(a,b), [ Element._powmat(self.A, a), Element._powmat(self.B, b), Element._powmat(self.C, c), Element._powmat(self.D, d) ]) @classmethod def _from_v(_, v): return Element(v, True) @staticmethod def _mulmat(A,B): return (A @ B) % Element.mod @staticmethod def _powmat(A,n): if n == 0: return Element.ID if n == 1: return A if n % 2: return Element._mulmat(A, Element._powmat(A, n-1)) X = Element._powmat(A, n//2) return Element._mulmat(X, X) def to_byte(self): if self._bytecache is None: self._bytecache = MAPPING[hash(self)] return self._bytecache def __add__(self, other): key = (self.to_byte(), other.to_byte()) r = _cache["add"].get(key) if r: return r r = Element._from_v(Element._mulmat(self.v, other.v)) _cache["add"][key] = r return r def __mul__(self, n): key = (self.to_byte(), n) r = _cache["mul"].get(key) if r: return r r = Element._from_v(Element._powmat(self.v, n)) _cache["mul"][key] = r return r def __rmul__(self, n): return self*n def __hash__(self): if self._cachehash is None: self._cachehash = hash(bytes(np.ravel(self.v))) return self._cachehash def __eq__(self, other): return hash(self) == hash(other) def __str__(self): return str(self.to_byte()) def __repr__(self): return f"<E:{self}>" MAPPING = {hash(Element(i)): i for i in range(Element.sz)}
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/SEETF/2023/crypto/No_Subbox/chal.py
ctfs/SEETF/2023/crypto/No_Subbox/chal.py
from aes import encrypt_block, Element, N_BYTES from secrets import randbelow key = bytes([randbelow(Element.sz) for _ in range(N_BYTES)]) pt = bytes([randbelow(Element.sz) for _ in range(N_BYTES)]) ct = encrypt_block(key, pt) print(f"pt = {pt.hex()}") print(f"ct = {ct.hex()}") print("flag = SEE{%s}"%key.hex()) ### Truncated printed output below # pt = f085c01fefa2af35326467f6facfcf50 # ct = a016124ed2b337a845ca03be0dd014cd
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/SEETF/2023/crypto/No_Subbox/aes.py
ctfs/SEETF/2023/crypto/No_Subbox/aes.py
# Modified from https://github.com/boppreh/aes/blob/master/aes.py from element import Element RCON = [*map(Element, ( 0x00, 0x01, 0x02, 0x04, 0x08, 0x10, 0x20, 0x40, 0x80, 0x1B, 0x36, 0x6C, 0xD8, 0xAB, 0x4D, 0x9A, 0x2F, 0x5E, 0xBC, 0x63, 0xC6, 0x97, 0x35, 0x6A, 0xD4, 0xB3, 0x7D, 0xFA, 0xEF, 0xC5, 0x91, 0x39, ))] N_ROUNDS = 6 N_BYTES = 16 def shift_rows(s): s[0][1], s[1][1], s[2][1], s[3][1] = s[1][1], s[2][1], s[3][1], s[0][1] s[0][2], s[1][2], s[2][2], s[3][2] = s[2][2], s[3][2], s[0][2], s[1][2] s[0][3], s[1][3], s[2][3], s[3][3] = s[3][3], s[0][3], s[1][3], s[2][3] def add_round_key(s, k): for i in range(4): for j in range(4): s[i][j] += k[i][j] def mix_single_column(a): b1, b2, b3, b4 = ( 2*a[0] + 3*a[1] + 1*a[2] + 1*a[3], 1*a[0] + 2*a[1] + 3*a[2] + 1*a[3], 1*a[0] + 1*a[1] + 2*a[2] + 3*a[3], 3*a[0] + 1*a[1] + 1*a[2] + 2*a[3] ) a[0], a[1], a[2], a[3] = b1, b2, b3, b4 def mix_columns(s): for i in range(4): mix_single_column(s[i]) def xor_bytes(a, b): return [i+j for i, j in zip(a, b)] def bytes2matrix(text): return [[*map(Element, text[i:i+4])] for i in range(0, len(text), 4)] def matrix2bytes(matrix): return bytes(map(lambda m: m.to_byte(), sum(matrix, []))) def expand_key(master_key): key_columns = bytes2matrix(master_key) iteration_size = len(master_key) // 4 i = 1 while len(key_columns) < (N_ROUNDS + 1) * 4: # Copy previous word. word = list(key_columns[-1]) # Perform schedule_core once every "row". if len(key_columns) % iteration_size == 0: # Circular shift. word.append(word.pop(0)) # XOR with first byte of R-CON, since the others bytes of R-CON are 0. word[0] += RCON[i] i += 1 # XOR with equivalent word from previous iteration. word = xor_bytes(word, key_columns[-iteration_size]) key_columns.append(word) # Group key words in 4x4 byte matrices. return [key_columns[4*i: 4*(i+1)] for i in range(len(key_columns) // 4)] def encrypt_block(key, plaintext): assert len(plaintext) == N_BYTES plain_state = bytes2matrix(plaintext) round_keys = expand_key(key) add_round_key(plain_state, round_keys[0]) for i in range(1, N_ROUNDS): shift_rows(plain_state) mix_columns(plain_state) add_round_key(plain_state, round_keys[i]) shift_rows(plain_state) add_round_key(plain_state, round_keys[-1]) return matrix2bytes(plain_state)
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/SEETF/2023/crypto/Hard_To_Write/cipher_build.py
ctfs/SEETF/2023/crypto/Hard_To_Write/cipher_build.py
from numba import jit, uint64, byte from numba.pycc import CC cc = CC('_cipher') import numpy as np PERM = np.array([0, 16, 32, 48, 1, 17, 33, 49, 2, 18, 34, 50, 3, 19, 35, 51, 4, 20, 36, 52, 5, 21, 37, 53, 6, 22, 38, 54, 7, 23, 39, 55, 8, 24, 40, 56, 9, 25, 41, 57, 10, 26, 42, 58, 11, 27, 43, 59, 12, 28, 44, 60, 13, 29, 45, 61, 14, 30, 46, 62, 15, 31, 47, 63], dtype=np.uint64) SBOX = np.array([3, 10, 6, 8, 15, 1, 13, 4, 11, 2, 5, 0, 7, 14, 9, 12], dtype=np.uint64) INVPERM = np.array([list(PERM).index(i) for i in range(64)], dtype=np.uint64) INVSBOX = np.array([list(SBOX).index(i) for i in range(16)], dtype=np.uint64) NROUNDS = 14 @cc.export('byte2int', 'uint64(byte[:])') @jit(uint64(byte[:])) def byte2int(blk): r = 0 for i in range(8): r += blk[i] << (i*8) return r @cc.export('int2byte', 'byte[:](uint64)') @jit(byte[:](uint64)) def int2byte(x): r = np.zeros(8, dtype=np.uint8) for i in range(8): r[i] = (x >> (i*8))&0xff return r @cc.export('toints', 'uint64[:](byte[:])') @jit(uint64[:](byte[:])) def toints(pt): r = np.zeros(len(pt)//8, dtype=np.uint64) for i in range(len(pt)//8): r[i] = byte2int(pt[8*i:8*i+8]) return r @jit(uint64(uint64)) def sub(p): r = 0 for i in range(16): r = r | SBOX[(p >> (i*4)) & 0xf] << (i*4) return r @jit(uint64(uint64)) def perm(p): r = 0 for i in range(64): r |= ((p >> i) & 1) << PERM[i] return r @cc.export('encryptblk', 'uint64(uint64, uint64[:])') @jit(uint64(uint64, uint64[:])) def encryptblk(p, key): for k in key[:-2]: p ^= k p = sub(p) p = perm(p) p ^= key[-2] p = sub(p) p ^= key[-1] return p @jit(uint64(uint64)) def invsub(p): r = 0 for i in range(16): r |= INVSBOX[(p >> (i*4)) & 0xf] << (i*4) return r @jit(uint64(uint64)) def invperm(p): r = 0 for i in range(64): r |= ((p >> i) & 1) << INVPERM[i] return r @cc.export('decryptblk', 'uint64(uint64, uint64[:])') @jit(uint64(uint64, uint64[:])) def decryptblk(p, key): p ^= key[-1] p = invsub(p) p ^= key[-2] for k in key[:-2][::-1]: p = invperm(p) p = invsub(p) p ^= k return p @cc.export('expandkey', 'uint64[:](uint64)') @jit(uint64[:](uint64)) def expandkey(key): c = key ret = np.zeros(NROUNDS, dtype=np.uint64) for i in range(NROUNDS): ret[i] = c c *= 11704981291924017277 # c &= (1<<64)-1 # <-- not needed because uint64 c = sub(c) return ret @cc.export('internal_decrypt', 'byte[:](byte[:], uint64)') @jit(byte[:](byte[:], uint64)) def internal_decrypt(pt, keyseed): key = expandkey(keyseed) ret = np.zeros(len(pt), np.uint8) pint = toints(pt) for i in range(len(pint)): p = pint[i] c = int2byte(decryptblk(p, key)) for j in range(8): ret[8*i+j] = c[j] return ret @cc.export('internal_encrypt', 'byte[:](byte[:], uint64)') @jit(byte[:](byte[:], uint64)) def internal_encrypt(pt, keyseed): key = expandkey(keyseed) ret = np.zeros(len(pt), np.uint8) pint = toints(pt) for i in range(len(pint)): p = pint[i] c = int2byte(encryptblk(p, key)) for j in range(8): ret[8*i+j] = c[j] return ret if __name__ == "__main__": cc.compile()
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/SEETF/2023/crypto/Hard_To_Write/server_secrets.py
ctfs/SEETF/2023/crypto/Hard_To_Write/server_secrets.py
FLAG = "SEE{XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX}"
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/SEETF/2023/crypto/Hard_To_Write/cipher.py
ctfs/SEETF/2023/crypto/Hard_To_Write/cipher.py
import numpy as np from _cipher import * def decrypt(pt:bytes, key:int) -> bytes: return internal_decrypt(np.frombuffer(pt, dtype=np.uint8), key).tobytes() def encrypt(pt:bytes, key:int) -> bytes: return internal_encrypt(np.frombuffer(pt, dtype=np.uint8), key).tobytes()
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/SEETF/2023/crypto/Hard_To_Write/server.py
ctfs/SEETF/2023/crypto/Hard_To_Write/server.py
from server_secrets import FLAG # only server has this! import re import os import sys import numpy as np from cipher import byte2int, encrypt m = re.match(r"^SEE\{(.+)\}$", FLAG) assert m naked_flag = m.groups()[0].encode() key = byte2int(np.frombuffer(os.urandom(8), dtype=np.uint8)) print("Encrypted flag:", encrypt(naked_flag, key).hex(), flush=True) print("Hex encoded buffer:", flush=True) try: toencrypt = bytes.fromhex(sys.stdin.readline().strip()) except: raise Exception("uwu") assert len(toencrypt) <= 10000000 assert len(toencrypt) % 8 == 0 encrypted = encrypt(toencrypt, key) print("Encrypted:", flush=True) print(encrypted.hex(), flush=True)
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/SEETF/2023/crypto/Qskates/chall.py
ctfs/SEETF/2023/crypto/Qskates/chall.py
#!/usr/bin/env python3 from qiskit import QuantumCircuit, Aer from numpy.random import randint from Crypto.Util.number import long_to_bytes from Crypto.Cipher import AES from Crypto.Util.Padding import pad import os import hashlib def encode_message(bits, bases): message = [] for i in range(n): qc = QuantumCircuit(1,1) if bases[i] == 0: if bits[i] == 0: pass else: qc.x(0) else: if bits[i] == 0: qc.h(0) else: qc.x(0) qc.h(0) qc.barrier() message.append(qc) return message def measure_message(message, bases): measurements = [] for q in range(min(n,len(bases))): if bases[q] == 0: message[q].measure(0,0) if bases[q] == 1: message[q].h(0) message[q].measure(0,0) aer_sim = Aer.get_backend('aer_simulator') result = aer_sim.run(message[q], shots=1, memory=True).result() measured_bit = int(result.get_memory()[0]) measurements.append(measured_bit) return measurements def remove_garbage(a_bases, b_bases, bits): good_bits = [] for q in range(n): if a_bases[q] == b_bases[q]: good_bits.append(bits[q]) return good_bits def verifyInput(lst): for i in lst: if i != 0 and i != 1: return False return True n = 100 alice_bits = randint(2,size=n) alice_bases = randint(2, size=n) bob_bases = randint(2, size=n) message = encode_message(alice_bits, alice_bases) bob_results = measure_message(message, bob_bases) alice_key = remove_garbage(alice_bases, bob_bases, alice_bits) bob_key = remove_garbage(alice_bases, bob_bases, bob_results) assert alice_key == bob_key flag = pad(open('flag.txt','rb').read(),16) key = hashlib.sha256(''.join([str(i) for i in alice_key]).encode()).digest()[:16] iv = os.urandom(16) cipher = AES.new(key=key, iv=iv, mode=AES.MODE_CBC) enc = cipher.encrypt(flag) print(f'iv = {iv.hex()}') print(f'enc = {enc.hex()}') while True: message = encode_message(alice_bits, alice_bases) eve_bases = [int(i) for i in input("Enter bases to intercept: ")] assert verifyInput(eve_bases) eve_results = measure_message(message, eve_bases) print("Measured message:", eve_results) new_bits = [int(i) for i in input("Enter bits to send to Bob: ")] assert verifyInput(new_bits) new_bits += alice_bits.tolist()[len(new_bits):] new_message = encode_message(new_bits, alice_bases) bob_results = measure_message(new_message, bob_bases) alice_key = remove_garbage(alice_bases, bob_bases, alice_bits) bob_key = remove_garbage(alice_bases, bob_bases, bob_results) print(alice_key == bob_key)
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/SEETF/2023/crypto/Dumb_Chall/main.py
ctfs/SEETF/2023/crypto/Dumb_Chall/main.py
import random import time from Crypto.Util.number import bytes_to_long, isPrime from secret import FLAG def fail(): print("You have disappointed the pigeon.") exit(-1) def generate_prime_number(bits: int = 128) -> int: num = random.getrandbits(bits) while not isPrime(num): num += 1 return num def generate_random_boolean() -> bool: return bool(random.getrandbits(1)) def first_verify(g, p, y, C, w, r) -> bool: assert w return ((y * C) % p) == pow(g, w, p) def second_verify(g, p, y, C, w, r) -> bool: assert r return pow(g, r, p) == C p = generate_prime_number() g = random.getrandbits(128) x = bytes_to_long(FLAG.encode()) y = pow(g, x, p) print(f"p = {p}") print(f"g = {g}") print(f"y = {y}") print("Something something zero-knowledge proofs blah blah...") print("Why not just issue the challenge and the verification at the same time? Saves TCP overhead!") seen_c = set() for round in range(30): w, r = None, None choice = generate_random_boolean() if not choice: w = int(input("Enter w: ")) C = int(input("Enter C: ")) if C in seen_c: fail() seen_c.add(C) verify = first_verify else: r = int(input("Enter r: ")) C = int(input("Enter C: ")) if C in seen_c: fail() seen_c.add(C) verify = second_verify if not verify(g, p, y, C, w, r): fail() else: print(f"You passed round {round + 1}.") time.sleep(1) print( "You were more likely to get hit by lightning than proof correctly 30 times in a row, you must know the secret right?" ) print(f"A flag for your troubles - {FLAG}")
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/SEETF/2023/crypto/Semaphore/semaphore.py
ctfs/SEETF/2023/crypto/Semaphore/semaphore.py
import ecdsa # https://pypi.org/project/ecdsa/ import os flag = os.environ.get('FLAG', 'SEE{not_the_real_flag}').encode() sk = ecdsa.SigningKey.generate() for nibble in flag.hex(): signature = sk.sign(flag + nibble.encode()) print(signature.hex()) # Code ends here. The output is printed below. ''' 04a22664841747a475192a7f9b6461404c0f85c46810d00d1a18249338e5bb58fe32e6580e6aab74dad040e1e7ae0a2d 4992c6691ae1e326f5038d050bce13d5007625c3c694a86dc9a75748f395ae80b5d904b6464f0e17b2df17e6b9f540ee 836b146003baaf00b28403ca52b7df2d949350cf4e57b7e9f981b6ee9293c93d44977f102b5bd4000d93890ebfff2d28 5e7d2389cb92df48845cf3d70a172e458de9456743964568c2532f080ea5b4ba70301b27f5d9019f5d0ac4aafd2147af 1cf28514e763cf6494814e0d64d32bd20ce99a983e88dc66225aaa4246c58ab6f33a2bfe441e023582b47937ac8d15a4 1a1980d999797b5af80d4f550d741708352f738c137f8ca6e1fd9dd3b70fa75f800f865b6b5098fb95c62ab40a80594f 83b70fc96da176c34f616a48be43ebc22b090545a52b972cc784d55c79996ef842493514a6969db7c5d34b9ef6fcd28e 99c5d66a1f7f79d5b194397af66a347b7cba9dc5d327424aea71bc82fba1bbf5d50acd57e6eea4fa366a542f1a91e350 37f606bfdc2004293292509364f154173a1c13aea5f6dd75be8b5cb0343e92c8efc405e7956b73132afa80d327521a8b 012a666c3dbf7a64760acf459fd4ad4de7a235ee8866c3810227c8f7cbcddda79130c46b820bff9521965dfe44de32af ceb8fdf5acaf767a76f40ae6112b5c402a2e4e7713631e4c51e963fa61b193fd8ef0fbcbf088e5b525d1d808c5d094dd 71b1a7e5b7816b1de309daa88a8a3883a37d28650532ecbc3f462b005b353266011bdf3d642d78822c8c7299449f1f22 02caf72b6060b761d23c9bdfd4e9296a34bfd0a364eba5a81ae842a117bdd82c28ac8c692911b7d3eedbf3c543d0f48d b959a90d2aab7a2be3684b69328d35ed9694d9df0eb4ea6e6938c806838d0db6b76718b9e7fc4268c14c17246f499af9 03b422faff6fd1de0dff181977560def1bef40ee307957d15039b06c202bc5827eba1d0e2c5027051fb5dc093bded056 fa5f0046485ea006d5917d353d3cba2010c3b5edbe87352f7450dd155c15e38de1d990be4754c5c0ff24d37a8f01af92 f027161939478e23ac9b99d56e37a0cdd76175a42892f8d7cb0dcc84964663d672c9f23812d016d445ff5c7589725c6d 30b8757465a5ec8801a5a190eb296d7d2c9ea3b1eb2c62f6062a0a8b5115f30c054cb0d5eeaba480dabfb3c5c70abef0 889087215877cabd0c743f5864306db81fa46e91eac31b759b0d23afc036235d265c609e37117b9d15266ce8ecc5db2b 9c76eae7ec44540bd41c06ba9c25b4734c9bbf68880494a38e0b118fca93677fa5770b98c0b982245a207880036e6445 2bd29f6aa55103be42b16e394a1190a03f8a22b7b7162a5d03c0423a19de47b4b8167bc330690f36db02ef5377624c80 c9b933108fad16ffd1275ea14e4b506d9c9c03df4287f99a71c09402c3a11c19932ad14af8468a84aedd8615a762d366 2e564b6e2730d220a65de2899ec7a99056c3d8e89f0178b5e974483bcc9b5949f69908777f7332bb4fe84d431e8a5a35 2f687205c31b07820a872e2a3d4e6897561ee3873086b445570a66b13232ade40e38397b648a5cac7a9a324664ece3bf 2dca9b0a9e96472b18119921a681d23d2ec3acacd1b9c0a011e23ca24407808be25e04edcbc736b9b11b6a167a2d297a b2781278a3acd8768ca8ba1ad698a3b775c330df9a7837d18f9796cd838e5714e461f1bbfd1d3af9230c05ea33bc5555 191447109bb7de900a70e06170e492fd84d908fde7ccd2a5ed6a28c1860e655958d2f54e4638a54cbebbd35a61b528dc 54e0e6509a899baf44574eaa7d302bf00e5edfd8b0d0fa62f74524bf92bea63384773489c69e64b4b757afc9da0ecda4 941d9cb5676e366157d8bd6c92b7687539acb7a06bc611f8ad64871f0e6a598385957517aeb9972b719477bbdb31865f 1741225d735cc11377c31e8976a269473d66d8f788f34822cae720cd82f0e99af50807d1edb7513ba14efc097183d192 f5568fc82c2ca245465533f9b98bb537c9bc8e2e050d00cdf431e8acf6ed5c69b88f93760cb7fe85128a22db83242ba4 d00c1c38ff9cd6e15846aac2e821b9d60846a96d0688f86f40ea3178030868579300e2c0aa9cf9ae373ae9f817fe7ae5 76fb8669a5694795efaa9b4e38c0a306112054c891f9f871a80b6caec231f35b45c0c6ca8f64423861a5d5d09362af51 cffe394dd32e1bd6c71d300412f6551512a9eb71be7eb4b53c702caae94ae8673bf95cb7e76a0bb06e345e7e35305efa cc82ce7885a5ac4bc08bdbd13976e3cd3b2a3f439180a329e826275e3dee8386720bf28d75596c289b5bc0b9d364eef9 4f4eb4b9bb6c6deaf1173763dbd1518079096d8863a4140dca9c01693ae4bfaab6f125e0ed5a5f20200b8c1a86e58ef8 9cad001be5d25df58a5a804ca97d9e6c7f32d6779fc020bf68727a83548382c5dc4e12359e0914cf7fca879c60fce06d 1f7091b011dfdd1ea0dcb6071f85d5c75642e37517d5263d4b468490496f90abb26e02307aa54d3d4dfde6d80626d933 7a05a981041f8e406fc69a5569c5aa2c2fa8a4c6445e3bd974a19f9fb3720cb5218c79e5eb586bfc3915d0e7ca7a9638 71b8b89846f6849a17cd6258695790f7c71945e0c6b8fd3f297809ad61ddd9f73f8ec4538e45d1d420f328fefd71fd39 d8397c87bd54c91a060d0565ff0f6edc0af0287889cd7a03ac321ea9ae1999f370ee8881b2a01b924f4fbc199cf1d868 5b848e0310b6d652310686af9cbbc6d08f42e37eb83c3c0cec22e643f859c30fc7bbeb8c1fe4e16c8dcf9e325a685a7a 4cc8713a14a5a074ecc112e22192bb162e1d5ea303939dbf2bbb9620da0ff9eb326fb5b30c7c133283a7949230ee7177 fa7e00b2da873ad104a50df8639ee6e8e702e256fd4a8ebbb25bde28988750eefcef91d4ec891458f3e700fef132071f 1fdfd4432de9d3647a194cf8d66b3d8a5e3eac5bb1e832b366ed37b4b7875fa6346b1b65bb3f068c61358ad7b7e5ee5e 0d660198e6c811a34136dc087693e81ebbd5877c722a7624ddb682043e5d24c8cf892f13b2cf2383f476f12e68bd94b5 e8f9d1f42b54c76836bae42b05bba24ffcdd0dd935380b615223a0c6ca1569a448d74cbb78e47bca635dade3e802c8a5 04a21057c034f7cb9eff39935f464aa5d4dc027b9d5da05ee5f097f12f40a4046f87683ad1638e1e05e61246ee178fbd cabf588910bce6d41552ac5addb00f196f90c809dc6856f8e8c7490338b98bc423d2cf42c3e3faa73ab171a5a8544433 d61eeaa195eaa6970dc99e4e0ed779ee0e450f4b73917b6fd00f4bd99b26a0bb05313cdc8915d17d7b0d9942410658af c758b4cf5847593c4cb4e356ec865e8797d74a564cf9ad1549feb4d8439e8598d0b69cd44c3267d36c1d7317303e2aa1 bd21290aee61dd300f3850b567114c8f5a1b6f8b170711b8b79f225a04961c5c39903d100a8725025da33922beba9098 a832c1f4b54699f59adff2dc5d9401888ef48eb1e3dee75d6b24334db5d8cdbe17cc87131fcfeb2fc59a084a817047a1 9251d8c0e198b84bb52e656388a4a5fc7e487dd777effa80cce8f0a9feab8b5a96bffeb73f36984c16fbb1214e2cfe65 8e2bc98948c3d0989ef1fcb26620a383a41414e55b5844e6e61e50335c18c097c1850c78acd776ffe4d35194227fb358 f18f9004efa7d5c6201faa99481df0870403f0952beffcecf9bae9eb05be06e777c83bd3fe30ba8666d72292c9f6c093 a07f86f2a093ca8d6fdbc63cb56d3527e6c85225fb77f86efea0dc1550333e7b5abcb49368c60a70ef4cf8456600b73e a520893f94bc749b07d25d8bd1185105c001f12f4e0004733f6b1ff2197925941891f343f3eaa97bfcd461776b46217d 739c2f2c68b83569cccfb8d9178ac5e5299723fedae515d6df245ad5a0964b91f9a5a6e869c7ef57598fd33757db51a3 cb59854d3b20c9f5d432e205af140bfbd34ccee0b579f67e6ceefd91e64815df1e84969a9ee2a57bd6e559d7ef9ec3c9 1b9556ba0691912615c25a08eebb0b56e46ee639c56ef2b979322e5cbc797c9c83fa59b83c5e9e45b9b7eb51eaa1ed77 0f49b18563052f9b64ebbc1a9e0fa1e5685e09c8bd266e4231e42fd25ac74f7bea9d4decd17bd9b5c9b8c808a3751612 77f08e003539e15a5a5f860cb8e9cd42ae239c9c2c7bb7d7e094b15834c86f70e4b8bb22fde71ddb4a6916b2e9725d00 5073b22c6ac1c3171e01bfaaf0ab55b2d8be72fc259efe5c36bc1cdfa2a15db2e682411d4289bd66090417aa9893c46a a11eadfd3a5c22820b1bc815088bebf74804b8479a77a8b72641a2743f6a1401038006cb90c777d7f29f42f519ef1545 e06f918ac5e068884627b2b30968e5241c8f7be6a66c92357f905eb734c7d2a8e0da5e2b355749dfa684173aa0cfaba7 ddcfe5abc02ba60668d6d87420fb1d74fc54b97707ff01cf2a0200ddf2eb708e40e9d9ae89841df4bb0e5c1aea8b6885 c7c7389b6a06f11386435449c154c1b6878c01288eeab32e0f54ce92a5c5b7c90a978a9ce4ea61efc3d2c8617f6fa6c4 41ead48d0c0640dc03cea84b6ed19d20a545de95953270a5c20043ccd84179f46d99ee44bf4a8798a09c174ff8aac7a1 c0219509f94da75f18f1fd56aecfa7b9021de999a571a4dda2be8de2ebd439ae242fd85c8742886af570cd6f0a4c58a2 d6fe36dc75694a4459a6f54294f17ece7f4fdc09e7e8fb2b992e72a0ab92da0f00f7b73282c804815b4c674778b760bd becb1781197c26b711796ebde491bdd2c1e8ce6fe70cdf255ff8af6badf01e977f06af4f047bb2485e5bf530e4413b32 586c6d74c886fa28de23b66a5616e7b0924c08ce87e8cce6826f3b3ef4c653d9bd103c9c8d8f9051017b7cdc4aed2507 e6480c201a46f1a537af82279a6936d0ef4b1d0e5ea60c56126c4ef38fb42bf1d881451498242173d850751c4f6b0b40 5e092141eec07faddd009722c58aa6042e404b144f1e29f76a1f0b8db7452bca3298373cb17cdf1afe0792b50500e97b f877b834ed12f579caed92aa8fb4708ea7629aaea623c63d863b31571cbce32464bbb6f4dc62bd5a37ac860a89f3d169 e6c6d06cc146fd1b488bae21ed510b483d8e118396186623ce876b3081538731190d2a81f57cdb1a2fe86ab02ac1f804 b0693ac1b3aa3d921ed516c5c7e7162cfa17567d41dfddbf46692ab01b3b23c60e6a1778064290126fdeea97f225768d 503349510da1d0c30f6a7738f710ec4a3d38074f0baee3ea374606ac6ddb104a7ff5765cf86c189613cd19d898ecc1ef c3b232a6769c8fb966fd9ebcccab5c9a55fdb211685e2b9136d818c3058a505e575a9d891eb61087b2e44c3a3863ffde d8413b76bcf223d39e74c02b99fa9ef4dcfe5ef2bedd366e2f9121fd90c764a7980c2927d61f98ddb7513c2a00162738 7f5df9befb7bd6820dd4b855cd5eb1d33c128423947e7601c88a3e922b3ad444bd39fd719cda592da81626578633bcd7 b13436a9210dcfb8ac294ae29fc92f750e9087a7cd39387a84efbf6c890ecc30f44eb6f6343892de42f4368e092963a7 c6800eb141fae73be3f14e18aa303c569a303374828799d6881bfa33eb5ead1ccb3c6e0ddd04baeef518347e1b75a1c2 2f9e95add8b9cb8d394eee05b61d3795843ce031e412c9d50c429d61460812e34a5c710b8949b0cafc6396b6cbe144f2 1cb85d64987c1a89272ccba305480e2dd6ea84104578be8d7bfc817ce95fd023b69d2da01a241aa40273c7f2f1bd3862 928dd997dcb9eeb7035a5b41cfb8e6227ba4df81d12184c7117af18919a65e865c578a52870c06aca8bbc51d6b1ee68f bff6eeb1e169f08e0aa215fcb49ac59b24a07416328d1fa64939063b9d811b47d89345f8980ee9fc514d0681b87a1a18 0869e138cb6c94f3aa4eba51c921052cbf61cc5ddae4a352b74c8ce8e8e92f6d77b6158c07a140bf8d640fc4ea05e209 dd6991b4b8945a16f372981b965cf7ca68e1d252dec7206623054e308661fae9861b7fcac3d493654d01e9dcc8d7dc21 cfa5a9251a1afd5ae0c7ec1b0526b3c0e809ec1313f531417e18fa8c3ec8bdbf9324fe8e5637fcfcf884ca05ad574e90 a3ca6bc05146bba763dd89ee448dca3868062a5f7ecd6eb4827567dac06cd468ed3a3ff218e16773767ce67954418041 ddafe8b0a311ec80c3914444208e1240568efb7493038c50c4eb4d34361ca12b2bece6d833d909761945b5b10c5ff94e b146adb3a575922705ba342f6904c9bbb92f5a94261f47edac363f7dde7d50020cd280a308a40bc8f82d692099de6687 7424a27cc2cda56f525948c33872f91326ed5638f6169c398585a87eb519e1294f66a30331b33f35aced9d0599a83c9a 88185e1182ab98f591b235fa9f59985cc46ad443f285d9e029de0e03d7c5636881ba7123775ba908a885b132842910e1 fadca658a0a25295f5121f6087701c83cf9737f5a747945c282cecfb5ec0488d6cecc49235cd8accfeb3c2c5c76398f9 d64b25adb930fc2deb30a6e45e6999f34317a82e80eabdc489e46c4e29cab2a618fd2a45e5bb17b43ae4dc8f851d17af 047217194a01a40a045d1c74a06328d3ec001730a0fde471367db054dcbac53f683f3f522308f40f7dd3a6a467093897 1b5cb6cecce1bdf9ea0c68fb90a4ace3991f8fa6c19dbf9792dbab79faab39e0b0663730de3396c6bb3d40e386880c72 6361f675be68f096e54cd833f4e06b50f0388370bdf65fa4c4db0d4448ff89b48b694246bf3da3c9d9c8e7b24289281d 557e1657574aa4d54cc39981bfc31f97b37edb14ec7f197d161bd0409a99bb1867a54b2c5dca27db5ed29eeb907114cf f141467f8e7ae6a012a746547c318551f8eb6090882baed7834ee8e0daa48878e822d8afdbe7b525d5b90d8152c59eba 744e97057789f5431586ca9e5e42c0d9bf2d5810e145c64c054e58211cdf6afcb21b56b1f778f33d3c731df01aeba4a7 b27c148ef046e856aa895ba02b9f8f982d42e3e5776c4b8f0c0e738c2e201efe2f70645286faae60a822663746233ba4 b53ce532c98b059a24c890d3d12492cfc7fb92172b9dda4f31d296185f34ec5dedc35714a5c73d117cedd037a1f4ef3c '''
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/SEETF/2023/crypto/BabyRC4/chall.py
ctfs/SEETF/2023/crypto/BabyRC4/chall.py
from Crypto.Cipher import ARC4 from os import urandom key = urandom(16) flag = b'SEE{?????????????????????????????????}'[::-1] def enc(ptxt): cipher = ARC4.new(key) return cipher.encrypt(ptxt) print(f"c0 = bytes.fromhex('{enc(flag).hex()}')") print(f"c1 = bytes.fromhex('{enc(b'a'*36).hex()}')") """ c0 = bytes.fromhex('b99665ef4329b168cc1d672dd51081b719e640286e1b0fb124403cb59ddb3cc74bda4fd85dfc') c1 = bytes.fromhex('a5c237b6102db668ce467579c702d5af4bec7e7d4c0831e3707438a6a3c818d019d555fc') """
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/SEETF/2023/crypto/Romeo_and_Juliet/romeo_and_juliet.py
ctfs/SEETF/2023/crypto/Romeo_and_Juliet/romeo_and_juliet.py
from Crypto.Util.number import getPrime, bytes_to_long import os flag = os.environ.get('FLAG', 'SEE{not_the_real_flag}').encode() class Person: def __init__(self): p, q = getPrime(512), getPrime(512) self.e = 65537 self.d = pow(self.e, -1, (p-1)*(q-1)) self.n = p * q def hear(self, m): return pow(m, self.e, self.n) def yell(self, c): return pow(c, self.d, self.n) Romeo, Juliet = Person(), Person() noise = os.urandom(16) print('Romeo hears the flag amidst some noise:', Romeo.hear(bytes_to_long(noise[:8] + flag + noise[8:]))) for _ in noise: print('Juliet hears:', Juliet.hear(Romeo.yell(int(input('Romeo yells: '))))) print('Romeo hears:', Romeo.hear(Juliet.yell(int(input('Juliet yells: ')))))
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/SEETF/2023/web/file_uploader_2/init.py
ctfs/SEETF/2023/web/file_uploader_2/init.py
import sqlite3 con = sqlite3.connect("user.db", check_same_thread=False) con.isolation_level = None cur = con.cursor() cur.execute(""" DROP TABLE IF EXISTS users; """) cur.execute(""" CREATE TABLE IF NOT EXISTS users ( dXNlcm5hbWVpbmJhc2U2NA TEXT NOT NULL PRIMARY KEY, cGFzc3dvcmRpbmJhc2U2NA TEXT NOT NULL ); """) cur.execute(""" INSERT INTO users (dXNlcm5hbWVpbmJhc2U2NA, cGFzc3dvcmRpbmJhc2U2NA) VALUES ('admin', 'SEE{<REDACTED>}'); """)
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/SEETF/2023/web/file_uploader_2/app.py
ctfs/SEETF/2023/web/file_uploader_2/app.py
from flask import Flask, render_template, render_template_string, request, redirect, url_for, session, send_from_directory import sqlite3 import os import uuid import re from waitress import serve app = Flask(__name__) app.secret_key = os.environ['secret_key'] app.config['TEMPLATES_AUTO_RELOAD'] = True con = sqlite3.connect("user.db", check_same_thread=False) con.set_trace_callback(print) cur = con.cursor() UPLOAD_FOLDER = './templates/static' ALLOWED_EXTENSIONS = {'gif', 'jpg', 'jpeg', 'png', 'svg'} def get_fileext(filename): fileext = filename.rsplit('.', 1)[1].lower() if '.' in filename and filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS: return fileext return None @app.route('/upload', methods=['GET', 'POST']) def upload_file(): if 'usersess' in session: if request.method == 'POST': # check if the post request has the file part if 'file' not in request.files: return render_template('profile.html', error='No file selected') file = request.files['file'] # If the user does not select a file, the browser submits an empty file without a filename. if file.filename == '': return render_template('profile.html', error='No file selected') fileext = get_fileext(file.filename) file.seek(0, 2) # seeks the end of the file filesize = file.tell() # tell at which byte we are file.seek(0, 0) # go back to the beginning of the file if fileext and filesize < 1*1024*1024: filename = session["usersess"]+"."+fileext if session['filename']: os.remove(UPLOAD_FOLDER+"/"+session['filename']) file.save(os.path.join(UPLOAD_FOLDER, filename)) session['filename'] = filename return redirect(url_for('profile')) return redirect(url_for('profile')) else: return(redirect(url_for('login'))) @app.route('/', methods=['GET', 'POST']) def login(): if request.method == 'POST': username = request.form['username'] password = request.form['password'] pattern = r'[^a-zA-Z0-9{_}]' if re.search(pattern, username) or re.search(pattern, password): return render_template('login.html', error='Sus input detected!') query = f'SELECT * FROM users WHERE dXNlcm5hbWVpbmJhc2U2NA = "{username}" AND cGFzc3dvcmRpbmJhc2U2NA = "{password}";' try: if cur.execute(query).fetchone(): session['usersess'] = str(uuid.uuid4()) session['filename'] = None return redirect(url_for('profile')) else: raise Exception('Invalid Credentials. Please try again.') except: error = 'Invalid Credentials. Please try again.' return render_template('login.html', error=error) else: return render_template('login.html') @app.route('/profile') def profile(): if 'usersess' in session: filename = session['filename'] if not filename: return render_template('profile.html') else: return render_template('profile.html', file_link="./uploads/"+filename) else: return redirect(url_for('login')) @app.route('/uploads/<path:path>') def viewfile(path): if session['filename'] == path: try: return render_template('static'+'/'+path) except: return send_from_directory(UPLOAD_FOLDER, path) else: return redirect(url_for('profile')) if __name__ == '__main__': serve(app, host='0.0.0.0', port=5000)
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/SEETF/2023/web/file_uploader_1/app.py
ctfs/SEETF/2023/web/file_uploader_1/app.py
from flask import Flask, render_template, render_template_string, request, redirect, url_for, session, send_from_directory import os import uuid import re import sys from waitress import serve app = Flask(__name__) app.secret_key = os.environ['secret_key'] UPLOAD_FOLDER = './static' ALLOWED_EXTENSIONS = {'pdf', 'png', 'jpg', 'jpeg', 'gif'} def get_fileext(filename): fileext = filename.rsplit('.', 1)[1].lower() if '.' in filename and filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS: return fileext return None @app.route('/upload', methods=['GET', 'POST']) def upload_file(): if request.method != 'POST': return redirect(url_for('profile')) # check if the post request has the file part if 'file' not in request.files: return redirect(url_for('profile')) file = request.files['file'] # If the user does not select a file, the browser submits an empty file without a filename. if file.filename == '': return redirect(url_for('profile')) fileext = get_fileext(file.filename) file.seek(0, 2) # seeks the end of the file filesize = file.tell() # tell at which byte we are file.seek(0, 0) # go back to the beginning of the file if fileext and filesize < 10*1024*1024: if session['ext'] and os.path.exists(os.path.join(UPLOAD_FOLDER, session['uuid']+"."+session['ext'])): os.remove(os.path.join(UPLOAD_FOLDER, session['uuid']+"."+session['ext'])) session['ext'] = fileext filename = session['uuid']+"."+session['ext'] file.save(os.path.join(UPLOAD_FOLDER, filename)) return redirect(url_for('profile')) else: template = f""" {file.filename} is not valid because it is too big or has the wrong extension """ l1 = ['+', '{{', '}}', '[2]', 'flask', 'os','config', 'subprocess', 'debug', 'read', 'write', 'exec', 'popen', 'import', 'request', '|', 'join', 'attr', 'globals', '\\'] l2 = ['aa-exec', 'agetty', 'alpine', 'ansible-playbook', 'ansible-test', 'aoss', 'apt', 'apt-get', 'aria2c', 'arj', 'arp', 'ascii-xfr', 'ascii85', 'ash', 'aspell', 'atobm', 'awk', 'aws', 'base', 'base32', 'base58', 'base64', 'basenc', 'basez', 'bash', 'batcat', 'bconsole', 'bpftrace', 'bridge', 'bundle', 'bundler', 'busctl', 'busybox', 'byebug', 'bzip2', 'c89', 'c99', 'cabal', 'cancel', 'capsh', 'cat', 'cdist', 'certbot', 'check_by_ssh', 'check_cups', 'check_log', 'check_memory', 'check_raid', 'check_ssl_cert', 'check_statusfile', 'chmod', 'choom', 'chown', 'chroot', 'cmp', 'cobc', 'column', 'comm', 'comm ', 'composer', 'cowsay', 'cowthink', 'cpan', 'cpio', 'cpulimit', 'crash', 'crontab', 'csh', 'csplit', 'csvtool', 'cupsfilter', 'curl', 'cut', 'dash', 'date', 'debug', 'debugfs', 'dialog', 'diff', 'dig', 'dir', 'distcc', 'dmesg', 'dmidecode', 'dmsetup', 'dnf', 'docker', 'dos2unix', 'dosbox', 'dotnet', 'dpkg', 'dstat', 'dvips', 'easy_install', 'echo', 'efax', 'elvish', 'emacs', 'env', 'eqn', 'espeak', 'exiftool', 'expand', 'expect', 'facter', 'file', 'find', 'finger', 'fish', 'flock', 'fmt', 'fold', 'fping', 'ftp', 'gawk', 'gcc', 'gcloud', 'gcore', 'gdb', 'gem', 'genie', 'genisoimage', 'ghc', 'ghci', 'gimp', 'ginsh', 'git', 'grc', 'grep', 'gtester', 'gzip', 'head', 'hexdump', 'highlight', 'hping3', 'iconv', 'ifconfig', 'iftop', 'install', 'ionice', 'irb', 'ispell', 'jjs', 'joe', 'join', 'journalctl', 'jrunscript', 'jtag', 'julia', 'knife', 'ksh', 'ksshell', 'ksu', 'kubectl', 'latex', 'latexmk', 'ld.so', 'ldconfig', 'less', 'less ', 'lftp', 'loginctl', 'logsave', 'look', 'ltrace', 'lua', 'lualatex', 'luatex', 'lwp-download', 'lwp-request', 'mail', 'make', 'man', 'mawk', 'more', 'mosquitto', 'mount', 'msfconsole', 'msgattrib', 'msgcat', 'msgconv', 'msgfilter', 'msgmerge', 'msguniq', 'mtr', 'multitime', 'mysql', 'nano', 'nasm', 'nawk', 'ncftp', 'neofetch', 'netstat', 'nft', 'nice', 'nmap', 'node', 'nohup', 'npm', 'nroff', 'nsenter', 'nslookup', 'octave', 'openssl', 'openvpn', 'openvt', 'opkg', 'pandoc', 'paste', 'pax', 'pdb', 'pdflatex', 'pdftex', 'perf', 'perl', 'perlbug', 'pexec', 'php', 'pic', 'pico', 'pidstat', 'ping', 'pip', 'pkexec', 'pkg', 'posh', 'pry', 'psftp', 'psql', 'ptx', 'puppet', 'pwsh', 'rake', 'readelf', 'red', 'redcarpet', 'redis', 'restic', 'rev', 'rlogin', 'rlwrap', 'route', 'rpm', 'rpmdb', 'rpmquery', 'rpmverify', 'rsync', 'rtorrent', 'ruby', 'run-mailcap', 'run-parts', 'rview', 'rvim', 'sash', 'scanmem', 'scp', 'screen', 'script', 'scrot', 'sed', 'service', 'setarch', 'setfacl', 'setlock', 'sftp', 'shuf', 'slsh', 'smbclient', 'snap', 'socat', 'socket', 'soelim', 'softlimit', 'sort', 'split', 'sqlite3', 'sqlmap', 'ssh', 'ssh-agent', 'ssh-keygen', 'ssh-keyscan', 'sshpass', 'start-stop-daemon', 'stdbuf', 'strace', 'strings', 'sysctl', 'systemctl', 'systemd-resolve', 'tac', 'tail', 'tar', 'task', 'taskset', 'tasksh', 'tbl', 'tclsh', 'tcpdump', 'tdbtool', 'tee', 'telnet', 'tex', 'tftp', 'time', 'timedatectl', 'timeout', 'tmate', 'tmux', 'top', 'torify', 'torsocks', 'touch', 'traceroute', 'troff', 'truncate', 'tshark', 'unexpand', 'uniq', 'unshare', 'unzip', 'update-alternatives', 'uudecode', 'uuencode', 'vagrant', 'valgrind', 'view', 'vigr', 'vim', 'vimdiff', 'vipw', 'virsh', 'volatility', 'w3m', 'wall', 'watch', 'wget', 'whiptail', 'whois', 'wireshark', 'wish', 'xargs', 'xdotool', 'xelatex', 'xetex', 'xmodmap', 'xmore', 'xpad', 'xxd', 'yarn', 'yash', 'yelp', 'yum', 'zathura', 'zip', 'zsh', 'zsoelim', 'zypper'] for i in l1: if i in template.lower(): print(template, i, file=sys.stderr) template = "nice try" break matches = re.findall(r"['\"](.*?)['\"]", template) for match in matches: print(match, file=sys.stderr) if not re.match(r'^[a-zA-Z0-9 \/\.\-]+$', match): template = "nice try" break for i in l2: if i in match.lower(): print(i, file=sys.stderr) template = "nice try" break return render_template_string(template) @app.route('/') def profile(): if 'uuid' in session: uuuid = session['uuid'] ext = session['ext'] if not ext: return render_template('profile.html') else: return render_template('profile.html', file_link="./uploads/"+uuuid+"."+ext) else: session['uuid'] = str(uuid.uuid4()) session['ext'] = None return(render_template('profile.html')) if __name__ == '__main__': serve(app, host='0.0.0.0', port=5000)
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/SEETF/2023/web/Throw_your_malware_here/app.py
ctfs/SEETF/2023/web/Throw_your_malware_here/app.py
from typing import Optional import zipfile import random import shutil import string import subprocess from pathlib import Path import pefile from fastapi import FastAPI, HTTPException, UploadFile from fastapi.responses import JSONResponse FILE_CACHE = Path("/app/cache") FLOSS_PATH = Path("/usr/local/bin/floss") app = FastAPI() def get_random_string(length: int = 16) -> str: # choose from all lowercase letter letters = string.ascii_lowercase return "".join(random.choice(letters) for _ in range(length)) @app.on_event("startup") def startup(): # Ensure caches exist if not FILE_CACHE.is_dir(): FILE_CACHE.mkdir() def run_floss(target: Path) -> str: args = [str(target), "--json"] try: pefile.PE(name=str(target)) except pefile.PEFormatError: args.extend(("--only", "static")) output = subprocess.check_output((FLOSS_PATH, *args)) return output.decode() @app.post("/floss") def floss_endpoint(sample: UploadFile, password: Optional[str]) -> JSONResponse: random_path = get_random_string() while (target_path := FILE_CACHE / random_path).exists(): random_path = get_random_string() with target_path.open("wb+") as f: shutil.copyfileobj(sample.file, f) is_zipfile = zipfile.is_zipfile(target_path) if is_zipfile: with zipfile.ZipFile(target_path) as f: # No zip bombs! file_size_sum = sum(data.file_size for data in f.filelist) compressed_size_sum = sum(data.compress_size for data in f.filelist) if (file_size_sum / compressed_size_sum > 10): raise HTTPException(413, "Zip Bomb Detected") zipobjects = f.infolist() if any(zipobject.file_size > 50000 for zipobject in zipobjects): raise HTTPException(418, "I'm a teapot!") files = f.namelist() args = ["unzip"] if password: args.extend(("-P", password)) args.extend((str(target_path), "-d", f"{FILE_CACHE / random_path}-zip")) a = subprocess.run(args) if a.returncode != 0: raise HTTPException(422, "Invalid password!") targets = [FILE_CACHE / f"{random_path}-zip" / file for file in files] else: targets = [target_path] results = [run_floss(target) for target in targets] return JSONResponse( {target.name: result for target, result in zip(targets, results)} if is_zipfile else results[0] )
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/SEETF/2023/web/PlantUML/server.py
ctfs/SEETF/2023/web/PlantUML/server.py
import requests BASE_URL = "http://plantuml:8080/" url = input(f"URL: {BASE_URL}") requests.get(f"{BASE_URL}{url}")
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/SEETF/2022/pwn/wayyang/wayyang.py
ctfs/SEETF/2022/pwn/wayyang/wayyang.py
#!/usr/local/bin/python import os FLAG_FILE = "FLAG" def get_input() -> int: print(''' ,#####, #_ _# |a` `a| | u | ________________________ \ = / | WAYYANG | |\___/| < TERMINAL v1.0 | ___ ____/: :\____ ___ |________________________| .' `.-===-\ /-===-.` '. / .-"""""-.-"""""-. \ /' =:= '\ .' ' .: o -=:=- o :. ' `. (.' /'. '-.....-'-.....-' .'\ '.) /' ._/ ". --:-- ." \_. '\ | .'| ". ---:--- ." |'. | | : | | ---:--- | | : | \ : | |_____._____| | : / / ( |----|------| ) \ /... .| | | | |. ...\ |::::/'' jgs / | \ ''\::::| '"""" /' .L_ `\ """"' /'-.,__/` `\__..-'\ ; / \ ; : / \ | | / \. | |`../ | ,/ ( _ ) | _) | | | | |___| \___| :===| |==| \ / |__| /\/\ /"""`8.__ |oo| \__.//___) |==| \__/''') print("What would you like to do today?") print("1. Weather") print("2. Time") print("3. Tiktok of the day") print("4. Read straits times") print("5. Get flag") print("6. Exit") choice = int(input(">> ")) return choice if __name__ == '__main__': choice = get_input() if choice == 1: print("CLEAR SKIES FOR HANDSOME MEN") elif choice == 2: print("IT'S ALWAYS SEXY TIME") elif choice == 3: print("https://www.tiktok.com/@benawad/video/7039054021797252399") elif choice == 4: filename = input("which news article you want babe :) ") not_allowed = [char for char in FLAG_FILE] for char in filename: if char in not_allowed: print("NICE TRY. WAYYANG SEE YOU!!!!!") os.system(f"cat news.txt") exit() try: os.system(f"cat {eval(filename)}") except: pass elif choice == 5: print("NOT READY YET. MAYBE AFTER CTF????")
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/SEETF/2022/crypto/neutrality/neutrality.py
ctfs/SEETF/2022/crypto/neutrality/neutrality.py
from secrets import randbits from Crypto.Util.number import bytes_to_long # get a one-time-pad in which exactly half the bits are set def get_xorpad(bitlength): xorpad = randbits(bitlength) return xorpad if bin(xorpad).count('1') == bitlength // 2 else get_xorpad(bitlength) def leak_encrypted_flag(): from secret import flag return bytes_to_long(flag.encode()) ^ get_xorpad(len(flag) * 8) # I managed to leak the encrypted flag a few times if __name__ == '__main__': for _ in range(200): print(leak_encrypted_flag())
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/SEETF/2022/crypto/probability/probability.py
ctfs/SEETF/2022/crypto/probability/probability.py
import random def play_round(): p1 = 0 while True: drawn = random.random() p1 += drawn print(f'You draw a [{drawn}]. (p1 = {p1})') if p1 >= 1: print('You have gone bust. Dealer wins!') return 1 if input('Do you want to hit or stand? ').lower() in ['s', 'stand']: break p2 = 0 while p2 <= p1: drawn = random.random() p2 += drawn print(f'Dealer draws a [{drawn}]. (p2 = {p2})') if p2 >= 1: print('Dealer has gone bust. You win!') return 0 else: print(f'Dealer has a higher total. Dealer wins!') return 1 def main(): print('================================================================================') print(' Welcome to the SEETF Casino. We will play 1337 rounds of 1337 blackjack. ') print(' You play first, then the dealer. The highest total under 1 wins the round. ') print(' If you win at least 800 rounds, you will be rewarded with a flag. Good luck! ') print('================================================================================') scores = [0, 0] for i in range(1337): print(f'Round {i + 1}:') winner = play_round() scores[winner] += 1 print(f'Score: {scores[0]}-{scores[1]}') print('-' * 80) if scores[0] >= 800: from secret import flag print(f'Here is your flag: {flag}') return print('Better luck next time!') 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/SEETF/2022/crypto/dlp/params.py
ctfs/SEETF/2022/crypto/dlp/params.py
g = 2015396303001729919228156288393303410061051071865788063380037014090425897729493301829934320750474906145633828841231002303814710345847310021499418592443013756285611643590907347178916293244009158428575031862799028094052154358394991651127332451946240293096173870291124070860340181726783938312770776902984900707372260990431246556075600016092089059477730941418801648299639472281439654617735586813602605590782694833777780843600454836827573205623691681680188413206506901196900146133037179659891566121919123865651572846221529209296867123045118161459300419926127703774745299845934528954823427540895502038196976111028912486328751406898819264072534513759550203355683729816898693681598530957059516070392144963879555346340054068363300419156055200023224885976239057690078347855332895813006326276802850246846794881345712131532475682758203622865258340391113591326511997631151930498983881828856729505419696832385136782487636845963055215713049675709476193302048649324036528676389669721155782165296156708163254833584113482968962258924909005164983048344470708848412799522634441776220531830132040782943603340200379221167847540106704126832019797908169656003014470867537389105926856305787044079830826554451843231924185876771606232988706442003467991827686121533791845350245803700543831829500169370690631867978914744376182469845696117314335370128334363076839700937425681875466936633036285042309070905199660569154398849880821117710615660504693882327380971062131553816362286804830872333845538064633117690870721356411191354915419928018832543020466917890022329695624476000191997270646694217801119459666148713901999128660841219224799785134977965763896783292777647781831890663669437269817227258905316583689914561124913960786573437534477866915021945690300165893667445013360119396899913485190453607849687550843663588936232428715000367111456046544024076467949318638893489483068040705152903727328328454880401551834428858220323288748427915171955494358594729469808577378565781215959656982110746730343752120579665668962310270984046306065506741557809542509099240099473351110753074890791988783640493133775318350202615335832405328467271368374915424318325686739703602667566114446785541797624023231082505644445415047271803760625638473416373977010895332865388965873039585354375263517654237514845676532022465847675942929254196325990231971232878508717372663225101001029310445590957490603941938062478450767228300538323152964267878176244538401187237659320575491124563833873281327046957365848262600210899016412928027072284155788146261180924947021067764905768669775105118295213164791074920336090648184195565570122202962365339841731273705812159145336200780833232165655827934549246549048826221948393660238321231065286637637639873313567345564391430229407896139906470906740432842741355372748975589797703333674882389139764981712071054312058305076357614840550677324560457488034509935135097038481348479678094274844537903997185135296860822825509896487540906078486407844339061663399214658213188834265699993704615759548052813383603536678315921242534037551356641859748950823862097430373913207042187986348460270848015831806365657603678301973228107645106132920069910894728026916163801655741079110879112939095401392242717459407375300002940053059636185871882964243089799304033112398276127536409694144424833379992360993658884345369579443862421665872835703773735588777835891940729322648541805870885398441552281514566534916437782364090976593318036304932840694983010581295972056969087274836652086727758867137308854520994399540762127093089543169809427077837109146715814601492684983885537557859850538983108024543398551512439768840349583051523456396057494301487896533588013347497234884687587308802977017329202197095394586879495448187466233784245833371732739241515081119501135636800817611336937579707841553327293699922059477249257799820163942953538839670795302461485311711023667084192735864798401018334445945636980087657043485637180389674301734419819935530405263683239428002115462412142998661658358931725292898357896225638065197478304010224497932449242573332777113180036103179125376622183092770493014769622042987308664362718169660220317370473260654859536471392026217505834030051910001591258604302619254746880569677745084332626324610460619679878250060915826880666253469389790855929848872178373191570064988397769147331049597816843509166291709458180085131352327555612229787781999949506637808370569604294294948920870285008457756132778904861475497075901375245482700788679209060650785593427934811918977629638680496498785109016328197263629516907469998981247649106261464729820708494457297984740776769487243311007897607929308981945976266305779144783416149541129382160362359600143345797014303675976148641657468276026442474028772421547086431311151262518248668882403348002860702080329363868873861310508606354351793455177784465074659966086198744873544560745594001918634418078713368513725794649092278877442179874966606081756279673178393760939980736138611904232852830165668249421969106663907122559622133764016434835703019994415627823095161055945406033871038411652043916477424549354089768447121507464626771217235866075275491323754166686175454466530446561499614047711957909805686614075062406729226409579321468303441094761477497338808759003986241119163650469727818516049680074833159035125272891544302357749451134095922058669778219419915295680101821803586127249647877164589335664745776656915967375036210597520026247704398137181383531541551320044640439359347596874818757897823360207478567645945520021278389755131491699445615357760551028530970804320019319049552554431429942904871421107534638360510520588361786481824168607943561141497173414621166645597768809118016604438805321591005318869436551957978897746017468624237798438756988488050840746316420592214643947170624732210340041544819512432228329681249009644682917125209192059049167626627022584640787710833878166924490790653580011997052768071598839559807833183086337837779614168659386409804622250471466259335146561489927495474302148734372721526090220641689040636271667735441058631094540027195726813561316314338627236355976920113549817964041897449883404772742605309405988436612275345060963285066341523531568882501623794074541805085243066662697390588802475789319256227845840710671255486474260823463428206848492412895679772262605530262623193773079077418162951751371203453999416191843292737448345197628392556793987099959929049482558550949011910984684892735771203216310695724935544215183085635053653452307838213041852615276821164681514239625346846465734131251268173343621427921222174792329776227383142720718639977822282091778636856499110733396279081850687070675268323453176403515599444182512004883596132122427910511689240974476229993414939654665805534530333074089475910240067169652862917642106188953029246822175529081039458239565433197129967882091306992667879638493112381751345254359377933870254556621254780151918830783134894028448817702597623369044571623491484658633387477592830702757865570350460578115676735751883467594658485901339025155891428882164712823835586606929253865005428718643843380744898722603331158560534127675239701527755603769012249501144437231141706097507047399266150836496297515646972888688228550570679578704423636608810481992243968256916695812924744864498161925329327054367821601607526716467518168900743196894781940239450403301764718390512668255025968124221371284747999827674411800717734062270930985774815657558046704927648091035270293586891700263356903694660125802974127261017965918917815237729747583812694398545618241 gm = 27119606681824995256527987265529024067710654631894351185958774717516460477667815018266405648998381221658822740064226744856698327648212406379730546719515641715155807273214381619894036510768564682733516340944533658984805729269461251839368948257177664473144329811342687747146910280201874840432336228010607991271700165072094711208391327901606793572060694747708731089059220935255425668164307525212490481326553618209273900808904676294826765248930158579318802701844136726420912785476658642967467118403350541033857507608658939376840053935315649844988485257111636700636315176846979089742723396751799790255924062847955722557500206953626670634981337019864708243926265581152327472504985887826574659862137906638388105528341539860094227775661899324205929939775867367356557989771384368260738422118727315731750100772871443549044311420183275115655197792712418697554627819430767503818746399871781530794677476716591107520751509124661993265096538069731098884368645286945675506910769027328227901385271922725709387260464019054890084063201722195150992522167440259916038660030855763279903564776922566894552394386571387707540599159911356630623611867155018562039552215214372892765121932935539018949519193505552433431785023833791304305738913921867741225757792841970787325138757080661836933191103916792087550055834684279318961999930411503330599613897947971820053688739682600302815364270080902157234682766878070330799909930007453997522098533507560365584305031760275399925948013336387029592405042221584188113290942704014105972295609403881994709420848904003889582239366256649412676954277976306246446462091419196873592642745720712938598775685608175087883893205452558268517554239226282601254042786748903947971835733907960897102906899786028605106535705155202069861980707292285757402224878079357578720689978707041797217008519262771793988340709170182881333118499881752348312001439299833976635636877447907572973433181871131565768803176652159825703246426538682019070878249462094065184208615779918742113973076311411354662891924406001034320619076810183539377137334520616889559276151573047763204815409589204997350723756403658236265106028820057015300324676417757555361454592323438434812496417103219399962119953303185017988733340476505815413063350326614815114350307755829497960466963104544326907126585085442817222019154256903173175102165594314156583972948995563490414235103058479102605487123737377372084941334605936773203811832488754136319005599682449955481854374872190526677934900185515387054829555904938958185722193954934617740415113417245718502634447404605558909395339851770452624948269489592888938413519504868030443184557188121475079673502302025886201180788759871604092184466644047760615211933939232421645266995034755575250530389145459765947480632123960601454062022399819871661044974442699451188572198455703876938429967149254866647586178785756577762411883766811794422442732958085973354831136045633087884634386597510713719026662472736016731654996794084509013305271291375092746820601015128165735225780168848726036344837539595106440724716238256264146962376701392832152061874039491087529296708694846395279770458249447751338808814389743212331823557947678005914223655602065835286797846249944465074996096564636597795672256066744035863685622440084140348899644365503203628573878998660418367429861049757123913044222112394098192521110472189209912444912185548395777028440304524476309567330856209424110312962742242870215546024337020267827825643655705824647738014419937785672696801662006824876258387886919692823717153450851408133771277502337306957591075083848980104669937585317602098307286207262668877037193649729142365232802349537175589100202609468095969253635184885439559829444035504770564406581338654239349288630170464336567140117581431624894621921646908532764213404059102445938490026077198582672869221978752402257380971487335509231109991081693269471781350083637057044476078790077997312022249460411926205361086484128273148223170391633468496477073739447762799634530049235501387062886895512336701431549313097589762120659813120030081980323334736000653197488102135616101535658238857933218723007546890795603455469387302374832330754396396682530878788258250087759810575088563263969519429229483314112816745088071258658948160376709350142034616187188882277007714098177443880080084898586435580399449626497123694019358572280344759181566546578288829980822906375429929868934749689467078484586550515931496829663402885589831958887544680809125286160517260337337230292842158645914769287249151915739568876593163672102944788114342627641153257600286875453261486296675725052756434899914916580497371568105451125753709475800699109815662682064670900794978097169174198710833173997213185263212004247721095291640080772435309140850621085439120451002634585601688198676981239896910447385597522040598803477644248195683373238652069594602217012834113883603490590272718687186210485556005992212628354455636060065958001376674091056253283081296003256773570000127349538510464997744649908648734877628723688737853911844766531520700644555839250714192205197804154468315837069498956478249392846561656376625224798134235783403384065897559139940880449380244679967481359100626385219652111443256241311296288272825851254434301012792756049354108589548316130352263972059386160125607774791541969724458366173652763412098499939555817124367495794453105693126504253291400149672975994307414416625237890434626332257100812304471029263267768786241748276821821100811765599030379673988519722231238950538858949940594196032350432993832000219180845309425875141128212849591651340056975657660396438867651804863507607946539813373300380504138653568853278617267091887554186660385422394348508521672133643442644145705321824034812217857604551978967497655773990035849590143696411502048514285424067132915016612227125610994982704309822571927381016951529671451272068911782050568528394410430063092706361120698799304906815801687035281901171827771913252442638898549100262745110900343529268154996189539606163450294196708325690271239608120494506321460746631791795821839612817226726561633524351767775392622421691212178467821323227028834878713656744215333208862869633786431043700922911137727002045106888543009827505547272937261878730332860241556868950837213791163653318046686179009923810650907018494971646008367395405312158913620295170208491788412196641393194280484026164956367219435906696158089618364469693029419444663964672637565511350200067180315897532161352055934211933695199408655851241147528960527449736895533013771766685326835033675299700811805652572944802540223786995689802313012957044697232194482901627290235970912899953390347907891595388391457451974515111723905823721779860469446928568809357998307245451016013398824723645842744466497757068408443089670029109298521178611864304831760276609141052804447440385964904726777771068552006988295415340973101646233610852691306814733770734107558725248725701229433548012886780502206571583297110012495526885458564264455737758789504749468751853228993451783009307898225308213887053792976678101374923010720463420460995669019588916730271847227138716995573307560740020917338947274990411894832277628526309974961885332978193063278753341058955027111747772569817096265790548897261705903338681545413827627430956985852911733389242924088272381536756366970883413727674386275809533354910646609687468851876335443044910424176747616789755147815569180075163688054780351287446392004785548798627548202253640558999921834451879210206100946221245416356107602000299748813752139180836543279955405582810 n = ([108851989682725349554689669128603992794422584115189365634843610633353350984177, 108494325597901567333847826936626671139511665627933673312771131459657523147659, 82883439953140875605735573696794554944065142381374052670778352032916049186817, 115489246044591845680641785786093475992483832086244363115929997874127264343253, 102183814270580135669127449788686760733338404261191675852191850563872719446249, 64040200332870499924825635753624592983233758350051374640202619776008376616789, 115670438971363168203297539488966519963167896268650777474696688742368137533297, 100781718687711859424723316245842771953544543896251167915978884326075043842747, 92824772089115490491542606661230907041925997375626295551286023663151927544297, 72769819859505635259382985450219970417533109019550269256343044124450921361541, 87085572195299466548808947084231958634819010426091761358697427184638180542951, 99152078787413750212103754970232336911268489654375094579004387360383186080771, 71041718108336498944061889389060216957226387363141774431333546891579295631037, 96481285854246585504814138990212517393942392293773296290529545079440525298043, 70075973413540138610070176747956784536801020982722937176752512072899432461879, 94764449949399565607378619612250283206646950163004989633901533278105802439179], [3, 3, 9, 8, 5, 9, 8, 4, 3, 10, 3, 5, 4, 10, 4, 8])
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/SEETF/2022/crypto/dlp/dlp.py
ctfs/SEETF/2022/crypto/dlp/dlp.py
from Crypto.Util.number import getPrime from random import randint from math import gcd from functools import reduce from hashlib import sha256 from typing import List, Tuple def product(l: List[int]) -> int: return reduce(lambda a, b: a*b, l) def gen_params() -> Tuple[int, Tuple[List[int], List[int]]]: while True: primes = [getPrime(256) for _ in range(16)] power = [randint(1, 10) for _ in primes] n = product(p**w for p, w in zip(primes, power)) g = randint(0, n-1) if gcd(g, n) != 1: continue if any(pow(g, p-1, p**w) == 1 for p, w in zip(primes, power)): continue g = pow(g, product(p-1 for p in primes), n) return g, (primes, power) g, (primes, power) = gen_params() n = product(p**w for p, w in zip(primes, power)) m = randint(0, product(p**(w-1) for p, w in zip(primes, power)) - 1) gm = pow(g, m, n) open("params.py", "w").write("\n".join([ f"g = {g}", f"gm = {gm}", f"n = {(primes, power)}" ])) print("SEE{%s}" % sha256(m.to_bytes((m.bit_length()+7)//8, "little")).hexdigest())
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/SEETF/2022/crypto/modifiability/modifiability.py
ctfs/SEETF/2022/crypto/modifiability/modifiability.py
from Crypto.Cipher import AES import os key = os.urandom(16) iv = os.urandom(16) modes = { 'CBC': lambda:AES.new(key, AES.MODE_CBC, iv=iv), 'CFB': lambda:AES.new(key, AES.MODE_CFB, iv=iv), 'OFB': lambda:AES.new(key, AES.MODE_OFB, iv=iv), 'CTR': lambda:AES.new(key, AES.MODE_CTR, nonce=b'', initial_value=iv), 'EAX': lambda:AES.new(key, AES.MODE_EAX, nonce=iv), 'GCM': lambda:AES.new(key, AES.MODE_GCM, nonce=iv), } print(r'''>>>>>> The Great TransMODEifier <<<<<< *TRIAL VERSION*: Limited to three uses ______ _.'______`._ .'.-' `-.`. /,' GCM CBC `.\ // / \\ ========;; / ::======== || EAX----() CFB || ========:: ;;======== \\ // \`. CTR OFB ,'/ `.`-.______.-'.' `-.______.-' Usage: inputmode outputmode ciphertext''') for i in ['1st','2nd','3rd']: try: inputmode, outputmode, ciphertext = input(f'{i} use: ').split() plaintext = modes[inputmode]().decrypt(bytes.fromhex(ciphertext)) if plaintext == b'I Can Has Flag Plz?': from secret import flag plaintext = flag.encode() print(modes[outputmode]().encrypt(plaintext).hex()) except Exception as e: print(repr(e)) print('Goodbye!')
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/SEETF/2022/crypto/rc4/rc4.py
ctfs/SEETF/2022/crypto/rc4/rc4.py
import os def rc4(key:bytes, pt:bytes) -> bytes: s = [*range(0x100)] j = 0 for i in range(len(key)): j = (j + s[i] + key[i]) & 0xff s[i], s[j] = s[j], s[i] i = 0 j = 0 ret = [] for c in pt: i = (i + 1) & 0xff j = (j + s[i]) & 0xff s[i], s[j] = s[j], s[i] k = s[(s[i] + s[j]) & 0xff] ret.append(k^c) return bytes(ret) def gen_rand_key(): return os.urandom(96).hex().encode() if __name__ == "__main__": from secret import secret pos_flag = b"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890_" assert all(f in pos_flag for f in secret) ct = b"".join(rc4(gen_rand_key(), secret) for _ in range(0x100000)) open("ct", "wb").write(ct) print(f"Flag: SEE{{{secret.decode()}}}")
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/SEETF/2022/crypto/close_enough/encrypt.py
ctfs/SEETF/2022/crypto/close_enough/encrypt.py
from Crypto.Util.number import getPrime, bytes_to_long from Crypto.PublicKey import RSA from secret import flag, getNextPrime p = getPrime(1024) q = getNextPrime(p) n = p * q e = 65537 key = RSA.construct((n, e)).export_key().decode() with open("key", "w") as f: f.write(key) m = bytes_to_long(flag.encode()) c = pow(m, e, n) print(f"c = {c}")
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/SEETF/2022/crypto/lost_modulus/encrypt.py
ctfs/SEETF/2022/crypto/lost_modulus/encrypt.py
from Crypto.Util.number import getPrime, long_to_bytes, bytes_to_long with open("flag.txt", "rb") as f: FLAG = f.read() n = bytes_to_long(FLAG) #make sure i have a big modulus while n.bit_length() < 2048: n *= n def encrypt(m1, m2): e = getPrime(256) assert m1.bit_length() >= 1600 and long_to_bytes(m1).startswith(b"SEE{"), 'first message must be at least 1600 bits and begin with "SEE{"' assert 500 <= m2.bit_length() <= 600, 'second message must be within 500 to 600 bits' return pow(m1, e, n), pow(m2, e, n) def main(): try: m1 = int(input("Message 1 (as integer) : ").strip()) m2 = int(input("Message 2 (as integer) : ").strip()) c1, c2 = encrypt(m1, m2) print(f"\nCiphers: \n{[c1,c2]}") except Exception as e: print(e) 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/SEETF/2022/crypto/the_true_ecc/ecc.py
ctfs/SEETF/2022/crypto/the_true_ecc/ecc.py
# python ecc.py > out.py from random import randint from os import urandom from Crypto.Cipher import AES from Crypto.Util.Padding import pad, unpad from hashlib import sha1 from typing import Tuple class Ellipse: """Represents the curve x^2 + ay^2 = 1 mod p""" def __init__(self, a: int, p: int): self.a = a self.p = p def __repr__(self) -> str: return f"x^2 + {self.a}y^2 = 1 mod {self.p}" def __eq__(self, other: 'Ellipse') -> bool: return self.a == other.a and self.p == other.p def is_on_curve(self, pt: 'Point') -> bool: x, y = pt.x, pt.y a, p = self.a, self.p return (x*x + a * y*y) % p == 1 class Point: """Represents a point on curve""" def __init__(self, curve: Ellipse, x: int, y: int): self.x = x self.y = y self.curve = curve assert self.curve.is_on_curve(self) def __repr__(self) -> str: return f"({self.x}, {self.y})" def __add__(self, other: 'Point') -> 'Point': x, y = self.x, self.y w, z = other.x, other.y a, p = self.curve.a, self.curve.p nx = (x*w - a*y*z) % p ny = (x*z + y*w) % p return Point(self.curve, nx, ny) def __mul__(self, n: int) -> 'Point': assert n > 0 Q = Point(self.curve, 1, 0) while n > 0: if n & 1 == 1: Q += self self += self n = n//2 return Q def __eq__(self, other: 'Point') -> bool: return self.x == other.x and self.y == other.y def gen_secret(G: Point) -> Tuple[Point, int]: priv = randint(1, p) pub = G*priv return pub, priv def encrypt(shared: Point, pt: bytes) -> bytes: key = sha1(str(shared).encode()).digest()[:16] iv = urandom(16) cipher = AES.new(key, AES.MODE_CBC, iv) ct = cipher.encrypt(pad(pt, 16)) return iv + ct def decrypt(shared: Point, ct: bytes) -> bytes: iv, ct = ct[:16], ct[16:] key = sha1(str(shared).encode()).digest()[:16] cipher = AES.new(key, AES.MODE_CBC, iv) pt = cipher.decrypt(ct) return unpad(pt, 16) a, p = 376014, (1 << 521) - 1 curve = Ellipse(a, p) gx = 0x1bcfc82fca1e29598bd932fc4b8c573265e055795ba7d68ca3985a78bb57237b9ca042ab545a66b352655a10b4f60785ba308b060d9b7df2a651ca94eeb63b86fdb gy = 0xca00d73e3d1570e6c63b506520c4fcc0151130a7f655b0d15ae3227423f304e1f7ffa73198f306d67a24c142b23f72adac5f166da5df68b669bbfda9fb4ef15f8e G = Point(curve, gx, gy) if __name__ == "__main__": from flag import flag alice_pub, alice_priv = gen_secret(G) blake_pub, blake_priv = gen_secret(G) shared = alice_pub * blake_priv ct = encrypt(shared, flag) assert shared == blake_pub * alice_priv assert decrypt(shared, ct) == flag print("alice_pub =", alice_pub) print("blake_pub =", blake_pub) print("ct =", ct)
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/SEETF/2022/crypto/the_true_ecc/out.py
ctfs/SEETF/2022/crypto/the_true_ecc/out.py
alice_pub = (2138196312148079184382240325330500803425686967483863166176111074666553873369606997586883533252879522314508512610120185663459330505669976143538280185135503158, 1350098408534349199229781714086607605984656432458083815306756044307591092126215092360795039519565477039721903019874871683998662788499599535946383133093677646) blake_pub = (4568773897927114993549462717422746966489956811871132275386853917467440322628373530720948282919382453518184702625364310911519327021756484938266990998628406420, 3649097172525610846241260554130988388479998230434661435854337888813320693155483292808012277418005770847521067027991154263171652473498536483631820529350606213) ct = b'q\xfa\xf2\xe5\xe3\xba.H\xa5\x07az\xc0;\xc4%\xdf\xfe\xa0MI>o8\x96M\xb0\xfe]\xb2\xfdi\x8e\x9e\xea\x9f\xca\x98\xf9\x95\xe6&\x1fB\xd5\x0b\xf2\xeb\xac\x18\x82\xdcu\xd5\xd5\x8e<\xb3\xe4\x85e\xddX\xca0;\xe2G\xef7\\uM\x8d0A\xde+\x9fu'
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/SEETF/2022/crypto/universality/univeRSAlity.py
ctfs/SEETF/2022/crypto/universality/univeRSAlity.py
import math, json from secrets import token_urlsafe from Crypto.Util.number import isPrime, bytes_to_long, long_to_bytes def main(): try: # create token token = token_urlsafe(8) js = json.dumps({'token': token}) # select primes print(f'Welcome to the RSA testing service. Your token is "{token}".') print('Please give me 128-bit primes p and q:') p = int(input('p=')) assert isPrime(p) and p.bit_length() == 128, 'p must be a 128-bit prime' assert str(float(math.pi)) in str(float(p)), 'p does not look like a certain universal constant' q = int(input('q=')) assert isPrime(q) and q.bit_length() == 128, 'q must be a 128-bit prime' assert str(float(math.e)) in str(float(q)), 'q does not look like a certain universal constant' # encode print('We will use e=65537 because it is good practice.') e = 65537 m = bytes_to_long(js.encode()) c = pow(m, e, p * q) # decode print('Now what should the corresponding value of d be?') d = int(input('d=')) m = pow(c, d, p * q) # interpret as json js = json.loads(long_to_bytes(m).decode()) assert js['token'] == token, 'Invalid token!' print('RSA test passed!') if 'flag' in js: from secret import flag print(flag) except Exception as e: print(e) 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/SEETF/2022/web/ssrf/app.py
ctfs/SEETF/2022/web/ssrf/app.py
from flask import Flask, request, render_template import os import advocate import requests app = Flask(__name__) @app.route('/', methods=['GET', 'POST']) def index(): if request.method == 'POST': url = request.form['url'] # Prevent SSRF try: advocate.get(url) except: return render_template('index.html', error=f"The URL you entered is dangerous and not allowed.") r = requests.get(url) return render_template('index.html', result=r.text) return render_template('index.html') @app.route('/flag') def flag(): if request.remote_addr == '127.0.0.1': return render_template('flag.html', FLAG=os.environ.get("FLAG")) else: return render_template('forbidden.html'), 403 if __name__ == '__main__': app.run(host="0.0.0.0", port=80, threaded=True)
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/SEETF/2022/web/charlottes_web/app/app.py
ctfs/SEETF/2022/web/charlottes_web/app/app.py
from flask import Flask, request from flask_httpauth import HTTPBasicAuth import os app = Flask(__name__) auth = HTTPBasicAuth() users = {'admin': os.environ.get('SECRET')} @auth.verify_password def verify_password(username, password): if username in users and password == users.get(username): return username @app.route('/') @auth.login_required def index(): if request.headers.get("TOKEN") == os.environ.get("TOKEN"): return os.environ.get("FLAG") return "Flag is only available through our Chrome extension." @app.after_request def add_header(response): response.headers['Access-Control-Allow-Origin'] = request.headers.get("Origin") response.headers['Access-Control-Allow-Headers'] = 'Token, Authorization' response.headers['Access-Control-Allow-Credentials'] = 'true' return response
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/SEETF/2022/web/the_pigeon_files/app/app.py
ctfs/SEETF/2022/web/the_pigeon_files/app/app.py
from flask import Flask, render_template, request app = Flask(__name__) @app.route('/') def index(): return render_template('index.html') 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/SEETF/2022/web/xspwn/app/app.py
ctfs/SEETF/2022/web/xspwn/app/app.py
from flask import Flask, render_template, request import socket import os app = Flask(__name__) admin_ip = socket.gethostbyname("admin") @app.route('/') def index(): return render_template('index.html') @app.route('/flag') def flag(): if request.remote_addr == admin_ip: return os.environ["FLAG"] else: return "You are not admin!" 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/SEETF/2022/web/username_generator/app/app.py
ctfs/SEETF/2022/web/username_generator/app/app.py
from flask import Flask, render_template, request import socket import os app = Flask(__name__) admin_ip = socket.gethostbyname("admin") @app.route('/') def index(): return render_template('index.html') @app.route('/flag') def flag(): if request.remote_addr == admin_ip: return os.environ["FLAG"] else: return "You are not admin!" 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/SEETF/2022/web/flagportal/backend/server.py
ctfs/SEETF/2022/web/flagportal/backend/server.py
from waitress import serve from flask import Flask, request import os, requests app = Flask(__name__) @app.route('/') def index(): return 'Hello World!' @app.route('/flag-count') def flag_count(): return '2' @app.route('/flag-plz', methods=['POST']) def flag(): if request.headers.get('ADMIN_KEY') == os.environ['ADMIN_KEY']: if 'target' not in request.form: return 'Missing URL' requests.post(request.form['target'], data={ 'flag': os.environ['SECOND_FLAG'], 'congrats': 'Thanks for playing!' }) return 'OK, flag has been securely sent!' else: return 'Access denied' @app.route('/forbidden') def forbidden(): return 'Forbidden', 403 serve(app, host='0.0.0.0', port=80)
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/HackTheVote/2020/pycry/run.py
ctfs/HackTheVote/2020/pycry/run.py
print "+===================================+" print "+ Primality Tester Lite v0.17 +" print "+===================================+" print "" def primtest(): print "What number would you like to test?" num = raw_input() try: num = long(num) except: print "invalid number..." exit(1) print "Enter a false positive probability (empty line for default):" prob = raw_input() if len(prob) > 0: try: prob = float(prob) except: print "invalid number..." exit(1) else: prob = 1e-06 print "If you would like to enter random byte strings to be used for primality testing, enter the number here (empty line for default PRNG):" numrands = raw_input() randfunc = None if len(numrands) > 0: try: numrands = long(numrands) except: print "invalid number..." exit(1) if numrands > 1024: print "That's a bit much don't you think? Upgrade to the PRO version to control more pseudorandomness" exit(1) print "Enter byte strings hex encoded one line at a time" rands = [] for i in xrange(numrands): rand = raw_input() try: rand = rand.decode('hex') except: print "invalid hex string..." exit(1) rands.append(rand) def prng(nb): if len(rands) == 0: return None return rands.pop(0) randfunc = prng print "Ok, all set. Testing for primality..." from Crypto.Util.number import isPrime try: res = isPrime(num, prob, randfunc) print "That number is%s prime"%("" if res else "n't") except: print "Hmmm.... sorry, that's a bad number. Please choose your numbers more carefully." while True: primtest() print "Test another number? (y/n):" resp = raw_input() if len(resp) == 0 or resp[0] == 'n': print "Thank you for using our service" break
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/HackTheVote/2020/snap_election/server/server.py
ctfs/HackTheVote/2020/snap_election/server/server.py
#!/usr/bin/env python3 import os import json import tempfile import subprocess from flask import Flask, request, abort, jsonify, send_file from werkzeug.utils import secure_filename DEVNULL = open(os.devnull,'w') app = Flask(__name__) # Set max file size app.config['MAX_CONTENT_LENGTH'] = 8 * 1024 * 1024 # Create tmp dir to hold uploads if not os.path.exists('tmp'): os.mkdir('tmp') @app.route('/') def index(): return send_file('index.html') @app.route('/tally',methods=['GET', 'POST']) def upload(): if 'file' not in request.files: return jsonify(error="Missing CSV File") file = request.files['file'] if file.filename == '': return jsonify(error="Missing CSV File") # Copy file into a tmp dir tmpdir = tempfile.TemporaryDirectory(dir=os.path.join(os.getcwd(), 'tmp')) filename = secure_filename(file.filename) path = os.path.join(tmpdir.name, filename) file.save(path) # Run counter program ballot_path = os.path.join(os.getcwd(), 'ballot.json') p = subprocess.Popen( ['timeout','5','htv-vote-counter',ballot_path,filename], cwd=tmpdir.name, stderr=DEVNULL, stdout=subprocess.PIPE ) # Validate json output try: res = json.loads(p.communicate()[0]) except: return jsonify(error="Could not parse JSON output") tmpdir.cleanup() return jsonify(res) if __name__ == '__main__': app.run(debug=True, host='0.0.0.0')
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/HackTheVote/2020/fileshare/cleaner.py
ctfs/HackTheVote/2020/fileshare/cleaner.py
import os, time, shutil def get_used_dirs(): pids = [p for p in os.listdir("/proc") if p.isnumeric()] res = set() for p in pids: try: path = os.path.realpath("/proc/%s/cwd"%p) if path.startswith("/tmp/fileshare."): res.add(path) except: pass return res while True: try: dirs = ["/tmp/"+d for d in os.listdir("/tmp") if d.startswith("fileshare.")] used = get_used_dirs() for d in dirs: if d not in used: try: os.system("umount %s/proc"%d) shutil.rmtree(d) except: pass except: pass time.sleep(5)
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/Defenit/2020/input_test_driver/pow_check.py
ctfs/Defenit/2020/input_test_driver/pow_check.py
#!/usr/bin/env python3 import os import random import hashlib def getRand(length=4): table = '0123456789abcdef' return ''.join([random.choice(table) for i in range(length)]) def getPow(): return hashlib.sha256(getRand().encode()).hexdigest()[-6:] def checkPow(inp, out): if hashlib.sha256(inp.encode()).hexdigest()[-6:] == out: return True else: return False def main(): out = getPow() print('pow :', out) inp = input('solution : ') if checkPow(inp, out): os.system('./start.sh') else: print('sorry ^___^'); 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/CyberGrabs/2021/crypto/The_Ancient_Temple/the_ancient_temple.py
ctfs/CyberGrabs/2021/crypto/The_Ancient_Temple/the_ancient_temple.py
M, s, l, C = 7777771, [], 1337, [] n=[] flag = "REDACTED" k = [list(map(int, list(' '.join(bin(ord(i))[2:]).split()))) for i in flag] def num_gen(first, last): o = [[1]] cnt = 1 while cnt <= last: if cnt >= first: yield o[-1][0] row = [o[-1][-1]] for b in o[-1]: row.append(row[-1] + b) cnt += 1 o.append(row) for i in num_gen(7, 13): s.append(i) for i in range(len(s)): ni = ((l*s[i]) % M) n.append(ni) for p in k: C_curr = [] for (x,y) in zip(p, n): C_ = x*y C_curr.append(C_) C += [sum(C_curr)] print(M, s, l, C, n)
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/CyberGrabs/2021/crypto/Not_RSA/Not_RSA1.py
ctfs/CyberGrabs/2021/crypto/Not_RSA/Not_RSA1.py
from math import sqrt import random from Crypto.Util.number import bytes_to_long N = 2433984714450860961589027518159810370561856716063956157321856705975948489337570445957833120668443867975490363019335530343179129689501017626817947777263721 c = 1378297008929492435762470180953416238081302819750327089183697281160938504327642742017058360280755400054663296904328307673692314945545918393502459480987913 a = int(sqrt(N) + 1) b = random.randint(0,9999999999) flag = b"REDACTED" m = bytes_to_long(flag) c = ((a**m)*(b**(a-1)))%((a-1)*(a-1))
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/CyberGrabs/2021/crypto/Old_Monks_Password/Old_Monk_pass.py
ctfs/CyberGrabs/2021/crypto/Old_Monks_Password/Old_Monk_pass.py
enc = b'\x0cYUV\x02\x13\x16\x1a\x01\x04\x05C\x00\twcx|z(((%.)=K%(>' enc1 = b'\x0bPPS\r\x0b\x02\x0f\x12\r\x03_G\t\x08yb}v+--*+*8=W,>' enc2 = b'\x07A[\x06\\\r\x15\t\x04\x07\x18VG]U]@\x02\x08&9&%\' 41".;' import codecs import random class pass_w: x = "hjlgyjgyj10hadanvbwdmkw00OUONBADANKHM;IMMBMZCNihaillm" def encode(self, text, i = -1): if i < 0 or i > len(self.x) + 1: i = random.randint(0, len(self.x) + 1) out = chr(i) for c in text: out += chr(ord(c) ^ ord(self.x[i])) i = (i + 1)%79 return codecs.encode(out) y = pass_w() print(y.encode("REDACTED")) #Enclose password within GrabCON{}
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/CyberGrabs/2022/crypto/asrysae/chall.py
ctfs/CyberGrabs/2022/crypto/asrysae/chall.py
from Crypto.Util.number import * import gmpy2 from secret import flag import binascii p = getPrime(512) q = getPrime(512) e = 65537 m = bytes_to_long(flag) ciphertext = pow(m, e, p*q) ciphertext = long_to_bytes(ciphertext) obj1 = open("ciphertext.txt",'w') obj1.write(f"p={p}\n\n") obj1.write(f"q={q}\n\n") obj1.write(f"ct={ciphertext.hex()}")
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/CyberGrabs/2022/crypto/t0t13nt/source_1.py
ctfs/CyberGrabs/2022/crypto/t0t13nt/source_1.py
from sympy import totient flag = REDACTED def functor(n): val = 0 for j in tqdm(range(1,n+1)): for i in range(1,j+1): val += j//i * totient(i) return val lest = [] for i in flag: lest.append(functor(ord(i)*6969696969)) print(lest)
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/CyberGrabs/2022/crypto/Unbr34k4bl3/source.py
ctfs/CyberGrabs/2022/crypto/Unbr34k4bl3/source.py
from Crypto.Util.number import * from secret import * assert (x>2 and x%2 == 0) assert (isPrime(e1) and isPrime(e2)) def functor(): val1 , val2 = 0,0 for i in range(x+1): val1 += pow(e1,i) for j in range(3): val2 += pow(e2,j) assert (val1 == val2) def keygen(): while True: p,q = [getStrongPrime(1024) for _ in range(2)] if p%4==3 and q%4==3: break r = 2 while True: r = r*x if r.bit_length()>1024 and isPrime(r-1): r = r-1 break return p,q,r functor() p,q,r = keygen() n = p*q*r print(f"p:{p}") print(f"q:{q}") ip = inverse(p,q) iq = inverse(q,p) c1 = pow(bytes_to_long(flag[0:len(flag)//2].encode('utf-8')),e1,n) c2 = pow(bytes_to_long(flag[len(flag)//2:].encode('utf-8')),e2,n) print(f"n:{n}",f"ip:{ip}",f"iq:{iq}",f"c1:{c1}",f"c2:{c2}",sep="\n")
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/WannaGameChampionship/2023/crypto/Among_SUS/utils.py
ctfs/WannaGameChampionship/2023/crypto/Among_SUS/utils.py
from Crypto.Cipher import AES import struct import math class InvalidTagError(Exception): def __init__(self, message="Invalid Authentication Tag"): self.message = message super().__init__(self.message) class MAC: MASK_R = 0x1337fffc0ffffffc0ffffffc0fff1337 MASK_S = 0xffffffffffffffffffffffffffffffff P = 0x7ffffffffffffffffffffffffffffffbb Q = 0x100000000000000000000000000000000 def __init__(self, key: bytes) -> None: if len(key) != 0x20: raise ValueError("[MAC Error]: The key's length must be (in byte)") self.r = int.from_bytes(key[0x00:0x10], byteorder='little') & self.MASK_R self.s = int.from_bytes(key[0x10:0x20], byteorder='little') ^ self.MASK_S def commit(self, message): res = 0 for i in range(0, math.ceil(len(message)/0x10)): res += int.from_bytes(message[i*0x10:(i+1)*0x10], byteorder='little') + self.Q res = (self.r * res) % self.P res = (res + self.s) % self.Q return int.to_bytes(res, length=0x10, byteorder='little') class AEMC: @classmethod def pad(self, data, size): if len(data) % size == 0: return data else: return data + bytes(size - len(data)%size) @classmethod def verify_auth_tag(self, tag_a, tag_b): if len(tag_a) != len(tag_b): return False ok = 0 for x, y in zip(tag_a, tag_b): ok |= x ^ y return ok == 0 @classmethod def generate_mac_key(self, master_key, nonce): cipher = AES.new(key=master_key, mode=AES.MODE_CTR, nonce=nonce) return cipher.encrypt(bytes(0x20)) def __init__(self, master_key) -> None: if len(master_key) != 0x20: raise ValueError("Master key must be 256 bits long") self.master_key = master_key def encrypt(self, plaintext, nonce, associated_data=None): return self.__encrypt( plaintext=plaintext, nonce=nonce, associated_data=associated_data if associated_data is not None else b"" ) def decrypt(self, ciphertext, nonce, associated_data=None): return self.__decrypt( ciphertext_tag=ciphertext, nonce=nonce, associated_data=associated_data if associated_data is not None else b"" ) def __encrypt(self, plaintext, associated_data, nonce): if len(nonce) != 12: raise ValueError("Nonce must be 96 bits long") mac_key = self.generate_mac_key(self.master_key, nonce) ciphertext = AES.new( key=self.master_key, mode=AES.MODE_CTR, nonce=nonce ).encrypt(plaintext=plaintext) mac_data = self.pad(associated_data, 0x10) mac_data += self.pad(ciphertext, 0x10) mac_data += struct.pack('<QQ', len(associated_data), len(ciphertext)) auth_tag = MAC(key=mac_key).commit(message=mac_data) return ciphertext + auth_tag def __decrypt(self, ciphertext_tag, associated_data, nonce): if len(nonce) != 12: raise ValueError("Nonce must be 96 bits long") ciphertext = ciphertext_tag[:-0x10] expected_tag = ciphertext_tag[-0x10:] mac_key = self.generate_mac_key(self.master_key, nonce) # verify auth_tag mac_data = self.pad(associated_data, 0x10) mac_data += self.pad(ciphertext, 0x10) mac_data += struct.pack('<QQ', len(associated_data), len(ciphertext)) calculated_tag = MAC(key=mac_key).commit(message=mac_data) if not self.verify_auth_tag(expected_tag, calculated_tag): raise InvalidTagError("No Hack!") return AES.new( key=self.master_key, mode=AES.MODE_CTR, nonce=nonce ).decrypt(ciphertext=ciphertext)
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/WannaGameChampionship/2023/crypto/Among_SUS/server.py
ctfs/WannaGameChampionship/2023/crypto/Among_SUS/server.py
from cryptography.hazmat.primitives.kdf.hkdf import HKDF from cryptography.hazmat.primitives import hashes from utils import AEMC, InvalidTagError import binascii import secrets import base64 import random import signal import json TIMEOUT = 720 FLAG = open("/flag", "r").read() INFO = b"W3llc0m3 t0 W4nn4G4m3 Ch4mpi0nsh1p 2023" MAX_ROUNDS = 20 ROUND = 1 MAX_TRIES = 14 class AmongSUS: N_PLAYERS = 512 TASKS = [ "Catch Fish" , "Clean Vent" , "Collect Shells" , "Help Critter" , "Chart Course" , "Clear Asteroids" , "Divert Power" , "Hoist Supplies" , "Clean Toilet" , "Collect Vegetables" , "Empty Chute" , "Measure Weather" ] @classmethod def generate_password(self, player: str, salt: bytes): return HKDF( algorithm=hashes.BLAKE2b(digest_size=64), salt=salt, info=INFO, length=32 ).derive(player.encode()) @classmethod def info_task(self, player): task = random.choice(self.TASKS) id = secrets.token_hex(0x10) digest = hashes.Hash(hashes.BLAKE2b(digest_size=64)) digest.update( json.dumps({ "id": id, "player": player, "task": task }).encode() ) return digest.finalize() def __init__(self) -> None: self.salt = secrets.token_bytes(0x0C) self.crewmates = [ f"player_{secrets.token_bytes(0x10).hex()}" for _ in range(self.N_PLAYERS) ] self.imposter = random.choice(self.crewmates) def info_players(self): print("[INFO PLAYERS]") for player in self.crewmates: print(">", player) def generate_task(self): print("[GENERATE TASK]") token = AEMC(master_key=self.generate_password(self.imposter, self.salt)).encrypt( plaintext=self.info_task(random.choice(self.crewmates)), nonce=self.salt, associated_data=INFO ) print("> Task Token:", base64.b64encode(token).decode()) def do_task(self): print("[DO TASK]") try: token = base64.b64decode(input("> Enter Task Token (in base64): ")) task = AEMC(master_key=self.generate_password(self.imposter, self.salt)).decrypt( ciphertext=token, nonce=self.salt, associated_data=INFO ) # print(task) # Nah print("> Doing task...") except (binascii.Error, InvalidTagError): print(f"> Invalid token: Impostorrrr!!!") def report_imposter(self): print("[REPORT IMPOSTER]") return input("> Who? ") == self.imposter if __name__ == "__main__": signal.alarm(TIMEOUT) print(""" β–„β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–„β–„β–„β–„β–ˆβ–ˆβ–ˆβ–„β–„β–„β–„ β–„β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–„ β–ˆβ–ˆβ–ˆβ–„β–„β–„β–„ β–„β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–„ β–„β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆ β–ˆβ–„ β–„β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆ β–„β–ˆβ–ˆβ–€β–€β–€β–ˆβ–ˆβ–ˆβ–€β–€β–€β–ˆβ–ˆβ–„ β–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–€β–€β–€β–ˆβ–ˆβ–„ β–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆ β–ˆβ–€ β–ˆβ–ˆβ–ˆ β–ˆβ–€ β–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆ β–ˆβ–€ β–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆ β–„β–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆ β–€β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆ β–€β–€β–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–„ β–€β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆ β–€β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆ β–„β–ˆ β–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆ β–„β–ˆ β–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆ β–ˆβ–€ β–€β–ˆ β–ˆβ–ˆβ–ˆ β–ˆβ–€ β–€β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–€ β–€β–ˆ β–ˆβ–€ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–€ β–„β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–€ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–€ β–„β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–€ """) print("[!] Welcome to Among SUS game. You need to find the exact impostor, otherwise everyone will be killed...") print(f"[!] There is only one impostor among all {AmongSUS.N_PLAYERS} players") print("[!] Press ENTER to continue...") input("") while True: game = AmongSUS() tries = 0 success = False if ROUND > MAX_ROUNDS: print(f"[*] Congratulation: {FLAG}") exit(0) print(f"\n[*] Round {ROUND}/{MAX_ROUNDS}") print(f"[*] This Game's Token: {game.salt.hex()}") while True: print("\nYour options:") print("1) Info players") print("2) Generate task") print("3) Do task") print("4) Report Imposter") print("5) Quit") choice = input("> ") if choice == '1': game.info_players() elif choice == '2': game.generate_task() elif choice == '3': if tries >= MAX_TRIES: print("[!] Sorry, you've reached your rate limit") continue game.do_task() tries += 1 elif choice == '4': if game.report_imposter(): success = True break elif choice == '5': print("[!] Bye") exit(0) else: print(f"[!] Invalid choice") if success: print("[!] Good!") ROUND += 1 continue else: print("[!] Oops!") break
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/WannaGameChampionship/2023/crypto/ezCurve/chall.py
ctfs/WannaGameChampionship/2023/crypto/ezCurve/chall.py
from sage.all import * from Crypto.Util.number import bytes_to_long from secrets import SystemRandom from secret import flag class Point: def __init__(self, x, y) -> None: self.x = int(x) self.y = int(y) def __str__(self) -> str: return f"({self.x},{self.y})" class Curve: def __init__(self) -> None: self.generate_parameters() def generate_parameters(self) -> None: rng = SystemRandom() self.p = random_prime(2**512-1, False, 2**511) self.k = rng.randint(1, self.p - 1) while True: x = rng.randint(1, self.p - 1) D = (self.k + (1 - self.k)*x**2) % self.p if legendre_symbol(D, self.p) == 1: r = rng.choice(GF(self.p)(D).nth_root(2, all=True)) y = (1 + rng.choice([-1, 1])*r) * inverse_mod(x * (self.k - 1), self.p) % self.p self.G = Point(x, y) break def get_parameters(self): return self.G, self.k, self.p def add(self, P: Point, Q: Point) -> Point: x = ((1 + P.x*P.y + Q.x*Q.y)*inverse_mod(P.x*Q.x, self.p) + (1 + self.k)*P.y*Q.y) % self.p y = (P.y*(inverse_mod(Q.x, self.p) + Q.y) + (inverse_mod(P.x, self.p) + P.y)*Q.y) % self.p # so weirddd :< return Point(inverse_mod(x - y, self.p), y) def mult(self, G: Point, k: int) -> Point: R = Point(1, 0) while k: if k&1: R = self.add(R, G) G = self.add(G, G) k >>= 1 return R curve = Curve() G, k, p = curve.get_parameters() print(f"G = {G}") print(f"k = {k}") print(f"p = {p}") print(f"H = {curve.mult(G, bytes_to_long(flag))}")
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false