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/Codegate/2022/Quals/crypto/nft/nft_web/account/migrations/0001_initial.py
ctfs/Codegate/2022/Quals/crypto/nft/nft_web/account/migrations/0001_initial.py
# Generated by Django 3.2.1 on 2022-02-04 18:05 from django.db import migrations, models class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='User', fields=[ ('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('user_id', models.CharField(max_length=128)), ('user_pw', models.CharField(max_length=128)), ('token', models.CharField(max_length=512)), ('token_key', models.CharField(max_length=512)), ('is_cached', models.BooleanField(default=False)), ], ), ]
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/Codegate/2022/Quals/crypto/nft/nft_web/account/migrations/__init__.py
ctfs/Codegate/2022/Quals/crypto/nft/nft_web/account/migrations/__init__.py
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/Codegate/2022/Quals/web/CAFE/bot.py
ctfs/Codegate/2022/Quals/web/CAFE/bot.py
#!/usr/bin/python3 from selenium import webdriver from selenium.webdriver.chrome.options import Options from webdriver_manager.chrome import ChromeDriverManager import time import sys options = webdriver.ChromeOptions() options.add_argument('--headless') options.add_argument('--disable-logging') options.add_argument('--disable-dev-shm-usage') options.add_argument('--no-sandbox') #options.add_argument("user-agent=Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.132 Safari/537.36") driver = webdriver.Chrome(ChromeDriverManager().install(),options=options) driver.implicitly_wait(3) driver.get('http://3.39.55.38:1929/login') driver.find_element_by_id('id').send_keys('admin') driver.find_element_by_id('pw').send_keys('$MiLEYEN4') driver.find_element_by_id('submit').click() time.sleep(2) driver.get('http://3.39.55.38:1929/read?no=' + str(sys.argv[1])) time.sleep(2) driver.quit()
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/AccessDenied/2022/crypto/reused_key/resused_key.py
ctfs/AccessDenied/2022/crypto/reused_key/resused_key.py
import os flag = "XXXX" some_simple_text = "YYYY" key = os.urandom(43) def encrypt(plain_text): assert len(plain_text) == len(key) ciphertext = bytearray([a ^ b for a, b in zip(plain_text, key)]) return ciphertext.hex() print(encrypt(flag.encode("utf-8"))) print(encrypt(some_simple_text.encode("utf-8"))) # flag 65f32f851cdb20eee875eea5a9a30f826cfd247eb550dcc89d1d4cdf952f5c28ca5f162355567fd262bb96 # encrypted some_simple_text 70f8259330c137d4e873ff9ea6a559ab2dea1a60d943859aa545578395301d28a0741d1e065a24d45cb19f
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/AccessDenied/2022/crypto/MITM-2/AES.py
ctfs/AccessDenied/2022/crypto/MITM-2/AES.py
from Crypto.Cipher import AES from binascii import hexlify, unhexlify from hashlib import md5 import os import signal def get_ciphers(keys, iv1, iv2): return [ AES.new(keys[0], mode=AES.MODE_ECB), AES.new(keys[1], mode=AES.MODE_CBC, iv=iv1), AES.new(keys[2], mode=AES.MODE_CBC, iv=iv2) ] def padding(m): return m + os.urandom(16 - (len(m) % 16)) def encrypt(m, keys, iv1, iv2): m = padding(m) ciphers = get_ciphers(keys, iv1, iv2) c = m for cipher in ciphers: c = cipher.encrypt(c) return c def decrypt(c, keys, iv1, iv2): assert len(c) % 16 == 0 ciphers = get_ciphers(keys, iv1, iv2) m = c for cipher in ciphers[::-1]: m = cipher.decrypt(m) return m
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/AccessDenied/2022/crypto/MITM-2/Bob.py
ctfs/AccessDenied/2022/crypto/MITM-2/Bob.py
from AES import encrypt, decrypt, padding from binascii import hexlify, unhexlify from hashlib import md5 import os # Alice and Bob keys are generated by [md5(os.urandom(3)).digest() for _ in rand] flag = b"XXXXXX" # flag keys = [ b'XXXXXXXXXXXXXXXX', b'XXXXXXXXXXXXXXXX' ] msg = b"thank_you_here_is_remaining_part" g = 41899070570517490692126143234857256603477072005476801644745865627893958675820606802876173648371028044404957307185876963051595214534530501331532626624926034521316281025445575243636197258111995884364277423716373007329751928366973332463469104730271236078593527144954324116802080620822212777139186990364810367977 p = 174807157365465092731323561678522236549173502913317875393564963123330281052524687450754910240009920154525635325209526987433833785499384204819179549544106498491589834195860008906875039418684191252537604123129659746721614402346449135195832955793815709136053198207712511838753919608894095907732099313139446299843 private_key = 0 # Bob private Key def main(): public_key = pow(g, private_key, p) print("> Here is my public key: {}".format(public_key)) key = int(input("> Your public key: ")) if(key == 0 or key == 1 or key == p - 1): print("> Ohhh...... Weak Keys") exit(0) aes_key = md5(unhexlify(hex(pow(key, private_key, p))[2:])).digest() keys.append(aes_key) code = input("> Give me the code(encrypted hex): ") decrypted_code = decrypt(unhexlify(code), keys, b"A"*16, b"B"*16) if(decrypted_code[:32] == flag[:32]): encrypted_msg = encrypt(msg, keys, b"A"*16, b"B"*16) encrypted_flag = encrypt(flag[32:], keys, b"A"*16, b"B"*16) print("> Your output: {} {}".format(hexlify(encrypted_msg), hexlify(encrypted_flag))) else: print("> You have given the wrong code") 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/AccessDenied/2022/crypto/MITM-2/Alice.py
ctfs/AccessDenied/2022/crypto/MITM-2/Alice.py
from AES import encrypt, decrypt, padding from binascii import hexlify, unhexlify from hashlib import md5 import os flag = b"XXXXXX" msg = b"here_is_my_code!" keys = [ b'XXXXXXXXXXXXXXXX', b'XXXXXXXXXXXXXXXX' ] g = 41899070570517490692126143234857256603477072005476801644745865627893958675820606802876173648371028044404957307185876963051595214534530501331532626624926034521316281025445575243636197258111995884364277423716373007329751928366973332463469104730271236078593527144954324116802080620822212777139186990364810367977 p = 174807157365465092731323561678522236549173502913317875393564963123330281052524687450754910240009920154525635325209526987433833785499384204819179549544106498491589834195860008906875039418684191252537604123129659746721614402346449135195832955793815709136053198207712511838753919608894095907732099313139446299843 private_key = 0 # Alice Private Key def main(): public_key = pow(g, private_key, p) print("> Here is my public key: {}".format(public_key)) key = int(input("> Your public key: ")) if(key == 0 or key == 1 or key == p - 1): print("> Ohhh...... Weak Keys") exit(0) aes_key = md5(unhexlify(hex(pow(key, private_key, p))[2:])).digest() keys.append(aes_key) encrypted_msg = encrypt(msg, keys, b"A"*16, b"B"*16) encrypted_flag = encrypt(flag[:32], keys, b"A"*16, b"B"*16) print("> Your output: {} {}".format(hexlify(encrypted_msg), hexlify(encrypted_flag))) if __name__ == '__main__': main()
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/AccessDenied/2022/crypto/Small_key/xor.py
ctfs/AccessDenied/2022/crypto/Small_key/xor.py
import os flag = b"XXXXXX" key = os.urandom(8) cipher_text = b"" for i in range(len(flag)): cipher_text += bytes([flag[i] ^ key[i % 8]]) print(cipher_text.hex()) # flag 763d32726973a23f79373473616ba86a60300e677634f734482a626f6e5ff22e636a327c2f5ff228240123242e6caa23483d6127765fff6d743a61212f38bb
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/AccessDenied/2022/crypto/ECC/chal.py
ctfs/AccessDenied/2022/crypto/ECC/chal.py
import tinyec.ec as ec import tinyec.registry as reg from hashlib import sha256 from random import randint class RNG: def __init__(self, seed): self.state = seed def next(self): self.state = self.state + 1 return self.state def hashInt(msg): h = sha256(msg).digest() return int.from_bytes(h, 'big') def sign(msg): m = hashInt(msg) k = rand.next() R = k * G r = R.x s = pow(k, -1, n) * (m + r * d) % n return (r, s) def verify(msg, sig): r, s = sig m = hashInt(msg) sinv = pow(s, -1, n) u1 = m * sinv % n u2 = r * sinv % n R_ = u1 * G + u2 * Q r_ = R_.x return r_ == r C = reg.get_curve("secp256r1") G = C.g n = C.field.n d = int(open("flag.txt", "rb").read().hex(), 16) Q = d * G rand = RNG(randint(2, n-1)) # Let's sign some msgs m1 = b"crypto means cryptography" m2 = b"may the curve be with you" m3 = b"the annoying fruit equation" sig1 = sign(m1) sig2 = sign(m2) sig3 = sign(m3) assert verify(m1, sig1) assert verify(m2, sig2) assert verify(m3, sig3) open("out.txt", "w").write(f"{sig1 = }\n{sig2 = }\n{sig3 = }")
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/MUST/2023/Quals/rev/a_lot_of_technique/rev.py
ctfs/MUST/2023/Quals/rev/a_lot_of_technique/rev.py
import base64 def encrypt_input(input_str): flag = input_str flag = unknown2(flag, 345345345) flag = unknown1(flag) flag = unknown2(flag, 0) flag = unknown(flag, 18) return flag def check_flag(encrypted_input): return encrypted_input == "HL13Oe5cEdBUwYlKM0hONdROENJsFNvz" def unknown(input_str, something): result = [] for c in input_str: if c.isalpha(): base = ord('A') if c.isupper() else ord('a') offset = (ord(c) - base + something) % 26 if offset < 0: offset += 26 c = chr(base + offset) result.append(c) return ''.join(result) def unknown1(xyz): return xyz[::-1] def unknown2(xyz, integer): return base64.b64encode(xyz.encode()).decode() def main(): user_input = input("Flag: ") encrypted_input = encrypt_input(user_input) if check_flag(encrypted_input): print("Correct flag! Congratulations!") else: print("Incorrect flag! Please try again.") 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/MUST/2023/Quals/rev/King_And_His_Servant/enc.py
ctfs/MUST/2023/Quals/rev/King_And_His_Servant/enc.py
def encrypt(): message = input("Enter the message you would like to encrypt: ").strip() key = input("Enter the key to encrypt with: ").strip() key_int = sum(ord(char) for char in key) encrypted_message = "" for c in message: if c in alphabet: position = alphabet.find(c) new_position = (position + key_int) new_character = alphabet[new_position] encrypted_message += new_character else: encrypted_message += c
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/Pwn2Win/2021/pwn/accessing_the_truth/run.py
ctfs/Pwn2Win/2021/pwn/accessing_the_truth/run.py
#!/usr/bin/python3 -u import random import string import subprocess import tempfile def random_string(n): return ''.join(random.choice(string.ascii_lowercase) for _ in range(n)) def check_pow(bits): r = random_string(10) print(f"hashcash -mb{bits} {r}") solution = input("Solution: \n").strip() if subprocess.call(["hashcash", f"-cdb{bits}", "-r", r, solution], cwd="/tmp", stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL) != 0: raise Exception("Invalid PoW") check_pow(25) fname = tempfile.NamedTemporaryFile().name subprocess.call(["cp", "OVMF.fd", fname]) try: subprocess.call(["chmod", "u+w", fname]) subprocess.call(["qemu-system-x86_64", "-monitor", "/dev/null", "-m", "64M", "-drive", "if=pflash,format=raw,file=" + fname, "-drive", "file=fat:rw:contents,format=raw", "-net", "none", "-nographic"], stderr=subprocess.DEVNULL, timeout=60) except: pass subprocess.call(["rm", "-rf", fname]) print("Bye!")
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/Pwn2Win/2021/crypto/A2S/a2s.py
ctfs/Pwn2Win/2021/crypto/A2S/a2s.py
""" This is a slightly modified version of BoppreH's A2S implementation found at at https://github.com/boppreh/AES Follow the original disclaimer __________________________________ This is an exercise in secure symmetric-key encryption, implemented in pure Python (no external libraries needed). Original AES-128 implementation by Bo Zhu (http://about.bozhu.me) at https://github.com/bozhu/AES-Python . PKCS#7 padding, CBC mode, PKBDF2, HMAC, byte array and string support added by me at https://github.com/boppreh/aes. Other block modes contributed by @righthandabacus. Although this is an exercise, the `encrypt` and `decrypt` functions should provide reasonable security to encrypted messages. """ s_box = ( 0x63, 0x7C, 0x77, 0x7B, 0xF2, 0x6B, 0x6F, 0xC5, 0x30, 0x01, 0x67, 0x2B, 0xFE, 0xD7, 0xAB, 0x76, 0xCA, 0x82, 0xC9, 0x7D, 0xFA, 0x59, 0x47, 0xF0, 0xAD, 0xD4, 0xA2, 0xAF, 0x9C, 0xA4, 0x72, 0xC0, 0xB7, 0xFD, 0x93, 0x26, 0x36, 0x3F, 0xF7, 0xCC, 0x34, 0xA5, 0xE5, 0xF1, 0x71, 0xD8, 0x31, 0x15, 0x04, 0xC7, 0x23, 0xC3, 0x18, 0x96, 0x05, 0x9A, 0x07, 0x12, 0x80, 0xE2, 0xEB, 0x27, 0xB2, 0x75, 0x09, 0x83, 0x2C, 0x1A, 0x1B, 0x6E, 0x5A, 0xA0, 0x52, 0x3B, 0xD6, 0xB3, 0x29, 0xE3, 0x2F, 0x84, 0x53, 0xD1, 0x00, 0xED, 0x20, 0xFC, 0xB1, 0x5B, 0x6A, 0xCB, 0xBE, 0x39, 0x4A, 0x4C, 0x58, 0xCF, 0xD0, 0xEF, 0xAA, 0xFB, 0x43, 0x4D, 0x33, 0x85, 0x45, 0xF9, 0x02, 0x7F, 0x50, 0x3C, 0x9F, 0xA8, 0x51, 0xA3, 0x40, 0x8F, 0x92, 0x9D, 0x38, 0xF5, 0xBC, 0xB6, 0xDA, 0x21, 0x10, 0xFF, 0xF3, 0xD2, 0xCD, 0x0C, 0x13, 0xEC, 0x5F, 0x97, 0x44, 0x17, 0xC4, 0xA7, 0x7E, 0x3D, 0x64, 0x5D, 0x19, 0x73, 0x60, 0x81, 0x4F, 0xDC, 0x22, 0x2A, 0x90, 0x88, 0x46, 0xEE, 0xB8, 0x14, 0xDE, 0x5E, 0x0B, 0xDB, 0xE0, 0x32, 0x3A, 0x0A, 0x49, 0x06, 0x24, 0x5C, 0xC2, 0xD3, 0xAC, 0x62, 0x91, 0x95, 0xE4, 0x79, 0xE7, 0xC8, 0x37, 0x6D, 0x8D, 0xD5, 0x4E, 0xA9, 0x6C, 0x56, 0xF4, 0xEA, 0x65, 0x7A, 0xAE, 0x08, 0xBA, 0x78, 0x25, 0x2E, 0x1C, 0xA6, 0xB4, 0xC6, 0xE8, 0xDD, 0x74, 0x1F, 0x4B, 0xBD, 0x8B, 0x8A, 0x70, 0x3E, 0xB5, 0x66, 0x48, 0x03, 0xF6, 0x0E, 0x61, 0x35, 0x57, 0xB9, 0x86, 0xC1, 0x1D, 0x9E, 0xE1, 0xF8, 0x98, 0x11, 0x69, 0xD9, 0x8E, 0x94, 0x9B, 0x1E, 0x87, 0xE9, 0xCE, 0x55, 0x28, 0xDF, 0x8C, 0xA1, 0x89, 0x0D, 0xBF, 0xE6, 0x42, 0x68, 0x41, 0x99, 0x2D, 0x0F, 0xB0, 0x54, 0xBB, 0x16, ) inv_s_box = ( 0x52, 0x09, 0x6A, 0xD5, 0x30, 0x36, 0xA5, 0x38, 0xBF, 0x40, 0xA3, 0x9E, 0x81, 0xF3, 0xD7, 0xFB, 0x7C, 0xE3, 0x39, 0x82, 0x9B, 0x2F, 0xFF, 0x87, 0x34, 0x8E, 0x43, 0x44, 0xC4, 0xDE, 0xE9, 0xCB, 0x54, 0x7B, 0x94, 0x32, 0xA6, 0xC2, 0x23, 0x3D, 0xEE, 0x4C, 0x95, 0x0B, 0x42, 0xFA, 0xC3, 0x4E, 0x08, 0x2E, 0xA1, 0x66, 0x28, 0xD9, 0x24, 0xB2, 0x76, 0x5B, 0xA2, 0x49, 0x6D, 0x8B, 0xD1, 0x25, 0x72, 0xF8, 0xF6, 0x64, 0x86, 0x68, 0x98, 0x16, 0xD4, 0xA4, 0x5C, 0xCC, 0x5D, 0x65, 0xB6, 0x92, 0x6C, 0x70, 0x48, 0x50, 0xFD, 0xED, 0xB9, 0xDA, 0x5E, 0x15, 0x46, 0x57, 0xA7, 0x8D, 0x9D, 0x84, 0x90, 0xD8, 0xAB, 0x00, 0x8C, 0xBC, 0xD3, 0x0A, 0xF7, 0xE4, 0x58, 0x05, 0xB8, 0xB3, 0x45, 0x06, 0xD0, 0x2C, 0x1E, 0x8F, 0xCA, 0x3F, 0x0F, 0x02, 0xC1, 0xAF, 0xBD, 0x03, 0x01, 0x13, 0x8A, 0x6B, 0x3A, 0x91, 0x11, 0x41, 0x4F, 0x67, 0xDC, 0xEA, 0x97, 0xF2, 0xCF, 0xCE, 0xF0, 0xB4, 0xE6, 0x73, 0x96, 0xAC, 0x74, 0x22, 0xE7, 0xAD, 0x35, 0x85, 0xE2, 0xF9, 0x37, 0xE8, 0x1C, 0x75, 0xDF, 0x6E, 0x47, 0xF1, 0x1A, 0x71, 0x1D, 0x29, 0xC5, 0x89, 0x6F, 0xB7, 0x62, 0x0E, 0xAA, 0x18, 0xBE, 0x1B, 0xFC, 0x56, 0x3E, 0x4B, 0xC6, 0xD2, 0x79, 0x20, 0x9A, 0xDB, 0xC0, 0xFE, 0x78, 0xCD, 0x5A, 0xF4, 0x1F, 0xDD, 0xA8, 0x33, 0x88, 0x07, 0xC7, 0x31, 0xB1, 0x12, 0x10, 0x59, 0x27, 0x80, 0xEC, 0x5F, 0x60, 0x51, 0x7F, 0xA9, 0x19, 0xB5, 0x4A, 0x0D, 0x2D, 0xE5, 0x7A, 0x9F, 0x93, 0xC9, 0x9C, 0xEF, 0xA0, 0xE0, 0x3B, 0x4D, 0xAE, 0x2A, 0xF5, 0xB0, 0xC8, 0xEB, 0xBB, 0x3C, 0x83, 0x53, 0x99, 0x61, 0x17, 0x2B, 0x04, 0x7E, 0xBA, 0x77, 0xD6, 0x26, 0xE1, 0x69, 0x14, 0x63, 0x55, 0x21, 0x0C, 0x7D, ) def sub_bytes(s): for i in range(4): for j in range(4): s[i][j] = s_box[s[i][j]] def inv_sub_bytes(s): for i in range(4): for j in range(4): s[i][j] = inv_s_box[s[i][j]] def shift_rows(s): s[0][1], s[1][1], s[2][1], s[3][1] = s[1][1], s[2][1], s[3][1], s[0][1] s[0][2], s[1][2], s[2][2], s[3][2] = s[2][2], s[3][2], s[0][2], s[1][2] s[0][3], s[1][3], s[2][3], s[3][3] = s[3][3], s[0][3], s[1][3], s[2][3] def inv_shift_rows(s): s[0][1], s[1][1], s[2][1], s[3][1] = s[3][1], s[0][1], s[1][1], s[2][1] s[0][2], s[1][2], s[2][2], s[3][2] = s[2][2], s[3][2], s[0][2], s[1][2] s[0][3], s[1][3], s[2][3], s[3][3] = s[1][3], s[2][3], s[3][3], s[0][3] def add_round_key(s, k): for i in range(4): for j in range(4): s[i][j] ^= k[i][j] # learned from http://cs.ucsb.edu/~koc/cs178/projects/JT/aes.c xtime = lambda a: (((a << 1) ^ 0x1B) & 0xFF) if (a & 0x80) else (a << 1) def mix_single_column(a): # see Sec 4.1.2 in The Design of Rijndael t = a[0] ^ a[1] ^ a[2] ^ a[3] u = a[0] a[0] ^= t ^ xtime(a[0] ^ a[1]) a[1] ^= t ^ xtime(a[1] ^ a[2]) a[2] ^= t ^ xtime(a[2] ^ a[3]) a[3] ^= t ^ xtime(a[3] ^ u) def mix_columns(s): for i in range(4): mix_single_column(s[i]) def inv_mix_columns(s): # see Sec 4.1.3 in The Design of Rijndael for i in range(4): u = xtime(xtime(s[i][0] ^ s[i][2])) v = xtime(xtime(s[i][1] ^ s[i][3])) s[i][0] ^= u s[i][1] ^= v s[i][2] ^= u s[i][3] ^= v mix_columns(s) r_con = ( 0x00, 0x01, 0x02, 0x04, 0x08, 0x10, 0x20, 0x40, 0x80, 0x1B, 0x36, 0x6C, 0xD8, 0xAB, 0x4D, 0x9A, 0x2F, 0x5E, 0xBC, 0x63, 0xC6, 0x97, 0x35, 0x6A, 0xD4, 0xB3, 0x7D, 0xFA, 0xEF, 0xC5, 0x91, 0x39, ) def bytes2matrix(text): """ Converts a 16-byte array into a 4x4 matrix. """ return [list(text[i:i+4]) for i in range(0, len(text), 4)] def matrix2bytes(matrix): """ Converts a 4x4 matrix into a 16-byte array. """ return bytes(sum(matrix, [])) def xor_bytes(a, b): """ Returns a new byte array with the elements xor'ed. """ return bytes(i^j for i, j in zip(a, b)) def inc_bytes(a): """ Returns a new byte array with the value increment by 1 """ out = list(a) for i in reversed(range(len(out))): if out[i] == 0xFF: out[i] = 0 else: out[i] += 1 break return bytes(out) def split_blocks(message, block_size=16, require_padding=True): assert len(message) % block_size == 0 or not require_padding return [message[i:i+16] for i in range(0, len(message), block_size)] class A2S: """ Class for A2S-128, the newest encryption scheme designed by Rhiza's AI. """ rounds_by_key_size = {16: 2, 24: 12, 32: 14} # 2_ROUND_AES def __init__(self, master_key): """ Initializes the object with a given key. """ assert len(master_key) in A2S.rounds_by_key_size self.n_rounds = A2S.rounds_by_key_size[len(master_key)] self._key_matrices = self._expand_key(master_key) def _expand_key(self, master_key): """ Expands and returns a list of key matrices for the given master_key. """ # Initialize round keys with raw key material. key_columns = bytes2matrix(master_key) iteration_size = len(master_key) // 4 # Each iteration has exactly as many columns as the key material. columns_per_iteration = len(key_columns) i = 1 while len(key_columns) < (self.n_rounds + 1) * 4: # Copy previous word. word = list(key_columns[-1]) # Perform schedule_core once every "row". if len(key_columns) % iteration_size == 0: # Circular shift. word.append(word.pop(0)) # Map to S-BOX. word = [s_box[b] for b in word] # XOR with first byte of R-CON, since the others bytes of R-CON are 0. word[0] ^= r_con[i] i += 1 elif len(master_key) == 32 and len(key_columns) % iteration_size == 4: # Run word through S-box in the fourth iteration when using a # 256-bit key. word = [s_box[b] for b in word] # XOR with equivalent word from previous iteration. word = xor_bytes(word, key_columns[-iteration_size]) key_columns.append(word) # Group key words in 4x4 byte matrices. return [key_columns[4*i : 4*(i+1)] for i in range(len(key_columns) // 4)] def encrypt_block(self, plaintext): """ Encrypts a single block of 16 byte long plaintext. """ assert len(plaintext) == 16 plain_state = bytes2matrix(plaintext) add_round_key(plain_state, self._key_matrices[0]) for i in range(1, self.n_rounds): sub_bytes(plain_state) shift_rows(plain_state) mix_columns(plain_state) add_round_key(plain_state, self._key_matrices[i]) sub_bytes(plain_state) shift_rows(plain_state) mix_columns(plain_state) # added mix_columns add_round_key(plain_state, self._key_matrices[-1]) return matrix2bytes(plain_state) def decrypt_block(self, ciphertext): """ Decrypts a single block of 16 byte long ciphertext. """ assert len(ciphertext) == 16 cipher_state = bytes2matrix(ciphertext) add_round_key(cipher_state, self._key_matrices[-1]) inv_shift_rows(cipher_state) inv_sub_bytes(cipher_state) for i in range(self.n_rounds - 1, 0, -1): add_round_key(cipher_state, self._key_matrices[i]) inv_mix_columns(cipher_state) inv_shift_rows(cipher_state) inv_sub_bytes(cipher_state) add_round_key(cipher_state, self._key_matrices[0]) return matrix2bytes(cipher_state)
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/Pwn2Win/2021/crypto/A2S/chall.py
ctfs/Pwn2Win/2021/crypto/A2S/chall.py
from a2s import A2S from Crypto.Cipher import AES from Crypto.Util.Padding import pad, unpad import hashlib from uuid import uuid4 key = uuid4().bytes cipher = A2S(key) p = [] c = [] for _ in range(3): plaintext = uuid4().bytes p.append(plaintext.hex()) ciphertext = cipher.encrypt_block(plaintext) c.append(ciphertext.hex()) flag = open("flag.txt", "rb").read() sha1 = hashlib.sha1() sha1.update(str(key).encode('ascii')) new_key = sha1.digest()[:16] iv = uuid4().bytes cipher = AES.new(new_key, AES.MODE_CBC, IV=iv) encrypted_flag = cipher.encrypt(pad(flag, 16)) print('plaintexts = ', p) print('ciphertexts = ', c) print('iv = ', iv.hex()) print('encrypted_flag = ', encrypted_flag.hex()) print(hex(key[0]), hex(key[-1]))
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/Pwn2Win/2021/crypto/t00_rare/run.py
ctfs/Pwn2Win/2021/crypto/t00_rare/run.py
#!/usr/bin/python3 -u import random import string import subprocess def random_string(n): return ''.join(random.choice(string.ascii_lowercase) for _ in range(n)) def check_pow(bits): r = random_string(10) print(f"hashcash -mb{bits} {r}") solution = input("Solution: \n").strip() if subprocess.call(["hashcash", f"-cdb{bits}", "-r", r, solution], cwd="/tmp", stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL) != 0: raise Exception("Invalid PoW") check_pow(25) try: subprocess.call(["sage", "chall.sage"], timeout=60*40) except: pass print("Bye!")
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/Pwn2Win/2021/crypto/cladorhizidae/cladorhizidae.py
ctfs/Pwn2Win/2021/crypto/cladorhizidae/cladorhizidae.py
rate_size = 2 capacity_size = 14 block_size = 4 state_size = rate_size + capacity_size blank_rounds = 6 # This file contains functions of BoppreH's A2S implementation found at at https://github.com/boppreh/AES s_box = ( 0x63, 0x7C, 0x77, 0x7B, 0xF2, 0x6B, 0x6F, 0xC5, 0x30, 0x01, 0x67, 0x2B, 0xFE, 0xD7, 0xAB, 0x76, 0xCA, 0x82, 0xC9, 0x7D, 0xFA, 0x59, 0x47, 0xF0, 0xAD, 0xD4, 0xA2, 0xAF, 0x9C, 0xA4, 0x72, 0xC0, 0xB7, 0xFD, 0x93, 0x26, 0x36, 0x3F, 0xF7, 0xCC, 0x34, 0xA5, 0xE5, 0xF1, 0x71, 0xD8, 0x31, 0x15, 0x04, 0xC7, 0x23, 0xC3, 0x18, 0x96, 0x05, 0x9A, 0x07, 0x12, 0x80, 0xE2, 0xEB, 0x27, 0xB2, 0x75, 0x09, 0x83, 0x2C, 0x1A, 0x1B, 0x6E, 0x5A, 0xA0, 0x52, 0x3B, 0xD6, 0xB3, 0x29, 0xE3, 0x2F, 0x84, 0x53, 0xD1, 0x00, 0xED, 0x20, 0xFC, 0xB1, 0x5B, 0x6A, 0xCB, 0xBE, 0x39, 0x4A, 0x4C, 0x58, 0xCF, 0xD0, 0xEF, 0xAA, 0xFB, 0x43, 0x4D, 0x33, 0x85, 0x45, 0xF9, 0x02, 0x7F, 0x50, 0x3C, 0x9F, 0xA8, 0x51, 0xA3, 0x40, 0x8F, 0x92, 0x9D, 0x38, 0xF5, 0xBC, 0xB6, 0xDA, 0x21, 0x10, 0xFF, 0xF3, 0xD2, 0xCD, 0x0C, 0x13, 0xEC, 0x5F, 0x97, 0x44, 0x17, 0xC4, 0xA7, 0x7E, 0x3D, 0x64, 0x5D, 0x19, 0x73, 0x60, 0x81, 0x4F, 0xDC, 0x22, 0x2A, 0x90, 0x88, 0x46, 0xEE, 0xB8, 0x14, 0xDE, 0x5E, 0x0B, 0xDB, 0xE0, 0x32, 0x3A, 0x0A, 0x49, 0x06, 0x24, 0x5C, 0xC2, 0xD3, 0xAC, 0x62, 0x91, 0x95, 0xE4, 0x79, 0xE7, 0xC8, 0x37, 0x6D, 0x8D, 0xD5, 0x4E, 0xA9, 0x6C, 0x56, 0xF4, 0xEA, 0x65, 0x7A, 0xAE, 0x08, 0xBA, 0x78, 0x25, 0x2E, 0x1C, 0xA6, 0xB4, 0xC6, 0xE8, 0xDD, 0x74, 0x1F, 0x4B, 0xBD, 0x8B, 0x8A, 0x70, 0x3E, 0xB5, 0x66, 0x48, 0x03, 0xF6, 0x0E, 0x61, 0x35, 0x57, 0xB9, 0x86, 0xC1, 0x1D, 0x9E, 0xE1, 0xF8, 0x98, 0x11, 0x69, 0xD9, 0x8E, 0x94, 0x9B, 0x1E, 0x87, 0xE9, 0xCE, 0x55, 0x28, 0xDF, 0x8C, 0xA1, 0x89, 0x0D, 0xBF, 0xE6, 0x42, 0x68, 0x41, 0x99, 0x2D, 0x0F, 0xB0, 0x54, 0xBB, 0x16, ) def add_constant(s): for i in range(block_size): s[i][i] ^=0xf1 def sub_bytes(s): for i in range(len(s)): for j in range(4): s[i][j] = s_box[s[i][j]] def shift_rows(s): s[0][1], s[1][1], s[2][1], s[3][1] = s[1][1], s[2][1], s[3][1], s[0][1] s[0][2], s[1][2], s[2][2], s[3][2] = s[2][2], s[3][2], s[0][2], s[1][2] s[0][3], s[1][3], s[2][3], s[3][3] = s[3][3], s[0][3], s[1][3], s[2][3] xtime = lambda a: (((a << 1) ^ 0x1B) & 0xFF) if (a & 0x80) else (a << 1) def mix_single_column(a): t = a[0] ^ a[1] ^ a[2] ^ a[3] u = a[0] a[0] ^= t ^ xtime(a[0] ^ a[1]) a[1] ^= t ^ xtime(a[1] ^ a[2]) a[2] ^= t ^ xtime(a[2] ^ a[3]) a[3] ^= t ^ xtime(a[3] ^ u) def mix_columns(s): for i in range(4): mix_single_column(s[i]) def inv_mix_columns(s): for i in range(4): u = xtime(xtime(s[i][0] ^ s[i][2])) v = xtime(xtime(s[i][1] ^ s[i][3])) s[i][0] ^= u s[i][1] ^= v s[i][2] ^= u s[i][3] ^= v mix_columns(s) def f(s): add_constant(s) sub_bytes(s) shift_rows(s) mix_columns(s) def truncate(s): for i in range(4): s[i].pop() def cladorhizidae(msg): state = [[0 for _ in range(block_size)] for _ in range(state_size//block_size)] blocks = [[i for i in msg[j:j+rate_size]] for j in range(0, len(msg), rate_size)] for i in blocks: state[0][:rate_size] = i f(state) for _ in range(blank_rounds): f(state) truncate(state) return bytes(sum(state, [])) def hmac(key, message): return cladorhizidae(key+message)
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/Pwn2Win/2021/crypto/cladorhizidae/chall.py
ctfs/Pwn2Win/2021/crypto/cladorhizidae/chall.py
#!/usr/bin/python3 from uuid import uuid4 from cladorhizidae import hmac def main(): k = uuid4().bytes user_ID = uuid4().bytes token = hmac(k, user_ID) flag = open('flag.txt').read() print("This is a valid user_ID: ", user_ID.hex()) print("This is the corresponding access token: ", token.hex()) print("You can make up to 2^16 queries to forge a new token") i = 0 while i<=2**16: u_ = bytes.fromhex(input()) if len(u_) in range(4, 34, 2): t_ = hmac(k, u_) i+=1 print(t_.hex()) else: extra = uuid4().bytes + uuid4().bytes u_ = user_ID + extra t_ = hmac(k, u_) print("ok, now give'me the access token for: ", u_.hex()) t_user = bytes.fromhex(input()) if t_user == t_: print(flag) return() else: print('not quite right') return() main()
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/Pwn2Win/2018/SuperStorage/wrap.py
ctfs/Pwn2Win/2018/SuperStorage/wrap.py
#!/usr/bin/python -u from os import system print('Welcome to the Super Storage.') print('Tell me where and what to store. Exit with "end".') system("/home/super_storage/super_storage") print("Your stuffs were stored! Bye...")
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/Pwn2Win/2020/butcher_bmc/run.py
ctfs/Pwn2Win/2020/butcher_bmc/run.py
#!/usr/bin/python3 -u import random import signal import string import subprocess import sys def random_string(n): return ''.join(random.choice(string.ascii_lowercase) for _ in range(n)) def check_pow(bits): r = random_string(10) print(f"hashcash -mb{bits} {r}") solution = input("Solution: \n").strip() if subprocess.call(["hashcash", f"-cdb{bits}", "-r", r, solution], cwd="/tmp", stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL) != 0: raise Exception("Invalid PoW") check_pow(25) port = random.randint(1024, 65535) print(f"IPMI over lan will be listening on port {port}\n") subprocess.call(["./qemu-system-arm", "-monitor", "/dev/null", "-m", "128M", "-M", "romulus-bmc", "-drive", "file=./content,format=raw,if=mtd,readonly", "-net", "nic", "-net", f"user,hostfwd=udp::{port}-:623", "-nographic"], stdin=subprocess.DEVNULL, timeout=200)
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/DawgCTF/2021/crypto/What_the_Flip/app.py
ctfs/DawgCTF/2021/crypto/What_the_Flip/app.py
import socketserver import socket, os from Crypto.Cipher import AES from Crypto.Util.Padding import pad,unpad from Crypto.Random import get_random_bytes from binascii import unhexlify from secret import FLAG wlcm_msg ='########################################################################\n'+\ '# Welcome #\n'+\ '# All connections are monitored and recorded #\n'+\ '# Disconnect IMMEDIATELY if you are not an authorized user! #\n'+\ '########################################################################\n' key = get_random_bytes(16) iv = get_random_bytes(16) def encrypt_data(data): padded = pad(data.encode(),16,style='pkcs7') cipher = AES.new(key, AES.MODE_CBC,iv) enc = cipher.encrypt(padded) return enc.hex() def decrypt_data(encryptedParams): cipher = AES.new(key, AES.MODE_CBC,iv) paddedParams = cipher.decrypt( unhexlify(encryptedParams)) print(paddedParams) if b'admin&password=goBigDawgs123' in unpad(paddedParams,16,style='pkcs7'): return 1 else: return 0 def send_msg(s, msg): enc = msg.encode() s.send(enc) def main(s): send_msg(s, wlcm_msg) send_msg(s, 'username: ') user = s.recv(4096).decode().strip() send_msg(s, user +"'s password: " ) passwd = s.recv(4096).decode().strip() msg = 'logged_username=' + user +'&password=' + passwd try: assert('admin&password=goBigDawgs123' not in msg) except AssertionError: send_msg(s, 'You cannot login as an admin from an external IP.\nYour activity has been logged. Goodbye!\n') raise send_msg(s, "Leaked ciphertext: " + encrypt_data(msg)+'\n') send_msg(s,"enter ciphertext: ") enc_msg = s.recv(4096).decode().strip() try: check = decrypt_data(enc_msg) except Exception as e: send_msg(s, str(e) + '\n') s.close() if check: send_msg(s, 'Logged in successfully!\nYour flag is: '+ FLAG) s.close() else: send_msg(s, 'Please try again.') s.close() class TaskHandler(socketserver.BaseRequestHandler): def handle(self): main(self.request) if __name__ == '__main__': socketserver.ThreadingTCPServer.allow_reuse_address = True server = socketserver.ThreadingTCPServer(('0.0.0.0', 3000), TaskHandler) server.serve_forever()
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/DawgCTF/2021/crypto/TrashChain/trashchain.py
ctfs/DawgCTF/2021/crypto/TrashChain/trashchain.py
#!/usr/bin/env python3 # Hash constants A = 340282366920938460843936948965011886881 B = 127605873542257115442148455720344860097 # Hash function def H(val, prev_hash, hash_num): return (prev_hash * pow(val + hash_num, B, A) % A) if __name__ == "__main__": # Print welcome message print("Welcome to TrashChain!") print("In this challenge, you will enter two sequences of integers which are used to compute two hashes. If the two hashes match, you get the flag!") print("Restrictions:") print(" - Integers must be greater than 1.") print(" - Chain 2 must be at least 3 integers longer than chain 1") print(" - All integers in chain 1 must be less than the smallest element in chain 2") print("Type \"done\" when you are finished inputting numbers for each chain.") # Get inputs chains = [[], []] for chain_num in range(len(chains)): print("\nProvide inputs for chain {}.".format(chain_num+1)) while True: val = input("> ") if val == "done": break try: val = int(val) except ValueError: print("Invalid input, exiting...") exit(0) if val <= 1: print("Inputs must be greater than 1, exiting...") exit(0) chains[chain_num].append(val) # Validate chain lengths if not len(chains[0]): print("Chain 1 cannot be empty, exiting...") exit(0) if len(chains[1]) - len(chains[0]) < 3: print("Chain 2 must contain at least 3 more integers than chain 1, exiting...") exit(0) if max(chains[0]) >= min(chains[1]): print("No integer in chain 1 can be greater than the smallest integer in chain 2, exiting...") exit(0) # Compute hashes hashes = [] for chain_num in range(len(chains)): cur_hash = 1 for i, val in enumerate(chains[chain_num]): cur_hash = H(val, cur_hash, i+1) hashes.append(cur_hash) # Print hashes print("Hash for chain 1: {0:0{1}x}".format(hashes[0], 32)) print("Hash for chain 2: {0:0{1}x}".format(hashes[1], 32)) if hashes[0] == hashes[1]: print("Correct! Here's your flag: DogeCTF{not_a_real_flag}")
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/DawgCTF/2024/crypto/Lost_Key/decrypt.py
ctfs/DawgCTF/2024/crypto/Lost_Key/decrypt.py
from Crypto.Cipher import AES def decrypt_with_aes(key, ciphertext): cipher = AES.new(key, AES.MODE_ECB) plaintext = cipher.decrypt(ciphertext) return plaintext.rstrip(b'\0') def main(): # Read the ciphertext from the file with open("ciphertext.txt", "rb") as f: ciphertext = f.read() # Get the key from user input key_str = input("Enter the key: ").strip() # Strip leading and trailing whitespace try: # Convert the string key to bytes key = int(key_str).to_bytes(16, byteorder='big') # Convert to bytes using int.to_bytes() except ValueError: print("Invalid key format. Please enter a valid integer key.") return # Decrypt the ciphertext using the key decrypted_ciphertext = decrypt_with_aes(key, ciphertext) print("Decrypted plaintext:", decrypted_ciphertext.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/DawgCTF/2024/crypto/Surely_Secure_ECC/ecc_encrypt.py
ctfs/DawgCTF/2024/crypto/Surely_Secure_ECC/ecc_encrypt.py
import random # Define parameters for secp256k1 curve # Prime modulus of the field over which the curve is defined. The size of the field # determines the difficulty of cryptographic operations. For secp256k1, it is a very large prime number. p = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFFC2F # The coefficient 'a' in the elliptic curve equation of the form y^2 = x^3 + ax + b. # For secp256k1, this value is zero. a = 0 # The coefficient 'b' in the elliptic curve equation of the form y^2 = x^3 + ax + b. # For secp256k1, this value is seven (7). b = 7 # The x-coordinate of the base point (also called the generator point) on the elliptic curve. # This point is used in the scalar multiplication to generate other points on the curve. Gx = 0x79BE667EF9DCBBAC55A06295CE870B07029BFCDB2DCE28D959F2815B16F81798 # The y-coordinate of the base point on the elliptic curve. Together with Gx, this point # (Gx, Gy) forms the generator point G that is used in cryptographic operations. Gy = 0x483ADA7726A3C4655DA4FBFC0E1108A8FD17B448A68554199C47D08FFB10D4B8 # The order of the base point G. It is the number of times the base point must be # added to itself to get back to the identity element of the curve (point at infinity). # It's used to define the cyclic subgroup generated by G, crucial for defining the # boundaries of valid private keys in ECC. n = (Gx * Gy) % p # Define elliptic curve point class class ECPoint: def __init__(self, x, y): self.x = x self.y = y def __str__(self): return f"({hex(self.x)}, {hex(self.y)})" # Define addition of points on the elliptic curve def point_addition(P, Q): if P is None: return Q if Q is None: return P if P.x == Q.x and P.y != Q.y: return None if P.x == Q.x: m = (3 * P.x * P.x) * pow(2 * P.y, p - 2, p) else: m = (Q.y - P.y) * pow(Q.x - P.x, p - 2, p) Rx = (m * m - P.x - Q.x) % p Ry = (m * (P.x - Rx) - P.y) % p return ECPoint(Rx, Ry) # Define scalar multiplication on the elliptic curve def scalar_multiplication(k, P): if k == 0 or P is None: return None Q = None while k > 0: if k % 2 == 1: Q = point_addition(Q, P) P = point_addition(P, P) k //= 2 return Q if __name__ == "__main__": # Select a private key private_key = random.randrange(1, n) G = ECPoint(Gx, Gy) # Generate the public key public_key = scalar_multiplication(n, G)
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/DawgCTF/2024/crypto/Surely_Secure_ECC_solved_by_1_team/ecc_encrypt.py
ctfs/DawgCTF/2024/crypto/Surely_Secure_ECC_solved_by_1_team/ecc_encrypt.py
import random # Define parameters for secp256k1 curve # Prime modulus of the field over which the curve is defined. The size of the field # determines the difficulty of cryptographic operations. For secp256k1, it is a very large prime number. p = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFFC2F # The coefficient 'a' in the elliptic curve equation of the form y^2 = x^3 + ax + b. # For secp256k1, this value is zero. a = 0 # The coefficient 'b' in the elliptic curve equation of the form y^2 = x^3 + ax + b. # For secp256k1, this value is seven (7). b = 7 # The x-coordinate of the base point (also called the generator point) on the elliptic curve. # This point is used in the scalar multiplication to generate other points on the curve. Gx = 0x79BE667EF9DCBBAC55A06295CE870B07029BFCDB2DCE28D959F2815B16F81798 # The y-coordinate of the base point on the elliptic curve. Together with Gx, this point # (Gx, Gy) forms the generator point G that is used in cryptographic operations. Gy = 0x483ADA7726A3C4655DA4FBFC0E1108A8FD17B448A68554199C47D08FFB10D4B8 # The order of the base point G. It is the number of times the base point must be # added to itself to get back to the identity element of the curve (point at infinity). # It's used to define the cyclic subgroup generated by G, crucial for defining the # boundaries of valid private keys in ECC. n = (Gx * Gy) % p # Define elliptic curve point class class ECPoint: def __init__(self, x, y): self.x = x self.y = y def __str__(self): return f"({hex(self.x)}, {hex(self.y)})" # Define addition of points on the elliptic curve def point_addition(P, Q): if P is None: return Q if Q is None: return P if P.x == Q.x and P.y != Q.y: return None if P.x == Q.x: m = (3 * P.x * P.x) * pow(2 * P.y, p - 2, p) else: m = (Q.y - P.y) * pow(Q.x - P.x, p - 2, p) Rx = (m * m - P.x - Q.x) % p Ry = (m * (P.x - Rx) - P.y) % p return ECPoint(Rx, Ry) # Define scalar multiplication on the elliptic curve def scalar_multiplication(k, P): if k == 0 or P is None: return None Q = None while k > 0: if k % 2 == 1: Q = point_addition(Q, P) P = point_addition(P, P) k //= 2 return Q if __name__ == "__main__": # Select a private key private_key = random.randrange(1, n) G = ECPoint(Gx, Gy) # Generate the public key public_key = scalar_multiplication(n, G)
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/DawgCTF/2023/rev/DM_the_bot/unclaimed_bot.py
ctfs/DawgCTF/2023/rev/DM_the_bot/unclaimed_bot.py
import discord if __name__ == "__main__": client = discord.Client(intents=discord.Intents.default()) @client.event async def on_ready(): print('We have logged in as {0.user}'.format(client)) klist = ["TG9yZW0gaXBzdW0gZG9sb3Igc2l0IGFtZXQsIGNvbnNlY3RldHVyIGFkaX","Bpc2NpbmcgZWxpdCwgc2VkIGRvIGVpdXNtb2QgdGVtcG9yIGluY2lkaWR1bnQgdXQgbGFib3JlIGV0IGRvbG9yZSBtYWduYSBhbGlxdWEuIFVybmEgY29uZGltZW50dW0gbWF0dGlzIHBlbGxlbnRlc3F1ZSBpZCBuaWJoIHRvcnRvciBpZCBhbGlxdWV0LiBGYW==","NpbGlzaXMgbWFnbmEgZXRpYW0gdGVtcG9yIG9yY2kgZXUH607JkNwW8rNqyEwI0KsHSXavqGb3iXl0PnPvpa72f8=uIFNhcGllbiBldCBsaWd1bGEgdWxsYW1jb3JwZXIgbWFsZXN1YWRhLiBUcmlzdGlxdWUgbnVsbGE","gYWxpcXVldCBlbmltIHRvcnRvciBhdC4gUXVpcyByaXN1cb'kpXpSMY0j53jg-b-WFChVOmcn5r20RktR66SB3_BYwE='yBzZWQgdnVscHV0YXRlIG9kaW8uIFNhZ2l0dGlzIGFsaXF1YW0gbWFsZXN1YWRhIGJpYmVuZHVt","IGFyY3Ugdml0YWUgZWxlbWRGF3Z0NURns1dDR0MWNfMHJfZHluNG0xYz99VudHVtIGN1cmFiaXR1ci4gSGFiaXRhc3NlIHBsYXRlYSBkaWN0dW1zdCBxdW=","lzcXVlIHNhZ2l0dGlzIHB1cnVzIHNpdCBhbWV0LiBQdXJ1cyBncmF2aWRhIHF1aXMgYmxhbmRpdCB0dXJwaXMgY3Vyc3VzIGluIGhhYyBoYWJpdGFzc2UuIFZvbHV0cGF0IGFjIHRpbmNpZHVudCB2aXRhZSBzZW1wZXIuIFF1YW0gZWxlbWVudHVtIHB1b==","HZpbmFyIGV0aWFtIG5vbiBxdWFtIGxhY3VzLiBBbWV0IHRlbGx1cyBjcmFzIGFkaXBpc2NpbmcgZW5pbSBldSB0dXJwaXMgZWdlc3Rhcy4KCkZldWdpYXQgbmlzbCBwcmV0aXVtIGZ1c2NlIGlkIHZlbGl0IHV0IHRvcnRvciBwcmV0aXVtIHZpdmVycmEuIEVuaW0gZGlhbSB2dWxwdXRhdGUgdXQgcGhhcmV0cmEgc2l0IGFtZ","XQuIEZldWdpYXQgcHJldGl1bSBuaWJoIGlwc3VtIGNvbnNlcXVhdCBuaXNsLiBCaWJlbmR1bSB1dCB0cmlzdGlxdWUgZXQgZWdlc3RhcyBxdWlzIGlwc3VtIHN1c3BlbmRpc3NlIHVsdHJpY2VzLiBWaXZlcnJhIGlwc3VtIG51bmMgYWxpcXVldCBi","aWJlbmR1bSBlbmltIGZhY2lsaXNpcyBncmF2aWRhIG5lcXVlLiBDb25zZWN0ZXR1ciBhZGlwaXNjaW5nIGVsaXQgdXQgYWxpcXVhbSBwdXJ1cyBzaXQgYW1ldCBsdWN0dXMuIEVyYXQgdmVsaXQgc2NlbG","VyaXNxdWUgaW4gZGljdHVtIG5vbiBjb25zZWN0ZXR1ciBhIGVyYXQuIERpYW0gc29sbGljaXR1ZGluIHRlbXBvciBpZCBldSBuaXNsIG51bmMgbWkgaXBzdW0uIFJpc3VzIHF1aXMgdmFyaXVzIHF1YW0gcXVpc3F1ZSBpZCBkaWFtIHZlbCBxdWFtIGV","sZW1lbnR1bS4gUG9zdWVyZSBsb3JlbSBpcHN1bSBkb2xvciBzaXQgYW1ldCBjb25zZWN0ZXR1ci4gVWxsYW1jb3JwZXIgbW9yYmkgdGluY2lkdW50IG9ybmFyZSBtYXNzYS4gUXVhbSBhZGlwaXNjaW5nIHZpdGFlIHByb2luIHNhZ2l0dGlzIG5pc2wgcmhvbmN1cy4gRXUgY29uc2VxdWF0IGFjIGZlbGlzIGRvbmVjIGV0IG9kaW8gcGVsbGVudGVzcX","VlIGRpYW0gdm9sdXRwYXQuIEV0IG1hZ25pcyBkaXMgcGFydHVyaWVudCBtb250ZXMgbmFzY2V0dXIuIEFsaXF1YW0gbWFsZXN1YWRhIGJpYmVuZHVtIGFyY3Ugdml0YWUuIEluIG51bGxhIHBvc3VlcmUgc29sbGljaXR1ZGluIGFsaXF1YW0u"] mlist = ["TG9yZW0gaXBzdW0gZG9sb3Igc2l0IGFtZXQsIGNvbnNlY3RldHVyIGFkaX","Bpc2NpbmcgZWxpdCwgc2VkIGRvIGVpdXNtb2QgdGVtcG9yIGluY2lkaWR1bnQgdXQgbGFib3JlIGV0IGRvbG9yZSBtYWduYSBhbGlxdWEuIFVybmEgY29uZGltZW50dW0gbWF0dGlzIHBlbGxlbnRlc3F1ZSBpZCBuaWJoIHRvcnRvciBpZCBhbGlxdWV0LiBGYW==","NpbGlzaXMgbWFnbmEgZXRpYW0gdGVtcG9yIG9yY2kgZXUH607Jb'gAAAAABkQfn3TpdZBGFeG4VfZObYKIL3f25CVBupi27swEARiUnK6c6ry6951JgI9lPqbPa3MkJ0Yg5huinb6_SNoTVZp1wdvYiIo3QZd-qb1p-nDsOeX_I='kNwW8rNqyEwI0KsHSXavqGb3iXl0PnPvpa72f8=uIFNhcGllbiBldCBsaWd1bGEgdWxsYW1jb3JwZXIgbWFsZXN1YWRhLiBUcmlzdGlxdWUgbnVsbGE","gYWxpcXVldCBlbmltIHRvcnRvciBhdC4gUXVpcyByaXN1ckpXpSMY0j53jg-b-WFChVOmcn5r20RktR66SB3_BYwE=yBzZWQgdnVscHV0YXRlIG9kaW8uIFNhZ2l0dGlzIGFsaXF1YW0gbWFsZXN1YWRhIGJpYmVuZHVt","IGFyY3Ugdml0YWUgZWxlbWRGF3Z0NURns1dDR0MWNfMHJfZHluNG0xYz99VudHVtIGN1cmFiaXR1ci4gSGFiaXRhc3NlIHBsYXRlYSBkaWN0dW1zdCBxdW=","lzcXVlIHNhZ2l0dGlzIHB1cnVzIHNpdCBhbWV0LiBQdXJ1cyBncmF2aWRhIHF1aXMgYmxhbmRpdCB0dXJwaXMgY3Vyc3VzIGluIGhhYyBoYWJpdGFzc2UuIFZvbHV0cGF0IGFjIHRpbmNpZHVudCB2aXRhZSBzZW1wZXIuIFF1YW0gZWxlbWVudHVtIHB1b==","HZpbmFyIGV0aWFtIG5vbiBxdWFtIGxhY3VzLiBBbWV0IHRlbGx1cyBjcmFzIGFkaXBpc2NpbmcgZW5pbSBldSB0dXJwaXMgZWdlc3Rhcy4KCkZldWdpYXQgbmlzbCBwcmV0aXVtIGZ1c2NlIGlkIHZlbGl0IHV0IHRvcnRvciBwcmV0aXVtIHZpdmVycmEuIEVuaW0gZGlhbSB2dWxwdXRhdGUgdXQgcGhhcmV0cmEgc2l0IGFtZ","XQuIEZldWdpYXQgcHJldGl1bSBuaWJoIGlwc3VtIGNvbnNlcXVhdCBuaXNsLiBCaWJlbmR1bSB1dCB0cmlzdGlxdWUgZXQgZWdlc3RhcyBxdWlzIGlwc3VtIHN1c3BlbmRpc3NlIHVsdHJpY2VzLiBWaXZlcnJhIGlwc3VtIG51bmMgYWxpcXVldCBi","aWJlbmR1bSBlbmltIGZhY2lsaXNpcyBncmF2aWRhIG5lcXVlLiBDb25zZWN0ZXR1ciBhZGlwaXNjaW5nIGVsaXQgdXQgYWxpcXVhbSBwdXJ1cyBzaXQgYW1ldCBsdWN0dXMuIEVyYXQgdmVsaXQgc2NlbG","VyaXNxdWUgaW4gZGljdHVtIG5vbiBjb25zZWN0ZXR1ciBhIGVyYXQuIERpYW0gc29sbGljaXR1ZGluIHRlbXBvciBpZCBldSBuaXNsIG51bmMgbWkgaXBzdW0uIFJpc3VzIHF1aXMgdmFyaXVzIHF1YW0gcXVpc3F1ZSBpZCBkaWFtIHZlbCBxdWFtIGV","sZW1lbnR1bS4gUG9zdWVyZSBsb3JlbSBpcHN1bSBkb2xvciBzaXQgYW1ldCBjb25zZWN0ZXR1ci4gVWxsYW1jb3JwZXIgbW9yYmkgdGluY2lkdW50IG9ybmFyZSBtYXNzYS4gUXVhbSBhZGlwaXNjaW5nIHZpdGFlIHByb2luIHNhZ2l0dGlzIG5pc2wgcmhvbmN1cy4gRXUgY29uc2VxdWF0IGFjIGZlbGlzIGRvbmVjIGV0IG9kaW8gcGVsbGVudGVzcX","VlIGRpYW0gdm9sdXRwYXQuIEV0IG1hZ25pcyBkaXMgcGFydHVyaWVudCBtb250ZXMgbmFzY2V0dXIuIEFsaXF1YW0gbWFsZXN1YWRhIGJpYmVuZHVtIGFyY3Ugdml0YWUuIEluIG51bGxhIHBvc3VlcmUgc29sbGljaXR1ZGluIGFsaXF1YW0u"] blist = ["YzNSbmMyUnlaMlJoWm1kbVJsZEdWMFJFUkVaWFpIZG1Da1pGUmtWSFptUmxaM0puUmtWR1JVZG1aR1ZuY21kemR3cEdSVVpGUjJaa1pXZHlaM04zUmtSRlIwWkhaM05uWkdnS1pXZHlaMFpIVjBaRVJVZEdSMmR6WjJSb1JuTjNSa1JGQ25KblpHVmxSMFpIWjNObmMyVmxSMFpIWjNOblpHaEdjd3BuYzJka2FFVkdSVWRtWkdWbmNrWkdaM05uWkdoeVoyUUtaR1ZuY2taR1ozTm5aR2h5WjJSbFpVZEdSMmRuWkdoeUNtUm9SVVpGUjJaeloyUm9Sbk4zUmtSRlpHZG5kMFpFUlFweVoyUmxaVWRHUjJkelozTmxaVWRHUjJkeloyUm9Sbk1LWjNOblpHaEZSa1ZIWm1SbFozSkdSbWR6WjJSb2NtZGtDbkpuWkdWbFIwWkhaM05uYzJWbFIwWkhaM05uWkdoR2N3cG5jMmRrYUVWR1JVZG1aR1ZuY2taR1ozTm5aR2h5WjJRS1pHVm5ja1pHWjNOblpHaHlaMlJsWlVkR1IyZG5aR2h5Q21Sb1JVWkZSMlp6WjJSb1JuTjNSa1JGWkdkbmQwWkVSUXB5WjJSbFpVZEdSMmR6WjNObFpVZEdSMmR6WjJSb1JuTUtaM05uWkdoRlJrVkhabVJsWjNKR1JtZHpaMlJvY21ka0NtZHpaMlJvY21ka1pXVkhSa2RuYzJka2FFWnpkMFpFUlFweVoyUmxaVWRHUjJkeloyUm9aM05uWkdoR2MzZEdSRVVLY21ka1pXVkhSa2RsWlVkR1IyZHpaMlJvUm5OM1JrUkZDbkpuWkdWbFIwWkhaM05uWkdoRlJrVkhabVJsWjNKR1JncEVZWGRuUTFSR2Uwd3pORkpPWDFRd1gwUXpVRXd3V1gwS2NtZGtaV1ZIUmtkbmMyZGthRVZHUlVkSFJrZG5jMmRrQ25KblpHVmxSMFpIWjNOblpHaEhjMmRrYUVaemQwWkVSUXB5WjJSbFpVZEdSMmR6WjNObFpVZEdSMmR6WjJSb1JuTUtaM05uWkdoRlJrVkhabVJsWjNKR1JtZHpaMlJvY21ka0NtUmxaM0pHUm1keloyUm9jbWRrWldWSFJrZG5aMlJvY2dwa2FFVkdSVWRtYzJka2FFWnpkMFpFUldSblozZEdSRVVLWm1SbFozSkdSbWR6WjJSb2NtZGtaV1ZIUmtkblJVWkZDbVprWldkeVJrWm5jMmRrYUhKblpHVmxhRVp6ZDBaRVJRcHlaMlJsWlVkR1IyZHpaM05sWlVkR1IyZHpaMlJvUm5NS1ozTm5aR2hGUmtWSFptUmxaM0pHUm1keloyUm9jbWRrQ21SbFozSkdSbWR6WjJSb2NtZGtaV1ZIUmtkbloyUm9jZ3BrYUVWR1JVZG1jMmRrYUVaemQwWkVSV1JuWjNkR1JFVUtjbWRrWldWSFJrZG5jMmR6WldWSFJrZG5jMmRrYUVaekNtZHpaMlJvUlVaRlIyWmtaV2R5UmtabmMyZGthSEpuWkFweVoyUmxaVWRHUjJkelozTmxaVWRHUjJkeloyUm9Sbk1LWjNOblpHaEZSa1ZIWm1SbFozSkdSbWR6WjJSb2NtZGtDbVJsWjNKR1JtZHpaMlJvY21ka1pXVkhSa2RuWjJSb2NncGthRVZHUlVkbWMyZGthRVp6ZDBaRVJXUm5aM2RHUkVVS2NtZGtaV1ZIUmtkbmMyZHpaV1ZIUmtkbmMyZGthRVp6Q21keloyUm9SVVpGUjJaa1pXZHlSa1puYzJka2FISm5aQXBrWldkeVJrWm5jMmRrYUhKblpHVmxSMFpIWjJka2FISUtaR2hGUmtWSFpuTm5aR2hHYzNkR1JFVmtaMmQzUmtSRg=="] @client.event async def on_message(message): if message.author == client.user: return if message.content.startswith('Yo') or message.content.startswith('yo'): await message.channel.send(blist[ord(mlist[2][12])-70][ord(klist[1][1])-112:]) client.run('BOT_ID')
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/DawgCTF/2023/rev/DM_the_bot2/bot.py
ctfs/DawgCTF/2023/rev/DM_the_bot2/bot.py
#BY: J4NU5 import discord STRING = 4 START = 22 STOP = 58 if __name__ == "__main__": client = discord.Client(intents=discord.Intents.default()) @client.event async def on_ready(): print('We have logged in as {0.user}'.format(client)) msglist = ["TG9yZW0gaXBzdW0gZG9sb3Igc2l0IGFtZXQsIGNvbnNlY3RldHVyIGFkaX","Bpc2NpbmcgZWxpdCwgc2VkIGRvIGVpdXNtb2QgdGVtcG9yIGluY2lkaWR1bnQgdXQgbGFib3JlIGV0IGRvbG9yZSBtYWduYSBhbGlxdWEuIFVybmEgY29uZGltZW50dW0gbWF0dGlzIHBlbGxlbnRlc3F1ZSBpZCBuaWJoIHRvcnRvciBpZCBhbGlxdWV0LiBGYW==","NpbGlzaXMgbWFnbmEgZXRpYW0gdGVtcG9yIG9yY2kgZXUuIFNhcGllbiBldCBsaWd1bGEgdWxsYW1jb3JwZXIgbWFsZXN1YWRhLiBUcmlzdGlxdWUgbnVsbGE","gYWxpcXVldCBlbmltIHRvcnRvciBhdC4gUXVpcyByaXN1cyBzZWQgdnVscHV0YXRlIG9kaW8uIFNhZ2l0dGlzIGFsaXF1YW0gbWFsZXN1YWRhIGJpYmVuZHVt","IGFyY3Ugdml0YWUgZWxlbWRGF3Z0NURns1dDR0MWNfMHJfZHluNG0xYz99VudHVtIGN1cmFiaXR1ci4gSGFiaXRhc3NlIHBsYXRlYSBkaWN0dW1zdCBxdW=","lzcXVlIHNhZ2l0dGlzIHB1cnVzIHNpdCBhbWV0LiBQdXJ1cyBncmF2aWRhIHF1aXMgYmxhbmRpdCB0dXJwaXMgY3Vyc3VzIGluIGhhYyBoYWJpdGFzc2UuIFZvbHV0cGF0IGFjIHRpbmNpZHVudCB2aXRhZSBzZW1wZXIuIFF1YW0gZWxlbWVudHVtIHB1b==","HZpbmFyIGV0aWFtIG5vbiBxdWFtIGxhY3VzLiBBbWV0IHRlbGx1cyBjcmFzIGFkaXBpc2NpbmcgZW5pbSBldSB0dXJwaXMgZWdlc3Rhcy4KCkZldWdpYXQgbmlzbCBwcmV0aXVtIGZ1c2NlIGlkIHZlbGl0IHV0IHRvcnRvciBwcmV0aXVtIHZpdmVycmEuIEVuaW0gZGlhbSB2dWxwdXRhdGUgdXQgcGhhcmV0cmEgc2l0IGFtZ","XQuIEZldWdpYXQgcHJldGl1bSBuaWJoIGlwc3VtIGNvbnNlcXVhdCBuaXNsLiBCaWJlbmR1bSB1dCB0cmlzdGlxdWUgZXQgZWdlc3RhcyBxdWlzIGlwc3VtIHN1c3BlbmRpc3NlIHVsdHJpY2VzLiBWaXZlcnJhIGlwc3VtIG51bmMgYWxpcXVldCBi","aWJlbmR1bSBlbmltIGZhY2lsaXNpcyBncmF2aWRhIG5lcXVlLiBDb25zZWN0ZXR1ciBhZGlwaXNjaW5nIGVsaXQgdXQgYWxpcXVhbSBwdXJ1cyBzaXQgYW1ldCBsdWN0dXMuIEVyYXQgdmVsaXQgc2NlbG","VyaXNxdWUgaW4gZGljdHVtIG5vbiBjb25zZWN0ZXR1ciBhIGVyYXQuIERpYW0gc29sbGljaXR1ZGluIHRlbXBvciBpZCBldSBuaXNsIG51bmMgbWkgaXBzdW0uIFJpc3VzIHF1aXMgdmFyaXVzIHF1YW0gcXVpc3F1ZSBpZCBkaWFtIHZlbCBxdWFtIGV","sZW1lbnR1bS4gUG9zdWVyZSBsb3JlbSBpcHN1bSBkb2xvciBzaXQgYW1ldCBjb25zZWN0ZXR1ci4gVWxsYW1jb3JwZXIgbW9yYmkgdGluY2lkdW50IG9ybmFyZSBtYXNzYS4gUXVhbSBhZGlwaXNjaW5nIHZpdGFlIHByb2luIHNhZ2l0dGlzIG5pc2wgcmhvbmN1cy4gRXUgY29uc2VxdWF0IGFjIGZlbGlzIGRvbmVjIGV0IG9kaW8gcGVsbGVudGVzcX","VlIGRpYW0gdm9sdXRwYXQuIEV0IG1hZ25pcyBkaXMgcGFydHVyaWVudCBtb250ZXMgbmFzY2V0dXIuIEFsaXF1YW0gbWFsZXN1YWRhIGJpYmVuZHVtIGFyY3Ugdml0YWUuIEluIG51bGxhIHBvc3VlcmUgc29sbGljaXR1ZGluIGFsaXF1YW0u"] @client.event async def on_message(message): if message.author == client.user: return if message.content.startswith('hello') or message.content.startswith('Hello') or message.content.startswith('hi') or message.content.startswith('Hi'): await message.channel.send(msglist[STRING][START:STOP]) client.run('THIS_SHOULD_PROBABLY_BE_A_PROPER_BOT_ID')
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/DawgCTF/2025/crypto/The_MAC_FAC/server.py
ctfs/DawgCTF/2025/crypto/The_MAC_FAC/server.py
#!/usr/local/bin/python3 from Crypto.Cipher import AES from Crypto.Util.strxor import * from Crypto.Util.number import * from Crypto.Util.Padding import * from secret import flag, xor_key, mac_key, admin_iv, admin_phrase import os banner = """ Welcome to the MAC FAC(tory). Here you can request prototype my secure MAC generation algorithm. I know no one can break it so I hid my flag inside the admin panel, but only I can access it. Have fun! """ menu1 = """ [1] - Generate a MAC [2] - Verify a MAC [3] - View MAC Logs [4] - View Admin Panel [5] - Exit """ admin_banner = """ There's no way you got in! You have to be cheating this bug will be reported and I will return stronger! """ + flag def xor(data: bytes, key: bytes) -> bytes: #Installing pwntools in docker was giving me issues so I have to port over xor from strxor repeated_key = (key * (len(data) // len(key) + 1))[:len(data)] return strxor(data, repeated_key) assert(len(mac_key) == 16) assert(len(xor_key) == 16) logs = [] def CBC_MAC(msg, iv): cipher = AES.new(mac_key, AES.MODE_CBC, iv) # Encrypt with CBC mode padded = pad(msg, 16) # Pad the message tag = cipher.encrypt(padded)[-16:] # only return the last block as the tag msg_enc, iv_enc = encrypt_logs(padded, iv) logs.append((f"User generated a MAC (msg={msg_enc.hex()}, IV={iv_enc.hex()}")) return tag def encrypt_logs(msg, iv): return (xor(msg, xor_key), xor(iv, xor_key))#Encrypts logs so users can't see other people's IVs and Messages def verify(msg, iv, tag): cipher = AES.new(mac_key, AES.MODE_CBC, iv) padded = pad(msg, 16) candidate = cipher.encrypt(padded)[-16:] return candidate == tag def view_logs(): print("\n".join(logs)) return def setup_admin(): tag = CBC_MAC(admin_phrase, admin_iv) return tag def verify_admin(msg, iv, user_tag, admin_tag): if msg == admin_phrase: print("This admin phrase can only be used once!") return tag = CBC_MAC(msg, iv) if (tag != user_tag): #Ensure msg and iv yield the provided tag print("Computed: ", tag.hex()) print("Provided: ", user_tag.hex()) print("Computed MAC Tag doesn't match provided tag") return else: if (tag == admin_tag): print(admin_banner) return else: print("Tag is invalid") def run(): admin_tag = setup_admin() print(banner) while True: print(menu1) usr_input = input("> ") if usr_input == "1": msg = input("Message: ") print(msg) if (len(msg.strip()) == 0): print("Please input a valid message") continue iv = bytes.fromhex(input("IV (in hex): ").strip()) if (len(iv) != 16): print("The IV has to be exactly 16 bytes") continue tag = CBC_MAC(msg.encode(), iv) print("The MAC Tag for your message is: ", tag.hex()) continue if usr_input == "2": msg = input("Message: ") if (len(msg.strip()) == 0): print("Please input a valid message") continue iv = bytes.fromhex(input("IV (in hex): ").strip()) if (len(iv) != 16): print("The IV has to be exactly 16 bytes") continue tag = bytes.fromhex(input("Tag (in hex): ").strip()) if (len(tag) != 16): print("The MAC has to be exactly 16 bytes") continue valid = verify(msg.encode(), iv, tag) if valid: print("The tag was valid!") else: print("The tag was invalid!") continue if usr_input == "3": view_logs() continue if usr_input == "4": msg = input("Admin passphrase: ") if (len(msg.strip()) == 0): print("Please input a valid message") continue iv = bytes.fromhex(input("IV (in hex): ").strip()) if (len(iv) != 16): print("The IV has to be exactly 16 bytes") continue tag = bytes.fromhex(input("Tag (in hex): ").strip()) if (len(tag) != 16): print("The MAC has to be exactly 16 bytes") continue verify_admin(msg.encode(), iv, tag, admin_tag) continue if usr_input == "5": break exit() if __name__ == '__main__': run()
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/DawgCTF/2025/crypto/Jokesmith/server.py
ctfs/DawgCTF/2025/crypto/Jokesmith/server.py
#!/usr/local/bin/python3 from secret import flag from Crypto.Util.number import * jokes = [ "Why did the prime break up with the modulus? Because it wasn't factoring in its feelings", "Why did the cryptographer bring RSA to the dance? Because it had great curves — wait, no, wrong cryptosystem", "Why did the CTF player cross the road? To get to the " + flag, ] def hideFlag(message): hidden = "" start = False for c in message: if (start): hidden += "X" else: hidden += c if c == "{": start = True if (start): hidden = hidden[:-1] + "}" return hidden def run(): print("You think you're funny? I got a few jokes of my own, tell me a joke and I'll tell you mine") transcript = [] for i in range(3): joke = input("Tell me a joke: ") funny = bytes_to_long(joke.encode()) % 2 if (not funny): print("Really? That's it? Come back with some better material") exit() else: transcript.append(joke) print("Ha! That was pretty funny! Here's one of my own") print(hideFlag(jokes[i])) transcript.append(jokes[i]) print("Here is our jokes! Show it to a friend to make them laugh! I better encrypt it though in case I said something private") m = "\n".join(transcript) p = getPrime(512) q = getPrime(512) N = p * q e = 3 c = pow(bytes_to_long(m.encode()), e, N) print("c =", c) print("N =", N) print("e =", e) if __name__ == '__main__': run()
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/DawgCTF/2025/crypto/Guess_Me_If_You_Can/server.py
ctfs/DawgCTF/2025/crypto/Guess_Me_If_You_Can/server.py
#!/usr/local/bin/python3 from Crypto.Util.number import * from secret import flag, init, N, a, b seed = init state = seed current_user = (None, None) accounts = [] notes = dict() menu1 = '''[1] - Register [2] - Login [3] - Manage Notes [4] - List Users [5] - Exit ''' menu2 = '''[1] - Register [2] - Logout [3] - Manage Notes [4] - List Users [5] - Exit ''' menu3 = '''[1] - Add Note [2] - Remove Note [3] - Return to Menu ''' def getNext(state): state = (a * state + b) % N return state def make_account(name, password): global accounts global notes accounts.append((name, password)) notes[name] = [] def register(name): for account in accounts: if name == account[0]: print("An account with this name already exists") raise ValueError(f"User '{name}' already exists. Please choose a different username") global state state = getNext(state) make_account(name, state) return state def list_users(): print("Here are all list of all users currently registered.") for i in range(len(accounts)): print("Account [" + str(i) + "] - ", accounts[i][0]) def login(name, password): for account in accounts: if account[0] == name and str(account[1]) == str(password): global current_user current_user = account print() print(f"Succesfully Logged in as {current_user[0]}") return print("Invalid username or password") def logout(): global current_user current_user = (None, None) def get_menu_choice(minimum, maximum, prompt, input_func=input): choice = "" while(True): choice = input_func(prompt) try: choice = int(choice) if (choice < minimum or choice > maximum): print("Invalid Choice. Try again") break except: print("Error parsing your input. Try again") return choice def view_notes(user): print(f"Here are the notes for user '{user}'") current_notes = notes[user] if (len(current_notes) == 0): print("This user currently has no notes!") return i = 1 for value in current_notes: print(f"Note {i}: {value}") i += 1 return def add_note(user, message): if (len(message) == 0): print("Can't add note with an empty message") return current_notes = notes[user] current_notes.append(message) notes[user] = current_notes return def remove_note(user, index): current_notes = notes[user] del current_notes[index] return def is_logged_in(): global current_user if (current_user[0] == None and current_user[1] == None): return False return True def handle_note(user, input_func=input): global notes view_notes(user) print() while(True): print(menu3) choice = get_menu_choice(1, 3, "> ") if choice == 1: msg = input_func("What message do you want to save? ") add_note(user, msg) break elif choice == 2: num_notes = len(notes[user]) if num_notes == 0: print("This user currently has no notes to remove.") else: note_choice = get_menu_choice(1, num_notes, f"Which note do you want to remove? (1 - {num_notes}) ") remove_note(user, note_choice - 1) break elif choice == 3: break def initAdmin(): register("admin") add_note("admin", flag) def run(input_func=input): global notes global accounts initAdmin() print("Welcome to the state of the art secure note taking app, Global Content Library . You can make accounts, see active users, store and view private information. Everything you can ask for. You can rest well knowing your password is securely generated, just make sure you don't lose it. That's the only way to access your account!") while(True): print() if is_logged_in(): print(menu2) else: print(menu1) choice = get_menu_choice(1, 5, "> ") if choice == 1: # Register name = input_func("Enter your name: ") try: password = register(name) except: continue print("Your secret password is: ", password, "\nPlease don't lose it!!") if choice == 2: if (current_user[0] == None and current_user[1] == None): name = input_func("Enter your name: ") password = input_func("Enter your password: ") login(name, password) else: logout() if choice == 3: if (current_user[0] == None): print("You must be logged in to use this feature") else: handle_note(current_user[0]) if choice == 4: list_users() if choice == 5:#Exit print("See you later!") exit() if __name__ == '__main__': run()
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/DawgCTF/2025/crypto/Cantors_Pairadox/chall.py
ctfs/DawgCTF/2025/crypto/Cantors_Pairadox/chall.py
from sage.all import sqrt, floor from secret import flag def getTriNumber(n): return n * (n + 1) // 2 # Ensure integer division def pair(n1, n2): S = n1 + n2 return getTriNumber(S) + n2 def pair_array(arr): result = [] for i in range(0, len(arr), 2): result.append(pair(arr[i], arr[i + 1])) return result def pad_to_power_of_two(arr): result = arr n = len(result) while (n & (n - 1)) != 0: result.append(0) n += 1 return result flag = [ord(f) for f in flag] flag = pad_to_power_of_two(flag) temp = flag for i in range(6): temp = pair_array(temp) print("Encoded:", temp)
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/DawgCTF/2025/crypto/Baby_RSA_1/source.py
ctfs/DawgCTF/2025/crypto/Baby_RSA_1/source.py
from Crypto.Util.number import * from sage.all import randint p = getPrime(512) q = getPrime(512) N = p * q e = 0x10001 m = bytes_to_long(b"DawgCTF{fake_flag}") c = pow(m, e, N) print("N =", N) print("e =", e) print("ct =", c) print() a = randint(0, 2**100) b = randint(0, 2**100) c = randint(0, 2**100) d = randint(0, 2**100) x = a * p + b * q y = c * p + d * q print("a =", a) print("b =", b) print("c =", c) print("d =", d) print() print("x =", x) print("y =", y)
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/DawgCTF/2025/crypto/Baby_RSA_2/chall.py
ctfs/DawgCTF/2025/crypto/Baby_RSA_2/chall.py
from Crypto.Util.number import * from secret import flag # This is my stuff! Don't look at it p = getPrime(512) q = getPrime(512) N = p * q e_priv = 0x10001 phi = (p - 1) * (q - 1) d_priv = inverse(e_priv, phi) m = bytes_to_long(flag) c = pow(m, e_priv, N) # This is your stuff! e_pub = getPrime(16) d_pub = inverse(e_pub, phi) print(f"e = {e_pub}") print(f"d = {d_pub}") print(f"N = {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/HeroCTF/2021/steg/RansomWTF/scramble.py
ctfs/HeroCTF/2021/steg/RansomWTF/scramble.py
import numpy as np import cv2 import sys """ EGGMAN'S RANSOMWARE. I LIKE EGGS, ESPECIALLY SCRAMBLED ONES. LET'S SEE HOW YOU LIKE YOUR SCRAMBLED PICTURES ! """ def scramble(image): # 420 EGGS ! np.random.seed(420) # Image dimensions : 1280x720 to_hide = cv2.imread(image) to_hide_array = np.asarray(to_hide) for i in range(to_hide_array.shape[0]): np.random.shuffle(to_hide_array[i]) gray = cv2.cvtColor(to_hide_array, cv2.COLOR_BGR2GRAY) cv2.imwrite('challenge.jpg', gray) print('EGGMAN IS DONE SCRAMBLING') # You can totally scramble images as well, just use the script. def main(): if len(sys.argv) != 2: print('Usage : {} [FILENAME]'.format(sys.argv[1])) exit(1) scramble(sys.argv[1]) 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/HeroCTF/2021/crypto/ExtractMyBlocks/challenge.py
ctfs/HeroCTF/2021/crypto/ExtractMyBlocks/challenge.py
#!/usr/bin/env python3 from os import getenv from Crypto.Cipher import AES BLOCK_SIZE = 16 FLAG = getenv("FLAG") KEY = getenv("KEY") padding = lambda msg: msg + "0" * (BLOCK_SIZE - len(msg) % BLOCK_SIZE) encrypt = lambda plain: AES.new(KEY, AES.MODE_ECB).encrypt(plain).hex() print("[SUPPORT] Password Reset") account_id = input("Please enter your account ID : ") msg = f""" Welcome back {account_id} ! Your password : {FLAG} Regards """ print(encrypt(padding(msg)))
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/HeroCTF/2021/crypto/h4XOR/xor.py
ctfs/HeroCTF/2021/crypto/h4XOR/xor.py
#!/usr/bin/env python3 from os import urandom from random import randint from pwn import xor input_img = open("flag.png", "rb").read() outpout_img = open("flag.png.enc", "wb") key = urandom(8) + bytes([randint(0, 9)]) outpout_img.write(xor(input_img, key))
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/HeroCTF/2024/misc/Free_Shell/free_shell.py
ctfs/HeroCTF/2024/misc/Free_Shell/free_shell.py
#!/usr/bin/env python3 import os import subprocess print("Welcome to the free shell service!") print("Your goal is to obtain a shell.") command = [ "/bin/sh", input("Choose param: "), os.urandom(32).hex(), os.urandom(32).hex(), os.urandom(32).hex() ] subprocess.run(command)
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/HeroCTF/2023/crypto/Lossy/chall.py
ctfs/HeroCTF/2023/crypto/Lossy/chall.py
from cryptography.hazmat.primitives.ciphers.algorithms import AES from cryptography.hazmat.primitives.ciphers import Cipher, modes from secret import flag, key assert len(flag) == 32 assert len(key) == 16 # should be equivalent to .hex() (probably) to_hex = lambda x: "".join(hex(k)[2:] for k in x) def encrypt(pt, key): aes = Cipher(AES(key), modes.ECB()) enc = aes.encryptor() ct = enc.update(pt) ct += enc.finalize() return ct ct = to_hex(encrypt(flag, key)) key = to_hex(key) print(f'{ct = }') print(f'{key = }') # ct = '17c69a812e76d90e455a346c49e22fb6487d9245b3a90af42e67c7b7c3f2823' # key = 'b5295cd71d2f7cedb377c2ab6cb93'
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/HeroCTF/2023/crypto/Hyper_Loop/hyper_loop.py
ctfs/HeroCTF/2023/crypto/Hyper_Loop/hyper_loop.py
from os import urandom flag = bytearray(b"Hero{????????????}") assert len(flag) == 18 for _ in range(32): for i, c in enumerate(urandom(6) * 3): flag[i] = flag[i] ^ c print(f"{flag = }") """ $ python3 hyper_loop.py flag = bytearray(b'\x05p\x07MS\xfd4eFPw\xf9}%\x05\x03\x19\xe8') """
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/HeroCTF/2023/crypto/Futile/chall.py
ctfs/HeroCTF/2023/crypto/Futile/chall.py
#!/usr/bin/env python from pylfsr import LFSR from functools import reduce import os flag = os.environ.get('FLAG','Hero{fake_flag}').encode() def binl2int(l: list) -> int: return reduce(lambda x,y: 2*x+y, l) def lfsr() -> LFSR: return LFSR(fpoly=[8,6,5,4], initstate='random') def get_uint8() -> int: return binl2int(lfsr().runKCycle(8)) def mask(flag: bytes) -> str: return bytearray(f ^ get_uint8() for f in flag).hex() while True: try: input('Hero{' + mask(flag[5:-1]) + '}\n') except: pass
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/HeroCTF/2023/crypto/Uniform/chall.py
ctfs/HeroCTF/2023/crypto/Uniform/chall.py
#!/usr/bin/env python import random import os # TODO: xanhacks told me that this was "too unoriginal" and # that I should change it, lets see how he likes this... # guess = lambda: random.getrandbits(32) guess = lambda: random.uniform(0, 2**32-1) for _ in range(624): print(guess()) secret = str(guess()) if input('> ').strip() == secret: print(os.environ.get('FLAG', 'Hero{fake_flag}')) else: print('Nope! It was:', secret)
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/HeroCTF/2023/web/Blogodogo_12/config.py
ctfs/HeroCTF/2023/web/Blogodogo_12/config.py
from flask_sqlalchemy import SQLAlchemy from flask_login import LoginManager from redis import Redis from secrets import token_hex from os import getenv db = SQLAlchemy() login_manager = LoginManager() redis_client = Redis( host=getenv("REDIS_HOST"), port=int(getenv("REDIS_PORT")), ) class TestConfig: DEBUG = True DEVELOPMENT = True BLOG_NAME = "Blogodogo" REFERRAL_CODE = getenv("REFERRAL_CODE") # SERVER_NAME = "localhost.localdomain" SECRET_KEY = token_hex() SESSION_COOKIE_HTTPONLY = True SESSION_COOKIE_SECURE = False SQLALCHEMY_DATABASE_URI = "sqlite:///:memory:" SQLALCHEMY_TRACK_MODIFICATIONS = False
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/HeroCTF/2023/web/Blogodogo_12/app.py
ctfs/HeroCTF/2023/web/Blogodogo_12/app.py
#!/usr/bin/env python3 from flask import Flask, request, redirect, url_for, flash import lorem from sqlalchemy.exc import IntegrityError import os import random from secrets import token_hex from datetime import datetime from config import TestConfig, db, login_manager from src.routes import bp_routes from src.models import Authors, Posts from src.utils import generate_hash def create_app(): app = Flask(__name__) app.config.from_object(TestConfig) login_manager.init_app(app) db.init_app(app) app.register_blueprint(bp_routes) with app.app_context(): db.create_all() @login_manager.user_loader def load_user(author_id): return Authors.query.get(int(author_id)) @login_manager.unauthorized_handler def unauthorized_callback(): flash("You need to be authenticated.", "warning") return redirect(url_for('bp_routes.login')) # ... SKIPPED db.session.commit() return app if __name__ == "__main__": app = create_app() app.run(host="0.0.0.0", port=5000)
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/HeroCTF/2023/web/Blogodogo_12/src/models.py
ctfs/HeroCTF/2023/web/Blogodogo_12/src/models.py
from flask_login import UserMixin from werkzeug.security import generate_password_hash, check_password_hash from datetime import datetime from config import db class Authors(db.Model, UserMixin): __tablename__ = "authors" id = db.Column(db.Integer, primary_key=True) username = db.Column(db.String(32), unique=True, nullable=False) password_hash = db.Column(db.String(128), unique=False, nullable=False) register_date = db.Column(db.DateTime(), unique=False, default=datetime.now()) admin = db.Column(db.Boolean, default=False) url = db.Column(db.String(128), unique=False, nullable=True, default="") avatar = db.Column(db.String(64), unique=False, nullable=True, default=None) @property def password(self): raise AttributeError('Password is not readable.') @password.setter def password(self, password): self.password_hash = generate_password_hash(password) def verify_password(self, password): return check_password_hash(self.password_hash, password) class Posts(db.Model): __tablename__ = "posts" id = db.Column(db.Integer, primary_key=True) title = db.Column(db.String(128), nullable=False, unique=False) subtitle = db.Column(db.String(128), nullable=False, unique=False) slug = db.Column(db.String(64), nullable=False, unique=True) content = db.Column(db.String(512), nullable=False, unique=False) draft = db.Column(db.Boolean, default=True) hash_preview = db.Column(db.String(64), nullable=False, unique=True) created_at = db.Column(db.DateTime(), default=datetime.utcnow) author_id = db.Column(db.Integer, db.ForeignKey("authors.id"))
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/HeroCTF/2023/web/Blogodogo_12/src/utils.py
ctfs/HeroCTF/2023/web/Blogodogo_12/src/utils.py
from datetime import datetime from random import seed, randbytes def generate_hash(timestamp=None): """Generate hash for post preview.""" if timestamp: seed(timestamp) else: seed(int(datetime.now().timestamp())) return randbytes(32).hex()
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/HeroCTF/2023/web/Blogodogo_12/src/__init__.py
ctfs/HeroCTF/2023/web/Blogodogo_12/src/__init__.py
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/HeroCTF/2023/web/Blogodogo_12/src/routes.py
ctfs/HeroCTF/2023/web/Blogodogo_12/src/routes.py
#!/usr/bin/env python3 from flask import ( Blueprint, render_template, redirect, current_app, flash, url_for, request ) from flask_login import ( login_user, logout_user, login_required, current_user ) from sqlalchemy import and_ import re import os import subprocess from config import db, redis_client from src.utils import generate_hash from src.models import Authors, Posts from src.forms import RegisterForm, LoginForm, EditProfileForm, AddPostForm bp_routes = Blueprint("bp_routes", __name__) @bp_routes.route("/", methods=["GET"]) def index(): register_number = Authors.query.count() posts = Posts.query.filter(Posts.draft.is_(False)).order_by(Posts.created_at).limit(5).all() for post in posts: post.author = Authors.query.filter_by(id=post.author_id).first() return render_template("pages/index.html", title="Index", posts=posts, register_number=register_number) @bp_routes.route("/about", methods=["GET"]) def about(): return render_template("pages/about.html", title="My super blog - About") @bp_routes.route("/login", methods=["GET", "POST"]) def login(): form = LoginForm() if form.validate_on_submit(): author = Authors.query.filter_by(username=form.username.data).first() if author and author.verify_password(form.password.data): login_user(author, remember=True) if author.username == "admin": flash(os.getenv('FLAG_2'), "success") else: flash('Logged in successfully.', "success") return redirect(url_for('bp_routes.index')) flash('Wrong username or password.', "warning") return render_template("pages/login.html", title="Login", form=form) @bp_routes.route("/register", methods=["GET", "POST"]) def register(): form = RegisterForm() if form.validate_on_submit(): if form.referral_code.data != current_app.config['REFERRAL_CODE']: flash('Wrong referral code.', "warning") return render_template("pages/register.html", title="Register", form=form) author = Authors( username=form.username.data, password=form.password.data ) db.session.add(author) db.session.commit() login_user(author, remember=True) flash("Author registered successfully.", "success") return redirect(url_for('bp_routes.index')) return render_template("pages/register.html", title="Register", form=form) @bp_routes.route("/logout", methods=["GET"]) @login_required def logout(): logout_user() flash('Author logged out successfully.', "success") return redirect(url_for('bp_routes.index')) @bp_routes.route("/profile", methods=["GET", "POST"]) @login_required def profile(): form = EditProfileForm() if form.validate_on_submit(): author = Authors.query.filter_by(id=current_user.id).first() _username = form.username.data _new_password = form.new_password.data _new_password_confirm = form.new_password_confirm.data _url = form.url.data _avatar = form.avatar.data if author.username != _username and Authors.query.filter_by(username=_username).first(): flash("Username already exists.", "warning") return render_template("pages/profile.html", title="My profile", form=form) if _new_password and _new_password != _new_password_confirm: flash("The two passwords do not match", "warning") return render_template("pages/profile.html", title="My profile", form=form) author.username = _username author.password = _new_password if _url: author.url = _url if _avatar: author.avatar = _avatar db.session.add(author) db.session.commit() flash("Profile successfully edited.", "success") key_name_url = "profile_" + current_user.username.lower() + "_url" key_name_username = "profile_" + current_user.username.lower() + "_username" cache_url, cache_username = redis_client.get(key_name_url), redis_client.get(key_name_username) if not cache_url or not cache_username: redis_client.set(key_name_username, current_user.username) redis_client.expire(key_name_username, 60) redis_client.set(key_name_url, current_user.url) redis_client.expire(key_name_url, 60) cache_url, cache_username = redis_client.get(key_name_url).decode(), redis_client.get(key_name_username).decode() return render_template("pages/profile.html", title="My profile", form=form, cache_url=cache_url, cache_username=cache_username) @bp_routes.route("/add", methods=["GET", "POST"]) @login_required def add_post(): form = AddPostForm() if form.validate_on_submit(): result = Posts.query.filter_by(slug=form.slug.data).first() if result: flash("Slug already exists.", "warning") return redirect(url_for('bp_routes.add_post')) post = Posts( title=form.title.data, subtitle=form.subtitle.data, slug=form.slug.data, content=form.content.data, draft=True, hash_preview=generate_hash(), author_id=current_user.id ) db.session.add(post) db.session.commit() flash("Post successfully added.", "success") return redirect(url_for('bp_routes.view_post', slug=post.slug)) return render_template("pages/add_post.html", title="Add a post", form=form) @bp_routes.route("/post/<string:slug>", methods=["GET"]) def view_post(slug): post = Posts.query.filter(Posts.slug == slug).first() if not post: flash("This post does not exists.", "warning") return redirect(url_for('bp_routes.index')) if post.draft and (not current_user.is_authenticated or post.author_id != current_user.id): flash("You cannot see draft of other users.", "warning") return redirect(url_for('bp_routes.index')) author = Authors.query.filter_by(id=post.author_id).first() return render_template("pages/post.html", title="View a post", post=post, author=author) @bp_routes.route("/post/report", methods=["POST"]) def report_post(): url = request.form.get("url", "") if not re.match("^http://localhost:5000/.*", url): flash("URL not valid, please match: ^http://localhost:5000/.*", "warning") return redirect(url_for('bp_routes.index')) subprocess.run(["node", "/app/bot/bot.js", url]) flash("Your request has been sent to an administrator!", "success") return redirect(url_for('bp_routes.index')) @bp_routes.route("/post/preview/<string:hash_preview>", methods=["GET"]) def preview_post(hash_preview): post = Posts.query.filter_by(hash_preview=hash_preview).first() if post: author = Authors.query.filter_by(id=post.author_id).first() return render_template("pages/post.html", title="Preview a post", post=post, author=author) flash("Unable to find the corresponding post.", "warning") return redirect(url_for('bp_routes.index')) @bp_routes.route("/author/<int:author_id>", methods=["GET"]) def view_author(author_id): author = Authors.query.filter_by(id=author_id).first() if author: posts = Posts.query.filter_by(author_id=author.id).all() return render_template("pages/author.html", title="Author profile", author=author, posts=posts) flash("Unable to find the corresponding author.", "warning") return redirect(url_for('bp_routes.index'))
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/HeroCTF/2023/web/Blogodogo_12/src/forms.py
ctfs/HeroCTF/2023/web/Blogodogo_12/src/forms.py
from flask_wtf import FlaskForm from wtforms import ( PasswordField, StringField, BooleanField, TextAreaField, FileField, SubmitField, ValidationError ) from wtforms.validators import DataRequired, EqualTo from src.models import Authors from re import search as re_search class RegisterForm(FlaskForm): username = StringField("Username", validators=[DataRequired()]) password = PasswordField( "Password", validators=[DataRequired(), EqualTo("confirm_password")] ) confirm_password = PasswordField("Confirm Password") referral_code = StringField("ReferralCode", validators=[DataRequired()]) submit = SubmitField("Register") def validate_username(self, field): if Authors.query.filter_by(username=field.data).first(): raise ValidationError("Username is already in use.") class LoginForm(FlaskForm): username = StringField("Username", validators=[DataRequired()]) password = PasswordField("Password", validators=[DataRequired()]) submit = SubmitField("Login") class EditProfileForm(FlaskForm): username = StringField("Username", validators=[DataRequired()]) old_password = PasswordField("Old password") new_password = PasswordField("New password", validators=[EqualTo("new_password_confirm")]) new_password_confirm = PasswordField("Confirm the new password") url = StringField("External link") avatar = FileField("Upload avatar") submit = SubmitField("Edit profile") class AddPostForm(FlaskForm): title = StringField("Title", validators=[DataRequired()]) subtitle = StringField("Subtitle", validators=[DataRequired()]) slug = StringField('Slug', validators=[DataRequired()]) content = TextAreaField("Content", validators=[DataRequired()]) submit = SubmitField("Add a post") def validate_slug(self, field): if not re_search(r"^[a-z0-9-]+$", field.data): raise validators.ValidationError('Invalid slug format.')
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/HeroCTF/2023/web/Simple_Notes/web/src/api.py
ctfs/HeroCTF/2023/web/Simple_Notes/web/src/api.py
from __main__ import app, secret, connect_db from flask import request, session, jsonify from datetime import datetime from uuid import uuid4 import jwt def auth_required(func): def verify(*args, **kwargs): if "logged" in session and "Authorization" in request.headers and request.headers["Authorization"]: token = request.headers["Authorization"].replace("Bearer ", "") error = 0 try: user = jwt.decode(token, secret, algorithms=["HS256"]) except: error = 1 if error: return jsonify({"error": "Invalid token!"}) else: return func(user["username"], *args, **kwargs) else: return jsonify({"error": "You must be authenticated!"}) verify.__name__ = func.__name__ return verify """ __ _ / / ____ ____ _(_)___ / / / __ \/ __ `/ / __ \ / /___/ /_/ / /_/ / / / / / /_____/\____/\__, /_/_/ /_/ /____/ """ @app.route("/api/login", methods=["POST"]) def api_login(): db = connect_db() cur = db.cursor() values = request.json if "username" in values and "password" in values and values["username"] and values["password"]: user = cur.execute("SELECT id FROM users WHERE username=? AND password=?", (values["username"], values["password"])) db.commit() user = user.fetchall() if len(user) == 1: session["username"] = values["username"] session["logged"] = 1 token = jwt.encode({"username": values["username"]}, secret, algorithm="HS256") return jsonify({"bearer": token}) else: res = jsonify({"error": "Invalid credentials!"}) res.status_code = 400 return res else: res = jsonify({"error": "Username and password can't be empty!"}) res.status_code = 400 return res """ ____ _ __ / __ \___ ____ _(_)____/ /____ _____ / /_/ / _ \/ __ `/ / ___/ __/ _ \/ ___/ / _, _/ __/ /_/ / (__ ) /_/ __/ / /_/ |_|\___/\__, /_/____/\__/\___/_/ /____/ """ @app.route("/api/register", methods=["POST"]) def api_register(): db = connect_db() cur = db.cursor() values = request.json if "username" in values and "password" in values and values["username"] and values["password"]: user = cur.execute("SELECT id FROM users WHERE username=?", (values["username"],)) db.commit() user = user.fetchall() if len(user) == 1: res = jsonify({"error": "Username already exist!"}) res.status_code = 400 return res else: cur.execute(f"INSERT INTO users (username, password) VALUES (?, ?)", (values["username"], values["password"])) db.commit() return jsonify({"success": "User created!"}) else: res = jsonify({"error": "Username and password can't be empty!"}) res.status_code = 400 return res """ ____ _____ __ / __ \_________ / __(_) /__ / /_/ / ___/ __ \/ /_/ / / _ \ / ____/ / / /_/ / __/ / / __/ /_/ /_/ \____/_/ /_/_/\___/ """ @app.route("/api/user/<string:user>", methods=["GET"]) @auth_required def api_note_list(username, user): if username != user: res = jsonify({"error": "Not authorized!"}) res.status_code = 403 return res db = connect_db() cur = db.cursor() notes = cur.execute("SELECT uuid, title, last_update FROM notes WHERE username=?", (username,)) db.commit() notes = notes.fetchall() return jsonify({"notes": notes}) """ ______ __ / ____/_______ ____ _/ /____ / / / ___/ _ \/ __ `/ __/ _ \ / /___/ / / __/ /_/ / /_/ __/ \____/_/ \___/\__,_/\__/\___/ """ @app.route("/api/user/<string:user>/create", methods=["POST"]) @auth_required def api_note_create(username, user): if username != user: res = jsonify({"error": "Not authorized!"}) res.status_code = 403 return res db = connect_db() cur = db.cursor() values = request.json if "name" in values and values["name"]: cur.execute(f"INSERT INTO notes (uuid, username, title, content, last_update) VALUES (?, ?, ?, ?, ?)", (str(uuid4()), username, values["name"], "", datetime.now().strftime("%c"))) db.commit() return jsonify({"success": "Note created!"}) else: res = jsonify({"error": "Name can't be empty!"}) res.status_code = 400 return res """ _ ___ | | / (_)__ _ __ | | / / / _ \ | /| / / | |/ / / __/ |/ |/ / |___/_/\___/|__/|__/ """ @app.route("/api/user/<string:user>/<string:uuid>", methods=["GET"]) @auth_required def api_note_get(username, user, uuid): if username != user: res = jsonify({"error": "Not authorized!"}) res.status_code = 403 return res db = connect_db() cur = db.cursor() notes = cur.execute("SELECT title, content FROM notes WHERE username=? AND uuid=?", (username, uuid)) db.commit() notes = notes.fetchall() if len(notes) == 1: return jsonify({ "title": notes[0][0], "content": notes[0][1] }) else: res = jsonify({"error": "Not authorized!"}) res.status_code = 403 return res """ ______ ___ __ / ____/___/ (_) /_ / __/ / __ / / __/ / /___/ /_/ / / /_ /_____/\__,_/_/\__/ """ @app.route("/api/user/<string:user>/<string:uuid>/edit", methods=["POST"]) @auth_required def api_note_edit(username, user, uuid): if username != user: res = jsonify({"error": "Not authorized!"}) res.status_code = 403 return res values = request.json if "title" in values and "content" in values: db = connect_db() cur = db.cursor() notes = cur.execute("SELECT title, content FROM notes WHERE username=? AND uuid=?", (username, uuid)) db.commit() notes = notes.fetchall() if len(notes) == 1: cur.execute(f"UPDATE notes SET title=?, content=?, last_update=? WHERE uuid=? AND username=?", (values["title"], values["content"], datetime.now().strftime("%c"), uuid, username)) db.commit() return jsonify({"success": "Note updated!"}) else: res = jsonify({"error": "Not authorized!"}) res.status_code = 403 return res else: res = jsonify({"error": "Title and content must be sent!"}) res.status_code = 400 return res
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/HeroCTF/2023/web/Simple_Notes/web/src/app.py
ctfs/HeroCTF/2023/web/Simple_Notes/web/src/app.py
from flask import Flask, request, redirect, session, render_template, jsonify, g from flask_cors import CORS from subprocess import run from os import urandom from re import match import sqlite3 # Init secret = urandom(32) app = Flask(__name__) # app.config["DEBUG"] = True app.config["SECRET_KEY"] = secret app.config["SESSION_COOKIE_SECURE"] = True app.config["SESSION_COOKIE_SAMESITE"] = "None" cors = CORS(app, resources={ r"/api/*": { "origins": ["null"] } }, allow_headers=[ "Authorization", "Content-Type" ], supports_credentials=True) # Database db_file = "sqlite.db" def connect_db(): db = getattr(g, '_database', None) if db is None: db = g._database = sqlite3.connect(db_file) return db @app.teardown_appcontext def close_connection(exception): db = getattr(g, '_database', None) if db is not None: db.close() # Handle 404 pages @app.errorhandler(404) def page_not_found(error): if "logged" in session: return redirect("/notes") else: return redirect("/login", 302) # API routes import api # Routes @app.route("/login", methods=["GET"]) def login(): if "logged" in session: return redirect("/notes") return render_template("login.html", title="Login") @app.route("/register", methods=["GET"]) def register(): if "logged" in session: return redirect("/notes") return render_template("register.html", title="Register") @app.route("/notes", methods=["GET"]) def notes(): if not "logged" in session: return redirect("/login") return render_template("notes.html", username=session["username"], title="Notes") @app.route("/notes/create", methods=["GET"]) def create(): if not "logged" in session: return redirect("/login") return render_template("create.html", username=session["username"], title="Create note") @app.route("/note/<string:uuid>", methods=["GET"]) def view(uuid): if not "logged" in session: return redirect("/login") return render_template("edit.html", username=session["username"], uuid=uuid, title="Edit note") @app.route("/logout", methods=["GET"]) def logout(): session.clear() r = request.args.get("r") if request.args.get("r") else "/login" return redirect(r) @app.route("/report", methods=["POST"]) def report(): url = request.form.get("url") if not match("^http(s)?://.*", url): return jsonify({"error": "The URL must match ^http(?)://.* !"}) else: run(["node", "/usr/app/bot/bot.js", url]) return jsonify({"success": "Your request has been sent to an administrator!"}) # Start if __name__ == "__main__": app.run(host="0.0.0.0", port=5000, ssl_context=("/usr/app/cert/cert.pem", "/usr/app/cert/key.pem"))
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/HeroCTF/2025/ppc/Whac_A_Mole/template.py
ctfs/HeroCTF/2025/ppc/Whac_A_Mole/template.py
from pwn import * # Adjust depending challenge adress HOST = "localhost" PORT = 8001 io = remote(HOST, PORT) while True: line = io.recvline() if b"IMAGE:" in line: # Read the base64 encoded image b64img = io.recvline().strip() log.info(f"Got image (length {len(b64img)})") # The server asks for answer io.recvuntil(b">> ") # TODO: process image and compute answer answer = 0 # Send back the answer io.sendline(str(answer).encode()) elif b"Wrong answer!" in line or b"Hero" in line: # Print the line and exit if it's an error or contains the flag print(line.decode().strip()) io.close() break else: log.info(line.decode().strip())
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/HeroCTF/2025/web/Revoked_Revenge/main.py
ctfs/HeroCTF/2025/web/Revoked_Revenge/main.py
import os import secrets import sqlite3 import time from functools import wraps import bcrypt import jwt from dotenv import load_dotenv from flask import ( Flask, flash, jsonify, make_response, redirect, render_template, request, ) app = Flask(__name__) app.static_folder = "static" load_dotenv() app.config["SECRET_KEY"] = "".join( [secrets.choice("abcdef0123456789") for _ in range(32)] ) FLAG = os.getenv("FLAG") def init_db(): conn = sqlite3.connect("database.db") cursor = conn.cursor() cursor.execute("""DROP TABLE IF EXISTS employees;""") cursor.execute("""DROP TABLE IF EXISTS revoked_tokens;""") cursor.execute("""DROP TABLE IF EXISTS users;""") cursor.execute("""CREATE TABLE IF NOT EXISTS users ( id INTEGER PRIMARY KEY AUTOINCREMENT, username TEXT UNIQUE NOT NULL, is_admin BOOL NOT NULL, password_hash TEXT NOT NULL)""") cursor.execute("""CREATE TABLE IF NOT EXISTS revoked_tokens ( id INTEGER PRIMARY KEY AUTOINCREMENT, token TEXT NOT NULL)""") cursor.execute("""CREATE TABLE IF NOT EXISTS employees ( id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT NOT NULL, email TEXT UNIQUE NOT NULL, position TEXT NOT NULL, phone TEXT NOT NULL, location TEXT NOT NULL)""") conn.commit() conn.close() def get_db_connection(): conn = sqlite3.connect("database.db") conn.row_factory = sqlite3.Row return conn def token_required(f): @wraps(f) def decorated(*args, **kwargs): token = request.cookies.get("JWT") if not token: flash("Token is missing!", "error") return redirect("/login") try: data = jwt.decode(token, app.config["SECRET_KEY"], algorithms=["HS256"]) username = data["username"] conn = get_db_connection() user = conn.execute( "SELECT id,is_admin FROM users WHERE username = ?", (username,) ).fetchone() revoked = conn.execute( "SELECT id FROM revoked_tokens WHERE token = ?", (token,) ).fetchone() conn.close() if not user or revoked: flash("Invalid or revoked token!", "error") return redirect("/login") request.is_admin = user["is_admin"] request.username = username except jwt.InvalidTokenError: flash("Invalid token!", "error") return redirect("/login") return f(*args, **kwargs) return decorated @app.route("/", methods=["GET"]) def index(): token = request.cookies.get("JWT", None) if token is None: return redirect("/login") else: return redirect("/employees") @app.route("/register", methods=["GET", "POST"]) def register(): if request.method == "GET": return render_template("register.html") elif request.method == "POST": data = request.form username = data.get("username") password = data.get("password") if not username or not password: return jsonify({"message": "Username and password required!"}), 400 password_hash = bcrypt.hashpw( password.encode("utf-8"), bcrypt.gensalt() ).decode("utf-8") conn = get_db_connection() try: conn.execute( "INSERT INTO users (username, is_admin, password_hash) VALUES (?, ?, ?)", (username, False, password_hash), ) conn.commit() except sqlite3.IntegrityError: flash("User already exists.", "error") return redirect("/register") finally: conn.close() flash("User created successfully.", "success") return redirect("/login") @app.route("/login", methods=["GET", "POST"]) def login(): if request.method == "GET": return render_template("login.html") elif request.method == "POST": data = request.form username = data.get("username") password = data.get("password") conn = get_db_connection() user = conn.execute( "SELECT * FROM users WHERE username = ?", (username,) ).fetchone() conn.close() if user and bcrypt.checkpw( password.encode("utf-8"), user["password_hash"].encode("utf-8") ): token = jwt.encode( { "username": username, "is_admin": user["is_admin"], "issued": time.time(), }, app.config["SECRET_KEY"], algorithm="HS256", ) resp = make_response(redirect("/employees")) resp.set_cookie("JWT", token) return resp flash("Invalid credentials.", "error") return redirect("/login") @app.route("/logout", methods=["GET"]) def logout(): token = request.cookies.get("JWT") if token: conn = get_db_connection() conn.execute("INSERT INTO revoked_tokens (token) VALUES (?)", (token,)) conn.commit() conn.close() resp = make_response(redirect("/login")) resp.delete_cookie("JWT") return resp @app.route("/employees", methods=["GET"]) @token_required def employees(): query = request.args.get("query", "") conn = get_db_connection() cursor = conn.cursor() cursor.execute( f"SELECT id, name, email, position FROM employees WHERE name LIKE '%{query}%'" ) results = cursor.fetchall() conn.close() print(request.username) return render_template("employees.html", username=request.username, employees=results, query=query) @app.route("/employee/<int:employee_id>", methods=["GET"]) @token_required def employee_details(employee_id): conn = get_db_connection() employee = conn.execute( "SELECT * FROM employees WHERE id = ?", (employee_id,) ).fetchone() conn.close() print(employee) if not employee: flash("Employee not found", "error") return redirect("/employees") return render_template("employee_details.html", username=request.username, employee=employee) @app.route("/admin", methods=["GET"]) @token_required def admin(): is_admin = getattr(request, "is_admin", None) if is_admin: return render_template("admin.html", username=request.username, flag=FLAG) flash("You don't have the permission to access this area", "error") return redirect("/employees") if __name__ == "__main__": init_db() app.run(debug=False, 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/HeroCTF/2025/web/Revoked/main.py
ctfs/HeroCTF/2025/web/Revoked/main.py
import os import secrets import sqlite3 import time from functools import wraps import bcrypt import jwt from dotenv import load_dotenv from flask import ( Flask, flash, jsonify, make_response, redirect, render_template, request, ) app = Flask(__name__) app.static_folder = "static" load_dotenv() app.config["SECRET_KEY"] = "".join( [secrets.choice("abcdef0123456789") for _ in range(32)] ) FLAG = os.getenv("FLAG") def init_db(): conn = sqlite3.connect("database.db") cursor = conn.cursor() cursor.execute("""DROP TABLE IF EXISTS employees;""") cursor.execute("""DROP TABLE IF EXISTS revoked_tokens;""") cursor.execute("""DROP TABLE IF EXISTS users;""") cursor.execute("""CREATE TABLE IF NOT EXISTS users ( id INTEGER PRIMARY KEY AUTOINCREMENT, username TEXT UNIQUE NOT NULL, is_admin BOOL NOT NULL, password_hash TEXT NOT NULL)""") cursor.execute("""CREATE TABLE IF NOT EXISTS revoked_tokens ( id INTEGER PRIMARY KEY AUTOINCREMENT, token TEXT NOT NULL)""") cursor.execute("""CREATE TABLE IF NOT EXISTS employees ( id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT NOT NULL, email TEXT UNIQUE NOT NULL, position TEXT NOT NULL, phone TEXT NOT NULL, location TEXT NOT NULL)""") conn.commit() conn.close() def get_db_connection(): conn = sqlite3.connect("database.db") conn.row_factory = sqlite3.Row return conn def token_required(f): @wraps(f) def decorated(*args, **kwargs): token = request.cookies.get("JWT") if not token: flash("Token is missing!", "error") return redirect("/login") try: data = jwt.decode(token, app.config["SECRET_KEY"], algorithms=["HS256"]) username = data["username"] conn = get_db_connection() user = conn.execute( "SELECT id,is_admin FROM users WHERE username = ?", (username,) ).fetchone() revoked = conn.execute( "SELECT id FROM revoked_tokens WHERE token = ?", (token,) ).fetchone() conn.close() if not user or revoked: flash("Invalid or revoked token!", "error") return redirect("/login") request.is_admin = user["is_admin"] request.username = username except jwt.InvalidTokenError: flash("Invalid token!", "error") return redirect("/login") return f(*args, **kwargs) return decorated @app.route("/", methods=["GET"]) def index(): token = request.cookies.get("JWT", None) if token is None: return redirect("/login") else: return redirect("/employees") @app.route("/register", methods=["GET", "POST"]) def register(): if request.method == "GET": return render_template("register.html") elif request.method == "POST": data = request.form username = data.get("username") password = data.get("password") if not username or not password: return jsonify({"message": "Username and password required!"}), 400 password_hash = bcrypt.hashpw( password.encode("utf-8"), bcrypt.gensalt() ).decode("utf-8") conn = get_db_connection() try: conn.execute( "INSERT INTO users (username, is_admin, password_hash) VALUES (?, ?, ?)", (username, False, password_hash), ) conn.commit() except sqlite3.IntegrityError: flash("User already exists.", "error") return redirect("/register") finally: conn.close() flash("User created successfully.", "success") return redirect("/login") @app.route("/login", methods=["GET", "POST"]) def login(): if request.method == "GET": return render_template("login.html") elif request.method == "POST": data = request.form username = data.get("username") password = data.get("password") conn = get_db_connection() user = conn.execute( "SELECT * FROM users WHERE username = ?", (username,) ).fetchone() conn.close() if user and bcrypt.checkpw( password.encode("utf-8"), user["password_hash"].encode("utf-8") ): token = jwt.encode( { "username": username, "is_admin": user["is_admin"], "issued": time.time(), }, app.config["SECRET_KEY"], algorithm="HS256", ) resp = make_response(redirect("/employees")) resp.set_cookie("JWT", token) return resp flash("Invalid credentials.", "error") return redirect("/login") @app.route("/logout", methods=["GET"]) def logout(): token = request.cookies.get("JWT") if token: conn = get_db_connection() conn.execute("INSERT INTO revoked_tokens (token) VALUES (?)", (token,)) conn.commit() conn.close() resp = make_response(redirect("/login")) resp.delete_cookie("JWT") return resp @app.route("/employees", methods=["GET"]) @token_required def employees(): query = request.args.get("query", "") conn = get_db_connection() cursor = conn.cursor() cursor.execute( f"SELECT id, name, email, position FROM employees WHERE name LIKE '%{query}%'" ) results = cursor.fetchall() conn.close() print(request.username) return render_template("employees.html", username=request.username, employees=results, query=query) @app.route("/employee/<int:employee_id>", methods=["GET"]) @token_required def employee_details(employee_id): conn = get_db_connection() employee = conn.execute( "SELECT * FROM employees WHERE id = ?", (employee_id,) ).fetchone() conn.close() print(employee) if not employee: flash("Employee not found", "error") return redirect("/employees") return render_template("employee_details.html", username=request.username, employee=employee) @app.route("/admin", methods=["GET"]) @token_required def admin(): is_admin = getattr(request, "is_admin", None) if is_admin: return render_template("admin.html", username=request.username, flag=FLAG) flash("You don't have the permission to access this area", "error") return redirect("/employees") if __name__ == "__main__": init_db() app.run(debug=False, 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/HeroCTF/2022/crypto/The_oracles_apprentice/chall.py
ctfs/HeroCTF/2022/crypto/The_oracles_apprentice/chall.py
#!/usr/bin/env python3 from Crypto.Util.number import getStrongPrime, bytes_to_long import random FLAG = open('flag.txt','rb').read() encrypt = lambda m: pow(m, e, n) decrypt = lambda c: pow(c, d, n) e = random.randrange(3, 65537, 2) p = getStrongPrime(1024, e=e) q = getStrongPrime(1024, e=e) n = p * q φ = (p-1) * (q-1) d = pow(e, -1, φ) c = encrypt(bytes_to_long(FLAG)) #print(f"{n=}") #print(f"{e=}") print(f"{c=}") for _ in range(3): t = int(input("c=")) print(decrypt(t)) if c != t else None
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/HeroCTF/2022/crypto/Poly321/encrypt.py
ctfs/HeroCTF/2022/crypto/Poly321/encrypt.py
#!/usr/bin/env python3 FLAG = "****************************" enc = [] for c in FLAG: v = ord(c) enc.append( v + pow(v, 2) + pow(v, 3) ) print(enc) """ $ python3 encrypt.py [378504, 1040603, 1494654, 1380063, 1876119, 1574468, 1135784, 1168755, 1534215, 866495, 1168755, 1534215, 866495, 1657074, 1040603, 1494654, 1786323, 866495, 1699439, 1040603, 922179, 1236599, 866495, 1040603, 1343210, 980199, 1494654, 1786323, 1417584, 1574468, 1168755, 1380063, 1343210, 866495, 188499, 127550, 178808, 135303, 151739, 127550, 112944, 178808, 1968875] """
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/HeroCTF/2022/web/SmallMistakeBigMistake/main.py
ctfs/HeroCTF/2022/web/SmallMistakeBigMistake/main.py
#!/usr/bin/env python from flask import Flask, session, render_template from string import hexdigits from random import choice from os import getenv app = Flask(__name__) app.secret_key = choice(hexdigits) * 32 @app.route("/", methods=["GET"]) def index(): flag = "You are not admin !" if session and session["username"] == "admin": flag = getenv("FLAG") return render_template("index.html", flag=flag) if __name__ == "__main__": app.run(host="0.0.0.0", port=int(getenv("PORT")))
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/Codefest/2025/crypto/AES_Decryption_Service/chall.py
ctfs/Codefest/2025/crypto/AES_Decryption_Service/chall.py
import os from Crypto.Cipher import AES from Crypto.Util.Padding import pad FLAG = ? KEY = ? def encryptflag(): cipher = AES.new(KEY, AES.MODE_ECB) ciphertext = cipher.encrypt(pad(FLAG, 16)) return ciphertext.hex() def decrypt(ciphertext, iv): cipher = AES.new(KEY, AES.MODE_CBC, iv) plaintext = cipher.decrypt(ciphertext) return plaintext.hex() print("AES Decryption Service\n") print(f"Encrypted Flag: {encryptflag()}\n") while True: try: IN = input('>>> ') IN = bytes.fromhex(IN) IV, CT = IN[:16], IN[16:] print(decrypt(CT, IV) + '\n') except ValueError: print('Invalid Input\n') continue except: print('\nOK Bye') break
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/BuckeyeCTF/2021/pwn/flattened/chall.py
ctfs/BuckeyeCTF/2021/pwn/flattened/chall.py
#!/usr/bin/env python3 import qiling import pwn import subprocess import capstone.x86_const pwn.context.arch = "amd64" dump = [] def code_hook(ql, address, size): global dump buf = ql.mem.read(address, size) for i in md.disasm(buf, address): allowed_syscalls = {1, 0x3c} if ( capstone.x86_const.X86_GRP_INT in i.groups and ql.reg.eax not in allowed_syscalls ): print(f"[-] syscall = {hex(ql.reg.eax)}") raise ValueError("HACKING DETECTED!") ignored_groups = { capstone.x86_const.X86_GRP_JUMP, capstone.x86_const.X86_GRP_CALL, capstone.x86_const.X86_GRP_RET, capstone.x86_const.X86_GRP_IRET, capstone.x86_const.X86_GRP_BRANCH_RELATIVE, } ignore = len(set(i.groups) & ignored_groups) > 0 print( f"[{' ' if ignore else '+'}] {hex(i.address)}: {i.mnemonic} {i.op_str}" ) if not ignore: dump.append(bytes(i.bytes)) inp = input("Enter code in hex:\n") code = bytes.fromhex(inp) ql = qiling.Qiling( code=code, rootfs="/", ostype="linux", archtype="x8664", ) ql.hook_code(code_hook) md = ql.create_disassembler() md.detail = True ql.run() print("[+] Your program has been flattened! Executing ...") new_code = b"".join(dump) filename = pwn.make_elf(new_code, extract=False, vma=0x11FF000) subprocess.run([filename])
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/BuckeyeCTF/2021/pwn/guess-god/pow.py
ctfs/BuckeyeCTF/2021/pwn/guess-god/pow.py
#!/usr/bin/env python3 # This is from kCTF (modified to remove backdoor) # https://github.com/google/kctf/blob/69bf578e1275c9223606ab6f0eb1e69c51d0c688/docker-images/challenge/pow.py # -*- coding: utf-8 -*- # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import base64 import os import secrets import socket import sys import hashlib try: import gmpy2 HAVE_GMP = True except ImportError: HAVE_GMP = False sys.stderr.write("[NOTICE] Running 10x slower, gotta go fast? pip3 install gmpy2\n") VERSION = 's' MODULUS = 2**1279-1 CHALSIZE = 2**128 SOLVER_URL = 'https://goo.gle/kctf-pow' def python_sloth_root(x, diff, p): exponent = (p + 1) // 4 for i in range(diff): x = pow(x, exponent, p) ^ 1 return x def python_sloth_square(y, diff, p): for i in range(diff): y = pow(y ^ 1, 2, p) return y def gmpy_sloth_root(x, diff, p): exponent = (p + 1) // 4 for i in range(diff): x = gmpy2.powmod(x, exponent, p).bit_flip(0) return int(x) def gmpy_sloth_square(y, diff, p): y = gmpy2.mpz(y) for i in range(diff): y = gmpy2.powmod(y.bit_flip(0), 2, p) return int(y) def sloth_root(x, diff, p): if HAVE_GMP: return gmpy_sloth_root(x, diff, p) else: return python_sloth_root(x, diff, p) def sloth_square(x, diff, p): if HAVE_GMP: return gmpy_sloth_square(x, diff, p) else: return python_sloth_square(x, diff, p) def encode_number(num): size = (num.bit_length() // 24) * 3 + 3 return str(base64.b64encode(num.to_bytes(size, 'big')), 'utf-8') def decode_number(enc): return int.from_bytes(base64.b64decode(bytes(enc, 'utf-8')), 'big') def decode_challenge(enc): dec = enc.split('.') if dec[0] != VERSION: raise Exception('Unknown challenge version') return list(map(decode_number, dec[1:])) def encode_challenge(arr): return '.'.join([VERSION] + list(map(encode_number, arr))) def get_challenge(diff): x = secrets.randbelow(CHALSIZE) return encode_challenge([diff, x]) def solve_challenge(chal): [diff, x] = decode_challenge(chal) y = sloth_root(x, diff, MODULUS) return encode_challenge([y]) def verify_challenge(chal, sol): [diff, x] = decode_challenge(chal) [y] = decode_challenge(sol) res = sloth_square(y, diff, MODULUS) return (x == res) or (MODULUS - x == res) def usage(): sys.stdout.write('Usage:\n') sys.stdout.write('Solve pow: {} solve $challenge\n') sys.stdout.write('Check pow: {} ask $difficulty\n') sys.stdout.write(' $difficulty examples (for 1.6GHz CPU) in fast mode:\n') sys.stdout.write(' 1337: 1 sec\n') sys.stdout.write(' 31337: 30 secs\n') sys.stdout.write(' 313373: 5 mins\n') sys.stdout.flush() sys.exit(1) def main(): if len(sys.argv) != 3: usage() sys.exit(1) cmd = sys.argv[1] if cmd == 'ask': difficulty = int(sys.argv[2]) if difficulty == 0: sys.stdout.write("== proof-of-work: disabled ==\n") sys.exit(0) challenge = get_challenge(difficulty) sys.stdout.write("== proof-of-work: enabled ==\n") sys.stdout.write("please solve a pow first\n") sys.stdout.write("You can run the solver with:\n") sys.stdout.write(" python3 <(curl -sSL {}) solve {}\n".format(SOLVER_URL, challenge)) sys.stdout.write("===================\n") sys.stdout.write("\n") sys.stdout.write("Solution? ") sys.stdout.flush() solution = '' with os.fdopen(0, "rb", 0) as f: while not solution: line = f.readline().decode("utf-8") if not line: sys.stdout.write("EOF") sys.stdout.flush() sys.exit(1) solution = line.strip() if verify_challenge(challenge, solution): sys.stdout.write("Correct\n") sys.stdout.flush() sys.exit(0) else: sys.stdout.write("Proof-of-work fail") sys.stdout.flush() elif cmd == 'solve': challenge = sys.argv[2] solution = solve_challenge(challenge) if verify_challenge(challenge, solution, False): sys.stderr.write("Solution: \n".format(solution)) sys.stderr.flush() sys.stdout.write(solution) sys.stdout.flush() sys.stderr.write("\n") sys.stderr.flush() sys.exit(0) else: usage() sys.exit(1) 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/BuckeyeCTF/2021/pwn/guess-god/server.py
ctfs/BuckeyeCTF/2021/pwn/guess-god/server.py
import hashlib import random import string import socket from socketserver import ThreadingTCPServer, StreamRequestHandler from multiprocessing import TimeoutError from multiprocessing.pool import ThreadPool import threading import subprocess import os import base64 from pathlib import Path import shutil import requests from proxyprotocol.v2 import ProxyProtocolV2 from proxyprotocol.reader import ProxyProtocolReader from proxyprotocol import ProxyProtocolWantRead from pow import get_challenge, verify_challenge, SOLVER_URL PORT_BASE = int(os.getenv("CHALL_PORT_BASE", "7000")) IP_BASE = "10.0.4." POW_DIFFICULTY = int(os.getenv("POW_DIFFICULTY", "0")) NUM_SERVERS = int(os.getenv("CHALL_NUM_SERVERS", "5")) DEBUG = int(os.getenv("DEBUG", "0")) == 1 MY_IP = None class MyTCPServer(ThreadingTCPServer): def server_bind(self): self.socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) self.socket.setsockopt(socket.SOL_SOCKET, socket.SO_KEEPALIVE, 1) self.socket.setsockopt(socket.IPPROTO_TCP, socket.TCP_KEEPIDLE, 10) self.socket.setsockopt(socket.IPPROTO_TCP, socket.TCP_KEEPINTVL, 3) self.socket.setsockopt(socket.IPPROTO_TCP, socket.TCP_KEEPCNT, 5) self.socket.bind(self.server_address) pool = None class MyTCPHandler(StreamRequestHandler): def handle(self): try: if not DEBUG: self.pp_result = read_proxy2(self) if not self.pp_result or not send_pow(self): return else: if not send_pow(self): return res = pool.apply_async(worker, (self,)) pos = pool._inqueue.qsize() # type: ignore self.wfile.write(f"[*] Queued in position {pos}\n".encode()) res.get(timeout=180) except (ConnectionError, TimeoutError) as e: print("connection err: %s" % (e)) pass def read_proxy2(req: MyTCPHandler): pp_reader = ProxyProtocolReader(ProxyProtocolV2()) pp_data = bytearray() while True: try: return pp_reader._parse(pp_data) except ProxyProtocolWantRead as want_read: try: if want_read.want_bytes is not None: pp_data += req.rfile.read(want_read.want_bytes) elif want_read.want_line: pp_data += req.rfile.readline() else: print("ProxyProtocolWantRead of unknown length") return None except (EOFError, ConnectionResetError) as exc: print("EOF waiting for proxy data") return None def send_pow(req: MyTCPHandler): if POW_DIFFICULTY == 0: req.wfile.write(b"== proof-of-work: disabled ==\n") req.wfile.flush() return True challenge = get_challenge(POW_DIFFICULTY) req.wfile.write(b"== proof-of-work: enabled ==\n") req.wfile.write(b"please solve a pow first\n") req.wfile.write(b"You can run the solver with:\n") req.wfile.write(" python3 <(curl -sSL {}) solve {}\n".format(SOLVER_URL, challenge).encode()) req.wfile.write(b"===================\n") req.wfile.write(b"\n") req.wfile.write(b"Solution? ") req.wfile.flush() solution = '' while not solution: solution = req.rfile.readline().decode("utf-8").strip() if verify_challenge(challenge, solution): req.wfile.write(b"Correct\n") req.wfile.flush() return True else: req.wfile.write(b"Proof-of-work fail") req.wfile.flush() return False thread_to_port = {} thread_port_lock = threading.Lock() def get_port(ident): global thread_to_port thread_port_lock.acquire() if ident in thread_to_port: port = thread_to_port[ident] else: port = len(thread_to_port) + PORT_BASE + 2 # leave .0 and .1 unused thread_to_port[ident] = port thread_port_lock.release() return port def is_socket_closed(sock) -> bool: try: # this will try to read bytes without blocking and also without removing them from buffer (peek only) data = sock.recv(16, socket.MSG_DONTWAIT | socket.MSG_PEEK) if len(data) == 0: return True return False except BlockingIOError: return False # socket is open and reading from it would block except ConnectionResetError: return True # socket was closed for some other reason except Exception as e: logger.exception("unexpected exception when checking if a socket is closed") return False return False def worker(req: MyTCPHandler): ip = req.client_address[0] src_port = req.client_address[1] if not DEBUG: real_ip = req.pp_result.source[0].exploded else: real_ip = ip print(f"Worker {threading.get_ident()} handling real ip {real_ip}") req.wfile.write(b"[+] Handling your job now\n") id = os.urandom(16).hex() path = Path("/tmp") / id if not path.exists(): path.mkdir() port = get_port(threading.get_ident()) req.wfile.write(f"\n[*] ip = {MY_IP}\n".encode()) req.wfile.write(f"[*] port = {port}\n\n".encode()) timeout = 60 * 5 req.wfile.write(f"[*] This instance will stay up for {timeout} seconds\n".encode()) req.wfile.flush() proc = subprocess.Popen(["/nsjail.sh", IP_BASE+str(port - PORT_BASE), real_ip], stdout=req.wfile) for x in range(timeout // 5): try: proc.wait(5) break except subprocess.TimeoutExpired: if is_socket_closed(req.request): break proc.terminate() try: proc.wait(1) except subprocess.TimeoutExpired: proc.kill() req.wfile.write(b"[*] Done. Goodbye!\n") req.wfile.flush() if __name__ == "__main__": port = 9000 MY_IP = requests.get("https://api.ipify.org?format=json").json()['ip'] with MyTCPServer(("0.0.0.0", port), MyTCPHandler) as server: try: pool = ThreadPool(processes=NUM_SERVERS) print(f"[*] Listening on port {port}") server.serve_forever() finally: pool.close()
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/BuckeyeCTF/2021/rev/Neurotic/src.py
ctfs/BuckeyeCTF/2021/rev/Neurotic/src.py
import torch from torch import nn import numpy as np from functools import reduce import base64 class NeuralNetwork(nn.Module): def __init__(self): super(NeuralNetwork, self).__init__() self.stack = nn.Sequential(*([nn.Linear(8, 8, bias=False)] * 7)) def forward(self, x): x = self.stack(x) return x device = "cuda" if torch.cuda.is_available() else "cpu" model = NeuralNetwork().to(device) torch.save(model.state_dict(), "model.pth") flag = b"buckeye{???????????????????????????????????????????????????????}" assert len(flag) == 64 X = np.reshape(list(flag), (8, 8)).astype(np.float32) Xt = torch.from_numpy(X).to(device) Y = model(Xt).detach().numpy() print(base64.b64encode(Y).decode()) # Output: 1VfgPsBNALxwfdW9yUmwPpnI075HhKg9bD5gPDLvjL026ho/xEpQvU5D4L3mOso+KGS7vvpT5T0FeN284inWPXyjaj7oZgI8I7q5vTWhOj7yFEq+TtmsPaYN7jxytdC9cIGwPti6ALw28Pm9eFZ/PkVBV75iV/U9NoP4PDoFn72+rI8+HHZivMwJvr2s5IQ+nASFvhoW2j1+uHE98MbuvdSNsT4kzrK82BGLvRrikz6oU66+oCGCPajDmzyg7Q69OjiDPvQtnjxwWw2+IB9ZPmaCLb4Mwhc+LimEPXXBQL75OQ8/ulQUvZZMsr3iO88+ZHz3viUgLT2U/d68C2xYPQ==
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/BuckeyeCTF/2021/crypto/Elliptigo/chall.py
ctfs/BuckeyeCTF/2021/crypto/Elliptigo/chall.py
from Crypto.Cipher import AES from Crypto.Util.Padding import pad from Crypto.Util.number import size, long_to_bytes import os import hashlib from collections import namedtuple FLAG = b"buckeye{???????????????????}" Point = namedtuple("Point", ("x", "z")) Curve = namedtuple("Curve", ("a", "b")) p = 2 ** 255 - 19 C = Curve(486662, 1) """ Implements the Montgomery Ladder from https://eprint.iacr.org/2017/212.pdf """ def point_add(P: Point, Q: Point, D: Point) -> Point: """ Algorithm 1 (xADD) """ V0 = (P.x + P.z) % p V1 = (Q.x - Q.z) % p V1 = (V1 * V0) % p V0 = (P.x - P.z) % p V2 = (Q.x + Q.z) % p V2 = (V2 * V0) % p V3 = (V1 + V2) % p V3 = (V3 * V3) % p V4 = (V1 - V2) % p V4 = (V4 * V4) % p x = (D.z * V3) % p z = (D.x * V4) % p return Point(x, z) def point_double(P: Point) -> Point: """ Algorithm 2 (xDBL) """ V1 = (P.x + P.z) % p V1 = (V1 * V1) % p V2 = (P.x - P.z) % p V2 = (V2 * V2) % p x = (V1 * V2) % p V1 = (V1 - V2) % p V3 = (((C.a + 2) // 4) * V1) % p V3 = (V3 + V2) % p z = (V1 * V3) % p return Point(x, z) def scalar_multiplication(P: Point, k: int) -> Point: """ Algorithm 4 (LADDER) """ if k == 0: return Point(0, 0) R0, R1 = P, point_double(P) for i in range(size(k) - 2, -1, -1): if k & (1 << i) == 0: R0, R1 = point_double(R0), point_add(R0, R1, P) else: R0, R1 = point_add(R0, R1, P), point_double(R1) return R0 def normalize(P: Point) -> Point: if P.z == 0: return Point(0, 0) return Point((P.x * pow(P.z, -1, p)) % p, 1) def legendre_symbol(x: int, p: int) -> int: return pow(x, (p - 1) // 2, p) def is_on_curve(x: int) -> bool: y2 = x ** 3 + C.a * x ** 2 + C.b * x return legendre_symbol(y2, p) != (-1 % p) def main(): print("Pick a base point") x = int(input("x: ")) if size(x) < 245: print("Too small!") return if x >= p: print("Too big!") return if not is_on_curve(x): print("That x coordinate is not on the curve!") return P = Point(x, 1) a = int.from_bytes(os.urandom(32), "big") A = scalar_multiplication(P, a) A = normalize(A) key = hashlib.sha1(long_to_bytes(A.x)).digest()[:16] cipher = AES.new(key, AES.MODE_ECB) ciphertext = cipher.encrypt(pad(FLAG, 16)) print(ciphertext.hex()) 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/BuckeyeCTF/2021/crypto/Super_VDF/chall.py
ctfs/BuckeyeCTF/2021/crypto/Super_VDF/chall.py
from gmpy2 import is_prime, mpz from random import SystemRandom rand = SystemRandom() PRIMES = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53] def get_prime(bit_length): while True: x = mpz(1) while x.bit_length() < bit_length: x *= rand.choice(PRIMES) if is_prime(x + 1): return x + 1 def get_correct_answer(): # Implementation redacted return -1 p = get_prime(1024) q = get_prime(1024) n = p * q print(f"n = {n}") print("Please calculate (59 ** 59 ** 59 ** 59 ** 1333337) % n") ans = int(input(">>> ")) if ans == get_correct_answer(): print("WTF do you own a supercomputer? Here's your flag:") print("buckeye{????????????????????????????????????}") else: print("WRONG")
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/BuckeyeCTF/2021/crypto/Key_exchange_2/server.py
ctfs/BuckeyeCTF/2021/crypto/Key_exchange_2/server.py
import random import hashlib # Mac/Linux: pip3 install pycryptodome # Windows: py -m pip install pycryptodome import Crypto.Util.number as cun from Crypto.Cipher import AES rand = random.SystemRandom() FLAG = b"buckeye{???????????????????????????????????????}" def diffie_hellman(message: bytes): p = cun.getPrime(512) g = 5 print(f"p = {p}") print(f"g = {g}") a = rand.randrange(2, p - 1) # private key A = pow(g, a, p) # public key print("Can you still get the shared secret without my public key A?") B = int(input("Give me your public key B: ")) if not (1 < B < p - 1): print("Suspicious public key") return # B ^ a === (g ^ b) ^ a === g ^ (ab) (mod p) # Nobody can derive this shared secret except us! shared_secret = pow(B, a, p) # Use AES, a symmetric cipher, to encrypt the flag using the shared key key = hashlib.sha1(cun.long_to_bytes(shared_secret)).digest()[:16] cipher = AES.new(key, AES.MODE_ECB) ciphertext = cipher.encrypt(message) print(f"ciphertext = {ciphertext.hex()}") print("I'm going to send you the flag.") print("However, I noticed that an FBI agent has been eavesdropping on my messages,") print("so I'm going to send it to you in a way that ONLY YOU can decrypt the flag.") print() diffie_hellman(FLAG)
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/BuckeyeCTF/2021/crypto/Key_exchange/server.py
ctfs/BuckeyeCTF/2021/crypto/Key_exchange/server.py
import random import hashlib # Mac/Linux: pip3 install pycryptodome # Windows: py -m pip install pycryptodome import Crypto.Util.number as cun from Crypto.Cipher import AES rand = random.SystemRandom() FLAG = b"buckeye{???????????????????????????????????????????????????????}" def diffie_hellman(message: bytes): p = cun.getPrime(512) g = 5 print(f"p = {p}") print(f"g = {g}") a = rand.randrange(2, p - 1) # private key A = pow(g, a, p) # public key # g ^ a === A (mod p) # It's computationally infeasible for anyone else to derive a from A print(f"A = {A}") B = int(input("Give me your public key B: ")) if not (1 < B < p - 1): print("Suspicious public key") return # B ^ a === (g ^ b) ^ a === g ^ (ab) (mod p) # Nobody can derive this shared secret except us! shared_secret = pow(B, a, p) # Use AES, a symmetric cipher, to encrypt the flag using the shared key key = hashlib.sha1(cun.long_to_bytes(shared_secret)).digest()[:16] cipher = AES.new(key, AES.MODE_ECB) ciphertext = cipher.encrypt(message) print(f"ciphertext = {ciphertext.hex()}") print("I'm going to send you the flag.") print("However, I noticed that an FBI agent has been eavesdropping on my messages,") print("so I'm going to send it to you in a way that ONLY YOU can decrypt the flag.") print() diffie_hellman(FLAG)
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/BuckeyeCTF/2021/crypto/Pseudo/chall.py
ctfs/BuckeyeCTF/2021/crypto/Pseudo/chall.py
#!/usr/bin/env python3 import random import os rand = random.SystemRandom() FLAG = b"buckeye{?????????????????????}" def is_prime(n, rounds=32): return all(pow(rand.randrange(2, n), n - 1, n) == 1 for _ in range(rounds)) class RNG: def __init__(self, p: int, a: int): self.p = p self.a = a def next_bit(self) -> int: ans = pow(self.a, (self.p - 1) // 2, self.p) self.a += 1 return int(ans == 1) def next_byte(self) -> int: ans = 0 for i in range(8): ans |= self.next_bit() << i return ans def next_bytes(self, n: int) -> bytes: return bytes(self.next_byte() for _ in range(n)) def main(): p = int(input("Give me a prime number: ")) if not (256 <= p.bit_length() <= 512): print("Wrong bit length") return if not is_prime(p): print("Fermat tells me your number isn't prime") return a = rand.randrange(2, p) rng = RNG(p, a) plaintext = b"Hello " + os.urandom(48).hex().encode() print("Have some ciphertexts:") for _ in range(32): s = rng.next_bytes(len(plaintext)) c = bytes(a ^ b for a, b in zip(s, plaintext)) print(c.hex()) if plaintext == input("Guess the plaintext:\n").encode(): print(f"Congrats! Here's the flag: {FLAG}") else: print("That's wrong") main()
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/BuckeyeCTF/2021/crypto/Defective_RSA/chall.py
ctfs/BuckeyeCTF/2021/crypto/Defective_RSA/chall.py
from Crypto.Util.number import getPrime, inverse, bytes_to_long e = 1440 p = getPrime(1024) q = getPrime(1024) n = p * q flag = b"buckeye{???????????????????????????????}" c = pow(bytes_to_long(flag), e, n) print(f"e = {e}") print(f"p = {p}") print(f"q = {q}") print(f"c = {c}") # e = 1440 # p = 108625855303776649594296217762606721187040584561417095690198042179830062402629658962879350820293908057921799564638749647771368411506723288839177992685299661714871016652680397728777113391224594324895682408827010145323030026082761062500181476560183634668138131801648343275565223565977246710777427583719180083291 # q = 124798714298572197477112002336936373035171283115049515725599555617056486296944840825233421484520319540831045007911288562132502591989600480131168074514155585416785836380683166987568696042676261271645077182221098718286132972014887153999243085898461063988679608552066508889401992413931814407841256822078696283307 # c = 4293606144359418817736495518573956045055950439046955515371898146152322502185230451389572608386931924257325505819171116011649046442643872945953560994241654388422410626170474919026755694736722826526735721078136605822710062385234124626978157043892554030381907741335072033672799019807449664770833149118405216955508166023135740085638364296590030244412603570120626455502803633568769117033633691251863952272305904666711949672819104143350385792786745943339525077987002410804383449669449479498326161988207955152893663022347871373738691699497135077946326510254675142300512375907387958624047470418647049735737979399600182827754
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/BuckeyeCTF/2021/web/jupyter/app/server.py
ctfs/BuckeyeCTF/2021/web/jupyter/app/server.py
import uvicorn from fastapi import FastAPI, File, Query import os from pathlib import Path import subprocess import requests UPLOADS_DIR = Path(os.environ["UPLOADS_DIR"]) APP_URL = os.environ["APP_URL"] BOT_URL = os.environ["BOT_URL"] BOT_TOKEN = os.environ["BOT_TOKEN"] app = FastAPI() @app.post("/upload_ipynb/") async def upload_ipynb(file: bytes = File(...)): filename = os.urandom(16).hex() + ".ipynb" filepath = UPLOADS_DIR / filename with open(filepath, "wb") as f: f.write(file) subprocess.run(f"jupyter trust {filepath}", shell=True) url = f"{APP_URL}:8888/notebooks/{filename}" data = {"url": url, "token": BOT_TOKEN} res = requests.post(f"{BOT_URL}/visit", json=data) return {"url": url, "bot_status_code": res.status_code} if __name__ == "__main__": uvicorn.run("server:app", host="0.0.0.0", root_path="/api", port=3000, workers=4)
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/BuckeyeCTF/2021/web/tesseract/app.py
ctfs/BuckeyeCTF/2021/web/tesseract/app.py
import os from flask import ( Flask, flash, request, redirect, url_for, Blueprint, current_app, render_template_string, send_from_directory, ) from werkzeug.utils import secure_filename import subprocess from dotenv import load_dotenv load_dotenv() main = Blueprint("main", __name__) def create_app(): app = Flask(__name__) app.config["UPLOAD_FOLDER"] = os.path.join(os.getcwd(), "uploads/") app.config["SECRET_KEY"] = os.environ.get("SECRET_KEY") app.config["MAX_CONTENT_LENGTH"] = 128 * 1024 # 128K app.register_blueprint(main) return app @main.route("/", methods=["GET", "POST"]) def upload_file(): messages = None if request.method == "POST": # check if the post request has the file part if "file" not in request.files: flash("No file part") return redirect(request.url) file = request.files["file"] # If the user does not select a file, the browser submits an # empty file without a filename. if file.filename == "": flash("No selected file") return redirect(request.url) if file: file.save(os.path.join(current_app.config["UPLOAD_FOLDER"], secure_filename(file.filename))) # Run OCR on the uploaded image process_path = os.path.join("/uploads", file.filename) process = subprocess.run( f"tesseract \'{process_path}\' \'{process_path}\' -l eng", shell=True, check=False, capture_output=True, ) print(process.args) if process.returncode == 0: print("Success") return redirect(url_for("main.download_file", name=filename + ".txt")) else: messages = [process.stdout.decode(), process.stderr.decode()] return render_template_string( """<!doctype html> <title>OCR As-A-Service</title> {% if messages %} <ul class=flashes> {% for message in messages %} <li>{{ message }}</li> {% endfor %} </ul> {% endif %} <h1>OCR As-A-Service</h1> <p>Upload an image and I'll grab the text off it!</p> <form method=post enctype=multipart/form-data> <input type=file name=file> <input type=submit value=Upload> </form> """, messages=messages, ) @main.route("/uploads/<name>") def download_file(name): return send_from_directory(current_app.config["UPLOAD_FOLDER"], name)
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/BuckeyeCTF/2021/web/sozu/app/server.py
ctfs/BuckeyeCTF/2021/web/sozu/app/server.py
from flask import Flask, request, abort, Response, jsonify, Blueprint, render_template import os app = Flask(__name__) internal = Blueprint('internal', __name__) public = Blueprint('public', __name__) @internal.route('/') def internal_home(): return render_template("internal/home.html") @internal.route('/flag') def internal_flag(): return jsonify({"flag": os.getenv("FLAG")}) @public.route('/') def public_home(): return render_template("public/home.html") app.register_blueprint(internal, url_prefix="/internal") app.register_blueprint(public, url_prefix="/public")
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/BuckeyeCTF/2024/misc/fixpoint/fixpoint.py
ctfs/BuckeyeCTF/2024/misc/fixpoint/fixpoint.py
import base64 standard_alphabet = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/' # alphabet = standard_alphabet # fixed_point = "Vm0wd2QyUXlVWGxWV0d4V1YwZDRWMVl3WkRSV01WbDNXa1JTVjAxV2JETlhhMUpUVmpBeFYySkVUbGhoTVVwVVZtcEJlRll5U2tWVWJHaG9UVlZ3VlZadGNFSmxSbGw1VTJ0V1ZXSkhhRzlVVmxaM1ZsWmFkR05GU214U2JHdzFWVEowVjFaWFNraGhSemxWVm14YU0xWnNXbUZrUjA1R1UyMTRVMkpIZHpGV1ZFb3dWakZhV0ZOcmFHaFNlbXhXVm0xNFlVMHhXbk5YYlVaclVqQTFSMVV5TVRSVk1rcElaSHBHVjFaRmIzZFdha1poVjBaT2NtRkhhRk5sYlhoWFZtMHhORmxWTUhoWGJrNVlZbFZhY2xWcVFURlNNVlY1VFZSU1ZrMXJjRWxhU0hCSFZqRmFSbUl6WkZkaGExcG9WakJhVDJOdFJraGhSazVzWWxob1dGWnRNSGhPUm14V1RVaG9XR0pyTlZsWmJGWmhZMnhXY1ZGVVJsTk5WbFkxVkZaU1UxWnJNWEpqUld4aFUwaENTRlpxUm1GU2JVbDZXa1prYUdFeGNHOVdha0poVkRKT2RGSnJhR2hTYXpWeldXeG9iMWRHV25STlNHaFBVbTE0VjFSVmFHOVhSMHB5VGxac1dtSkdXbWhaTW5oWFkxWkdWVkpzVGs1V2JGa3hWa1phVTFVeFduSk5XRXBxVWxkNGFGVXdhRU5UUmxweFVtMUdVMkpWYkRaWGExcHJZVWRGZUdOSE9WZGhhMHBvVmtSS1QyUkdTbkpoUjJoVFlYcFdlbGRYZUc5aU1XUkhWMjVTVGxOSGFGQlZiVEUwVmpGU1ZtRkhPVmhTTUhCNVZHeGFjMWR0U2tkWGJXaGFUVzVvV0ZreFdrZFdWa3B6VkdzMVYySkdhM2hXYTFwaFZURlZlRmR1U2s1WFJYQnhWV3hrTkdGR1ZYZGhSVTVVVW14d2VGVnRNVWRWTWtwV1lrUmFXR0V4Y0hKWlZX" alphabet = "bctf{?????????????????????????FiXed???????????????????????p01nT}" fixed_point = "NslSBwm6YNHHNreCNsmojw8zY9nGVzep9NoJ5LHpH3b8NKnQlB2Ca{XzIxeUyR85Y{COjRD09P4mFEAAFACZlAo0jwnGBrj7UAbwYBHDjBDEjBlMY{DWkE46YrVtaKh6ABDdVLoty{5Gjr5DMrmSNAo05DVu5NjR93m9VEDqMfHcjr5rAr2WVPo0lBVGaxA{N3mvBw8cYzbL5DHLlB8GBxrzYNo95B52N9HCIR4Ol3mcaxm3AocWkE2tArVeF{D0NxlvVrm6UElHFKmklB5CNE2tU{VtFPmp9B8WUNAtlNmUUBefyACwNR7zY9leFEwzj9nxARvDks5caoHo5sv{k{8ZYPH9aKwRABASy{HqY9vSjxAfNrBOVDA0As5EBEL7UBCZALAUj35SNKLAABmoHsocj6VUBxVp9NoSHBHDV64GU98ZjAmR5Evzl9leYweWl3lRFRv0UD4HB{X8IBv6BrDtjAl8Fwe29NoRBR4Zj9HUarmgAr5ck{DzlBAt5B76ABmf9rDkjAAGkzANNrvkjBDtY9nCaRnxMxH9ABmZAsb8NKnNy{mC5DIRl{VAUNeMMrDvBxADVs4SU92o93VoAR7zYDmEBsI7ABjwy{m09femjsIRjsm{VE4cYfeEVRBOUB8WBrmylD4GUBeAI3mvHwDOl9luFw5pY{mcVfAtlzHcjKLKU3m{MR4cjBVuFrDUNsmRMR4t5P5HU98fIAmJF{LZyfocjKLMj3ldU{8qYr88FRLflB5mBK20ArDANKAlN3m{VrmZjB59az5NANrOYzrzAKncBxVp9B5v5BmzyNVcjK46F3vvkfoKH9LGawoyMslvFLHDlElHHKADAomtNLAtUDVtaKL8Y{jw5LAtHBDmkRLRyPV{NR78YPAEVzA793vvILHKj35SFrexMrvkyLBzY3vlBx5xMrm9VBHO5DAUaRLyNACwVfAjlBeAUNeKyBDvyrH0ND48HKnxMrvkN9hzYE5AFze293CZU{Hy" translation_table = str.maketrans(standard_alphabet, alphabet) def encode(s): """Base64 encode the string using our custom alphabet""" return base64.b64encode(s.encode()).decode().replace('=', '').translate(translation_table) starting_string = input("String to encode? ") current = starting_string print(f"{0} {starting_string}") for i in range(100): old = current current = encode(current) print(f"{i+1} {current[0:1000] + (current[1000:] and '...')}") if current[0:1000] == old[0:1000]: if current.startswith(fixed_point): print("Found the fixed point, and it is what I expected!") else: print("Found a fixed point, but it's not what I expected!!!") break else: print("Failed to find a fixed point")
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/BuckeyeCTF/2024/crypto/xnor/xnor.py
ctfs/BuckeyeCTF/2024/crypto/xnor/xnor.py
import os def xnor_bit(a_bit, b_bit): if a_bit == "1" and b_bit == "1": return "1" elif a_bit == "1" and b_bit == "0": return "0" elif a_bit == "0" and b_bit == "1": return "0" elif a_bit == "0" and b_bit == "0": return "1" def xnor_byte(a_byte, b_byte): a_bits = get_bits_from_byte(a_byte) b_bits = get_bits_from_byte(b_byte) result_bits = [xnor_bit(a_bits[i], b_bits[i]) for i in range(8)] result_byte = get_byte_from_bits(result_bits) return result_byte def xnor_bytes(a_bytes, b_bytes): assert len(a_bytes) == len(b_bytes) return bytes([xnor_byte(a_bytes[i], b_bytes[i]) for i in range(len(a_bytes))]) def get_bits_from_byte(byte): return list("{:08b}".format(byte)) def get_byte_from_bits(bits): return int("".join(bits), 2) message = b"Blue is greener than purple for sure!" key = os.urandom(37) flag = b"bctf{???????????????????????????????}" def main(): print(f"Key: {key.hex()}") print(f"\nMessage: {message}") encrypted = xnor_bytes(message, key) print(f"Enrypted message: {encrypted.hex()}") print(f"\nFlag: {flag}") encrypted_flag = xnor_bytes(flag, key) print(f"Encrypted flag: {encrypted_flag.hex()}") 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/BuckeyeCTF/2024/crypto/zkwarmup/zkwarmup.py
ctfs/BuckeyeCTF/2024/crypto/zkwarmup/zkwarmup.py
from math import gcd import random import time from flag import flag class Verifier: def __init__(self, y, n): self.y = y self.n = n self.previous_ss = set() self.previous_zs = set() def flip_coin(self) -> int: return random.randrange(2) def verify(self, s, z, b) -> bool: if s in self.previous_ss or z in self.previous_zs: print("Bad: repeated s or z") return False self.previous_ss.add(s) self.previous_zs.add(z) n = self.n y = self.y if s == 0: print("Bad: s = 0") return False if gcd(s, n) != 1: print("Bad: gcd(s, n) != 1") return False return pow(z, 2, n) == (s * pow(y, 1 - b)) % n def main(): print("Welcome to zkwarmup!") # p = getPrime(1024) # q = getPrime(1024) # n = p * q n = 19261756194530262169516227535327268535825703622469356233861243450409596218324982327819027354327762272541787979307084854543427241827543331732057807638293377995167826046761991463655794445629511818504788588146049602678202660790161211079215140614149179394809442098536009911202757117559092796991732111808588753074002377241720729762405118846289128192452140379045358673985940236403266552967867241351260376075804662700969038717732248036975281084947926661161892037413944872628410488986135370175176475239647256670545733839891394321932103696968961386864456665963903759123610214930997530883831800104920546270573046968308379346633 print(f"n = {n}") random.seed(int(time.time())) x = random.randrange(1, n) y = pow(x, 2, n) print(f"y = {y}") print("Can you prove that you know sqrt(y) without revealing it to the verifier?") verifier = Verifier(y, n) n_rounds = 128 for i in range(n_rounds): s = int(input("Provide s: ")) % n b = verifier.flip_coin() print(f"b = {b}") z = int(input("Provide z: ")) % n if verifier.verify(s, z, b): print(f"Verification passed! {n_rounds - i - 1} rounds remaining") else: print("Verification failed!") return print("You've convinced the verifier you know sqrt(y)!") print(flag) if __name__ == "__main__": main()
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/BuckeyeCTF/2024/crypto/hashbrown/hashbrown.py
ctfs/BuckeyeCTF/2024/crypto/hashbrown/hashbrown.py
import os # pip install pycryptodome from Crypto.Cipher import AES flag = "bctf{????????????????}" secret = os.urandom(16) my_message = "\n".join( [ "Grate the raw potatoes with a cheese grater, place them into a bowl and cover completely with water. Let sit for 10 minutes.", "Drain the grated potatoes well; if this is not done thoroughly the potatoes will steam instead of fry.", "Mix in chopped onions by hand.", "Mix the egg OR flour into the hash brown mixture evenly. This will allow the hash browns to stay together when frying.", "Place a large frying pan on medium-high heat and add enough oil to provide a thin coating over the entire bottom of the pan.", "When the oil has come up to temperature apply a large handful of potatoes to the pan and reshape into a patty that is about 1/4-1/2 inch (6-12 mm) thick. The thinner the patty, the crispier the hash browns will be throughout.", "Flip when they are crisp and brown on the cooking side. They should also stick together nicely before they are flipped. This should take about 5-8 minutes.", "The hash browns are done when the new side is brown and crispy. This should take another 3-5 minutes.", ] ).encode() def aes(block: bytes, key: bytes) -> bytes: assert len(block) == len(key) == 16 return AES.new(key, AES.MODE_ECB).encrypt(block) def pad(data): padding_length = 16 - len(data) % 16 return data + b"_" * padding_length def hash(data: bytes): data = pad(data) state = bytes.fromhex("f7c51cbd3ca7fe29277ff750e762eb19") for i in range(0, len(data), 16): block = data[i : i + 16] state = aes(block, state) return state def sign(message, secret): return hash(secret + message) def main(): print("Recipe for hashbrowns:") print(my_message) print("Hashbrowns recipe as hex:") print(my_message.hex()) print("Signature:") print(sign(my_message, secret).hex()) print() print("Give me recipe for french fry? (as hex)") your_message = bytes.fromhex(input("> ")) print("Give me your signiature?") your_signiature = bytes.fromhex(input("> ")) print() print("Your recipe:") print(your_message) print("Your signiature:") print(your_signiature.hex()) print() if b"french fry" not in your_message: print("That is not a recipe for french fry!!") elif your_signiature != sign(your_message, secret): print("That is not a valid signiature!!") else: print("Thank you very much. Here is your flag:") print(flag) if __name__ == "__main__": main()
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/BuckeyeCTF/2024/crypto/rsa/rsa.py
ctfs/BuckeyeCTF/2024/crypto/rsa/rsa.py
import Crypto.Util.number as cun import math message = b"bctf{fake_flag}" m = int.from_bytes(message, "big") p = cun.getPrime(128) q = cun.getPrime(128) e = 65537 n = p * q phi = (p - 1) * (q - 1) d = pow(e, -1, phi) assert (e * d) % phi == 1 assert math.gcd(e, phi) == 1 c = pow(m, e, n) print(f"e = {e}") print(f"n = {n}") print(f"c = {c}") """ Output: e = 65537 n = 66082519841206442253261420880518905643648844231755824847819839195516869801231 c = 19146395818313260878394498164948015155839880044374872805448779372117637653026 """
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/BuckeyeCTF/2023/pwn/flag_sharing/solve_template.py
ctfs/BuckeyeCTF/2023/pwn/flag_sharing/solve_template.py
from instancer.pow import solve_challenge from pwn import * # fill in port number here p_gateway = remote("chall.pwnoh.io", ...) # Solve the proof-of-work if enabled (limits abuse) pow = p_gateway.recvline() if pow.startswith(b"== proof-of-work: enabled =="): p_gateway.recvline() p_gateway.recvline() challenge = p_gateway.recvline().decode().split(" ")[-1] p_gateway.recvuntil("Solution? ") p_gateway.sendline(solve_challenge(challenge)) # Get the IP and port of the instance p_gateway.recvuntil("ip = ") ip = p_gateway.recvuntil("\n").decode().strip() p_gateway.recvuntil("port = ") port = int(p_gateway.recvuntil("\n").decode().strip()) # Helper to start the bot (which has the flag) # (optionally, you can start the bot with a fake flag for debugging) def start_bot(fake_flag=None): p_gateway.recvuntil("Choice: ") if fake_flag is not None: p_gateway.sendline("2") p_gateway.recvuntil(":") p_gateway.sendline(fake_flag) else: p_gateway.sendline("1") p_gateway.recvuntil("Bot spawned") p = remote(ip, port) # Start bot with real flag start_bot() # ** your really great solution goes here ** p.interactive()
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/BuckeyeCTF/2023/pwn/flag_sharing/bot/bot.py
ctfs/BuckeyeCTF/2023/pwn/flag_sharing/bot/bot.py
import sys if sys.argv[1] == "": with open("flag.txt", "r") as f: flag = f.read() else: flag = sys.argv[1] flag = int.from_bytes(flag.encode(), "little") from pwn import * p = remote("chal", 5000) p.recvuntil(b"----") p.recvline() p.recvuntil(b"----") p.recvline() while flag != 0: match flag & 3: case 0: p.sendline(b"W") case 1: p.sendline(b"A") case 2: p.sendline(b"S") case 3: p.sendline(b"D") p.recvuntil(b"----") p.recvline() p.recvuntil(b"----") p.recvline() print(hex(flag)) flag = flag >> 2 time.sleep(0.25)
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/BuckeyeCTF/2023/pwn/flag_sharing/instancer/pow.py
ctfs/BuckeyeCTF/2023/pwn/flag_sharing/instancer/pow.py
#!/usr/bin/env python3 # This is from kCTF (modified to remove backdoor) # https://github.com/google/kctf/blob/69bf578e1275c9223606ab6f0eb1e69c51d0c688/docker-images/challenge/pow.py # -*- coding: utf-8 -*- # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import base64 import os import secrets import socket import sys import hashlib try: import gmpy2 HAVE_GMP = True except ImportError: HAVE_GMP = False sys.stderr.write("[NOTICE] Running 10x slower, gotta go fast? pip3 install gmpy2\n") VERSION = 's' MODULUS = 2**1279-1 CHALSIZE = 2**128 SOLVER_URL = 'https://goo.gle/kctf-pow' def python_sloth_root(x, diff, p): exponent = (p + 1) // 4 for i in range(diff): x = pow(x, exponent, p) ^ 1 return x def python_sloth_square(y, diff, p): for i in range(diff): y = pow(y ^ 1, 2, p) return y def gmpy_sloth_root(x, diff, p): exponent = (p + 1) // 4 for i in range(diff): x = gmpy2.powmod(x, exponent, p).bit_flip(0) return int(x) def gmpy_sloth_square(y, diff, p): y = gmpy2.mpz(y) for i in range(diff): y = gmpy2.powmod(y.bit_flip(0), 2, p) return int(y) def sloth_root(x, diff, p): if HAVE_GMP: return gmpy_sloth_root(x, diff, p) else: return python_sloth_root(x, diff, p) def sloth_square(x, diff, p): if HAVE_GMP: return gmpy_sloth_square(x, diff, p) else: return python_sloth_square(x, diff, p) def encode_number(num): size = (num.bit_length() // 24) * 3 + 3 return str(base64.b64encode(num.to_bytes(size, 'big')), 'utf-8') def decode_number(enc): return int.from_bytes(base64.b64decode(bytes(enc, 'utf-8')), 'big') def decode_challenge(enc): dec = enc.split('.') if dec[0] != VERSION: raise Exception('Unknown challenge version') return list(map(decode_number, dec[1:])) def encode_challenge(arr): return '.'.join([VERSION] + list(map(encode_number, arr))) def get_challenge(diff): x = secrets.randbelow(CHALSIZE) return encode_challenge([diff, x]) def solve_challenge(chal): [diff, x] = decode_challenge(chal) y = sloth_root(x, diff, MODULUS) return encode_challenge([y]) def verify_challenge(chal, sol): [diff, x] = decode_challenge(chal) [y] = decode_challenge(sol) res = sloth_square(y, diff, MODULUS) return (x == res) or (MODULUS - x == res) def usage(): sys.stdout.write('Usage:\n') sys.stdout.write('Solve pow: {} solve $challenge\n') sys.stdout.write('Check pow: {} ask $difficulty\n') sys.stdout.write(' $difficulty examples (for 1.6GHz CPU) in fast mode:\n') sys.stdout.write(' 1337: 1 sec\n') sys.stdout.write(' 31337: 30 secs\n') sys.stdout.write(' 313373: 5 mins\n') sys.stdout.flush() sys.exit(1) def main(): if len(sys.argv) != 3: usage() sys.exit(1) cmd = sys.argv[1] if cmd == 'ask': difficulty = int(sys.argv[2]) if difficulty == 0: sys.stdout.write("== proof-of-work: disabled ==\n") sys.exit(0) challenge = get_challenge(difficulty) sys.stdout.write("== proof-of-work: enabled ==\n") sys.stdout.write("please solve a pow first\n") sys.stdout.write("You can run the solver with:\n") sys.stdout.write(" python3 <(curl -sSL {}) solve {}\n".format(SOLVER_URL, challenge)) sys.stdout.write("===================\n") sys.stdout.write("\n") sys.stdout.write("Solution? ") sys.stdout.flush() solution = '' with os.fdopen(0, "rb", 0) as f: while not solution: line = f.readline().decode("utf-8") if not line: sys.stdout.write("EOF") sys.stdout.flush() sys.exit(1) solution = line.strip() if verify_challenge(challenge, solution): sys.stdout.write("Correct\n") sys.stdout.flush() sys.exit(0) else: sys.stdout.write("Proof-of-work fail") sys.stdout.flush() elif cmd == 'solve': challenge = sys.argv[2] solution = solve_challenge(challenge) if verify_challenge(challenge, solution, False): sys.stderr.write("Solution: \n".format(solution)) sys.stderr.flush() sys.stdout.write(solution) sys.stdout.flush() sys.stderr.write("\n") sys.stderr.flush() sys.exit(0) else: usage() sys.exit(1) 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/BuckeyeCTF/2023/pwn/flag_sharing/instancer/server.py
ctfs/BuckeyeCTF/2023/pwn/flag_sharing/instancer/server.py
import hashlib import random import string import socket from socketserver import ThreadingTCPServer, StreamRequestHandler from multiprocessing import TimeoutError from multiprocessing.pool import ThreadPool import threading import subprocess import os, time import base64 from pathlib import Path import shutil import requests from proxyprotocol.v2 import ProxyProtocolV2 from proxyprotocol.reader import ProxyProtocolReader from proxyprotocol import ProxyProtocolWantRead from pow import get_challenge, verify_challenge, SOLVER_URL import logging logger = logging.getLogger(__name__) PORT_BASE = int(os.getenv("CHAL_PORT_BASE", "7000")) IP_BASE = "10.0.{}.3" IFACE = "eth{}" POW_DIFFICULTY = int(os.getenv("POW_DIFFICULTY", "0")) NUM_SERVERS = int(os.getenv("CHAL_NUM_SERVERS", "5")) DEBUG = int(os.getenv("DEBUG", "0")) == 1 # These are required attributes CHAL_NET_PREFIX = os.environ["CHAL_NET_PREFIX"] # set by setup.sh CHAL_IMAGE_NAME = os.environ["CHAL_IMAGE_NAME"] # set by docker-compose.yml MY_IP = None class MyTCPServer(ThreadingTCPServer): def server_bind(self): self.socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) self.socket.setsockopt(socket.SOL_SOCKET, socket.SO_KEEPALIVE, 1) self.socket.setsockopt(socket.IPPROTO_TCP, socket.TCP_KEEPIDLE, 10) self.socket.setsockopt(socket.IPPROTO_TCP, socket.TCP_KEEPINTVL, 3) self.socket.setsockopt(socket.IPPROTO_TCP, socket.TCP_KEEPCNT, 5) self.socket.bind(self.server_address) pool = None class MyTCPHandler(StreamRequestHandler): menu_state: int def setup(self): super().setup() self.menu_state = 0 def handle(self): try: if not DEBUG: self.pp_result = read_proxy2(self) if not self.pp_result or not send_pow(self): return else: if not send_pow(self): return res = pool.apply_async(worker, (self,)) pos = pool._inqueue.qsize() # type: ignore self.wfile.write(f"[*] Queued in position {pos}\n".encode()) res.get(timeout=180) except (ConnectionError, TimeoutError) as e: print("connection err: %s" % (e)) pass def read_proxy2(req: MyTCPHandler): pp_reader = ProxyProtocolReader(ProxyProtocolV2()) pp_data = bytearray() while True: try: return pp_reader._parse(pp_data) except ProxyProtocolWantRead as want_read: try: if want_read.want_bytes is not None: pp_data += req.rfile.read(want_read.want_bytes) elif want_read.want_line: pp_data += req.rfile.readline() else: print("ProxyProtocolWantRead of unknown length") return None except (EOFError, ConnectionResetError) as exc: print("EOF waiting for proxy data") return None def send_pow(req: MyTCPHandler): if POW_DIFFICULTY == 0: req.wfile.write(b"== proof-of-work: disabled ==\n") req.wfile.flush() return True challenge = get_challenge(POW_DIFFICULTY) req.wfile.write(b"== proof-of-work: enabled ==\n") req.wfile.write(b"please solve a pow first\n") req.wfile.write(b"You can run the solver with:\n") req.wfile.write(" python3 <(curl -sSL {}) solve {}\n".format(SOLVER_URL, challenge).encode()) req.wfile.write(b"===================\n") req.wfile.write(b"\n") req.wfile.write(b"Solution? ") req.wfile.flush() solution = '' while not solution: solution = req.rfile.readline().decode("utf-8").strip() if verify_challenge(challenge, solution): req.wfile.write(b"Correct\n") req.wfile.flush() return True else: req.wfile.write(b"Proof-of-work fail") req.wfile.flush() return False thread_to_port = {} thread_port_lock = threading.Lock() def get_port(ident): global thread_to_port thread_port_lock.acquire() if ident in thread_to_port: port = thread_to_port[ident] else: port = len(thread_to_port) + PORT_BASE + 2 # leave .0 and .1 unused thread_to_port[ident] = port thread_port_lock.release() return port def is_socket_closed(sock) -> bool: try: # this will try to read bytes without blocking and also without removing them from buffer (peek only) data = sock.recv(16, socket.MSG_DONTWAIT | socket.MSG_PEEK) if len(data) == 0: return True return False except BlockingIOError: return False # socket is open and reading from it would block except ConnectionResetError: return True # socket was closed for some other reason except OSError as e: if e.errno == 9: # Bad file descriptor return True else: logger.exception(f"unexpected exception when checking if a socket is closed: {e}") except Exception as e: logger.exception(f"unexpected exception when checking if a socket is closed: {e}") return False def process_command(req: MyTCPHandler, bot_network_name): req.request.setblocking(False) bot_container_id = None try: # State 0: Main menu if req.menu_state == 0: line = req.rfile.readline() # Option 1: Spawn with real flag if line == b"1\n": req.menu_state = 3 bot_spawn = subprocess.run(["./spawn_bot.sh", bot_network_name, ""], timeout=3, stdout=subprocess.PIPE, check=True, text=True) bot_container_id = bot_spawn.stdout.split("\n")[0] req.wfile.write(b"[+] Bot spawned using real flag\n") # Option 2: Spawn with fake flag elif line == b"2\n": req.menu_state = 1 req.wfile.write(b"Enter your desired flag: ") # State 1: Waiting for fake flag elif req.menu_state == 1: line = req.rfile.readline() if len(line) > 1: line = line.decode('utf-8').split("\n")[0] req.menu_state = 3 # Spawn the bot with their desired flag bot_spawn = subprocess.run(["./spawn_bot.sh", bot_network_name, line], timeout=3, stdout=subprocess.PIPE, check=True, text=True) bot_container_id = bot_spawn.stdout.split("\n")[0] req.wfile.write(f"[+] Bot spawned using fake flag: {line}\n".encode()) except Exception as e: logger.warning(f"{e}") req.request.setblocking(True) return bot_container_id def worker(req: MyTCPHandler): ip = req.client_address[0] src_port = req.client_address[1] if not DEBUG: real_ip = req.pp_result.source[0].exploded else: real_ip = ip print(f"Worker {threading.get_ident()} handling real ip {real_ip}") req.wfile.write(b"[+] Handling your job now\n") id = os.urandom(16).hex() path = Path("/tmp") / id if not path.exists(): path.mkdir() port = get_port(threading.get_ident()) instance_idx = port - PORT_BASE req.wfile.write(f"\n[*] ip = {MY_IP}\n".encode()) req.wfile.write(f"[*] port = {port}\n\n".encode()) timeout = 60 * 5 req.wfile.write(f"[*] This instance will stay up for {timeout} seconds\n".encode()) req.wfile.flush() start_time = time.time() try: proc = subprocess.run([ "./launch.sh", IP_BASE.format(instance_idx), IFACE.format(instance_idx - 1), real_ip, CHAL_NET_PREFIX + str(instance_idx), CHAL_IMAGE_NAME ], stdout=subprocess.PIPE, timeout=3, check=True, text=True) except Exception as e: req.wfile.write(b"[*] Error\n") req.wfile.flush() return try: req.wfile.write(f"\n[!] Instance running!\n".encode()) req.wfile.write(f"\nOptions:\n".encode()) req.wfile.write(f" [1] Launch bot with real flag\n".encode()) req.wfile.write(f" [2] Launch bot with custom flag\n".encode()) req.wfile.write(f"Choice: ".encode()) except Exception as e: pass container_id = proc.stdout.split("\n")[0] bot_container_id = None last_health_check = time.time() while time.time() - start_time < timeout: try: if time.time() - last_health_check > 10: status_check = subprocess.run(["./status.sh", container_id], timeout=3) if status_check.returncode != 0: logger.warning(f"Container died for {real_ip}") break last_health_check = time.time() if bot_container_id is None: # non-blocking bot_container_id = process_command( req, CHAL_NET_PREFIX + str(instance_idx) ) time.sleep(1) if is_socket_closed(req.connection): logger.warning(f"{real_ip} closed\n") break except Exception as e: logger.warning(str(e)) raise e break try: kill = subprocess.run(["./kill.sh", container_id], timeout=3) if bot_container_id is not None: kill = subprocess.run(["./kill.sh", bot_container_id], timeout=3) except Exception as e: req.wfile.write(b"[*] Error. Please contact admins.\n") logger.warning(str(e)) pass req.wfile.write(b"[*] Done. Goodbye!\n") req.wfile.flush() if __name__ == "__main__": port = 9000 MY_IP = requests.get("https://api.ipify.org?format=json").json()['ip'] with MyTCPServer(("0.0.0.0", port), MyTCPHandler) as server: try: pool = ThreadPool(processes=NUM_SERVERS) print(f"[*] Listening on port {port}") server.serve_forever() finally: pool.close()
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/BuckeyeCTF/2023/pwn/chat_app/instancer/pow.py
ctfs/BuckeyeCTF/2023/pwn/chat_app/instancer/pow.py
#!/usr/bin/env python3 # This is from kCTF (modified to remove backdoor) # https://github.com/google/kctf/blob/69bf578e1275c9223606ab6f0eb1e69c51d0c688/docker-images/challenge/pow.py # -*- coding: utf-8 -*- # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import base64 import os import secrets import socket import sys import hashlib try: import gmpy2 HAVE_GMP = True except ImportError: HAVE_GMP = False sys.stderr.write("[NOTICE] Running 10x slower, gotta go fast? pip3 install gmpy2\n") VERSION = 's' MODULUS = 2**1279-1 CHALSIZE = 2**128 SOLVER_URL = 'https://goo.gle/kctf-pow' def python_sloth_root(x, diff, p): exponent = (p + 1) // 4 for i in range(diff): x = pow(x, exponent, p) ^ 1 return x def python_sloth_square(y, diff, p): for i in range(diff): y = pow(y ^ 1, 2, p) return y def gmpy_sloth_root(x, diff, p): exponent = (p + 1) // 4 for i in range(diff): x = gmpy2.powmod(x, exponent, p).bit_flip(0) return int(x) def gmpy_sloth_square(y, diff, p): y = gmpy2.mpz(y) for i in range(diff): y = gmpy2.powmod(y.bit_flip(0), 2, p) return int(y) def sloth_root(x, diff, p): if HAVE_GMP: return gmpy_sloth_root(x, diff, p) else: return python_sloth_root(x, diff, p) def sloth_square(x, diff, p): if HAVE_GMP: return gmpy_sloth_square(x, diff, p) else: return python_sloth_square(x, diff, p) def encode_number(num): size = (num.bit_length() // 24) * 3 + 3 return str(base64.b64encode(num.to_bytes(size, 'big')), 'utf-8') def decode_number(enc): return int.from_bytes(base64.b64decode(bytes(enc, 'utf-8')), 'big') def decode_challenge(enc): dec = enc.split('.') if dec[0] != VERSION: raise Exception('Unknown challenge version') return list(map(decode_number, dec[1:])) def encode_challenge(arr): return '.'.join([VERSION] + list(map(encode_number, arr))) def get_challenge(diff): x = secrets.randbelow(CHALSIZE) return encode_challenge([diff, x]) def solve_challenge(chal): [diff, x] = decode_challenge(chal) y = sloth_root(x, diff, MODULUS) return encode_challenge([y]) def verify_challenge(chal, sol): [diff, x] = decode_challenge(chal) [y] = decode_challenge(sol) res = sloth_square(y, diff, MODULUS) return (x == res) or (MODULUS - x == res) def usage(): sys.stdout.write('Usage:\n') sys.stdout.write('Solve pow: {} solve $challenge\n') sys.stdout.write('Check pow: {} ask $difficulty\n') sys.stdout.write(' $difficulty examples (for 1.6GHz CPU) in fast mode:\n') sys.stdout.write(' 1337: 1 sec\n') sys.stdout.write(' 31337: 30 secs\n') sys.stdout.write(' 313373: 5 mins\n') sys.stdout.flush() sys.exit(1) def main(): if len(sys.argv) != 3: usage() sys.exit(1) cmd = sys.argv[1] if cmd == 'ask': difficulty = int(sys.argv[2]) if difficulty == 0: sys.stdout.write("== proof-of-work: disabled ==\n") sys.exit(0) challenge = get_challenge(difficulty) sys.stdout.write("== proof-of-work: enabled ==\n") sys.stdout.write("please solve a pow first\n") sys.stdout.write("You can run the solver with:\n") sys.stdout.write(" python3 <(curl -sSL {}) solve {}\n".format(SOLVER_URL, challenge)) sys.stdout.write("===================\n") sys.stdout.write("\n") sys.stdout.write("Solution? ") sys.stdout.flush() solution = '' with os.fdopen(0, "rb", 0) as f: while not solution: line = f.readline().decode("utf-8") if not line: sys.stdout.write("EOF") sys.stdout.flush() sys.exit(1) solution = line.strip() if verify_challenge(challenge, solution): sys.stdout.write("Correct\n") sys.stdout.flush() sys.exit(0) else: sys.stdout.write("Proof-of-work fail") sys.stdout.flush() elif cmd == 'solve': challenge = sys.argv[2] solution = solve_challenge(challenge) if verify_challenge(challenge, solution, False): sys.stderr.write("Solution: \n".format(solution)) sys.stderr.flush() sys.stdout.write(solution) sys.stdout.flush() sys.stderr.write("\n") sys.stderr.flush() sys.exit(0) else: usage() sys.exit(1) 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/BuckeyeCTF/2023/pwn/chat_app/instancer/server.py
ctfs/BuckeyeCTF/2023/pwn/chat_app/instancer/server.py
import hashlib import random import string import socket from socketserver import ThreadingTCPServer, StreamRequestHandler from multiprocessing import TimeoutError from multiprocessing.pool import ThreadPool import threading import subprocess import os import time import base64 from pathlib import Path import shutil import requests from proxyprotocol.v2 import ProxyProtocolV2 from proxyprotocol.reader import ProxyProtocolReader from proxyprotocol import ProxyProtocolWantRead from pow import get_challenge, verify_challenge, SOLVER_URL PORT_BASE = int(os.getenv("CHALL_PORT_BASE", "7000")) SERVER_IP_BASE = "10.0.4." CLIENT_IP_BASE = "10.0.5." POW_DIFFICULTY = int(os.getenv("POW_DIFFICULTY", "0")) NUM_SERVERS = int(os.getenv("CHALL_NUM_SERVERS", "5")) DEBUG = int(os.getenv("INSTANCER_DEBUG", "0")) == 1 MY_IP = None class MyTCPServer(ThreadingTCPServer): def server_bind(self): self.socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) self.socket.setsockopt(socket.SOL_SOCKET, socket.SO_KEEPALIVE, 1) self.socket.setsockopt(socket.IPPROTO_TCP, socket.TCP_KEEPIDLE, 10) self.socket.setsockopt(socket.IPPROTO_TCP, socket.TCP_KEEPINTVL, 3) self.socket.setsockopt(socket.IPPROTO_TCP, socket.TCP_KEEPCNT, 5) self.socket.bind(self.server_address) pool = None class MyTCPHandler(StreamRequestHandler): def handle(self): try: if not DEBUG: self.pp_result = read_proxy2(self) if not self.pp_result or not send_pow(self): return else: if not send_pow(self): return res = pool.apply_async(worker, (self,)) pos = pool._inqueue.qsize() # type: ignore self.wfile.write(f"[*] Queued in position {pos}\n".encode()) res.get(timeout=180) except (ConnectionError, TimeoutError) as e: print("connection err: %s" % (e)) pass def read_proxy2(req: MyTCPHandler): pp_reader = ProxyProtocolReader(ProxyProtocolV2()) pp_data = bytearray() while True: try: return pp_reader._parse(pp_data) except ProxyProtocolWantRead as want_read: try: if want_read.want_bytes is not None: pp_data += req.rfile.read(want_read.want_bytes) elif want_read.want_line: pp_data += req.rfile.readline() else: print("ProxyProtocolWantRead of unknown length") return None except (EOFError, ConnectionResetError) as exc: print("EOF waiting for proxy data") return None def send_pow(req: MyTCPHandler): if POW_DIFFICULTY == 0: req.wfile.write(b"== proof-of-work: disabled ==\n") req.wfile.flush() return True challenge = get_challenge(POW_DIFFICULTY) req.wfile.write(b"== proof-of-work: enabled ==\n") req.wfile.write(b"please solve a pow first\n") req.wfile.write(b"You can run the solver with:\n") req.wfile.write(" python3 <(curl -sSL {}) solve {}\n".format(SOLVER_URL, challenge).encode()) req.wfile.write(b"===================\n") req.wfile.write(b"\n") req.wfile.write(b"Solution? ") req.wfile.flush() solution = '' while not solution: solution = req.rfile.readline().decode("utf-8").strip() if verify_challenge(challenge, solution): req.wfile.write(b"Correct\n") req.wfile.flush() return True else: req.wfile.write(b"Proof-of-work fail") req.wfile.flush() return False thread_to_port = {} thread_port_lock = threading.Lock() def get_port(ident): global thread_to_port thread_port_lock.acquire() if ident in thread_to_port: port = thread_to_port[ident] else: port = len(thread_to_port) + PORT_BASE + 2 # leave .0 and .1 unused thread_to_port[ident] = port thread_port_lock.release() return port def is_socket_closed(sock) -> bool: try: # this will try to read bytes without blocking and also without removing them from buffer (peek only) data = sock.recv(16, socket.MSG_DONTWAIT | socket.MSG_PEEK) if len(data) == 0: return True return False except BlockingIOError: return False # socket is open and reading from it would block except ConnectionResetError: return True # socket was closed for some other reason except Exception as e: logger.exception("unexpected exception when checking if a socket is closed") return False return False def worker(req: MyTCPHandler): ip = req.client_address[0] src_port = req.client_address[1] if not DEBUG: real_ip = req.pp_result.source[0].exploded else: real_ip = ip print(f"Worker {threading.get_ident()} handling real ip {real_ip}") req.wfile.write(b"[+] Handling your job now\n") id = os.urandom(16).hex() path = Path("/tmp") / id if not path.exists(): path.mkdir() port = get_port(threading.get_ident()) req.wfile.write(f"\n[*] ip = {MY_IP}\n".encode()) req.wfile.write(f"[*] port = {port}\n\n".encode()) timeout = 60 * 5 req.wfile.write(f"[*] This instance will stay up for {timeout} seconds\n".encode()) req.wfile.flush() proc = subprocess.Popen(["./start_server.sh", SERVER_IP_BASE+str(port - PORT_BASE), real_ip], stdout=req.wfile) time.sleep(3) client_proc = subprocess.Popen(["./start_client.sh", CLIENT_IP_BASE+str(port - PORT_BASE), SERVER_IP_BASE+str(port - PORT_BASE)], stdout=subprocess.PIPE) req.wfile.write(f"[*] Client IP: {CLIENT_IP_BASE+str(port - PORT_BASE)}\n".encode()) req.wfile.flush() for x in range(timeout // 5): try: proc.wait(5) break except subprocess.TimeoutExpired: if is_socket_closed(req.request): break proc.terminate() try: proc.wait(1) except subprocess.TimeoutExpired: proc.kill() client_proc.terminate() try: client_proc.wait(1) except subprocess.TimeoutExpired: client_proc.kill() req.wfile.write(b"[*] Done. Goodbye!\n") req.wfile.flush() if __name__ == "__main__": port = 9000 MY_IP = requests.get("https://api.ipify.org?format=json").json()['ip'] with MyTCPServer(("0.0.0.0", port), MyTCPHandler) as server: try: pool = ThreadPool(processes=NUM_SERVERS) print(f"[*] Listening on port {port}") server.serve_forever() finally: pool.close()
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/BuckeyeCTF/2023/rev/Skribl/chal/setup.py
ctfs/BuckeyeCTF/2023/rev/Skribl/chal/setup.py
from setuptools import find_packages, setup setup( name='flaskr', version='1.0.0', packages=find_packages(), include_package_data=True, zip_safe=False, install_requires=[ 'flask', 'Bootstrap-Flask', 'Flask-WTF' ], )
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/BuckeyeCTF/2023/rev/Skribl/chal/__init__.py
ctfs/BuckeyeCTF/2023/rev/Skribl/chal/__init__.py
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/BuckeyeCTF/2023/rev/Skribl/chal/skribl.py
ctfs/BuckeyeCTF/2023/rev/Skribl/chal/skribl.py
import math import time from flask import Flask, render_template, redirect, url_for, request from flask_bootstrap import Bootstrap5 from flask_wtf import FlaskForm, CSRFProtect from wtforms import StringField, SubmitField from wtforms.validators import DataRequired, Length # Don't try this at home, kids try: from backend import create_skribl, init_backend except: from .backend import create_skribl, init_backend app = Flask(__name__) app.secret_key = 'tO$&!|0wkamvVia0?n$NqIRVWOG' bootstrap = Bootstrap5(app) csrf = CSRFProtect(app) skribls = {} stime = math.floor(time.time()) init_backend(skribls) class SkriblForm(FlaskForm): skribl = StringField('Your message: ', validators=[DataRequired(), Length(1, 250)]) author = StringField("Your name:", validators=[Length(0, 40)]) submit = SubmitField('Submit') @app.route('/', methods=['GET', 'POST']) def index(): form = SkriblForm() message = "" if form.validate_on_submit(): message = form.skribl.data author = form.author.data key = create_skribl(skribls, message, author) return redirect(url_for('view', key=key)) return render_template('index.html', form=form, error_msg=request.args.get("error_msg", '')) @app.route('/view/<key>', methods=['GET']) def view(key): print(f"Viewing with key {key}") if key in skribls: message, author = skribls[key] return render_template("view.html", message=message, author=author, key=key) else: return redirect(url_for('index', error_msg=f"Skribl not found: {key}")) @app.route('/about', methods=["GET"]) def about(): return render_template('about.html') @app.context_processor def inject_stime(): return dict(stime=math.floor(time.time()) - stime)
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/BuckeyeCTF/2023/crypto/My_First_Hash/my-first-hash.py
ctfs/BuckeyeCTF/2023/crypto/My_First_Hash/my-first-hash.py
import hashlib from sys import exit flag = '8f163b472e2164f66a5cd751098783f9' str = input("Enter the flag\n") str = hashlib.md5(str.encode()) if str.digest().hex() == flag: print("Congrats! You got the flag!") else: print("Nope. Try again!") exit()
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/BuckeyeCTF/2023/crypto/Turtle_Tree/util.py
ctfs/BuckeyeCTF/2023/crypto/Turtle_Tree/util.py
import secrets import hashlib empty_node_identifier = b"E" leaf_node_identifier = b"L" def bytes_to_bits(bs: bytes) -> list[int]: bits = [0] * (len(bs) * 8) for i in range(len(bits)): byte_index = i // 8 bit_of_byte = i % 8 bits[i] = int((bs[byte_index] << bit_of_byte) & (1 << 7) > 0) return bits def bits_to_bytes(bits: list[int]) -> bytes: bs = [0] * ((len(bits) + 7) // 8) for i, x in enumerate(bits): if x == 1: byte_index = i // 8 bit_of_byte = i % 8 bs[byte_index] |= x << (7 - (bit_of_byte)) return bytes(bs) def get_nth_bit(bs: bytes, n: int) -> int: byte_index = n // 8 bit_of_byte = n % 8 return int((bs[byte_index] & (1 << (7 - bit_of_byte))) != 0)
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/BuckeyeCTF/2023/crypto/Turtle_Tree/main.py
ctfs/BuckeyeCTF/2023/crypto/Turtle_Tree/main.py
from merkle_tree import * import json import hashlib import secrets import random from cryptography.hazmat.primitives import hashes from cryptography.hazmat.primitives.asymmetric import ec from cryptography.hazmat.primitives.serialization import ( Encoding, PublicFormat, load_pem_public_key, ) from cryptography.hazmat.primitives.kdf.hkdf import HKDF from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes from flag import flag class Server: merkle_tree: MerkleTree usernames: set def __init__(self): self.merkle_tree = MerkleTree() self.usernames = set() def register(self, username: str, public_key: bytes): if len(username) == 0: raise ValueError("Empty username") if username in self.usernames: raise ValueError("Username is taken") key = username.encode() value = public_key index = hashlib.sha256(key).digest() self.merkle_tree.set(index, key, value) self.usernames.add(username) def query(self, username: str) -> AuthenticationPath: key = username.encode() index = hashlib.sha256(key).digest() return self.merkle_tree.get(index) def generate_random_users(server): for i in range(256): username = f"user_{random.randbytes(4).hex()}" private_key = ec.generate_private_key(ec.SECP256R1()) server.register( username, private_key.public_key().public_bytes( Encoding.PEM, PublicFormat.SubjectPublicKeyInfo ), ) def bob_query_self(server, bob_public_key): print() print("Bob is querying his own key...") bob_ap = server.query("bob") if bob_ap.proof_type() != AuthenticationPath.proof_of_inclusion: raise ValueError("Bob expected a proof of inclusion") result, error = bob_ap.verify(bob_public_key, server.merkle_tree.root_hash) if not result: raise ValueError(f"Bob failed to verify authentication path: {error}") print("Bob successfully queried his own key!") print(f"Bob's authentication path was:\n{json.dumps(bob_ap.json_dict())}") return bob_ap def prompt_for_registration(server): print("Please register your username and public key with the server!") username = input("Enter your username: ") if type(username) is not str and len(username) == 0: raise ValueError("Invalid username") public_key = bytes.fromhex(input("Enter your public key in hex: ")) server.register(username, public_key) ap = server.query(username) print("Successfully registered!") def main(): server = Server() generate_random_users(server) alice_private_key = ec.generate_private_key(ec.SECP256R1()) alice_public_key = alice_private_key.public_key().public_bytes( Encoding.PEM, PublicFormat.SubjectPublicKeyInfo ) server.register("alice", alice_public_key) print(f"Alice's public key is {alice_public_key.hex()}") bob_private_key = ec.generate_private_key(ec.SECP256R1()) bob_public_key = bob_private_key.public_key().public_bytes( Encoding.PEM, PublicFormat.SubjectPublicKeyInfo ) server.register("bob", bob_public_key) print(f"Bob's public key is {alice_public_key.hex()}") bob_ap = bob_query_self(server, bob_public_key) prompt_for_registration(server) print() print("Alice is querying for Bob's public key.") print("But YOU are able to intercept this query and modify the username!") s = input("Please specify a username: ") if "bob" not in s: raise ValueError("Username is too suspicious") ap = server.query(s) result, error = ap.verify(None, server.merkle_tree.root_hash) if not result: raise ValueError(f"Alice failed peer validation of Bob: {error}") if ap.proof_type() != AuthenticationPath.proof_of_inclusion: raise ValueError("Alice expected a proof of inclusion") if ( bytes_to_bits(bob_ap.lookup_index)[: bob_ap.leaf.level] != bytes_to_bits(ap.lookup_index)[: bob_ap.leaf.level] ): raise ValueError("This authentication path isn't for Bob") print("Alice successfully verified the authentication path to Bob's public key!") print("Alice is sending the flag to Bob encrypted with his public key:") shared_key = alice_private_key.exchange(ec.ECDH(), load_pem_public_key(ap.leaf.value)) # type: ignore derived_key = HKDF( algorithm=hashes.SHA256(), length=32, salt=None, info=None, ).derive(shared_key) iv = secrets.token_bytes(16) cipher = Cipher(algorithms.AES(derived_key), modes.CBC(iv)) encryptor = cipher.encryptor() ct = encryptor.update(flag) + encryptor.finalize() print(f"Ciphertext: {ct.hex()}") print(f"IV: {iv.hex()}") 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/BuckeyeCTF/2023/crypto/Turtle_Tree/proof.py
ctfs/BuckeyeCTF/2023/crypto/Turtle_Tree/proof.py
from util import * import hashlib import struct class ProofNode: level: int index: bytes value: bytes | None def hash(self, tree_nonce: bytes) -> bytes: h = b"" if self.value == None: h = hashlib.sha256( empty_node_identifier + tree_nonce + self.index + struct.pack("<I", self.level) ).digest() else: h = hashlib.sha256( leaf_node_identifier + tree_nonce + self.index + struct.pack("<I", self.level) + self.value ).digest() return h def json_dict(self) -> dict: return { "level": self.level, "index": self.index.hex(), "value": self.value.hex() if self.value != None else None, } class AuthenticationPath: tree_nonce: bytes pruned_tree: list[bytes] lookup_index: bytes leaf: ProofNode proof_of_inclusion = 0 proof_of_absence = 1 def __init__(self): self.pruned_tree = [] def auth_path_hash(self) -> bytes: h = self.leaf.hash(self.tree_nonce) index_bits = bytes_to_bits(self.leaf.index) depth = self.leaf.level while depth > 0: depth -= 1 if index_bits[depth]: h = hashlib.sha256(self.pruned_tree[depth] + h).digest() else: h = hashlib.sha256(h + self.pruned_tree[depth]).digest() return h def proof_type(self): if self.lookup_index == self.leaf.index: return AuthenticationPath.proof_of_inclusion else: return AuthenticationPath.proof_of_absence def verify(self, value: bytes | None, tree_hash: bytes) -> tuple[bool, str | None]: if self.proof_type() == AuthenticationPath.proof_of_absence: index_bits = bytes_to_bits(self.leaf.index) lookup_index_bits = bytes_to_bits(self.lookup_index) if index_bits[: self.leaf.level] != lookup_index_bits[: self.leaf.level]: return ( False, "Lookup index is inconsistent with index of the proof node", ) else: if value != None and value != self.leaf.value: return (False, "Value does not match") if tree_hash != self.auth_path_hash(): return (False, "Authentication path hash does not match provided tree hash") return (True, None) def json_dict(self) -> dict: return { "tree_nonce": self.tree_nonce.hex(), "pruned_tree": [x.hex() for x in self.pruned_tree], "lookup_index": self.lookup_index.hex(), "leaf": self.leaf.json_dict(), }
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/BuckeyeCTF/2023/crypto/Turtle_Tree/merkle_tree.py
ctfs/BuckeyeCTF/2023/crypto/Turtle_Tree/merkle_tree.py
from __future__ import annotations from abc import ABC, abstractmethod import hashlib import struct import secrets from util import * from proof import * class Node(ABC): parent: Node | None level: int @abstractmethod def hash(self, merkle_tree: MerkleTree) -> bytes: pass class InteriorNode(Node): left_child: Node right_child: Node left_hash: bytes | None right_hash: bytes | None def __init__(self, parent: Node | None, level: int, prefix_bits: list[int]): self.parent = parent self.level = level self.left_child = EmptyNode() self.right_child = EmptyNode() self.left_child.level = level + 1 self.left_child.parent = self self.left_child.index = bits_to_bytes(prefix_bits + [0]) self.right_child.level = level + 1 self.right_child.parent = self self.right_child.index = bits_to_bytes(prefix_bits + [1]) self.left_hash = None self.right_hash = None def hash(self, merkle_tree: MerkleTree) -> bytes: if self.left_hash == None: self.left_hash = self.left_child.hash(merkle_tree) if self.right_hash == None: self.right_hash = self.right_child.hash(merkle_tree) return hashlib.sha256(self.left_hash + self.right_hash).digest() class LeafNode(Node): index: bytes key: bytes value: bytes def replace_with(self, node: LeafNode): self.parent = node.parent self.level = node.level self.index = node.index self.key = node.key self.value = node.value def hash(self, merkle_tree: MerkleTree) -> bytes: return hashlib.sha256( leaf_node_identifier + merkle_tree.nonce + self.index + struct.pack("<I", self.level) + self.value ).digest() class EmptyNode(Node): index: bytes def hash(self, merkle_tree: MerkleTree) -> bytes: return hashlib.sha256( empty_node_identifier + merkle_tree.nonce + self.index + struct.pack("<I", self.level) ).digest() class MerkleTree: root: InteriorNode nonce: bytes root_hash: bytes def __init__(self): self.root = InteriorNode(None, 0, []) self.nonce = secrets.token_bytes(32) self.root_hash = self.root.hash(self) def set(self, index: bytes, key: bytes, value: bytes): to_add = LeafNode() to_add.index = index to_add.key = key to_add.value = value self.insert_node(index, to_add) def insert_node(self, index: bytes, to_add: LeafNode): cursor = self.root depth = 0 index_bits = bytes_to_bits(index) while True: if type(cursor) is LeafNode: if cursor.parent == None: raise ValueError("Invalid tree") if cursor.index == index: # Replace the value to_add.parent = cursor.parent to_add.level = cursor.level cursor.replace_with(to_add) self.recompute_hash_upwards(cursor) return new_interior_node = InteriorNode( cursor.parent, depth, index_bits[:depth] ) direction = get_nth_bit(cursor.index, depth) if direction: new_interior_node.right_child = cursor else: new_interior_node.left_child = cursor cursor.level = depth + 1 cursor.parent = new_interior_node if type(new_interior_node.parent) is not InteriorNode: raise ValueError("Invalid tree") if new_interior_node.parent.left_child == cursor: new_interior_node.parent.left_child = new_interior_node elif new_interior_node.parent.right_child == cursor: new_interior_node.parent.right_child = new_interior_node else: raise ValueError("Invalid tree") cursor = new_interior_node elif type(cursor) is InteriorNode: direction = index_bits[depth] if direction: if type(cursor.right_child) is EmptyNode: cursor.right_child = to_add to_add.level = depth + 1 to_add.parent = cursor self.recompute_hash_upwards(to_add) break else: cursor = cursor.right_child else: if type(cursor.left_child) is EmptyNode: cursor.left_child = to_add to_add.level = depth + 1 to_add.parent = cursor self.recompute_hash_upwards(to_add) break else: cursor = cursor.left_child depth += 1 else: raise ValueError("Invalid tree") def recompute_hash_upwards(self, node: Node): cursor = node while cursor.parent != None: parent = cursor.parent if type(parent) is not InteriorNode: raise ValueError("Invalid tree") if parent.left_child == cursor: direction = 0 elif parent.right_child == cursor: direction = 1 else: raise ValueError("Invalid tree") if direction: parent.right_hash = cursor.hash(self) else: parent.left_hash = cursor.hash(self) cursor = parent if cursor != self.root: raise ValueError("Invalid tree") self.root_hash = self.root.hash(self) def get(self, lookup_index: bytes) -> AuthenticationPath: lookup_index_bits = bytes_to_bits(lookup_index) depth = 0 cursor = self.root auth_path = AuthenticationPath() auth_path.tree_nonce = self.nonce auth_path.lookup_index = lookup_index while True: if type(cursor) is LeafNode: break elif type(cursor) is EmptyNode: break elif type(cursor) is InteriorNode: direction = lookup_index_bits[depth] if direction: if cursor.left_hash == None: raise ValueError("Need to recompute hash") auth_path.pruned_tree.append(cursor.left_hash) cursor = cursor.right_child else: if cursor.right_hash == None: raise ValueError("Need to recompute hash") auth_path.pruned_tree.append(cursor.right_hash) cursor = cursor.left_child depth += 1 else: raise ValueError("Invalid tree") if type(cursor) is LeafNode: auth_path.leaf = ProofNode() auth_path.leaf.level = cursor.level auth_path.leaf.index = cursor.index auth_path.leaf.value = cursor.value return auth_path elif type(cursor) is EmptyNode: auth_path.leaf = ProofNode() auth_path.leaf.level = cursor.level auth_path.leaf.index = cursor.index auth_path.leaf.value = None return auth_path else: raise ValueError("Invalid tree") def recompute_hash(self): self.root_hash = self.root.hash(self)
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/BuckeyeCTF/2023/crypto/Rivest_Shamir_Adleman/dist.py
ctfs/BuckeyeCTF/2023/crypto/Rivest_Shamir_Adleman/dist.py
message = b"[REDACTED]" m = int.from_bytes(message, "big") p = 3782335750369249076873452958462875461053 q = 9038904185905897571450655864282572131579 e = 65537 n = p * q et = (p - 1) * (q - 1) d = pow(e, -1, et) c = pow(m, e, n) print(f"e = {e}") print(f"n = {n}") print(f"c = {c}") # OUTPUT: # e = 65537 # n = 34188170446514129546929337540073894418598952490293570690399076531159358605892687 # c = 414434392594516328988574008345806048885100152020577370739169085961419826266692
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/BuckeyeCTF/2023/crypto/Real_Smooth/main.py
ctfs/BuckeyeCTF/2023/crypto/Real_Smooth/main.py
from Crypto.Cipher import ChaCha20 from Crypto.Random import get_random_bytes def encrypt(key, nonce, plaintext): chacha = ChaCha20.new(key=key, nonce=nonce) return chacha.encrypt(plaintext) def main(): lines = open("passwords.txt", "rb").readlines() key = get_random_bytes(32) nonce = get_random_bytes(8) lines = [x.ljust(18) for x in lines] lines = [encrypt(key, nonce, x) for x in lines] open("database.txt", "wb").writelines(lines) 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/BuckeyeCTF/2023/web/Text_Adventure_API/server.py
ctfs/BuckeyeCTF/2023/web/Text_Adventure_API/server.py
#!/usr/local/bin/python import os import io import pickle from flask import Flask, Response, request, jsonify, session from waitress import serve app = Flask(__name__) app.secret_key = os.environ.get("FLASK_SECRET_KEY", "") rooms = { "start": { "description": "You are in a kitchen. There's a table, a cabinet, and a fridge.", "exits": ["table", "cabinet", "fridge"] }, "table": { "description": "You find a table with some items on it.", "exits": ["start"], "objects": { "note": "A handwritten note with a message.", "apple": "A shiny red apple." } }, "cabinet": { "description": "You open the cabinet and see various utensils.", "exits": ["start"], "objects": { "spoon": "A metal spoon.", "fork": "A fork with three prongs." } }, "fridge": { "description": "You open the fridge and see various food items.", "exits": ["start"], "objects": { "milk": "A carton of fresh milk.", "eggs": "A dozen eggs in a container." } } } @app.route('/api/move', methods=['POST']) def move(): data = request.get_json() exit_choice = data.get("exit") current_location = get_current_location() if exit_choice in rooms[current_location]["exits"]: session['current_location'] = exit_choice return jsonify({"message": f"You move to the {exit_choice}. {rooms[exit_choice]['description']}"}) else: return jsonify({"message": "You can't go that way."}) @app.route('/api/examine', methods=['GET']) def examine(): current_location = get_current_location() room_description = rooms[current_location]['description'] exits = rooms[current_location]['exits'] if "objects" in rooms[current_location]: objects = rooms[current_location]['objects'] return jsonify({"current_location": current_location, "description": room_description, "objects": [obj for obj in objects], "exits": exits}) else: return jsonify({"current_location": current_location, "description": room_description, "message": "There are no objects to examine here.", "exits": exits}) @app.route('/api/examine/<object_name>', methods=['GET']) def examine_object(object_name): current_location = get_current_location() if "objects" in rooms[current_location] and object_name in rooms[current_location]['objects']: object_description = rooms[current_location]['objects'][object_name] return jsonify({"object": object_name, "description": object_description}) else: return jsonify({"message": f"{object_name} not found or cannot be examined here."}) def get_current_location(): return session.get('current_location', 'start') @app.route('/api/save', methods=['GET']) def save_session(): session_data = { 'current_location': get_current_location() # Add other session-related data as needed } memory_stream = io.BytesIO() pickle.dump(session_data, memory_stream) response = Response(memory_stream.getvalue(), content_type='application/octet-stream') response.headers['Content-Disposition'] = 'attachment; filename=data.pkl' return response @app.route('/api/load', methods=['POST']) def load_session(): if 'file' not in request.files: return jsonify({"message": "No file part"}) file = request.files['file'] if file and file.filename.endswith('.pkl'): try: loaded_session = pickle.load(file) session.update(loaded_session) except: return jsonify({"message": "Failed to load save game session."}) return jsonify({"message": "Game session loaded."}) else: return jsonify({"message": "Invalid file format. Please upload a .pkl file."}) if __name__ == '__main__': if os.environ.get("DEPLOY_ENV") == "production": serve(app, host='0.0.0.0', port=5000) else: 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/BuckeyeCTF/2025/misc/monkeys/monkeys-template.py
ctfs/BuckeyeCTF/2025/misc/monkeys/monkeys-template.py
from pwn import * io = remote("monkeys.challs.pwnoh.io", 1337, ssl=True) io.recvuntil(b"code:\n") io.sendline(b""" function(input) return input .. string.char(0x98) end """) io.sendline(b"EOF") data = io.recvline() + io.recvline() if b"Output bytestring: " in data: output = bytes.fromhex(data.split(b": ")[1].strip().decode()) info(f"{len(output)=}") # transform output back into input... input = output io.sendline(input.hex().encode()) print(io.recvall().decode().strip()) else: print((data + io.recvall()).decode().strip())
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/BuckeyeCTF/2025/rev/Square_Cipher/square_cipher.py
ctfs/BuckeyeCTF/2025/rev/Square_Cipher/square_cipher.py
(lambda x=int(input('> '),16):(all((int(bin(y).translate(str.maketrans('1b','fx')),0)&x).bit_count()==15 for y in[511,261632,1838599,14708792,117670336,133955584,68585259008,35115652612096,246772580483072,1974180643864576,15793445150916608,17979214137393152,9205357638345293824,4713143110832790437888,4731607904558235517441,9463215809116471034882,18926431618232942069764,33121255085135066300416,37852863236465884139528,75705726472931768279056,151411452945863536558112,264970040681080530403328,302822905891727073116224,605645811783454146232448,1211291623566908292464896,2119760325448644243226624,2413129272746388704198656])and x&2135465562637171390290201561322170738230609084732268110734985633502584038857972308065155558608880==1271371190459412480076309932821732439054921890752535035282222258816851982409101952239053178406432 or print('incorrect'))and print(__import__('os').environ.get('FLAG','bctf{fake_flag}')))()
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/BuckeyeCTF/2025/crypto/nitwit/nitwit.py
ctfs/BuckeyeCTF/2025/crypto/nitwit/nitwit.py
import hashlib import random import ast from math import log from flag import flag """ This implements Winternitz one-time signatures as defined in http://toc.cryptobook.us """ # Define Winternitz parameters v = 256 # maximum bits for message size hash_size = 32 d = 15 # base n_0 = 64 assert (d + 1) ** n_0 == 2**v n_1 = int(log(n_0, d + 1)) + 1 n = n_0 + n_1 def get_hash(x: bytes) -> bytes: return hashlib.sha256(x).digest() def hash_chain(x: bytes, d: int) -> bytes: for _ in range(d): x = get_hash(x) return x def int_to_vec(m: int, vec_len: int, base: int) -> list[int]: # Given an integer, output a vector that represents the digits of m in the # specified base (big-endian) digits = [0] * vec_len i = len(digits) - 1 while m > 0: digits[i] = m % base m //= base i -= 1 return digits def domination_free_function(m: int) -> list[int]: # This function maps an integer to a vector. # What is a domination free function? # Let f(a) = xs # Let f(b) = ys # If f is a domination free function, then # all(x[i] >= y[i] for i in range(len(xs))) # must be false for any integers a and b. m_vec = int_to_vec(m, n_0, d + 1) # Compute checksum c = (d * n_0) - sum(m_vec) c_vec = int_to_vec(c, n_1, d + 1) return m_vec + c_vec class Winternitz: def __init__(self): # Secret key stuff self.secret = random.SystemRandom().getrandbits(v) prg = random.Random(self.secret) self.xs = [prg.randbytes(hash_size) for _ in range(n)] # Public key stuff self.ys = [hash_chain(x, d) for x in self.xs] def public_key(self) -> bytes: return get_hash(b"".join(self.ys)) def sign(self, m: bytes) -> list[bytes]: if len(m) * 8 > v: raise ValueError("Message too long") ss = domination_free_function(int.from_bytes(m, "big")) return [hash_chain(self.xs[i], s) for i, s in enumerate(ss)] def verify(self, public_key: bytes, m: bytes, signature: list[bytes]): ss = domination_free_function(int.from_bytes(m, "big")) ys = [hash_chain(signature[i], d - s) for i, s in enumerate(ss)] return public_key == get_hash(b"".join(ys)) def main(): print("Welcome to my signing service!") w = Winternitz() pk = w.public_key() print(f"Public key: {pk.hex()}") print("Enter a message to sign as hex string:") m = bytes.fromhex(input(">>> ")) if b"admin" in m: print("Not authorized") return sig = w.sign(m) print(f"Your signature is:") print(sig) print() print("Can you forge a signature for another message?") print("Enter a new message to sign as a hex string:") m_new = bytes.fromhex(input(">>> ")) if m == m_new: print("Repeated message") return print("Enter signature:") forged_sig = ast.literal_eval(input(">>> ")) print(forged_sig) if type(forged_sig) is not list: print("Bad signature") return if len(forged_sig) != n: print("Bad signature") return if not all(type(x) is bytes for x in forged_sig): print("Bad signature") return if not all(len(x) == hash_size for x in forged_sig): print("Bad signature") return if w.verify(pk, m_new, forged_sig): if b"admin" in m_new: print("You must be the admin, so here's your flag:") print(flag) else: print("Valid signature, but you're not admin") else: print("Signature failed to verify") 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/BuckeyeCTF/2025/crypto/Augury/main.py
ctfs/BuckeyeCTF/2025/crypto/Augury/main.py
import hashlib stored_data = {} def generate_keystream(i): return (i * 3404970675 + 3553295105) % (2 ** 32) def upload_file(): print("Choose a name for your file") name = input() if name in stored_data: print("There is already a file with that name") return print("Remember that your privacy is our top priority and all stored files are encrypted.") print("Choose a password") password = input() m = hashlib.shake_128() m.update(password.encode()) keystream = int.from_bytes(m.digest(4), byteorder="big") print("Now upload the contents of your file in hexadecimal") contents = input() b = bytearray(bytes.fromhex(contents)) for i in range(0, len(b), 4): key = keystream.to_bytes(4, byteorder="big") b[i + 0] ^= key[0] if i + 1 >= len(b): continue b[i + 1] ^= key[1] if i + 2 >= len(b): continue b[i + 2] ^= key[2] if i + 3 >= len(b): continue b[i + 3] ^= key[3] keystream = generate_keystream(keystream) stored_data[name] = b print("Your file has been uploaded and encrypted") def view_files(): print("Available files:") for i in stored_data.keys(): print(i) print("Choose a file to get") name = input() if name not in stored_data: print("That file is not available") return print(stored_data[name].hex()) def main(): print("Welcome to Augury") print("The best place for secure storage!") while True: print("Please select an option:") print("1. Upload File") print("2. View Files") print("3. Exit") choice = input() match choice: case "1": upload_file() case "2": view_files() case "3": exit() main()
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/BuckeyeCTF/2022/rev/tokenstokens/interact.py
ctfs/BuckeyeCTF/2022/rev/tokenstokens/interact.py
import time import random import subprocess from transformers import AutoTokenizer import os tokenizer = AutoTokenizer.from_pretrained("etokenizer") # tokenize user input x = input('enter ONE command: ') tokens = tokenizer.convert_tokens_to_ids(tokenizer.tokenize(x)) args = [os.path.join(os.getcwd(),'tokenstokens')] for i in range(len(tokens)): args.append(str(tokens[i])) # pretend to do something for i in range(8): time.sleep(random.randint(1,4)) print('thinking...') if (random.randint(0, 1) == 1): print('eek!') break print('running:') # C program! popen = subprocess.Popen(args, stdout=subprocess.PIPE) popen.wait() print(popen.stdout.read())
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/BuckeyeCTF/2022/crypto/TwinPrimeRSA/chall.py
ctfs/BuckeyeCTF/2022/crypto/TwinPrimeRSA/chall.py
import Crypto.Util.number as cun while True: p = cun.getPrime(1024) q = p + 2 if cun.isPrime(q): break n = p * q e = 0x10001 phi = (p - 1) * (q - 1) d = pow(e, -1, phi) FLAG = cun.bytes_to_long(b"buckeye{?????????????????????????????????????????????????????????????}") c = pow(FLAG, e, n) assert pow(c, d, n) == FLAG print(f"n = {n}") print(f"c = {c}") """ Output: n = 20533399299284046407152274475522745923283591903629216665466681244661861027880216166964852978814704027358924774069979198482663918558879261797088553574047636844159464121768608175714873124295229878522675023466237857225661926774702979798551750309684476976554834230347142759081215035149669103794924363457550850440361924025082209825719098354441551136155027595133340008342692528728873735431246211817473149248612211855694673577982306745037500773163685214470693140137016315200758901157509673924502424670615994172505880392905070519517106559166983348001234935249845356370668287645995124995860261320985775368962065090997084944099 c = 786123694350217613420313407294137121273953981175658824882888687283151735932871244753555819887540529041840742886520261787648142436608167319514110333719357956484673762064620994173170215240263058130922197851796707601800496856305685009993213962693756446220993902080712028435244942470308340720456376316275003977039668016451819131782632341820581015325003092492069871323355309000284063294110529153447327709512977864276348652515295180247259350909773087471373364843420431252702944732151752621175150127680750965262717903714333291284769504539327086686569274889570781333862369765692348049615663405291481875379224057249719713021 """
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/BuckeyeCTF/2022/crypto/QuadPrimeRSA/chall.py
ctfs/BuckeyeCTF/2022/crypto/QuadPrimeRSA/chall.py
import Crypto.Util.number as cun p = cun.getPrime(500) while True: q = cun.getPrime(1024) r = q + 2 if cun.isPrime(r): break s = cun.getPrime(500) n_1 = p * q n_2 = r * s e = 0x10001 d_1 = pow(e, -1, (p - 1) * (q - 1)) d_2 = pow(e, -1, (r - 1) * (s - 1)) FLAG = cun.bytes_to_long(b"buckeye{??????????????????????????????????????????????????????????????????????}") c_1 = pow(FLAG, e, n_1) c_2 = pow(FLAG, e, n_2) assert pow(c_1, d_1, n_1) == FLAG assert pow(c_2, d_2, n_2) == FLAG print(f"n_1 = {n_1}") print(f"n_2 = {n_2}") print(f"c_1 = {c_1}") print(f"c_2 = {c_2}") """ Output: n_1 = 266809852588733960459210318535250490646048889879697803536547660295087424359820779393976863451605416209176605481092531427192244973818234584061601217275078124718647321303964372896579957241113145579972808278278954608305998030194591242728217565848616966569801983277471847623203839020048073235167290935033271661610383018423844098359553953309688771947405287750041234094613661142637202385185625562764531598181575409886288022595766239130646497218870729009410265665829 n_2 = 162770846172885672505993228924251587431051775841565579480252122266243384175644690129464185536426728823192871786769211412433986353757591946187394062238803937937524976383127543836820456373694506989663214797187169128841031021336535634504223477214378608536361140638630991101913240067113567904312920613401666068950970122803021942481265722772361891864873983041773234556100403992691699285653231918785862716655788924038111988473048448673976046224094362806858968008487 c_1 = 90243321527163164575722946503445690135626837887766380005026598963525611082629588259043528354383070032618085575636289795060005774441837004810039660583249401985643699988528916121171012387628009911281488352017086413266142218347595202655520785983898726521147649511514605526530453492704620682385035589372309167596680748613367540630010472990992841612002290955856795391675078590923226942740904916328445733366136324856838559878439853270981280663438572276140821766675 c_2 = 111865944388540159344684580970835443272640009631057414995719169861041593608923140554694111747472197286678983843168454212069104647887527000991524146682409315180715780457557700493081056739716146976966937495267984697028049475057119331806957301969226229338060723647914756122358633650004303172354762801649731430086958723739208772319851985827240696923727433786288252812973287292760047908273858438900952295134716468135711755633215412069818249559715918812691433192840 """
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/BuckeyeCTF/2022/crypto/fastfor/check_hash.py
ctfs/BuckeyeCTF/2022/crypto/fastfor/check_hash.py
from PIL import Image import numpy def check_hash(fi): image = numpy.asarray(Image.open('static/IMG.png')) submission = numpy.asarray(Image.open(fi)) if image.shape != submission.shape: return False same = numpy.bitwise_xor(image, submission) if (numpy.sum(same) == 0): return False im_alt = numpy.fft.fftn(image) in_alt = numpy.fft.fftn(submission) im_hash = numpy.std(im_alt) in_hash = numpy.std(in_alt) if im_hash - in_hash < 1 and im_hash - in_hash > -1: return True return False
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/BuckeyeCTF/2022/crypto/SSSHIT/chall.py
ctfs/BuckeyeCTF/2022/crypto/SSSHIT/chall.py
import Crypto.Util.number as cun import random import ast def evaluate_polynomial(polynomial: list, x: int, p: int): return ( sum( (coefficient * pow(x, i, p)) % p for i, coefficient in enumerate(polynomial) ) % p ) N_SHARES = 3 def main(): print( f"I wrote down a list of people who are allowed to get the flag and split it into {N_SHARES} using Shamir's Secret Sharing." ) MESSAGE = cun.bytes_to_long(b"qxxxb, BuckeyeCTF admins, and NOT YOU") p = cun.getPrime(512) polynomial = [MESSAGE] + [random.randrange(1, p) for _ in range(N_SHARES - 1)] points = [(i, evaluate_polynomial(polynomial, i, p)) for i in range(1, N_SHARES + 1)] print("Your share is:") print(points[0]) print("The other shares are:") for i in range(1, len(points)): print(points[i]) print() print("Now submit your share for reconstruction:") your_input = ast.literal_eval(input(">>> ")) if ( type(your_input) is not tuple or len(your_input) != 2 or type(your_input[0]) is not int or type(your_input[1]) is not int or your_input[0] != 1 or not (0 <= your_input[1] < p) ): print("Bad input") return points[0] = your_input xs = [point[0] for point in points] ys = [point[1] for point in points] y_intercept = 0 for j in range(N_SHARES): product = 1 for i in range(N_SHARES): if i != j: product = (product * xs[i] * pow(xs[i] - xs[j], -1, p)) % p y_intercept = (y_intercept + ys[j] * product) % p reconstructed_message = cun.long_to_bytes(y_intercept) if reconstructed_message == b"qxxxb, BuckeyeCTF admins, and ME": print("Here's your flag:") print("buckeye{?????????????????????????????????????????}") else: print(f"Sorry, only these people can see the flag: {reconstructed_message}") main()
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false