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/Ugra/2024/Quals/crypto/Eat_the_rich/prover.py
ctfs/Ugra/2024/Quals/crypto/Eat_the_rich/prover.py
import gmpy2 import json import random import requests import time BASE = "https://securityisamyth.q.2024.ugractf.ru" TOKEN = input("Enter token: ") p, g, y = [int(n, 16) for n in requests.post(f"{BASE}/{TOKEN}/get-parameters").text.split(", ")] print("Computing, please wait...") rs = [random.randint(0, p - 2) for _ in range(32)] cs = [int(gmpy2.powmod(g, r, p)) for r in rs] choices = eval(requests.post(f"{BASE}/{TOKEN}/announce-cs", data=b"".join(c.to_bytes(16384 // 8) for c in cs)).text) x = eval(input(f"Please solve {g:x}^x = 0x{y:x} (mod 0x{p:x}) for x: ")) print("Verifying...") answers = [(x + r) % (p - 1) if choice == 0 else r for r, choice in zip(rs, choices)] result = requests.post(f"{BASE}/{TOKEN}/answer-choices", data=b"".join(answer.to_bytes(16384 // 8) for answer in answers)).text print(result)
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/Null/2025/misc/Reservation/reservation.py
ctfs/Null/2025/misc/Reservation/reservation.py
import os import socket from dotenv import load_dotenv # from python-dotenv load_dotenv() FLAG = os.getenv("FLAG", "nullctf{aergnoujiwaegnjwkoiqergwnjiokeprgwqenjoig}") PROMPT = os.getenv("PROMPT", "bananananannaanan") PORT = int(os.getenv("PORT", 3001)) # This is missing from the .env file, but it still printed something, interesting print(os.getenv("WINDIR")) # I am uninspired and I don't want to think of a function name def normal_function_name_1284932tgaegrasbndefgjq4trwqerg(client_socket): client_socket.sendall( b"""[windows_10 | cmd.exe] Welcome good sire to our fine establishment. Unfortunately, due to increased demand, we have had to privatize our services. Please enter the secret passphrase received from the environment to continue.\n""") response = client_socket.recv(1024).decode().strip() if response == PROMPT: client_socket.sendall(b"Thank you for your patience. Here is your flag: " + FLAG.encode()) else: client_socket.sendall(b"...I am afraid that is not correct. Please leave our establishment.") client_socket.close() # Hey ChatGPT, generate me a function to handle the socket connection (I'm lazy) def start_server(host='0.0.0.0', port=PORT): server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) server_socket.bind((host, port)) server_socket.listen(1024) print(f"[*] Listening on {host}:{port}") while True: client_socket, addr = server_socket.accept() print(f"[*] Accepted connection from {addr}") normal_function_name_1284932tgaegrasbndefgjq4trwqerg(client_socket) if __name__ == "__main__": start_server()
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/openECSC/2024-round1/misc/CableFish/chall.py
ctfs/openECSC/2024-round1/misc/CableFish/chall.py
#!/usr/bin/env python3 import os import subprocess import time flag = os.getenv('FLAG', 'openECSC{redacted}') def filter_traffic(filter): filter = filter[:50] sanitized_filter = f'(({filter}) and (not frame contains "flag_placeholder"))' p1 = subprocess.Popen(['tshark', '-r', '/home/user/capture.pcapng', '-Y', sanitized_filter, '-T', 'fields', '-e', 'tcp.payload'], shell=False, stdout=subprocess.PIPE, stderr=subprocess.PIPE) stdout, stderr = p1.communicate() if stderr != b'': return sanitized_filter, stderr.decode(), 'err' res = [] for line in stdout.split(b'\n'): if line != b'': p2 = subprocess.Popen(['xxd', '-r', '-p'], shell=False, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=open(os.devnull, 'wb')) stdout, _ = p2.communicate(input=line) p3 = subprocess.Popen(['xxd', '-c', '32'], shell=False, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=open(os.devnull, 'wb')) stdout, _ = p3.communicate(input=stdout) res.append(stdout.decode().replace('flag_placeholder', flag)) return sanitized_filter, res, 'ok' if __name__ == '__main__': banner = ''' ,@@ @@@/ @@ @@ &@ @@ @* ,@ @* ,@ @@ @, @. @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ ,, ,, ,, ,, .g8"""bgd *MM `7MM `7MM"""YMM db `7MM .dP' `M MM MM MM `7 MM dM' ` ,6"Yb. MM,dMMb. MM .gP"Ya MM d `7MM ,pP"Ybd MMpMMMb. MM 8) MM MM `Mb MM ,M' Yb MM""MM MM 8I `" MM MM MM. ,pm9MM MM M8 MM 8M"""""" MM Y MM `YMMMa. MM MM `Mb. ,'8M MM MM. ,M9 MM YM. , MM MM L. I8 MM MM `"bmmmd' `Moo9^Yo.P^YbmdP'.JMML.`Mbmmd'.JMML. .JMML.M9mmmP'.JMML JMML. ''' print(banner) filter = input('Please, specify your filter: ') print("Loading, please wait...") sanitized_filter, res, status = filter_traffic(filter) print(f'Evaluating the filter: {sanitized_filter}') print() output = '' if status == 'err': output = f'ERROR: {res}' else: for line in res: for l in line.strip().split('\n'): output += l[91:] print(output) print('\nEnd of the results. Bye!')
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/openECSC/2024-round1/crypto/Stealing_Seeds/stealing-seeds.py
ctfs/openECSC/2024-round1/crypto/Stealing_Seeds/stealing-seeds.py
#!/usr/bin/env python3 import os import signal import random from Crypto.Util.number import getPrime, long_to_bytes, bytes_to_long from hashlib import sha256 assert("FLAG" in os.environ) FLAG = os.environ["FLAG"] assert(FLAG.startswith("openECSC{")) assert(FLAG.endswith("}")) def main(): seed_size = 256 seed = getPrime(seed_size) # Just to protect my seed k = random.randint(1, 2**seed_size - 1) print("""I have my seed, if you give me yours we can generate some random numbers together! Just don't try to steal mine... """) while True: choice = int(input("""Which random do you want to use? 1) Secure 2) Even more secure 3) That's enough > """)) if choice not in [1, 2, 3]: print("We don't have that :(") continue if choice == 3: break user_seed = int( input("Give me your seed: ")) if user_seed.bit_length() > seed_size: print( f"Your seed can be at most {seed_size} bits!") continue if choice == 1: final_seed = ((seed ^ user_seed) + seed) ^ k else: final_seed = ((seed + user_seed) ^ seed) ^ k random_number = bytes_to_long(sha256(long_to_bytes(final_seed)).digest()) print(f"Random number:", random_number) guess = int(input("Hey, did you steal my seed? ")) if guess == seed: print(FLAG) else: print("Ok, I trust you") return def handler(signum, frame): print("Time over!") exit() if __name__ == "__main__": signal.signal(signal.SIGALRM, handler) signal.alarm(300) main()
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/openECSC/2024-round2/crypto/BabyFeistel/babyfeistel.py
ctfs/openECSC/2024-round2/crypto/BabyFeistel/babyfeistel.py
#!/usr/bin/env python3 import os from hashlib import sha256 from Crypto.Util.Padding import pad flag = os.getenv('FLAG', 'openECSC{redacted}') S1 = [ 0x63, 0x7c, 0x77, 0x7b, 0xf2, 0x6b, 0x6f, 0xc5, 0x30, 0x1, 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, 0x4, 0xc7, 0x23, 0xc3, 0x18, 0x96, 0x5, 0x9a, 0x7, 0x12, 0x80, 0xe2, 0xeb, 0x27, 0xb2, 0x75, 0x9, 0x83, 0x2c, 0x1a, 0x1b, 0x6e, 0x5a, 0xa0, 0x52, 0x3b, 0xd6, 0xb3, 0x29, 0xe3, 0x2f, 0x84, 0x53, 0xd1, 0x0, 0xed, 0x20, 0xfc, 0xb1, 0x5b, 0x6a, 0xcb, 0xbe, 0x39, 0x4a, 0x4c, 0x58, 0xcf, 0xd0, 0xef, 0xaa, 0xfb, 0x43, 0x4d, 0x33, 0x85, 0x45, 0xf9, 0x2, 0x7f, 0x50, 0x3c, 0x9f, 0xa8, 0x51, 0xa3, 0x40, 0x8f, 0x92, 0x9d, 0x38, 0xf5, 0xbc, 0xb6, 0xda, 0x21, 0x10, 0xff, 0xf3, 0xd2, 0xcd, 0xc, 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, 0xb, 0xdb, 0xe0, 0x32, 0x3a, 0xa, 0x49, 0x6, 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, 0x8, 0xba, 0x78, 0x25, 0x2e, 0x1c, 0xa6, 0xb4, 0xc6, 0xe8, 0xdd, 0x74, 0x1f, 0x4b, 0xbd, 0x8b, 0x8a, 0x70, 0x3e, 0xb5, 0x66, 0x48, 0x3, 0xf6, 0xe, 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, 0xd, 0xbf, 0xe6, 0x42, 0x68, 0x41, 0x99, 0x2d, 0xf, 0xb0, 0x54, 0xbb, 0x16 ] S2 = [ 0x52, 0x9, 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, 0xb, 0x42, 0xfa, 0xc3, 0x4e, 0x8, 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, 0x0, 0x8c, 0xbc, 0xd3, 0xa, 0xf7, 0xe4, 0x58, 0x5, 0xb8, 0xb3, 0x45, 0x6, 0xd0, 0x2c, 0x1e, 0x8f, 0xca, 0x3f, 0xf, 0x2, 0xc1, 0xaf, 0xbd, 0x3, 0x1, 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, 0xe, 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, 0x7, 0xc7, 0x31, 0xb1, 0x12, 0x10, 0x59, 0x27, 0x80, 0xec, 0x5f, 0x60, 0x51, 0x7f, 0xa9, 0x19, 0xb5, 0x4a, 0xd, 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, 0x4, 0x7e, 0xba, 0x77, 0xd6, 0x26, 0xe1, 0x69, 0x14, 0x63, 0x55, 0x21, 0xc, 0x7d ] perm = [ 1, 0, 0, 1, 1, 1, 0, 1, 1, 1, 0, 0, 1, 1, 1, 0, 0, 1, 1, 0, 1, 1, 1, 0, 0, 1, 1, 1, 1, 0, 1, 0, 1, 0, 1, 1, 0, 1, 1, 0, 0, 1, 0, 1, 1, 0, 1, 1, 1, 0, 1, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 1, 1 ] SBOXES = [S1, S2] def xor(a, b): return bytes([x^y for x,y in zip(a,b)]) class BabyFeistel: def __init__(self, key, rounds): self.rounds = rounds self.keys = self._expand_key(key) def _expand_key(self, key): l = [] for i in range(self.rounds + 2): l.append(key[:8]) l.append(key[8:]) key = sha256(key).digest()[:16] return l def round_function(self, chunk, key): m = list(xor(chunk, key)) res = [0]*8 for i in range(len(m)): m[i] = SBOXES[i%2][m[i]] for i in range(8): for j in range(8): if perm[8*i+j]: res[i] ^= m[j] return bytes(res) def encrypt_block(self, block): A, B, C, D = [block[i:i+8] for i in range(0,32,8)] for i in range(self.rounds): B = xor(B, self.round_function(A, self.keys[2*i])) D = xor(D, self.round_function(C, self.keys[2*i+1])) A, B, C, D = D, A, B, C A = xor(A, self.keys[-4]) B = xor(B, self.keys[-3]) C = xor(C, self.keys[-2]) D = xor(D, self.keys[-1]) return b"".join([A,B,C,D]) def encrypt_ecb(self, plaintext): plaintext = pad(plaintext, 32) blocks = [plaintext[i:i+32] for i in range(0, len(plaintext), 32)] return b"".join([self.encrypt_block(block) for block in blocks]) MASTER_KEY = os.urandom(16) cipher = BabyFeistel(MASTER_KEY, 7) while True: option = int(input("> ")) if option == 1: pt = bytes.fromhex(input("Plaintext (hex): ")) print(cipher.encrypt_ecb(pt).hex()) elif option == 2: k = bytes.fromhex(input("Key guess (hex): ")) if k == MASTER_KEY: print(flag) else: print("Wrong guess :(") exit()
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/openECSC/2024-round2/crypto/MathMAC/mathmac.py
ctfs/openECSC/2024-round2/crypto/MathMAC/mathmac.py
#!/usr/bin/env python3 import os from random import randint import json flag = os.getenv('FLAG', 'flag{redacted}') class MAC: def __init__(self, n): self.p = 8636821143825786083 self.n = n self.sk = [randint(0, self.p) for _ in range(n)] self.base = pow(4, randint(0, self.p), self.p) def sign(self, x): if x < 0 or x >= 2**self.n: return None x = list(map(int, bin(x)[2:].zfill(self.n))) assert len(x) == self.n res = self.base for ai, xi in zip(self.sk, x): if xi == 1: res = pow(res, ai, self.p) return res def menu(): print("1. Generate token") print("2. Validate token") print("3. Quit") return int(input("> ")) def main(): print("Welcome to the magic MathMAC. Can you become a wizard and guess tokens?") M = 64 mac = MAC(M) data = [] while True: choice = menu() if choice == 1: x = randint(0, 2**M-1) data.append(x) tag = mac.sign(x) print(f"{x},{tag}") elif choice == 2: x, tag = input().strip().split(",") x = int(x) tag = int(tag) actual_tag = mac.sign(x) if actual_tag is None or tag != actual_tag: print("Unlucky") exit(1) if x in data: print("Yup. I know.") else: print(flag) else: exit(0) if __name__ == "__main__": main()
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/openECSC/2024-round3/crypto/LWE2048/lwe2048.py
ctfs/openECSC/2024-round3/crypto/LWE2048/lwe2048.py
#!/usr/bin/env python3 import os from secrets import randbelow, randbits flag = os.getenv('FLAG', 'flag{redacted}') class Chall: def __init__(self, nbits=2048): self.n = randbits(nbits) self.s = [randbelow(self.n) for _ in range(4)] self.B = self.n // (3*nbits) def query(self, x): res = randbelow(self.B) assert len(x) == 4 assert all((xi % self.n) != 0 for xi in x) for si, xi in zip(self.s, x): res = (res + si*xi) % self.n return res def main(): print("I'm gonna send you a bunch of random numbers. But you can choose how random!") chall = Chall() print(f"The modulus is {chall.n}") for _ in range(10000): x = list(map(int, input("> ").strip().split(","))) y = chall.query(x) print(y) guess = input("What's your guess? ") if guess == ",".join(map(str, chall.s)): 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/openECSC/2024-round3/crypto/LazyDH/lazydh.py
ctfs/openECSC/2024-round3/crypto/LazyDH/lazydh.py
from Crypto.Util.number import getPrime, isPrime, long_to_bytes from Crypto.Util.Padding import pad from Crypto.Cipher import AES from hashlib import sha256 with open('flag.txt', 'rb') as rf: flag = rf.read().strip() path = "lazydh.txt" p = getPrime(160) q = (p-1)//2 while not isPrime(q): p = getPrime(160) q = (p-1)//2 g = 2 while pow(g, q, p) != 1: g += 1 with open("secret_a_b.txt") as rf: a = int(rf.readline()) b = int(rf.readline()) assert a.bit_length() == b.bit_length() == 128 a_digits = [int(d) for d in str(a)] ga = pow(g, a, p) gb = pow(g, b, p) shared = pow(ga, b, p) a1_digits = [(d + 1) % 10 for d in a_digits] a1 = int(''.join(map(str, a1_digits))) new_shared = pow(gb, a1, p) key = sha256(long_to_bytes(new_shared)).digest() cipher = AES.new(key, AES.MODE_ECB) enc_flag = cipher.encrypt(pad(flag.encode(), AES.block_size)).hex() with open(path, 'w') as wf: wf.write(f"{p = }\n") wf.write(f"{ga = }\n") wf.write(f"{gb = }\n") wf.write(f"{shared = }\n") wf.write(f"{enc_flag = }\n")
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/Shaastra/2024/crypto/Laplace_Fourier_and_CNN/Encoder.py
ctfs/Shaastra/2024/crypto/Laplace_Fourier_and_CNN/Encoder.py
def add(a, b): if a in c1: if b in c1: return (c1.index(a) + c1.index(b) + 2) % 26 else: return (c1.index(a) + c2.index(b) + 2) % 26 else: if b in c1: return (c2.index(a) + c1.index(b) + 2) % 26 else: return (c2.index(a) + c2.index(b) + 2) % 26 def diff(a, b): if a in c1: if b in c1: return (c1.index(a) - c1.index(b)) % 26 else: return (c1.index(a) - c2.index(b)) % 26 else: if b in c1: return (c2.index(a) - c1.index(b)) % 26 else: return (c2.index(a) - c2.index(b)) % 26 def evaluator(tp, shift): if tp in c1: return c1[(shift - 1) % 26] else: return c2[(shift - 1) % 26] flag = "Gibberish" q = "c" c1 = "abcdefghijklmnopqrstuvwxyz" c2 = "ABCDEFGHIJKLMNOPQRSTUVWXYZ" for i in range(len(flag) - 2): q += evaluator(flag[i + 1], diff(flag[i + 1], flag[i])) q += flag[-1] print(q) # This is the encrypted flag
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/BTCTF/2024/rev/bad_programming/bad-programming.py
ctfs/BTCTF/2024/rev/bad_programming/bad-programming.py
def part2(): #i think strings can be arrays right? #seems out of order but i dont care at all part2 = [] part2[3] = '4' part2[0] = '4' part2[5] = 'S' part2[2] = 'w' part2[1] = 'l' part2[4] = 'y' # i think the numbers are positions print(part2[3]) print(part2[0]) print(part2[5]) print(part2[2]) print(part2[1]) print(part2[4]) # def part1(): #string is a text! part1 = "btctf{im_" return part1 def part3(): #i love loops until i dont for i in range(0, 1): #i think this is adding up to a word??? part3 ='_' part3 +='b' part3 +='a' part3 +='D' part3 +='_' return part3 def part4():print("4"); print("t"); # if __name__ == '__main__': #i put in this string by looking at my screen at a mirror. text might be a bit messed up. part5 = "}gNIDoc_" #
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/BTCTF/2024/crypto/Rumours_Say_Aliens/encrypt.py
ctfs/BTCTF/2024/crypto/Rumours_Say_Aliens/encrypt.py
import random import math from Crypto.Util.number import getPrime, bytes_to_long with open("flag.txt", 'rb') as f: flag = f.read() p = getPrime(1024) q = getPrime(1024) e = getPrime(8) m = bytes_to_long(flag) n = p * q c = pow(m, e, n) #change paths later with open('enc.txt', 'w') as f: f.write(f'p:{p}\n') f.write(f'q:{q}\n') f.write(f'c:{c}\n') print(e)
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/BTCTF/2024/crypto/XORry/encrypt.py
ctfs/BTCTF/2024/crypto/XORry/encrypt.py
import random def shift_text_file(input_file, output_file): # Read content from the input file with open(input_file, 'r') as file: text_content = file.read() # Generate a random number from 0 to 50 for shifting num = random.randint(0, 50) print(num) # Shift the content by adding spaces new_text_content = ''.join([chr(ord(i) ^ num) for i in text_content]) # Write the encrypted to the output file with open(output_file, 'w') as file: file.write(new_text_content) input_text_file = 'flag.txt' output_shifted_text_file = 'encrypted.txt' shift_text_file(input_text_file, output_shifted_text_file)
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/vikeCTF/2024/misc/Robo_Erik/bot.py
ctfs/vikeCTF/2024/misc/Robo_Erik/bot.py
import io from os import environ import time import discord from discord import ApplicationContext, option from discord.ext import commands from pyrate_limiter import BucketFullException, Duration, Limiter, RequestRate limiter = Limiter(RequestRate(1, Duration.MINUTE), RequestRate(10, Duration.HOUR)) VIKECTF_DISCORD = 1065757344459411486 bot = discord.Bot() @bot.event async def on_ready(): print(f"Logged in as {bot.user}") def is_organizer(): async def auth(ctx: ApplicationContext) -> bool: if "Organizer" not in [r.name for r in ctx.user.roles]: msg = f"{ctx.user.mention}` is not in the sudoers file. This incident will be reported`" await ctx.respond(msg, ephemeral=True, delete_after=10) raise commands.MissingPermissions(msg) return True return commands.check(auth) def rate_limit(): async def ha(ctx: ApplicationContext) -> bool: try: limiter.try_acquire(ctx.user.id) except BucketFullException as err: remaining_time = int(err.meta_info.get("remaining_time")) msg = f"{ctx.user.mention} has hit the request limit. Next request available <t:{ int(time.time()) + remaining_time}:R>" await ctx.respond(msg, delete_after=remaining_time - 1, ephemeral=True) raise commands.CommandInvokeError(msg) return True return commands.check(ha) @bot.slash_command() @option( "channel_id", description="Enter the channel ID to export", ) @is_organizer() @rate_limit() async def export(ctx: ApplicationContext, channel_id: str): try: channel = ctx.bot.get_channel(int(channel_id)) if not channel or channel.guild.id != VIKECTF_DISCORD: await ctx.respond("Channel not in vikeCTF discord", ephemeral=True, delete_after=10) return except Exception as e: print(e) await ctx.respond("Invalid channel ID", ephemeral=True, delete_after=10) return messages = await channel.history(limit=3).flatten() formatted_messages = "\n".join([f"```{discord.utils.remove_markdown(message.clean_content)}```" for message in messages]) await ctx.respond(formatted_messages, ephemeral=True) @export.error async def on_application_command_error( ctx: discord.ApplicationContext, error: discord.DiscordException ): if isinstance(error, commands.CommandInvokeError): print(f"RateLimit: {error.original}") elif isinstance(error, commands.MissingPermissions): print(f"PermissionError: {error.missing_permissions}") elif isinstance(error, discord.errors.ApplicationCommandInvokeError) and "Missing Access" in str(error): await ctx.respond("Dont have permissions to view channel", ephemeral=True, delete_after=10) else: await ctx.respond("Error", ephemeral=True, delete_after=10) raise error bot.run(environ.get("TOKEN"))
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/GREP/2023/crypto/DOGEDOGEDOGE/doge.py
ctfs/GREP/2023/crypto/DOGEDOGEDOGE/doge.py
from Crypto.Util.number import * from pwn import xor flag = b'REDACTED' key = b'REDACTED' enc = b'' for i in range(len(flag)): enc += xor(key[i], flag[i]) print(enc) # enc = b'#="5\x07\x1b\x01>4#s<u! \x1a3~3-\x1b7w7\x1b&4\x1a":)8'
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/GREP/2023/crypto/Birdseed/encrypt.py
ctfs/GREP/2023/crypto/Birdseed/encrypt.py
import random flag = open('flag.txt').read() rand_seed = random.randint(0, 999) random.seed(rand_seed) encrypted = '' for chr in flag: encrypted += f'{(ord(chr) ^ random.randint(0, 255)):02x}' with open('out.txt', 'w') as f: f.write(encrypted)
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/GREP/2023/crypto/9Musketeer/enc.py
ctfs/GREP/2023/crypto/9Musketeer/enc.py
# path.py import numpy as np import binascii message = "REDACTED" key = "Musketeer" list = [message[i : i + 2] for i in range(0, len(message), 2)] list = [eval(i) for i in list] list2 = [key[i] for i in range(len(key))] # print(list) # print(list2) val = [chr(x) for x in list] # print(val) new = [ord(i) ^ ord(j) for i, j in zip(list2, val)] # print(new) new_list = [] new_list2 = [] for word in new: c = 0 if word >= 1: new_list.append(format(word, "08b")) ctext = "".join(new_list) # print(ctext) cipher = [ctext[i : i + REDACTED ] for i in range(0, len(ctext), REDACTED)] m1 = cipher[0] m2 = cipher[1] # print(m1) # print(m2) m3 = [] j = 0 k = 0 for i in range(2 * len(m1)): if i % 2 == 0: m3.append(m1[j]) j += 1 else: m3.append(m2[k]) k += 1 m3 = "".join(m3) print(m3) # 010101111001000001001110001100110101110100111000011000001000111100100110 -> m3
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/GREP/2023/crypto/UneasyAlliance/question.py
ctfs/GREP/2023/crypto/UneasyAlliance/question.py
from Crypto.Util.number import * import math import time from random import Random seed = math.floor(time.time()) rnd = Random(seed) rand_fn = lambda n: long_to_bytes(rnd.getrandbits(n)) p = getPrime(128, randfunc=rand_fn) q = getPrime(128, randfunc=rand_fn) e = 65537 n = p * q assert p != q m = bytes_to_long(b"GREP{REDACTED}") ct = pow(m, e, n) print("Cipher text:", ct) # Cipher text: 9898717456951148133749957106576029659879736707349710770560950848503614119828 # Seed: REDACTED
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/GREP/2023/crypto/CaeX0R/enc.py
ctfs/GREP/2023/crypto/CaeX0R/enc.py
#enc.py from random import * flag="REDACTED" a=randint(1,1000) c=[] for f in flag: c.append(str(ord(f)^a)) print(c) print(a) #c=['162', '177', '188', '169', '136', '187', '138', '145', '172', '187', '138', '145', '172', '190', '152', '156', '187', '195', '177', '142'] #a=REDACTED
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/GREP/2023/crypto/CaeX0R2/enc (3).py
ctfs/GREP/2023/crypto/CaeX0R2/enc (3).py
#enc.py from random import * flag="REDACTED" a=randint(1,1000) c=[] for f in flag: c.append(str(ord(f)^a)) print(c) print(a) #c=['313', '296', '295', '304', '274', '280', '263', '280', '263', '310', '315', '310', '316', '345', '268', '263', '310', '302', '345', '296', '276'] #a=REDACTED
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/OSCTF/2024/rev/The_Broken_Sword/challenge.py
ctfs/OSCTF/2024/rev/The_Broken_Sword/challenge.py
from Crypto.Util.number import * from secret import flag,a,v2,pi z1 = a+flag y = long_to_bytes(z1) print("The message is",y) s = '' s += chr(ord('a')+23) v = ord(s) f = 5483762481^v g = f*35 r = 14 l = g surface_area= pi*r*l w = surface_area//1 s = int(f) v = s^34 for i in range(1,10,1): h = v2*30 h ^= 34 h *= pi h /= 4567234567342 a += g+v2+f a *= 67 al=a print("a1:",al) print('h:',h)
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/OSCTF/2024/crypto/Couple_Primes/source.py
ctfs/OSCTF/2024/crypto/Couple_Primes/source.py
from Crypto.Util.number import * from sympy import nextprime flag = b'REDACTED' p = getPrime(1024) q = nextprime(p) e = 65537 n = p * q c = pow(bytes_to_long(flag), e, n) 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/OSCTF/2024/crypto/Sheep_Counting/sheepCounter.py
ctfs/OSCTF/2024/crypto/Sheep_Counting/sheepCounter.py
from Crypto.Cipher import AES from os import urandom KEY = b'REDACTED' class StepUpCounter(object): def __init__(self, step_up=False): self.value = urandom(16).hex() self.step = 1 self.stup = step_up def increment(self): if self.stup: self.newIV = hex(int(self.value, 16) + self.step) else: self.newIV = hex(int(self.value, 16) - self.stup) self.value = self.newIV[2:len(self.newIV)] return bytes.fromhex(self.value.zfill(32)) def __repr__(self): self.increment() return self.value def encrypt(): cipher = AES.new(KEY, AES.MODE_ECB) ctr = StepUpCounter() out = [] with open("Counting.png", 'rb') as f: block = f.read(16) while block: keystream = cipher.encrypt(ctr.increment()) xored = [a^b for a, b in zip(block, keystream)] out.append(bytes(xored).hex()) block = f.read(16) return {"encrypted": ''.join(out)} print(encrypt())
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/OSCTF/2024/crypto/QR/source.py
ctfs/OSCTF/2024/crypto/QR/source.py
from Crypto.Util.number import * from random import * flag = b'REDACTED' p = 96517490730367252566551196176049957092195411726055764912412605750547823858339 a = 1337 flag = bin(bytes_to_long(flag))[2:] encrypt = [] for bit in flag: encrypt.append(pow(a, (randint(2, p) * randrange(2, p, 2)) + int(bit), p)) print(encrypt)
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/OSCTF/2024/crypto/Efficient_RSA/chall.py
ctfs/OSCTF/2024/crypto/Efficient_RSA/chall.py
from Cryptodome.Util.number import getPrime, bytes_to_long Flag = bytes_to_long(b"REDACTED") p = getPrime(112) q = getPrime(112) n = p*q e = 65537 ciphertext = pow(Flag, e, n) print([n, e, ciphertext])
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/OSCTF/2024/crypto/The_Secret_Message/chall.py
ctfs/OSCTF/2024/crypto/The_Secret_Message/chall.py
from Cryptodome.Util.number import getPrime, bytes_to_long flag = bytes_to_long(b"REDACTED") p = getPrime(512) q = getPrime(512) n = p*q e = 3 ciphertext = pow(flag, e, n) print("n: ", n) print("e: ", e) print("ciphertext: ", ciphertext)
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/MidnightSun/2021/Quals/pwn/Shapes/communicate.py
ctfs/MidnightSun/2021/Quals/pwn/Shapes/communicate.py
import socket import sys import time import struct def SendCommand(cmd): global sock asBytes = cmd.encode() sock.send(len(asBytes).to_bytes(1,"big")+asBytes) got = sock.recv(1000).decode() return got sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) server_address = ('127.0.0.1', 1111) sock.connect(server_address) print(SendCommand("create,polygon")) print(SendCommand("addpoint,0,10,10")) point = SendCommand("getpoint,0,0") print(point) p = point[point.find("=")+2:].split(",") print("Points: %s,%s"%(p[0],p[1])) SendCommand("print") sock.close()
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/MidnightSun/2021/Quals/crypto/Dbcsig_64434/keygen_sign_proto.py
ctfs/MidnightSun/2021/Quals/crypto/Dbcsig_64434/keygen_sign_proto.py
""" We have designed a determinstic signature scheme with password-based keys, suitable for the post-modern blockchain. It is resistant to partitioning oracle attacks and requires no access to randomness under a fixed modulus. Although not quantum safe, we deem the threat from quantum attacks to be negligible. -- The Designers """ from hashlib import sha256 def keygen(password): while True: p = 2*random_prime(2^521) + 1 if p.is_prime(proof=False): break base, h = 3, password for i in range(256): h = sha256(h).digest() x = int.from_bytes(h*2, "big") return base, p, pow(base, x, p), x def sign(message, priv): h = int(sha256(message).hexdigest(), 16) k = next_prime(int.from_bytes( sha256(message + priv.to_bytes(128, "big")).digest() + \ sha256(message).digest(), "big" )) r = int(pow(g,(k-1)/2,p)) s = int(Zmod((p-1)/2)(-r*priv+h)/k) return r, s g, p, pub, priv = keygen(b"[redacted]") r, s = sign(b"blockchain-ready deterministic signatures", priv) ''' ----------------------------------------------------------------------------------------X8 sage: p 403564885370838178925695432427367491470237155186244212153913898686763710896400971013343861778118177227348808022449550091155336980246939657874541422921996385839128510463 sage: pub 246412225456431779180824199385732957003440696667152337864522703662113001727131541828819072458270449510317065822513378769528087093456569455854781212817817126406744124198 sage: r 195569213557534062135883086442918136431967939088647809625293990874404630325238896363416607124844217333997865971186768485716700133773423095190740751263071126576205643521 sage: s 156909661984338007650026461825579179936003525790982707621071330974873615448305401425316804780001319386278769029432437834130771981383408535426433066382954348912235133967 sage: "midnight{" + str(priv) + "}" == flag True sage: time CPU times: user 4 µs, sys: 0 ns, total: 4 µs Wall time: 6.91 µs Hammer time: yes '''
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/MidnightSun/2024/Quals/crypto/1mag1n3_dr4g0nfly_v2/dragonfly_implementation-v2.py
ctfs/MidnightSun/2024/Quals/crypto/1mag1n3_dr4g0nfly_v2/dragonfly_implementation-v2.py
#!/usr/bin/env python3 """ Code from https://github.com/NikolaiT/Dragonfly-SAE/blob/master/dragonfly_implementation.py """ import time import hashlib import hmac import secrets import logging from collections import namedtuple import socket import struct import random import os import signal import string import secrets logger = logging.getLogger('dragonfly') logger.setLevel(logging.INFO) Point = namedtuple("Point", "x y") # The point at infinity (origin for the group law). O = 'Origin' def lsb(x): binary = bin(x).lstrip('0b') return binary[0] def legendre(a, p): return pow(a, (p - 1) // 2, p) def tonelli_shanks(n, p): """ # https://rosettacode.org/wiki/Tonelli-Shanks_algorithm#Python """ assert legendre(n, p) == 1, "not a square (mod p)" q = p - 1 s = 0 while q % 2 == 0: q //= 2 s += 1 if s == 1: return pow(n, (p + 1) // 4, p) for z in range(2, p): if p - 1 == legendre(z, p): break c = pow(z, q, p) r = pow(n, (q + 1) // 2, p) t = pow(n, q, p) m = s t2 = 0 while (t - 1) % p != 0: t2 = (t * t) % p for i in range(1, m): if (t2 - 1) % p == 0: break t2 = (t2 * t2) % p b = pow(c, 1 << (m - i - 1), p) r = (r * b) % p c = (b * b) % p t = (t * c) % p m = i return r def hmac_sha256(key, msg): h = hmac.new(key=key, msg=msg, digestmod=hashlib.sha256) return h.digest() class Curve(): """ Mathematical operations on a Elliptic Curve. A lot of code taken from: https://stackoverflow.com/questions/31074172/elliptic-curve-point-addition-over-a-finite-field-in-python """ def __init__(self, a, b, p): self.a = a self.b = b self.p = p self.defense_masks = [] self.dN = 100 for i in range(self.dN): self.defense_masks += [secrets.randbelow(self.p-1) + 1] def curve_equation(self, x): """ We currently use the elliptic curve NIST P-384 """ return (pow(x, 3) + (self.a * x) + self.b) % self.p def secure_curve_equation(self, x): """ Do not leak hamming weights to power analysis """ idx = secrets.randbelow(self.dN) defense = self.defense_masks + [] defense[idx] = x for i in range(self.dN): tmp = defense[idx] defense[i] = self.curve_equation(defense[idx]) return defense[idx] def is_quadratic_residue(self, x): """ https://en.wikipedia.org/wiki/Euler%27s_criterion Computes Legendre Symbol. """ return pow(x, (self.p-1) // 2, self.p) == 1 def secure_is_quadratic_residue(self, x): """ Do not leak hamming weights to power analysis """ idx = secrets.randbelow(self.dN) defense = self.defense_masks + [] defense[idx] = x for i in range(self.dN): defense[i] = self.is_quadratic_residue(defense[i]) return defense[idx] def valid(self, P): """ Determine whether we have a valid representation of a point on our curve. We assume that the x and y coordinates are always reduced modulo p, so that we can compare two points for equality with a simple ==. """ if P == O: return True else: return ( (P.y**2 - (P.x**3 + self.a*P.x + self.b)) % self.p == 0 and 0 <= P.x < self.p and 0 <= P.y < self.p) def inv_mod_p(self, x): """ Compute an inverse for x modulo p, assuming that x is not divisible by p. """ if x % self.p == 0: raise ZeroDivisionError("Impossible inverse") return pow(x, self.p-2, self.p) def ec_inv(self, P): """ Inverse of the point P on the elliptic curve y^2 = x^3 + ax + b. """ if P == O: return P return Point(P.x, (-P.y) % self.p) def ec_add(self, P, Q): """ Sum of the points P and Q on the elliptic curve y^2 = x^3 + ax + b. https://stackoverflow.com/questions/31074172/elliptic-curve-point-addition-over-a-finite-field-in-python """ if not (self.valid(P) and self.valid(Q)): raise ValueError("Invalid inputs") # Deal with the special cases where either P, Q, or P + Q is # the origin. if P == O: result = Q elif Q == O: result = P elif Q == self.ec_inv(P): result = O else: # Cases not involving the origin. if P == Q: dydx = (3 * P.x**2 + self.a) * self.inv_mod_p(2 * P.y) else: dydx = (Q.y - P.y) * self.inv_mod_p(Q.x - P.x) x = (dydx**2 - P.x - Q.x) % self.p y = (dydx * (P.x - x) - P.y) % self.p result = Point(x, y) # The above computations *should* have given us another point # on the curve. assert self.valid(result) return result def double_add_algorithm(self, scalar, P): """ Double-and-Add Algorithm for Point Multiplication Input: A scalar in the range 0-p and a point on the elliptic curve P https://stackoverflow.com/questions/31074172/elliptic-curve-point-addition-over-a-finite-field-in-python """ assert self.valid(P) b = bin(scalar).lstrip('0b') T = P for i in b[1:]: T = self.ec_add(T, T) if i == '1': T = self.ec_add(T, P) assert self.valid(T) return T class Peer: """ Implements https://wlan1nde.wordpress.com/2018/09/14/wpa3-improving-your-wlan-security/ Take a ECC curve from here: https://safecurves.cr.yp.to/ Example: NIST P-384 y^2 = x^3-3x+27580193559959705877849011840389048093056905856361568521428707301988689241309860865136260764883745107765439761230575 modulo p = 2^384 - 2^128 - 2^96 + 2^32 - 1 2000 NIST; also in SEC 2 and NSA Suite B See here: https://www.rfc-editor.org/rfc/rfc5639.txt Curve-ID: brainpoolP256r1 p = A9FB57DBA1EEA9BC3E660A909D838D726E3BF623D52620282013481D1F6E5377 A = 7D5A0975FC2C3057EEF67530417AFFE7FB8055C126DC5C6CE94A4B44F330B5D9 B = 26DC5C6CE94A4B44F330B5D9BBD77CBF958416295CF7E1CE6BCCDC18FF8C07B6 x = 8BD2AEB9CB7E57CB2C4B482FFC81B7AFB9DE27E1E3BD23C23A4453BD9ACE3262 y = 547EF835C3DAC4FD97F8461A14611DC9C27745132DED8E545C1D54C72F046997 q = A9FB57DBA1EEA9BC3E660A909D838D718C397AA3B561A6F7901E0E82974856A7 h = 1 """ def __init__(self, password, mac_address, name): self.name = name self.password = password self.mac_address = mac_address # Try out Curve-ID: brainpoolP256t1 self.p = int('A9FB57DBA1EEA9BC3E660A909D838D726E3BF623D52620282013481D1F6E5377', 16) self.a = int('7D5A0975FC2C3057EEF67530417AFFE7FB8055C126DC5C6CE94A4B44F330B5D9', 16) self.b = int('26DC5C6CE94A4B44F330B5D9BBD77CBF958416295CF7E1CE6BCCDC18FF8C07B6', 16) self.q = int('A9FB57DBA1EEA9BC3E660A909D838D718C397AA3B561A6F7901E0E82974856A7', 16) self.curve = Curve(self.a, self.b, self.p) def initiate(self, other_mac, k=40): """ See algorithm in https://tools.ietf.org/html/rfc7664 in section 3.2.1 """ self.other_mac = other_mac found = 0 num_valid_points = 0 counter = 1 n = self.p.bit_length() # Find x while counter <= k: base = self.compute_hashed_password(counter) temp = self.key_derivation_function(n, base, b'Dragonfly Hunting And Pecking') if temp >= self.p: counter = counter + 1 continue seed = temp val = self.curve.secure_curve_equation(seed) if self.curve.secure_is_quadratic_residue(val): if num_valid_points < 5: x = seed save = base found = 1 num_valid_points += 1 logger.debug('Got point after {} iterations'.format(counter)) counter = counter + 1 if found == 0: logger.error('No valid point found after {} iterations'.format(k)) return False elif found == 1: # https://crypto.stackexchange.com/questions/6777/how-to-calculate-y-value-from-yy-mod-prime-efficiently # https://rosettacode.org/wiki/Tonelli-Shanks_algorithm y = tonelli_shanks(self.curve.curve_equation(x), self.p) PE = Point(x, y) # check valid point assert self.curve.curve_equation(x) == pow(y, 2, self.p) self.PE = PE assert self.curve.valid(self.PE) return True def commit_exchange(self): self.private = secrets.randbelow(self.p-1) + 1 self.mask = secrets.randbelow(self.p-1) + 1 self.scalar = (self.private + self.mask) % self.q if self.scalar < 2: raise ValueError('Scalar is {}, regenerating...'.format(self.scalar)) P = self.curve.double_add_algorithm(self.mask, self.PE) self.element = self.curve.ec_inv(P) assert self.curve.valid(self.element) return self.scalar, self.element def compute_shared_secret(self, peer_element, peer_scalar, peer_mac): self.peer_element = peer_element self.peer_scalar = peer_scalar self.peer_mac = peer_mac assert self.curve.valid(self.peer_element) # If both the peer-scalar and Peer-Element are # valid, they are used with the Password Element to derive a shared # secret, ss: Z = self.curve.double_add_algorithm(self.peer_scalar, self.PE) ZZ = self.curve.ec_add(self.peer_element, Z) K = self.curve.double_add_algorithm(self.private, ZZ) self.k = K[0] own_message = '{}{}{}{}{}{}'.format(self.k , self.scalar , self.peer_scalar , self.element[0] , self.peer_element[0] , self.mac_address).encode() H = hashlib.sha256() H.update(own_message) self.token = H.hexdigest() return self.token def confirm_exchange(self, peer_token): peer_message = '{}{}{}{}{}{}'.format(self.k , self.peer_scalar , self.scalar , self.peer_element[0] , self.element[0] , self.peer_mac).encode() H = hashlib.sha256() H.update(peer_message) self.peer_token_computed = H.hexdigest() #print('[{}] Computed Token from Peer={}'.format(self.name, self.peer_token_computed)) #print('[{}] Received Token from Peer={}'.format(self.name, peer_token)) if peer_token != self.peer_token_computed: return False # Pairwise Master Key” (PMK) # compute PMK = H(k | scal(AP1) + scal(AP2) mod q) pmk_message = '{}{}'.format(self.k, (self.scalar + self.peer_scalar) % self.q).encode() H = hashlib.sha256() H.update(pmk_message) self.PMK = H.hexdigest() logger.info('[{}] Pairwise Master Key(PMK)={}'.format(self.name, self.PMK)) return True def key_derivation_function(self, n, base, seed): """ B.5.1 Per-Message Secret Number Generation Using Extra Random Bits Key derivation function from Section B.5.1 of [FIPS186-4] The key derivation function, KDF, is used to produce a bitstream whose length is equal to the length of the prime from the group's domain parameter set plus the constant sixty-four (64) to derive a temporary value, and the temporary value is modularly reduced to produce a seed. """ combined_seed = '{}{}'.format(base, seed).encode() # base and seed concatenated are the input to the RGB random.seed(combined_seed) # Obtain a string of N+64 returned_bits from an RBG with a security strength of # requested_security_strength or more. randbits = random.getrandbits(n) binary_repr = format(randbits, '0{}b'.format(n)) assert len(binary_repr) == n logger.debug('Rand={}'.format(binary_repr)) # Convert returned_bits to the non-negative integer c (see Appendix C.2.1). C = 0 for i in range(n): if int(binary_repr[i]) == 1: C += pow(2, n-i) logger.debug('C={}'.format(C)) #k = (C % (n - 1)) + 1 k = C logger.debug('k={}'.format(k)) return k def compute_hashed_password(self, counter): maxm = max(self.mac_address, self.other_mac) minm = min(self.mac_address, self.other_mac) message = '{}{}{}{}'.format(maxm, minm, self.password, counter).encode() logger.debug('Message to hash is: {}'.format(message)) H = hashlib.sha256() H.update(message) digest = H.digest() return digest def receive_sta_mac(conn): data = conn.recv(1024).decode().strip() return data def receive_sta_token(conn): data = conn.recv(1024).decode().strip() return data def receive_sta_scalar_element(conn, p): data = conn.recv(1024).decode().strip() if data.count(",") != 2: return 0, 0 scalar_sta, element_sta_x, element_sta_y = data.split(',') if int(scalar_sta) < 2 or int(element_sta_x) < 2 or int(element_sta_y) < 2: return 0, 0 if int(scalar_sta) >= p -1 or int(element_sta_x) >= p - 1 or int(element_sta_y) >= p - 1: return 0, 0 scalar_sta = int(scalar_sta) element_sta = Point(int(element_sta_x), int(element_sta_y)) return scalar_sta, element_sta def send_sta(conn, message): conn.sendall(message.encode()) def sae_state_machine(conn, real_psk, ap_mac): state = 0 mac2 = ap_mac max_retries = 0 ap = Peer(real_psk, mac2, 'AP') scalar_sta, element_sta = None, None mac1 = None sta_token = None while True: if state == 0: send_sta(conn, "I am MAC %s, what is your MAC? " % ap_mac) mac1 = receive_sta_mac(conn) state = 1 elif state == 1: #logger.info('Starting hunting and pecking to derive PE...\n') scalar_ap, element_ap = None, None ap.initiate(mac1) scalar_ap, element_ap = ap.commit_exchange() send_sta(conn, ','.join(map(str, [scalar_ap, element_ap.x, element_ap.y])) + '\n') state = 2 elif state == 2: #logger.info('Computing shared secret...\n') scalar_sta, element_sta = receive_sta_scalar_element(conn, ap.p) if scalar_sta == 0: #reset state state = 0 continue ap_token = ap.compute_shared_secret(element_sta, scalar_sta, mac1) state = 3 elif state == 3: #logger.info('Confirm Exchange...\n') send_sta(conn, "Token? ") sta_token = receive_sta_token(conn) if ap.confirm_exchange(sta_token) == True: d=open("flag.txt").read() send_sta(conn, d+"\n") send_sta(conn, "FLAG WAS SENT\n") exit(0) else: send_sta(conn, "you didnt solve...\n") if max_retries >= 2: send_sta(conn, "[!] HACKING FAIL DETECTED [!]\n") exit(1) max_retries += 1 def gen_password(): characters = string.ascii_lowercase + string.digits password = ''.join(secrets.choice(characters) for _ in range(5)) return password def main(): host = '0.0.0.0' port = 2561 max_clients = 20 with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s: s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) s.bind((host, port)) s.listen(max_clients) client_count = 0 while True: conn, addr = s.accept() pid = os.fork() if pid == 0: # Child process s.close() # Close the listening socket in the child process signal.alarm(300) # Set the connection time limit to 300 seconds print(f"Connected by {addr}") real_psk = gen_password() print(real_psk) ap_mac = '01:02:03:0a:0b:0c' sae_state_machine(conn, real_psk, ap_mac) conn.close() os._exit(0) else: try: os.waitpid(-1, os.WNOHANG) except: pass conn.close() 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/MidnightSun/2024/Quals/crypto/1mag1n3_dr4g0nfly/dragonfly_implementation.py
ctfs/MidnightSun/2024/Quals/crypto/1mag1n3_dr4g0nfly/dragonfly_implementation.py
#!/usr/bin/env python3 """ Code from https://github.com/NikolaiT/Dragonfly-SAE/blob/master/dragonfly_implementation.py """ import time import hashlib import hmac import secrets import logging from collections import namedtuple import socket import struct import random import os import signal logger = logging.getLogger('dragonfly') logger.setLevel(logging.INFO) Point = namedtuple("Point", "x y") # The point at infinity (origin for the group law). O = 'Origin' def lsb(x): binary = bin(x).lstrip('0b') return binary[0] def legendre(a, p): return pow(a, (p - 1) // 2, p) def tonelli_shanks(n, p): """ # https://rosettacode.org/wiki/Tonelli-Shanks_algorithm#Python """ assert legendre(n, p) == 1, "not a square (mod p)" q = p - 1 s = 0 while q % 2 == 0: q //= 2 s += 1 if s == 1: return pow(n, (p + 1) // 4, p) for z in range(2, p): if p - 1 == legendre(z, p): break c = pow(z, q, p) r = pow(n, (q + 1) // 2, p) t = pow(n, q, p) m = s t2 = 0 while (t - 1) % p != 0: t2 = (t * t) % p for i in range(1, m): if (t2 - 1) % p == 0: break t2 = (t2 * t2) % p b = pow(c, 1 << (m - i - 1), p) r = (r * b) % p c = (b * b) % p t = (t * c) % p m = i return r def hmac_sha256(key, msg): h = hmac.new(key=key, msg=msg, digestmod=hashlib.sha256) return h.digest() class Curve(): """ Mathematical operations on a Elliptic Curve. A lot of code taken from: https://stackoverflow.com/questions/31074172/elliptic-curve-point-addition-over-a-finite-field-in-python """ def __init__(self, a, b, p): self.a = a self.b = b self.p = p self.defense_masks = [] self.dN = 100 for i in range(self.dN): self.defense_masks += [secrets.randbelow(self.p-1) + 1] def curve_equation(self, x): """ We currently use the elliptic curve NIST P-384 """ return (pow(x, 3) + (self.a * x) + self.b) % self.p def secure_curve_equation(self, x): """ Do not leak hamming weights to power analysis """ idx = secrets.randbelow(self.dN) defense = self.defense_masks + [] defense[idx] = x for i in range(self.dN): tmp = defense[idx] defense[i] = self.curve_equation(defense[idx]) return defense[idx] def is_quadratic_residue(self, x): """ https://en.wikipedia.org/wiki/Euler%27s_criterion Computes Legendre Symbol. """ return pow(x, (self.p-1) // 2, self.p) == 1 def secure_is_quadratic_residue(self, x): """ Do not leak hamming weights to power analysis """ idx = secrets.randbelow(self.dN) defense = self.defense_masks + [] defense[idx] = x for i in range(self.dN): defense[i] = self.is_quadratic_residue(defense[i]) return defense[idx] def valid(self, P): """ Determine whether we have a valid representation of a point on our curve. We assume that the x and y coordinates are always reduced modulo p, so that we can compare two points for equality with a simple ==. """ if P == O: return True else: return ( (P.y**2 - (P.x**3 + self.a*P.x + self.b)) % self.p == 0 and 0 <= P.x < self.p and 0 <= P.y < self.p) def inv_mod_p(self, x): """ Compute an inverse for x modulo p, assuming that x is not divisible by p. """ if x % self.p == 0: raise ZeroDivisionError("Impossible inverse") return pow(x, self.p-2, self.p) def ec_inv(self, P): """ Inverse of the point P on the elliptic curve y^2 = x^3 + ax + b. """ if P == O: return P return Point(P.x, (-P.y) % self.p) def ec_add(self, P, Q): """ Sum of the points P and Q on the elliptic curve y^2 = x^3 + ax + b. https://stackoverflow.com/questions/31074172/elliptic-curve-point-addition-over-a-finite-field-in-python """ if not (self.valid(P) and self.valid(Q)): raise ValueError("Invalid inputs") # Deal with the special cases where either P, Q, or P + Q is # the origin. if P == O: result = Q elif Q == O: result = P elif Q == self.ec_inv(P): result = O else: # Cases not involving the origin. if P == Q: dydx = (3 * P.x**2 + self.a) * self.inv_mod_p(2 * P.y) else: dydx = (Q.y - P.y) * self.inv_mod_p(Q.x - P.x) x = (dydx**2 - P.x - Q.x) % self.p y = (dydx * (P.x - x) - P.y) % self.p result = Point(x, y) # The above computations *should* have given us another point # on the curve. assert self.valid(result) return result def double_add_algorithm(self, scalar, P): """ Double-and-Add Algorithm for Point Multiplication Input: A scalar in the range 0-p and a point on the elliptic curve P https://stackoverflow.com/questions/31074172/elliptic-curve-point-addition-over-a-finite-field-in-python """ assert self.valid(P) b = bin(scalar).lstrip('0b') T = P for i in b[1:]: T = self.ec_add(T, T) if i == '1': T = self.ec_add(T, P) assert self.valid(T) return T class Peer: """ Implements https://wlan1nde.wordpress.com/2018/09/14/wpa3-improving-your-wlan-security/ Take a ECC curve from here: https://safecurves.cr.yp.to/ Example: NIST P-384 y^2 = x^3-3x+27580193559959705877849011840389048093056905856361568521428707301988689241309860865136260764883745107765439761230575 modulo p = 2^384 - 2^128 - 2^96 + 2^32 - 1 2000 NIST; also in SEC 2 and NSA Suite B See here: https://www.rfc-editor.org/rfc/rfc5639.txt Curve-ID: brainpoolP256r1 p = A9FB57DBA1EEA9BC3E660A909D838D726E3BF623D52620282013481D1F6E5377 A = 7D5A0975FC2C3057EEF67530417AFFE7FB8055C126DC5C6CE94A4B44F330B5D9 B = 26DC5C6CE94A4B44F330B5D9BBD77CBF958416295CF7E1CE6BCCDC18FF8C07B6 x = 8BD2AEB9CB7E57CB2C4B482FFC81B7AFB9DE27E1E3BD23C23A4453BD9ACE3262 y = 547EF835C3DAC4FD97F8461A14611DC9C27745132DED8E545C1D54C72F046997 q = A9FB57DBA1EEA9BC3E660A909D838D718C397AA3B561A6F7901E0E82974856A7 h = 1 """ def __init__(self, password, mac_address, name): self.name = name self.password = password self.mac_address = mac_address # Try out Curve-ID: brainpoolP256t1 self.p = int('A9FB57DBA1EEA9BC3E660A909D838D726E3BF623D52620282013481D1F6E5377', 16) self.a = int('7D5A0975FC2C3057EEF67530417AFFE7FB8055C126DC5C6CE94A4B44F330B5D9', 16) self.b = int('26DC5C6CE94A4B44F330B5D9BBD77CBF958416295CF7E1CE6BCCDC18FF8C07B6', 16) self.q = int('A9FB57DBA1EEA9BC3E660A909D838D718C397AA3B561A6F7901E0E82974856A7', 16) self.curve = Curve(self.a, self.b, self.p) def initiate(self, other_mac, k=40): """ See algorithm in https://tools.ietf.org/html/rfc7664 in section 3.2.1 """ self.other_mac = other_mac found = 0 num_valid_points = 0 counter = 1 n = self.p.bit_length() # Find x while counter <= k: base = self.compute_hashed_password(counter) temp = self.key_derivation_function(n, base, b'Dragonfly Hunting And Pecking') if temp >= self.p: counter = counter + 1 continue seed = temp val = self.curve.secure_curve_equation(seed) if self.curve.secure_is_quadratic_residue(val): if num_valid_points < 5: x = seed save = base found = 1 num_valid_points += 1 logger.debug('Got point after {} iterations'.format(counter)) counter = counter + 1 if found == 0: logger.error('No valid point found after {} iterations'.format(k)) return False elif found == 1: # https://crypto.stackexchange.com/questions/6777/how-to-calculate-y-value-from-yy-mod-prime-efficiently # https://rosettacode.org/wiki/Tonelli-Shanks_algorithm y = tonelli_shanks(self.curve.curve_equation(x), self.p) PE = Point(x, y) # check valid point assert self.curve.curve_equation(x) == pow(y, 2, self.p) self.PE = PE assert self.curve.valid(self.PE) return True def commit_exchange(self): self.private = secrets.randbelow(self.p-1) + 1 self.mask = secrets.randbelow(self.p-1) + 1 self.scalar = (self.private + self.mask) % self.q if self.scalar < 2: raise ValueError('Scalar is {}, regenerating...'.format(self.scalar)) P = self.curve.double_add_algorithm(self.mask, self.PE) self.element = self.curve.ec_inv(P) assert self.curve.valid(self.element) return self.scalar, self.element def compute_shared_secret(self, peer_element, peer_scalar, peer_mac): self.peer_element = peer_element self.peer_scalar = peer_scalar self.peer_mac = peer_mac assert self.curve.valid(self.peer_element) # If both the peer-scalar and Peer-Element are # valid, they are used with the Password Element to derive a shared # secret, ss: Z = self.curve.double_add_algorithm(self.peer_scalar, self.PE) ZZ = self.curve.ec_add(self.peer_element, Z) K = self.curve.double_add_algorithm(self.private, ZZ) self.k = K[0] own_message = '{}{}{}{}{}{}'.format(self.k , self.scalar , self.peer_scalar , self.element[0] , self.peer_element[0] , self.mac_address).encode() H = hashlib.sha256() H.update(own_message) self.token = H.hexdigest() return self.token def confirm_exchange(self, peer_token): peer_message = '{}{}{}{}{}{}'.format(self.k , self.peer_scalar , self.scalar , self.peer_element[0] , self.element[0] , self.peer_mac).encode() H = hashlib.sha256() H.update(peer_message) self.peer_token_computed = H.hexdigest() #print('[{}] Computed Token from Peer={}'.format(self.name, self.peer_token_computed)) #print('[{}] Received Token from Peer={}'.format(self.name, peer_token)) if peer_token != self.peer_token_computed: return False # Pairwise Master Key” (PMK) # compute PMK = H(k | scal(AP1) + scal(AP2) mod q) pmk_message = '{}{}'.format(self.k, (self.scalar + self.peer_scalar) % self.q).encode() H = hashlib.sha256() H.update(pmk_message) self.PMK = H.hexdigest() logger.info('[{}] Pairwise Master Key(PMK)={}'.format(self.name, self.PMK)) return True def key_derivation_function(self, n, base, seed): """ B.5.1 Per-Message Secret Number Generation Using Extra Random Bits Key derivation function from Section B.5.1 of [FIPS186-4] The key derivation function, KDF, is used to produce a bitstream whose length is equal to the length of the prime from the group's domain parameter set plus the constant sixty-four (64) to derive a temporary value, and the temporary value is modularly reduced to produce a seed. """ combined_seed = '{}{}'.format(base, seed).encode() # base and seed concatenated are the input to the RGB random.seed(combined_seed) # Obtain a string of N+64 returned_bits from an RBG with a security strength of # requested_security_strength or more. randbits = random.getrandbits(n) binary_repr = format(randbits, '0{}b'.format(n)) assert len(binary_repr) == n logger.debug('Rand={}'.format(binary_repr)) # Convert returned_bits to the non-negative integer c (see Appendix C.2.1). C = 0 for i in range(n): if int(binary_repr[i]) == 1: C += pow(2, n-i) logger.debug('C={}'.format(C)) #k = (C % (n - 1)) + 1 k = C logger.debug('k={}'.format(k)) return k def compute_hashed_password(self, counter): maxm = max(self.mac_address, self.other_mac) minm = min(self.mac_address, self.other_mac) message = '{}{}{}{}'.format(maxm, minm, self.password, counter).encode() logger.debug('Message to hash is: {}'.format(message)) H = hashlib.sha256() H.update(message) digest = H.digest() return digest def receive_sta_mac(conn): data = conn.recv(1024).decode().strip() return data def receive_sta_token(conn): data = conn.recv(1024).decode().strip() return data def receive_sta_scalar_element(conn, p): data = conn.recv(1024).decode().strip() if data.count(",") != 2: return 0, 0 scalar_sta, element_sta_x, element_sta_y = data.split(',') if int(scalar_sta) < 2 or int(element_sta_x) < 2 or int(element_sta_y) < 2: return 0, 0 if int(scalar_sta) >= p -1 or int(element_sta_x) >= p - 1 or int(element_sta_y) >= p - 1: return 0, 0 scalar_sta = int(scalar_sta) element_sta = Point(int(element_sta_x), int(element_sta_y)) return scalar_sta, element_sta def send_sta(conn, message): conn.sendall(message.encode()) def sae_state_machine(conn, real_psk, ap_mac): state = 0 mac2 = ap_mac max_retries = 0 ap = Peer(real_psk, mac2, 'AP') scalar_sta, element_sta = None, None mac1 = None sta_token = None while True: if state == 0: send_sta(conn, "I am MAC %s, what is your MAC? " % ap_mac) mac1 = receive_sta_mac(conn) state = 1 elif state == 1: #logger.info('Starting hunting and pecking to derive PE...\n') scalar_ap, element_ap = None, None ap.initiate(mac1) scalar_ap, element_ap = ap.commit_exchange() send_sta(conn, ','.join(map(str, [scalar_ap, element_ap.x, element_ap.y])) + '\n') state = 2 elif state == 2: #logger.info('Computing shared secret...\n') scalar_sta, element_sta = receive_sta_scalar_element(conn, ap.p) if scalar_sta == 0: #reset state state = 0 continue ap_token = ap.compute_shared_secret(element_sta, scalar_sta, mac1) state = 3 elif state == 3: #logger.info('Confirm Exchange...\n') send_sta(conn, "Token? ") sta_token = receive_sta_token(conn) if ap.confirm_exchange(sta_token) == True: d=open("flag.txt").read() send_sta(conn, d+"\n") send_sta(conn, "FLAG WAS SENT\n") exit(0) else: send_sta(conn, "you didnt solve...\n") if max_retries >= 2: send_sta(conn, "[!] HACKING FAIL DETECTED [!]\n") exit(1) max_retries += 1 def gen_password(): passwords = open("rockyou-75.txt","rb").readlines() return secrets.choice(passwords).decode().strip() def main(): host = '0.0.0.0' port = 2561 max_clients = 20 with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s: s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) s.bind((host, port)) s.listen(max_clients) client_count = 0 while True: conn, addr = s.accept() pid = os.fork() if pid == 0: # Child process s.close() # Close the listening socket in the child process signal.alarm(300) # Set the connection time limit to 300 seconds print(f"Connected by {addr}") real_psk = gen_password() print(real_psk) ap_mac = '01:02:03:0a:0b:0c' sae_state_machine(conn, real_psk, ap_mac) conn.close() os._exit(0) else: try: os.waitpid(-1, os.WNOHANG) except: pass conn.close() 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/MidnightSun/2022/Quals/crypto/BabyZK/babyzk.py
ctfs/MidnightSun/2022/Quals/crypto/BabyZK/babyzk.py
#!/usr/bin/python3 from sys import stdin, stdout, exit from secrets import randbelow from gmpy import next_prime from flag import FLAG class BabyZK: def __init__(self, degree, nbits): self.p = self.__safeprime(nbits) self.degree = degree self.m = [randbelow(self.p-1) for i in range(self.degree)] self.g = 2 + randbelow(self.p-3) self.ctr = 0 def __safeprime(self, nbits): stdout.write("Generating safeprime...") p = -1 while True: q = next_prime(randbelow(2 * 2**nbits)) p = 2*q + 1 if p.is_prime(): break return p def __eval(self, x: int) -> int: y = 0 for a in self.m: y += y * x + a return y % (self.p-1) def prover(self, x: int) -> int: if self.ctr > self.degree + 1: raise Exception("Sorry, you are out of queries...") self.ctr += 1 return int(pow(self.g, self.__eval(x), self.p)) def verify(self, x: int, u: int): if not u < self.p or u < 0: raise Exception("Oof, this is not mod p...") if int(pow(self.g, self.__eval(x), self.p)) != u: raise Exception("No can do...") bzk = BabyZK(15, 1024) def prove(): stdout.write("> ") stdout.flush() challenge = int(stdin.readline()) stdout.write("%d\n" % bzk.prover(challenge)) stdout.flush() def verify(): for i in range(100): challenge = randbelow(bzk.p) stdout.write("%d\n" % challenge) stdout.flush() response = int(stdin.readline()) bzk.verify(challenge, response) stdout.write("%s\n" % FLAG) stdout.flush() banner = lambda: stdout.write(""" 1) Query the prover oracle. 2) Prove to verifier that you know the secret. 3) Exit. """) choices = { 1: prove, 2: verify, 3: exit } banner() stdout.flush() while True: try: choice = stdin.readline() choices.get(int(choice))() except Exception as e: stdout.write("%s\n" % e) stdout.flush() exit()
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/MidnightSun/2022/Quals/crypto/PellesRotor-SupportedArithmetic/pelles_rotor_supported_arithmetic.py
ctfs/MidnightSun/2022/Quals/crypto/PellesRotor-SupportedArithmetic/pelles_rotor_supported_arithmetic.py
#!/usr/bin/python3 from sys import stdin, stdout, exit from flag import FLAG from secrets import randbelow from gmpy import next_prime p = int(next_prime(randbelow(2**512))) q = int(next_prime(randbelow(2**512))) n = p * q e = 65537 phi = (p - 1)*(q - 1) d = int(pow(e, -1, phi)) d_len = len(str(d)) print("encrypted flag", pow(FLAG, 3331646268016923629, n)) stdout.flush() ctr = 0 def oracle(c, i): global ctr if ctr > 10 * d_len // 9: print("Come on, that was already way too generous...") return ctr += 1 rotor = lambda d, i: int(str(d)[i % d_len:] + str(d)[:i % d_len]) return int(pow(c, rotor(d, i), n)) banner = lambda: stdout.write(""" Pelle's Rotor Supported Arithmetic Oracle 1) Query the oracle with a ciphertext and rotation value. 2) Exit. """) banner() stdout.flush() choices = { 1: oracle, 2: exit } while True: try: choice = stdin.readline() print("c:") stdout.flush() cipher = stdin.readline() print("rot:") stdout.flush() rotation = stdin.readline() print(choices.get(int(choice))(int(cipher), int(rotation))) stdout.flush() except Exception as e: stdout.write("%s\n" % e) stdout.flush() exit()
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/Glacier/2023/blockchain/GlacierCoin/solve-pow.py
ctfs/Glacier/2023/blockchain/GlacierCoin/solve-pow.py
import hashlib,random x = 100000000+random.randint(0,200000000000) for i in range(x,x+20000000000): m = hashlib.sha256() ticket = str(i) m.update(ticket.encode('ascii')) digest1 = m.digest() m = hashlib.sha256() m.update(digest1 + ticket.encode('ascii')) if m.hexdigest().startswith('0000000'): print(i) break
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/Glacier/2023/blockchain/The_Council_of_Apes/solve-pow.py
ctfs/Glacier/2023/blockchain/The_Council_of_Apes/solve-pow.py
import hashlib,random x = 100000000+random.randint(0,200000000000) for i in range(x,x+20000000000): m = hashlib.sha256() ticket = str(i) m.update(ticket.encode('ascii')) digest1 = m.digest() m = hashlib.sha256() m.update(digest1 + ticket.encode('ascii')) if m.hexdigest().startswith('0000000'): print(i) break
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/Glacier/2023/blockchain/GlacierVault/solve-pow.py
ctfs/Glacier/2023/blockchain/GlacierVault/solve-pow.py
import hashlib,random x = 100000000+random.randint(0,200000000000) for i in range(x,x+20000000000): m = hashlib.sha256() ticket = str(i) m.update(ticket.encode('ascii')) digest1 = m.digest() m = hashlib.sha256() m.update(digest1 + ticket.encode('ascii')) if m.hexdigest().startswith('0000000'): print(i) break
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/Glacier/2023/blockchain/ChairLift/solve-pow.py
ctfs/Glacier/2023/blockchain/ChairLift/solve-pow.py
import hashlib,random x = 100000000+random.randint(0,200000000000) for i in range(x,x+20000000000): m = hashlib.sha256() ticket = str(i) m.update(ticket.encode('ascii')) digest1 = m.digest() m = hashlib.sha256() m.update(digest1 + ticket.encode('ascii')) if m.hexdigest().startswith('0000000'): print(i) break
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/Glacier/2023/misc/Avatar/chall.py
ctfs/Glacier/2023/misc/Avatar/chall.py
print("You get one chance to awaken from the ice prison.") code = input("input: ").strip() whitelist = """gctf{"*+*(=>:/)*+*"}""" # not the flag if any([x not in whitelist for x in code]) or len(code) > 40000: print("Denied!") exit(0) eval(eval(code, {'globals': {}, '__builtins__': {}}, {}), {'globals': {}, '__builtins__': {}}, {})
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/Glacier/2023/misc/Silent_Snake/chall/repl.py
ctfs/Glacier/2023/misc/Silent_Snake/chall/repl.py
#!/usr/bin/env python3 import os import sys import code DEBUG = os.environ.get("DEBUG", "0") == "1" cpipe = os.fdopen(int(sys.argv[1]), "w", buffering=1) devnull = open("/dev/null", mode="w") print(""" Welcome to silent-snake, the blind REPL! You've got a single ls that you can redeem using `run_command('ls <directory_to_ls>')` To exit the jail, use `exit()` or `run_command('exit')` Have fun! """) if not DEBUG: sys.stdout.close() sys.stderr.close() os.close(1) os.close(2) sys.stdout = devnull sys.stderr = devnull else: print(50*"=") print("WARNING: Debugging mode is *ON*. stdout and stderr are available here, but you won't be able to see the REPL's output during the challenge.") print(50*"=") # Redirect stderr to stdout os.dup2(1, 2, inheritable=True) def run_command(cmd: str): cpipe.write(cmd + "\n") code.interact(local=locals()) run_command("exit")
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/Glacier/2023/misc/Silent_Snake/chall/silent_snake.py
ctfs/Glacier/2023/misc/Silent_Snake/chall/silent_snake.py
#!/usr/bin/env python3 import os import random import subprocess import time DEBUG = os.environ.get("DEBUG", "0") == "1" def drop_to_unprivileged(uid: int, gid: int): # Drop to a unprivileged user and group. assert uid != 0 and gid != 0 os.setresgid(uid, uid, uid) os.setresuid(gid, gid, gid) def drop_to_ctf_uid_gid(): drop_to_unprivileged(4242, 4242) (r, w) = os.pipe() os.set_inheritable(w, True) repl = subprocess.Popen(["./repl.py", str(w)], close_fds=False, preexec_fn=drop_to_ctf_uid_gid) os.close(w) ppipe = os.fdopen(r, "r", buffering=1) allowed = { "ls": True, } try: while repl.poll() == None: cmd = ppipe.readline() if cmd == "": break cmd = cmd.strip().split(" ") if DEBUG: print("RECEIVED COMMAND:", cmd) if cmd[0] == "exit": break elif cmd[0] == "ls" and allowed["ls"] and len(cmd) == 2: valid = True resolved = [] path = cmd[1] if not path.startswith("-") and os.path.isdir(path): cmd = ["ls", "-l", path] if DEBUG: print(cmd) subprocess.run(cmd, stderr=(subprocess.STDOUT if DEBUG else subprocess.DEVNULL), preexec_fn=drop_to_ctf_uid_gid) allowed["ls"] = False except Exception as ex: if DEBUG: import traceback traceback.print_exc() if DEBUG: print("Terminating REPL process...") repl.kill() repl.wait() if DEBUG: print("REPL terminated - waiting...") time.sleep(random.randrange(300, 600))
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/Glacier/2023/pwn/flipper/utils/add-debug/elf/enum-print.py
ctfs/Glacier/2023/pwn/flipper/utils/add-debug/elf/enum-print.py
import sys, re from optparse import OptionParser def read_toks(): data = sys.stdin.read() while data: data = data.lstrip() if data.startswith("//") or data.startswith("#"): data = data.split("\n",1)[1] elif data.startswith("/*"): data = data.split("*/",1)[1] elif data.startswith("\"") or data.startswith("'"): c = data[0] m = re.match(r'%s([^\\%s]|\\.)*%s' % (c,c,c), data) yield m.group(0) data = data[m.end():] else: m = re.match(r"[_a-zA-Z0-9]+|[{}();]|[^_a-zA-Z0-9 \n\t\f]+", data) yield m.group(0) data = data[m.end():] enums = {} def do_top_level(toks, ns=[]): while toks: tok = toks.pop(0) if tok == "enum" and toks[0] == "class": toks.pop(0) name = toks.pop(0) # Get to the first token in the body while toks.pop(0) != "{": pass # Consume body and close brace do_enum_body("::".join(ns + [name]), toks) elif tok == "class": name = do_qname(toks) # Find the class body, if there is one while toks[0] != "{" and toks[0] != ";": toks.pop(0) # Enter the class's namespace if toks[0] == "{": toks.pop(0) do_top_level(toks, ns + [name]) elif tok == "{": # Enter an unknown namespace do_top_level(toks, ns + [None]) elif tok == "}": # Exit the namespace assert len(ns) return elif not ns and tok == "string" and toks[:2] == ["to_string", "("]: # Get the argument type and name toks.pop(0) toks.pop(0) typ = do_qname(toks) if typ not in enums: continue arg = toks.pop(0) assert toks[0] == ")" if typ in options.mask: make_to_string_mask(typ, arg) else: make_to_string(typ, arg) def fmt_value(typ, key): if options.no_type: val = key else: val = "%s%s%s" % (typ, options.separator, key) if options.strip_underscore: val = val.strip("_") return val def expr_remainder(typ, arg): if options.hex: return "\"(%s)0x\" + to_hex((int)%s)" % (typ, arg) else: return "\"(%s)\" + std::to_string((int)%s)" % (typ, arg) def make_to_string(typ, arg): print("std::string") print("to_string(%s %s)" % (typ, arg)) print("{") print(" switch (%s) {" % arg) for key in enums[typ]: if key in options.exclude: print(" case %s::%s: break;" % (typ, key)) continue print(" case %s::%s: return \"%s\";" % \ (typ, key, fmt_value(typ, key))) print(" }") print(" return %s;" % expr_remainder(typ, arg)) print("}") print def make_to_string_mask(typ, arg): print("std::string") print("to_string(%s %s)" % (typ, arg)) print("{") print(" std::string res;") for key in enums[typ]: if key in options.exclude: continue print(" if ((%s & %s::%s) == %s::%s) { res += \"%s|\"; %s &= ~%s::%s; }" % \ (arg, typ, key, typ, key, fmt_value(typ, key), arg, typ, key)) print(" if (res.empty() || %s != (%s)0) res += %s;" % \ (arg, typ, expr_remainder(typ, arg))) print(" else res.pop_back();") print(" return res;") print("}") print def do_enum_body(name, toks): keys = [] while True: key = toks.pop(0) if key == "}": assert toks.pop(0) == ";" enums[name] = keys return keys.append(key) if toks[0] == "=": toks.pop(0) toks.pop(0) if toks[0] == ",": toks.pop(0) else: assert toks[0] == "}" def do_qname(toks): # Get a nested-name-specifier followed by an identifier res = [] while True: res.append(toks.pop(0)) if toks[0] != "::": return "::".join(res) toks.pop(0) parser = OptionParser() parser.add_option("-x", "--exclude", dest="exclude", action="append", help="exclude FIELD", metavar="FIELD", default=[]) parser.add_option("-u", "--strip-underscore", dest="strip_underscore", action="store_true", help="strip leading and trailing underscores") parser.add_option("-s", "--separator", dest="separator", help="use SEP between type and field", metavar="SEP", default="::") parser.add_option("--hex", dest="hex", action="store_true", help="return unknown values in hex", default=False) parser.add_option("--no-type", dest="no_type", action="store_true", help="omit type") parser.add_option("--mask", dest="mask", action="append", help="treat TYPE as a bit-mask", metavar="TYPE", default=[]) (options, args) = parser.parse_args() if args: parser.error("expected 0 arguments") do_top_level(list(read_toks()))
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/Glacier/2023/crypto/Missing_Bits/encode_file.py
ctfs/Glacier/2023/crypto/Missing_Bits/encode_file.py
from Crypto.PublicKey import RSA from Crypto.Util.number import bytes_to_long from Crypto.Util.number import long_to_bytes content = open("2048_key_original.priv", "rb").read() key = RSA.import_key(content) filecontent = open("plaintext_message", "rb").read() ct = pow(bytes_to_long(filecontent), key.e, key.n) open("ciphertext_message", "wb").write(long_to_bytes(ct))
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/Glacier/2023/crypto/Glacier_Spirit/challenge.py
ctfs/Glacier/2023/crypto/Glacier_Spirit/challenge.py
#!/usr/bin/env python3 import ascon import secrets from secret import FLAG BLOCK_SIZE = 16 def xor(a, b): return bytes([x ^ y for x, y in zip(a, b)]) def split_blocks(message): return [message[i:i + BLOCK_SIZE] for i in range(0, len(message), BLOCK_SIZE)] def mac_creation(key, message): assert len(message) % BLOCK_SIZE == 0 message_blocks = split_blocks(message) enc_out = b"\x00" * BLOCK_SIZE for message in message_blocks: chaining_values = xor(message, enc_out) enc_out = ascon.encrypt(key, chaining_values, b'', b'') assert len(enc_out) == BLOCK_SIZE return enc_out def pad_message(message): first_block_pad = len(message) % BLOCK_SIZE first_block_pad = 16 if first_block_pad == 0 else first_block_pad return (first_block_pad.to_bytes() * (BLOCK_SIZE - first_block_pad)) + message def encrypt(key, message): assert len(message) % BLOCK_SIZE == 0 message_blocks = split_blocks(message) assert len(message_blocks) < BLOCK_SIZE nonce = secrets.token_bytes(BLOCK_SIZE-1) cts = [] for ctr, message in enumerate(message_blocks): cipher_input = nonce + (ctr+1).to_bytes(1, 'little') enc = ascon.encrypt(key, cipher_input, b'', b'') ct = xor(message, enc) cts.append(ct) return nonce, b''.join(cts) def create_message_and_mac(key, message): padded_message = pad_message(message) nonce, ct = encrypt(key, padded_message) tag = mac_creation(key, padded_message) return nonce, ct, tag if __name__ == "__main__": print(" Glacier Spirit\n\n") print(" , /\.__ _.-\ ") print(" /~\, __ /~ \ ./ \ ") print(" ,/ /_\ _/ \ ,/~,_.~''\ /_\_ /'\ ") print(" / \ /## \ / V#\/\ /~8# # ## V8 #\/8 8\ ") print(" /~#'#'#''##V&#&# ##\/88#'#8# #' #\#&'##' ##\ ") print(" j# ##### #'#\&&'####/###& #'#&## #&' #'#&#'#'\ ") print(" /#'#'#####'###'\&##'/&#'####'### # #&#&##'#'### \ ") print(" J#'###'#'#'#'####'\# #'##'#'##'#'#####&'## '#'&'##|\ ") key = secrets.token_bytes(BLOCK_SIZE) print("The spirit of the glacier gifts you a flag!\n") nonce, ct, tag = create_message_and_mac(key, FLAG) print(f"{nonce.hex()}, {ct.hex()}, {tag.hex()}") print("\nNow you can bring forth your own messages to be blessed by the spirit of the glacier!\n") for i in range(8): print(f"Offer your message:") user_msg = input() try: msg = bytes.fromhex(user_msg) except: print("The spirit of the glacier is displeased with the format of your message.") exit(0) nonce, ct, tag = create_message_and_mac(key, msg) print("The spirit of the glacier has blessed your message!\n") print(f"{nonce.hex()}, {ct.hex()}, {tag.hex()}") print("The spirit of the glacier has left you. You are alone once more.")
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/Glacier/2023/crypto/SLCG/encrypt.py
ctfs/Glacier/2023/crypto/SLCG/encrypt.py
from __future__ import annotations import os FLAG = b"gctf{???????}" class LCG: def __init__(self, mod: int, mult: int, add: int, seed: int): self.mod = mod self.mult = mult self.add = add self.value = seed def __next__(self) -> int: self.value = (self.value * self.mult + self.add) % self.mod return self.value def __iter__(self) -> LCG: return self @classmethod def random_values(cls): return LCG( int.from_bytes(os.urandom(16)), int.from_bytes(os.urandom(16)), int.from_bytes(os.urandom(16)), int.from_bytes(os.urandom(16)) ) class Encryptor: def __init__(self): self.lcgs: tuple[LCG] = (LCG.random_values(), LCG.random_values()) def encrypt(self, message: str) -> list[int]: result = [] for ascii_char in message: bin_char = list(map(int, list(f"{ascii_char:07b}"))) for bit in bin_char: result.append(next(self.lcgs[bit])) self.lcgs = ( LCG( next(self.lcgs[0]), next(self.lcgs[0]), next(self.lcgs[0]), next(self.lcgs[0]) ), LCG( next(self.lcgs[1]), next(self.lcgs[1]), next(self.lcgs[1]), next(self.lcgs[1]) ) ) return result def main() -> int: encryption = Encryptor() print(f"ct = {encryption.encrypt(FLAG)}") return 0 if __name__ == "__main__": raise SystemExit(main())
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/Glacier/2023/crypto/ARISAI/chall.py
ctfs/Glacier/2023/crypto/ARISAI/chall.py
from Crypto.Util.number import bytes_to_long from Crypto.Util.number import getPrime PRIME_LENGTH = 24 NUM_PRIMES = 256 FLAG = b"gctf{redacted}" N = 1 e = 65537 for i in range(NUM_PRIMES): prime = getPrime(PRIME_LENGTH) N *= prime ct = pow(bytes_to_long(FLAG), e, N) print(f"{N=}") print(f"{e=}") print(f"{ct=}")
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/Glacier/2023/web/Peak/admin-simulation/admin.py
ctfs/Glacier/2023/web/Peak/admin-simulation/admin.py
#!/usr/bin/env python3 import sys, requests import os from time import sleep from bs4 import BeautifulSoup from datetime import datetime from selenium import webdriver from selenium.webdriver.support import expected_conditions as EC from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.chrome.service import Service from selenium.webdriver.common.action_chains import ActionChains from selenium.webdriver.common.by import By from pyvirtualdisplay import Display import urllib3 urllib3.disable_warnings() class AdminAutomation: host = os.environ.get("HOST", "http://web") timeout = int(os.environ.get("TIMEOUT", "5")) driver = None _username = 'admin' _password = '' display = Display(visible=0, size=(800, 600)) display.start() def __init__(self, password:str=''): chrome_options = self._set_chrome_options() service = Service(executable_path=r'/usr/bin/chromedriver') self.driver = webdriver.Chrome(service=service, options=chrome_options) self.driver.set_page_load_timeout(self.timeout) self._password = password if self._password == '': raise Exception('No password for admin configured!') def _set_chrome_options(self): ''' Sets chrome options for Selenium: - headless browser is enabled - sandbox is disbaled - dev-shm usage is disabled - SSL certificate errors are ignored ''' chrome_options = webdriver.ChromeOptions() options = [ '--headless', '--no-sandbox', '--disable-dev-shm-usage', '--ignore-certificate-errors', '--disable-extensions', '--no-first-run', '--disable-logging', '--disable-notifications', '--disable-permissions-api', '--hide-scrollbars', '--disable-gpu', '--window-size=800,600', '--disable-xss-auditor' ] for option in options: chrome_options.add_argument(option) return chrome_options def login(self) -> bool: ''' Login as admin - Returns: `True` if successful and `False` of unsuccessful ''' self.driver.get(f'{self.host}/login.php') WebDriverWait(self.driver, 10).until(EC.presence_of_element_located((By.NAME, 'username'))) self.driver.find_element('name', 'username').send_keys('admin') WebDriverWait(self.driver, 10).until(EC.presence_of_element_located((By.NAME, 'password'))) self.driver.find_element('name', 'password').send_keys(self._password) WebDriverWait(self.driver, 10).until(EC.element_to_be_clickable((By.NAME, 'button'))) self.driver.find_element('name', 'button').click() if self.driver.current_url != f'{self.host}/': return False print(f'[{datetime.now()}] Successfully logged in!\r\n') return True def read_messages(self): print(f'[{datetime.now()}] Checking messages...') self.driver.get(f'{self.host}/admin/support.php') if self.driver.current_url != f'{self.host}/admin/support.php': raise Exception("Cannot access support.php! Session probably expired!") links = [element.get_attribute('href') for element in self.driver.find_elements('name', 'inbox-header')] if len(links) > 0: for link in links: if link: try: self.driver.get(link) if self.driver.current_url == link: print(f'[{datetime.now()}] Visiting: {self.driver.current_url}\r\n') else: print(f'[{datetime.now()}] After visiting {link}, got redirect to: {self.driver.current_url}\r\n') except Exception as ex: '''Timeout or other exception occurred on url. ''' print(f'[{datetime.now()}] Error after visiting: {link} (Current URL: {self.driver.current_url}). Error: {ex}\r\n') def close(self): if self.driver: self.driver.close() self.driver.quit() self.driver = None if self.display: self.display.stop() if __name__ == '__main__': os.system('pkill -f chrome') os.system('pkill -f Xvfb') admin = None try: if len(sys.argv) < 2: raise Exception('Specify a password!') admin = AdminAutomation(sys.argv[1]) tries = 0 while not admin.login(): if tries > 5: raise Exception('Could not login!') tries += 1 sleep(1) while True: admin.read_messages() sleep(5) admin.close() quit() except Exception as ex: print(f'[-] Error: {ex}') if admin is not None: admin.close() quit()
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/Glacier/2023/web/Glacier_Exchange/server.py
ctfs/Glacier/2023/web/Glacier_Exchange/server.py
from flask import Flask, render_template, request, send_from_directory, jsonify, session from flask_restful import Api from src.coin_api import get_coin_price_from_api from src.wallet import Wallet import os import secrets app = Flask(__name__) api = Api(app) app.secret_key = os.urandom(64) wallets = {} def get_wallet_from_session(): if "id" not in session: session["id"] = make_token() if session["id"] not in wallets: wallets[session["id"]] = Wallet() return wallets[session["id"]] def make_token(): return secrets.token_urlsafe(16) @app.route("/", methods=["GET", "POST"]) def index(): return render_template( "index.html", ) @app.route('/assets/<path:path>') def assets(path): return send_from_directory('assets', path) @app.route('/api/data/fetch/<path:coin>') def fetch(coin: str): data = get_coin_price_from_api(coin) return jsonify(data) @app.route('/api/wallet/transaction', methods=['POST']) def transaction(): payload = request.json status = 0 if "sourceCoin" in payload and "targetCoin" in payload and "balance" in payload: wallet = get_wallet_from_session() status = wallet.transaction(payload["sourceCoin"], payload["targetCoin"], float(payload["balance"])) return jsonify({ "result": status }) @app.route("/api/wallet/join_glacier_club", methods=["POST"]) def join_glacier_club(): wallet = get_wallet_from_session() clubToken = False inClub = wallet.inGlacierClub() if inClub: f = open("/flag.txt") clubToken = f.read() f.close() return { "inClub": inClub, "clubToken": clubToken } @app.route('/api/wallet/balances') def get_balance(): wallet = get_wallet_from_session() balances = wallet.getBalances() user_balances = [] for name in balances: user_balances.append({ "name": name, "value": balances[name] }) return user_balances @app.route('/api/fetch_coins') def fetch_coins(): return jsonify([ { "name": 'cashout', "value": 'Cashout Account', "short": 'CA' }, { "name": 'glaciercoin', "value": 'GlacierCoin', "short": 'GC' }, { "name": 'ascoin', "value": 'AsCoin', "short": 'AC' }, { "name": 'doge', "value": 'Doge', "short": 'DO' }, { "name": 'gamestock', "value": 'Gamestock', "short": 'GS' }, { "name": 'ycmi', "value": 'Yeti Clubs Manufacturing Inc.', "short": 'YC' }, { "name": 'smtl', "value": 'Synthetic Mammoth Tusks LLC', "short": 'ST' }, ]) if __name__ == '__main__': app.run( host="0.0.0.0", port=8080, debug=True, )
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/Glacier/2023/web/Glacier_Exchange/src/wallet.py
ctfs/Glacier/2023/web/Glacier_Exchange/src/wallet.py
import threading class Wallet(): def __init__(self) -> None: self.balances = { "cashout": 1000, "glaciercoin": 0, "ascoin": 0, "doge": 0, "gamestock": 0, "ycmi": 0, "smtl": 0 } self.lock = threading.Lock(); def getBalances(self): return self.balances def transaction(self, source, dest, amount): if source in self.balances and dest in self.balances: with self.lock: if self.balances[source] >= amount: self.balances[source] -= amount self.balances[dest] += amount return 1 return 0 def inGlacierClub(self): with self.lock: for balance_name in self.balances: if balance_name == "cashout": if self.balances[balance_name] < 1000000000: return False else: if self.balances[balance_name] != 0.0: return False return True
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/Glacier/2023/web/Glacier_Exchange/src/coin_api.py
ctfs/Glacier/2023/web/Glacier_Exchange/src/coin_api.py
import time import random def get_coin_price_from_api(coin: str): coins = coin.split('/') if(len(coins) != 2): return [] seed = coins[0] + coins[1] if coins[0] < coins[1] else coins[1] + coins[0] is_reverse = coins[0] < coins[1] random.seed(seed) end_timestamp = int(time.time()) * 1000 new_open = 15.67 new_high = 15.83 new_low = 15.24 new_close = 15.36 new_volume = 3503100 movement = 0.7 data = [] max_ticks = 200 for ts in range(0, max_ticks): display_new_open = 1. / new_open if is_reverse else new_open display_new_high = 1. / new_high if is_reverse else new_high display_new_low = 1. / new_low if is_reverse else new_low display_new_close = 1. / new_close if is_reverse else new_close data.append({ "Date": end_timestamp - (max_ticks - ts) * (1000 * 86400), "Open": display_new_open, "High": display_new_high, "Low": display_new_low, "Close": display_new_close, "Volume": new_volume }) # New Open => Downwards Trend # New Close => Upwards Trend indicator = new_open if random.random() > 0.5 else new_close new_open = indicator + movement * (random.random() - 0.5) new_high = indicator + movement * (random.random() - 0.5) new_low = indicator + movement * (random.random() - 0.5) new_close = indicator + movement * (random.random() - 0.5) new_volume = new_volume + movement * (random.random() - 0.5) return data
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/Glacier/2022/crypto/ChaCha60/chacha60.py
ctfs/Glacier/2022/crypto/ChaCha60/chacha60.py
#!/usr/bin/env python3 from Crypto.Cipher import ChaCha20 import numpy as np import os from binascii import hexlify with np.load('matrices.npz') as f: m1 = f.get('m1') m2 = f.get('m2') m3 = f.get('m3') if __name__ == '__main__': key = np.unpackbits(bytearray(os.urandom(8)), bitorder='little') k1 = m1.dot(key) % 2 k2 = m2.dot(key) % 2 k3 = m3.dot(key) % 2 k1 = bytes(np.packbits(k1, bitorder='little')) k2 = bytes(np.packbits(k2, bitorder='little')) k3 = bytes(np.packbits(k3, bitorder='little')) print("base key: " + bytes(np.packbits(key, bitorder='little')).hex()) print("exp. key: " + (k1 + k2 + k3).hex()) k1 = k1 + b'\0' * 28 k2 = k2 + b'\0' * 28 k3 = k3 + b'\0' * 28 nonce = b'\0' * 8 c1 = ChaCha20.new(key=k1, nonce=nonce) c2 = ChaCha20.new(key=k2, nonce=nonce) c3 = ChaCha20.new(key=k3, nonce=nonce) with open('flag.png', 'rb') as f: pt = f.read() ct = c3.encrypt(c2.encrypt(c1.encrypt(pt))) with open('flag.png.enc', 'wb') as f: f.write(ct)
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/Glacier/2022/crypto/CryptoShop/store.py
ctfs/Glacier/2022/crypto/CryptoShop/store.py
from typing import Union from typing import Set # pip install pycryptodome import Crypto from Crypto.PublicKey import RSA SHOP_ITEMS = { "USB Rubber Ducky": 1, "Malduino": 2, "WIFI Deauther": 3, "Bluetooth Jammer": 5, "GSM Jammer": 7, "Bad USB": 10, "CTF-Flag": 1000, } FLAG = open("flag.txt", "r").read() def calc_refund_code(price: int, d: int, n: int): return pow(price, d, n) class ShopTransaction: def __init__( self, name: str, price: int, priv_key: Crypto.PublicKey.RSA.RsaKey ): self.name = name self.price = price self.refund_code = calc_refund_code(self.price, priv_key.d, priv_key.n) def __str__(self): return f"{self.name}: {self.price}(Refund-Code: {self.refund_code})" class ShopState: def __init__( self, name: str, balance: int = 5, priv_key: Crypto.PublicKey.RSA.RsaKey = None ): self.name = name self.balance = balance self.prev_refunds: Set[int] = set() self.priv_key = priv_key self.pub_key = self.priv_key.public_key() def refund_item(self, price: int, refund_code: int) -> int: if refund_code in self.prev_refunds: return -1 reference_code = calc_refund_code( price, self.priv_key.d, self.priv_key.n ) if refund_code != reference_code: print(type(refund_code)) print(type(reference_code)) print("Refund-Code\n", reference_code) print("Calculated-Code\n", refund_code) return -2 self.balance += price return 0 def buy(self, name: str) -> Union[ShopTransaction, int]: price = SHOP_ITEMS[name] if self.balance < price: return -1 self.balance -= price if name == "CTF-Flag": print(f"Take this: {FLAG}") return ShopTransaction(name, price, self.priv_key) def generate_keys() -> Crypto.PublicKey.RSA.RsaKey: key = RSA.generate(1024) return key def buy_menu(shop_state: ShopState) -> int: print("What item do you want to bye?") for i, item in enumerate(SHOP_ITEMS): print(f"{i}. {item}") print() item_name = input("> ").strip() if item_name not in SHOP_ITEMS.keys(): print(f"Error! Item {item_name} could not be found") return -1 shop_transaction = shop_state.buy(item_name) if isinstance(shop_transaction, int) and shop_transaction == -1: print("Error, not enough money") return 0 print(f"Bought {shop_transaction.name} for {shop_transaction.price}") print(f"Refund-Code:\n{shop_transaction.refund_code}") return 0 def refund_menu(shop_state: ShopState) -> int: print("What do you want to refund?") print("Please provide the refundcode") refund_code = input("> ").strip() print("Please provide the price") refund_amount = input("> ").strip() try: refund_amount = int(refund_amount) except ValueError: print(f"Value {refund_amount} not a valid price") return 0 try: refund_code = int(refund_code) except ValueError: print(f"Invalid {refund_code}") return 0 ret_val = shop_state.refund_item(refund_amount, refund_code) if ret_val == 0: print("Successfully refunded") if ret_val == -1: print("Error, this refund code was already used!!") if ret_val == -2: print("Error, this refund code does not match the price!") return 0 def display_menu(): key = generate_keys() print("Welcome to the PWN-Store. Please authenticate:") user = input("Your Name: ") print(f"Welcome back {user}!") user_shop_state = ShopState(user, priv_key=key) print(f"Customernumber: {user_shop_state.pub_key.n}") while True: print() print(f"Accountname: {user} (Balance: {user_shop_state.balance}€)") print("1. List Items") print("2. Buy Item") print("3. Refund Item") print("4. Exit") print() action = input("> ") try: action = int(action.strip()) except ValueError: print(f"Error, {action} is not a valid number!") continue if action < 0 or action > 5: print(f"Error, {action} is not a valic action") if action == 1: for i, item in enumerate(SHOP_ITEMS): print(f"{i}. {item} (Price: {SHOP_ITEMS[item]})") if action == 2: ret_val = buy_menu(user_shop_state) if ret_val != 0: print("An Error occured! Exiting") break if action == 3: refund_menu(user_shop_state) if action == 4: break return 0 if __name__ == "__main__": raise SystemExit(display_menu())
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/Glacier/2022/crypto/Unpredictable/src.py
ctfs/Glacier/2022/crypto/Unpredictable/src.py
from Crypto.Util.number import bytes_to_long from secret import flag, roll_faster, a, b, m import random texts = open("txt.txt", "rb").readlines() def roll(x, y): for _ in range(y): x = (a*x + b) % m return x print("Im not evil, have some paramteres") print(f"{a = }") print(f"{b = }") print(f"{m = }") seeds = [] cts = [] for pt in texts: x = random.getrandbits(512) y = random.getrandbits(512) # r = roll(x,y) # This is taking too long r = roll_faster(x,y) seeds.append(max(x,y)) cts.append(r ^ bytes_to_long(pt)) print(f"{seeds = }") print(f"{cts = }") flag_ct = bytes_to_long(flag) ^ roll_faster(random.getrandbits(512), random.getrandbits(512)) print(f"{flag_ct = }")
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/Glacier/2022/web/GlacierTopNews/challenge/setup.py
ctfs/Glacier/2022/web/GlacierTopNews/challenge/setup.py
from setuptools import setup setup()
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/Glacier/2022/web/GlacierTopNews/challenge/glacier_webserver/api.py
ctfs/Glacier/2022/web/GlacierTopNews/challenge/glacier_webserver/api.py
import multiprocessing import os import platform from urllib import urlopen import psutil from flask import request from glacier_webserver.config import app from glacier_webserver.utils import Filter from glacier_webserver.utils import require_jwt def get_system_info(): _, _, load15 = psutil.getloadavg() cpu_usage = (load15/multiprocessing.cpu_count()) * 100 env_var = { key: os.environ[key] for key in os.environ if "PORT" not in key and "HOST" not in key and "KEY" not in key } return { 'environment': env_var, 'machine': platform.machine(), 'version': platform.version(), 'platform': platform.platform(), 'system': platform.system(), 'cpu_usage': cpu_usage, 'ram_usage': psutil.virtual_memory().percent, } @app.route('/api/system_info', methods=['POST']) @require_jwt def get_system_information(): return get_system_info(), 200, {'Content-Type': 'application/json'} @app.route('/api/get_resource', methods=['POST']) def get_resource(): url = request.json['url'] if(Filter.isBadUrl(url)): return 'Illegal Url Scheme provided', 500 content = urlopen(url) return content.read(), 200
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/Glacier/2022/web/GlacierTopNews/challenge/glacier_webserver/_main.py
ctfs/Glacier/2022/web/GlacierTopNews/challenge/glacier_webserver/_main.py
import logging import os import random import sqlite3 import string import glacier_webserver.api import glacier_webserver.config import glacier_webserver.routes import glacier_webserver.utils import jwt from glacier_webserver.config import app from glacier_webserver.utils import Database def prepair_environment(): secret = ''.join( random.choice( string.ascii_uppercase + string.digits ) for _ in range(30) ) admin_jwt = jwt.encode( { "name": "admin", "is_admin": True }, secret, algorithm="HS256" ) logging.info(admin_jwt) Database().setup_database(admin_jwt) def main(): app.before_first_request(prepair_environment) app.run(host='0.0.0.0', port='8080') return 0 if __name__ == '__main__': logging.basicConfig(level=logging.DEBUG) raise SystemExit(main())
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/Glacier/2022/web/GlacierTopNews/challenge/glacier_webserver/utils.py
ctfs/Glacier/2022/web/GlacierTopNews/challenge/glacier_webserver/utils.py
import sqlite3 from functools import wraps import os import flask from flask import redirect from flask import render_template from flask import request from glacier_webserver.config import app class Filter: BAD_URL_SCHEMES = ['file', 'ftp', 'local_file'] BAD_HOSTNAMES = ["google", "twitter", "githubusercontent", "microsoft"] @staticmethod def isBadUrl(url): return Filter.bad_schema(url) @staticmethod def bad_schema(url): scheme = url.split(':')[0] return scheme.lower() in Filter.BAD_URL_SCHEMES @staticmethod def bad_urls(url): for hostname in Filter.BAD_HOSTNAMES: if hostname in url: return True return False def singleton(cls): instances = {} def getinstance(): if cls not in instances: instances[cls] = cls() return instances[cls] return getinstance @singleton class Database: __instance = None def __init__(self, database_name="/tmp/glacier.db"): self.connection = sqlite3.connect(database_name) self.cursor = self.connection.cursor() def setup_database(self, admin_jwt): self.cursor.execute( "DROP TABLE IF EXISTS secrets" ) self.cursor.execute( "CREATE TABLE IF NOT EXISTS secrets (jwt_secret text PRIMARY KEY)" ) if not self.load_secret(): self.cursor.execute( "INSERT INTO secrets VALUES (?)", (admin_jwt,) ) self.connection.commit() self.token = self.load_secret()[0][0] def load_secret(self): secret = self.cursor.execute( "select jwt_secret from secrets limit 1;" ).fetchall() return secret def get_admin_token(self): return self.token def require_jwt(func): @wraps(func) def decorator(*args, **kwargs): token = None if "token" in request.cookies: token = request.cookies["token"] else: return app.make_response(redirect("/")) if token == Database().get_admin_token(): return func(*args, **kwargs) else: return app.make_response(redirect("/")) return decorator def render_template_with_wrapper(template_path, page): if not os.path.isfile("%(root_path)s/templates/%(tmp_path)s%(page)s.html" % { "root_path": app.root_path, "tmp_path": template_path, "page": page } ): return render_template('error/404.html'), 404 return render_template( template_path + '/template.html', content=render_template( "%(template_path)s%(page)s.html" % { "template_path": template_path, "page": page } ), js_file="/static/js/%(template_path)s%(page)s.js" % { "template_path": template_path, "page": page } )
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/Glacier/2022/web/GlacierTopNews/challenge/glacier_webserver/config.py
ctfs/Glacier/2022/web/GlacierTopNews/challenge/glacier_webserver/config.py
from flask import Flask app = Flask(__name__) # app.config['EXPLAIN_TEMPLATE_LOADING'] = True
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/Glacier/2022/web/GlacierTopNews/challenge/glacier_webserver/__init__.py
ctfs/Glacier/2022/web/GlacierTopNews/challenge/glacier_webserver/__init__.py
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/Glacier/2022/web/GlacierTopNews/challenge/glacier_webserver/routes.py
ctfs/Glacier/2022/web/GlacierTopNews/challenge/glacier_webserver/routes.py
import os import flask from flask.templating import TemplateNotFound from config import app from flask import render_template from flask import send_from_directory from glacier_webserver.utils import render_template_with_wrapper from glacier_webserver.utils import require_jwt @app.errorhandler(404) @app.errorhandler(TemplateNotFound) def render_error(error): return render_template('error/404.html'), 404 @app.route('/session/logout') def sessionLogout(): return flask.redirect('/', code=302) @app.route('/', defaults={'path': ''}) @app.route('/<path:path>') def render_index(path): page = path if page == '': page = '/index' return render_template_with_wrapper('page', page) @app.route('/admin', defaults={'path': ''}) @app.route('/<path:path>') @require_jwt def render_admin(path): page = path if page == '': page = '/index' return render_template_with_wrapper('admin', page) @app.route('/favicon.ico') def favicon(): return send_from_directory( os.path.join( app.root_path, 'static' ), 'favicon.ico', mimetype='image/vnd.microsoft.icon' )
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/Junior.Crypt/2024/misc/From_4_to_7/Hamming.py
ctfs/Junior.Crypt/2024/misc/From_4_to_7/Hamming.py
import numpy as np from random import randint from secret import FLAG mess = FLAG mess = mess.encode().hex() inp = [bin(int(h,16))[2:].zfill(4) for h in mess] inp = [[int(b) for b in c] for c in inp] imatr = np.array(inp) print (imatr) Gen = np.array([[0,1,1,1,0,0,0], [1,0,1,0,1,0,0], [1,1,0,0,0,1,0], [1,1,1,0,0,0,1]]) code = np.mod(np.dot(imatr, Gen), 2) scode = "".join(["".join([str(x) for x in c]) for c in code]) print ("".join([hex(int(scode[i:i+8],2))[2:].zfill(2) for i in range(0, len(scode),8)])) for i in range(0, code.shape[0]): ind = randint(0, 2 * code.shape[1]) if ind < code.shape[1]: code[i, ind] = code[i, ind] ^ 1 ecode = "".join(["".join([str(x) for x in c]) for c in code]) print (len(ecode), ecode) print ("".join([hex(int(ecode[i:i+8],2))[2:].zfill(2) for i in range(0, len(ecode),8)]))
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/Junior.Crypt/2024/steg/Stego_in_code/StegoInCode.py
ctfs/Junior.Crypt/2024/steg/Stego_in_code/StegoInCode.py
#============================================================================# #============================ARCANE CALCULATOR===============================# #============================================================================# import hashlib from cryptography.fernet import Fernet import base64 # GLOBALS --v arcane_loop_trial = True jump_into_full = False full_version_code = "" username_trial = "ANDERSON" bUsername_trial = b"ANDERSON" key_part_static1_trial = "picoCTF{1n_7h3_|<3y_of_" key_part_dynamic1_trial = "xxxxxxxx" key_part_static2_trial = "}" key_full_template_trial = key_part_static1_trial + key_part_dynamic1_trial + key_part_static2_trial star_db_trial = { "Alpha Centauri": 4.38, "Barnard's Star": 5.95, "Luhman 16": 6.57, "WISE 0855-0714": 7.17, "Wolf 359": 7.78, "Lalande 21185": 8.29, "UV Ceti": 8.58, "Sirius": 8.59, "Ross 154": 9.69, "Yin Sector CL-Y d127": 9.86, "Duamta": 9.88, "Ross 248": 10.37, "WISE 1506+7027": 10.52, "Epsilon Eridani": 10.52, "Lacaille 9352": 10.69, "Ross 128": 10.94, "EZ Aquarii": 11.10, "61 Cygni": 11.37, "Procyon": 11.41, "Struve 2398": 11.64, "Groombridge 34": 11.73, "Epsilon Indi": 11.80, "SPF-LF 1": 11.82, "Tau Ceti": 11.94, "YZ Ceti": 12.07, "WISE 0350-5658": 12.09, "Luyten's Star": 12.39, "Teegarden's Star": 12.43, "Kapteyn's Star": 12.76, "Talta": 12.83, "Lacaille 8760": 12.88 } def intro_trial(): print("\n===============================================\n\ Welcome to the Arcane Calculator, " + username_trial + "!\n") print("This is the trial version of Arcane Calculator.") print("The full version may be purchased in person near\n\ the galactic center of the Milky Way galaxy. \n\ Available while supplies last!\n\ =====================================================\n\n") def menu_trial(): print("___Arcane Calculator___\n\n\ Menu:\n\ (a) Estimate Astral Projection Mana Burn\n\ (b) [LOCKED] Estimate Astral Slingshot Approach Vector\n\ (c) Enter License Key\n\ (d) Exit Arcane Calculator") choice = input("What would you like to do, "+ username_trial +" (a/b/c/d)? ") if not validate_choice(choice): print("\n\nInvalid choice!\n\n") return if choice == "a": estimate_burn() elif choice == "b": locked_estimate_vector() elif choice == "c": enter_license() elif choice == "d": global arcane_loop_trial arcane_loop_trial = False print("Bye!") else: print("That choice is not valid. Please enter a single, valid \ lowercase letter choice (a/b/c/d).") def validate_choice(menu_choice): if menu_choice == "a" or \ menu_choice == "b" or \ menu_choice == "c" or \ menu_choice == "d": return True else: return False def estimate_burn(): print("\n\nSOL is detected as your nearest star.") target_system = input("To which system do you want to travel? ") if target_system in star_db_trial: ly = star_db_trial[target_system] mana_cost_low = ly**2 mana_cost_high = ly**3 print("\n"+ target_system +" will cost between "+ str(mana_cost_low) \ +" and "+ str(mana_cost_high) +" stone(s) to project to\n\n") else: # TODO : could add option to list known stars print("\nStar not found.\n\n") def locked_estimate_vector(): print("\n\nYou must buy the full version of this software to use this \ feature!\n\n") def enter_license(): user_key = input("\nEnter your license key: ") user_key = user_key.strip() global bUsername_trial if check_key(user_key, bUsername_trial): decrypt_full_version(user_key) else: print("\nKey is NOT VALID. Check your data entry.\n\n") def check_key(key, username_trial): global key_full_template_trial if len(key) != len(key_full_template_trial): return False else: # Check static base key part --v i = 0 for c in key_part_static1_trial: if key[i] != c: return False i += 1 # TODO : test performance on toolbox container # Check dynamic part --v if key[i] != hashlib.sha256(username_trial).hexdigest()[4]: return False else: i += 1 if key[i] != hashlib.sha256(username_trial).hexdigest()[5]: return False else: i += 1 if key[i] != hashlib.sha256(username_trial).hexdigest()[3]: return False else: i += 1 if key[i] != hashlib.sha256(username_trial).hexdigest()[6]: return False else: i += 1 if key[i] != hashlib.sha256(username_trial).hexdigest()[2]: return False else: i += 1 if key[i] != hashlib.sha256(username_trial).hexdigest()[7]: return False else: i += 1 if key[i] != hashlib.sha256(username_trial).hexdigest()[1]: return False else: i += 1 if key[i] != hashlib.sha256(username_trial).hexdigest()[8]: return False return True def decrypt_full_version(key_str): key_base64 = base64.b64encode(key_str.encode()) f = Fernet(key_base64) try: with open("keygenme.py", "w") as fout: global full_version global full_version_code full_version_code = f.decrypt(full_version) fout.write(full_version_code.decode()) global arcane_loop_trial arcane_loop_trial = False global jump_into_full jump_into_full = True print("\nFull version written to 'keygenme.py'.\n\n"+ \ "Exiting trial version...") except FileExistsError: sys.stderr.write("Full version of keygenme NOT written to disk, "+ \ "ERROR: 'keygenme.py' file already exists.\n\n"+ \ "ADVICE: If this existing file is not valid, "+ \ "you may try deleting it and entering the "+ \ "license key again. Good luck") def ui_flow(): intro_trial() while arcane_loop_trial: menu_trial() # Encrypted blob of full version full_version = \ b""" gAAAAABgT_nvDJgvWszj2nOh_RPhV8_0f0opQeoixBZ1txFJDliTcsbh1IWf4oLPoi00xYvnToAbwc7_srVOqKAz58mJorl8tTZu5Ebx3XY2C4PZVObzoD8Gmj4JLq42bPFimD-aS1slgwYA2CpLiWxPjfhMo_XeTTWHq-aiuZFKdgOuko2UmFOz4Au2_E_nG9pgnEuM8s_46K_VZwchzYdEtpKR0X8rz7xOjZY0iPWo9R4TtvGKDIzjXgvtSkSnq5QF_ZsB5QQ7rVY2GbAhwd6FbtKr-toGc21MP-1pTaEsilOvXzBHPS15uyAOa2J2h_Ss4cc6f_934KOkQcyZUL4fMBznXVFYqBf62qkpy-WrF66l87TKJbaz_i07Ma9NkD4vAqV0hs6lzXVuVzXhDtSmh8WKyFKXFQZMbtvmumD6QdUAijlqWRIUYsvn_SL5NNLbx2dUd404_BTjBBv-eEpiVSeM84LCrobjsZ8EXennPLhv0ntofE_MVk-W-GqevWf3nnUz4KG2kUkLoNspiVq9cCa3JypMnQuW5hMbPXS7_ZkrUA_9xxB7eo91mf6U4OOHkm4r0WeOkLD4SvfJHvN8JQ-W9JQzDp7uBuPXY0tPxtkWI-NcaV-bEko1W4vR1jXUgn1vOhQQdvW76BBZ54f6zpjxT13KUl5ZW0HJViqXQdhdXgLVC8vV225Wp3ORPR8hVOQvVHHmwe3Oi6lG8dcFxoldUm1vBRj1EmaZbVxu5JRUnY9JZwN8NDMIFJi-j5cNF9j1GgbTelnw3FtMHfU78o4BM15p3RYKihPb758GiA7UlwRcufVzNzGAog70tjbZ1yxzuzapx_fzZWEL4koVWmWw0pHgoPIj3WwMmmHNP4aKrdXGIVUK2MmUvfLhD71nRZa9Fiz7t526uOsD63cC30dJl-nmG0s2zjfpZkPdZBYhNdNHNcYzVmL3xo3NIkY3VgfoFxs72eqZKUarLpShIoajCfPMg1Qtp7AlX48qXXp8qOWCsqIPByF8Rkkin8GRH6FoLzIbQa4RSJwmQJvJGlB3U_VFPSkvwHc1WqB2aBsAyo5u4WNkT8Az4tQqehxC5u5XtlN1f3rvC_RHDvRecixkVTJZC7n6jRxNscgeHiEvaAmtYxlTLROT7c-h5ahkczvqPgkzMXI46SwPsB3kcaDXKkKbXmK86N0VpxV813pLVx9pRGt_HWK_9GIwAlOcGyxd44X1Xf27mgn5blCSRdYzZ2YHytGVlE1dR_Iqp0o606mSJsRGUUqvPl0pm62eCDKYgK20TX3oLy0YsddI5tHzz4U5nD4bq8mYm2tvtZrAs42jno8Q8NEjzJTszdHvkNDzNafqiaL6uh3QXsZyGBGFW50IjqHi2x-I8zKeT-V-pMAdIXeyrdeMRilxcjzF2QhpM1-3eYU5rjm-Siyfeq271-pGmxd-X7qlXUcwRhHSkycmRRExmw_5BVGrnxkCPD8b77j-O-WFPyGrmISlUU74Xw2QD0sebKmsufEvfQLqgcrgVYS8C44UJ7YC2SaGu_SeI1-QpatPXs5z90TfuxMWv95rWjZLfznjmMUwxTud2NV3GI0EY3x4Jb48MX99PqPpyGtiCMlgrcJERCO5dzqRKL6HjWYr9nSehQGveSN2YL7415-u2-GoCB8yTtgYBw8whah4HKVSLTmQovW0oKaggWtxePgQ6wR6KEiya_7oSNCDyY0exSqR8rR8CinLOZ6DLuTisuget54vXuZth231fTktvgs0Ws_36hjwfOJl34oXH2u3gulIG-lJExfVl5F7EahkGEVL7BN42opk71Yg9SYsU4D5wusEQanUtfdK65rHix-WVPGRlUbII_6DkUAXzIPLboEPeD61VFnMl357QQFTy1AWzXrDcyVxpvq0neYYTzWvQCTD5bIh7Q6bCHvhuTvv6Y198X-KpBXk4v2f_Vw-0FjztR9iameTAMICQkr8VNU4kKVuEO1NqjhRWEdYfuPBtE3Wq76bS1kddfLqMn7BtxuZYyKneLsrkqWHmQptS6MawoMNIMlGsXPZh-Y5QqkwAYt2nXQX6o5xVycViHM5HYUln-_8LEYuF6G3z79vO5AWtk764mkGNDdauDZWMaJpjk44oyN1Crxii2cU89Lhv0HlVLfgL1RxCj4Fr_LH2MoLGXAJZY6MdtBJJsZwyghEaeTVdMRwTAs7x6SPcKu0GXje4wvBEkWK7eW5DfZkLsywD-96t9GHmfXr8CWq-oyotIxWyOQN1amK-LmBeYWT7vwYL2yG8B60PVVY7mSBtxll-ASvDXfAdxtJzjR01C0pugXAeIEmRDUvQpJQgKDemgCfWrXzMyuFcHTwTNBsB8LQ9BDZco4Hf2J1L4eKZ-g5-FKYO5qeXkxqWBQjHomQ7Bz5ZrkKZPPFJW_GWbDC2AhN9nnKOlYqYALY7MJBKk5m3rRdbEd4xbCf9mffs3326BdfgDPOSBwtxhreJyy7Xpg6XrjlZifWk-aONIVNcqv1EriLoAZH2NKMifTB464XOMWYLwUfxpeCXMx_l0oqzOzugtDvmSfVg-D7elgV_S_htW1Siie012OkFr-TF1FT4kybe1XJcZgtSq_ISivmkbxBQwtKEPv8Fpj_971NN1_f06-MdvEbFDbIItGh1J3TpgsATP4fIno6Ar98qB2oM00KABU6YDBPJJHLVn9hm5Dt5R9Y6xx0GaPnwaNmsFgRRYRKVSGknsPqpqtYI6RSuUh3k08lbizZGbAjbF5u9oBrYTQgpwTSkPUzXP_rvo5obx-hZrzWCxJqlqNcFcEGl663-8_NwIVNfGGcw1RQl8gsVBS45idRw_tD2Oe3cTyGvoB4EnlSZAICRcoz69K0ItP4oEFCOQRernrw8q0Mt2NQv3-LULOwgrui9YQlspmOKnAqFlo50Ic6bqyUGkrrJhbVFqMBlDA90dpeqmc-RFdyaRhgcF7RnMZz-e1Jvj9r5EfkJCceCzWJicBfmpMIGSnaW4yF38G9phyRfW0aQMdf7Oy-C39ctUryIsCkhGfhFmejgdd2D9dU4nMOYwwHc5ZScUQNNddvqfXOs71EcqTHSOuVlTyc8jtERi9yODDEArWikIJs_U7xJtU0PKUbk_LKGkE3HtWd-cUgVkAuDzxgax9GN2OsTsUbV1yRDTT6q85nvKI4yIEZXijDbIUIFgQazmyEbhmqJhDkV914NmeHSKtSUt2KMBiqdhhUEW7gfndneETMJdab9BHgOIJzRANxAHxHsWQQsXhDmhlhMrEotOjMKjFFbSyopLqHzviqDqqP5QTv3jJ5sUinx5am0PpTbf1YnpSRgE8V7hBRvzuxnYMPAWrCeCzATneDwXFCtJrQsHOIYNh-VkZiolMD4pbqc00mv6C8Wm-hvkcGUsKMCguBhcMjOviugK10ghfmXRVKIBmTrHxRcwaD5TZdCFgu37XlX0xT37IGFhkbv4xk3_UCeIszClOweHMHhX0qoc-vWhCvDYHG-JxhByEt9utfM5orkiy0iyChlIgByx5NBAGV1OlY_oSee3ZEpAmTvleB6HaURrl3aWAIrgs_SU2V3vfhq7qPe82qTCfYkB_pqQ76jWngOhh6bc-nfSEw2ZM6SQIJUsndsObphS_9JKHBE-DQFoVx5f0y-l4u2K6QwIsLnrbWbfDC8O7obRZs21mnYjcouk0EUsd7FK56YI_WzuMJrBTV_2sBU_5-l4HiJHxKF-OAk-JhWhm_k_lpJ-Q7ze7d4wZPdxS3t4mZ63cxIhJ4K_7dZmtZaubA2k1gvymHuN2aMURxBy4YQZIx01NEMIyzwKdQ3EDVoqRmgUqwRFWmoGTjgPdt7k6tdfK_jcizDB2cibvb0VvEOyk21g== """ # Enter main loop ui_flow() if jump_into_full: exec(full_version_code)
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/Junior.Crypt/2024/rev/Random_cipher/code_terror.py
ctfs/Junior.Crypt/2024/rev/Random_cipher/code_terror.py
from random import randint def encrypt(text): key = randint(1, 2 * len(text)) print (ord(text[0]), key) result = [] for c in text: result.append(ord(c) + (ord(c) % key)) key = key + 1 return result
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/Junior.Crypt/2024/rev/Mutated_Caesar/Caesare.py
ctfs/Junior.Crypt/2024/rev/Mutated_Caesar/Caesare.py
from random import randint from hashlib import md5 from secret import flag hash = md5(flag.encode()).hexdigest() n1, n2 = randint(0x20, 0x41), randint(0x7d, 0x7e) CN = {chr(i+n1): i for i in range(0, n2-n1+1)} NC = {i: chr(i+n1) for i in range(0, n2-n1+1)} N = len(CN.keys()) key = randint(0,N) cipher = "".join([NC[(CN[c] + key) % N] for c in flag]) print (f"cipher = {cipher}") print (f"md5 = {hash}")
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/Junior.Crypt/2024/crypto/Unrevealed_secret/one-time_pad.py
ctfs/Junior.Crypt/2024/crypto/Unrevealed_secret/one-time_pad.py
import random def generate_string(length): # This function generates a random string of the specified length byte_list = [(random.randint(0, 127) + 256)//2 for _ in range(length)] byte_string = bytes(byte_list) utf8_string = byte_string.decode('utf-8', errors='replace') return utf8_string def xor_cipher(message, key): # This function performs XOR encryption on the message and key message_nums = [ord(c) for c in message] key_nums = [ord(c) for c in key] cipher_nums = [m ^ k for m, k in zip(message_nums, key_nums)] return ''.join(chr(i) for i in cipher_nums) # Example usage flag = "grodno{fake_flag}" key = generate_string(len(flag)) print("key:", key) if len(flag) > len(key): raise ValueError("The key length must not be less than the message length") if len(flag) < len(key): key = key[:len(flag)] encrypted_flag = xor_cipher(flag, key) print("encrypted_flag:", encrypted_flag) with open("encrypted_flag.txt", 'w', encoding='utf-8') as file: file.write(encrypted_flag)
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/Junior.Crypt/2024/crypto/Reliable_key/fernet_key.py
ctfs/Junior.Crypt/2024/crypto/Reliable_key/fernet_key.py
from base64 import b64encode from cryptography.fernet import Fernet from secret import x, flag n = 10530501314829737874338613873650498171114627332307613994419407788634861562083322399274706728851613783038612832934799681466704648468659504306294557287010679135096281292788625947204689823009613513036059444686163400496389028820505101159995113086874613360194601737451882502875472664931315351364072755341368399195377949130121228649108591228187977254920299214792628781732900532259698502116761082272476623334888785154788317837909384199960439349800314143652331891640890986990081442823929959369055574955932654572516283586817801546821214759075673666346475255312894077467851773144287543918131651139625172681441644771681483415867906954570241819389649931420187947408311075782155539521801408594141153358308083234492591119888877906728792663689496877339346194975907031220809187224717496519534843016253146071119684925090310440001862035531789026756298635323588531920872173520328579668053465585616830876796919501915034046970063608400209751796795173922619 print (f"n={n}\n") g = pow(2, 1000, n) print (f"g={g}\n") h = pow(g, x, n) print (f"h={h}\n") bkey = b64encode(x.to_bytes(32, 'big')) f = Fernet(bkey) cipher = f.encrypt(flag.encode()) print (f"cipher={cipher}")
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/Junior.Crypt/2024/crypto/Electronic_voting/vote.py
ctfs/Junior.Crypt/2024/crypto/Electronic_voting/vote.py
# pip install lightphe from lightphe import LightPHE import pickle from random import randint # build a cryptosystem cs = LightPHE(algorithm_name = 'Paillier') with open(f'vote/cs.pickle', 'wb') as f: pickle.dump(cs, f, protocol=pickle.HIGHEST_PROTOCOL) N = 250 # number of voting participants k = 8 kand = 6 # number of candidates # define ciphers for i in range(N): kandid = randint(1,kand) vote = cs.encrypt(2**(k*(kandid-1))) with open(f'vote/vote.{i}.pickle', 'wb') as f: pickle.dump(vote, f, protocol=pickle.HIGHEST_PROTOCOL)
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/Junior.Crypt/2025/misc/ZKP_with_Hint/zkp9052.py
ctfs/Junior.Crypt/2025/misc/ZKP_with_Hint/zkp9052.py
# for Users #! /usr/bin/python3 -u from random import randint from Crypto.Util.number import getPrime # Конфигурация FLAG = 'CTF{zkp_basic_secret_123}' ROUNDS = 2 # Параметры протокола p = getPrime(512) # Простое число g = 2 # Генератор группы Zp* x = randint(1,p-2) # Секрет (g^x mod p = y) y = pow(g, x, p) # y n_leak = 464 def main(): print(f"\n=== Zero-Knowledge Proof: Prove You Know x ===") print(f"Параметры / Parameters: \np={p}, \ng={g}, \ny={y}\n") print(f"Докажите, что знаете x, такой что g^x ≡ y mod p\n") print(f"Всего раундов / Rounds: {ROUNDS}\n") err_flag = False for round_num in range(1, ROUNDS+1): print(f"=== Round {round_num} ===\n") # 1. Проверяющий генерирует r, отправляет C = g^r mod p. # Однако, в результате утечки, к Доказывающему приходит еще и 464 младших бита r r = randint(1, p-1) # Случайный nonce C = pow(g, r, p) leak = r % 2**n_leak # Утечка print(f"C = g^r mod p: {C}") print(f"Утечка / leak(r): {leak}") # 464 младших бита r # 2. Проверяющий генерирует и отправляет challenge e e = randint(1, 2**32) print(f"e = {e}") # 3. Доказывающий восстанавливает r и присылает s = (r + e*x) mod (p-1) print(f"Вычислите / Calculate s = (r + e*x) mod (p-1):") s = int(input().strip()) # 4. Верификация left = pow(g, s, p) right = (C * pow(y, e, p)) % p if left != right: print(f"\nОшибка верификации / Verification failed!") print (f"Правильный s / Correct s is: {(r + e * x) % (p-1)}") print (f"Рaунд не пройден / Round not passed\n") else: print("Рaунд пройден / Round passed\n\n") err_flag = True # Все раунды пройдены if err_flag: print(f"Success! Flag: {FLAG}") else: print ("Не беда. Решите следующий раз ... / No problem. Decide next time ...") if __name__ == "__main__": main()
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/Junior.Crypt/2025/misc/Broken_ZKP._I/zkp9050.py
ctfs/Junior.Crypt/2025/misc/Broken_ZKP._I/zkp9050.py
#! /usr/bin/python3 -u from random import randint from Crypto.Util.number import getPrime # Конфигурация FLAG = 'CTF{zkp_basic_secret_123}' ROUNDS = 5 # Параметры протокола p = getPrime(512) # Простое число g = 2 # Генератор x = randint(1,p-2) # Секрет (g^x mod p = y) y = pow(g, x, p) # y r = randint(1,p-1) C = pow(g, r, p) def verify(s, e): return pow(g, s, p) == (C * pow(y, e, p)) % p def main(): c_mist = 0 print(f"\n=== Zero-Knowledge Proof: Prove You Know x ===") print(f"Параметры / Parameters: p={p}, g={g}, y={y}, r={r}\n") print(f"Всего раундов / Rounds: {ROUNDS}\n") for round_num in range(1, ROUNDS+1): print(f"=== Round {round_num} ===\n") # 1. Проверяющий отправляет challenge e e = randint(1, pow(2,32)) print(f"Challenge e = {e}") # 2. Доказывающий отправляет s = (r + e*x) mod (p-1) print("Отправьте / Send s = (r + e*x) mod (p-1): ") s = int(input().strip()) # 3. Верификация #left = pow(g, s, p) #right = (C * pow(y, e, p)) % p if verify(s, e): #left != right: c_mist += 1 print(f"\nОшибка верификации / Verification failed!\n") print (f"s = {(r + e*x) % (p-1)}") if c_mist > 2: return print("Рaунд пройден / Round passed!\n\n") # Все раунды пройдены print ("Все раунды пройдены. Может все-таки знаете, чему равен x:") x_proof = int(input().strip()) if x == x_proof: print(f"Success! Flag: {FLAG}") else: print ("Вы ошились / You are mistake ...") 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/Junior.Crypt/2025/misc/ZKP_9+/zkp9049.py
ctfs/Junior.Crypt/2025/misc/ZKP_9+/zkp9049.py
from random import randint FLAG = 'REDACTED_FLAG' ROUNDS = 3 # Параметры протокола p = 23 # Простое число g = 5 # Генератор x = randint(1,p-2) # Секрет (g^x mod p = y) y = pow(g, x, p) # y def main(): print(f"\n=== Zero-Knowledge Proof: Prove You Know x ===") print(f"Параметры / Parameters: {p=}, {g=}, {y=}") print(f"Всего раундов / Rounds: {ROUNDS}\n") for round_num in range(1, ROUNDS+1): print(f"=== Round {round_num} ===\n") # 1. Доказывающий выбирает r и отправляет C = g^r mod p print("Выберите r и отправьте C = g^r mod p / Select r and send C = g^r mod p: ") C = int(input().strip()) # 2. Проверяющий отправляет challenge e e = randint(1, 100) print(f"Challenge e = {e}") # 3. Доказывающий отправляет s = r + e*x mod (p-1) print("Отправьте / Send s = r + e*x mod (p-1): ") s = int(input().strip()) # 4. Верификация left = pow(g, s, p) right = (C * pow(y, e, p)) % p if left != right: print(f"\nОшибка верификации / Verification failed!\n") return print("Рaунд пройден / Round passed!\n\n") # Все раунды пройдены print(f"Success! Flag: {FLAG}") if __name__ == "__main__": main()
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/Junior.Crypt/2025/misc/Homomorphic_Fraud/Paillier9054.py
ctfs/Junior.Crypt/2025/misc/Homomorphic_Fraud/Paillier9054.py
from Crypto.Util.number import getPrime, bytes_to_long import random # Генерация ключей Paillier def generate_keypair(bits=512): p = getPrime(bits) q = getPrime(bits) n = p * q g = n + 1 # Стандартный выбор для g в Paillier lambda_ = (p - 1) * (q - 1) mu = pow(lambda_, -1, n) return (n, g), (lambda_, mu) # Шифрование def encrypt(m, pub_key): n, g = pub_key r = random.randint(1, n - 1) c = (pow(g, m, n**2) * pow(r, n, n**2)) % n**2 return c # Дешифрование def decrypt(c, priv_key, pub_key): n, g = pub_key lambda_, mu = priv_key x = pow(c, lambda_, n**2) l = (x - 1) // n m = (l * mu) % n return m # Инициализация FLAG = "grodno{Redacted_Flag}" pub_key, priv_key = generate_keypair() balance = random.randint(0, 999999) # Начальный баланс enc_balance = encrypt(balance, pub_key) end_balance = encrypt(1000000, pub_key) print(f"[*] Public Key (n, g) = {pub_key}") print(f"[*] Encrypted Balance = {enc_balance}") # Обработчик "транзакций" def process_transaction(enc_amount): global enc_balance # Гомоморфное сложение: Enc(balance + amount) enc_balance = (enc_balance * enc_amount) % (pub_key[0] ** 2) return enc_balance # Пример работы сервера (имитация API) if __name__ == "__main__": print("\n[*] Server is running. Send your transactions as `Enc(amount)`.") while True: try: user_input = int(input(">> Enc(amount) = ")) new_enc_balance = process_transaction(user_input) print(f"[+] New Encrypted Balance = {new_enc_balance}") if decrypt(new_enc_balance, priv_key, pub_key) == decrypt(end_balance, priv_key, pub_key): print (f"Flag is: {FLAG}") break elif new_enc_balance > end_balance: print (f"Слишком много / Too many") break except: print("[!] Invalid input. Use integers.")
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/Junior.Crypt/2025/misc/Error_another_error_.../chall_9057.py
ctfs/Junior.Crypt/2025/misc/Error_another_error_.../chall_9057.py
from random import randint, shuffle from copy import copy def hamming_encode_7_4(data_bits): """Кодирование 4 бит данных в 7-битный код Хэмминга (7,4) Args: data_bits: str - строка из 4 бит (например, '1101') Returns: str: 7-битная закодированная строка """ if len(data_bits) != 4 or not all(bit in '01' for bit in data_bits): raise ValueError("Нужно 4 бита (например, '1101')") d1, d2, d3, d4 = map(int, data_bits) # Вычисляем контрольные биты (p1, p2, p3) p1 = d1 ^ d2 ^ d4 p2 = d1 ^ d3 ^ d4 p3 = d2 ^ d3 ^ d4 # Собираем закодированное сообщение (позиции 1-7) encoded = [p1, p2, d1, p3, d2, d3, d4] return ''.join(map(str, encoded)) hcode = [[(bin(i)[2:]).zfill(4), 0, (bin(i)[2:]).zfill(4)] for i in range(0,15)] + [[(bin(i)[2:]).zfill(4), 0, (bin(i)[2:]).zfill(4)] for i in range(0,15)] shuffle(hcode) for ind in range(0, len(hcode)): r = randint(0,10) hcode[ind][1] = r if r <= 6 else 0 code0 = hamming_encode_7_4(hcode[ind][0]) if r <= 6: code0 = code0[:r] + ('1' if code0[r] == '0' else '0') + code0[r+1:] hcode[ind][0] = copy(code0) FLAG = 'grodno{Redacted_FLAG}' err_flag = False ROUNDS = 3 print(f"\nВсего раундов / Rounds: {ROUNDS}\n") for round_num in range(0, ROUNDS): print(f"=== Round {round_num + 1} ===\n") answer = input(f"{hcode[round_num][0]} позиция:данные >>") if answer == f"{hcode[round_num][1]}:{hcode[round_num][2]}": print(f"Правильно / Right") else: print(f"Ошибка. Правильный ответ / Error. Good answer: {hcode[round_num][1]}:{hcode[round_num][2]}") err_flag = True break if not err_flag: print(f"\nFlag is: {FLAG}")
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/Junior.Crypt/2025/misc/Homomorphic_weak/chall_9055.py
ctfs/Junior.Crypt/2025/misc/Homomorphic_weak/chall_9055.py
from Crypto.Util.number import getPrime, isPrime, bytes_to_long import random from math import gcd def generate_keys(bit_length=512, max_diff=10000): """Генерирует параметры криптосистемы""" while True: p = getPrime(bit_length // 2) q = p + random.randint(1, max_diff) if isPrime(q) and gcd(p*q, (p-1)*(q-1)) == 1: # Проверяем, что q тоже простое n = p * q g = n + 1 # Стандартный выбор g return (n, g) def encrypt(m, n, g): """Шифрование сообщения m """ r = random.randint(1, n - 1) # Случайное r c = (pow(g, m, n**2) * pow(r, n, n**2)) % n**2 return c # Создаем флаг flag = b"CTF{Redacted_FLAG}" m = bytes_to_long(flag) # Создаем ключи public_key = generate_keys() n, g = public_key # Шифруем флаг c = encrypt(m, n, g) # Выводим данные для участников CTF print("Public Key (n, g):") print(f"n = {n}") print(f"g = {g}\n") print("Encrypted Flag (c):") print(f"c = {c}\n") ========================= Public Key (n, g): n = 8242620732262909867878113281012018732278863945420526557791199254408257645474897397593577196677011122595919740541591920781506102495280619868063408571075243 g = 8242620732262909867878113281012018732278863945420526557791199254408257645474897397593577196677011122595919740541591920781506102495280619868063408571075244 Encrypted Flag (c): c = 20530188269857033227552501374512492063210340036515162066082507507361374259664195970635336752542990474419048162794543137690229029552303482501325914475518269059105250902383881689172038649928553356614692672188510858274714501424154824636569505416997036242381758585152998128009272173679378880154204715815820964451
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/Junior.Crypt/2025/rev/Dynamic_Key/chall_dynamic_key.py
ctfs/Junior.Crypt/2025/rev/Dynamic_Key/chall_dynamic_key.py
import time def dynamic_key(): return ((int(time.time()) % 256) ^ 0xFF) & 0x7F def encrypt(s, key): return bytes([(c + key) ^ (i * 2) for i, c in enumerate(s.encode())]) def check_flag(flag: str) -> bool: if not flag.startswith("grodno{") or not flag.endswith("}"): return False middle = flag[7:-1] key = dynamic_key() encrypted = encrypt(middle, key) expected = b'\x74\xab\x9a\x62\x95\x6b\x9f\x81\x6b\x87\xbd\x99\x81\xb9\x93\x98\xb5\x80\x8d\xa9\x5b\x4a\xb1\x8e\xac\xa7\x9c\xb9\xa9\xa4\xa8\xb1\x39\xdc\xd7\x26\xd5\xea\xee\xdb\xc8\xc7\xca\xf5\x39\xc8\xc0\xcb' return encrypted == expected flag = input("Enter flag: ") print("Correct!" if check_flag(flag) else "Wrong!")
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/Junior.Crypt/2025/rev/Turing_Award/chall_Turing_Award.py
ctfs/Junior.Crypt/2025/rev/Turing_Award/chall_Turing_Award.py
def check_flag(flag): enc = [0x6e, 0x49, 0x60, 0x9, 0x78, 0x75, 0x1, 0x3f, 0x58, 0x68, 0x4f] key = b"MYSECRETKEY" if not flag.startswith("grodno{") or not flag.endswith("}") or len(flag) != 30: return False middle = flag[7:-1] for i in range(11): if (ord(middle[i*2]) ^ ord(middle[i*2+1])) != enc[i] ^ key[i]: return False return True flag = input("Enter flag: ") if check_flag(flag): print("Correct!") 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/Junior.Crypt/2025/rev/Hybrid_Encryption/chall_hibrid_enc.py
ctfs/Junior.Crypt/2025/rev/Hybrid_Encryption/chall_hibrid_enc.py
import base64 def encrypt(flag: str) -> str: if not flag.startswith("grodno{") or not flag.endswith("}"): return "" encoded = bytes([ord(c) ^ 0xAA for c in flag[7:-1]]) return base64.b64encode(encoded).decode() def check_flag(flag: str) -> bool: return encrypt(flag) == "np2Z3p2c3s6YmZ3ezs2ZmM/Tnc7NmJmdz5yYm96cz8+Ym53Z3w==" flag = input("Enter flag: ") print("Correct!" if check_flag(flag) else "Wrong!")
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/Junior.Crypt/2025/rev/Reverse_Puzzle/chall_rev_puzzle.py
ctfs/Junior.Crypt/2025/rev/Reverse_Puzzle/chall_rev_puzzle.py
def puzzle(s: str, step: int) -> str: return s if step == 0 else puzzle(s[::2] + s[1::2], step - 1) def check_flag(flag: str) -> bool: return False if not flag.startswith("grodno{") or not flag.endswith("}") else puzzle(flag[7:-1], 5) == '789603251257384214725442633' flag = input("Enter flag: ") print("Correct!" if check_flag(flag) else "Wrong!")
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/Junior.Crypt/2025/ppc/Randomized_Flag/server_9047.py
ctfs/Junior.Crypt/2025/ppc/Randomized_Flag/server_9047.py
from random import getrandbits with open("flag.txt","rb") as f: flag = f.read() for i in range(2**64): print(getrandbits(32) + flag[getrandbits(32) % len(flag)]) a = input() # 1 - I known flag, else - next number if a == '1': ans = input('Flag is: ') if ans == flag.decode(): print (f"Your flag: {flag}") break
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/Junior.Crypt/2025/ppc/100_percent_Robust_PRNG/server_9046.py
ctfs/Junior.Crypt/2025/ppc/100_percent_Robust_PRNG/server_9046.py
import time import random import math flag = "FAKE_FLAG" m = random.getrandbits(31) a = 2**10 b = 2**30 rand_numbers = [] d = """ Попробуем взломать генератор псевдослучайных чисел (ПСЧ) Python. Считаем, что ПСЧ создаются функцией getrandbits(31) стандартной библиотеки random. Вы можете попросить несколько последовательных ПСЧ, до 1000 штук. А затем вы должны угадать следующее ПСЧ.""" print (f"{d}\n\n") print ('1. Получить следующее число') print ('2. Угадать следующее число') ind = 0 while True: if ind == 1000: print ('Слишком долго думаешь. Отдохни ...') break inp = input('> ') if inp == '1': print (f"Следующее число: {random.getrandbits(31)}") elif inp == '2': ans = int(input('Ваше число: ')) my_ans = random.getrandbits(31) if ans == my_ans: print (f"\nФлаг: {flag}") else: print (f"\nОшибка. Мое число: {my_ans}") break ind += 1
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/Junior.Crypt/2025/ppc/LCG_hack/server_9042.py
ctfs/Junior.Crypt/2025/ppc/LCG_hack/server_9042.py
import math import time flag = "FAKE_FLAG" m=math.ceil(time.time()*1000000) a=2**15-1 b=2**51-1 x = m rand_numbers = [x,] for i in range(1,50): x = (a*x + b) % m rand_numbers.append(x) d = """ Попробуем взломать Линейный Конгруэнтный Генератор псевдослучайных чисел (ПСЧ). Его формула: Xn+1 = (A * Xn + B) mod M Вы можете попросить несколько последовательных ПСЧ, до 50 штук. А затем угадать следующее ПСЧ.""" print (f"{d}\n\n") print ('1. Получить следующее число') print ('2. Угадать следующее число') ind = 0 while True: if ind == len(rand_numbers): print ('Слишком долго думаешь. Отдохни ...') break inp = input('> ') if inp == '1': print (f"Следующее число: {rand_numbers[ind]}") elif inp == '2': ans = int(input('Ваше число: ')) if ans == rand_numbers[ind]: print (f"\nФлаг: {flag}") else: print (f"\nОшибка. Мое число: {rand_numbers[ind]}") break ind += 1
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/Junior.Crypt/2025/ppc/Robust_PRNG_in_Python/server_9045.py
ctfs/Junior.Crypt/2025/ppc/Robust_PRNG_in_Python/server_9045.py
import time import random import math flag = "FAKE_FLAG" m=math.ceil(time.time()*1000000) a = 2**10 b = 2**30 random.seed(m) rand_numbers = [] d = """ Попробуем взломать генератор псевдослучайных чисел (ПСЧ) Python. Считаем, что ПСЧ создаются функцией getrandbits(31) стандартной библиотеки random. Вы можете попросить несколько последовательных ПСЧ, до 1000 штук. А затем вы должны угадать следующее ПСЧ.""" print (f"{d}\n\n") print ('1. Получить следующее число') print ('2. Угадать следующее число') ind = 0 while True: if ind == 1000: print ('Слишком долго думаешь. Отдохни ...') break inp = input('> ') if inp == '1': print (f"Следующее число: {random.getrandbits(31)}") elif inp == '2': ans = int(input('Ваше число: ')) my_ans = random.getrandbits(31) if ans == my_ans: print (f"\nФлаг: {flag}") else: print (f"\nОшибка. Мое число: {my_ans}") break ind += 1
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/Junior.Crypt/2025/ppc/Python_PRNG_hack/server_9043.py
ctfs/Junior.Crypt/2025/ppc/Python_PRNG_hack/server_9043.py
import time import random import math flag = "FAKE_FLAG" m=math.ceil(time.time()*1000000) a = 2**10 b = 2**30 random.seed(m) rand_numbers = [] d = """ Попробуем взломать генератор псевдослучайных чисел (ПСЧ) Python. Считаем, что ПСЧ создаются функцией randint стандартной библиотеки random. Вы можете попросить несколько последовательных ПСЧ, до 1000 штук. А затем вы должны угадать следующее ПСЧ.""" print (f"{d}\n\n") print ('1. Получить следующее число') print ('2. Угадать следующее число') ind = 0 while True: if ind == 1000: print ('Слишком долго думаешь. Отдохни ...') break inp = input('> ') if inp == '1': print (f"Следующее число: {random.getrandbits(32)}") elif inp == '2': ans = int(input('Ваше число: ')) my_ans = random.getrandbits(32) if ans == my_ans: print (f"\nФлаг: {flag}") else: print (f"\nОшибка. Мое число: {my_ans}") break ind += 1
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/Junior.Crypt/2025/crypto/OTP_with_shift_register/OTP_LFSR.py
ctfs/Junior.Crypt/2025/crypto/OTP_with_shift_register/OTP_LFSR.py
# Key generation def lfsr(state, mask): #Генерация нового бита и обновление состояния LFSR bit = (state & 1) # Младший бит (стандартный для right-shift LFSR) state = state >> 1 # Сдвиг вправо if bit: state ^= mask # Применяем маску обратной связи return state, bit # Известные параметры initial_state = 0b1100101011110001 # 16-битное начальное состояние mask = 0b1011010000000001 # 16-битная маска обратной связи. Примитивный полином
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/Junior.Crypt/2025/crypto/Grey_Box_Hacking/chall_9058.py
ctfs/Junior.Crypt/2025/crypto/Grey_Box_Hacking/chall_9058.py
def lfsr(state, mask): # Generating a new bit and updating the state LFSR feedback = (state & 1) # Least bit (standard for right-shift LFSR) state = state >> 1 # Right shift if feedback: state ^= mask # Using a feedback mask return state, feedback initial_state = 0x???? # 16-bit initial state mask = 0x???? # 16-bit feedback mask b64_Enc_XOR_text = "rKcUtOpHHO6ZXNzB3IwyLXPzQX9pkAYLNfrolB191POUEJoz3xQANLSTm1inSV3jh88w15d5jcaQttzpNyewT7mPufbvtVf+xMTS7Zeeai4u6/TyeFHGLPH9cHnCNg==" """ def lfsr(state, mask): # state: the current state of the LFSR, represented as an integer. # For example, for a 4-bit LFSR, if the state is [1,0,0,0], then state = 8 (or 0b1000). # mask: a feedback mask that determines which bits participate in the XOR. # Each set bit in the mask corresponds to a "tap" in the LFSR. # For example, for a polynomial x^4 + x^3 + 1, the mask could be 0b1100 (for 4-bit) # or 0b1001 (for 4-bit, if 1 is x^0 and 4 is x^3) feedback = (state & 1) # This is the key. In this style of implementation (a Galois LFSR with right shifting), # the output bit (the one used for feedback, and often the # output of the entire LFSR) is the **least significant bit** (LSB) of the current state. # The `& 1` operation effectively extracts this least significant bit. state = state >> 1 # Right shift # All bits in the register are shifted one place to the right. The least significant bit that we # just saved in `feedback` is dropped. if feedback: state ^= mask # Using a feedback mask # This is the heart of the Galois LFSR. If the `feedback` bit (i.e. the least significant bit before the shift) is 1, # then the **new state** is XORed with the mask. This creates the effect that the # "taps" (defined by the mask) are changed. If the `feedback` bit is 0, # then no change (XOR with 0) occurs. return state, feedback # The function returns the new state of the LFSR and the bit that was "thrown out" (output_bit / feedback_bit). """
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/Junior.Crypt/2025/crypto/Signature_ECDSA/chall_ECDSA.py
ctfs/Junior.Crypt/2025/crypto/Signature_ECDSA/chall_ECDSA.py
from ecdsa import SECP256k1 import hashlib from random import randint from mySecret import d # d in range(1,n) - my Private Key # ============================================= # 0. Elliptic Curve SECP256k1 Parameters # ============================================= curve = SECP256k1 G = curve.generator # Base Point n = curve.order # Subgroup Order # ============================================= # 1. Generating Keys and Messages # ============================================= Q = d * G # my Public Key m1 = b"Hello, world!" m2 = b"Goodbye, world!" h1 = int(hashlib.sha256(m1).hexdigest(), 16) % n h2 = int(hashlib.sha256(m2).hexdigest(), 16) % n # ============================================= # 2. Generating signatures # ============================================= k = randint(1, n - 1) R = k * G r = R.x() % n # Signature for m1 s1 = (pow(k, -1, n) * (h1 + r * d)) % n # Signature for m2 s2 = (pow(k, -1, n) * (h2 + r * d)) % n print(f"\n[Signature 1]\nr1 = {hex(r)}\ns1 = {hex(s1)}\nh1 = {hex(h1)}\n") print(f"[Signature 2]\nr2 = {hex(r)}\ns2 = {hex(s2)}\nh2 = {hex(h2)}") ==== [Signature 1] r1 = 0xe37ce11f44951a60da61977e3aadb42c5705d31363d42b5988a8b0141cb2f50d s1 = 0xdf88df0b8b3cc27eedddc4f3a1ecfb55e63c94739e003c1a56397ba261ba381d h1 = 0x315f5bdb76d078c43b8ac0064e4a0164612b1fce77c869345bfc94c75894edd3 [Signature 2] r2 = 0xe37ce11f44951a60da61977e3aadb42c5705d31363d42b5988a8b0141cb2f50d s2 = 0x2291d4ab9e8b0c412d74fb4918f57580b5165f8732fd278e65c802ff8be86f61 h2 = 0xa6ab91893bbd50903679eb6f0d5364dba7ec12cd3ccc6b06dfb04c044e43d300
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/Junior.Crypt/2025/crypto/Very_Obfuscated_Crypto/Obfuscated.py
ctfs/Junior.Crypt/2025/crypto/Very_Obfuscated_Crypto/Obfuscated.py
import numpy as _ __ = 257 ___ = 3 def ____(_____, ______): _______ = int(round(_.linalg.det(_____))) % ______; ________ = pow(_______, -1, ______); _________ = _.round(_______ * _.linalg.inv(_____)).astype(int) ;__________ = (________ * _________) % ______; return __________.astype(int) def ___________(____________: bytes, _____________: int) -> bytes: ______________ = (_____________ - len(____________) % _____________) % _____________; return ____________ + bytes([0] * ______________) def _______________(_________________: bytes, __________________: _.ndarray) -> _.ndarray: _________________ = ___________(_________________, __________________.shape[0]);____________________ = _.frombuffer(_________________, dtype=_.uint8).reshape(-1, __________________.shape[0]);return (____________________ @ __________________.T) % __ if __name__ == "__main__": flag = b"VERYSECRETFLAG" while True: A = _.random.randint(1, __, (___, ___)) try: ______________________ = ____(A, __);break except: continue encrypted = _______________(flag, A) print("A:\n " + repr(A.tolist()) + " \nencrypted:\n" + repr(encrypted.tolist()))
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/Junior.Crypt/2025/crypto/Bitflip_RSA/BitflipRSA.py
ctfs/Junior.Crypt/2025/crypto/Bitflip_RSA/BitflipRSA.py
from Crypto.Util.number import getPrime, bytes_to_long flag = "grodno{REDACTED}" p = getPrime(1024) q = getPrime(1024) n = p * q e = 65537 c = pow(bytes_to_long(flag.encode()), e, n) xor = p ^ int(bin(q)[2:][::-1], 2) print(f"RSA module (n): {n}") print(f"Ciphertext (c): {c}") print(f"XOR: {xor}")
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/Junior.Crypt/2025/crypto/Amount_of_his_dreams/Homo_RSA.py
ctfs/Junior.Crypt/2025/crypto/Amount_of_his_dreams/Homo_RSA.py
from mySecret import leak, e, n # leak = {n1: sign1, n2: sign2, ... } print ("Private RSA-key, 1024 bits") print (f"n = {n}") print (f"e = {e}\n") # Vasily's Dream Sum s = 51999884711298256279139483764500625524555947558324683565293215223860861439365869245016556808946069376210234208051889905473428307099335266198556660549084421948376963868131939751733713217547145342061587754812000747394877170239958534615968079443224197703107182407137345808430083378360519257003496366898745432749 print (f"dream_sum = {s}") for x in leak.keys(): print (f"Sign({x}) = {leak[x]}\n") # leak[x] = pow(x, d, n)
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/ESCAPE/2023/Quals/crypto/Bunker_Escape/prob.py
ctfs/ESCAPE/2023/Quals/crypto/Bunker_Escape/prob.py
from Crypto.Util.number import bytes_to_long, long_to_bytes, getPrime from gmpy2 import invert class Cipher: def __init__(self): self.n = 108506951736793336490683880256855846248083684741694466461336182348417411176781023957825388818844036495751633876599810798436954790114984279939172259886462851438954959031979074506295441495658302003723943179142742062326225122087241430684094279948641138924448463919864585525265270367948313098530841624367001646231 self.e = 65537 def encrypt(self, msg): return pow(msg, self.e, self.n) ments = [ ?, ?, ?, ?, ?, ... ] RSA = Cipher() while True: for ment in ments: c = RSA.encrypt(bytes_to_long(ment)) print(c)
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/MetaRed/2021/crypto/Crypto_101/challenge.py
ctfs/MetaRed/2021/crypto/Crypto_101/challenge.py
from Crypto.Util.number import * from binascii import hexlify import gmpy from flag import FLAG flag = FLAG data = b'potatoespotatoespotatoes' BITS = 512 flag = int(flag.hex(), 16) data = int(data.hex(), 16) p = getStrongPrime(BITS) q = getStrongPrime(BITS) r = getStrongPrime(BITS) n1 = p * q n2 = q * r e = 65537 c1 = pow(flag, e, n1) c2 = pow(data, e, n2) print("n1=" + str(n1)) print("n2=" + str(n2)) print("e=" + str(e)) print("c1=" + str(c1)) print("c2=" + str(c2))
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/MetaRed/2021/crypto/dogogram/app/web/utils.py
ctfs/MetaRed/2021/crypto/dogogram/app/web/utils.py
from PIL import Image, ImageChops from hashlib import md5 from uuid import uuid4 import sqlite3 def compareJPG(file1, file2): img1 = Image.open(file1) img2 = Image.open(file2) equal_size = img1.height == img2.height and img1.width == img2.width equal_content = not ImageChops.difference( img1.convert("RGB"), img2.convert("RGB") ).getbbox() return equal_size and equal_content def whitelistAdd(fd): print('wla') con = sqlite3.connect("whitelist.db") cur = con.cursor() fd.stream.seek(0) fhash = md5(fd.read()).hexdigest() cur.execute("insert into whitelist (hash) values (?)", (fhash,)) con.commit() def isWhitelisted(fd): print('wl') con = sqlite3.connect("whitelist.db") cur = con.cursor() fd.stream.seek(0) fhash = md5(fd.read()).hexdigest() cur.execute("select * from whitelist where hash = ?", (fhash,)) row = cur.fetchone() if row is None: return False else: return True def saveFile(fd): fid = str(uuid4()) fd.stream.seek(0) fd.save("static/uploads/" + fid + ".jpg") return fid
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/MetaRed/2021/crypto/dogogram/app/web/server.py
ctfs/MetaRed/2021/crypto/dogogram/app/web/server.py
from flask import Flask, request, render_template, redirect, abort, url_for from hashlib import md5 from utils import * app = Flask(__name__) app.config['MAX_CONTENT_LENGTH'] = 1 * 1000 * 1000 @app.route("/") def index(): return render_template('index.html') @app.route('/upload', methods=['POST']) def upload_file(): if request.method == 'POST': try: fnew = request.files['file'] fbase = open("dog.jpg", "rb") # Check if file has been uploaded before if isWhitelisted(fnew): fid = saveFile(fnew) return redirect(url_for('view', fid = fid)) # New files are checked pixel by pixel if compareJPG(fnew, fbase): whitelistAdd(fnew) fid = saveFile(fnew) return redirect(url_for('view', fid = fid)) else: return abort(401) except: return abort(401) @app.route('/view/<uuid:fid>', methods=['GET']) def view(fid): try: f1 = open("cat.jpg", "rb") f2 = open("static/uploads/" + str(fid) + ".jpg", "rb") if compareJPG(f1,f2): flag = "FLAG{test_flag}" return render_template('fileview.html', fid = fid, flag = flag) else: return render_template('fileview.html', fid = fid) except: return abort(404) @app.errorhandler(401) def page_not_found(error): return render_template('dogsonly.html'), 401 @app.errorhandler(404) def page_not_found(error): return render_template('dogonotfound.html'), 404
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/MetaRed/2021/crypto/dogogram/app/web/wsgi.py
ctfs/MetaRed/2021/crypto/dogogram/app/web/wsgi.py
from server import app if __name__ == "__main__": app.run()
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/MetaRed/2021/web/Repeated_Lock/app.py
ctfs/MetaRed/2021/web/Repeated_Lock/app.py
from flask import Flask, render_template, render_template_string, request import os import utils app = Flask(__name__) app.config['SECRET_KEY'] = 'CTFUA{REDACTED}' @app.route('/', methods=['GET', 'POST']) def home(): return render_template('home.html') @app.route('/admin', methods=['GET', 'POST']) def admin(): return 'Under Construction...' @app.route('/users') def users(): username = request.args.get('user', '<User>') if utils.filter(username): return render_template_string('Hello ' + username + '!') else: return 'Hello ' + username + '!' if __name__ == '__main__': app.run(host='0.0.0.0', port=5000, debug=True)
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/MetaRed/2024/rev/This_will_make_you_ANGRy/script.py
ctfs/MetaRed/2024/rev/This_will_make_you_ANGRy/script.py
import angr import #Find the library that allows to create symbolic variables # Load the binary project = angr.Project('/paht/to/angry binary', auto_load_libs=False) # Length of the argument argument_length = #Complete with the length of the argument # Create a symbolic variable of size argument_length for argument, each character is 8 bits argument = #"library that allows to create symbolic variables".BVS('argument', 8 * argument_length) # Define the initial state with the symbolic argument # Add options to remove annoying warnings of angr initial_state = project.factory.entry_state(args=['./angry', argument], add_options ={ angr.options.SYMBOL_FILL_UNCONSTRAINED_MEMORY, angr.options.SYMBOL_FILL_UNCONSTRAINED_REGISTERS }) # Constrain each byte of the input to be a printable character for byte in argument.chop(8): initial_state.solver.add(byte >= X) # Replace X with the hex value of first printable character initial_state.solver.add(byte <= Y) # Replace Y with the hex value of last printable character # Define the success condition def is_successful(state): stdout_output = state. #Find the attribute that contains the output of the binary in Angr return b'X' in stdout_output #Replace X with the message that indicates success # Define the failure condition def should_abort(state): stdout_output = state. #Find the attribute that contains the output of the binary in Angr return b'Y!' in stdout_output #Replace Y with the message that indicates failure # Define the simulation manager simgr = project.factory.simulation_manager(initial_state) # Explore the binary looking for a solution print("Exploring...") simgr.explore(find=is_successful, avoid=should_abort) # Check if we found a solution if simgr.found: solution_state = simgr.found[0] solution = solution_state.Z(argument, cast_to=bytes) #Replace Z with the evaluation of a symbolic expression. print(f"Found the solution: {solution.decode()}") else: print("Could not find the solution.")
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/Paradigm/2023/misc/Hello_World/challenge.py
ctfs/Paradigm/2023/misc/Hello_World/challenge.py
from eth_launchers.pwn_launcher import PwnChallengeLauncher from eth_launchers.team_provider import get_team_provider PwnChallengeLauncher( project_location="project", provider=get_team_provider(), ).run()
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/Paradigm/2023/misc/Cosmic_Radiation/solve.py
ctfs/Paradigm/2023/misc/Cosmic_Radiation/solve.py
import yaml from eth_launchers.koth_solver import KothChallengeSolver from eth_launchers.solver import TicketedRemote from eth_launchers.utils import solve from web3 import Web3 class Solver(KothChallengeSolver): def launch_instance(self): with TicketedRemote() as r: r.recvuntil(b"?") r.send(b"1\n") r.recvuntil(b"?") r.send( b"0xae7ab96520DE3A18E5e111B5EaAb095312D7fE84:0:1:2:3:4:5:6:7,0x00000000219ab540356cbb839cbe05303d7705fa:0:1:2:3:4:5:6:7\n" ) try: r.recvuntil(b"---\n") except: log = r.recvall().decode("utf8") print(log) raise Exception("failed to create instance") data_raw = r.recvall().decode("utf8") return yaml.safe_load(data_raw) def _submit(self, rpcs, player, challenge): web3 = Web3(Web3.HTTPProvider(rpcs[0])) solve(web3, "project", player, challenge, "script/Solve.s.sol:Solve") Solver().start()
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/Paradigm/2023/misc/Cosmic_Radiation/challenge.py
ctfs/Paradigm/2023/misc/Cosmic_Radiation/challenge.py
from typing import List from web3 import Web3 from anvil_server.database import UserData from anvil_server.socket import ( CreateInstanceRequest, CreateInstanceResponse, UnixClient, UpdateMetadataRequest, ) from eth_launchers.koth_launcher import KothChallengeLauncher from eth_launchers.launcher import ETH_RPC_URL from eth_launchers.score_submitter import ScoreSubmitter, get_score_submitter from eth_launchers.team_provider import TeamProvider, get_team_provider from eth_launchers.utils import anvil_setBalance, anvil_setCode from foundry.anvil import LaunchAnvilInstanceArgs class Challenge(KothChallengeLauncher): def __init__( self, project_location: str, provider: TeamProvider, submitter: ScoreSubmitter ): super().__init__( project_location, provider, submitter, want_metadata=["bitflips"] ) def create_instance(self, client: UnixClient) -> CreateInstanceResponse: return client.create_instance( CreateInstanceRequest( id=self.team, instances={ "main": LaunchAnvilInstanceArgs( balance=1000, fork_url=ETH_RPC_URL, fork_block_num=18_437_825, ), }, ) ) def deploy(self, user_data: UserData) -> str: web3 = user_data.get_privileged_web3("main") bitflips = input("bitflips? ") corrupted_addrs = {} for bitflip in bitflips.split(","): (addr, *bits) = bitflip.split(":") addr = Web3.to_checksum_address(addr) bits = [int(v) for v in bits] if addr in corrupted_addrs: raise Exception("already corrupted this address") corrupted_addrs[addr] = True balance = web3.eth.get_balance(addr) if balance == 0: raise Exception("invalid target") code = bytearray(web3.eth.get_code(addr)) for bit in bits: byte_offset = bit // 8 bit_offset = 7 - bit % 8 if byte_offset < len(code): code[byte_offset] ^= 1 << bit_offset total_bits = len(code) * 8 corrupted_balance = int(balance * (total_bits - len(bits)) / total_bits) anvil_setBalance(web3, addr, hex(corrupted_balance)) anvil_setCode(web3, addr, "0x" + code.hex()) resp = UnixClient().update_metadata( UpdateMetadataRequest( id=self.team, metadata={ "bitflips": bitflips, }, ) ) if not resp.ok: raise Exception(resp.message) return super().deploy(user_data) Challenge( project_location="project", provider=get_team_provider(), submitter=get_score_submitter(), ).run()
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/Paradigm/2023/misc/Dropper/challenge.py
ctfs/Paradigm/2023/misc/Dropper/challenge.py
from anvil_server.database import UserData from anvil_server.socket import ( CreateInstanceRequest, CreateInstanceResponse, GetInstanceRequest, UnixClient, UpdateMetadataRequest, ) from eth_abi import abi from eth_launchers.koth_launcher import KothChallengeLauncher from eth_launchers.launcher import ETH_RPC_URL from eth_launchers.score_submitter import ScoreSubmitter, get_score_submitter from eth_launchers.team_provider import TeamProvider, get_team_provider from eth_launchers.utils import anvil_setBalance, anvil_setCode from foundry.anvil import LaunchAnvilInstanceArgs from web3 import Web3 class Challenge(KothChallengeLauncher): def __init__( self, project_location: str, provider: TeamProvider, submitter: ScoreSubmitter ): super().__init__(project_location, provider, submitter, want_metadata=["code"]) def submit_score(self) -> int: client = UnixClient() resp = client.get_instance(GetInstanceRequest(id=self.team)) if not resp.ok: print(resp.message) return 1 challenge_addr = resp.user_data.metadata["challenge_address"] web3 = resp.user_data.get_privileged_web3("main") (code,) = abi.decode( ["bytes"], web3.eth.call( { "to": Web3.to_checksum_address(challenge_addr), "data": Web3.keccak(text="bestImplementation()")[:4].hex(), } ), ) resp = client.update_metadata( UpdateMetadataRequest( id=self.team, metadata={ "code": code.hex(), }, ) ) if not resp.ok: print(resp.message) return 1 return super().submit_score() Challenge( project_location="project", provider=get_team_provider(), submitter=get_score_submitter(), ).run()
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/Paradigm/2023/misc/Free_Real_Estate/watcher.py
ctfs/Paradigm/2023/misc/Free_Real_Estate/watcher.py
import asyncio import json import random import sys import time from typing import List from anvil_server.database import UserData from anvil_server.socket import GetInstanceRequest, UnixClient, UpdateMetadataRequest from eth_abi import abi from eth_account.signers.local import LocalAccount from eth_launchers.daemon import Daemon from web3 import Web3 from web3.middleware.signing import construct_sign_and_send_raw_middleware class Watcher(Daemon): def __init__(self): super().__init__(required_properties=["challenge_address"]) def update_claimed(self, external_id: str, claimed: List[str]): client = UnixClient() data = client.get_instance( GetInstanceRequest( id=external_id, ) ) if not data.ok: raise Exception("failed to get instance", data.message) resp = client.update_metadata( UpdateMetadataRequest( id=external_id, metadata={ "claimed": data.user_data.metadata.get("claimed", []) + claimed, }, ) ) if not resp.ok: raise Exception("failed to update metadata", data.message) def _run(self, user_data: UserData): randomness_provider = user_data.get_additional_account(0) web3 = user_data.get_unprivileged_web3("main") web3.middleware_onion.add( construct_sign_and_send_raw_middleware(randomness_provider) ) (distributor,) = abi.decode( ["address"], web3.eth.call( { "to": user_data.metadata["challenge_address"], "data": web3.keccak(text="MERKLE_DISTRIBUTOR()")[:4].hex(), } ), ) from_number = web3.eth.block_number - 1 while True: latest_number = web3.eth.block_number print(f"from_number={from_number} latest={latest_number}") if from_number > latest_number: time.sleep(1) continue logs = web3.eth.get_logs( { "address": web3.to_checksum_address(distributor), "topics": [ web3.keccak(text="Claimed(uint256,address,uint256)").hex(), ], "fromBlock": from_number, "toBlock": latest_number, } ) claimed = [] for log in logs: print(f"fetched log={web3.to_json(log)}") claimed.append(Web3.to_checksum_address(log["data"][44:64].hex())) if len(claimed) > 0: try: self.update_claimed(user_data.external_id, claimed) except Exception as e: print("failed to update claimed", e) from_number = latest_number + 1 Watcher().start()
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/Paradigm/2023/misc/Free_Real_Estate/challenge.py
ctfs/Paradigm/2023/misc/Free_Real_Estate/challenge.py
import json from typing import List from anvil_server.database import UserData from anvil_server.socket import ( CreateInstanceRequest, CreateInstanceResponse, UnixClient, ) from eth_launchers.koth_launcher import KothChallengeLauncher from eth_launchers.launcher import ETH_RPC_URL from eth_launchers.score_submitter import ScoreSubmitter, get_score_submitter from eth_launchers.team_provider import TeamProvider, get_team_provider from eth_launchers.utils import deploy from foundry.anvil import LaunchAnvilInstanceArgs class Challenge(KothChallengeLauncher): def __init__( self, project_location: str, provider: TeamProvider, submitter: ScoreSubmitter ): super().__init__( project_location, provider, submitter, want_metadata=["claimed"] ) def create_instance(self, client: UnixClient) -> CreateInstanceResponse: return client.create_instance( CreateInstanceRequest( id=self.team, instances={ "main": LaunchAnvilInstanceArgs( balance=1000, fork_url=ETH_RPC_URL, ), }, daemons=[ "/home/user/watcher.py", ], ) ) def deploy(self, user_data: UserData) -> str: with open("airdrop-merkle-proofs.json", "r") as f: airdrop_data = json.load(f) web3 = user_data.get_privileged_web3("main") return deploy( web3, self.project_location, user_data.mnemonic, env={ "MERKLE_ROOT": airdrop_data["merkleRoot"], "TOKEN_TOTAL": airdrop_data["tokenTotal"], }, ) Challenge( project_location="project", provider=get_team_provider(), submitter=get_score_submitter(), ).run()
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/Paradigm/2023/pwn/100/challenge.py
ctfs/Paradigm/2023/pwn/100/challenge.py
from eth_launchers.pwn_launcher import PwnChallengeLauncher from eth_launchers.team_provider import get_team_provider PwnChallengeLauncher( project_location="project", provider=get_team_provider(), ).run()
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/Paradigm/2023/pwn/Grains_of_Sand/challenge.py
ctfs/Paradigm/2023/pwn/Grains_of_Sand/challenge.py
from anvil_server.socket import ( CreateInstanceRequest, CreateInstanceResponse, UnixClient, ) from eth_launchers.launcher import ETH_RPC_URL from eth_launchers.pwn_launcher import PwnChallengeLauncher from eth_launchers.team_provider import get_team_provider from foundry.anvil import LaunchAnvilInstanceArgs class Challenge(PwnChallengeLauncher): def create_instance(self, client: UnixClient) -> CreateInstanceResponse: return client.create_instance( CreateInstanceRequest( id=self.team, instances={ "main": LaunchAnvilInstanceArgs( balance=1000, fork_url=ETH_RPC_URL, fork_block_num=18_437_825, ), }, ) ) Challenge( project_location="project", provider=get_team_provider(), ).run()
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false