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/RACTF/2021/web/Emojibook/notes/migrations/0001_initial.py
ctfs/RACTF/2021/web/Emojibook/notes/migrations/0001_initial.py
# Generated by Django 3.2.6 on 2021-08-10 21:55 from django.conf import settings from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): initial = True dependencies = [ migrations.swappable_dependency(settings.AUTH_USER_MODEL), ] operations = [ migrations.CreateModel( name='Note', fields=[ ('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('name', models.CharField(max_length=255)), ('body', models.TextField()), ('author', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL)), ], ), ]
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/RACTF/2021/web/Emojibook/notes/migrations/__init__.py
ctfs/RACTF/2021/web/Emojibook/notes/migrations/__init__.py
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/BackdoorCTF/2024/blockchain/Betray_your_master/solve-pow.py
ctfs/BackdoorCTF/2024/blockchain/Betray_your_master/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/BackdoorCTF/2024/blockchain/Curvy_Pool/solve-pow.py
ctfs/BackdoorCTF/2024/blockchain/Curvy_Pool/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/BackdoorCTF/2024/blockchain/EasyPeasyLemonSqueezy/solve-pow.py
ctfs/BackdoorCTF/2024/blockchain/EasyPeasyLemonSqueezy/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/BackdoorCTF/2024/misc/Decompressor/chall.py
ctfs/BackdoorCTF/2024/misc/Decompressor/chall.py
#!/usr/bin/env python3 import random from collections import Counter from numpy import poly1d from queue import PriorityQueue from src.secret import flag, coeff assert len(flag) == 49 assert len(coeff) == 6 assert all(x > 0 and isinstance(x, int) for x in coeff) P = poly1d(coeff) class Node: def __init__(self, freq, symbol, left=None, right=None): self.freq = freq self.symbol = symbol self.left = left self.right = right def __lt__(self, nxt): if self.freq == nxt.freq: return self.symbol < nxt.symbol return self.freq < nxt.freq def get_codes(codes, node=None, val=""): if node: if not node.left and not node.right: codes[node.symbol] = val else: get_codes(codes, node.left, val + '0') get_codes(codes, node.right, val + '1') def compress(s: str) -> str: cnt = Counter(s) codes = {} pq = PriorityQueue() for element in cnt: pq.put(Node(cnt[element], element)) n_nodes = len(cnt) while n_nodes > 1: left = pq.get() right = pq.get() new = Node(left.freq + right.freq, min(left.symbol, right.symbol), left, right) pq.put(new) n_nodes -= 1 get_codes(codes, node=pq.get()) cmprsd = "" for c in s: cmprsd += codes[c] # return cmprsd, codes return cmprsd def get_info() -> int: s = list(flag) idx = random.randint(0, len(flag)-1) return P(ord(s[idx])) def main(): print("Welcome, agent, to the Decompressor Challenge!") print("Your mission, should you choose to accept it, involves unraveling the encrypted flag.") print("Can you decompress the flag without the codes?") print("Good luck, and may the odds be ever in your favor!\n") while True: print("Select your next action:") print("1. Retrieve compressed flag without codes.") print("2. Access additional intel.") print("3. Abort mission and exit.") choice = input("> ") if choice == "1": code = compress(flag) print(f"Compressed Flag: {code}") elif choice == "2": info = get_info() print(f"Additional Info: {info}") elif choice == "3": print("Mission aborted. Goodbye!") break else: print("Invalid choice! Please select a valid option.")
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/BackdoorCTF/2024/crypto/AESwap/chall.py
ctfs/BackdoorCTF/2024/crypto/AESwap/chall.py
from aes import * from flag import flag import os NSWAPS = 42*6 - 42//2 + 4 msg = b'thoushaltnotpass' assert len(msg) == 16 for i in range(NSWAPS): indices = list( map(int, input(f"({i+1}) Bribe soldiers to swap their positions: ").split())) s_box[indices[0]], s_box[indices[1]] = s_box[indices[1]], s_box[indices[0]] key = os.urandom(16) aes = AES(key) ciphertext = aes.encrypt_block(msg) print(ciphertext.hex()) flag = pad(flag) flag_blocks = split_blocks(flag) for i, block in enumerate(flag_blocks): flag_blocks[i] = aes.encrypt_block(block) ciphertext = b''.join(flag_blocks) print(ciphertext.hex())
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/BackdoorCTF/2024/crypto/AESwap/aes.py
ctfs/BackdoorCTF/2024/crypto/AESwap/aes.py
#!/usr/bin/env python3 """ This is an exercise in secure symmetric-key encryption, implemented in pure Python (no external libraries needed). Original AES-128 implementation by Bo Zhu (http://about.bozhu.me) at https://github.com/bozhu/AES-Python . PKCS#7 padding, CBC mode, PKBDF2, HMAC, byte array and string support added by me at https://github.com/boppreh/aes. Other block modes contributed by @righthandabacus. Although this is an exercise, the `encrypt` and `decrypt` functions should provide reasonable security to encrypted messages. """ s_box = [ 0x63, 0x7C, 0x77, 0x7B, 0xF2, 0x6B, 0x6F, 0xC5, 0x30, 0x01, 0x67, 0x2B, 0xFE, 0xD7, 0xAB, 0x76, 0xCA, 0x82, 0xC9, 0x7D, 0xFA, 0x59, 0x47, 0xF0, 0xAD, 0xD4, 0xA2, 0xAF, 0x9C, 0xA4, 0x72, 0xC0, 0xB7, 0xFD, 0x93, 0x26, 0x36, 0x3F, 0xF7, 0xCC, 0x34, 0xA5, 0xE5, 0xF1, 0x71, 0xD8, 0x31, 0x15, 0x04, 0xC7, 0x23, 0xC3, 0x18, 0x96, 0x05, 0x9A, 0x07, 0x12, 0x80, 0xE2, 0xEB, 0x27, 0xB2, 0x75, 0x09, 0x83, 0x2C, 0x1A, 0x1B, 0x6E, 0x5A, 0xA0, 0x52, 0x3B, 0xD6, 0xB3, 0x29, 0xE3, 0x2F, 0x84, 0x53, 0xD1, 0x00, 0xED, 0x20, 0xFC, 0xB1, 0x5B, 0x6A, 0xCB, 0xBE, 0x39, 0x4A, 0x4C, 0x58, 0xCF, 0xD0, 0xEF, 0xAA, 0xFB, 0x43, 0x4D, 0x33, 0x85, 0x45, 0xF9, 0x02, 0x7F, 0x50, 0x3C, 0x9F, 0xA8, 0x51, 0xA3, 0x40, 0x8F, 0x92, 0x9D, 0x38, 0xF5, 0xBC, 0xB6, 0xDA, 0x21, 0x10, 0xFF, 0xF3, 0xD2, 0xCD, 0x0C, 0x13, 0xEC, 0x5F, 0x97, 0x44, 0x17, 0xC4, 0xA7, 0x7E, 0x3D, 0x64, 0x5D, 0x19, 0x73, 0x60, 0x81, 0x4F, 0xDC, 0x22, 0x2A, 0x90, 0x88, 0x46, 0xEE, 0xB8, 0x14, 0xDE, 0x5E, 0x0B, 0xDB, 0xE0, 0x32, 0x3A, 0x0A, 0x49, 0x06, 0x24, 0x5C, 0xC2, 0xD3, 0xAC, 0x62, 0x91, 0x95, 0xE4, 0x79, 0xE7, 0xC8, 0x37, 0x6D, 0x8D, 0xD5, 0x4E, 0xA9, 0x6C, 0x56, 0xF4, 0xEA, 0x65, 0x7A, 0xAE, 0x08, 0xBA, 0x78, 0x25, 0x2E, 0x1C, 0xA6, 0xB4, 0xC6, 0xE8, 0xDD, 0x74, 0x1F, 0x4B, 0xBD, 0x8B, 0x8A, 0x70, 0x3E, 0xB5, 0x66, 0x48, 0x03, 0xF6, 0x0E, 0x61, 0x35, 0x57, 0xB9, 0x86, 0xC1, 0x1D, 0x9E, 0xE1, 0xF8, 0x98, 0x11, 0x69, 0xD9, 0x8E, 0x94, 0x9B, 0x1E, 0x87, 0xE9, 0xCE, 0x55, 0x28, 0xDF, 0x8C, 0xA1, 0x89, 0x0D, 0xBF, 0xE6, 0x42, 0x68, 0x41, 0x99, 0x2D, 0x0F, 0xB0, 0x54, 0xBB, 0x16, ] def sub_bytes(s): for i in range(4): for j in range(4): s[i][j] = s_box[s[i][j]] def shift_rows(s): s[0][1], s[1][1], s[2][1], s[3][1] = s[1][1], s[2][1], s[3][1], s[0][1] s[0][2], s[1][2], s[2][2], s[3][2] = s[2][2], s[3][2], s[0][2], s[1][2] s[0][3], s[1][3], s[2][3], s[3][3] = s[3][3], s[0][3], s[1][3], s[2][3] def add_round_key(s, k): for i in range(4): for j in range(4): s[i][j] ^= k[i][j] # learned from https://web.archive.org/web/20100626212235/http://cs.ucsb.edu/~koc/cs178/projects/JT/aes.c def xtime(a): return (((a << 1) ^ 0x1B) & 0xFF) if (a & 0x80) else (a << 1) def mix_single_column(a): # see Sec 4.1.2 in The Design of Rijndael t = a[0] ^ a[1] ^ a[2] ^ a[3] u = a[0] a[0] ^= t ^ xtime(a[0] ^ a[1]) a[1] ^= t ^ xtime(a[1] ^ a[2]) a[2] ^= t ^ xtime(a[2] ^ a[3]) a[3] ^= t ^ xtime(a[3] ^ u) def mix_columns(s): for i in range(4): mix_single_column(s[i]) r_con = ( 0x00, 0x01, 0x02, 0x04, 0x08, 0x10, 0x20, 0x40, 0x80, 0x1B, 0x36, 0x6C, 0xD8, 0xAB, 0x4D, 0x9A, 0x2F, 0x5E, 0xBC, 0x63, 0xC6, 0x97, 0x35, 0x6A, 0xD4, 0xB3, 0x7D, 0xFA, 0xEF, 0xC5, 0x91, 0x39, ) def bytes2matrix(text): """ Converts a 16-byte array into a 4x4 matrix. """ return [list(text[i:i+4]) for i in range(0, len(text), 4)] def matrix2bytes(matrix): """ Converts a 4x4 matrix into a 16-byte array. """ return bytes(sum(matrix, [])) def xor_bytes(a, b): """ Returns a new byte array with the elements xor'ed. """ return bytes(i ^ j for i, j in zip(a, b)) def pad(plaintext): """ Pads the given plaintext with PKCS#7 padding to a multiple of 16 bytes. Note that if the plaintext size is a multiple of 16, a whole block will be added. """ padding_len = 16 - (len(plaintext) % 16) padding = bytes([padding_len] * padding_len) return plaintext + padding def split_blocks(message, block_size=16, require_padding=True): assert len(message) % block_size == 0 or not require_padding return [message[i:i+16] for i in range(0, len(message), block_size)] class AES: """ Class for AES-128 encryption with CBC mode and PKCS#7. This is a raw implementation of AES, without key stretching or IV management. Unless you need that, please use `encrypt` and `decrypt`. """ rounds_by_key_size = {16: 10, 24: 12, 32: 14} def __init__(self, master_key): """ Initializes the object with a given key. """ assert len(master_key) in AES.rounds_by_key_size self.n_rounds = AES.rounds_by_key_size[len(master_key)] self._key_matrices = self._expand_key(master_key) def _expand_key(self, master_key): """ Expands and returns a list of key matrices for the given master_key. """ # Initialize round keys with raw key material. key_columns = bytes2matrix(master_key) iteration_size = len(master_key) // 4 i = 1 while len(key_columns) < (self.n_rounds + 1) * 4: # Copy previous word. word = list(key_columns[-1]) # Perform schedule_core once every "row". if len(key_columns) % iteration_size == 0: # Circular shift. word.append(word.pop(0)) # Map to S-BOX. word = [s_box[b] for b in word] # XOR with first byte of R-CON, since the others bytes of R-CON are 0. word[0] ^= r_con[i] i += 1 elif len(master_key) == 32 and len(key_columns) % iteration_size == 4: # Run word through S-box in the fourth iteration when using a # 256-bit key. word = [s_box[b] for b in word] # XOR with equivalent word from previous iteration. word = xor_bytes(word, key_columns[-iteration_size]) key_columns.append(word) # Group key words in 4x4 byte matrices. return [key_columns[4*i: 4*(i+1)] for i in range(len(key_columns) // 4)] def encrypt_block(self, plaintext): """ Encrypts a single block of 16 byte long plaintext. """ assert len(plaintext) == 16 plain_state = bytes2matrix(plaintext) add_round_key(plain_state, self._key_matrices[0]) for i in range(1, self.n_rounds): sub_bytes(plain_state) shift_rows(plain_state) mix_columns(plain_state) add_round_key(plain_state, self._key_matrices[i]) sub_bytes(plain_state) shift_rows(plain_state) add_round_key(plain_state, self._key_matrices[-1]) return matrix2bytes(plain_state)
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/BackdoorCTF/2024/crypto/I_Like_McDonalds/server.py
ctfs/BackdoorCTF/2024/crypto/I_Like_McDonalds/server.py
import hashlib from typing import List class CustomMAC: def __init__(self): self._internal_state = b"" def update(self, message: bytes) -> None: if not self._internal_state: self._internal_state = self.get_key() + message else: self._internal_state += message def get_key(self) -> bytes: return open("key.txt", "rb").read().strip() def digest(self) -> bytes: return hashlib.sha256(self._internal_state).digest()[:8] class TokenManager: def __init__(self): self._mac = CustomMAC() self._seen_tokens: List[bytes] = [] def verify_and_store(self, message: bytes, token: bytes) -> bool: self._mac = CustomMAC() self._mac.update(message) expected_token = self._mac.digest() if token != expected_token: print(f"Invalid token! Expected token: {expected_token.hex()}") return False if token in self._seen_tokens: print("Token already used!") return False self._seen_tokens.append(token) return True def main(): print("Welcome to the Token Verification Challenge!") print("============================================") print("Rules:") print("1. Submit message-token pairs") print("2. Each token must be valid for its message") print("3. You cannot reuse tokens") print("4. Get 64 valid tokens accepted to win!") print("\nFormat: <hex-encoded-message> <hex-encoded-token>") print("Example: 48656c6c6f 1234567890abcdef") manager = TokenManager() successes = 0 for i in range(128): try: print(f"\nAttempt {i+1}/128") print("Enter your message and token: ", end='') user_input = input().strip().split() if len(user_input) != 2: print("Invalid input format!") continue message = bytes.fromhex(user_input[0]) token = bytes.fromhex(user_input[1]) if manager.verify_and_store(message, token): successes += 1 print(f"Success! {successes}/64 valid tokens verified") if successes >= 64: print("\nCongratulations! You beat the challenge!") with open("flag.txt", "r") as f: print(f.read().strip()) break except Exception as e: print(f"Error: {str(e)}") continue if successes < 64: print("\nChallenge failed! Not enough valid tokens.") 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/BackdoorCTF/2023/blockchain/BabyBlackjack/solve-pow.py
ctfs/BackdoorCTF/2023/blockchain/BabyBlackjack/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/BackdoorCTF/2023/blockchain/VulnChain/solve-pow.py
ctfs/BackdoorCTF/2023/blockchain/VulnChain/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/BackdoorCTF/2023/misc/Not_So_Guessy/Guessy_1970.py
ctfs/BackdoorCTF/2023/misc/Not_So_Guessy/Guessy_1970.py
Secret_Number = "REDACTED" Flag = "REDACTED" coin = {1:'Heads', 0:'Tails'} wins = 0 print("Welcome to The Guessy Game.") print("To get The Flag, you have to beat me in Heads and Tails until I admit defeat.") print("However if you lose once, You Lose.") while Secret_Number: draw = coin[Secret_Number % 2] Secret_Number//=2 print() print(f"Wins : {wins}") print('Heads or Tails?') guess = input() if guess == draw: wins += 1 if Secret_Number==0 : print('Fine. I give up. You have beaten me.') print('Here is your Flag. Take it!') print() print(Flag) print() exit() print('Okay you guessed right this time. But its not enough to defeat me.') else : print("Haha. I knew you didn't have it in you.") print("You guessed wrong. Bye byee") exit()
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/BackdoorCTF/2023/misc/Not_So_Guessy/Guessy_2020.py
ctfs/BackdoorCTF/2023/misc/Not_So_Guessy/Guessy_2020.py
Secret_Number = "REDACTED" Flag = "REDACTED" AI = {2:'Scissors', 1:'Paper', 0:'Rock'} win = {'Rock':'Paper','Paper':'Scissors','Scissors':'Rock'} draws = 0 wins = 0 print("Welcome to The Guessy Game.") print("To get The Flag, you have to beat the AI I made in Rock, Paper, Scissors until it can't take the losses and self-destructs.") print("However if you lose once, You Lose.") print("Beware! If the AI draws you twice, it will analyse your mind and you will never be able to defeat it ever.") while Secret_Number: hand = AI[Secret_Number % 3] Secret_Number//=3 print() print(f"Wins : {wins}, Draws : {draws}") print('Rock, Paper, Scissors!') guess = input() if guess == hand: print("Ah, Seems like its a draw.") draws += 1 if draws == 2: print("The AI now knows your every move. You will never win.") exit() elif guess == win[hand]: wins += 1 if Secret_Number==0 : print("Fine. You got me. It wasn't an AI it was just a simple Python Code.") print('Here is your Flag. Take it!') print() print(Flag) print() exit() print('Okay you guessed right this time. But its not enough to defeat my AI.') else : print("Haha. I knew you didn't have it in you.") print("You guessed wrong. Bye byee") exit()
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/BackdoorCTF/2023/misc/mini_RSA_v2/chal.py
ctfs/BackdoorCTF/2023/misc/mini_RSA_v2/chal.py
from Crypto.Util.number import getPrime , bytes_to_long , GCD import random import time random.seed(time.time()) flag = b"flag{REDACTED}" #Flag has been removed KEY_SIZE = 512 RSA_E = 65537 def fast_exp(a, b, n): output = 1 while b > 0: if b & 1: output = output * a % n a = a * a % n b >>= 1 return output def check(p, q, n): a_ = random.randint(1, 100) b_ = random.randint(1, 100) s = fast_exp(p, fast_exp(q, a_, (p - 1) * (q - 1)), n) t = fast_exp(q, fast_exp(p, b_, (p - 1) * (q - 1)), n) result = s + t print(result) def gen_RSA_params(N, e): p = getPrime(N) q = getPrime(N) while GCD(e, (p - 1) * (q - 1)) > 1: p = getPrime(N) q = getPrime(N) n = p * q check(p, q, n) return (p, q, n) p, q, n = gen_RSA_params(KEY_SIZE, RSA_E) m = bytes_to_long(flag) c = pow(m, RSA_E, n) print(c) print(n)
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/BackdoorCTF/2023/misc/mini_RSA/script.py
ctfs/BackdoorCTF/2023/misc/mini_RSA/script.py
from Crypto.Util.number import getPrime , bytes_to_long , GCD import random import time random.seed(time.time()) flag = b"flag{REDACTED}" #Flag has been removed KEY_SIZE = 512 RSA_E = 3 def fast_exp(a, b, n): output = 1 while b > 0: if b & 1: output = output * a % n a = a * a % n b >>= 1 return output def check(p, q, n): a_ = random.randint(1, 100) b_ = random.randint(1, 100) s = fast_exp(p, fast_exp(q, a_, (p - 1) * (q - 1)), n) t = fast_exp(q, fast_exp(p, b_, (p - 1) * (q - 1)), n) result = s + t print(result) def gen_RSA_params(N, e): p = getPrime(N) q = getPrime(N) while GCD(e, (p - 1) * (q - 1)) > 1: p = getPrime(N) q = getPrime(N) n = p * q check(p, q, n) return (p, q, n) p, q, n = gen_RSA_params(KEY_SIZE, RSA_E) m = bytes_to_long(flag) c = pow(m, RSA_E, n) print(c) print(n)
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/BackdoorCTF/2023/misc/secret_of_j4ck4l/app.py
ctfs/BackdoorCTF/2023/misc/secret_of_j4ck4l/app.py
from flask import Flask, request, render_template_string, redirect import os import urllib.parse app = Flask(__name__) base_directory = "message/" default_file = "message.txt" def ignore_it(file_param): yoooo = file_param.replace('.', '').replace('/', '') if yoooo != file_param: return "Illegal characters detected in file parameter!" return yoooo def another_useless_function(file_param): return urllib.parse.unquote(file_param) def url_encode_path(file_param): return urllib.parse.quote(file_param, safe='') def useless (file_param): file_param1 = ignore_it(file_param) file_param2 = another_useless_function(file_param1) file_param3 = ignore_it(file_param2) file_param4 = another_useless_function(file_param3) file_param5 = another_useless_function(file_param4) return file_param5 @app.route('/') def index(): return redirect('/read_secret_message?file=message') @app.route('/read_secret_message') def read_file(file_param=None): file_param = request.args.get('file') file_param = useless(file_param) print(file_param) file_path = os.path.join(base_directory, file_param) try: with open(file_path, 'r') as file: content = file.read() return content except FileNotFoundError: return 'File not found! or maybe illegal characters detected' except Exception as e: return f'Error: {e}' if __name__ == '__main__': app.run(debug=False, host='0.0.0.0', port=4053)
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/BackdoorCTF/2023/misc/Something_in_Common/script.py
ctfs/BackdoorCTF/2023/misc/Something_in_Common/script.py
from Crypto.Util.number import * flag = "This flag has been REDACTED" moduli = "This array has been REDACTED" m = bytes_to_long(flag.encode()) e = 3 remainders = [pow(m,e,n) for n in moduli] f = open('output.txt','w') for i in range(len(moduli)): f.write(f"m ^ e mod {moduli[i]} = {remainders[i]}\n") f.write(f"\ne = {e}") f.close()
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/BackdoorCTF/2023/crypto/ColL3g10n/script.py
ctfs/BackdoorCTF/2023/crypto/ColL3g10n/script.py
from hashlib import md5, sha256 import random from Crypto.Util.number import * alphanum = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz' flag = "This flag has been REDACTED" secret = ''.join(random.choices(alphanum,k=10)) sec_num = bytes_to_long(secret.encode()) history = [] tries = 3 while tries: print(f"Tries left : {tries}") print("Provide the hex of first message: ",end='') m1 = bytes.fromhex(input()) print("Provide the hex of second message: ",end='') m2 = bytes.fromhex(input()) if m1==m2: print("Do you take me as a fool?. Give me 2 different messages.\n") tries-=1 continue if m1[0] in history or m2[0] in history: print("You have already provided messages with the same first byte. You still lose a try.\n") tries-=1 continue if md5(m1).hexdigest()==md5(m2).hexdigest() and sha256(m1).hexdigest()[:5]==sha256(m2).hexdigest()[:5]: history.append(m1[0]) print("Wow! Both messages have the same signature.") print("Okay I can reveal some part of the secret to you. Give me a number with no more than 24 set bits and I will reveal those bits of the secret to you.") print("num: ",end='') num = int(input()) bit_count = bin(num).count('1') if bit_count>24: print("Read the rules properly. No more than 24 bits allowed.\n") tries-=1 continue print(f"Revealing bits : {sec_num&num}\n") tries-=1 continue else: print("The signatures don't match.\n") tries-=1 continue print("Can you Guess the secret: ",end='') guess = input() if guess == secret: print(f"You gussed correctly. Here is your flag: {flag}") else: print(f"Wrong guess. Bye bye!")
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/BackdoorCTF/2023/crypto/Safe_Curvy_Curve/chall.py
ctfs/BackdoorCTF/2023/crypto/Safe_Curvy_Curve/chall.py
from Crypto.Util.number import getPrime, getRandomNBitInteger, bytes_to_long, long_to_bytes from sage.all import * n = 325325755182481058670589439237195225483797901549838835146388756505962515992731682902174843378473793118013824587686743801443229435097379024643408429957717590072275498734396840489261986361764935791083084431387935565119970246214821662977047205360090509590387268197591520307878877103247121412898793371812283196864079961633428662039795223806526580626911586062085681619829271800589543048515261459541945856915535056363750996243146294104205192635607675773145823355324367791593757860302117944097894321078809559514655550115178790472355420484756646090492860950760854985816746318432545157312928351659730275368368710393481 # non-residue D = 104195424559311137181271279442498654957365659039072230133307906910289876977215387204406606621273182995744469913980318794193540266885069529501579897759819085330481440863835062469771268905581027223137570462332151650553239341513789960350350245008144164176339007365876329719830893966710072622193879546377346644622 # redacted p = "REDACTED" q = n // p flag = b"REDACTED" class Point: def __init__(self, x, y): self.x = x self.y = y def __add__(self, other): x = (self.x*other.x + D*self.y*other.y)%n y = (self.y*other.x + self.x*other.y)%n return Point(x, y) def __mul__(self, d): Q = Point(1, 0) P = Point(self.x, self.y) while d != 0: if d&1 == 1: Q += P P += P d >>= 1 return Q def __str__(self) -> str: return f"{self.x}, {self.y}" def check_residue(y): if pow(y, (p - 1)//2, p) == 1 and pow(y, (q - 1)//2, q) == 1: return True return False def gen_point(): while True: x = getRandomNBitInteger(2000 - 464) x = bytes_to_long(flag + long_to_bytes(x)) x %= n y2 = ((x*x - 1)*pow(D, -1, n))%n if(check_residue(y2)): yp = pow(y2, (p + 1) // 4, p) yq = pow(y2, (q + 1) // 4, q) y = crt([yp, yq], [p, q]) return Point(x, y) def add(a, b): if a == "i": return b return (D + a*b)*pow(a + b, - 1, n)%n def power(a, d): res = "i" x = a while d != 0: if d&1 == 1: res = add(res, x) x = add(x, x) d >>= 1 return res def point(m): return Point((m**2 + D)*pow(m**2 - D, -1, n)%n, 2*m*pow(m*m - D, -1, n)%n) M = gen_point() Mx, My = M.x, M.y assert (Mx**2 - D*My**2)%n == 1 e = 65537 C = M*e print(C) # 162961013908573567883708515220539578804107270477973090499542519193835498763624042601337274226440312066476160075983577251445943502548471650694617020354363039427231006183897304593798946447482514180041848851245384617847515040075915213698357885114317390276898478740949700799011676589252761736123613456698426984426140183972297018822418150981970598934664464599487393545946613698687046341448558294255407327000026161574779286948527797313848936686929888861150592859573221003557737086661845641459024783317432643308034709718127845066442672512067552552244030535478274512743971354192981490674475749853430371212307520421190, 239668740066200913943562381887193634676899220686058888912170632953311361194017666904277854011894382855202483252661143091091993190645295938873381009873178536800816517615786834926664362950059833369410239281041504946121643304746955139178731148307192034732522723412439705530514113775245607466575056817920259552225402143084439183697819510515790086246564683416312338905722676300264277098153045593619223527605305078928548583405756368607546463429755374790443440435124030514385157787083987202901009878849122637030860266764644062073632184729561756322435322264642199576207018861730005366413597578298926774145872631956206
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/BackdoorCTF/2023/crypto/Curvy_Curves/chall.py
ctfs/BackdoorCTF/2023/crypto/Curvy_Curves/chall.py
from Crypto.Util.number import getRandomNBitInteger, bytes_to_long, long_to_bytes from sage.all import * # non-residue D = 136449572493235894105040063345648963382768741227829225155873529439788000141924302071247144068377223170502438469323595278711906213653227972959011573520003821372215616761555719247287249928879121278574549473346526897917771460153933981713383608662604675157541813068900456012262173614716378648849079776150946352466 # redacted p = "REDACTED" q = "REDACTED" # n = p*q n = 22409692526386997228129877156813506752754387447752717527887987964559571432427892983480051412477389130668335262274931995291504411262883294295070539542625671556700675266826067588284189832712291138415510613208544808040871773692292843299067831286462494693987261585149330989738677007709580904907799587705949221601393 flag = b"flag{REDACTED}" class Point: def __init__(self, x, y): self.x = x self.y = y def __add__(self, other): x = (self.x*other.x + D*self.y*other.y)%n y = (self.y*other.x + self.x*other.y)%n return Point(x, y) def __mul__(self, d): Q = Point(1, 0) P = Point(self.x, self.y) while d != 0: if d&1 == 1: Q += P P += P d >>= 1 return Q def __str__(self) -> str: return f"{self.x}, {self.y}" def check_residue(y): if pow(y, (p - 1)//2, p) == 1 and pow(y, (q - 1)//2, q) == 1: return True return False def gen_point(): while True: x = getRandomNBitInteger(1023 - 240) x = bytes_to_long(flag + long_to_bytes(x)) x %= n y2 = ((x*x - 1)*pow(D, -1, n))%n if(check_residue(y2)): yp = pow(y2, (p + 1) // 4, p) yq = pow(y2, (q + 1) // 4, q) y = crt([yp, yq], [p, q]) return Point(x, y) M = gen_point() e = 65537 C = M*e print(C) # Cx = 10800064805285540717966506671755608695842888167470823375167618999987859282439818341340065691157186820773262778917703163576074192246707402694994764789796637450974439232033955461105503709247073521710698748730331929281150539060841390912041191898310821665024428887410019391364779755961320507576829130434805472435025, Cy = 2768587745458504508888671295007858261576650648888677215556202595582810243646501012099700700934297424175692110043143649129142339125437893189997882008360626232164112542648695106763870768328088062485508904856696799117514392142656010321241751972060171400632856162388575536779942744760787860721273632723718380811912
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/BackdoorCTF/2023/crypto/Knapsack/script.py
ctfs/BackdoorCTF/2023/crypto/Knapsack/script.py
import random import hashlib from Crypto.Util.number import bytes_to_long from Crypto.Cipher import AES flag = b"The flag has been REDACTED" secret = b"The seccret has been REDACTED" key = hashlib.sha256(secret).digest()[:16] cipher = AES.new(key, AES.MODE_ECB) padded_flag = flag + b'\x00'*(-len(flag)%16) ciphertext = cipher.encrypt(padded_flag) f = open('output.txt','w') f.write(f"Ciphertext: {ciphertext.hex()}\n\n") arr = [ random.randint(1,1000000000000) for i in range(40) ] k = bytes_to_long(secret) s = 0 for i in range(40): if k&(1<<i): s+=arr[i] f.write(f'numbers: {str(arr)[1:-1]}\nsum: {s}\n') f.close()
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/BackdoorCTF/2025/crypto/The_Job/server.py
ctfs/BackdoorCTF/2025/crypto/The_Job/server.py
import random rand = random.SystemRandom() from flag import FLAG k = 256 mod = 10**9+7 hash_table = [[] for i in range(k)] print("Your friend, a full stack developer, was asked to implement a hash table by his boss. Your friend, being an experienced individual, created a hash table which has 256 slots, and each slot can hold multiple values using a linked list.\n\nWhen a number arrives as input, it will be hashed and if the hash is x, the number will be inserted into the xth slot of the hash table at the end of the respective list. Although, if the xth slot doesn't exist, the program will die.\n") print("However when he went to submit his code, he was presented with an unreasonable request. His manager demands that the inputs need to be equally divided among all slots. So, the difference in sizes of any two slots of the table should not be 2 or more.\n\nNow, your friend is not an expert when it comes to hashing. So, he comes to you, a cryptography genius. All you have to do is create a hash polynomial that equally divides the input. The polynomial will be evaluated on the input number and the remainder from the modulus 1e9+7 will be taken as the hash to determine the slot where that number goes.\nFor example: if the polynomial is x^2 + 2x - 3, and the input is 5: f(5) = 32 mod 1000000007. So it will go into slot 32. (slots are from 0 to k-1)\n") print("Now even your friend knows that this task is impossible. So he took the help of your unethical hacker friend to leak the input numbers on which his manager will test the hash table.\n") input("Press Enter to start > ") n = 896 number_array = [rand.randint(0,mod-1) for i in range(n)] while len(set(number_array))!=n: number_array = [rand.randint(0,mod-1) for i in range(n)] print(f"Here are the leaked numbers : {','.join([str(num) for num in number_array])}\n") coeff_str = input("Enter the coefficients of the polynomial.\nExample: if the polynomial is x^2 + 2x - 3, Enter 1,2,1000000004\nThe degree of the polynomial should be less than the count of input numbers.\n> ") try: coeff_arr = list(map(int,coeff_str.split(','))) except: print("Incorrect input format") exit() if len(coeff_arr)>n: print("The degree of the polynomial should be less than the count of input numbers.") exit() coeff_arr = [coeff%mod for coeff in coeff_arr] def get_hash(num,coeff_arr): hash = 0 mult = 1 for i in range(len(coeff_arr)): hash = (hash + mult * coeff_arr[len(coeff_arr)-1-i])%mod mult = (mult*num)%mod return hash for i in range(n): hash = get_hash(number_array[i],coeff_arr) if hash>=k: print(f"Input {i} : Faulty Hash function! Slot {hash} doesn't exist.") exit() hash_table[hash].append(number_array[i]) for i in range(k): if len(hash_table[i])>(n+k-1)/k: print("You have failed your friend in need. How can you be called a cryptography genius, if you can't even forge a hash function. Go back to solving ciphers. Maths isn't your thing.") exit() print("You have successfully created a hash that your friend can use. You retain your title as the cryptography genius.\n") print("OR SO YOU THOUGHT. Turns out your friend is not a genius himself. While creating the architecture for the hash table, he inserted a random value into the a random index of the hash table. Now everytime you use an empty hash table, it's never empty. There is always one extra number in one particular index which can ruin your plans of dividing all inputs equally.\n") print("Your friend doesn't remember which index he used. And he can't modify the architecture of the hash table since he has already submitted it.\n\nBut he has 6 free trials provided by his manager. Where he can submit a hash polynomial and the manager will tell if the hash table is balanced or not (if the difference between the maximum size at any index and minimum size at any index is less than 2).\n") print("Now the mission falls back to you. You have to devise valid hash polynomials that the manager will test and tell if the hash table is balanced or not. And at the end of all free trials, you have to tell which index contains the unnecessary number.\n\n*The input numbers will remain the same as previously leaked.\n") input("Press Enter to continue > ") target = rand.randint(0,k-1) junk = rand.randint(0,mod-1) for turn in range(6): print(f"Trial {turn+1} : ") coeff_str = input("Enter the coefficients of the polynomial.\n> ") try: coeff_arr = list(map(int,coeff_str.split(','))) except: print("Incorrect input format") exit() coeff_arr = [coeff%mod for coeff in coeff_arr] if len(coeff_arr)>n: print("The degree of the polynomial should be less than the count of input numbers.") exit() hash_table = [[] for i in range(k)] hash_table[target].append(junk) for num in number_array: hash = get_hash(num,coeff_arr) if hash>=k: print(f"Input {i} : Faulty Hash function! Slot {hash} doesn't exist.") exit() hash_table[hash].append(number_array[i]) good = True for i in range(k): if len(hash_table[i])>(n+k-1)/k: good = False print("Manager says the hash failed in distributing input equally.\n\n") break if good: print("Manager says the hash passed in distributing input equally\n\n") try: index = int(input("Tell your friend the index : ")) except: print("Wrong format, Enter an integer.") exit() if index != target: print("Your friend tried to remove the number at the index you told him. The hash table crashed a burned. Your friend has lost the job.") exit() else: print("Your friend tried to remove the number at the index you told him. It worked! You have saved your friend's job.\n") print("You truly are a cryptography genius!") print(f"Here is the flag : {FLAG}")
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/BackdoorCTF/2025/crypto/p34kC0nj3c7ur3/chall.py
ctfs/BackdoorCTF/2025/crypto/p34kC0nj3c7ur3/chall.py
from Cryptodome.Util.number import isPrime, bytes_to_long, long_to_bytes from message import message def uniqueHash(x): steps = 0 while x != 1: steps += 1 if x % 2 == 0: x = x // 2 else: x = 3 * x + 1 if steps >= 10000: return steps return steps message = bytes_to_long(message) myHash = uniqueHash(message) PROOF = 10 print("This is my hash of hash:", uniqueHash(myHash)) prevs = [] steps = 250 while len(prevs) < PROOF: x = int(input("Enter your message in hex: "), 16) if uniqueHash(x) == myHash and x not in prevs: if isPrime(x) == isPrime(message): prevs.append(x) print("Correct!") else: print("Well Well, you failed!") else: print("Incorrect!") steps -= 1 if steps == 0: print("Enough fails!") quit() print("Wow! you know my message is:", long_to_bytes(message))
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/BackdoorCTF/2025/crypto/Ambystoma_Mexicanum_Revenge/chall.py
ctfs/BackdoorCTF/2025/crypto/Ambystoma_Mexicanum_Revenge/chall.py
from cryptography.hazmat.primitives.ciphers.aead import AESGCMSIV import binascii import os KEY_SIZE = 16 NONCE_SIZE = 12 FLAG = "flag{lol_this_is_obv_not_the_flag}" KEYS = [] CIPHERTEXTS = [] CIPHERTEXTS_LEN = 1 REQUEST = "gib me flag plis" class Service: def __init__(self): self.key = self.gen_key() self.nonce = os.urandom(NONCE_SIZE) self.aad = b"" def gen_key(self): self.key = os.urandom(KEY_SIZE) return self.key def decrypt(self, ciphertext, key): try: plaintext = AESGCMSIV(key).decrypt(self.nonce, ciphertext, self.aad) return plaintext except Exception: return None usertext = "" ASCII_BANNER = """ ╔═══════════════════════════════════════════════════════════╗ ║ CRYPTIC SERVICE ║ ╚═══════════════════════════════════════════════════════════╝ ∧_∧ (・ω・) Protecting your secrets one key at a time... """ print(ASCII_BANNER) service = Service() KEYS.append(service.key.hex()) MENU_HEADER = """ ╔════════════════════════════════════╗ ║ MAIN MENU ║ ╚════════════════════════════════════╝ """ while True: print(MENU_HEADER) print("Choose an option:") print("1. rotate key") print("2. debug") print("3. push ciphertext") print("4. request flag") choice = input("Your choice: ").strip() if choice == "1": service.gen_key() KEYS.append(service.key.hex()) print("\nKey rotated.\n") elif choice == "2": print(f"\n{KEYS=}") print(f"{CIPHERTEXTS=}") print(f"nonce={service.nonce.hex()}\n") elif choice == "3": ct = input("\nEnter ciphertext (hex): ").strip() CIPHERTEXTS.append(ct) if len(CIPHERTEXTS) > CIPHERTEXTS_LEN: print("\nSorry, I cannot remember more ciphertexts :(\n") break elif choice == "4": for i in range(4): try: key = binascii.unhexlify(KEYS[i]) ct = binascii.unhexlify(CIPHERTEXTS[i % len(CIPHERTEXTS)]) text = service.decrypt(ct, key)[16 * i:16 * (i+1)].decode('utf-8').strip() if not text or len(text) == 0 or text is None: print("why so rude :(\n") exit(0) except Exception: print("you have no honour!\n") exit(0) usertext += text if usertext == REQUEST: print(f"Damn, you are something. Here is the flag: {FLAG}\n") exit(0) else: print("Request politely please!!\n") exit(0) else: print("I don't recognize this.")
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/BackdoorCTF/2025/crypto/bolt_fast/chall.py
ctfs/BackdoorCTF/2025/crypto/bolt_fast/chall.py
from Crypto.Util.number import getPrime, inverse, bytes_to_long def flash_key(): while True: p = getPrime(1024) q = getPrime(1024) N = p * q #you can't even use weiner's attack now hahaha dp_smart= getPrime(16) try: e = inverse(dp_smart, p-1) return N, e, dp_smart except ValueError: continue N, e, _= flash_key() flag = b"flag{REDACTED}" m = bytes_to_long(flag) c = pow(m, e, N) print("Need for Speed") print("Since Wiener said calculating d_p and d_q is fast, I decided to make it even faster 'cause I am smarter.") print(f"N = {N}") print(f"e = {e}") 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/BackdoorCTF/2025/crypto/lcg_2/chall.py
ctfs/BackdoorCTF/2025/crypto/lcg_2/chall.py
import sys from secrets import randbelow from Crypto.Util.number import getPrime FLAG = "flag{REDACTED}" MAIN_BITS = 128 INTERVAL_MODULUS = 1031 class LCG: """A Linear Congruential Generator class.""" def __init__(self, a, c, m, seed=None): self.a = a self.c = c self.m = m if seed is not None: self.seed = seed else: self.seed = randbelow(m) def next(self): self.seed = (self.a * self.seed + self.c) % self.m return self.seed def skip(self, n): if n == 0: return self.seed a_n = pow(self.a, n, self.m) try: inv_a_minus_1 = pow(self.a - 1, -1, self.m) geometric_sum = (self.c * (a_n - 1) * inv_a_minus_1) % self.m except ValueError: geometric_sum = (self.c * n) % self.m self.seed = (a_n * self.seed + geometric_sum) % self.m return self.seed def print_banner(): print(r""" ******* ******* ******** ** ** ******** /**////** **/////** **//////**/** /**/**///// /** /** ** //** ** // /** /**/** /******* /** /**/** /** /**/******* /**///** /** /**/** *****/** /**/**//// /** //** //** ** //** ////**/** /**/** /** //** //******* //******** //******* /******** // // /////// //////// /////// //////// ** ** ** **** **** ******* ******** ******* /**/** /**/**/** **/**/**////**/**///// /**////** /**/** /**/**//** ** /**/** /**/** /** /** /**/** /**/** //*** /**/******* /******* /******* /**/** /**/** //* /**/**//// /**//// /**///** ** /**/** /**/** / /**/** /** /** //** //***** //******* /** /**/** /********/** //** ///// /////// // // // //////// // // """) print("[-] TARGET: Rogue Jumper") print("[-] STATUS: Navigation Drive Unstable") print("[-] INTEL: Jump intervals controlled by aux circuit (mod 1031)") print("---------------------------------------------------------") def main(): print_banner() m_int = INTERVAL_MODULUS a_int = <redacted> c_int = <redacted> seed_int= <redacted> interval_lcg = LCG(a_int, c_int, m_int, seed_int) m_main = getPrime(MAIN_BITS) a_main = randbelow(m_main) c_main = randbelow(m_main) main_lcg = LCG(a_main, c_main, m_main) print(f"[i] Main Navigation Modulus (M): {m_main}") print(f"[i] Aux System Modulus (m): {m_int}") print("\n[SYSTEM] Tracking initiated...") QUERIES_ALLOWED = 20 for i in range(QUERIES_ALLOWED): print(f"\n--- Observation {i+1}/{QUERIES_ALLOWED} ---") print("1. Ping ship location (Observe)") print("2. Engage Tractor Beam (Predict)") choice = input("Select Action > ").strip() if choice == '1': jump_distance = interval_lcg.next() if jump_distance > 0: current_coord = main_lcg.skip(jump_distance - 1) else: current_coord = main_lcg.seed print(f"[+] Signal Detected. Coordinate: {current_coord}") print(f"[+] Jump Magnitude: UNKNOWN (Auxiliary Encrypted)") elif choice == '2': print("\n[!] TRACTOR BEAM CHARGING...") print("[!] To lock on, predict the next 3 coordinates.") try: answers = [] for _ in range(3): jump = interval_lcg.next() if jump > 0: val = main_lcg.skip(jump - 1) else: val = main_lcg.seed answers.append(val) u1 = int(input("Predicted Coord 1: ")) u2 = int(input("Predicted Coord 2: ")) u3 = int(input("Predicted Coord 3: ")) if u1 == answers[0] and u2 == answers[1] and u3 == answers[2]: print("\n[SUCCESS] Target Locked! Beam engaged.") print(f"[OUTPUT] {FLAG}") sys.exit(0) else: print("\n[FAILURE] Prediction mismatch. Target escaped into hyperspace.") sys.exit(0) except ValueError: print("[ERROR] Invalid input.") sys.exit(0) else: print("[!] Invalid command.") print("\n[SYSTEM] Tracking sensors overheated. Connection lost.") 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/BackdoorCTF/2025/crypto/Ambystoma_Mexicanum/chall.py
ctfs/BackdoorCTF/2025/crypto/Ambystoma_Mexicanum/chall.py
from cryptography.hazmat.primitives.ciphers.aead import AESGCMSIV import binascii import os KEY_SIZE = 16 NONCE_SIZE = 12 FLAG = "flag{lol_this_is_obv_not_the_flag}" KEYS = [] CIPHERTEXTS = [] CIPHERTEXTS_LEN = 1 REQUEST = "gib me flag plis" class Service: def __init__(self): self.key = self.gen_key() self.nonce = os.urandom(NONCE_SIZE) self.aead = b"" def gen_key(self): self.key = os.urandom(KEY_SIZE) return self.key def decrypt(self, ciphertext, key): try: plaintext = AESGCMSIV(key).decrypt(self.nonce, ciphertext, self.aead) return plaintext except Exception: return None usertext = "" ASCII_BANNER = """ ╔═══════════════════════════════════════════════════════════╗ ║ CRYPTIC SERVICE ║ ╚═══════════════════════════════════════════════════════════╝ ∧_∧ (・ω・) Protecting your secrets one key at a time... """ print(ASCII_BANNER) service = Service() KEYS.append(service.key.hex()) MENU_HEADER = """ ╔════════════════════════════════════╗ ║ MAIN MENU ║ ╚════════════════════════════════════╝ """ while True: print(MENU_HEADER) print("Choose an option:") print("1. rotate key") print("2. debug") print("3. push ciphertext") print("4. request flag") choice = input("Your choice: ").strip() if choice == "1": service.gen_key() KEYS.append(service.key.hex()) print("\nKey rotated.\n") elif choice == "2": print(f"\n{KEYS=}") print(f"{CIPHERTEXTS=}") print(f"nonce={service.nonce.hex()}\n") elif choice == "3": ct = input("\nEnter ciphertext (hex): ").strip() CIPHERTEXTS.append(ct) if len(CIPHERTEXTS) > CIPHERTEXTS_LEN: print("\nSorry, I cannot remember more ciphertexts :(\n") break elif choice == "4": for i in range(4): key = binascii.unhexlify(KEYS[i % len(KEYS)]) ct = binascii.unhexlify(CIPHERTEXTS[i % len(CIPHERTEXTS)]) text = service.decrypt(ct, key)[16 * i:16 * (i+1)].decode('utf-8').strip() if not text or len(text) == 0: print("why so rude :(\n") exit(0) usertext += text if usertext == REQUEST: print(f"Damn, you are something. Here is the flag: {FLAG}\n") exit(0) else: print("Request politely please!!\n") exit(0) else: print("I don't recognize this. Bye!")
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/BackdoorCTF/2025/crypto/m4candch3353/chall.py
ctfs/BackdoorCTF/2025/crypto/m4candch3353/chall.py
import math from Crypto.Hash import CMAC from Crypto.Util.number import long_to_bytes, getPrime, bytes_to_long, isPrime from Crypto.Cipher import AES from hidden import power_tower_mod, flag assert bytes_to_long(flag).bit_length() == 1263 """ power_tower_mod -> takes x, n and some data and returns . . . x x x x x mod n i.e. infinite power tower of x modulo n x^(x^(x^(x^(x.......))))) mod n There are no vulnerabilities in that function trust me!! """ class bigMac: def __init__(self, security = 1024): self.security = security self.n, self.data = self.generator() self.base = getPrime(security) * getPrime(security) self.message = bytes_to_long(flag) self.process() self.verified = False self.bits = 96 self.keys = [] for i in range(self.bits): self.keys.append(getPrime(self.bits)) print("My m4c&ch3353:", self.mac) print("My signature: ", self.getSignature(self.base)) self.next() def generator(self): chunk = 128 while 1: data = [] n = 1 for i in range(2 * self.security // chunk): data.append([getPrime(chunk), 1]) n *= data[-1][0] data.append([2, 2 * self.security - n.bit_length()]) while n.bit_length() < 2 * self.security: n *= 2 if n.bit_length() == 2 * self.security: return n, data def process(self): x = long_to_bytes(self.n) cc = CMAC.new(x[:16], ciphermod=AES) self.mac = cc.update(x).hexdigest() def getSignature(self, toSign): return (toSign * toSign) % (1 << (toSign.bit_length() - (self.security // 250))) def verify(self, N, data): self.next() if self.verified: print("ALREADY VERIFIED") return False if N.bit_length() != 2 * self.security: print("size of N is not correct.") return False prev = self.n mac = self.mac self.n = N self.process() x = 1 maxPrime = 0 for i in range(len(data)): data[i][0] = int(data[i][0]) data[i][1] = int(data[i][1]) if not isPrime(data[i][0]): self.n = prev self.mac = mac print("Gimme primesssssss onlyyyy!!") return False x *= pow(data[i][0], data[i][1]) maxPrime = max(maxPrime, data[i][0]) if self.mac != mac or x != N or maxPrime.bit_length() > self.security // 5: self.n = prev self.mac = mac print("Failed to verify.") return False print("Yayyyyyyyy! big mac got verified! for n =", prev) print("Data =", self.data) self.data = data self.n = N self.verified = True return True def next(self): self.base = power_tower_mod(self.base, self.data, self.n) def obfuscateSmall(self, m): obs = m & ((1 << self.bits) - 1) m ^= obs final = 0 for i in range(self.bits): if ((obs >> i) & 1): final += self.keys[i] return m + final def communicate(self): self.next() if self.verified: x = self.obfuscateSmall(bytes_to_long(flag)) while math.gcd(x, n) != 1: x += 1 while math.gcd(self.base, self.n) != 1: self.base += 1 print(f"Here is your obfuscated c: {pow(x, self.base, self.n)}") else: print("Verification needed.") def power_tower(self, x): self.next() if self.verified: print("WTF(What a Freak), you have n do it yourself.") return -1 return power_tower_mod(x, self.data, self.n) if __name__ == "__main__": big = bigMac() steps = 90 while steps > 0: print("1: Communicate.") print("2: Verify.") print("3: Obfuscating.") print("4: Quit.") steps -= 1 x = int(input("Choose: ")) if x == 1: big.communicate() elif x == 2: n = int(input("Give me the MY modulus : ")) *inp, = input("Enter prime factorization in format [prime1, count1]-[prime2, count2]-[...: ").split('-') data = [] for i in inp: curr = i[1:-1].split(", ") data.append([int(curr[0]), int(curr[1])]) big.verify(n, data) elif x == 3: x = int(input("Enter your message : ")) print("Here is your obfuscated message : ", big.obfuscateSmall(x)) elif x == 4: print("Goodbye.") quit() else: print("Wrong input.")
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/BackdoorCTF/2022/crypto/Fishy/chall.py
ctfs/BackdoorCTF/2022/crypto/Fishy/chall.py
from random import getrandbits as grb from Crypto.Util.number import bytes_to_long as bl modulus = pow(2, 32) s_boxes = [[grb(32) for i in range(256)] for j in range(4)] f = open("s_boxes.txt", "w") f.write(str(s_boxes)) f.close() initial_sub_keys = [ "243f6a88", "85a308d3", "13198a2e", "03707344", "a4093822", "299f31d0", "082efa98", "ec4e6c89", "452821e6", "38d01377", "be5466cf", "34e90c6c", "c0ac29b7", "c97c50dd", "3f84d5b5", "b5470917", "9216d5d9", "8979fb1b", ] key = "".join([hex(grb(32))[2:].zfill(8) for i in range(18)]) f = open("key.txt", "w") f.write(str(key)) f.close() processed_sub_keys = [ hex(int(initial_sub_keys[i], 16) ^ int(key[8 * i : 8 * (i + 1)], 16))[2:].zfill(8) for i in range(len(initial_sub_keys)) ] f = open("processed_keys.txt", "w") f.write(str(processed_sub_keys)) f.close() pt = bin(bl(b"flag{th3_f4k3_fl4g}"))[2:] while len(pt) % 64 != 0: pt = "0" + pt pt = hex(int(pt, 2))[2:].zfill(len(pt) // 16) ct = "" for i in range(len(pt) // 16): xl = pt[16 * i : 16 * i + 8] xr = pt[16 * i + 8 : 16 * i + 16] # rounds for j in range(16): tmp = xl xl = bin(int(xl, 16) ^ int(processed_sub_keys[j], 16))[2:].zfill(32) xa = int(xl[:8], 2) xb = int(xl[8:16], 2) xc = int(xl[16:24], 2) xd = int(xl[24:32], 2) xa = (s_boxes[0][xa] + s_boxes[1][xb]) % modulus xc = s_boxes[2][xc] ^ xa f_out = (xc + s_boxes[3][xd]) % modulus xl = hex(int(xr, 16) ^ f_out)[2:].zfill(8) xr = tmp xrt = xr xr = hex(int(xl, 16) ^ int(processed_sub_keys[16], 16))[2:].zfill(8) xl = hex(int(xrt, 16) ^ int(processed_sub_keys[17], 16))[2:].zfill(8) ct += xl + xr f.write(str(xl) + str(xr) + "\n") print(ct)
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/BackdoorCTF/2022/crypto/Morph/chall.py
ctfs/BackdoorCTF/2022/crypto/Morph/chall.py
#!/usr/bin/python from sage.all import * from Crypto.Util.number import bytes_to_long, long_to_bytes from Crypto.Cipher import AES from Crypto.Util.Padding import pad, unpad import random import os import hashlib from base64 import b64encode, b64decode p = 100458505468885003633418577656224333902553170484436983273607309963845847739507115860865964753239939027972338834707903941940188314348678981808910413754306718965087266944429878241410578991733762502442817585765598816431431108282071433256273345939973526837788093199292557721204590554061504359121574222368307048919809010489980961017706729222034791017130925070426893349814057145812995340991548906078333104951440614482037356443864699967124299012034397810342312642333550598174454039699165710636052240583294703998189114479917657125270697086234200442489544474659560583354052797579309573507121265302226528942789519 n = 4 def gen_random_matrix(): return matrix(GF(p), n, [random.randint(0, p) for _ in range(n*n)]) M = gen_random_matrix() def gen_matrix_singular(): while True: S = gen_random_matrix() while S.det() == 0: S = gen_random_matrix() entries = [random.randint(0, p) for _ in range(n - 1)] + [0] D = diagonal_matrix(GF(p), entries) H = S.inverse()*D*S if M*H != H*M: return H def multiply(M, H1i, H2i, M_, H1j, H2j): return (H1j*M*H2j + M_, H1i*H1j, H2i*H2j) def power(M, H1, H2, m): res = (O, I, I) x = (M, H1, H2) while m != 0: if m & 1: lt = [*res, *x] res = multiply(*res, *x) x = multiply(*x, *x) m = m >> 1 return res def encrypt(flag, shared_secret): i = 0 key = 0 for row in shared_secret: for item in row: key += item**i i += 1 key = hashlib.sha256(long_to_bytes(int(key))).digest() iv = os.urandom(16) cipher = AES.new(key, AES.MODE_CBC, iv) encrypted_text = cipher.encrypt(pad(flag, AES.block_size)) return b64encode(iv + encrypted_text).decode("utf-8") def decrypt(cipher, shared_secret): iv, enc = b64decode(cipher)[:16], b64decode(cipher)[16:] i = 0 key = 0 for row in shared_secret: for item in row: key += item**i i += 1 key = hashlib.sha256(long_to_bytes(int(key))).digest() cipher = AES.new(key, AES.MODE_CBC, iv) flag = cipher.decrypt(enc) return unpad(flag, AES.block_size) H1 = gen_matrix_singular() H2 = gen_matrix_singular() I = identity_matrix(GF(p), n) O = zero_matrix(GF(p), n) flag = b'flag{REDACTED}' x, y = random.randint(1, p - 1), random.randint(1, p - 1) A, B = power(M, H1, H2, x), power(M, H1, H2, y) assert multiply(*A, *B)[0] == multiply(*B, *A)[0] shared_secret = multiply(*A, *B)[0] cip = encrypt(flag, shared_secret) decrypted = decrypt(cip, shared_secret) assert decrypted == flag f = open('enc.txt', 'w') print(f"p={p}", file=f) print(f"n={n}", file=f) print(f"M={list(M)}", file=f) print(f"H1={list(H1)}", file=f) print(f"H2={list(H2)}", file=f) print(f"A={list(A[0])}", file=f) print(f"B={list(B[0])}", file=f) print(f"cip={cip}", file=f)
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/BackdoorCTF/2022/crypto/RandomNonsense/chall.py
ctfs/BackdoorCTF/2022/crypto/RandomNonsense/chall.py
#!/usr/bin/python from Crypto.Util.number import long_to_bytes, bytes_to_long from math import gcd import ecdsa import random import hashlib import string Curve = ecdsa.NIST384p G = Curve.generator n = Curve.order counter = 7 flag = 'REDACTED' msg_to_sign = b'''Sign me to get the flag''' KEYS = string.ascii_letters + string.digits VALUES = range(1, len(KEYS) + 1) MAP = dict(zip(KEYS, VALUES)) def encode(m: bytes) -> int: m = m.decode() enc_arr = range(1, counter + 1) if len(list(set(m))) == counter: s = set() enc_arr = [] for x in m: if x in s: continue enc_arr.append(MAP[x]) s.add(x) return sum([(-2)**i*x for i, x in enumerate(enc_arr)])%n def gen_keypair(): d = random.randint(1, n-1) Q = d*G return d, Q def inv(z: int): return pow(z, -1, n) def sign(msg, d): x = int(hashlib.sha256(long_to_bytes(encode(msg) & random.randrange(1, n - 1))).hexdigest(), 16) % 2**50 while True: k = (random.getrandbits(320) << 50) + x r = (k*G).x() if r != 0: break m = int(hashlib.sha256(msg).hexdigest(), 16) s = (inv(k)*(m + r*d)) % n return (int(r), int(s)) def verify(msg, r, s): z = int(hashlib.sha256(msg).hexdigest(), 16) VV = z*inv(s)*G + r*inv(s)*Q if (VV.x() - r)%n == 0: return True return False d, Q = gen_keypair() def main(): global counter options = '''Here are your options: [S]ign a message [V]erify a signature [P]ublic Key [Q]uit''' print(options) choice = input('choice? ') choice = choice.lower() if choice == 'p': print(Q.x(), Q.y(), n) if choice == 'v': msg = input('msg? ').encode() r = int(input('r? ')) s = int(input('s? ')) if verify(msg, r, s): print('Successful Verification') if msg == msg_to_sign: print(f'Flag: {flag}') else: print('Try Again !') if choice == 's': msg = input('msg? ').encode() r, s = sign(msg, d) if msg != msg_to_sign: print(f'r={r}, s={s}') if choice == 'q': exit(0) counter += 1 d, Q = gen_keypair() print('Welcome to my secure signature scheme !!') if __name__ == '__main__': for _ in range(50): main()
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/BackdoorCTF/2022/crypto/WhatTheCure/chall.py
ctfs/BackdoorCTF/2022/crypto/WhatTheCure/chall.py
#!/usr/bin/python3 from Crypto.Cipher import AES from Crypto.Util.Padding import pad from Crypto.Util.number import long_to_bytes from random import randint from hashlib import sha256 import json from secret import p, G, flag def points_add(P, Q): x1, y1 = P x2, y2 = Q m = (1 - x1 * x2) % p x = ((x1 + x2) * pow(m, -1, p)) % p y = (y1 * y2 * m * m) % p return (x, y) def point_scalar_mult(P, n): R = (0, 1) while (n > 0): if n & 1: R = points_add(R, P) P = points_add(P, P) n //= 2 return R if __name__ == "__main__": k = randint(1, p//2) R = point_scalar_mult(G, k) key = sha256(long_to_bytes(k)).digest() cipher = AES.new(key, AES.MODE_ECB) ct = cipher.encrypt(pad(flag, 16)).hex() out = {} out['Gx'], out['Gy'] = G out['Rx'], out['Ry'] = R out['ct'] = ct with open("out.json", "wt") as f: f.write(json.dumps(out))
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/BackdoorCTF/2022/web/S3KSU4L_INJ3C710N/chall/generate.py
ctfs/BackdoorCTF/2022/web/S3KSU4L_INJ3C710N/chall/generate.py
import random from faker import Faker from main import db,User faker=Faker() hexc=[] for i in range(16): hexc.append(hex(i)[2:]) for i in range(50): random.shuffle(hexc) passwords=[] lucky=random.randint(100,400) f=open('users.txt','w') for i in range(500): random.shuffle(hexc) passwords.append("".join(hexc)) name=faker.name() phone=faker.phone_number() if phone[0]!='+': phone='+'+phone if i == lucky: name='Adm1n_h3r3_UwU' f.write(name+'||'+passwords[i]+'||'+faker.address().replace('\n',', ')+'||'+phone+'||'+faker.email()) f.write('\n') f.close() def create_db(): f=open('users.txt','r').read() users=f.split('\n') for usr in users: if usr=='': break username=usr.split('||')[0] password=usr.split('||')[1] address=usr.split('||')[2] phone=usr.split('||')[3] email=usr.split('||')[4] user= User(name=username, age=random.randint(20,80), address=address, phone=phone, email=email, password=password) db.session.add(user) db.session.commit() create_db()
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/BackdoorCTF/2022/web/S3KSU4L_INJ3C710N/chall/main.py
ctfs/BackdoorCTF/2022/web/S3KSU4L_INJ3C710N/chall/main.py
from flask import Flask, render_template, request from flask_sqlalchemy import SQLAlchemy from helpsort import helper import random app = Flask(__name__) app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///db.sqlite' app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False db = SQLAlchemy(app) class User(db.Model): id = db.Column(db.Integer, primary_key=True) name = db.Column(db.String(64), index=True) age = db.Column(db.Integer, index=True) address = db.Column(db.String(256)) phone = db.Column(db.String(20)) email = db.Column(db.String(120)) password=db.Column(db.String(20),index=True) def to_dict(self): return { 'name': self.name, 'age': self.age, 'address': self.address, 'phone': self.phone, 'email': self.email, 'password':self.password } db.create_all() @app.route('/') def index(): return render_template('server_table.html', title='OUR VALUABLE EMPLOYEES') @app.route('/api/data') def data(): query = User.query total_filtered = query.count() col_index = request.args.get('order[0][column]') flag=1 if col_index is None: col_index=0 flag=0 col_name = request.args.get(f'columns[{col_index}][data]') users=[user.to_dict() for user in query] descending = request.args.get(f'order[0][dir]') == 'desc' try: if descending: users=sorted(users,key=lambda x:helper(x,col_name),reverse=True) else : users=sorted(users,key=lambda x:helper(x,col_name),reverse=False) except: pass start = request.args.get('start', type=int) length = request.args.get('length', type=int) users=users[start:start+length] for user in users: del user['password'] if flag==0: random.shuffle(users) return { 'data': users, 'recordsFiltered': total_filtered, 'recordsTotal': 500, 'draw': request.args.get('draw', type=int), } if __name__ == '__main__': app.run('0.0.0.0', 16052)
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/BackdoorCTF/2022/web/S3KSU4L_INJ3C710N/chall/helpsort.py
ctfs/BackdoorCTF/2022/web/S3KSU4L_INJ3C710N/chall/helpsort.py
from collections import OrderedDict def helper(data, prop, is_data=False): pr = prop.split('.') pr1= prop.split('.') count=0 for p in pr: if count == 2: return None count+=1 pr1=pr1[1:] nextprop = '.'.join(pr1) if hasattr(data, p): if nextprop=='': return getattr(data, p) return helper(getattr(data, p), nextprop, True) elif type(data) == dict or isinstance(data, OrderedDict): if nextprop=='': return data[p] ret = helper(data[p], nextprop, True) if p in data else None return ret elif type(data) == list or type(data) == tuple or type(data)==str: try: if nextprop=='': return data[int(p)] return helper(data[int(p)], nextprop, True) except (ValueError, TypeError, IndexError): return None else: return None if is_data: return data else: return None
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/FE-CTF/2023/misc/Alice_and_Bob_Flip_a_Bit_Easiest/main.py
ctfs/FE-CTF/2023/misc/Alice_and_Bob_Flip_a_Bit_Easiest/main.py
#!/usr/bin/env python3 import json, os, random, mmap from seccomp import SyscallFilter, Arg, ALLOW, EQ, MASKED_EQ, KILL random = random.SystemRandom() ROUNDS = 1000 def recv(io): fd, _ = io r = b'' while True: c = os.read(fd, 1) if c in (b'', b'\0'): break r += c if not r: return return json.loads(r) def send(io, data): _, fd = io os.write(fd, json.dumps(data).encode() + b'\0') def close(io): i, o = io os.close(i) os.close(o) def sandbox(code, name): pi, co = os.pipe() ci, po = os.pipe() pio = pi, po cio = ci, co pid = os.fork() if pid > 0: close(cio) def call(*args): send(pio, args) return recv(pio) return pid, call elif pid == 0: random.seed(0) flt = SyscallFilter(defaction=KILL) flt.add_rule(ALLOW, "write", Arg(0, EQ, co)) flt.add_rule(ALLOW, "read", Arg(0, EQ, ci)) flt.add_rule(ALLOW, "mmap", Arg(3, MASKED_EQ, mmap.MAP_ANONYMOUS, mmap.MAP_ANONYMOUS), Arg(4, EQ, 2**32-1), Arg(5, EQ, 0), ) flt.add_rule(ALLOW, "munmap") flt.add_rule(ALLOW, "brk") flt.load() exec(code) func = locals()[name] while True: args = recv(cio) if not args: break send(cio, func(*args)) sys.exit(0) else: raise RuntimeError("Could not fork") alice_pid, alice = sandbox(bytes.fromhex(input("alice> ")).decode(), "alice") bob_pid, bob = sandbox(bytes.fromhex(input("bob> ")).decode(), "bob") try: pairs = [] for _ in range(ROUNDS): token = list(os.urandom(21)) msg = alice(token) assert type(msg) == list and len(msg) <= 64 * 8 and all(x is True or x is False for x in msg) if msg: msg[random.randrange(0, len(msg))] ^= True pairs.append((token, msg)) random.shuffle(pairs) for alice_token, msg in pairs: bob_token = bob(msg) assert alice_token == bob_token with open("flag", "r") as flag: print(flag.read()) finally: os.kill(alice_pid, 9) os.kill(bob_pid, 9)
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/FE-CTF/2023/misc/Alice_and_Bob_Flip_a_Bit_Easier/main.py
ctfs/FE-CTF/2023/misc/Alice_and_Bob_Flip_a_Bit_Easier/main.py
#!/usr/bin/env python3 import json, os, random, mmap from seccomp import SyscallFilter, Arg, ALLOW, EQ, MASKED_EQ, KILL random = random.SystemRandom() ROUNDS = 1000 def recv(io): fd, _ = io r = b'' while True: c = os.read(fd, 1) if c in (b'', b'\0'): break r += c if not r: return return json.loads(r) def send(io, data): _, fd = io os.write(fd, json.dumps(data).encode() + b'\0') def close(io): i, o = io os.close(i) os.close(o) def sandbox(code, name): pi, co = os.pipe() ci, po = os.pipe() pio = pi, po cio = ci, co pid = os.fork() if pid > 0: close(cio) def call(*args): send(pio, args) return recv(pio) return pid, call elif pid == 0: random.seed(0) flt = SyscallFilter(defaction=KILL) flt.add_rule(ALLOW, "write", Arg(0, EQ, co)) flt.add_rule(ALLOW, "read", Arg(0, EQ, ci)) flt.add_rule(ALLOW, "mmap", Arg(3, MASKED_EQ, mmap.MAP_ANONYMOUS, mmap.MAP_ANONYMOUS), Arg(4, EQ, 2**32-1), Arg(5, EQ, 0), ) flt.add_rule(ALLOW, "munmap") flt.add_rule(ALLOW, "brk") flt.load() exec(code) func = locals()[name] while True: args = recv(cio) if not args: break send(cio, func(*args)) sys.exit(0) else: raise RuntimeError("Could not fork") alice_pid, alice = sandbox(bytes.fromhex(input("alice> ")).decode(), "alice") bob_pid, bob = sandbox(bytes.fromhex(input("bob> ")).decode(), "bob") try: pairs = [] for _ in range(ROUNDS): token = list(os.urandom(62)) msg = alice(token) assert type(msg) == list and len(msg) <= 64 * 8 and all(x is True or x is False for x in msg) if msg: msg[random.randrange(0, len(msg))] ^= True pairs.append((token, msg)) random.shuffle(pairs) for alice_token, msg in pairs: bob_token = bob(msg) assert alice_token == bob_token with open("flag", "r") as flag: print(flag.read()) finally: os.kill(alice_pid, 9) os.kill(bob_pid, 9)
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/FE-CTF/2023/misc/Asteroids_Cadet/course-correction.py
ctfs/FE-CTF/2023/misc/Asteroids_Cadet/course-correction.py
#!/usr/bin/env python3 from pwn import * from Crypto.Cipher import AES WARP_COORDINATES = b'00000000-0000-0000-0000-000000000000' HOST = args.get('HOST', 'localhost') PORT = int(args.get('PORT', 1337)) sock = remote(HOST, PORT) def course_correction(asteroids): '''We need to make this function run faster, sir''' size = int((len(asteroids)*8)**(1/3)) for n in iters.count(1): for directions in iters.product('WASDQE', repeat=n): x = y = z = size // 2 for m in iters.cycle(directions): match m: case 'W': y += 1 case 'A': x -= 1 case 'S': y -= 1 case 'D': x += 1 case 'Q': z -= 1 case 'E': z += 1 if x < 0 or x >= size or \ y < 0 or y >= size or \ z < 0 or z >= size: return ''.join(directions) if x == y == z == size // 2: break i, j = divmod(x + (y + z * size) * size, 8) if asteroids[i] & 1<<j: break def asteroids(): while True: for _ in range(5): print(sock.recvline().decode(), end='') numb = sock.u32() data = sock.recvn(numb) sock.sendlineafter(b'Ready, captain?', b'Alright let\'s go in') key = sock.recvn(32) print(sock.recvline().decode(), end='') aes = AES.new(key, AES.MODE_CTR, nonce=b'') asteroids = aes.decrypt(data) course = course_correction(asteroids) print(f'Correcting course: {course}') sock.sendlineafter(b'Course correction> ', course.encode()) print() if __name__ == '__main__': try: sock.sendlineafter(b'Warp coordinates> ', WARP_COORDINATES) asteroids() except EOFError: print('its_been_an_honor.gif')
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/FE-CTF/2023/misc/Alice_and_Bob_Flip_a_Bit_Easy/main.py
ctfs/FE-CTF/2023/misc/Alice_and_Bob_Flip_a_Bit_Easy/main.py
#!/usr/bin/env python3 import json, os, random, mmap from seccomp import SyscallFilter, Arg, ALLOW, EQ, MASKED_EQ, KILL random = random.SystemRandom() ROUNDS = 1000 def recv(io): fd, _ = io r = b'' while True: c = os.read(fd, 1) if c in (b'', b'\0'): break r += c if not r: return return json.loads(r) def send(io, data): _, fd = io os.write(fd, json.dumps(data).encode() + b'\0') def close(io): i, o = io os.close(i) os.close(o) def sandbox(code, name): pi, co = os.pipe() ci, po = os.pipe() pio = pi, po cio = ci, co pid = os.fork() if pid > 0: close(cio) def call(*args): send(pio, args) return recv(pio) return pid, call elif pid == 0: random.seed(0) flt = SyscallFilter(defaction=KILL) flt.add_rule(ALLOW, "write", Arg(0, EQ, co)) flt.add_rule(ALLOW, "read", Arg(0, EQ, ci)) flt.add_rule(ALLOW, "mmap", Arg(3, MASKED_EQ, mmap.MAP_ANONYMOUS, mmap.MAP_ANONYMOUS), Arg(4, EQ, 2**32-1), Arg(5, EQ, 0), ) flt.add_rule(ALLOW, "munmap") flt.add_rule(ALLOW, "brk") flt.load() exec(code) func = locals()[name] while True: args = recv(cio) if not args: break send(cio, func(*args)) sys.exit(0) else: raise RuntimeError("Could not fork") alice_pid, alice = sandbox(bytes.fromhex(input("alice> ")).decode(), "alice") bob_pid, bob = sandbox(bytes.fromhex(input("bob> ")).decode(), "bob") try: pairs = [] for _ in range(ROUNDS): token = list(os.urandom(63)) msg = alice(token) assert type(msg) == list and len(msg) <= 64 * 8 and all(x is True or x is False for x in msg) if msg: msg[random.randrange(0, len(msg))] ^= True pairs.append((token, msg)) random.shuffle(pairs) for alice_token, msg in pairs: bob_token = bob(msg) assert alice_token == bob_token with open("flag", "r") as flag: print(flag.read()) finally: os.kill(alice_pid, 9) os.kill(bob_pid, 9)
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/FE-CTF/2023/pwn/Crackstation_Level_3/crackstation.py
ctfs/FE-CTF/2023/pwn/Crackstation_Level_3/crackstation.py
#!/usr/bin/env python3 # coding: utf-8 # 外国人想法真是不一样 import base64 import ctypes import importlib import os import struct import sys import zlib from Crypto.Cipher import AES from hashlib import md5 assert sys.maxsize > 9876543210, 'Can\'t run on a steam engine :(' assert sys.platform[0] == 'l', 'Software update required' sys.excepthook=lambda*_:os._exit(0) FLAGS = [False, True, True, False, True] NOPE = [] flags = {} def flag(y): def flag(x, z): try: 0/0 except Exception as e: flag = e.__traceback__.tb_frame.f_back.f_lineno flags[flag] = flag = f'{x}{y}{z}' return Flag(flag) return flag class Flag(str): __getattr__ = flag('.') __matmul__ = flag('@') __sub__ = flag('-') __floordiv__ = flag('!') FLAG,FLAG = os.path.splitext(os.path.basename(sys.modules['__main__'].__file__))[::-1] while True: try: importlib.import_module(FLAG) ; break except NameError as flag: _, flag, _ = flag.args[0].split("'") globals()['__builtins__'][flag] = Flag(flag) flag = ctypes.CDLL(None).mmap flag.restype = ctypes.c_long flag.argtypes = (ctypes.c_long,) * 6 def galf(p): return ctypes.cast(p, ctypes.c_voidp).value Flag = ctypes.cast(flag(0, 1<<32, 3, 16418, -1, 0), ctypes.POINTER(ctypes.c_ubyte)) fLag = ctypes.cast(flag(0, 1<<33, 7, 16418, -1, 0), ctypes.POINTER(ctypes.c_ubyte)) flAg = ctypes.cast(flag(0, 1<< 6, 3, 16418, -1, 0), ctypes.POINTER(ctypes.c_uint32)) flaG = ctypes.cast(flag(0, 1<< 7, 3, 16418, -1, 0), ctypes.POINTER(ctypes.c_voidp)) FLAG = flag(0, 1<< 7, 7, 16418, -1, 0) aes = AES.new(md5(open(__file__, 'rb').read()).digest(), AES.MODE_ECB) for i, (_, x) in enumerate(sorted(flags.items()), 0x2ab): a, b = x.split('!') o = int(bytes(a, 'utf8').hex(), 16) % 7 x = int(aes.decrypt(bytes.fromhex(b)).hex(), 16) y = [o] for _ in range(5 + (o==6)): y.append(x & 0xff) ; x >>= 8 xs = y[o==6:] for j, x in enumerate(xs): Flag[i*6+j] = x flAg[15] = 0x1002 def in_(i): return Flag[i & 0xffffffff] if i > 0xfff else os._exit(1) def out(i, x): Flag[i & 0xffffffff] = x & 0xff if i > 0xfff else os._exit(1) def IN_(i): return flAg[i & 0xf] def OUT(i, x): flAg[i & 0xf] = x def inn(a): x=in_;return x(a),x(a+1)&15,x(a+1)>>4,x(a+2)|x(a+3)<<8|x(a+4)<<16|x(a+5)<<24 def flag(truth): res = {} while truth[0] != 0: n = 0 i = 0 while True: b = truth.pop(0) n |= (b & 0x7f) << i * 7 i += 1 if not b & 0x80: break off = n - 2 if truth[0] == 1: truth.pop(0) n = 0 i = 0 while True: b = truth.pop(0) n |= (b & 0x7f) << i * 7 i += 1 if not b & 0x80: break sz = n - 2 rec = (sz, flag(truth)) else: rec = flag(truth) res[off] = rec truth.pop(0) return res def recurse(addr, sig, n): if isinstance(sig, tuple): sz, sig = sig while recurse(addr, sig, n): addr += sz else: ret = False for off, sub in sig.items(): x = ( Flag[addr + off] | Flag[addr + off + 1] << 8 | Flag[addr + off + 2] << 16 | Flag[addr + off + 3] << 24 | Flag[addr + off + 4] << 32 | Flag[addr + off + 5] << 40 | Flag[addr + off + 6] << 48 | Flag[addr + off + 7] << 56 ) if 0x1000 <= min(x, x + n) < 2**32: recurse(min(x, x + n), sub, n) Flag[addr + off] = (x + n) & 0xff Flag[addr + off + 1] = ((x + n) >> 8) & 0xff Flag[addr + off + 2] = ((x + n) >> 16) & 0xff Flag[addr + off + 3] = ((x + n) >> 24) & 0xff Flag[addr + off + 4] = ((x + n) >> 32) & 0xff Flag[addr + off + 5] = ((x + n) >> 40) & 0xff Flag[addr + off + 6] = ((x + n) >> 48) & 0xff Flag[addr + off + 7] = ((x + n) >> 56) & 0xff ret = True return ret _syscall = ctypes.CDLL(None).syscall _syscall.restype = ctypes.c_long _syscall.argtypes = (ctypes.c_long,) * 6 def do_syscall(nr, argsaddr): argsaddr &= 0xffffffff flag = do_syscall.flag.get(nr, {}) recurse(argsaddr, flag, galf(Flag)) args = struct.unpack('<QQQQQQ', bytes(Flag[argsaddr : argsaddr + 6 * 8])) ret = _syscall(nr, *args) recurse(argsaddr, flag, -galf(Flag)) return ret do_syscall.flag=flag(bytearray(zlib.decompress(base64.b85decode('''c$`&KTW^g)6x\ }nQ6yF1K+)v^~LZoqxxIKu72fPU4PDB(*e?Ub%q18LuCOo(#+J<tpT12W^)l#%XBZwD?AaMziw64L6w\ f6odagwvwUbAQI*?VTbIX)JNU_-n}ju)_@uwlxEBQ`SjQsYEY=44bXDUs2b9RnL1J4}d-OZ<4i1lUBX\ (lS|O64X<4wW+Xanw<-qj?oMq&5Ws=Ma&hMje03v3_+QbHJXc@d73j{aY0&SA#9OWT8t_VdL$5KNsJC\ ;Dd;lfEr+dutwi1`#8!i^fnN(-r~R!5+W^}L+oX}rU|W=JRosU0cGwQsPL1TjcENTdvImwAUI5z*+eZ\ be?N9tc2f-nij0zo~h@oN)NeOv{@k$4%B2*J<s69b;#^!6Otz)2`>>S~|O*JG1a3B{LzDURrE;$@WBU\ uyS3INMqCGQMf-43M7sp}5oJAvG_i5{zV&)j{s^1yhnxju#-aq-9OzMt@fv8PUN>lp*jZLt@Oza+eJd\ TFmM{>JemlDC|BM|e;8K=^1=pIq!l<nXrTvr7m1#abAkaM1WyIOxBzq3=$=xF1>z<R^8%tmJQ}NB1Xe\ _irEvJVb?rBEn%pF`>lke5tuIhRVI}qQYFI*MmM{f}<21BUJhDNbuQLs|f1jmUPn8r+nBSnmWy_vtDJ\ j<aH*hCvWh)Y@fWtOdyR6H~Igc5q`}c&|)iHWA^ndg|zx)*Ef=N(zaS#_OP9)9fVtiPHVl3CA$ed>`x\ zK+MZ;uDf&Wp4+H7<dL;v4JQzr6lvS}TdsrUvm?OQ#OoV<f^RKKq(kd+xzw*d7$#`p|duk)UnJgsjQ8\ -~;rNeUN9~&oviv''')))) def magic(*some_arguments): def less_magic(some_function): global FLAG @ctypes.CFUNCTYPE(None, ctypes.c_long) def another_function(x): try: # XXX: Here be dragons? y = (x - 5 - galf(fLag)) // 2 OUT(15, y) some_function() OUT(0, 0) except: os._exit(0) sys.argv.append(another_function) # Won't work without... ¯\_(ツ)_/¯ flag = b''.join(( b'\x55\x48\x89\xe5\x48\x83\xe4\xf0\x48\xb8', another_function, b'\xff\xd0\xc9', *some_arguments, b'\xc3', )) ctypes.memmove(FLAG, flag, len(flag)) FLAG += len(flag) return ctypes.cast(FLAG - len(flag), ctypes.CFUNCTYPE(None)) return less_magic def more_magic(normal_amount_of_magic): cigam_fo_tnuoma_lamron = galf(normal_amount_of_magic) x = 0 while True: if cigam_fo_tnuoma_lamron == flaG[x]: break x += 1 return b'\xe8\x00\x00\x00\x00\x5f\x41\xff\x55' + bytes([x<<3]) def this(x, xs, force=False): assert not FLAGS[3] or x % 6 == 0 if fLag[2*x] and not force: return xs = xs.ljust(12, b'\x90') assert len(xs) == 12 y = x * 2 + galf(fLag) ctypes.memmove(y, xs, len(xs)) @magic( b'\x48\xbb' + flAg, b'\x49\xbc' + Flag, b'\x49\xbd' + flaG, b'\x49\xbe' + fLag, b'\x49\x8d\x86\x04\x20\x00\x00', b'\xff\xe0', ) def entry(): pass # lol wat? def p32(x): return struct.pack('<I', x % 2**32) @magic(b'\x48\x83\x2c\x24\x0a') def thing(): x = IN_(15) if FLAGS[0]: this(x, more_magic(device), force=True) return o, a, b, c = inn(x) o_, a_, b_, c_ = inn(x + 6) if a: wa = b'\x89\x43' + bytes([a*4]) else: wa = b'' y1 = x + 6 y2 = None magic = more_magic(device) if o == 0: magic = more_magic(action) elif o == 5 and a == b == 15: y1 = y = (x + 6 + c) % 2**32 z = (6 + c) * 2 - 5 magic = b'\xe9' + p32(z) elif (o == 5 and (a, b, c) == (14, 15, 3) and o_ == 5 and a_ == b_ == 15) and FLAGS[1]: ra = x + 9 y1 += 6 y2 = y = (x + 6 + 6 + c_) % 2**32 z = (6 + 6 + c_) * 2 - 7 - 5 magic = b'\xc7\x43\x38' + p32(ra) + b'\xe8' + p32(z) this(x + 6, b'\xeb\x0a') elif o == 5 and (a, b, c) == (15, 14, 3) and FLAGS[1]: magic = b'\xc3' elif (o == 5 and (a, b, c) == (13, 13, 2**32-4) and o_ == 3 and a_ != 15 and b_ == 13 and c_ == 3) and FLAGS[2]: magic = b'\x83\x6b\x34\x04\x8b\x43' + bytes([a_*4]) + b'\x50' y1 += 6 this(x + 6, b'\xeb\x0a') elif (o == 2 and a != 15 and b == 13 and c == 3 and o_ == 5 and (a_, b_, c_) == (13, 13, 4)) and FLAGS[2]: magic = b'\x83\x43\x34\x04\x58\x89\x43' + bytes([a*4]) y1 += 6 this(x + 6, b'\xeb\x0a') elif (o, a, b, c) == (4, 0, 0, 3): magic = more_magic(gadget) elif 15 not in (a, b): if o == 1: y2 = y = (x + 6 + c) % 2**32 z = (6 + c) * 2 - 3 - 3 - 6 magic = ( b'\x8b\x43' + bytes([a*4]) + b'\x3b\x43' + bytes([b*4]) + b'\x0f\x82' + p32(z) ) elif o == 5: magic = ( b'\x8b\x43' + bytes([b*4]) + b'\x05' + p32(c) + wa ) elif o == 2: magic = b'\x8b\x43' + bytes([b*4]) + b'\x41' if c == 0: magic += b'\x0f\xb6' elif c == 1: magic += b'\x0f\xb7' else: magic += b'\x8b' magic += b'\x04\x04\x89\x43' + bytes([a*4]) elif o == 3: magic = ( b'\x8b\x43' + bytes([b*4]) + b'\x8b\x4b' + bytes([a*4]) ) if c == 0: magic += b'\x41\x88' elif c == 1: magic += b'\x66\x41\x89' else: magic += b'\x41\x89' magic += b'\x0c\x04' elif o == 4: magic = b'\x8b\x43' + bytes([a*4]) magic += [ b'\x03\x43' + bytes([b*4]), b'\x2b\x43' + bytes([b*4]), b'\xf7\x63' + bytes([b*4]), b'\x31\xd2\xf7\x73' + bytes([b*4]), b'\x31\xd2\xf7\x73' + bytes([b*4]) + b'\x92', b'\x23\x43' + bytes([b*4]), b'\x0b\x43' + bytes([b*4]), b'\x33\x43' + bytes([b*4]), b'\x8b\x4b' + bytes([b*4]) + b'\xd3\xe0', b'\x8b\x4b' + bytes([b*4]) + b'\xd3\xe8', b'\xf7\xd8', b'\xf7\xd0', ][c] magic += b'\x89\x43' + bytes([a*4]) this(x, magic, force=True) for y in (y1, y2): if y: this(y, more_magic(thing)) @magic(b'\x8b\x43\x3c\x48\x01\xc0\x4c\x01\xf0\x48\x89\x04\x24') def device(): x = IN_(15) o, a, b, c = inn(x) OUT(15, x + 6) if o == 0: OUT(a, do_syscall(IN_(b) + c, IN_(a))) elif o == 1: if IN_(a) < IN_(b): OUT(15, IN_(15) + c) elif o == 2: y = IN_(b) x = in_(y) if c > 0: x |= in_(y + 1) << 8 if c > 1: x |= in_(y + 2) << 16 x |= in_(y + 3) << 24 OUT(a, x) elif o == 3: x = IN_(a) y = IN_(b) out(y, x) if c > 0: out(y + 1, x >> 8) if c > 1: out(y + 2, x >> 16) out(y + 3, x >> 24) elif o == 4: r = [ lambda a, b: a + b, lambda a, b: a - b, lambda a, b: a * b, lambda a, b: a // b, lambda a, b: a % b, lambda a, b: a & b, lambda a, b: a | b, lambda a, b: a ^ b, lambda a, b: a << b, lambda a, b: a >> b, lambda a, b: -a, lambda a, b: ~a, ][c](IN_(a), IN_(b)) OUT(a, r) elif o == 5: OUT(a, IN_(b) + c) else: os._exit(0) this(IN_(15), more_magic(thing)) @magic(b'\xcc') def gadget(): os._exit(0) @magic() def action(): _, a, b, c = inn(IN_(15)) nr = IN_(b) + c if nr in NOPE: OUT(a, 0xffffefff) else: OUT(a, do_syscall(nr, IN_(a))) flaG[0] = galf(thing) flaG[1] = galf(device) flaG[2] = galf(gadget) if not FLAGS[4]: flaG[3] = galf(action) this(0x1002, more_magic(thing)) entry()
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/FE-CTF/2023/pwn/Crackstation_Level_3/server.py
ctfs/FE-CTF/2023/pwn/Crackstation_Level_3/server.py
#!/usr/bin/env -S python3 -u import sys import re import os import signal import tempfile ok = re.compile(r'^[a-z0-9_.-]+@[a-z0-9_.-]+\s+//\s+[a-f0-9]{32}$') print('Send hash list, then end with a blank line') sys.stdout.flush() lines = ['import crackstation'] for lino, line in enumerate(sys.stdin.buffer.raw, 1): line = line.strip().decode() if not line: break if not ok.match(line): print(f'Format error on line {lino}:') print(line) exit(1) lines.append(line) if len(lines) <= 1: print('No tickee, no washee.') exit(1) with tempfile.TemporaryDirectory() as rundir: with open(rundir + '/runme.py', 'w') as f: for line in lines: f.write(line + '\n') os.symlink(os.getcwd() + '/crackstation.py', rundir + '/crackstation.py') if os.fork() == 0: signal.alarm(60) argv = ['python3', '-u', rundir + '/runme.py'] os.execvp(argv[0], argv) else: os.wait()
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/FE-CTF/2023/pwn/Crackstation_Level_1/crackstation.py
ctfs/FE-CTF/2023/pwn/Crackstation_Level_1/crackstation.py
#!/usr/bin/env python3 # coding: utf-8 # 外国人想法真是不一样 import base64 import ctypes import importlib import os import struct import sys import zlib from Crypto.Cipher import AES from hashlib import md5 assert sys.maxsize > 9876543210, 'Can\'t run on a steam engine :(' assert sys.platform[0] == 'l', 'Software update required' sys.excepthook=lambda*_:os._exit(0) FLAGS = [False, True, True, False, False] NOPE = [] flags = {} def flag(y): def flag(x, z): try: 0/0 except Exception as e: flag = e.__traceback__.tb_frame.f_back.f_lineno flags[flag] = flag = f'{x}{y}{z}' return Flag(flag) return flag class Flag(str): __getattr__ = flag('.') __matmul__ = flag('@') __sub__ = flag('-') __floordiv__ = flag('!') FLAG,FLAG = os.path.splitext(os.path.basename(sys.modules['__main__'].__file__))[::-1] while True: try: importlib.import_module(FLAG) ; break except NameError as flag: _, flag, _ = flag.args[0].split("'") globals()['__builtins__'][flag] = Flag(flag) flag = ctypes.CDLL(None).mmap flag.restype = ctypes.c_long flag.argtypes = (ctypes.c_long,) * 6 def galf(p): return ctypes.cast(p, ctypes.c_voidp).value Flag = ctypes.cast(flag(0, 1<<32, 3, 16418, -1, 0), ctypes.POINTER(ctypes.c_ubyte)) fLag = ctypes.cast(flag(0, 1<<33, 7, 16418, -1, 0), ctypes.POINTER(ctypes.c_ubyte)) flAg = ctypes.cast(flag(0, 1<< 6, 3, 16418, -1, 0), ctypes.POINTER(ctypes.c_uint32)) flaG = ctypes.cast(flag(0, 1<< 7, 3, 16418, -1, 0), ctypes.POINTER(ctypes.c_voidp)) FLAG = flag(0, 1<< 7, 7, 16418, -1, 0) aes = AES.new(md5(open(__file__, 'rb').read()).digest(), AES.MODE_ECB) for i, (_, x) in enumerate(sorted(flags.items()), 0x2ab): a, b = x.split('!') o = int(bytes(a, 'utf8').hex(), 16) % 7 x = int(aes.decrypt(bytes.fromhex(b)).hex(), 16) y = [o] for _ in range(5 + (o==6)): y.append(x & 0xff) ; x >>= 8 xs = y[o==6:] for j, x in enumerate(xs): Flag[i*6+j] = x flAg[15] = 0x1002 def in_(i): return Flag[i & 0xffffffff] if i > 0xfff else os._exit(1) def out(i, x): Flag[i & 0xffffffff] = x & 0xff if i > 0xfff else os._exit(1) def IN_(i): return flAg[i & 0xf] def OUT(i, x): flAg[i & 0xf] = x def inn(a): x=in_;return x(a),x(a+1)&15,x(a+1)>>4,x(a+2)|x(a+3)<<8|x(a+4)<<16|x(a+5)<<24 def flag(truth): res = {} while truth[0] != 0: n = 0 i = 0 while True: b = truth.pop(0) n |= (b & 0x7f) << i * 7 i += 1 if not b & 0x80: break off = n - 2 if truth[0] == 1: truth.pop(0) n = 0 i = 0 while True: b = truth.pop(0) n |= (b & 0x7f) << i * 7 i += 1 if not b & 0x80: break sz = n - 2 rec = (sz, flag(truth)) else: rec = flag(truth) res[off] = rec truth.pop(0) return res def recurse(addr, sig, n): if isinstance(sig, tuple): sz, sig = sig while recurse(addr, sig, n): addr += sz else: ret = False for off, sub in sig.items(): x = ( Flag[addr + off] | Flag[addr + off + 1] << 8 | Flag[addr + off + 2] << 16 | Flag[addr + off + 3] << 24 | Flag[addr + off + 4] << 32 | Flag[addr + off + 5] << 40 | Flag[addr + off + 6] << 48 | Flag[addr + off + 7] << 56 ) if 0x1000 <= min(x, x + n) < 2**32: recurse(min(x, x + n), sub, n) Flag[addr + off] = (x + n) & 0xff Flag[addr + off + 1] = ((x + n) >> 8) & 0xff Flag[addr + off + 2] = ((x + n) >> 16) & 0xff Flag[addr + off + 3] = ((x + n) >> 24) & 0xff Flag[addr + off + 4] = ((x + n) >> 32) & 0xff Flag[addr + off + 5] = ((x + n) >> 40) & 0xff Flag[addr + off + 6] = ((x + n) >> 48) & 0xff Flag[addr + off + 7] = ((x + n) >> 56) & 0xff ret = True return ret _syscall = ctypes.CDLL(None).syscall _syscall.restype = ctypes.c_long _syscall.argtypes = (ctypes.c_long,) * 6 def do_syscall(nr, argsaddr): argsaddr &= 0xffffffff flag = do_syscall.flag.get(nr, {}) recurse(argsaddr, flag, galf(Flag)) args = struct.unpack('<QQQQQQ', bytes(Flag[argsaddr : argsaddr + 6 * 8])) ret = _syscall(nr, *args) recurse(argsaddr, flag, -galf(Flag)) return ret do_syscall.flag=flag(bytearray(zlib.decompress(base64.b85decode('''c$`&KTW^g)6x\ }nQ6yF1K+)v^~LZoqxxIKu72fPU4PDB(*e?Ub%q18LuCOo(#+J<tpT12W^)l#%XBZwD?AaMziw64L6w\ f6odagwvwUbAQI*?VTbIX)JNU_-n}ju)_@uwlxEBQ`SjQsYEY=44bXDUs2b9RnL1J4}d-OZ<4i1lUBX\ (lS|O64X<4wW+Xanw<-qj?oMq&5Ws=Ma&hMje03v3_+QbHJXc@d73j{aY0&SA#9OWT8t_VdL$5KNsJC\ ;Dd;lfEr+dutwi1`#8!i^fnN(-r~R!5+W^}L+oX}rU|W=JRosU0cGwQsPL1TjcENTdvImwAUI5z*+eZ\ be?N9tc2f-nij0zo~h@oN)NeOv{@k$4%B2*J<s69b;#^!6Otz)2`>>S~|O*JG1a3B{LzDURrE;$@WBU\ uyS3INMqCGQMf-43M7sp}5oJAvG_i5{zV&)j{s^1yhnxju#-aq-9OzMt@fv8PUN>lp*jZLt@Oza+eJd\ TFmM{>JemlDC|BM|e;8K=^1=pIq!l<nXrTvr7m1#abAkaM1WyIOxBzq3=$=xF1>z<R^8%tmJQ}NB1Xe\ _irEvJVb?rBEn%pF`>lke5tuIhRVI}qQYFI*MmM{f}<21BUJhDNbuQLs|f1jmUPn8r+nBSnmWy_vtDJ\ j<aH*hCvWh)Y@fWtOdyR6H~Igc5q`}c&|)iHWA^ndg|zx)*Ef=N(zaS#_OP9)9fVtiPHVl3CA$ed>`x\ zK+MZ;uDf&Wp4+H7<dL;v4JQzr6lvS}TdsrUvm?OQ#OoV<f^RKKq(kd+xzw*d7$#`p|duk)UnJgsjQ8\ -~;rNeUN9~&oviv''')))) def magic(*some_arguments): def less_magic(some_function): global FLAG @ctypes.CFUNCTYPE(None, ctypes.c_long) def another_function(x): try: # XXX: Here be dragons? y = (x - 5 - galf(fLag)) // 2 OUT(15, y) some_function() OUT(0, 0) except: os._exit(0) sys.argv.append(another_function) # Won't work without... ¯\_(ツ)_/¯ flag = b''.join(( b'\x55\x48\x89\xe5\x48\x83\xe4\xf0\x48\xb8', another_function, b'\xff\xd0\xc9', *some_arguments, b'\xc3', )) ctypes.memmove(FLAG, flag, len(flag)) FLAG += len(flag) return ctypes.cast(FLAG - len(flag), ctypes.CFUNCTYPE(None)) return less_magic def more_magic(normal_amount_of_magic): cigam_fo_tnuoma_lamron = galf(normal_amount_of_magic) x = 0 while True: if cigam_fo_tnuoma_lamron == flaG[x]: break x += 1 return b'\xe8\x00\x00\x00\x00\x5f\x41\xff\x55' + bytes([x<<3]) def this(x, xs, force=False): assert not FLAGS[3] or x % 6 == 0 if fLag[2*x] and not force: return xs = xs.ljust(12, b'\x90') assert len(xs) == 12 y = x * 2 + galf(fLag) ctypes.memmove(y, xs, len(xs)) @magic( b'\x48\xbb' + flAg, b'\x49\xbc' + Flag, b'\x49\xbd' + flaG, b'\x49\xbe' + fLag, b'\x49\x8d\x86\x04\x20\x00\x00', b'\xff\xe0', ) def entry(): pass # lol wat? def p32(x): return struct.pack('<I', x % 2**32) @magic(b'\x48\x83\x2c\x24\x0a') def thing(): x = IN_(15) if FLAGS[0]: this(x, more_magic(device), force=True) return o, a, b, c = inn(x) o_, a_, b_, c_ = inn(x + 6) if a: wa = b'\x89\x43' + bytes([a*4]) else: wa = b'' y1 = x + 6 y2 = None magic = more_magic(device) if o == 0: magic = more_magic(action) elif o == 5 and a == b == 15: y1 = y = (x + 6 + c) % 2**32 z = (6 + c) * 2 - 5 magic = b'\xe9' + p32(z) elif (o == 5 and (a, b, c) == (14, 15, 3) and o_ == 5 and a_ == b_ == 15) and FLAGS[1]: ra = x + 9 y1 += 6 y2 = y = (x + 6 + 6 + c_) % 2**32 z = (6 + 6 + c_) * 2 - 7 - 5 magic = b'\xc7\x43\x38' + p32(ra) + b'\xe8' + p32(z) this(x + 6, b'\xeb\x0a') elif o == 5 and (a, b, c) == (15, 14, 3) and FLAGS[1]: magic = b'\xc3' elif (o == 5 and (a, b, c) == (13, 13, 2**32-4) and o_ == 3 and a_ != 15 and b_ == 13 and c_ == 3) and FLAGS[2]: magic = b'\x83\x6b\x34\x04\x8b\x43' + bytes([a_*4]) + b'\x50' y1 += 6 this(x + 6, b'\xeb\x0a') elif (o == 2 and a != 15 and b == 13 and c == 3 and o_ == 5 and (a_, b_, c_) == (13, 13, 4)) and FLAGS[2]: magic = b'\x83\x43\x34\x04\x58\x89\x43' + bytes([a*4]) y1 += 6 this(x + 6, b'\xeb\x0a') elif (o, a, b, c) == (4, 0, 0, 3): magic = more_magic(gadget) elif 15 not in (a, b): if o == 1: y2 = y = (x + 6 + c) % 2**32 z = (6 + c) * 2 - 3 - 3 - 6 magic = ( b'\x8b\x43' + bytes([a*4]) + b'\x3b\x43' + bytes([b*4]) + b'\x0f\x82' + p32(z) ) elif o == 5: magic = ( b'\x8b\x43' + bytes([b*4]) + b'\x05' + p32(c) + wa ) elif o == 2: magic = b'\x8b\x43' + bytes([b*4]) + b'\x41' if c == 0: magic += b'\x0f\xb6' elif c == 1: magic += b'\x0f\xb7' else: magic += b'\x8b' magic += b'\x04\x04\x89\x43' + bytes([a*4]) elif o == 3: magic = ( b'\x8b\x43' + bytes([b*4]) + b'\x8b\x4b' + bytes([a*4]) ) if c == 0: magic += b'\x41\x88' elif c == 1: magic += b'\x66\x41\x89' else: magic += b'\x41\x89' magic += b'\x0c\x04' elif o == 4: magic = b'\x8b\x43' + bytes([a*4]) magic += [ b'\x03\x43' + bytes([b*4]), b'\x2b\x43' + bytes([b*4]), b'\xf7\x63' + bytes([b*4]), b'\x31\xd2\xf7\x73' + bytes([b*4]), b'\x31\xd2\xf7\x73' + bytes([b*4]) + b'\x92', b'\x23\x43' + bytes([b*4]), b'\x0b\x43' + bytes([b*4]), b'\x33\x43' + bytes([b*4]), b'\x8b\x4b' + bytes([b*4]) + b'\xd3\xe0', b'\x8b\x4b' + bytes([b*4]) + b'\xd3\xe8', b'\xf7\xd8', b'\xf7\xd0', ][c] magic += b'\x89\x43' + bytes([a*4]) this(x, magic, force=True) for y in (y1, y2): if y: this(y, more_magic(thing)) @magic(b'\x8b\x43\x3c\x48\x01\xc0\x4c\x01\xf0\x48\x89\x04\x24') def device(): x = IN_(15) o, a, b, c = inn(x) OUT(15, x + 6) if o == 0: OUT(a, do_syscall(IN_(b) + c, IN_(a))) elif o == 1: if IN_(a) < IN_(b): OUT(15, IN_(15) + c) elif o == 2: y = IN_(b) x = in_(y) if c > 0: x |= in_(y + 1) << 8 if c > 1: x |= in_(y + 2) << 16 x |= in_(y + 3) << 24 OUT(a, x) elif o == 3: x = IN_(a) y = IN_(b) out(y, x) if c > 0: out(y + 1, x >> 8) if c > 1: out(y + 2, x >> 16) out(y + 3, x >> 24) elif o == 4: r = [ lambda a, b: a + b, lambda a, b: a - b, lambda a, b: a * b, lambda a, b: a // b, lambda a, b: a % b, lambda a, b: a & b, lambda a, b: a | b, lambda a, b: a ^ b, lambda a, b: a << b, lambda a, b: a >> b, lambda a, b: -a, lambda a, b: ~a, ][c](IN_(a), IN_(b)) OUT(a, r) elif o == 5: OUT(a, IN_(b) + c) else: os._exit(0) this(IN_(15), more_magic(thing)) @magic(b'\xcc') def gadget(): os._exit(0) @magic() def action(): _, a, b, c = inn(IN_(15)) nr = IN_(b) + c if nr in NOPE: OUT(a, 0xffffefff) else: OUT(a, do_syscall(nr, IN_(a))) flaG[0] = galf(thing) flaG[1] = galf(device) flaG[2] = galf(gadget) if not FLAGS[4]: flaG[3] = galf(action) this(0x1002, more_magic(thing)) entry()
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/FE-CTF/2023/pwn/Crackstation_Level_1/lolcat.py
ctfs/FE-CTF/2023/pwn/Crackstation_Level_1/lolcat.py
#!/usr/bin/env python3 import crackstation webertanya@yahoo.com // cacd5501925ccf1736814dca112a57a2 stephanie71@cherry-carter.info // bd5428030cc01ccb2fdd52f533b24808 benjaminconrad@gmail.com // c980664827796011e26607b8b4dabd5e klarson@gmail.com // b9d956700f8f80986e613ef969821274 pbuck@black.com // bb5eb9acbcb1d5d4ea79d59eb346bc1c alexander97@hotmail.com // bc908d5a3ca0bd64769fb3591c6851e9 xjones@hotmail.com // e50dd15c60d7dcd8e22aa3820bee9c3a jacksonchad@yahoo.com // bc937d73be4a1ce3353756dfd6781c8a mirandamichael@burgess-bauer.com // ba4ee3f6c94cd25378115eaf4cf2a1c3 anthony10@yahoo.com // bf233f0747aa595fef926e26dfc1c027 todddonald@terrell-dean.info // e17f7bdf25e20662fdf3d363ba0aff32 dmitchell@yahoo.com // f689711a109e321b825e8718d939b0eb allenbrianna@yahoo.com // a5419cfcdd73292fd651342c177855d8 benjamin51@bush-price.com // e47c9c1caf71f6038096735ba25602d8 dennisnicholas@gmail.com // af6def404be6f31f6965199794febb33 qfrederick@hotmail.com // e154707ed669b7fdfcfefaa5a5df8773 amymelendez@hotmail.com // fc84e666fbfb018423838d57fe91cca9 christopher70@lopez-morrison.biz // bfc00b232d9ee6bdb237fd246b9c3cc8 monica20@white.com // f4f90406e2d1d5787128bda20a4465c7 mhaley@hotmail.com // eb60daef0c6da1a30c771504aadf8150 hsims@mcknight-griffin.com // cdc096a4f94c749de13b048d3570efb2 goodwinjodi@yahoo.com // febd9b5240e8a8ee36f5259085e7fb59 claudiamartinez@camacho.com // ee8e4da20ee95dd6eb542e15dc3aa835 rodriguezandrew@hotmail.com // f82a39e7b0844790477c76160b87e77d christy63@davis.info // fcdd6d05b12b7e4da1844413bb53b4d3 ufritz@williams-nicholson.org // c1c053978c7cd13cba6e8896bb80e146 mike37@quinn-green.com // d7a8c2ded3eb9ef11d9d19da1cf52cbb jameshowell@gmail.com // f4c179764c42ec6b0d13e78a86bd5006 teresalee@fisher.com // e4b48ea960c2f49e8adfce62a25a2da5 steven68@hotmail.com // b8a185f3c0f79aed17676a9a9a930d37 wallison@yahoo.com // de7f4d737cd1a0b8a0188055a3530b0a shane86@gmail.com // a5d27afe4e4cc57dfd2b3c66d471d487 oturner@yahoo.com // cccc1b160d028ff53c52a88c5e479e62 billyschneider@gmail.com // b79207cc15c43dba7505e0ae37c48264 marissa36@wilson.net // f54499733a4fd1c51f3f120b010ce1dd ksimpson@gmail.com // aeb210252c9c929267226b4b1aff55a2 kenneth28@hotmail.com // bb871b42437e6e1eabc7678f66b4c9b5 mariaharmstrong@shelton.com // a9a8fdd55872c6da0695be2b8c27d7e8 kristen19@gmail.com // c537c924d8926ff09a91c833fdf6c3b1 aaronnorman@yahoo.com // d029a366f807efd533fcd304c3629dcc gregory06@russell-barber.com // bb0d1d94ce448e5f60e62b9224ddccf2 smithheather@walker.org // bf71e922134fb217978ccc3682dfab9f brennanphyllis@gmail.com // cb3a9c71598b3d7b4ef6c576de81d937 davidcontreras@harris.com // c9219ae705ab472dec158395ac9f7c41 pgreen@jones.com // f7872ac94a504c7ccbbe1b46f7af51a4 hansonsean@lewis.com // d61de34895dccc1ff7e6e2be6dbb6329 deborahthomas@hotmail.com // ca4b82f406cbc068c12173deea43294a deborah51@hotmail.com // c71ba848ddbcf653eb3a18bab87f212c eric70@bailey.com // d86d4696e47a281596f34ac50906c656 emilyrobinson@gmail.com // eb3d0d0dbb4cab3c8c7e6709130f9299 tom72@gmail.com // a72ca39b314862dad263c140cd2000e1 kinggary@hotmail.com // cfbcc809c8cd482484127765a9333a08 amber36@gmail.com // b41cc414116467c952cdc37fb90ade16 santosdavid@baker.com // eb3865efa1d4ff0d7771825f9b4f1c04 suzannemcguire@yahoo.com // cf2705bf188b89a1f9fd61b48c737cd6 adavis@gmail.com // cd0e7f8450ffdf6fe542b7af8a440c1c isaac93@hotmail.com // e1a5628f7b593de3c449615f118b737d thompsonelizabeth@burch.com // aa4294e02e88cf504003e28f04f78fa4 codonnell@hotmail.com // bce9c8c49451870ee59622c98771c486 tanya24@perez.com // ecd8ed648786ebe07cf2d4f718bda6fe kristinakline@gmail.com // a5e6ca8141c437261985a1805b68e654 williamsjoseph@fitzgerald.com // f0f26f23584e985e146027865943e775 laura74@gmail.com // c82b1f641c9677e215d17fe3ae34f3a1 ryan45@johnson.com // b5e51bb7c16174cc429a39038ed38b98 bankserika@roberts.com // a6abba6c270e57bffadb06720e33c7dd whiteheadadrian@gmail.com // fb48f1a7a6fa8f8c3a8d9c5a07e10af2 flowersjoshua@roach-black.org // fbf93dce3338f52fbef27cae1fc9e0df craig99@gmail.com // feaa94d5ca37f8752a4e6dda9db98cf6 theresa56@yahoo.com // c440db0e2d1371f96d1d3152deb554bd nicholasgross@hotmail.com // a2205e436ec6d43b27372455704c327a cchung@mendoza.com // ab503a5376cd2c6636ceff5eac686825 kristina05@gmail.com // e0c488d84aa55547d8d053a1de369bf6 padillakristin@manning.org // fadfe20034e6a0b1b74090ed37b49f47 jamesconway@white.com // b63bf6a8ab4093557cdc874e88cde3e7 cwilliams@clark.com // a59d50813e334fa33dd7893e235e312a ebuck@hotmail.com // ae794d14a8701f0eccb3fa094d5615d3 oharris@hotmail.com // ba95a8f5c2cf35013da0e9a04acb599a dsmith@gmail.com // ee0c08d1a4a7eb5a8a7715aebee3ddf9 vicki85@hotmail.com // efecbbbdc9013cecafabb698a54c4c1a usanchez@hotmail.com // de925b351d8086fefbe9fa7d7c955239 obennett@gmail.com // dd8c4a1a9aac7ff6f7af3df0c1994e1f hmyers@harris.info // a0d394de6f77f75465c3926d4ffce567 john73@kemp.com // c38fd562726c96c279dddf973777cae5 elliottmelissa@gmail.com // f832453f819ec34895f8798471dace14 wstone@hotmail.com // d58e2838c1c92d56d94b475759c04b2c stevensimpson@sosa.com // a9cfdb05834197fbb852accb2d84535e russellgarcia@yahoo.com // da49aaf04258e1a46e26bbdd5616c9e8 kimberly09@mendoza.com // d72fb4a1879f3ce3bfac761e230d7749 guzmankelly@lopez.info // a6019e1c884c523cc3226adf4ee5fc16 elaine12@gmail.com // d614b4962a4194dfc9101a18b15dc65e anne33@yahoo.com // c812986704f813b3b78062f5cc552839 carol00@torres.com // e3edef8df8fbf51c55bd94a4f032547f stephanieboyd@hamilton.info // d6a5ede0e028b8f4f29a4aed84fbec39 marklewis@hotmail.com // cd6e661233c9a8307bcdf3ed95b9dd2a laura08@yahoo.com // aa8ba17855b1528e1eb5801a03cde558 wcline@gmail.com // ded94f5e8c5c783250d518169d04867e ruizwarren@gmail.com // bc6ed4674abdb36fb3428b92b4ad777d chadgraham@baxter.com // ca8656a809d7731938d46cb801dfbed0 rblackburn@delacruz.com // aa258494882c4590e2d79f854b8db78a rowealexander@mitchell.info // ed900b3b6666bc61ef7bd1cbdee7ea04 whitneybailey@gmail.com // b31e574c99fcfa4b1f8c06dcb25452fb wongmichael@green-walker.com // b4da032b499f9417a3c7b79da721a2c3 iodonnell@hall-kim.com // a97a2604bf19bc71efdffedb840fa0cf nicholas55@gmail.com // c3c67463a89f295c48eea139e5e3ae91 gibsonlisa@francis.com // ee044a6afee603de856da76f2f22d6f1 thomasmoreno@olson.com // debd21b5d77b1f5cad7112933a95825d mblanchard@davidson.info // d536c0166ce047bc76e41cd1e1d67edb james62@pierce.biz // a3281a04ed9801158cc0ce1edab62fb1 taylorjennifer@hotmail.com // e66c09c539e1555f85451c2e049dc7a7 benjaminwilliams@gmail.com // ac411e6a30b3e352d373dda09cac3cb4 jmartin@gmail.com // feda7365a68bbb6da8d67fc9cf595eea monicagarcia@hotmail.com // daae10219fb03063ead95161eec77975 dominique01@yahoo.com // c9caa0ffbe648b108aa76d6d7f8c1a69 melissa58@moore.com // a959939938beaa3ad3a28fc258cad861 jgarza@reyes.com // d7aa5ed2d85293b7e02f36c954c63d3c richardsalan@mason-hodges.info // a9b6762a3cc7f6c06b538f2b8822ebea qhenry@baker.com // d10131c844ca74dd9d75352d2577889b schwartzmelinda@sanders.com // e92e687c9c6ce9250862adfe46362b93 wrightdiane@robertson.net // c365c517e514f91b56c01efe76a47ba3 awilson@gmail.com // e198050830fad81f292977e30bca53a1 michaelbates@mckee-peterson.com // a6bb4a2a61a397c2f05938983aa479bb amorrison@hotmail.com // fe2a720110874c97adcd4acf16bdee6c vhill@yahoo.com // db4b875ee8062d1b4c28b1e34c92d047 mitchellbill@yahoo.com // bc3b54aec35872e48864b961c223b477 jacksonbrittany@yahoo.com // c9ba7f93d685f9be68dffddae551b534 martinerica@gmail.com // cbdc689c6bb6c7c21d143359a6e4c94d obennett@benton-gray.com // d492c06a8efd5d9db836774234153148 carriegonzalez@yahoo.com // c759f74d6ce814ec5eacc4fa6fe51279 tommy88@barton.com // ee55197a9663535b91063d38b6393d42 steven18@hotmail.com // c59c1cfdb4af299f86bcc6560f01ca6d fernandobarber@gmail.com // cf7f15e4a546e280b4a8f30b3483aea8 uferguson@mcdonald-medina.com // f9740aba88ecefc42a469c49ac51221e pburton@hotmail.com // c9061f0f7294ec28fbcf4e92ab36e144 cooperjoseph@conner.biz // ce0dfadbcc66d7d903b47bcece77c206 znorton@molina-rodriguez.biz // f53f409a00f0c68b21bde5b1e052da30 nicholeguerrero@yahoo.com // cbb23a2e254cf6710527e7b9d26884a2
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/FE-CTF/2023/pwn/Crackstation_Level_1/server.py
ctfs/FE-CTF/2023/pwn/Crackstation_Level_1/server.py
#!/usr/bin/env -S python3 -u import sys import re import os import signal import tempfile ok = re.compile(r'^[a-z0-9_.-]+@[a-z0-9_.-]+\s+//\s+[a-f0-9]{32}$') print('Send hash list, then end with a blank line') sys.stdout.flush() lines = ['import crackstation'] for lino, line in enumerate(sys.stdin.buffer.raw, 1): line = line.strip().decode() if not line: break if not ok.match(line): print(f'Format error on line {lino}:') print(line) exit(1) lines.append(line) if len(lines) <= 1: print('No tickee, no washee.') exit(1) with tempfile.TemporaryDirectory() as rundir: with open(rundir + '/runme.py', 'w') as f: for line in lines: f.write(line + '\n') os.symlink(os.getcwd() + '/crackstation.py', rundir + '/crackstation.py') if os.fork() == 0: signal.alarm(60) argv = ['python3', '-u', rundir + '/runme.py'] os.execvp(argv[0], argv) else: os.wait()
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/FE-CTF/2023/pwn/Crackstation_Warmup/crackstation.py
ctfs/FE-CTF/2023/pwn/Crackstation_Warmup/crackstation.py
#!/usr/bin/env python3 # coding: utf-8 # 外国人想法真是不一样 import base64 import ctypes import importlib import os import struct import sys import zlib from Crypto.Cipher import AES from hashlib import md5 assert sys.maxsize > 9876543210, 'Can\'t run on a steam engine :(' assert sys.platform[0] == 'l', 'Software update required' sys.excepthook=lambda*_:os._exit(0) FLAGS = [False, True, False, False, False] NOPE = [] flags = {} def flag(y): def flag(x, z): try: 0/0 except Exception as e: flag = e.__traceback__.tb_frame.f_back.f_lineno flags[flag] = flag = f'{x}{y}{z}' return Flag(flag) return flag class Flag(str): __getattr__ = flag('.') __matmul__ = flag('@') __sub__ = flag('-') __floordiv__ = flag('!') FLAG,FLAG = os.path.splitext(os.path.basename(sys.modules['__main__'].__file__))[::-1] while True: try: importlib.import_module(FLAG) ; break except NameError as flag: _, flag, _ = flag.args[0].split("'") globals()['__builtins__'][flag] = Flag(flag) flag = ctypes.CDLL(None).mmap flag.restype = ctypes.c_long flag.argtypes = (ctypes.c_long,) * 6 def galf(p): return ctypes.cast(p, ctypes.c_voidp).value Flag = ctypes.cast(flag(0, 1<<32, 3, 16418, -1, 0), ctypes.POINTER(ctypes.c_ubyte)) fLag = ctypes.cast(flag(0, 1<<33, 7, 16418, -1, 0), ctypes.POINTER(ctypes.c_ubyte)) flAg = ctypes.cast(flag(0, 1<< 6, 3, 16418, -1, 0), ctypes.POINTER(ctypes.c_uint32)) flaG = ctypes.cast(flag(0, 1<< 7, 3, 16418, -1, 0), ctypes.POINTER(ctypes.c_voidp)) FLAG = flag(0, 1<< 7, 7, 16418, -1, 0) aes = AES.new(md5(open(__file__, 'rb').read()).digest(), AES.MODE_ECB) for i, (_, x) in enumerate(sorted(flags.items()), 0x2ab): a, b = x.split('!') o = int(bytes(a, 'utf8').hex(), 16) % 7 x = int(aes.decrypt(bytes.fromhex(b)).hex(), 16) y = [o] for _ in range(5 + (o==6)): y.append(x & 0xff) ; x >>= 8 xs = y[o==6:] for j, x in enumerate(xs): Flag[i*6+j] = x flAg[15] = 0x1002 def in_(i): return Flag[i & 0xffffffff] if i > 0xfff else os._exit(1) def out(i, x): Flag[i & 0xffffffff] = x & 0xff if i > 0xfff else os._exit(1) def IN_(i): return flAg[i & 0xf] def OUT(i, x): flAg[i & 0xf] = x def inn(a): x=in_;return x(a),x(a+1)&15,x(a+1)>>4,x(a+2)|x(a+3)<<8|x(a+4)<<16|x(a+5)<<24 def flag(truth): res = {} while truth[0] != 0: n = 0 i = 0 while True: b = truth.pop(0) n |= (b & 0x7f) << i * 7 i += 1 if not b & 0x80: break off = n - 2 if truth[0] == 1: truth.pop(0) n = 0 i = 0 while True: b = truth.pop(0) n |= (b & 0x7f) << i * 7 i += 1 if not b & 0x80: break sz = n - 2 rec = (sz, flag(truth)) else: rec = flag(truth) res[off] = rec truth.pop(0) return res def recurse(addr, sig, n): if isinstance(sig, tuple): sz, sig = sig while recurse(addr, sig, n): addr += sz else: ret = False for off, sub in sig.items(): x = ( Flag[addr + off] | Flag[addr + off + 1] << 8 | Flag[addr + off + 2] << 16 | Flag[addr + off + 3] << 24 | Flag[addr + off + 4] << 32 | Flag[addr + off + 5] << 40 | Flag[addr + off + 6] << 48 | Flag[addr + off + 7] << 56 ) if 0x1000 <= min(x, x + n) < 2**32: recurse(min(x, x + n), sub, n) Flag[addr + off] = (x + n) & 0xff Flag[addr + off + 1] = ((x + n) >> 8) & 0xff Flag[addr + off + 2] = ((x + n) >> 16) & 0xff Flag[addr + off + 3] = ((x + n) >> 24) & 0xff Flag[addr + off + 4] = ((x + n) >> 32) & 0xff Flag[addr + off + 5] = ((x + n) >> 40) & 0xff Flag[addr + off + 6] = ((x + n) >> 48) & 0xff Flag[addr + off + 7] = ((x + n) >> 56) & 0xff ret = True return ret _syscall = ctypes.CDLL(None).syscall _syscall.restype = ctypes.c_long _syscall.argtypes = (ctypes.c_long,) * 6 def do_syscall(nr, argsaddr): argsaddr &= 0xffffffff flag = do_syscall.flag.get(nr, {}) recurse(argsaddr, flag, galf(Flag)) args = struct.unpack('<QQQQQQ', bytes(Flag[argsaddr : argsaddr + 6 * 8])) ret = _syscall(nr, *args) recurse(argsaddr, flag, -galf(Flag)) return ret do_syscall.flag=flag(bytearray(zlib.decompress(base64.b85decode('''c$`&KTW^g)6x\ }nQ6yF1K+)v^~LZoqxxIKu72fPU4PDB(*e?Ub%q18LuCOo(#+J<tpT12W^)l#%XBZwD?AaMziw64L6w\ f6odagwvwUbAQI*?VTbIX)JNU_-n}ju)_@uwlxEBQ`SjQsYEY=44bXDUs2b9RnL1J4}d-OZ<4i1lUBX\ (lS|O64X<4wW+Xanw<-qj?oMq&5Ws=Ma&hMje03v3_+QbHJXc@d73j{aY0&SA#9OWT8t_VdL$5KNsJC\ ;Dd;lfEr+dutwi1`#8!i^fnN(-r~R!5+W^}L+oX}rU|W=JRosU0cGwQsPL1TjcENTdvImwAUI5z*+eZ\ be?N9tc2f-nij0zo~h@oN)NeOv{@k$4%B2*J<s69b;#^!6Otz)2`>>S~|O*JG1a3B{LzDURrE;$@WBU\ uyS3INMqCGQMf-43M7sp}5oJAvG_i5{zV&)j{s^1yhnxju#-aq-9OzMt@fv8PUN>lp*jZLt@Oza+eJd\ TFmM{>JemlDC|BM|e;8K=^1=pIq!l<nXrTvr7m1#abAkaM1WyIOxBzq3=$=xF1>z<R^8%tmJQ}NB1Xe\ _irEvJVb?rBEn%pF`>lke5tuIhRVI}qQYFI*MmM{f}<21BUJhDNbuQLs|f1jmUPn8r+nBSnmWy_vtDJ\ j<aH*hCvWh)Y@fWtOdyR6H~Igc5q`}c&|)iHWA^ndg|zx)*Ef=N(zaS#_OP9)9fVtiPHVl3CA$ed>`x\ zK+MZ;uDf&Wp4+H7<dL;v4JQzr6lvS}TdsrUvm?OQ#OoV<f^RKKq(kd+xzw*d7$#`p|duk)UnJgsjQ8\ -~;rNeUN9~&oviv''')))) def magic(*some_arguments): def less_magic(some_function): global FLAG @ctypes.CFUNCTYPE(None, ctypes.c_long) def another_function(x): try: # XXX: Here be dragons? y = (x - 5 - galf(fLag)) // 2 OUT(15, y) some_function() OUT(0, 0) except: os._exit(0) sys.argv.append(another_function) # Won't work without... ¯\_(ツ)_/¯ flag = b''.join(( b'\x55\x48\x89\xe5\x48\x83\xe4\xf0\x48\xb8', another_function, b'\xff\xd0\xc9', *some_arguments, b'\xc3', )) ctypes.memmove(FLAG, flag, len(flag)) FLAG += len(flag) return ctypes.cast(FLAG - len(flag), ctypes.CFUNCTYPE(None)) return less_magic def more_magic(normal_amount_of_magic): cigam_fo_tnuoma_lamron = galf(normal_amount_of_magic) x = 0 while True: if cigam_fo_tnuoma_lamron == flaG[x]: break x += 1 return b'\xe8\x00\x00\x00\x00\x5f\x41\xff\x55' + bytes([x<<3]) def this(x, xs, force=False): assert not FLAGS[3] or x % 6 == 0 if fLag[2*x] and not force: return xs = xs.ljust(12, b'\x90') assert len(xs) == 12 y = x * 2 + galf(fLag) ctypes.memmove(y, xs, len(xs)) @magic( b'\x48\xbb' + flAg, b'\x49\xbc' + Flag, b'\x49\xbd' + flaG, b'\x49\xbe' + fLag, b'\x49\x8d\x86\x04\x20\x00\x00', b'\xff\xe0', ) def entry(): pass # lol wat? def p32(x): return struct.pack('<I', x % 2**32) @magic(b'\x48\x83\x2c\x24\x0a') def thing(): x = IN_(15) if FLAGS[0]: this(x, more_magic(device), force=True) return o, a, b, c = inn(x) o_, a_, b_, c_ = inn(x + 6) if a: wa = b'\x89\x43' + bytes([a*4]) else: wa = b'' y1 = x + 6 y2 = None magic = more_magic(device) if o == 0: magic = more_magic(action) elif o == 5 and a == b == 15: y1 = y = (x + 6 + c) % 2**32 z = (6 + c) * 2 - 5 magic = b'\xe9' + p32(z) elif (o == 5 and (a, b, c) == (14, 15, 3) and o_ == 5 and a_ == b_ == 15) and FLAGS[1]: ra = x + 9 y1 += 6 y2 = y = (x + 6 + 6 + c_) % 2**32 z = (6 + 6 + c_) * 2 - 7 - 5 magic = b'\xc7\x43\x38' + p32(ra) + b'\xe8' + p32(z) this(x + 6, b'\xeb\x0a') elif o == 5 and (a, b, c) == (15, 14, 3) and FLAGS[1]: magic = b'\xc3' elif (o == 5 and (a, b, c) == (13, 13, 2**32-4) and o_ == 3 and a_ != 15 and b_ == 13 and c_ == 3) and FLAGS[2]: magic = b'\x83\x6b\x34\x04\x8b\x43' + bytes([a_*4]) + b'\x50' y1 += 6 this(x + 6, b'\xeb\x0a') elif (o == 2 and a != 15 and b == 13 and c == 3 and o_ == 5 and (a_, b_, c_) == (13, 13, 4)) and FLAGS[2]: magic = b'\x83\x43\x34\x04\x58\x89\x43' + bytes([a*4]) y1 += 6 this(x + 6, b'\xeb\x0a') elif (o, a, b, c) == (4, 0, 0, 3): magic = more_magic(gadget) elif 15 not in (a, b): if o == 1: y2 = y = (x + 6 + c) % 2**32 z = (6 + c) * 2 - 3 - 3 - 6 magic = ( b'\x8b\x43' + bytes([a*4]) + b'\x3b\x43' + bytes([b*4]) + b'\x0f\x82' + p32(z) ) elif o == 5: magic = ( b'\x8b\x43' + bytes([b*4]) + b'\x05' + p32(c) + wa ) elif o == 2: magic = b'\x8b\x43' + bytes([b*4]) + b'\x41' if c == 0: magic += b'\x0f\xb6' elif c == 1: magic += b'\x0f\xb7' else: magic += b'\x8b' magic += b'\x04\x04\x89\x43' + bytes([a*4]) elif o == 3: magic = ( b'\x8b\x43' + bytes([b*4]) + b'\x8b\x4b' + bytes([a*4]) ) if c == 0: magic += b'\x41\x88' elif c == 1: magic += b'\x66\x41\x89' else: magic += b'\x41\x89' magic += b'\x0c\x04' elif o == 4: magic = b'\x8b\x43' + bytes([a*4]) magic += [ b'\x03\x43' + bytes([b*4]), b'\x2b\x43' + bytes([b*4]), b'\xf7\x63' + bytes([b*4]), b'\x31\xd2\xf7\x73' + bytes([b*4]), b'\x31\xd2\xf7\x73' + bytes([b*4]) + b'\x92', b'\x23\x43' + bytes([b*4]), b'\x0b\x43' + bytes([b*4]), b'\x33\x43' + bytes([b*4]), b'\x8b\x4b' + bytes([b*4]) + b'\xd3\xe0', b'\x8b\x4b' + bytes([b*4]) + b'\xd3\xe8', b'\xf7\xd8', b'\xf7\xd0', ][c] magic += b'\x89\x43' + bytes([a*4]) this(x, magic, force=True) for y in (y1, y2): if y: this(y, more_magic(thing)) @magic(b'\x8b\x43\x3c\x48\x01\xc0\x4c\x01\xf0\x48\x89\x04\x24') def device(): x = IN_(15) o, a, b, c = inn(x) OUT(15, x + 6) if o == 0: OUT(a, do_syscall(IN_(b) + c, IN_(a))) elif o == 1: if IN_(a) < IN_(b): OUT(15, IN_(15) + c) elif o == 2: y = IN_(b) x = in_(y) if c > 0: x |= in_(y + 1) << 8 if c > 1: x |= in_(y + 2) << 16 x |= in_(y + 3) << 24 OUT(a, x) elif o == 3: x = IN_(a) y = IN_(b) out(y, x) if c > 0: out(y + 1, x >> 8) if c > 1: out(y + 2, x >> 16) out(y + 3, x >> 24) elif o == 4: r = [ lambda a, b: a + b, lambda a, b: a - b, lambda a, b: a * b, lambda a, b: a // b, lambda a, b: a % b, lambda a, b: a & b, lambda a, b: a | b, lambda a, b: a ^ b, lambda a, b: a << b, lambda a, b: a >> b, lambda a, b: -a, lambda a, b: ~a, ][c](IN_(a), IN_(b)) OUT(a, r) elif o == 5: OUT(a, IN_(b) + c) else: os._exit(0) this(IN_(15), more_magic(thing)) @magic(b'\xcc') def gadget(): os._exit(0) @magic() def action(): _, a, b, c = inn(IN_(15)) nr = IN_(b) + c if nr in NOPE: OUT(a, 0xffffefff) else: OUT(a, do_syscall(nr, IN_(a))) flaG[0] = galf(thing) flaG[1] = galf(device) flaG[2] = galf(gadget) if not FLAGS[4]: flaG[3] = galf(action) this(0x1002, more_magic(thing)) entry()
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/FE-CTF/2023/pwn/Crackstation_Warmup/runme.py
ctfs/FE-CTF/2023/pwn/Crackstation_Warmup/runme.py
#!/usr/bin/env python3 import crackstation ethanking@yahoo.com // d3886f99adaf4a39da593981374810f9 robinsoncarol@jacobson.com // ec17a2968f8ce5f644e38b4a5f448f05 edwingray@gmail.com // bae55dc19b3ec29415ebc258ae145b6f cindy00@hernandez.com // af2331661cc7943c71e4089b6dc53195 ethan34@gmail.com // e9f488c6aa9ff7e59e4d845c146db203 amy76@brooks-garrett.net // f1a04d5f448507639a284007e7891c60 ralphtodd@fischer.net // bd0f823ce632cee6776a10b6ae82c7ff deleoncharles@yahoo.com // fd42678b52f9ad012e3795e128d64c83 hannah22@gmail.com // adf610c6966498be26bbc0b0f85a312a kimberly92@hotmail.com // c877027b4493ca1a0884cfad350b52ed mjohnson@hotmail.com // a7ad55d23f09a0a3f45597737468ff3a stephenflores@gmail.com // c3848b1c173e651cc085d14bc3238dd4 kmorton@jones.com // fae8bc9ed6f128d17c45a88dddc353ee castillolorraine@yahoo.com // b9760dc8dd41a559afbff6f4037c9597 abigailwilliams@johnson.biz // aaaea1b011b36a660619c6ce4e2573c2 craigwillis@carter-nelson.org // e26708c7b4fb93d1c1f4a8994d280f44 scott46@hotmail.com // be3cc8995845291850190d0512e1561c mcdonaldelizabeth@cross.com // eb4d45bc4072780bc6e56a981da139bb ecobb@roy.com // a6e9b754bf1cc607d487ca05e178e7ee fredsanders@hotmail.com // ef8b8fcaf81e4a521964a04f48408310 jennifer10@ford.com // e3a3cfae180024f0cd2f7efd6134a6ba joseph15@hotmail.com // ead12d4653485123d596551b4f4f012b kathleen80@yahoo.com // aa408f24c7db7c70fcabb76d9d995de9 guerrerocourtney@yahoo.com // f5469a7d119354740fea12e99e204815 kweaver@rodriguez-mendoza.com // b47b74dc19b8e293ca6e5225bf42f4a7 grosskatrina@hotmail.com // f8fc2f1954d8cc4847ed8b7eb3ef599e smithkelli@rosales-steele.com // f163ab01c053d6c02a54bab254a02d86 thumphrey@gmail.com // ddc6568eddce7868abee444f4f959667 tasha49@morris-hogan.biz // f578d5917993a84653f554b5484bd6e7 hernandezmegan@shaw.com // ab316c66e933b5d44fcd647a3f3bf26d ingramvictor@gmail.com // ab66266a8ff93800c0859067dcb5eb53 gstewart@bartlett.com // fd004ae1605a0bfae74114749398d0f7 tommy21@cook.com // bee95cb6b69ca704772ce025e84ec6cf fgordon@yahoo.com // e6c60b47b038a4f5feab4114d29e249b annasoto@hotmail.com // d275d5eb64dfc33d18e9a85ae4a43cb2 stephanie08@robertson-norris.org // f25ad6cb3c94228d45d5894d00614bca christophergoodman@hotmail.com // d929585157c9726ae5fe095d9472a8e2 hlamb@gmail.com // b8dec462e0a1ccb397c6c963bfae1752 david26@hotmail.com // cbfab5357be465ea3f3b7dbf0fb69847 lutzdustin@johnson.org // c41afec14f6c66de43bb398a86103f2e orozcochristopher@harris-moore.com // bd72335a29d4e04a590464fbb1649834 rebecca80@poole-smith.com // c952d66f5114466a6f9e0c04fdf01683 victoriasalazar@adams-jackson.org // fd345755355584c1ea9115e60bf40bfa ireynolds@hotmail.com // f4cb9d5d51f7d87d092bb61bc28e56aa jaredthomas@yahoo.com // d88da4c221b32e6c23ea05eba8af54de ukemp@castro-sanchez.net // b197bbdded7a392917338d90deb1ad83 zadams@chandler.info // f7e37978ce14adc033782d9026b8d7e5 debra86@gmail.com // c6673843e33095deae71d5482be57c0c michaelnguyen@gmail.com // f5a4a8f171433cb6545c5480f2bb2596 shirley91@price.com // eba9e36bfcf55f74b074519792a7c781 simpsonseth@hotmail.com // c415a5e9cd5ed2f764533fb90063d5b7 normanjames@hernandez-berry.com // fc88a07c39d45e675650d0fc33d6c72f patrickcameron@watson.com // eb06041fee14230ed714c303819b403e ecampos@hanna-moore.com // bb2546d2692ff700dc6c87cf7bdf4d42 krista30@yahoo.com // a9e749f42d739535e70344807a327cca alexis92@gmail.com // a177fb2c7eef880db68f985eaf551074 aallen@gmail.com // b22ffad59afbeecbdc9cb3bb417dade4 vickicarter@bowers.net // e80191fe8ad4faae0c662c36bfa27cb2 ethompson@gmail.com // ad642253cc5c41d2adfdb29f1186894c markwilliams@yahoo.com // ea614f864d58087754d3a045ea79b69c sean91@bell.info // dddfc2fa3c2567cfa21ab4d20e79f454 lindsey13@yahoo.com // ffcb098acd5af4345a21ab3c6ded2c3d stephanie60@yahoo.com // fb41c4bccd7c65537f605c07da868b47 ulong@johnson.com // f58ca921ff3e6dcc88b2926af6fd87c7 moorematthew@buckley.biz // dd703f75ccd424aea719f81233381953 pedrogardner@yahoo.com // fd2c95a706afbf5a2221281199eac08a swatson@yahoo.com // a2194f9af7dbc6a35796caf2559eb488 mgutierrez@rodriguez.net // bc0c66256ce5ccda1eb17eaa34fc184e morgankristin@franklin-lang.com // ecc12c0acc30b79fab3ec97e60d79480 juliehouston@yahoo.com // a78f70c502d458a91c548f18cdeed664 emccall@bauer.com // b3a9694b23d9d1f813d705240ce4ee5e hmartin@fowler.net // b6d70142a0b8b49dab1d42da4b71d290 clarkmarcus@castaneda.com // e5c2dd3f00418065ed386729971c954f efarmer@yahoo.com // cf9d3e21c33250391db45ac72e2dcb2b garnerisabel@hotmail.com // b585a70a07662773996fac8fc9dacf0b brobinson@richardson.net // b9047506337f3ebee479b9b174e7ff5e reginald57@erickson.org // e8f50568f064bcdbab5aad9b6b7ef411 jasminedennis@hotmail.com // ce32ba3b8fec468c45c8405213121161 kevin61@gmail.com // c98afbfdc11213406d9a094cd60bdfbd taylor31@larson.com // f2aee4b669515ab112fa33137bfe24ad hlee@gmail.com // a56e37d166eed440658d94363e3dc899 ashley58@gray.com // b02a33da1dd7c544c98d8c3d56e11223 lblackburn@anderson.com // a89d7f158741a752626172b6dcc32230 sara88@hotmail.com // b45d2effb731fa6cdfeaa68c9670e137 david32@morrow-vaughn.com // d91e85ca1e2874ea8c6885e09e826451 ghernandez@whitaker-livingston.biz // ed6eb394b767243774872bce31f5a2f1 christineadkins@hamilton.org // f40cbb71212b6c07e949d24c3251b64b williamssamantha@gordon-phillips.org // fa766b4448460d85a8906d17a291e4b0 brownjared@myers.biz // bc0c4bae504e28fee785dd5d46c1f684 edwinnelson@clark.com // e1d00c81e2c65722bdaf082c4b9e19b0 jocelynadams@davis.com // b87c0c6a6e97382ba843c5ec44e9ff13 nrodriguez@gmail.com // cf984d8b51974b14fbcdcac5c3e44a00 davidsnyder@gonzalez-wilson.org // d5d87951726455c5b99613d709c88c68 hannahcox@holt-munoz.biz // dedd3fd02529b31c3b36b48dac9002d1 campbellkristy@duran-miller.info // ef034c1a2edf4c1d5b6affed74220520 tramirez@dean.biz // fece07794cc1f761346be9c1d50037e9 perezelizabeth@gmail.com // f33f3c2e514f1a464e32cf1023823ff1 vicki87@yahoo.com // f730e7a26905bb28b83d71d5b7b6ddf9 daniel53@hotmail.com // e3ab844cb52a3d913c4510289572d84e morrismiranda@yahoo.com // e8e60f3bfe7c50bc367a5ffb2747f92d bryanhartman@ryan.com // af641994bc313275c6d0a6371af9d9f6 diazpatricia@oneal.com // f1044e400284d50cc24b41ad0411ea7d christopher05@clarke-holloway.info // ebbde3eab3990f85d706c80aff166891 tylersmith@hotmail.com // d88d29a850add66712eb9ad4d7a07606 hendersonnancy@glass-wheeler.biz // dfa14cc56522a633d4c334ebd5bafa6f slewis@yahoo.com // faf37aabf387f2c5bcd0b6d7f9e32e3d john52@yahoo.com // cb08da8a1eb94398c22e144a354eec5f ysalazar@yahoo.com // a24de18f948dc75aafac9911f8988f9e emcclain@hotmail.com // fd9c9803c856c519a82952413ee263d3 jacqueline78@hotmail.com // df4e77c73dcee3bfffac8a66f70b69c6 aevans@hotmail.com // fdb792b87951b7de62839c9f3cf76119 michaeltaylor@freeman.com // cd3ef3713ad1358f76dfce55a2a22c9c hernandezmitchell@gmail.com // e5702cba83939134040d39f7f226d504 robertparker@hotmail.com // de8e47cd0ae23bf5505dc39e749aa357 isolis@evans.com // ecaacee4196b67eeb64d8c7a266fd2d2 wongjonathan@hotmail.com // b8df8516e1b5fa2c4f5fe3c2795e71f2 smithcarla@hotmail.com // bebdd14d01adbe6ef3b5233f8cbef53a jmoore@yahoo.com // ddcfc4c78bcdea5bc10abed62865aee0 shannonwade@yahoo.com // b2470d0f0998bc3e0c1029adcb3ce7bf beasleybrandon@yahoo.com // a587a5a4a425e9cc76fa51b6e97a83d7 tiffanyrobbins@hotmail.com // d096423fddfa6b8822b5fe9d28655305 ibarrachristopher@wang.com // c54f7eafbcd05d46296957684b9c5d5b ctaylor@butler-morales.org // e03a9444afe5148dd47c779f69ea1c9f lisaparker@cummings.com // e8a27c0e4286d154221b6d8375684da4 ygreer@guerra-richardson.com // a8bdb0effe4acf45245907b665a290b1 krobinson@mclaughlin-lamb.biz // fcff23f39414b214707c4a37b1a08143 ronnie13@hotmail.com // a2689d9fdd74e9b0f6ee27e8030bb06a khaley@yahoo.com // de6c63570ae6c6401550bf64be38a23d alexis87@thomas-brown.net // cf298a309bdd739f3a5a389d02a50348 ubaldwin@smith.com // c3d1eaf1b8074a890eab611f292fe906 ian82@hotmail.com // ce8c156624c7abec031f05704548d2ea stephen10@smith.org // c21a29f44621ce4d10bf1b72ba169985 melvin99@garcia.info // d2fac5e3bfc74553050e850b8fc85306 jmclaughlin@mccall.biz // a5976a4d245c38d002a45f05e7414746 johnny90@yahoo.com // f24c6afb9dbfbe6c2bd9243a369ae250 simmonsmichael@blanchard.biz // ef62eb9d31406b6baf1e5f31e613cc16 lewiseric@hotmail.com // db9bf4fdcff36fa834ab5e2531b3c5e3 fbush@hotmail.com // c3f9e136703ac13f65c50e6998c45856 potterbrooke@yahoo.com // b709b9235c96c932bfa07a4c6339adb4 sanchezsherry@sanders.com // f5149dec52a667422ef784fe075d5b7c lmitchell@jackson.com // c21ee8efad22b0a2235c9248f59fc499 jasonmartinez@yahoo.com // b4e9837fc6a47f37801b16ea43cabb3b brandtdiana@gmail.com // df5427a7dcbfc53a5c8efb2829a06efc frederickjackson@hotmail.com // b5ec187bd089dcf544ed966e81cd7330 rivasrobert@freeman.com // bd4e7b1cba12b2951bb1d41ea7a4599d elliswendy@smith.net // dcbf1489df22611edb816c34d795e0ef mark82@parrish.info // ef1e071c70f1a10ba8b142307fbc9a19 katherineadams@wallace.com // e367c5e062f67ac9d85b82ac8695a433 annahanson@gmail.com // cad2c40a0f1e3d21222acd08892572fb elizabeth61@powell.net // d37ea62f1c753baaa09aa50197c3d734 nsilva@andrews.org // a4baa3f5ae2bf74238ccdb5acec973fb thomasdiamond@gmail.com // a4edf4ad3e0ed981679bf1e7b3b035ff harrisandrea@yahoo.com // d6c4264c83656dd16b4310c64ec369a8 michaelthompson@davidson.org // b5590c8c8d16cf7a8e1e6a5a1477290a andreagoodman@sanders-doyle.com // a06400e48a4c11ddd99559711cb159ed wallacesamantha@yahoo.com // b2f9c9c39d665371d3c34d9fde2d73bc raymondalexis@chambers-garcia.net // d83297b38087de942bb71a9bb7d94726 wintersmarisa@hotmail.com // c41b49ad8cb2ac513b6e98b06b308df6 christopher15@hotmail.com // e6b46e30cf2c5e30d5fb5af5ca333b5a gadams@robinson-hernandez.com // b7189aea8f348c2ab964e6890147e19b gregoryadams@yahoo.com // feecec721c248a773a7da28354829410 kathrynjohnson@adams.com // bd0c7eba69c5d8ee14669e61d8cac60d vasquezangela@singh-wells.com // c1a5986e6877e38d719704039d5c4f19 snyderamanda@graham.com // fef46076f5949df8752048e593e44c55 aprilwalker@yahoo.com // cd851c6604153ecedacf5ed1d2482492 paul90@yahoo.com // f9dcf8e0e9eb7ba525707758dc12c24d laurenedwards@kidd-davidson.com // da22c7bf2b2eb745a974f0b364d87540 ggiles@hotmail.com // abbf8c0d766a2e60d22bce6ef1e73418 rjohns@hotmail.com // cb5929e9c047ef2d788c9d6d29342bb5 marklopez@lee.com // eb61821377d789f77675fe53284232d9 hilljesse@hotmail.com // fd2bbd4e80a2036772915a937473474e henrywayne@rogers.net // a6abcf05d7dc8c5f5864989df9f52f1b david98@hotmail.com // e16d9e3532cc560884b40c393634a1e5 woodlaura@gmail.com // b97f74ac8c09c9222b8bd65642611095 charles20@yahoo.com // bcf804344815488342c56d652538c174 espencer@gmail.com // a5723c3f3e84338f0c1a5c574427f403 kimberlybaker@mitchell.org // a725e5d2344e638408ae658cd71b350d carolynsanchez@ball.com // c7ce2c19d6e0ce7054ed480f97c69d1e markzimmerman@hardy.net // b9a23fbb72893d5fd55fa4a6c488da1a arnoldjill@hansen.com // a1a5b248cdaabd0bf65c2a7f9b9cccd9 jessicacollins@garcia.biz // b6c286119752a1c0238e212e5b900375 elawrence@hotmail.com // c4ce6b5975ec1358ce81d09379102c88 uknox@gmail.com // a4c83cfef1370ac7100c8407813db965 carrillojoshua@gmail.com // aacca7633e28457f8584cd76e78e7ae9 hernandezchristopher@yahoo.com // c683349de4411ad354a3311e69d1b95c chelseasmith@martinez.net // ebbba15fc8f11bd74e94faeaa9fc771c rosedanielle@gmail.com // bcf5c4f676e1725601a1c8b4a889d3ff steven49@shah-evans.com // c2cf38301e5e85c1a1047dbdfb264606 jocelynallison@yahoo.com // cd2452f4cc585a4d5d39e0ee825003f9 kevin51@jordan.com // aa9fb271d4739666761b564f3b8b6b00 ljones@knight.org // d81ceb1717e411810966631ad8093822 jbailey@hotmail.com // e1829c2ba56fb7e9e1405652b98fc203 zspencer@miles.org // fe9c95c40960c4ce76c086d63296bfef ricky94@kennedy.com // e2f9d9b53be911aabdbfc719592fa692 charmon@mcpherson.com // bc5761bff142d2ddf310647f2b6ef5b6 justin55@yahoo.com // fe2fb6d1a99206485f76b5244b9c0458 jamesthomas@gmail.com // d2bc061aab66eb8201f8bb638fd52f98 ryanmcdaniel@turner.com // b3069b27f7ab3b2d9145b56f5ed7f0d5 brittanydoyle@yahoo.com // a184403e37dd9fe27fad9fe90e60e619 stephenturner@gmail.com // d4289c0b7d8b8b9db4a1c6ad38d4f741 marquezmolly@carter-schmidt.com // d60c4e1fc8a79afca3a1215ee489ebb8
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/FE-CTF/2023/pwn/Crackstation_Level_4/crackstation.py
ctfs/FE-CTF/2023/pwn/Crackstation_Level_4/crackstation.py
#!/usr/bin/env python3 # coding: utf-8 # 外国人想法真是不一样 import base64 import ctypes import importlib import os import struct import sys import zlib from Crypto.Cipher import AES from hashlib import md5 assert sys.maxsize > 9876543210, 'Can\'t run on a steam engine :(' assert sys.platform[0] == 'l', 'Software update required' sys.excepthook=lambda*_:os._exit(0) FLAGS = [False, True, True, True, True] NOPE = [] flags = {} def flag(y): def flag(x, z): try: 0/0 except Exception as e: flag = e.__traceback__.tb_frame.f_back.f_lineno flags[flag] = flag = f'{x}{y}{z}' return Flag(flag) return flag class Flag(str): __getattr__ = flag('.') __matmul__ = flag('@') __sub__ = flag('-') __floordiv__ = flag('!') FLAG,FLAG = os.path.splitext(os.path.basename(sys.modules['__main__'].__file__))[::-1] while True: try: importlib.import_module(FLAG) ; break except NameError as flag: _, flag, _ = flag.args[0].split("'") globals()['__builtins__'][flag] = Flag(flag) flag = ctypes.CDLL(None).mmap flag.restype = ctypes.c_long flag.argtypes = (ctypes.c_long,) * 6 def galf(p): return ctypes.cast(p, ctypes.c_voidp).value Flag = ctypes.cast(flag(0, 1<<32, 3, 16418, -1, 0), ctypes.POINTER(ctypes.c_ubyte)) fLag = ctypes.cast(flag(0, 1<<33, 7, 16418, -1, 0), ctypes.POINTER(ctypes.c_ubyte)) flAg = ctypes.cast(flag(0, 1<< 6, 3, 16418, -1, 0), ctypes.POINTER(ctypes.c_uint32)) flaG = ctypes.cast(flag(0, 1<< 7, 3, 16418, -1, 0), ctypes.POINTER(ctypes.c_voidp)) FLAG = flag(0, 1<< 7, 7, 16418, -1, 0) aes = AES.new(md5(open(__file__, 'rb').read()).digest(), AES.MODE_ECB) for i, (_, x) in enumerate(sorted(flags.items()), 0x2ab): a, b = x.split('!') o = int(bytes(a, 'utf8').hex(), 16) % 7 x = int(aes.decrypt(bytes.fromhex(b)).hex(), 16) y = [o] for _ in range(5 + (o==6)): y.append(x & 0xff) ; x >>= 8 xs = y[o==6:] for j, x in enumerate(xs): Flag[i*6+j] = x flAg[15] = 0x1002 def in_(i): return Flag[i & 0xffffffff] if i > 0xfff else os._exit(1) def out(i, x): Flag[i & 0xffffffff] = x & 0xff if i > 0xfff else os._exit(1) def IN_(i): return flAg[i & 0xf] def OUT(i, x): flAg[i & 0xf] = x def inn(a): x=in_;return x(a),x(a+1)&15,x(a+1)>>4,x(a+2)|x(a+3)<<8|x(a+4)<<16|x(a+5)<<24 def flag(truth): res = {} while truth[0] != 0: n = 0 i = 0 while True: b = truth.pop(0) n |= (b & 0x7f) << i * 7 i += 1 if not b & 0x80: break off = n - 2 if truth[0] == 1: truth.pop(0) n = 0 i = 0 while True: b = truth.pop(0) n |= (b & 0x7f) << i * 7 i += 1 if not b & 0x80: break sz = n - 2 rec = (sz, flag(truth)) else: rec = flag(truth) res[off] = rec truth.pop(0) return res def recurse(addr, sig, n): if isinstance(sig, tuple): sz, sig = sig while recurse(addr, sig, n): addr += sz else: ret = False for off, sub in sig.items(): x = ( Flag[addr + off] | Flag[addr + off + 1] << 8 | Flag[addr + off + 2] << 16 | Flag[addr + off + 3] << 24 | Flag[addr + off + 4] << 32 | Flag[addr + off + 5] << 40 | Flag[addr + off + 6] << 48 | Flag[addr + off + 7] << 56 ) if 0x1000 <= min(x, x + n) < 2**32: recurse(min(x, x + n), sub, n) Flag[addr + off] = (x + n) & 0xff Flag[addr + off + 1] = ((x + n) >> 8) & 0xff Flag[addr + off + 2] = ((x + n) >> 16) & 0xff Flag[addr + off + 3] = ((x + n) >> 24) & 0xff Flag[addr + off + 4] = ((x + n) >> 32) & 0xff Flag[addr + off + 5] = ((x + n) >> 40) & 0xff Flag[addr + off + 6] = ((x + n) >> 48) & 0xff Flag[addr + off + 7] = ((x + n) >> 56) & 0xff ret = True return ret _syscall = ctypes.CDLL(None).syscall _syscall.restype = ctypes.c_long _syscall.argtypes = (ctypes.c_long,) * 6 def do_syscall(nr, argsaddr): argsaddr &= 0xffffffff flag = do_syscall.flag.get(nr, {}) recurse(argsaddr, flag, galf(Flag)) args = struct.unpack('<QQQQQQ', bytes(Flag[argsaddr : argsaddr + 6 * 8])) ret = _syscall(nr, *args) recurse(argsaddr, flag, -galf(Flag)) return ret do_syscall.flag=flag(bytearray(zlib.decompress(base64.b85decode('''c$`&KTW^g)6x\ }nQ6yF1K+)v^~LZoqxxIKu72fPU4PDB(*e?Ub%q18LuCOo(#+J<tpT12W^)l#%XBZwD?AaMziw64L6w\ f6odagwvwUbAQI*?VTbIX)JNU_-n}ju)_@uwlxEBQ`SjQsYEY=44bXDUs2b9RnL1J4}d-OZ<4i1lUBX\ (lS|O64X<4wW+Xanw<-qj?oMq&5Ws=Ma&hMje03v3_+QbHJXc@d73j{aY0&SA#9OWT8t_VdL$5KNsJC\ ;Dd;lfEr+dutwi1`#8!i^fnN(-r~R!5+W^}L+oX}rU|W=JRosU0cGwQsPL1TjcENTdvImwAUI5z*+eZ\ be?N9tc2f-nij0zo~h@oN)NeOv{@k$4%B2*J<s69b;#^!6Otz)2`>>S~|O*JG1a3B{LzDURrE;$@WBU\ uyS3INMqCGQMf-43M7sp}5oJAvG_i5{zV&)j{s^1yhnxju#-aq-9OzMt@fv8PUN>lp*jZLt@Oza+eJd\ TFmM{>JemlDC|BM|e;8K=^1=pIq!l<nXrTvr7m1#abAkaM1WyIOxBzq3=$=xF1>z<R^8%tmJQ}NB1Xe\ _irEvJVb?rBEn%pF`>lke5tuIhRVI}qQYFI*MmM{f}<21BUJhDNbuQLs|f1jmUPn8r+nBSnmWy_vtDJ\ j<aH*hCvWh)Y@fWtOdyR6H~Igc5q`}c&|)iHWA^ndg|zx)*Ef=N(zaS#_OP9)9fVtiPHVl3CA$ed>`x\ zK+MZ;uDf&Wp4+H7<dL;v4JQzr6lvS}TdsrUvm?OQ#OoV<f^RKKq(kd+xzw*d7$#`p|duk)UnJgsjQ8\ -~;rNeUN9~&oviv''')))) def magic(*some_arguments): def less_magic(some_function): global FLAG @ctypes.CFUNCTYPE(None, ctypes.c_long) def another_function(x): try: # XXX: Here be dragons? y = (x - 5 - galf(fLag)) // 2 OUT(15, y) some_function() OUT(0, 0) except: os._exit(0) sys.argv.append(another_function) # Won't work without... ¯\_(ツ)_/¯ flag = b''.join(( b'\x55\x48\x89\xe5\x48\x83\xe4\xf0\x48\xb8', another_function, b'\xff\xd0\xc9', *some_arguments, b'\xc3', )) ctypes.memmove(FLAG, flag, len(flag)) FLAG += len(flag) return ctypes.cast(FLAG - len(flag), ctypes.CFUNCTYPE(None)) return less_magic def more_magic(normal_amount_of_magic): cigam_fo_tnuoma_lamron = galf(normal_amount_of_magic) x = 0 while True: if cigam_fo_tnuoma_lamron == flaG[x]: break x += 1 return b'\xe8\x00\x00\x00\x00\x5f\x41\xff\x55' + bytes([x<<3]) def this(x, xs, force=False): assert not FLAGS[3] or x % 6 == 0 if fLag[2*x] and not force: return xs = xs.ljust(12, b'\x90') assert len(xs) == 12 y = x * 2 + galf(fLag) ctypes.memmove(y, xs, len(xs)) @magic( b'\x48\xbb' + flAg, b'\x49\xbc' + Flag, b'\x49\xbd' + flaG, b'\x49\xbe' + fLag, b'\x49\x8d\x86\x04\x20\x00\x00', b'\xff\xe0', ) def entry(): pass # lol wat? def p32(x): return struct.pack('<I', x % 2**32) @magic(b'\x48\x83\x2c\x24\x0a') def thing(): x = IN_(15) if FLAGS[0]: this(x, more_magic(device), force=True) return o, a, b, c = inn(x) o_, a_, b_, c_ = inn(x + 6) if a: wa = b'\x89\x43' + bytes([a*4]) else: wa = b'' y1 = x + 6 y2 = None magic = more_magic(device) if o == 0: magic = more_magic(action) elif o == 5 and a == b == 15: y1 = y = (x + 6 + c) % 2**32 z = (6 + c) * 2 - 5 magic = b'\xe9' + p32(z) elif (o == 5 and (a, b, c) == (14, 15, 3) and o_ == 5 and a_ == b_ == 15) and FLAGS[1]: ra = x + 9 y1 += 6 y2 = y = (x + 6 + 6 + c_) % 2**32 z = (6 + 6 + c_) * 2 - 7 - 5 magic = b'\xc7\x43\x38' + p32(ra) + b'\xe8' + p32(z) this(x + 6, b'\xeb\x0a') elif o == 5 and (a, b, c) == (15, 14, 3) and FLAGS[1]: magic = b'\xc3' elif (o == 5 and (a, b, c) == (13, 13, 2**32-4) and o_ == 3 and a_ != 15 and b_ == 13 and c_ == 3) and FLAGS[2]: magic = b'\x83\x6b\x34\x04\x8b\x43' + bytes([a_*4]) + b'\x50' y1 += 6 this(x + 6, b'\xeb\x0a') elif (o == 2 and a != 15 and b == 13 and c == 3 and o_ == 5 and (a_, b_, c_) == (13, 13, 4)) and FLAGS[2]: magic = b'\x83\x43\x34\x04\x58\x89\x43' + bytes([a*4]) y1 += 6 this(x + 6, b'\xeb\x0a') elif (o, a, b, c) == (4, 0, 0, 3): magic = more_magic(gadget) elif 15 not in (a, b): if o == 1: y2 = y = (x + 6 + c) % 2**32 z = (6 + c) * 2 - 3 - 3 - 6 magic = ( b'\x8b\x43' + bytes([a*4]) + b'\x3b\x43' + bytes([b*4]) + b'\x0f\x82' + p32(z) ) elif o == 5: magic = ( b'\x8b\x43' + bytes([b*4]) + b'\x05' + p32(c) + wa ) elif o == 2: magic = b'\x8b\x43' + bytes([b*4]) + b'\x41' if c == 0: magic += b'\x0f\xb6' elif c == 1: magic += b'\x0f\xb7' else: magic += b'\x8b' magic += b'\x04\x04\x89\x43' + bytes([a*4]) elif o == 3: magic = ( b'\x8b\x43' + bytes([b*4]) + b'\x8b\x4b' + bytes([a*4]) ) if c == 0: magic += b'\x41\x88' elif c == 1: magic += b'\x66\x41\x89' else: magic += b'\x41\x89' magic += b'\x0c\x04' elif o == 4: magic = b'\x8b\x43' + bytes([a*4]) magic += [ b'\x03\x43' + bytes([b*4]), b'\x2b\x43' + bytes([b*4]), b'\xf7\x63' + bytes([b*4]), b'\x31\xd2\xf7\x73' + bytes([b*4]), b'\x31\xd2\xf7\x73' + bytes([b*4]) + b'\x92', b'\x23\x43' + bytes([b*4]), b'\x0b\x43' + bytes([b*4]), b'\x33\x43' + bytes([b*4]), b'\x8b\x4b' + bytes([b*4]) + b'\xd3\xe0', b'\x8b\x4b' + bytes([b*4]) + b'\xd3\xe8', b'\xf7\xd8', b'\xf7\xd0', ][c] magic += b'\x89\x43' + bytes([a*4]) this(x, magic, force=True) for y in (y1, y2): if y: this(y, more_magic(thing)) @magic(b'\x8b\x43\x3c\x48\x01\xc0\x4c\x01\xf0\x48\x89\x04\x24') def device(): x = IN_(15) o, a, b, c = inn(x) OUT(15, x + 6) if o == 0: OUT(a, do_syscall(IN_(b) + c, IN_(a))) elif o == 1: if IN_(a) < IN_(b): OUT(15, IN_(15) + c) elif o == 2: y = IN_(b) x = in_(y) if c > 0: x |= in_(y + 1) << 8 if c > 1: x |= in_(y + 2) << 16 x |= in_(y + 3) << 24 OUT(a, x) elif o == 3: x = IN_(a) y = IN_(b) out(y, x) if c > 0: out(y + 1, x >> 8) if c > 1: out(y + 2, x >> 16) out(y + 3, x >> 24) elif o == 4: r = [ lambda a, b: a + b, lambda a, b: a - b, lambda a, b: a * b, lambda a, b: a // b, lambda a, b: a % b, lambda a, b: a & b, lambda a, b: a | b, lambda a, b: a ^ b, lambda a, b: a << b, lambda a, b: a >> b, lambda a, b: -a, lambda a, b: ~a, ][c](IN_(a), IN_(b)) OUT(a, r) elif o == 5: OUT(a, IN_(b) + c) else: os._exit(0) this(IN_(15), more_magic(thing)) @magic(b'\xcc') def gadget(): os._exit(0) @magic() def action(): _, a, b, c = inn(IN_(15)) nr = IN_(b) + c if nr in NOPE: OUT(a, 0xffffefff) else: OUT(a, do_syscall(nr, IN_(a))) flaG[0] = galf(thing) flaG[1] = galf(device) flaG[2] = galf(gadget) if not FLAGS[4]: flaG[3] = galf(action) this(0x1002, more_magic(thing)) entry()
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/FE-CTF/2023/pwn/Crackstation_Level_4/server.py
ctfs/FE-CTF/2023/pwn/Crackstation_Level_4/server.py
#!/usr/bin/env -S python3 -u import sys import re import os import signal import tempfile ok = re.compile(r'^[a-z0-9_.-]+@[a-z0-9_.-]+\s+//\s+[a-f0-9]{32}$') print('Send hash list, then end with a blank line') sys.stdout.flush() lines = ['import crackstation'] for lino, line in enumerate(sys.stdin.buffer.raw, 1): line = line.strip().decode() if not line: break if not ok.match(line): print(f'Format error on line {lino}:') print(line) exit(1) lines.append(line) if len(lines) <= 1: print('No tickee, no washee.') exit(1) with tempfile.TemporaryDirectory() as rundir: with open(rundir + '/runme.py', 'w') as f: for line in lines: f.write(line + '\n') os.symlink(os.getcwd() + '/crackstation.py', rundir + '/crackstation.py') if os.fork() == 0: signal.alarm(60) argv = ['python3', '-u', rundir + '/runme.py'] os.execvp(argv[0], argv) else: os.wait()
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/FE-CTF/2023/pwn/Crackstation_Level_2/crackstation.py
ctfs/FE-CTF/2023/pwn/Crackstation_Level_2/crackstation.py
#!/usr/bin/env python3 # coding: utf-8 # 外国人想法真是不一样 import base64 import ctypes import importlib import os import struct import sys import zlib from Crypto.Cipher import AES from hashlib import md5 assert sys.maxsize > 9876543210, 'Can\'t run on a steam engine :(' assert sys.platform[0] == 'l', 'Software update required' sys.excepthook=lambda*_:os._exit(0) FLAGS = [False, True, True, False, False] NOPE = [0, 2, 17, 19, 40, 59, 257, 295, 322, 366, 371, 385, 396, 397] flags = {} def flag(y): def flag(x, z): try: 0/0 except Exception as e: flag = e.__traceback__.tb_frame.f_back.f_lineno flags[flag] = flag = f'{x}{y}{z}' return Flag(flag) return flag class Flag(str): __getattr__ = flag('.') __matmul__ = flag('@') __sub__ = flag('-') __floordiv__ = flag('!') FLAG,FLAG = os.path.splitext(os.path.basename(sys.modules['__main__'].__file__))[::-1] while True: try: importlib.import_module(FLAG) ; break except NameError as flag: _, flag, _ = flag.args[0].split("'") globals()['__builtins__'][flag] = Flag(flag) flag = ctypes.CDLL(None).mmap flag.restype = ctypes.c_long flag.argtypes = (ctypes.c_long,) * 6 def galf(p): return ctypes.cast(p, ctypes.c_voidp).value Flag = ctypes.cast(flag(0, 1<<32, 3, 16418, -1, 0), ctypes.POINTER(ctypes.c_ubyte)) fLag = ctypes.cast(flag(0, 1<<33, 7, 16418, -1, 0), ctypes.POINTER(ctypes.c_ubyte)) flAg = ctypes.cast(flag(0, 1<< 6, 3, 16418, -1, 0), ctypes.POINTER(ctypes.c_uint32)) flaG = ctypes.cast(flag(0, 1<< 7, 3, 16418, -1, 0), ctypes.POINTER(ctypes.c_voidp)) FLAG = flag(0, 1<< 7, 7, 16418, -1, 0) aes = AES.new(md5(open(__file__, 'rb').read()).digest(), AES.MODE_ECB) for i, (_, x) in enumerate(sorted(flags.items()), 0x2ab): a, b = x.split('!') o = int(bytes(a, 'utf8').hex(), 16) % 7 x = int(aes.decrypt(bytes.fromhex(b)).hex(), 16) y = [o] for _ in range(5 + (o==6)): y.append(x & 0xff) ; x >>= 8 xs = y[o==6:] for j, x in enumerate(xs): Flag[i*6+j] = x flAg[15] = 0x1002 def in_(i): return Flag[i & 0xffffffff] if i > 0xfff else os._exit(1) def out(i, x): Flag[i & 0xffffffff] = x & 0xff if i > 0xfff else os._exit(1) def IN_(i): return flAg[i & 0xf] def OUT(i, x): flAg[i & 0xf] = x def inn(a): x=in_;return x(a),x(a+1)&15,x(a+1)>>4,x(a+2)|x(a+3)<<8|x(a+4)<<16|x(a+5)<<24 def flag(truth): res = {} while truth[0] != 0: n = 0 i = 0 while True: b = truth.pop(0) n |= (b & 0x7f) << i * 7 i += 1 if not b & 0x80: break off = n - 2 if truth[0] == 1: truth.pop(0) n = 0 i = 0 while True: b = truth.pop(0) n |= (b & 0x7f) << i * 7 i += 1 if not b & 0x80: break sz = n - 2 rec = (sz, flag(truth)) else: rec = flag(truth) res[off] = rec truth.pop(0) return res def recurse(addr, sig, n): if isinstance(sig, tuple): sz, sig = sig while recurse(addr, sig, n): addr += sz else: ret = False for off, sub in sig.items(): x = ( Flag[addr + off] | Flag[addr + off + 1] << 8 | Flag[addr + off + 2] << 16 | Flag[addr + off + 3] << 24 | Flag[addr + off + 4] << 32 | Flag[addr + off + 5] << 40 | Flag[addr + off + 6] << 48 | Flag[addr + off + 7] << 56 ) if 0x1000 <= min(x, x + n) < 2**32: recurse(min(x, x + n), sub, n) Flag[addr + off] = (x + n) & 0xff Flag[addr + off + 1] = ((x + n) >> 8) & 0xff Flag[addr + off + 2] = ((x + n) >> 16) & 0xff Flag[addr + off + 3] = ((x + n) >> 24) & 0xff Flag[addr + off + 4] = ((x + n) >> 32) & 0xff Flag[addr + off + 5] = ((x + n) >> 40) & 0xff Flag[addr + off + 6] = ((x + n) >> 48) & 0xff Flag[addr + off + 7] = ((x + n) >> 56) & 0xff ret = True return ret _syscall = ctypes.CDLL(None).syscall _syscall.restype = ctypes.c_long _syscall.argtypes = (ctypes.c_long,) * 6 def do_syscall(nr, argsaddr): argsaddr &= 0xffffffff flag = do_syscall.flag.get(nr, {}) recurse(argsaddr, flag, galf(Flag)) args = struct.unpack('<QQQQQQ', bytes(Flag[argsaddr : argsaddr + 6 * 8])) ret = _syscall(nr, *args) recurse(argsaddr, flag, -galf(Flag)) return ret do_syscall.flag=flag(bytearray(zlib.decompress(base64.b85decode('''c$`&KTW^g)6x\ }nQ6yF1K+)v^~LZoqxxIKu72fPU4PDB(*e?Ub%q18LuCOo(#+J<tpT12W^)l#%XBZwD?AaMziw64L6w\ f6odagwvwUbAQI*?VTbIX)JNU_-n}ju)_@uwlxEBQ`SjQsYEY=44bXDUs2b9RnL1J4}d-OZ<4i1lUBX\ (lS|O64X<4wW+Xanw<-qj?oMq&5Ws=Ma&hMje03v3_+QbHJXc@d73j{aY0&SA#9OWT8t_VdL$5KNsJC\ ;Dd;lfEr+dutwi1`#8!i^fnN(-r~R!5+W^}L+oX}rU|W=JRosU0cGwQsPL1TjcENTdvImwAUI5z*+eZ\ be?N9tc2f-nij0zo~h@oN)NeOv{@k$4%B2*J<s69b;#^!6Otz)2`>>S~|O*JG1a3B{LzDURrE;$@WBU\ uyS3INMqCGQMf-43M7sp}5oJAvG_i5{zV&)j{s^1yhnxju#-aq-9OzMt@fv8PUN>lp*jZLt@Oza+eJd\ TFmM{>JemlDC|BM|e;8K=^1=pIq!l<nXrTvr7m1#abAkaM1WyIOxBzq3=$=xF1>z<R^8%tmJQ}NB1Xe\ _irEvJVb?rBEn%pF`>lke5tuIhRVI}qQYFI*MmM{f}<21BUJhDNbuQLs|f1jmUPn8r+nBSnmWy_vtDJ\ j<aH*hCvWh)Y@fWtOdyR6H~Igc5q`}c&|)iHWA^ndg|zx)*Ef=N(zaS#_OP9)9fVtiPHVl3CA$ed>`x\ zK+MZ;uDf&Wp4+H7<dL;v4JQzr6lvS}TdsrUvm?OQ#OoV<f^RKKq(kd+xzw*d7$#`p|duk)UnJgsjQ8\ -~;rNeUN9~&oviv''')))) def magic(*some_arguments): def less_magic(some_function): global FLAG @ctypes.CFUNCTYPE(None, ctypes.c_long) def another_function(x): try: # XXX: Here be dragons? y = (x - 5 - galf(fLag)) // 2 OUT(15, y) some_function() OUT(0, 0) except: os._exit(0) sys.argv.append(another_function) # Won't work without... ¯\_(ツ)_/¯ flag = b''.join(( b'\x55\x48\x89\xe5\x48\x83\xe4\xf0\x48\xb8', another_function, b'\xff\xd0\xc9', *some_arguments, b'\xc3', )) ctypes.memmove(FLAG, flag, len(flag)) FLAG += len(flag) return ctypes.cast(FLAG - len(flag), ctypes.CFUNCTYPE(None)) return less_magic def more_magic(normal_amount_of_magic): cigam_fo_tnuoma_lamron = galf(normal_amount_of_magic) x = 0 while True: if cigam_fo_tnuoma_lamron == flaG[x]: break x += 1 return b'\xe8\x00\x00\x00\x00\x5f\x41\xff\x55' + bytes([x<<3]) def this(x, xs, force=False): assert not FLAGS[3] or x % 6 == 0 if fLag[2*x] and not force: return xs = xs.ljust(12, b'\x90') assert len(xs) == 12 y = x * 2 + galf(fLag) ctypes.memmove(y, xs, len(xs)) @magic( b'\x48\xbb' + flAg, b'\x49\xbc' + Flag, b'\x49\xbd' + flaG, b'\x49\xbe' + fLag, b'\x49\x8d\x86\x04\x20\x00\x00', b'\xff\xe0', ) def entry(): pass # lol wat? def p32(x): return struct.pack('<I', x % 2**32) @magic(b'\x48\x83\x2c\x24\x0a') def thing(): x = IN_(15) if FLAGS[0]: this(x, more_magic(device), force=True) return o, a, b, c = inn(x) o_, a_, b_, c_ = inn(x + 6) if a: wa = b'\x89\x43' + bytes([a*4]) else: wa = b'' y1 = x + 6 y2 = None magic = more_magic(device) if o == 0: magic = more_magic(action) elif o == 5 and a == b == 15: y1 = y = (x + 6 + c) % 2**32 z = (6 + c) * 2 - 5 magic = b'\xe9' + p32(z) elif (o == 5 and (a, b, c) == (14, 15, 3) and o_ == 5 and a_ == b_ == 15) and FLAGS[1]: ra = x + 9 y1 += 6 y2 = y = (x + 6 + 6 + c_) % 2**32 z = (6 + 6 + c_) * 2 - 7 - 5 magic = b'\xc7\x43\x38' + p32(ra) + b'\xe8' + p32(z) this(x + 6, b'\xeb\x0a') elif o == 5 and (a, b, c) == (15, 14, 3) and FLAGS[1]: magic = b'\xc3' elif (o == 5 and (a, b, c) == (13, 13, 2**32-4) and o_ == 3 and a_ != 15 and b_ == 13 and c_ == 3) and FLAGS[2]: magic = b'\x83\x6b\x34\x04\x8b\x43' + bytes([a_*4]) + b'\x50' y1 += 6 this(x + 6, b'\xeb\x0a') elif (o == 2 and a != 15 and b == 13 and c == 3 and o_ == 5 and (a_, b_, c_) == (13, 13, 4)) and FLAGS[2]: magic = b'\x83\x43\x34\x04\x58\x89\x43' + bytes([a*4]) y1 += 6 this(x + 6, b'\xeb\x0a') elif (o, a, b, c) == (4, 0, 0, 3): magic = more_magic(gadget) elif 15 not in (a, b): if o == 1: y2 = y = (x + 6 + c) % 2**32 z = (6 + c) * 2 - 3 - 3 - 6 magic = ( b'\x8b\x43' + bytes([a*4]) + b'\x3b\x43' + bytes([b*4]) + b'\x0f\x82' + p32(z) ) elif o == 5: magic = ( b'\x8b\x43' + bytes([b*4]) + b'\x05' + p32(c) + wa ) elif o == 2: magic = b'\x8b\x43' + bytes([b*4]) + b'\x41' if c == 0: magic += b'\x0f\xb6' elif c == 1: magic += b'\x0f\xb7' else: magic += b'\x8b' magic += b'\x04\x04\x89\x43' + bytes([a*4]) elif o == 3: magic = ( b'\x8b\x43' + bytes([b*4]) + b'\x8b\x4b' + bytes([a*4]) ) if c == 0: magic += b'\x41\x88' elif c == 1: magic += b'\x66\x41\x89' else: magic += b'\x41\x89' magic += b'\x0c\x04' elif o == 4: magic = b'\x8b\x43' + bytes([a*4]) magic += [ b'\x03\x43' + bytes([b*4]), b'\x2b\x43' + bytes([b*4]), b'\xf7\x63' + bytes([b*4]), b'\x31\xd2\xf7\x73' + bytes([b*4]), b'\x31\xd2\xf7\x73' + bytes([b*4]) + b'\x92', b'\x23\x43' + bytes([b*4]), b'\x0b\x43' + bytes([b*4]), b'\x33\x43' + bytes([b*4]), b'\x8b\x4b' + bytes([b*4]) + b'\xd3\xe0', b'\x8b\x4b' + bytes([b*4]) + b'\xd3\xe8', b'\xf7\xd8', b'\xf7\xd0', ][c] magic += b'\x89\x43' + bytes([a*4]) this(x, magic, force=True) for y in (y1, y2): if y: this(y, more_magic(thing)) @magic(b'\x8b\x43\x3c\x48\x01\xc0\x4c\x01\xf0\x48\x89\x04\x24') def device(): x = IN_(15) o, a, b, c = inn(x) OUT(15, x + 6) if o == 0: OUT(a, do_syscall(IN_(b) + c, IN_(a))) elif o == 1: if IN_(a) < IN_(b): OUT(15, IN_(15) + c) elif o == 2: y = IN_(b) x = in_(y) if c > 0: x |= in_(y + 1) << 8 if c > 1: x |= in_(y + 2) << 16 x |= in_(y + 3) << 24 OUT(a, x) elif o == 3: x = IN_(a) y = IN_(b) out(y, x) if c > 0: out(y + 1, x >> 8) if c > 1: out(y + 2, x >> 16) out(y + 3, x >> 24) elif o == 4: r = [ lambda a, b: a + b, lambda a, b: a - b, lambda a, b: a * b, lambda a, b: a // b, lambda a, b: a % b, lambda a, b: a & b, lambda a, b: a | b, lambda a, b: a ^ b, lambda a, b: a << b, lambda a, b: a >> b, lambda a, b: -a, lambda a, b: ~a, ][c](IN_(a), IN_(b)) OUT(a, r) elif o == 5: OUT(a, IN_(b) + c) else: os._exit(0) this(IN_(15), more_magic(thing)) @magic(b'\xcc') def gadget(): os._exit(0) @magic() def action(): _, a, b, c = inn(IN_(15)) nr = IN_(b) + c if nr in NOPE: OUT(a, 0xffffefff) else: OUT(a, do_syscall(nr, IN_(a))) flaG[0] = galf(thing) flaG[1] = galf(device) flaG[2] = galf(gadget) if not FLAGS[4]: flaG[3] = galf(action) this(0x1002, more_magic(thing)) entry()
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/FE-CTF/2023/pwn/Crackstation_Level_2/server.py
ctfs/FE-CTF/2023/pwn/Crackstation_Level_2/server.py
#!/usr/bin/env -S python3 -u import sys import re import os import signal import tempfile ok = re.compile(r'^[a-z0-9_.-]+@[a-z0-9_.-]+\s+//\s+[a-f0-9]{32}$') print('Send hash list, then end with a blank line') sys.stdout.flush() lines = ['import crackstation'] for lino, line in enumerate(sys.stdin.buffer.raw, 1): line = line.strip().decode() if not line: break if not ok.match(line): print(f'Format error on line {lino}:') print(line) exit(1) lines.append(line) if len(lines) <= 1: print('No tickee, no washee.') exit(1) with tempfile.TemporaryDirectory() as rundir: with open(rundir + '/runme.py', 'w') as f: for line in lines: f.write(line + '\n') os.symlink(os.getcwd() + '/crackstation.py', rundir + '/crackstation.py') if os.fork() == 0: signal.alarm(60) argv = ['python3', '-u', rundir + '/runme.py'] os.execvp(argv[0], argv) else: os.wait()
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/FE-CTF/2023/crypto/Two_Time_Pad/imgcrypt.py
ctfs/FE-CTF/2023/crypto/Two_Time_Pad/imgcrypt.py
#!/usr/bin/env python3 import os import sys import itertools from PIL import Image, ImageChops from argon2.low_level import hash_secret_raw, Type def expand_key(key, size): return hash_secret_raw( key, hash_len=size, salt=b'saltysalt', time_cost=1, memory_cost=1024, parallelism=1, type=Type.I, ) def imgcrypt(img, key): keyimg = Image.new(img.mode, img.size) keyimg.frombytes(expand_key(key, len(img.tobytes()))) return ImageChops.add_modulo(img, keyimg) if __name__ == "__main__": if len(sys.argv) != 4: print(f'usage: {sys.argv[0]} <keyfile> <inimg> <outimg>') exit(1) inimg = Image.open(sys.argv[2]) keyfile = sys.argv[1] if os.path.exists(keyfile): with open(keyfile, 'rb') as f: key = f.read() else: print(f'Generating key; saving to {keyfile}') key = os.urandom(32) with open(keyfile, 'wb') as f: f.write(key) outimg = imgcrypt(inimg, key) outimg.save(sys.argv[3])
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/FE-CTF/2023/crypto/Padding_Oracle/server.py
ctfs/FE-CTF/2023/crypto/Padding_Oracle/server.py
#!/usr/bin/env -S python3 -u import os import threading import sys from Crypto.Cipher import AES from Crypto.Random import get_random_bytes from Crypto.Util.Padding import pad, unpad from binascii import hexlify os.chdir(os.path.dirname(__file__)) KEY = open("server.key", "rb").read() FLAG_TXT = open("flag.txt").read() FLAG_ENC = open("flag.enc").read() class PaddingError(Exception): pass class CipherTextFormatError(Exception): pass class Cipher: def __init__(self, key: bytes): self._key = key def encrypt(self, message: str) -> str: aes = AES.new(self._key, AES.MODE_OFB, iv=get_random_bytes(AES.block_size)) ciphertext = aes.encrypt(pad(message.encode(), AES.block_size)) return hexlify(aes.iv + ciphertext).decode() def decrypt(self, message: str) -> str: ciphertext_bytes = self._get_hex_bytes(message) iv, ciphertext = ciphertext_bytes[0:AES.block_size], ciphertext_bytes[AES.block_size:] aes = AES.new(self._key, AES.MODE_OFB, iv=iv) plaintext = aes.decrypt(ciphertext) plaintext_unpad = self._unpad(plaintext) return plaintext_unpad.decode() @staticmethod def _get_hex_bytes(ciphertext: str) -> bytes: try: if len(ciphertext) % AES.block_size != 0: raise CipherTextFormatError() return bytes.fromhex(ciphertext) except ValueError: raise CipherTextFormatError() @staticmethod def _unpad(plaintext: bytes) -> bytes: try: return unpad(plaintext, AES.block_size) except ValueError: raise PaddingError() cipher = Cipher(KEY) def handle() -> None: print(f"Welcome {os.getenv('SOCAT_PEERADDR', '')}") print(f"Encrypted flag: {FLAG_ENC}") while True: ciphertext = input("Enter a ciphertext you want to decrypt: ").rstrip() if not ciphertext: break try: flag_dec = cipher.decrypt(ciphertext) if flag_dec == FLAG_TXT: print(f"Flag: {flag_dec}") else: print("Padding correct!") except PaddingError: print("Padding incorrect!") except (CipherTextFormatError, UnicodeDecodeError): print("Invalid message format!") def main() -> None: assert len(KEY) in AES.key_size assert len(FLAG_ENC) % AES.block_size == 0 handle() 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/FE-CTF/2022/pwn/snake-oil/magic.py
ctfs/FE-CTF/2022/pwn/snake-oil/magic.py
import os,sys _ = 'aIaabVaacaXadaaaeaaafaaagaaahaaaiaaajaaakaaalaaamaLanaaaoaaapaaaqaaaraaa'\ 'saaataaauaaavaaawaaaxaaayaaaCaabbaabcaabdaabeaabfaabgaabhaabiaabjaabkaab'\ 'laabmaabnaaboaabpaabqaabraabsaabtaabuaabvaabwaabxaabyaabzaacbaaccaacdaac'\ 'eaacfaacgaachaaciaacjaackaaclaacmaacnaacoaacpaacqaacraacsaactaacuaacvaac'\ 'waacxaacyaaczaadbaadcaaddaadeaadfaadgaadhaadiaadjaadkaadlaadmaadnaadoaad'\ 'paadqaadraadsaadtaaduaadvaadwaadxaadyaadzaaebaaecaaedaaeeaaefaaegaaehaae'\ 'iaaejaaekaaelaaemaaenaaeoaaepaaeqaaeraaesaaetaaeuaaevaaewaaexaaeyaaeDaaf'\ 'baafcaafdaafeaaffaafgaafhaafiaafjaafkaaflaafmaafnaafoaafpaafqaafraafsaaf'\ 'taafuaafvaafwaafxaafyaafzaagbaagcaagdaageaagfaaggaaghaagiaagjaagkaaglaag'\ 'maagnaagoaagpaagqaagraagsaagtaaguaagvaagwaagxaagyaagzaahbaahcaahdaaheaah'\ 'faahgaahhaahiaahjaahkaahlaahmaahnaahoaahpaahqaahraahsaahtaahuaahvaahwaah'\ 'xaahyaahzaaibaaicaaidaaieaaifaaigaaihaaiiaaijaaikaailaaimaainaaioaaipaai'\ 'qaairaaisaaitaaiuaaivaaiwaaixaaiyaaizaajbaajcaajdaajeaajfaajgaajhaajiaaj'\ 'jaajkaajlaajmaajnaajoaajpaajqaajraajsaajtaajuaajvaajwaajxaajyaajMaakbaak' def __(a): b=sorted(_ for _ in enumerate(_)if _[True].isupper())[::~False] c='' d=False f=a while a: if a>=b[d][False]: c+=b[d][True] a+=~b[d][False]+True continue if a>=b[d][False]*(9-b[d][False]//b[-~d][False]%2)//0o12: a-=b[d][False] e=min(_[False]for _ in b if a+_[False]>=False) c+=dict(b)[e] c+=b[d][True] a+=e d=-~d setattr(sys.modules[__name__],c,f) return c __(True) [__(_)for(_)in(range(I+I,I+I+I+I+I+I+I+I+I+I+I+I))] {__((XI**_-I)//II):__(XI**_-I)for(_)in(range(I,V))} class A(object): def __pos__(_): return sys.stdin.buffer.read(I)[False] def __add__(_,__): sys.stdout.buffer.write(bytes([__])) sys.stdout.buffer.flush() def __mul__(_,__): for __ in __.encode('latin1'): _+__ class B(object): _=lambda x:lambda y,z:y(x,z) __or__=_(VIII) def __init__(_): _.a,_.b,_.c=(False,)*III __add__=_(False) def __call__(_,__,___): x=B() x.b=_.b-~___.b x.c=x.a=___.a*XI**(_.b+True)+__*XI**_.b+_.a ___.c=_.c=_.c^_.c return x __mul__=_(II) __xor__=_(V) __sub__=_(I) __mod__=_(IV) __truediv__=_(IX) def __lt__(__,___): global _ _=(_ or __)(VII,___) return _ __and__=_(VI) def __gt__(__,___): global _ _=(_ or __)(X,___) return _ __matmul__=_(III) def __getitem__(_,__): __%=XI**V __*=V return _.a//XI**__%XI**V def __setitem__(_,__,___): ____=_[__] __%=XI**V __*=V _.a+=(___-____)*XI**__ def __del__(__): if not __.c:return _ = A() a = [False]*XI while X: a=[(_%XI**V)for(_)in(a)] b=__[a[False]];a[False]-=~False b,c=divmod(b,XI) b,d=divmod(b,XI) b,e=divmod(b,XI) b,f=divmod(b,XI) b,g=divmod(b,XI) h=f+g*XI i=e+h*XI j=d+i*XI if False: print(open('flag').read()) elif c==V: a[False]+=j-MMMMMMMCCCXX elif c==II: a[d]=__[a[e]+f-V] a[e]+=g-V elif c==III: __[a[e]+f-V]=a[d] a[e]+=g-V elif c==IV: a[d]=i elif not c: if not d|e|f|g: break elif I<=d<=VIII: d-=True if[ lambda a,_:a==False, lambda a,_:a!=False, lambda a,b:a==b, lambda a,b:a!=b, lambda a,b:a>b, lambda a,b:a>=b, lambda a,b:a<b, lambda a,b:a<=b, ][d](a[e],a[f]): a[False]+=I elif c==VII: a[d]+=i-DCLXV elif c==VIII: if not d: a[e]+=MCCCXXXI*h elif d==I: __[a[e]]=h-LX elif c==VI: if d<=VII: a[e]=[ lambda a,b:a+b, lambda a,b:a-b, lambda a,b:a*b, lambda a,b:a//b, lambda a,b:a%b, lambda a,b:min(a,b), lambda a,b:max(a,b), lambda a,b:~(a+b), ][d](a[f],a[g]) elif c==IX: a[IX]=a[False] a[False]+=j-MMMMMMMCCCXX elif c==X: a[d]=eval((__.a//XI**(a[e]*V)%XI**(a[f]*V)).to_bytes(a[f]*III,'little').decode('latin1').strip('\0'))or(0) elif not ~-c: a[d]=a[e] a[f]=a[g] _=setattr(sys.modules['__main__'],'_',B())
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/FE-CTF/2022/pwn/snake-oil/runme.py
ctfs/FE-CTF/2022/pwn/snake-oil/runme.py
#!/usr/bin/env python3 import magic;_%_>_+_&_%_%_-_%_@_+_/_/_%_&_^_%_^_|_@_@_%_<_<_|_+_%_|_/_@_+_%_%_&_@_+_@_<\ _^_^_&_@_|_^_^_&_@_%_^_^_&_/_|_<_|_^_%_<_>_+_+_+_%_-_<_|_^_*_&_^_^_%_<_&_@_+_+_%_-_<_@_\ %_-_|_^_+_%_<_%_|_+_+_%_-_<_|_%_-_|_^_+_@_-_^_^_&_^_%_%_^_^_%_<_%_|_+_%_|_+_>_+_%_%_&_@\ _+_%_@_+_+_+_@_<_^_^_&_@_|_^_^_&_@_%_^_^_&_@_@_^_^_&_%_-_*_&_+_/_*_*_&_^_%_-_|_@_@_/_+_\ *_&_^_%_-_@_<_+_/_/_-_&_^_+_+_+_+_+_<_|_+_+_+_/_@_+_+_+_&_@_+_+_+_@_<_+_+_+_/_/_+_+_+_*\ _/_+_+_+_/_|_+_+_+_^_>_+_+_+_*_/_+_+_+_>_*_+_+_+_*_/_+_+_+_+_>_+_+_+_&_>_+_+_+_*_/_+_+_\ +_%_>_+_+_+_>_*_+_+_+_+_+_-_+_+_-_>_+_+_+_<_>_+_+_+_%_>_+_+_+_>_*_+_+_+_+_>_+_+_+_/_|_+\ _+_+_>_/_+_+_+_*_/_+_+_+_%_|_+_+_+_+_>_+_+_+_<_^_+_+_+_>_*_+_+_+_&_@_+_+_+_+_+_+_+_+_<_\ |_+_+_+_/_@_+_+_+_&_@_+_+_+_&_&_+_+_+_*_/_+_+_+_/_/_+_+_+_/_/_+_+_+_-_>_+_+_+_+_%_+_+_+\ _>_*_+_+_+_&_@_+_+_+_+_+_+_+_+_<_|_+_+_+_/_ @_+_+_+_&_@_+_+_+_*_&_+_+_+_-_>_+_+_+_+_>_+\ _+_+_%_|_+_+_+_&_@_+_+_+_&_>_+_+_ +_>_*_+_+_+_>_|_+_+_+_%_>_+_+_+_*_\ /_+_+_+_/_|_+_+_+_|_/_+_+_+_> _*_+_+_+_/_|_+_+_+_+_>_+_+_+_+_\ +_-_+_+_&_>_+_+_+_^_/_+_+_+_ &_/_+_+_+_+_>_+_+_+_%_/_+_+_\ +_+_%_+_+_+_>_*_+_+_+_|_/_+_ +_+_&_>_+_+_+_ ^_/_+_+_+_>_>_+_+_+_>_|_+_+\ _+_/_|_+_+_+_&_/_+_+_+_%_|_ +_+_+_+_>_+_+_+_&_@ _+_+_+_+_+_+_+_+_@_/_>_%_%\ _-_*_-_+_+_%_-_%_+_-_/_<_< _^_^_%_<_%_+_-_>_-_<_ -_*_*_/_>_^_&_-_+_/_+_+_&\ _&_+_%_|_<_&_%_<_^_/_@_|_ *_%_*_-_/_%_|_/_*_%_-_- _>_^_<_|_-_^_&_^_/_>_@_|_\ <_<_|_%_+_|_+_-_&_>_>_+_/_<_^_@_^_-_@_/_@_@_*_|_<_-_ -_^_|_<_-_%_|_%_-_|_^_|_@\ _/_|_/_%_<_-_/_&_^_/_@_%_*_@_*_+_/_>_%_<_-_-_>_*_@_/ _>_%_%_@_^_>_%_%_@_&_>_%_\ %_-_^_-_+_+_-_&_*_+_+_-_-_*_+_+_/_@_%_<_^_-_<_-_+_+_ <_<_&_^_^_&_-_>_>_<_@_-_>_\ %_%_@_<_>_%_%_-_@_<_+_+_-_*_&_+_+_-_-_>_+_+_<_-_<_^ _^_/_*_%_<_^_-_*_>_+_+_<_*_\ &_^_^_-_-_^_+_+_<_>_@_^_^_%_^_+_+_+_*_<_*_^_^_+_*_ <_/_*_^_%_|_^_^_%_%_+_+_+_%_\ @_-_+_+_%_&_+_+_+_*_<_*_^_^_+_<_&_<_%_^_*_&_^_^_& _+_<_*_&_*_<_<_&_^_&_*_<_<_@_&\ _+_%_%_<_%_<_@_-_*_&_*_@_@_<_<_&_&_^_^_^_^_%_^_ ^_&_+_<_-_^_@_%_<_^_^_%_<_@_|_-_\ |_-_<_>_<_<_<_&_^_^_%_|_<_>_+_@_|_<_^_^_<_<_& _^_^_|_-_<_<_^_@_-_>_^_^_@_*_>_&_^\ _-_-_*_+_+_%_*_*_|_-_/_@_|_^_^_*_*_>_&_^_*_ -_>_^_^_<_^_&_^_^_^_@_*_^_^_-_-_^_+_\ +_<_>_<_^_^_*_<_>_^_&_<_>_&_^_^_&_+_>_>_< _*_&_>_^_&_*_^_>_^_&_*_/_>_^_&_-_+_/_+_\ +_@_+_+_+_+_+_+_+_+_+_+_+_+_+_+_+_+_+_+ _+_%_%_+_+_+_+_*_@_>_&_^_%_&_^_^_*_<_-_^_\ ^_&_*_<_<_*_&_+_<_<_%_%_|_@_-_*_&_@_%_ <_|_&_%_<_<_|_@_<_-_^_^_<_-_&_^_^_<_@_%_^_^\ _^_%_%_^_^_-_+_/_+_+_@_/_>_%_%_@_^_>_ %_%_@_&_>_%_%_<_>_-_^_^_*_^_-_^_^_*_&_*_^_^_+\ _<_^_&_/_^_<_^_^_^_|_-_-_^_^_^_>_&_& _^_<_-_&_^_^_<_*_&_^_^_@_-_>_^_^_@_*_>_&_^_&_+\ _<_*_&_*_<_<_%_^_<_<_&_^_^_%_|_@_-_* _&_@_*_|_<_@_*_>_<_^_&_+_<_-_^_|_-_<_^_^_-_-_-\ _@_^_<_@_&_^_^_/_>_-_^_^_*_-_>_&_^_*_ *_>_<_^_-_@_&_+_+_/_&_-_^_^_*_-_>_^_^_*_*_>_&_\ ^_+_&_^_&_@_^_*_@_&_^_&_+_|_-_^_*_<_|_ ^_^_%_%_@_-_*_&_*_<_<_%_*_%_|_%_^_&_+_<_<_%_\ &_+_|_*_&_*_|_|_%_^_&_@_%_<_|_&_%_@_<_|_%_<_*_+_+_+_&_&_<_<_^_|_&_^_^_%_<_@_-_*_+_%_%_<\ _|_^_%_&_^_^_&_+_<_*_&_*_<_<_@_^_&_*_<_%_<_%_|_@_-_*_&_*_|_|_@_&_+_@_-_^_*_@_@_@_^_&_+_\ |_|_@_+_^_<_|_%_^_&_^_^_^_<_%_%_^_^_@_%_>_|_^_%_/_+_+_+_-_%_/_@_/_+_|_/_&_<_^_*_|_^_^_%\ _<_+_+_+_+_%_/_&_*_^_<_^_^_^_&_+_<_*_/_*_<_<_^_^_*_|_>_|_^_&_*_<_<_|_&_+_<_<_%_%_|_@_-_\ *_&_@_%_<_|_&_%_<_<_|_&_+_|_-_^_&_-_|_ |_&_&_+_|_|_/_*_|_|_^_^_<_|_|_&_<_&_-_|_|_\ @_&_-_|_|_<_%_@_-_+_+_%_<_@_-_*_+_&_ |_<_/_^_<_^_^_^_<_|_*_%_@_%_@_+_+_+_&_+_\ <_-_^_&_-_<_<_&_&_+_<_<_/_@_|_<_^_^_ <_/_&_^_^_^_&_*_^_^_+_*_@_@_>_^_>_<_^_^\ _*_<_>_|_^_<_<_%_^_^_@_<_>_|_^_%_%_+ _+_+_%_/_+_+_+_+_<_/_&_>_^_@_<_^_^_&_+_\ <_-_^_&_-_<_<_&_&_+_<_<_/_*_<_<_^_^_& _+_<_<_%_&_+_|_*_/_*_|_|_^_^_&_+_<_<_|_%_\ %_+_+_+_%_|_@_-_*_+_^_<_|_<_^_<_^_^_^_&_- _<_<_|_%_%_-_+_+_&_+_|_-_^_&_-_|_|_&_&_+_|_|\ _/_@_<_|_^_^_<_/_&_^_^_^_^_@_^_^_&_+_<_-_^_*_|_>_|_^_@_|_<_^_^_<_^_%_^_^_^_&_<_%_^_*_^_\ -_%_^_%_/_+_+_+_+_|_/_^_>_^_@_&_^_^_&_+_|_/_&_+_|_|_^_%_^_+_&_^_^_&_+_<_-_/_&_+_|_-_|_*\ _|_|_^_^_@_|_<_^_^_<_/_&_^_^_^_^_%_^_^_&_+_<_-_/_*_<_<_%_^_+_*_<_<_|_<_/_%_^_^_@_/_-_%_\ ^_<_>_/_^_^_*_&_>_^_&_*_^_>_^_&_*_/_>_^_&_-_+_/_+_+_%_|_+_+_+_*_<_-_^_^_+_*_<_%_|_^_|_^\ _^_^_<_|_&_^_^_<_-_&_^_^_^_>_%_^_^_-_-_|_+_+_-_+_/_+_+_+_*_@_%_&_^_+_&_^_^_*_<_*_^_^_@_\ <_-_^_^_<_-_&_^_^_<_*_&_^_^_<_@_%_^_^_^_|_%_^_^_-_+_/_+_+_%_<_<_@_@_%_|_-_+_+_>_-_<_|_*\ _-_+_/_+_+_/_@_@_<_-_&_&_+_%_|_<_&_%_<_^_/_@_|_*_%_*_-_/_%_|_/_*_%_-_-_>_^_<_|_-_^_&_^_\ /_>_@_|_<_<_|_%_+_|_+_-_&_>_>_+_/_<_^_@_^_-_@_/_@_@_*_|_<_-_-_^_|_<_-_%_|_%_-_|_^_|_@_/\ _|_/_%_<_-_/_&_^_/_@_%_*_@_*_+_/_>_%_<_-_-_>_*_*_+_-_|_>_&_|_%_|_@_@_>_/_&_/_%_<_<_>_>_
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/FE-CTF/2022/rev/snake-jazz/magic.py
ctfs/FE-CTF/2022/rev/snake-jazz/magic.py
import sys,os class X(object): def __init__(x,a=0,b=0,c=0): x.a=a x.b=b or ~-a x.c=c def __invert__(x): x.c-=x.c return X(x.a,x.b,x.c) def __pow__(x, y): x=~x x.a*=y x.b*=y x.c+=3 return x def __pos__(x): x**=3 x.b=-~x.b return x def __neg__(x): x**=3 return x def __or__(x, y): y**=(~x).a y.b+=x.b return y def __add__(x, y): return x|+y def __sub__(x, y): return x|-y def __del__(x): if not x.c: return y=[0]*9 while 3**y[8]<x.a: z=x.b//3**y[8]%3**7 y[8]+=7 a=z//3**4 b=z//9%9 c=z%9 d=c+x.b//3**y[8]%3**7*3*3 if a==0: os._exit(0) elif a==1: y[8]+=7 y[b]=d elif a==2: y[b]=y[c] elif a in(3,8): y[b]=x.b//3**y[c]%3**(3*3) if a==8: y[c]+=9 y[c]%=3**9 elif a in(4,6,7): if a==6: y[8]+=7 b,c,d=8,7,d or y[b] if a>4: y[c]-=9 y[c]%=3**9 x.b+=y[b]*3**y[c]-x.b//3**y[c]%3**9*3**y[c] if a==6: y[8]=d elif a==5: if y[b]: y[8]=d else: y[8]+=7 pass elif 9<=a<=12: y[b]={ 9:lambda a,b:a<b, 10:lambda a,b:(a+b)%3**9, 11:lambda a,b:(a*b)%3**9, 12:lambda a,b:(a-b)%3**9, }[a](y[b],y[c]) elif 13<=a<=15: e,f=0,y[c] for _ in range(9): e*=3 e+={ 13:lambda a,b:~(a+b)%3, 14:lambda a,b:min(a,b), 15:lambda a,b:max(a,b), }[a](y[b]%3,f%3) y[b]//=3 f//=3 for _ in range(9): y[b]*=3 y[b]+=e%3 e//=3 elif a==16: y[b]=y[b]*3**c%3**9 elif a==17: y[b]=y[b]//3**c elif a==18: y[b]=ord(sys.stdin.read(1)) elif a==19: sys.stdout.write(chr(y[b]));sys.stdout.flush() else: 0/0 for i in range(1, 100): setattr(sys.modules['__main__'],'_'*i,X(3**i))
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/FE-CTF/2022/rev/snake-jazz/runme.py
ctfs/FE-CTF/2022/rev/snake-jazz/runme.py
#!/usr/bin/env python3 import magic;_+___+---+---+-__+++-+_-_+_++_++++-+-_+_++_-__-_-+++-++---\ _+_+-+++-+--++__-++___++++_-+_-+__+-+++_-+-_-_-_+_+++-_+--++-_+_-+_---_\ +_-+--_-++_+_--_--+_++_+__-++-+_++--+__+__++-___++_+_--__-_-__--+--_-_-\ --++__-+-____-_+++-_++---+-__+++++_+-+++-___+_++-__-_--_-_-_--+-+++--_-\ _++______++-+-++_++-_-_+-+-_+++_--__--___-+_+++-++_+-++_-+-+-_+--_++-_-\ -++---+__+_____+__--+_--+++__+--+_+--+___-+++++++_+-+_++_-_+-+__-_++++-\ +-__+_++____+_-+-+-+__+-+_-+--_+++__----++-++-+__+-+----__-+_++__+++_-+\ +_+--+--__--+_++__+--++_+-_-_++-_-+-_+_+__++-++_+++++-__+_---+_+_+-+-__\ ++-----++-+--_-_++__+--__++-___-_+-+__+-+__+_---_+++_--+-+-+_++_-+++__+\ +-_--+++++--_+_++_--_-+___-___+++-_++++-++-+_++-++_-+++++_+-__---_-_--_\ -+_-+-__+_--+++_-__+_+_-+-++---+_+-+-+__+++_----_-+_-+-+_-++___---++-__\ +-+_+_+--_+---+++--++__+_-+----_--_+_-+_-+_+-+---++_+++-+_+_____----+-+\ ++-+__+--_++--_-___+_+_-+--_++--+++__--+_+_-+_-----+_+_+-___+++-+__-+__\ -+___++-++_+___-+-_+_-_----_--+_+_-___+_____-_+_+_-+--+__-_+++-_-++__-_\ +++-__--++-+++_+_+__+--___-+-_--_-++-+-+-_+ +_++++___--+__-+_--__+_-__+\ ____---___++++-+_-+__---__++-++-+-__-+-_-++_----_+-+_+_-__+_+____-_+---\ _+--+-_+----_+--++___--__-+-_-+++-+--_+_+__-+_--++-----+++_-_-+_+_-+-+-\ ---+_+-+++__+++_-_--_-+_-+++_-++____--++-__+++_+_+--_----+++--_+__+_-+-\ _--_--_+_++_-+_+-+_--++_+++++_+______---+-+++++__+--_+---_-___+-+_-+--_\ +---+++__-++_+_-++_+---+_+_+-+__+++-+_--_-+___-+_-++__+_+_++-_-___++---\ +_-__-++_+_+----_+_-++___--__+--_-++++++_-++-+-_--++-___-+_+_+--++---++\ +---+__+_-+-+--_--_+__+_-+_+-++--++_+++_+_+_____+---+-+++_+__+--_+_--_-\ ___+++_-+--_+_--+++__-_+_+_-++_----+_+-__+__+++-___-_-+_+_-_+-_-+_-+__+\ +-++--_-__+__--_+-+-_+_-__+---_-+_-_+_--___+--+-___+_+_+-+___--+++-++-+\ _+_-+_+++_-+-__+--+_-++-++_++_-+-+---++--+-+__+_+--_--_--_++_+_-+_+-_+-\ -++_+++-+_+_____----+-+++-+__+--_++--_-___+_+_-+--_++--+++__--+_+_-++__\ ---+_+_+_+__++++_+--_-+__+_-_-++__-_+-__+_-_---_++_+_-+_--__-+---++-_+-\ ++_+_+-+-+---+++_- -+__+_-_+-_-_-- _++-++-_+--_----_-++_-___-++____-++-\ ___-_++_+_-_+__--+-+-+_--___+++_+___--_-___++_-_+_-+__+-+-_++-+_+_-__-+\ ---+__--------_+_-_--+_____---_+_-+--_+___+++----___-_+_-+-_--++++_-_+_\ +_-+_-+__-++_-+_-_-_-+_-_+-___-_-__+++_-___-__--__+_+-++_--___+-_+++-_-\ _+-+++_++-------_--_+++++_+__-_+_+-__+-+-_-+--_-+_----+------+_+-+-__+-\ --+--+--+__+-++++--_-___-++_-+--___--+++__--+_+_-++__---+_+_+_+__+++-+-\ --_-+____+_-++_-_+--++-_+__+_+_+-+++---+++_-_+__+_-_++--_--_++_-_-+_+-_\ ++-__----_--_+_++_-+_--+++-_--+++_--++_+_-++-+_--+_+++__+_+++_+_-__-_-_\ +_+------++--+-+-_-++_+--+++----++-_-++__+_++----_--_---+_-+_++-+--++_+\ --_+_+___-__---+-+-+-+__+-------_-__+_++_-+---__--+++_++_+_+_-+_-_---+_\ +++++__+++++---_-+_+_++_-++_-+-+_++-__++-++---+__++--_++-+---__+_---__-\ __++-+----+_-_+-+-+-+__---+++-+-+__+_-+__--_--_+_++_-+_+-+_--++_+++++_+\ ______---+-+++++__+--_+---_-___+-+_-+--_+_+_+++__-++-+-_-_+++--_-++__+-\ +-_-_+_+--_-++_++-+-_-_+-+--_-++_-+-+-_-_+++--_-++__+-+-_-_+_+--_-++_++\ -+-_-_+-+--_-++_-+-+-_-_+++--_-++__+-+-_-_+_+--_-++_++-+-_-_+-+--_-++_-\ +-+-_-_+++--_-++__+-+-_-_+_+--_-++_++-+-_-_+-+--_-+_--+++-_-+_+--_-+__+\ _+_-++_-----++-_+_-+_+_+-++----+++_--+__+_-_+---_--_-+-+_-+_++__--++_++\ -+-_+____-++-++++__-+_-+_-_++-+____+___-__-___-_-+-+__+---++_---++_+-+-\ ++_+_-+--_-_-+__++__+_-__++--+_-+---++_--++-+--++_+--__-_+_-++-----+__-\ _____-___++_+_-+-_+++_--+++-++++_+-_++-++_-+___+--+____+-__-__-__+-_-+-\ +__----++_--_-+_+-+-____--+--_++-+_+-__-_++_--+-+_--+_+_+-++_+++--++---\ +_-_-_+__++__- _--_-+_+__+_-++_--+--++-_-_- +_+_+---__--++++_-_+_+_-+_+\ ___-++_--_-++-_---_++_+_-_-__--+-_-__--___+-__+___-++____+ +_---_-+__++\ ___++-+_+-___-+--+_+_------+-_+_-_-+_-____---_-_-+--___-_+++---++__-_+_\ +___--++++___+_+_-+_____-++_-__-++-_--+_++_+_-____--+-_--_--___+-+_+___\ -+-_+__++_--++-_-+_+----_+_+-__+_--++___--+++_+__+_+_-+-_-_--+_+-+__+_+\ ++_++___-_-+_+_-++_-+-+_++__+-_+-+---+-+_-+_+---+--+_---+_+++_+-_--__-+\ _+-_+__++- _-+__+_-+__+_---++_+-__-_+___++++-+++++++_--+_-++-_+_++-+__+\ __-__-_+--_-+-_+--_-+++-+++-__+-_--_-_++_+-+_+--_+__++_+_--------+_+_-+\ -__++++-_+--__-+-__-+-++-+-_+++__+--+_-__++-+_-++++-___++_-_-+--_--_+_-\ -+-_-_-_+---_++_+--+_--__--_--++-_-___++_+--++_+_+---_--+_--+-+_++-++++\ +_---_-_+_++__-+-__++__-_--+-_+-+_+-_-__+-+_-_-+-_++_---_-_+-_++-++---+\ _-_---_++++--__--_++-----_++_+-___--_-_+--+_-++-_-+----_-++++-+____-_--\ ___-_+-_+-+-_+_++_++___--++--__++_+__+-_--+__-+_+-_++--+_+--+_+-_-+-_++\ +__+-+-+_-+-+-_--++__-__+_+_++---__-+_+-++---++__+--+--+_-_+_+-+_-__---\ +--+_++__+-++__--_-__+_-_+-+--+-+_+-+++-+--++-_---+++++-++_---_--_++-_+\ -+_++_-++-+_+-_+---__-+_++__-_-+----_-+-_+++_-+++_-_--++-_-+++_+_+-_+--\ --++++-_+__+_------_--___++_-+_+__+--++_+_-++_+___++_---+-+_+++__+--+__\ --_-__-+-+_-+--+-+--+++_--_+_+_-+------+_+++_-__+++__+_--__-_+__+___+_-\ -___++-____-+____-__++-+-+_+__-+-+_+__----+-_+_+_-_++_-____-++_--_+---_\ -_+---__+----+-_+_-+_++-_---+--___++-__+-+++_-+_+-+-_-_+__+----++_-_+_-\ ____+--+-_+-__+_+--+__-_--_+-+_+-_+-+++__++_+-___-___++-__+-+_+_-___+-+\ _--__-_++__-__+--_+-++__+_--++-_-_-+_+--_+-_-+_-___++-+-_-_-__+_+---+-+\ -___++++--+--_--_--_-+_+_-+_++_---++_+-__+_+____++---+-+-+-+__+--_++--_\ -__++++_-+--_+_--+++_+-++_+_-++_----+_+++++__+++--_+__-+_-_--+-+-+__+_-\ +--___+_-__----+_+-++_+____+-_+_-__-_+-+_++_+-------__+__+_+-_-_-___+-_\ +-__++_+__++++++__-__-_-_-_+-++++_+__+-_-_+-_-_+---+__+---_---__ +__---\ __-_-_+_-__+-__--+-__+++-____-__-+-_+_+-++--_+__+-___-__-_+-_-___+---+_\ -_-_+___+-++-++++-__---+_-+--+__++_--+--_-+_++_+_-++_-_++_++-___+-++---\ -_-++--_++_+---__+_--+__-__--++__-+-+_++--+-+_+--++--_---++--__+-+---__\ ++_++__-__+++--_-+--+_+_-++++__--++-_+_-+_+_+-++----+++_--+__+_-_+---_-\ -_-+-+_-+_++__--++_+--++_+___-_----+-+-+_+__+----+--_-__+_-+_-+---_---+\ ++_++-_++_-+_----_+++__++_-_-___+--++-_-__+_+_+--_----+++_+-+__+_--+-+-\ _--__+---_+-++--+_----__+--++__-+-+_+__++++---+-+---+__+---+_--_-__+_++\ _-+---__--+++_++_+_+_-+_-_---+_+++++__+++--_+__-+_-_--+-+-++__+++--_-+_\ --_--__+-+_-+_+++_--++_+_-_+_+___-__---+-+_+-+__+----+--_-__-_++_-+----\ _--+++_-+++_+_-+_-----+_+-+_+__+++++_--_-+__-_+_-++_+-_--++-___++_+_+-+\ __+--+++---+-+-+___-_--+++---_-_+_-+_+-_+___++-__-+_++_-_+-+++++----+-_\ ++++__++_+__+__-+_--_---+-+--_++_++-+-_+-_+_-+-_--_-+___++_--_--+-+_++-\ _-_++-+---+-+---__--_--__-+--__+---+-_+++-+--+_+-_--+_-++-_-_++-_-___+_\ -+-+-_+__++_----++_-++-_++-+---+_-__-__++_-+-+_--+-+++_-+-__+-__++_+_++\ +++--+--_-_-_+-_+--++_--_---___+--_-+---+++_++-++_-+-+------+--__-+_--+\ +--++_-_---_-_-___-+-+_-+-+-+--_+-_+_-+--+_-___++--___-++_+___+-+_+++--\ --+_++-__+_+_-__+_-+--+-_+-___-_-+++__+___-+-+-+___+-+-+-++----+-_+_-++\ +++_++-_++__-_-___---+_++--+__+_-+_+-__--_+-++-_--+---+__+-+___-+-+++-_\ +_-+-_-+++-___++++++__+++-_-+--+-_+-_+-+--_--++--__-+_--++--+-+_-+--_-+\ _++-++++__----_-_--+++_--++__--_+__-_++_-_____+-_+++++--_--_-_--__+--+-\ -+__-__+_++-+--+--------_-+---------_+-++----+---++-_+-+---++_--_++++++\ _-++++-+--_+--+-+-+-+-_---_++_-_+--+_+_+_+-_--_++_+--_-+---_+--+-------\ _+-+-+-__-+-++--__---+-_--++_-__+--_+---+--___+--------+-+_+++++_-_-+--_
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/FE-CTF/2022/crypto/trust-issues/mac.py
ctfs/FE-CTF/2022/crypto/trust-issues/mac.py
#!/usr/bin/env python3 import sys import random import base64 import struct KEY_LEN = 16 TAG_LEN = 16 def generate_key(): return random.randbytes(KEY_LEN) def import_key(path): key = base64.b64decode(open(path, 'rb').read().strip()) assert len(key) == KEY_LEN return key def export_key(key, path): open(path, 'wb').write(base64.b64encode(key) + b'\n') def xor(s, t): return bytes(x ^ y for x, y in zip(s, t)) def enc(k, b, n=32): v0, v1 = struct.unpack('!2I', b) s, d, m = 0, 0x9e3779b9, 0xffffffff for _ in range(n): v0 = (v0 + (((v1 << 4 ^ v1 >> 5) + v1) ^ (s + k[s & 3]))) & m s = (s + d) & m v1 = (v1 + (((v0 << 4 ^ v0 >> 5) + v0) ^ (s + k[s >> 11 & 3]))) & m return struct.pack('!2I', v0, v1) def mac(key, buf, iv=None): buf += b'\0' * (8 - len(buf) % 8) k = struct.unpack('!4I', key) iv = iv or random.randbytes(8) c = iv for i in range(0, len(buf), 8): p = buf[i : i + 8] c = enc(k, xor(p, c)) tag = iv + c assert len(tag) == TAG_LEN return tag def sign(key, buf): tag = mac(key, buf) return \ b'-----BEGIN MAC-----\n' + \ base64.b64encode(tag) + b'\n' \ b'-----END MAC-----\n' + \ buf def verify(key, buf): line, buf = buf.split(b'\n', 1) assert line == b'-----BEGIN MAC-----' b64tag, buf = buf.split(b'\n', 1) tag = base64.b64decode(b64tag) line, buf = buf.split(b'\n', 1) assert line == b'-----END MAC-----' tag2 = mac(key, buf, tag[:8]) if tag == tag2: return buf if __name__ == '__main__': def usage(): print( f'usage: {sys.argv[0]} genkey [--seed SEED] KEYFILE\n' f' OR {sys.argv[0]} sign [--seed SEED] KEYFILE < FILE > FILE\n' f' OR {sys.argv[0]} verify KEYFILE < FILE', file=sys.stderr ) exit(1) if '--seed' in sys.argv: i = sys.argv.index('--seed') try: seed = int(sys.argv[i + 1]) except: usage() random.seed(seed) sys.argv[i : i + 2] = [] argc = len(sys.argv) if argc != 3: usage() cmd = sys.argv[1] keyfile = sys.argv[2] if cmd == 'genkey': key = generate_key() export_key(key, keyfile) elif cmd in ('sign', 'verify'): key = import_key(keyfile) if cmd == 'sign': sys.stdout.buffer.write(sign(key, sys.stdin.buffer.read())) else: if verify(key, sys.stdin.buffer.read()): exit(0) else: exit(1) else: usage()
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/FE-CTF/2022/crypto/trust-issues/vm.py
ctfs/FE-CTF/2022/crypto/trust-issues/vm.py
#!/usr/bin/env python3 import sys import os import time import types class VM(object): OP_VLQ = 0x80 OP_NEW = 0x81 OP_SHOW = 0x82 OP_SAVE = 0x83 OP_DIG = 0x84 OP_BURY = 0x85 OP_ZAP = 0x86 OP_POP = 0x87 OP_PULL = 0x88 OP_PEEK = 0x89 OP_PUSH = 0x8a OP_DUP = 0x8b OP_OVER = 0x8c OP_SWAP = 0x8d OP_SWIZ = 0x8e OP_IF = 0x8f OP_JMP = 0x90 OP_JZ = 0x91 OP_JNZ = 0x92 OP_CALL = 0x93 OP_RET = 0x94 OP_ADD = 0x95 OP_SUB = 0x96 OP_NEG = 0x97 OP_INC = 0x98 OP_DEC = 0x99 OP_MUL = 0x9a OP_DIV = 0x9b OP_MOD = 0x9c OP_AND = 0x9d OP_OR = 0x9e OP_XOR = 0x9f OP_NOT = 0xa0 OP_LSH = 0xa1 OP_RSH = 0xa2 OP_EQ = 0xa3 OP_NE = 0xa4 OP_LT = 0xa5 OP_LE = 0xa6 OP_GT = 0xa7 OP_GE = 0xa8 OP_SYS = 0xa9 OP_HLT = 0xaa OP_BRK = 0xab SYS_GETC = 0 SYS_PUTC = 1 SYS_OPEN = 2 SYS_CLOSE = 3 SYS_READ = 4 SYS_WRITE = 5 SYS_TIME = 6 SYS_LIST = 7 def __init__(self, code, singlestep=False): self.stack = [] self.rstack = [] self.pc = 0 self.prog = [] self.halted = False self.singlestep = singlestep self.gen_tables() self.decode(code) def decode(self, code): i = 0 def next(): nonlocal i if not code: raise ValueError b = code[i] i += 1 return b def vlq(): n = 0 i = 0 while True: b = next() n |= (b & 0x7f) << i * 7 i += 1 if not b & 0x80: break n = (n >> 1) * (-1 if n & 1 else 1) return n while i < len(code): b = next() op = self.op_table.get(b) if op: self.prog.append(op) elif b == VM.OP_VLQ: self.prog.append(vlq()) else: # XXX: ISA requires n < 0x80, we should probably check this self.prog.append(b) def ctx(self): stack = [] max_stack = 16 for e in self.stack[:max_stack]: x = f'{e:02x}' if 32 <= e <= 126: c = chr(e) elif e == 10: c = '\\n' else: c = None if c: x += f'(\x1b[32;1m{c}\x1b[m)' stack.append(x) print('%-3d[ %s%s' % ( len(self.stack), ' '.join(stack), ' ...' if len(self.stack) > max_stack else ''), end=' ', file=sys.stderr, ) op = self.prog[self.pc] print(f'0x{self.pc:04x})', file=sys.stderr) if isinstance(op, int): print(f'# {op:#x}', file=sys.stderr) else: print(op.__name__[3:], file=sys.stderr) def run(self): while not self.halted and self.pc < len(self.prog): if self.singlestep: self.ctx() op = self.prog[self.pc] self.pc += 1 if isinstance(op, int): self.push(op) else: op() def gen_tables(self): optbl = dict() systbl = dict() for uname in dir(self): lname = uname.lower() if uname.isupper() and hasattr(self, lname): n = getattr(self, uname) if uname.startswith('OP_'): optbl[n] = getattr(self, lname) elif uname.startswith('SYS_'): systbl[n] = getattr(self, lname) self.op_table = optbl self.sys_table = systbl def push(self, *xs): self.stack[0:0] = xs def pop(self, i=0): return self.stack.pop(i) def show(self, n, i=0): return self.stack[i:i+n] def save(self, xs, i=0): self.stack[i:i] = xs def zap(self, n, i=0): xs = self.show(n, i) self.stack[i:i+n] = [] return xs def op_new(self): self.stack += [0] * self.pop() def op_show(self): n = self.pop() i = self.pop() self.save(self.show(n, i)) def op_save(self): n = self.pop() i = self.pop() self.save(self.show(n), n + i) def op_dig(self): n = self.pop() i = self.pop() self.save(self.zap(n, i)) def op_bury(self): n = self.pop() i = self.pop() self.save(self.zap(n), i) def op_zap(self): n = self.pop() i = self.pop() self.zap(n, i) op_pop = pop op_pop.__name__ = 'op_pop' def op_pull(self): self.save(self.zap(1, self.pop())) def op_peek(self): self.save(self.show(1, self.pop())) def op_push(self): n = self.pop() self.save(self.zap(1), n) def op_dup(self): self.save(self.show(1, 0)) def op_over(self): self.save(self.show(1, 1)) def op_swap(self): self.push(self.pop(1)) def op_swiz(self): self.push(self.pop(2)) def op_if(self): f = self.pop() t = self.pop() c = self.pop() self.push(t if c else f) def op_jmp(self): self.pc = self.pop() def op_jz(self): x = self.pop() if self.pop() == 0: self.pc = x def op_jnz(self): x = self.pop() if self.pop() != 0: self.pc = x def op_call(self): self.rstack.append(self.pc) self.op_jmp() def op_ret(self): self.pc = self.rstack.pop() def op_add(self): self.push(self.pop() + self.pop()) def op_sub(self): x = self.pop() self.push(self.pop() - x) def op_neg(self): self.push(-self.pop()) def op_inc(self): self.push(self.pop() + 1) def op_dec(self): self.push(self.pop() - 1) def op_mul(self): self.push(self.pop() * self.pop()) def op_div(self): x = self.pop() self.push(self.pop() // x) def op_mod(self): x = self.pop() self.push(self.pop() % x) def op_and(self): self.push(self.pop() & self.pop()) def op_or(self): self.push(self.pop() | self.pop()) def op_xor(self): self.push(self.pop() ^ self.pop()) def op_not(self): self.push(~self.pop()) def op_lsh(self): x = self.pop() self.push(self.pop() << x) def op_rsh(self): x = self.pop() self.push(self.pop() >> x) def op_eq(self): self.push(int(self.pop() == self.pop())) def op_ne(self): self.push(int(self.pop() != self.pop())) def op_lt(self): x = self.pop() self.push(int(self.pop() < x)) def op_le(self): x = self.pop() self.push(int(self.pop() <= x)) def op_gt(self): x = self.pop() self.push(int(self.pop() > x)) def op_ge(self): x = self.pop() self.push(int(self.pop() >= x)) def op_sys(self): self.sys_table[self.pop()]() def op_hlt(self): self.halted = True def op_brk(self): self.ctx() def sys_getc(self): self.push(*sys.stdin.buffer.read(1) or [0]) def sys_putc(self): sys.stdout.write(chr(self.pop() & 0xff)) sys.stdout.flush() def popstr(self): s = '' while True: b = self.pop() if not b: break s += chr(b) return s def pushstr(self, s): self.save(list(s)) def sys_open(self): flag = self.pop() try: self.push(os.open(self.popstr(), flag, 0o644)) except: self.push(-1) def sys_close(self): os.close(self.pop()) def sys_read(self): n = self.pop() s = os.read(self.pop(), n) self.pushstr(s) self.push(len(s)) def sys_list(self): try: ds = os.listdir(self.popstr()) except: self.push(-1) return for d in sorted(ds, reverse=True): self.pushstr(d.encode()) self.push(len(d)) self.push(len(ds)) if __name__ == '__main__': import click import mac import signal import base64 import pwd import grp signal.alarm(300) @click.command() @click.argument( 'program', required=False, type=click.File('rb')) @click.option( '--singlestep', '-s', is_flag=True, help='Break after every step.') @click.option( '--key-file', metavar='FILE', help='MAC key used to verify signed programs.') @click.option( '--user', '-u', metavar='USER', help='Set user.') def main(program, singlestep, key_file, user): '''Stack machine emulator.''' if program: program = program.read() else: program = base64.b64decode(sys.stdin.buffer.readline()) if program.startswith(b'-----BEGIN MAC-----'): if not key_file: print('Program is signed; a key is required', file=sys.stderr) exit(1) program = mac.verify(mac.import_key(key_file), program) if not program: print('MAC error', file=sys.stderr) exit(1) elif key_file: print('Program must be signed', file=sys.stderr) exit(1) if user: try: uid = pwd.getpwnam(user).pw_uid os.setgroups([]) os.setgid(uid) os.setuid(uid) except OSError: print('Could not change user', file=sys.stderr) exit(1) except KeyError: print('No such user:', user, file=sys.stderr) exit(1) try: vm = VM(program, singlestep) vm.run() except: print('Magic smoke got out', file=sys.stderr) exit(1) main()
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/Tamil/2021/crypto/AEXOR/enc.py
ctfs/Tamil/2021/crypto/AEXOR/enc.py
from Crypto.Cipher import AES from os import * from binascii import * from pwn import xor from TamilCTF import * key = getkey() rep_key = getsubkey() enc = b'' for i in range(len(key)): enc += hexlify(xor(key[i],rep_key[i%len(rep_key)])) msg = flag() iv = urandom(16) cipher = AES.new(key,AES.MODE_XXX,iv) ciphertext = hexlify(cipher.encrypt(msg)) print(ciphertext) print(hexlify(iv)) print(enc)
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/SpookyCTF/2024/crypto/encryption_activated/encrypt.py
ctfs/SpookyCTF/2024/crypto/encryption_activated/encrypt.py
def mycipher(myinput): global myletter rawdecrypt = list(myinput) for iter in range(0,len(rawdecrypt)): rawdecrypt[iter] = chr(ord(rawdecrypt[iter]) + ord(myletter)) myletter = chr(ord(myletter) + 1) encrypted = "".join(rawdecrypt) print("NICC{" + encrypted + "}")
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/ECW/2025/Quals/web/Alice_and_the_Literal_Escape/src.py
ctfs/ECW/2025/Quals/web/Alice_and_the_Literal_Escape/src.py
from fastapi import FastAPI, Request, Form from fastapi.templating import Jinja2Templates from fastapi.responses import HTMLResponse from guard.middleware import SecurityMiddleware from guard.models import SecurityConfig import psycopg2, subprocess, textwrap, os, json TRUSTED_IPS = ["127.0.0.1"] app = FastAPI() config = SecurityConfig( whitelist=TRUSTED_IPS, blacklist=[], ) app.add_middleware(SecurityMiddleware, config=config) conn = psycopg2.connect("dbname=postgres") PSQL = ["psql", "-d", "postgres", "-q"] templates = Jinja2Templates(directory="templates") @app.get("/", response_class=HTMLResponse) async def home(request: Request): return templates.TemplateResponse("index.html", {"request": request, "reply": None}) @app.post("/cargo/upload") async def cargo(request: Request, note: str = Form(...)): sql = f"INSERT INTO notes VALUES('"+note+"');" proc = subprocess.run( PSQL, input=sql, capture_output=True, text=True ) reply = json.dumps({ "rc": proc.returncode, "out": proc.stdout, "err": proc.stderr, }, indent=2, ensure_ascii=False) return templates.TemplateResponse("index.html", {"request": request, "reply": reply})
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/Kind4SUS/2025/misc/talking_to_the_void/server.py
ctfs/Kind4SUS/2025/misc/talking_to_the_void/server.py
from subprocess import run, PIPE from secrets import token_bytes from hashlib import sha256 from base64 import b64encode, b64decode from time import sleep class RNG: def __init__(self): secret = token_bytes(16).hex() def digest(state): state = secret + state state = sha256(state.encode()).digest() state = b64encode(state).decode() return state self._digest = digest self._memory = set() self.reset() def reset(self, seed=""): if seed in self._memory: print("Nope: hard reset...") self.__init__() return self._state = seed def step(self): state = self._state ans = self._digest(state) self._memory.add(ans) self._state = ans return ans def run_shell(self, n): n = int(n) for i in range(3, 0, -1): print("Thinking" + "." * i, flush=True) sleep(20) state = self.step() cmd = state[:n] print("Running:", cmd, flush=True) res = run([cmd], text=True, stdout=PIPE, stderr=PIPE) ans = res.stdout.split() ans = [token for token in ans if token.startswith("KSUS")] ans = "\n".join(map(self._scramble, ans)) return ans def _scramble(self, message): secret = self._state secret = b64decode(secret) message = message.encode() ans = bytes(x ^ y for x, y in zip(message, secret)) ans = b64encode(ans).decode() return ans def main(attempts=256): x = RNG() print(""" Options: > exit > reset {seed} > step > shell {n_char} Your choice? """) while attempts: y = input("?\n") if not y: continue y, *args = y.split() if y == "exit": break elif y == "reset": x.reset(*args) elif y == "step": ans = x.step() print(ans) elif y == "shell": ans = x.run_shell(*args) print(ans) break else: print("Invalid choice") attempts -= 1 from signal import alarm if __name__ == "__main__": alarm(321) try: main() except Exception: print("Something went wrong") print("bye!")
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/Kind4SUS/2025/misc/gravity_well/server.py
ctfs/Kind4SUS/2025/misc/gravity_well/server.py
#!/bin/env python3 from subprocess import run def test_len(*args): return lambda x: len(x) in range(*args) def test_ascii(x): return str.isascii(x) def test_alpha(x): return str.isalpha(x) def test_upper(x): return str.isupper(x) def test_on(x): return lambda test: test(x) def safe(x): return "'" not in x def test(x, *tests): if (not safe(x)) or not all(map(test_on(x), tests)): print("Nuh-uh") exit(0) return True def main(): par = input("parameter> ") test(par, test_len(5, 10, 2), test_alpha, test_upper) val = input("value> ") test(val, test_len(30), test_ascii) cmd = input("script> ") test(cmd, test_len(20), test_ascii) all(test(x, test_alpha) for x in cmd.split(" ")) with open("flag.txt") as f: flag = f.readline().rstrip() run([ "podman", "run", "--rm" , "python:3.13.2-alpine" , "sh", "-c", f"echo '{flag}' > flag.txt && {par}='{val}' python -Ic '{cmd}'"]) if __name__ == "__main__": try: main() except: pass
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/Kind4SUS/2025/pwn/The_kindling_of_the_first_Flag/chall.py
ctfs/Kind4SUS/2025/pwn/The_kindling_of_the_first_Flag/chall.py
import hashlib from Crypto.Cipher import AES from Crypto.Util.Padding import pad, unpad import os import base64 import random FLAG = "JlLScp2qTzfFZ7kIYP6Jm5Mv/2h6p26S0OWgmXYdEMAl1Sjg6hwW95bPsZdtiggvHVVv8zM+x7vRw2qOr3ORbw==" RED = "\033[0;31m" PURPLE = "\033[0;35m" ITALIC = "\033[3m" BOLD = "\033[1m" UNDERLINE = "\033[4m" END = "\033[0m" # don't mind the crypto stuff class Cipher: def encrypt(self, plainText, key): iv = os.urandom(16) privateKey = hashlib.sha256(key.encode("utf-8")).digest() cipher = AES.new(privateKey, AES.MODE_CBC, iv) encryptedBytes = cipher.encrypt(pad(plainText.encode(), AES.block_size)) return base64.b64encode(iv + encryptedBytes).decode() def decrypt(self, encrypted, key): encryptedData = base64.b64decode(encrypted) iv = encryptedData[:16] privateKey = hashlib.sha256(key.encode("utf-8")).digest() cipher = AES.new(privateKey, AES.MODE_CBC, iv) try: decryptedBytes = unpad(cipher.decrypt(encryptedData[16:]), AES.block_size) except: die(1) return decryptedBytes.decode() places = ["Cemetery of Ash", "Grand Archives", "Profaned Capital", "Farron Keep", "Anor Londo", "High Wall of Lothric", "Undead Settlement", "Firelink Shrine", "Road of Sacrifices", "Irithyll Dungeon", "Catacombs of Carthus", "Lothric Castle", "Cathedral of the Deep","Irithyll of the Boreal Valley","Untended Graves","Kiln of the First Flame"] routes = [ [60, "Firelink Shrine", "Kiln of the First Flame", "Undead Settlement", "High Wall of Lothric"], [-10, "Lothric Castle", "High Wall of Lothric", "Irithyll of the Boreal Valley", "Untended Graves"], [12, "Irithyll Dungeon", "Grand Archives", "Undead Settlement", "Kiln of the First Flame"], [-5555, "Road of Sacrifices", "Catacombs of Carthus", "Anor Londo", "Cathedral of the Deep"], [555, "Irithyll of the Boreal Valley", "Irithyll Dungeon", "High Wall of Lothric", "Cemetery of Ash"], [3, "Firelink Shrine", "Undead Settlement", "Lothric Castle", "Untended Graves"], [1015, "High Wall of Lothric", "Road of Sacrifices", "Irithyll Dungeon", "Grand Archives"], [35, "Kiln of the First Flame", "High Wall of Lothric", "Cemetery of Ash", "Irithyll of the Boreal Valley"], [143, "Cathedral of the Deep", "Farron Keep", "Undead Settlement", "Lothric Castle"], [1551, "Irithyll of the Boreal Valley", "Profaned Capital", "High Wall of Lothric", "Farron Keep"], [70, "Farron Keep", "Irithyll of the Boreal Valley", "Grand Archives", "Firelink Shrine"], [77, "High Wall of Lothric", "Untended Graves", "Grand Archives", "Farron Keep"], [718640, "Farron Keep", "Road of Sacrifices", "Profaned Capital", "Anor Londo"], [869, "Anor Londo", "Irithyll Dungeon", "Catacombs of Carthus", "Road of Sacrifices"], [6969, "Lothric Castle", "High Wall of Lothric", "Kiln of the First Flame", "Cathedral of the Deep"] ] position = "" path = [] def checkFlag(): global path aes = Cipher() a = "" b = "" for p in path: if path.index(p) % 2 == 0: a += f"{p[0]+p[-1]}" else: b += f"{p[0]+p[-1]}" key = a+b attempt = aes.decrypt(FLAG,key) if "KSUS" not in attempt: die(1) else: print(f"\nYou hear that sweet female voice again, this time clearer.\n{ITALIC}Well done, Unflagged...{END}, she muses as a torn piece of parchment manifests itself in front of you:") print(f"{PURPLE}{attempt}{END}") exit() def printLocationDetails(): global position print(f"\nYou find yourself in a place called {PURPLE}{BOLD}{position.upper()}{END}.") print("A number of dangerous paths, crawling with enemies, open in front of you... An infinite sea of possibilities.\nWhere will you go?\n") for i,r in enumerate(routes[places.index(position)][1:]): print(f"\t{i}. {r}") def die(way): quotes = [ f"As you make your next step, you waste a second to glance at the bloodied path you are about to leave behind. \nOne second too long, as a blazing sword piercing right through you suddenly reminds you. \n{ITALIC}This spot marks our grave, but you may rest here too, if you would like...{END} a young prince whispers.", f"The earth trembles and you feel the sudden urge to look to the greyish sky above you.\n{ITALIC}Ignorant slaves, how quickly you forget{END}, a twisted dragon-man spits as he crushes you under his feet.", f"The deadly scythe of a woman grabs you by the waist.\n{ITALIC}Return from whence thou cam'st. For that is thy place of belonging{END}, the Sister commands before taking you to your grave.", f"In the thick mist, a nun-like figure reveals herself in front of you.\n{ITALIC}Return Lord of Londor. You have your own subjects to attain to{END}, she whispers as she cuts right through you with her scythe." ] if way: print(f"\n{random.choice(quotes)}") else: print(f"{ITALIC}What is taking you so long?{END}, Patches croons before kicking you off a cliff again.") print(f"\n\t{RED}YOU DIED{END}\n") exit() def proceed(next): global position if sum([0, 0, 0, 1][routes[places.index(position)][0]:routes[places.index(position)][0]+1]) == 1: if next > ((221^216)>>True)*((len("...Rise, if you would...for that is our curse...")^53)>>1): die(1) elif sum(int(d) for d in str(abs(routes[places.index(position)][0]))) % 3 == 0: if next > (int(bool(len("Why, Patches, why?")))): die(1) elif str(abs(routes[places.index(position)][0]))[-1] in "05": if next > (True << True): die(1) elif (sum(int(str(routes[places.index(position)][0])[i]) for i in range(0, len(str(routes[places.index(position)][0])), 2)) - sum(int(str(routes[places.index(position)][0])[i]) for i in range(1, len(str(routes[places.index(position)][0])), 2))) % 11 == 0: if next > (sum(map(int,str(111111)[::2]))): die(1) path.append(routes[places.index(position)][next]) position = routes[places.index(position)][next] def play(): global position global path while True: if position != "Kiln of the First Flame" and len(path) < 22: printLocationDetails() next = int(input("\nChoose a number > ")) if next < 0 or next > 3: exit() proceed(next+1) elif position == "Kiln of the First Flame": checkFlag() elif len(path) >= 22: die(0) def main(): global position print(f"\n{ITALIC}You slowly rise as you are awaken by a sweet and ageless voice. \n'Let the Flame guide thee in this search for the flag', she whispers softly into your ear. \nBefore you can ask any questions, she disappears. \n\nYou are now left in utter silence.{END}\n") print(f"\t{UNDERLINE}PRESS ENTER TO CONTINUE{END}") input() position = "Cemetery of Ash" path.append(position) play() 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/Kind4SUS/2025/crypto/Lightning_Fast_Scrambling/lfs.py
ctfs/Kind4SUS/2025/crypto/Lightning_Fast_Scrambling/lfs.py
from hashlib import sha256 from base64 import b64encode, b64decode # utility wrapper for hashing def digest(message): "Gives a bytes object representing the sha256 encoding of its argument (a sequence of bytes)" return sha256(message).digest() # utility wrapper for encoding and decoding def base64_encode(x): "Encodes a sequence of bytes in a string, using base64 encoding" return b64encode(x).decode() def base64_decode(x): return b64decode(x, validate=True) # crypto magic def create_key(passphrase): h = passphrase.encode() h = digest(h) k = 0 for i in range(8): k <<= 8 k |= h[i] return k if k else 1 def secret_byte_stream(key): x = key mask = 255 while True: y = x # 64 a = y & mask yield a y >>= 8 x = y y >>= 1 # 45 a ^= y & mask y >>= 14 # 31 a ^= y & mask y >>= 17 # 14 a ^= y & mask x |= a << 56 def scramble(message, key): stream = secret_byte_stream(key) return bytes(x ^ y for x, y in zip(message, stream)) # user-facing stuff def encrypt(text, passphrase): message = text.encode() hash = digest(message) key = create_key(passphrase) e = scramble(message, key) return '#'.join(map(base64_encode, [e, hash])) def decrypt(text, passphrase): e, hash = map(base64_decode, text.split('#')) key = create_key(passphrase) message = scramble(e, key) if hash != digest(message): raise ValueError("Wrong key") return message.decode() def create_flag(secret): return "".join(["KSUS{", secret.encode().hex(), "}"]) if __name__ == "__main__": secret = input("secret > ") passphrase = input("passphrase > ") flag = create_flag(secret) print("flag :", flag) challenge = encrypt(flag, passphrase) assert flag == decrypt(challenge, passphrase) print("challenge :", challenge)
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/Kind4SUS/2025/crypto/Feistel_heart/challenge.py
ctfs/Kind4SUS/2025/crypto/Feistel_heart/challenge.py
from Crypto.Util.number import bytes_to_long, getPrime, long_to_bytes from Crypto.Util.Padding import pad import os, signal assert("FLAG" in os.environ) FLAG = os.environ["FLAG"] assert(FLAG.startswith("KSUS{") and FLAG.endswith("}")) def xor_bytes(bytes_a, bytes_b): return bytes(a ^ b for a, b in zip(bytes_a, bytes_b)).ljust(2, b'\x00') def f(sub_block, round_key, modulus): return long_to_bytes((bytes_to_long(sub_block) + pow(65537, bytes_to_long(round_key), modulus)) % (1<<17-1)).ljust(2, b'\x00') def encrypt_block(block, key, modulus, rounds=8, shortcut=False): sub_block_1 = block[:2].ljust(2, b'\x00') sub_block_2 = block[2:4].ljust(2, b'\x00') sub_block_3 = block[4:].ljust(2, b'\x00') for i in range(0, rounds): round_key = key[i*2:i*2+2] new_sub_block_1 = xor_bytes(sub_block_1, sub_block_2) new_sub_block_2 = f(sub_block_3, round_key, modulus) new_sub_block_3 = xor_bytes(sub_block_2, round_key) sub_block_1 = new_sub_block_1 sub_block_2 = new_sub_block_2 sub_block_3 = new_sub_block_3 if shortcut and sub_block_1 == b"\xff\xff": break return sub_block_1 + sub_block_2 + sub_block_3 def encrypt(plaintext, key, modulus): iv = os.urandom(6) padded = pad(plaintext.encode(), 6) blocks = [padded[i:i+6] for i in range(0, len(padded), 6)] res = [] for i in range(len(blocks)): if i == 0: block = xor_bytes(blocks[i], iv) else: block = xor_bytes(blocks[i], bytes.fromhex(res[-1])) res.append(encrypt_block(block, key, modulus).hex()) return iv.hex() + "".join(res) def handle(): key = os.urandom(16) N = getPrime(1024) print("flag =", encrypt(FLAG, key, N)) print("N =", N) encrypted = [] while True: print("[1] Encrypt") print("[2] Exit") opt = input("> ") if opt == "1": plaintext = input("Enter your fantastic plaintext (in hex): ") if len(plaintext) % 2 != 0 or len(plaintext) < 2 or len(plaintext) > 12: print("It doesn't look fine to me :/") elif plaintext in encrypted: print("Nah, you've already encrypted it!") else: encrypted.append(plaintext) ciphertext = encrypt_block(bytes.fromhex(plaintext).rjust(6, b"\x00"), key, N, shortcut=True) print("Here it is: " + ciphertext.hex()) elif opt == "2": print("Bye (^-^)") exit(0) else: print("Nope :/") if __name__ == "__main__": signal.alarm(300) handle()
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/TMUCTF/2021/crypto/Signed_Flag/challenge.py
ctfs/TMUCTF/2021/crypto/Signed_Flag/challenge.py
from string import ascii_uppercase, ascii_lowercase, digits from random import randrange, choice from Crypto.PublicKey import DSA from hashlib import sha1 from gmpy2 import xmpz, to_binary, invert, powmod, is_prime def gen_rand_str(size=40, chars=ascii_uppercase + ascii_lowercase + digits): return ''.join(choice(chars) for _ in range(size)) def gen_g(p, q): while True: h = randrange(2, p - 1) exp = xmpz((p - 1) // q) g = powmod(h, exp, p) if g > 1: break return g def keys(g, p, q): d = randrange(2, q) e = powmod(g, d, p) return e, d def sign(msg, k, p, q, g, d): while True: r = powmod(g, k, p) % q h = int(sha1(msg).hexdigest(), 16) try: s = (invert(k, q) * (h + d * r)) % q return r, s except ZeroDivisionError: pass if __name__ == "__main__": print("\n") print(".___________..___ ___. __ __ ______ .___________. _______ ___ ___ ___ __ ") print("| || \/ | | | | | / || || ____| |__ \ / _ \ |__ \ /_ | ") print('`---| |----`| \ / | | | | | | ,----"`---| |----`| |__ ) | | | | | ) | | | ') print(" | | | |\/| | | | | | | | | | | __| / / | | | | / / | | ") print(" | | | | | | | `--' | | `----. | | | | / /_ | |_| | / /_ | | ") print(" |__| |__| |__| \______/ \______| |__| |__| |____| \___/ |____| |_| ") steps = 10 for i in range(steps): key = DSA.generate(2048) p, q = key.p, key.q print("\n\nq =", q) g = gen_g(p, q) e, d = keys(g, p, q) k = randrange(2, q) msg1 = gen_rand_str() msg2 = gen_rand_str() msg1 = str.encode(msg1, "ascii") msg2 = str.encode(msg2, "ascii") r1, s1 = sign(msg1, k, p, q, g, d) r2, s2 = sign(msg2, k, p, q, g, d) print("\nsign('" + msg1.decode() + "') =", s1) print("\nsign('" + msg2.decode() + "') =", s2) if i == (steps - 1): with open('flag', 'rb') as f: flag = f.read() secret = flag else: secret = gen_rand_str() secret = str.encode(secret, "ascii") r3, s3 = sign(secret, k, p, q, g, d) print("\nsign(secret) =", s3, r3) h = input("\nGive me SHA1(secret) : ") if h == str(int(sha1(secret).hexdigest(), 16)): print("\nThat's right, the secret is", secret.decode()) else: print("\nSorry, I cannot give you the secret. Bye!") break
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/TMUCTF/2021/crypto/Broken_RSA/challenge.py
ctfs/TMUCTF/2021/crypto/Broken_RSA/challenge.py
from Crypto.Util.number import * e = 65537 with open('n', 'rb') as f: n = int(f.read()) with open('secret', 'rb') as f: secret_msg = f.read() pads = [b'\x04', b'\x02', b'\x00', b'\x01', b'\x03'] with open('out.txt', 'w') as f: for i in range(len(pads)): for j in range(len(pads)): msg = pads[j] * (i + 1) + b'TMUCTF' + pads[len(pads) - j - 1] * (i + 1) enc = pow(bytes_to_long(msg), e, n) f.write(str(enc) + '\n') enc = pow(bytes_to_long(secret_msg), e, n) f.write(str(enc))
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/TMUCTF/2021/crypto/435/challenge.py
ctfs/TMUCTF/2021/crypto/435/challenge.py
import binascii import hashlib import sys from Crypto.Cipher import AES key = b'*XhN2*8d%8Slp3*v' key_len = len(key) def pad(message): padding = bytes((key_len - len(message) % key_len) * chr(key_len - len(message) % key_len), encoding='utf-8') return message + padding def encrypt(message, key, iv): aes = AES.new(key, AES.MODE_CBC, iv) return aes.encrypt(message) h = hashlib.sha256(key).hexdigest() hidden = binascii.unhexlify(h)[:10] message = b'CBC (Cipher Blocker Chaining) is an advanced form of block cipher encryption' + hidden with open('flag', 'rb') as f: IV = f.read().strip(b'TMUCTF{').strip(b'}') print(binascii.hexlify(encrypt(pad(message), key, IV)))
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/TMUCTF/2021/crypto/Baby_Encoder/challenge.py
ctfs/TMUCTF/2021/crypto/Baby_Encoder/challenge.py
from Crypto.Util.number import bytes_to_long def displace(a, base): res = [] for i in range(base): if base + i >= len(a): for j in range(base - 1, i - 1, -1): res.append(a[j]) return res res.append(a[base + i]) res.append(a[i]) for j in range(len(a) - 1, 2 * base - 1, -1): res.append(a[j]) return res def flag_encoder(flag): encoded_flag = [] n = len(flag) for i in range(n): encoded_flag.append(ord(flag[i]) ^ ord(flag[i - 1])) for i in range(n): encoded_flag[i] ^= encoded_flag[n - i - 1] a = [] for i in range(0, n, 3): a.append(encoded_flag[i] + encoded_flag[i + 1]) a.append(encoded_flag[i + 1] + encoded_flag[i + 2]) a.append(encoded_flag[i + 2] + encoded_flag[i]) encoded_flag = a for i in range(1, n): if i % 6 == 0: encoded_flag = displace(encoded_flag, i) encoded_flag = ''.join(chr(encoded_flag[i]) for i in range(n)) return encoded_flag with open('flag', 'rb') as f: flag = f.read().decode('UTF-8') print(str(bytes_to_long(flag_encoder(flag).encode())))
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/TMUCTF/2021/crypto/Common_Factor/challenge.py
ctfs/TMUCTF/2021/crypto/Common_Factor/challenge.py
from Crypto.Util.number import * from functools import reduce def encrypt(msg, n): enc = pow(bytes_to_long(msg), e, n) return enc e = 65537 primes = [getPrime(2048) for i in range(5)] n = reduce(lambda a, x: a * x, primes, 1) print(n) x1 = primes[1] ** 2 x2 = primes[2] ** 2 x3 = primes[1] * primes[2] y1 = x1 * primes[2] + x2 * primes[1] y2 = x2 * (primes[3] + 1) - 1 y3 = x3 * (primes[3] + 1) - 1 print(x2 + x3 + y1) print(y2 + y3) with open('flag', 'rb') as f: flag = f.read() print(encrypt(flag, n))
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/TMUCTF/2021/web/Fake_Registration/app.py
ctfs/TMUCTF/2021/web/Fake_Registration/app.py
import os from flask import Flask, render_template, request from peewee import * app = Flask(__name__) db = SqliteDatabase("TMUCTF.db") class Users(Model): id = AutoField() username = CharField(unique=True) password = CharField() class Meta: database = db @db.connection_context() def initialize(): try: db.create_tables([Users]) Users.create(username="admin", password=os.getenv("FLAG")) except: pass initialize() @app.route("/") @app.route("/register", methods=["POST"]) def register(): msg = "" if request.method == "POST" and "username" in request.form and "password" in request.form: username = request.form["username"] password = request.form["password"] if len(username) > 67: msg = "Error: Too long username!" elif len(password) > 67: msg = "Error: Too long password!" else: sql = f"INSERT INTO `users`(username, password) VALUES ('{username}', '{password}')" try: db.execute_sql(sql) msg = "Your registration was successful!" except Exception as e: msg = "Error: " + str(e) return render_template("register.html", msg=msg) if __name__ == "__main__": app.run(host="0.0.0.0", port=5000)
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/1337UP/2024/crypto/kRSA/kRSA.py
ctfs/1337UP/2024/crypto/kRSA/kRSA.py
from Crypto.Util.number import * import signal def timeout_handler(signum, frame): print("Secret key expired") exit() signal.signal(signal.SIGALRM, timeout_handler) signal.alarm(300) FLAG = "INTIGRITI{fake_flag}" SIZE = 32 class Alice: def __init__(self): self.p = getPrime(1024) self.q = getPrime(1024) self.n = self.p*self.q self.e = 0x10001 def public_key(self): return self.n,self.e def decrypt_key(self, ck): phi = (self.p-1)*(self.q-1) d = inverse(e, phi) self.k = pow(ck, d, n) class Bob: def __init__(self): self.k = getRandomNBitInteger(SIZE) def key_exchange(self, n, e): return pow(self.k, e, n) alice = Alice() bob = Bob() n,e = alice.public_key() print("Public key from Alice :") print(f"{n=}") print(f"{e=}") ck = bob.key_exchange(n, e) print("Bob sends encrypted secret key to Alice :") print(f"{ck=}") alice.decrypt_key(ck) assert(alice.k == bob.k) try: k = int(input("Secret key ? ")) except: exit() if k == bob.k: print(FLAG) else: print("That's not the secret key")
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/1337UP/2024/crypto/Black_Box_Blackjack/blackjack.py
ctfs/1337UP/2024/crypto/Black_Box_Blackjack/blackjack.py
#!/usr/bin/env python3 import os from Crypto.Util.number import getPrime, bytes_to_long, long_to_bytes FLAG = os.getenv("FLAG", "INTIGRITI{REDACTED}").encode() class HandStates: OKAY = 0, STANDING = 1, BUST = 2, BLACKJACK = 3, @staticmethod def get_state(score): if score > 21: return HandStates.BUST elif score == 21: return HandStates.BLACKJACK return HandStates.OKAY class Card: VALUE_TO_NAME = { 1: "Ace", 11: "Jack", 12: "Queen", 13: "King", } def __init__(self, suit, value): self.suit = suit self.value = value def __repr__(self): name = self.VALUE_TO_NAME.get(self.value, str(self.value)) return f"{name} of {self.suit}" class Deck: def __init__(self, seed): self.seed = seed self.reset() def reset(self): self.cards = [] self.build() self.shuffle() def build(self): for suit in ["Hearts", "Diamonds", "Clubs", "Spades"]: for value in range(1, 14): self.cards.append(Card(suit, value)) def shuffle(self): new_cards = [] for i in range(52): card_index = self.seed % (52 - i) new_cards.append(self.cards.pop(card_index)) self.seed //= (52 - i) self.cards = new_cards def deal(self): if len(self.cards) == 0: self.reset() return self.cards.pop(0) class Blackjack: def __init__(self, player_names, seed): self.player_names = player_names self.player_moneys = [0] * len(player_names) self.num_players = len(player_names) self.deck = Deck(seed) def setup_hands(self): self.hand_states = [HandStates.OKAY] * (self.num_players + 1) self.hands = [[self.deck.deal(), self.deck.deal()] for _ in range(self.num_players + 1)] for i, hand in enumerate(self.hands): score = sum(card.value for card in hand) state = HandStates.get_state(score) self.hand_states[i] = state def play_round(self): print(f"Dealer ({self.hands[0][0].value}):") print("- " + str(self.hands[0][0])) print("- HIDDEN") print() for i in range(1, self.num_players + 1): self.show_hands(i) for i in range(1, self.num_players + 1): if self.hand_states[i] != HandStates.OKAY: continue name = self.player_names[i - 1] is_hit = False if i == 1: action = input("Hit or stand? ").lower() if action == "hit": is_hit, state, card = (True, *self.hit(1)) else: is_hit, state, card = self.choose_action(i) if is_hit: if state == HandStates.BLACKJACK: print(f"{name} hit {card} and got a blackjack!") self.hand_states[i] = HandStates.BLACKJACK elif state == HandStates.BUST: print(f"{name} hit {card} and went bust!") self.hand_states[i] = HandStates.BUST else: print(f"{name} hits {card}!") else: print(f"{name} stands.") self.hand_states[i] = HandStates.STANDING print("\n" + "-" * 48 + "\n") def show_hands(self, hand_index): name = self.player_names[hand_index - 1] if hand_index > 0 else "Dealer" hand = self.hands[hand_index] score = sum(card.value for card in hand) state = HandStates.get_state(score) if state == HandStates.BLACKJACK: print(f"{name} ({score}): Blackjack!") elif state == HandStates.BUST: print(f"{name} ({score}): Bust!") elif state == HandStates.STANDING: print(f"{name} ({score}): Standing") else: print(f"{name} ({score}):") for card in hand: print("- " + str(card)) print() def get_score(self, hand): return sum(card.value for card in hand) def hit(self, hand_index): hand = self.hands[hand_index] card = self.deck.deal() hand.append(card) return (HandStates.get_state(self.get_score(hand)), card) def choose_action(self, hand_index): score = self.get_score(self.hands[hand_index]) if score < 17: return (True, *self.hit(hand_index)) return (False, HandStates.STANDING, None) def are_any_players_okay(self): return any([state == HandStates.OKAY for state in self.hand_states[1:]]) def play_dealer(self): self.show_hands(0) state = self.hand_states[0] is_action_made = False while state == HandStates.OKAY: is_action_made = True is_hit, state, card = self.choose_action(0) if is_hit: print(f"Dealer hits {card}!") else: print("Dealer stands.") if is_action_made: self.hand_states[0] = state print() self.show_hands(0) def str_money(self, money): if money < 0: return f"-${abs(money)}" return f"€{money}" def show_results(self): dealer_score = self.get_score(self.hands[0]) dealer_state = self.hand_states[0] for i in range(1, self.num_players + 1): name = self.player_names[i - 1] score = self.get_score(self.hands[i]) state = self.hand_states[i] money = self.player_moneys[i - 1] if state == HandStates.BLACKJACK: money += 100 print(f"{name} got a blackjack! {self.str_money(money)}") elif state == HandStates.BUST: money -= 75 print(f"{name} went bust! {self.str_money(money)}") elif dealer_state == HandStates.BUST or score > dealer_score: money += 50 print(f"{name} beat the dealer! {self.str_money(money)}") else: money -= 50 print(f"{name} lost to the dealer! {self.str_money(money)}") self.player_moneys[i - 1] = money def show_final_winner(self): max_money = max(self.player_moneys) winners = [name for name, money in zip(self.player_names, self.player_moneys) if money == max_money] if len(winners) == 1: print(f"The winner is {winners[0]}!") else: print(f"The winners are {', '.join(winners)}!") if self.player_moneys[0] < 0: print("Looks like you are in the red :(") print("Better luck next time!") elif self.player_moneys[0] == max_money: print("Congrats on winning!") else: print("Thanks for playing!") class Crypto: def __init__(self, n_bits): REDACTED def encrypt(self, data): REDACTED def run(game): game.setup_hands() game.play_round() while game.are_any_players_okay(): game.play_round() print("Dealer's turn!\n") print("-" * 48 + "\n") game.play_dealer() print("Game over!\n") print("-" * 48 + "\n") game.show_results() print("\n" + "-" * 48 + "\n") if __name__ == "__main__": crypto = Crypto(350) print(""" /$$$$$$$ /$$ /$$ /$$$$$$$ | $$__ $$| $$ | $$ | $$__ $$ | $$ \ $$| $$ /$$$$$$ /$$$$$$$| $$ /$$| $$ \ $$ /$$$$$$ /$$ /$$ | $$$$$$$ | $$ |____ $$ /$$_____/| $$ /$$/| $$$$$$$ /$$__ $$| $$ /$$/ | $$__ $$| $$ /$$$$$$$| $$ | $$$$$$/ | $$__ $$| $$ \ $$ \ $$$$/ | $$ \ $$| $$ /$$__ $$| $$ | $$_ $$ | $$ \ $$| $$ | $$ >$$ $$ | $$$$$$$/| $$| $$$$$$$| $$$$$$$| $$ \ $$| $$$$$$$/| $$$$$$/ /$$/\ $$ |_______/ |__/ \_______/ \_______/|__/ \__/|_______/ \______/ |__/ \__/ """) print("Welcome to the Black Box casino!") name = input("What is your name? ") print("As this is the Black Box casino, I will not be telling you my name.") print("Although my name encrypted is:", crypto.encrypt(FLAG).hex()) print("Not that you will be able to decrypt it anyways...") print("After all, you don't even know what cryptosystem I am using!\n") print("=" * 48 + "\n") print("LET'S BEGIN!\n") names = [name, "Alice", "Bob", "Eve", "Mallory", "Trent", "Samuel", "Amber"] print("Welcome to the table!") print("You will be playing against the following players:") for n in names[1:]: print(f"- {n}") print("You will be playing three rounds of Blackjack.") print("The player with the most money at the end wins!") print("I hope nobody ends up in the red ;)\n") print("-" * 48 + "\n") seed = bytes_to_long(crypto.encrypt(name.encode(errors="surrogateescape"))) game = Blackjack(names, seed) run(game) print("Let's play again!\n") print("-" * 48 + "\n") run(game) print("One last time!\n") print("-" * 48 + "\n") run(game) game.show_final_winner()
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/1337UP/2023/misc/PyJail/jail.py
ctfs/1337UP/2023/misc/PyJail/jail.py
import ast import unicodedata blacklist = "0123456789[]\"\'._" check = lambda x: any(w in blacklist for w in x) def normalize_code(code): return unicodedata.normalize('NFKC', code) def execute_code(code): try: normalized_code = normalize_code(code) parsed = ast.parse(code) for node in ast.walk(parsed): if isinstance(node, ast.Call): if isinstance(node.func, ast.Name): if node.func.id in ("os","system","eval","exec","input","open"): return "Access denied!" elif isinstance(node, ast.Import): return "No imports for you!" if check(code): return "Hey, no hacking!" else: return exec(normalized_code, {}, {}) except Exception as e: return str(e) if __name__ == "__main__": while True: user_code = input(">> ") if user_code.lower() == 'quit': break result = execute_code(user_code) print("Result:", result)
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/1337UP/2023/pwn/Over_The_Edge/over_the_edge.py
ctfs/1337UP/2023/pwn/Over_The_Edge/over_the_edge.py
import numpy as np import warnings import socket, sys import threading warnings.filterwarnings("ignore", category=RuntimeWarning) warnings.filterwarnings("ignore", category=DeprecationWarning) def process_input(input_value): num1 = np.array([0], dtype=np.uint64) num2 = np.array([0], dtype=np.uint64) num2[0] = 0 a = input_value if a < 0: return "Exiting..." num1[0] = (a + 65) if (num2[0] - num1[0]) == 1337: return 'You won!\n' return 'Try again.\n' def handle_client(client_socket, client_address): try: print(f"Accepted connection from {client_address}") client_socket.send(b"Time to jump over the edge!\n") client_socket.send(b"") while True: input_data = client_socket.recv(1024).decode().strip() if not input_data: break input_value = int(input_data) response = process_input(input_value) if response == 'You won!\n': with open("flag", "r") as flag_file: flag_content = flag_file.read() client_socket.send(flag_content.encode()) client_socket.close() break else: client_socket.send(response.encode()) client_socket.close() print(f"Connection from {client_address} closed") except: client_socket.close() def main(): host = '0.0.0.0' port = 1337 server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) server_socket.bind((host, port)) server_socket.listen() print(f"Listening on {host}:{port}") while True: client_socket, client_address = server_socket.accept() client_thread = threading.Thread(target=handle_client, args=(client_socket, client_address)) client_thread.start() 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/1337UP/2023/crypto/Share_It_2/app.py
ctfs/1337UP/2023/crypto/Share_It_2/app.py
from flask import Flask, render_template, request, redirect, url_for, make_response from Crypto.Cipher import AES from Crypto.Util.Padding import pad, unpad import os import json import base64 from uuid import uuid4 import time from waitress import serve app = Flask(__name__) key = os.urandom(16) id_to_iv = {} last_clear = int(time.time()) FLAG = os.getenv("FLAG") if not FLAG: FLAG = "FLAG{dummy}" def store_iv(iv): # Clear dict once every hour global last_clear crnt_time = time.time() if crnt_time > 1*60*60 + last_clear: id_to_iv.clear() last_clear = crnt_time iv_id = str(uuid4()) id_to_iv[iv_id] = iv return iv_id def gen_encrypted_cookie(username, first_name, last_name): iv = os.urandom(16) cipher = AES.new(key, AES.MODE_CBC, iv=iv) user_dict = {'username': username, 'first_name': first_name, 'last_name': last_name, 'admin': False} c = cipher.encrypt(pad(json.dumps(user_dict).encode(), 16)) iv_id = store_iv(iv) return base64.b64encode(json.dumps({'user_dict': base64.b64encode(c).decode(), 'id': iv_id}).encode()).decode() def decrypt_cookie(cookie, iv=None): cookie_dict = json.loads(base64.b64decode(cookie).decode()) if iv: iv = bytes.fromhex(iv) else: iv_id = cookie_dict['id'] iv = id_to_iv.get(iv_id) if not iv: raise Exception(f'IV not found using id: {iv_id}') cipher = AES.new(key, AES.MODE_CBC, iv=iv) try: pt = cipher.decrypt(base64.b64decode( cookie_dict['user_dict'].encode())) except: raise Exception("Decryption error") try: pt = unpad(pt, 16) except: raise Exception("Unpad error") try: user_dict = json.loads(pt) except: raise Exception(f'Invalid json: {pt}') return user_dict @app.route("/") def index(): cookie = request.cookies.get("token") if cookie == None: return redirect(url_for('register')) else: try: user_dict = decrypt_cookie(cookie, iv=request.args.get("debug_iv")) except Exception as e: return str(e), 500 return render_template('index.html', username=user_dict['username']) @app.route("/register", methods=['GET', 'POST']) def register(): if request.method == "GET": return render_template("register.html") elif request.method == "POST": username = request.form["username"] print(f'{username=}') if username == None or username == "": return "username must be set", 400 first_name = request.form["first_name"] if first_name == None or first_name == "": return "first_name must be set", 400 last_name = request.form["last_name"] if last_name == None or last_name == "": return "last_name must be set", 400 cookie = gen_encrypted_cookie(username, first_name, last_name) res = make_response(redirect(url_for('index'))) print(cookie) res.set_cookie('token', cookie) return res @app.route("/admin-opinions") def admin(): cookie = request.cookies.get("token") if cookie == None: return redirect(url_for('register')) else: try: user_dict = decrypt_cookie(cookie, iv=request.args.get("debug_iv")) except Exception as e: return str(e), 500 if not user_dict['admin'] == True: return "<p>Only admins are allowed to read these cool opionons</p>", 403 else: return render_template("admin.html", flag=FLAG) if __name__ == '__main__': serve(app, host='0.0.0.0', port='5000')
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/1337UP/2023/crypto/1_10/chall.py
ctfs/1337UP/2023/crypto/1_10/chall.py
from random import randint from re import search from flag import FLAG cs = [randint(0, 2**1000) for _ in range(10)] xs = [randint(0, 2**64) for _ in range(10)] xs = [ord(f) + i - (i%1000) for i, f in zip(xs, search("{(.*)}", FLAG).group(1))] print(f"{cs = }") print(f"s = {sum(c*x for c, x in zip(cs, xs))}")
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/1337UP/2023/crypto/1_10/out.py
ctfs/1337UP/2023/crypto/1_10/out.py
cs = [8508903290440008966939565321248693758153261635170177499193552423579929500027826696702216711413627480472568726828904707392607240309148374882044455682656477650413559779578913981575195542381602155806438946382809049847521263107908111429547314575039079118614485792613461747911710760754291582134293099750060, 10234293217173095983648586990138462404689872504690765936890158736280331352728086141006820545673419953576281340699793983414878095413526583845311613647542879798224462254801103246845064675391113534349390649562211376117941776588135441368773636568930887968431002105334751994385414474789708434897717472259757, 6001064586644974650131784742218587067958465984737568290249286706923485137083921908971767187010824715217158349948368322929900720010489749231105336650564421771867089333709608235963711368415685056362117910529113580811922176651335662802405504434103542105450330213217418470901029864459362153866361049469621, 5859510800336462649673113647904370677448984650623412649303149431740483580968255760095323745895405406649271411277663981671465673293279417168147656423009231087547991428322779036740050269460373254323377738756038706795196225547099530503996157675637620918729310987613041873955654973230573780794437230183289, 8212120161226957435594246142362544687871307206030517377713172267061914524817671684448986080347503212333314134144272096534190656954277299391948626024244379808998220515649968150824587976113971840005858079163744362874678111323034234960076591622752217194796532407435861854992608669653483268713825154541681, 4292538496747452556903766205458518557016170261915268175117554973221631407580344459540989898488936014316805799620957521118332103032738032797936315597220903773140347787977387271254963436603728977128756213671653297994336981775219965231686927050793105808729293803455246360077380768093287937551667515822737, 8583458084429417950887051233123781099671792568724013361916924355046040863544385972858215904752358387759143712618915109914726815547284050405347634520790328222420443989299783668017365846692013464579110450651166600940834254189911732107856656458621485902792541383514622551498513045029193930072821693821256, 927938350277846540058170699346614173130036388369329189433895716040551556863284640834396837739290832786836335265440745786025530973467859153202044442045287145528583412999497854136387626360287750242048999254798532603013016406637079389023297629455299864761196574249382738851682248453939600976884575974199, 4606866838328488359534883828872534448488908284003992208192170511899852596906485417934690617926601159129473558885893097400239110669875450476234618534668886892219546199419412794765402627731086862572263105282498567494065303352715044800789544479262215220148659740517187562922289802434925672447697743660640, 5696622808956926263797513675882969816326582766528835713485415099018508834817057303528828064039948371652175876967703746446602159940653502950606513683435185458750394450192106019388424601807240033502531431423705043713657847236861816929000927218441444067742560786753091009546483807078198791541719979069795] s = 605466527953516222016485516214431809590993588699320208021845670703468281059947406248463347211427615855012720451029976981068579151311047123161756448068506197424807516350675172131826275005312472029312861168498961728971558322943730466676859739724928104907194812943584226111451426124864722285484117269190235012612078303171378
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/1337UP/2023/crypto/Not_So_Smooth/notsosmooth.py
ctfs/1337UP/2023/crypto/Not_So_Smooth/notsosmooth.py
from Crypto.Util.number import long_to_bytes from Crypto.Util.strxor import strxor from random import randint from flag import FLAG def f(x, n): return (pow(u,n,p)*x + v*(1-pow(u,n,p))*pow(1-u, -1, p)) % p p = 97201997431130462639713476119411091922677381239967611061717766639853376871260165905989218335681560177626304205941143288128749532327607316527719299945637260643711897738116821179208534292854942631428531228316344113303402450588666012800739695018334321748049518585617428717505851025279186520225325765864212731597 u = 14011530787746260724685809284106528245188320623672333581950055679051366424425259006994945665868546765648275822501035229606171697373122374288934559593175958252416643298136731105775907857798815936190074350794406666922357841091849449562922724459876362600203284195621546769313749721476449207319566681142955460891977927184371401451946649848065952527323468939007868874410618846898618148752279316070498097254384228565132693552949206926391461108714034141321700284318834819732949544823937032615318011463993204345644038210938407875147446570896826729265366024224612406740371824999201173579640264979086368843819069035017648357042 v = 16560637729264127314502582188855146263038095275553321912067588804088156431664370603746929023264744622682435376065011098909463163865218610904571775751705336266271206718700427773757241393847274601309127403955317959981271158685681135990095066557078560050980575698278958401980987514566688310172721963092100285717921465575782434632190913355536291988686994429739581469633462010143996998589435537178075521590880467628369030177392034117774853431604525531066071844562073814187461299329339694285509725214674761990940902460186665127466202741989052293452290042871514149972640901432877318075354158973805495004367245286709191395753 w = 30714296289538837760400431621661767909419746909959905820574067592409316977551664652203146506867115455464665524418603262821119202980897986798059489126166547078057148348119365709992892615014626003313040730934533283339617856938614948620116906770806796378275546490794161777851252745862081462799572448648587153412425374338967601487603800379070501278705056791472269999767679535887678042527423534392867454254712641029797659150392148648565421400107500607994226410206105774620083214215531253544274444448346065590895353139670885420838370607181375842930315910289979440845957719622069769102831263579510660283634808483329218819353 a = randint(0, 2**2048) b = randint(0, 2**2048) A = f(w, a) B = f(w, b) key = long_to_bytes(f(B, a))[:len(FLAG)] enc = strxor(FLAG, key) print(f"{A = }") print(f"{B = }") print(f"{enc = }") """ A = 7393401480034113709683683682039780458211722756040975666277858366986963864147091724359492764726999692812421940595309756560491142512219957986281425163574890752574157617546760386852366936945888357800966704941013951530688031419816817272581287237223765833452303447283089906937413964658335387593899889933721262202 B = 6919381992041136573008188094979879971060160509085428532054694712745921654244468113796582501225839242977870949915769181804595896718922228206397860738237256125972615830799470450058633231003927061049289907097099916321068776956652172887225970642896455423957706532253349472544176183473470843719479781727784095989 enc = b'\xcfW\x85\x8d\xedU\xdd\xd9`\x16f\xb8j(\xeb9-\x1b\xb8\x18 0av\xe5\xabK\xc6' """
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/1337UP/2023/crypto/Keyless/encrypt.py
ctfs/1337UP/2023/crypto/Keyless/encrypt.py
def encrypt(message): encrypted_message = "" for char in message: a = (ord(char) * 2) + 10 b = (a ^ 42) + 5 c = (b * 3) - 7 encrypted_char = c ^ 23 encrypted_message += chr(encrypted_char) return encrypted_message flag = "INTIGRITI{REDACTED}" encrypted_flag = encrypt(flag) with open("flag.txt.enc", "w") 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/1337UP/2023/crypto/Share_It_1/app.py
ctfs/1337UP/2023/crypto/Share_It_1/app.py
from flask import Flask, render_template, request, redirect, url_for, make_response from Crypto.Cipher import AES from Crypto.Util.Padding import pad, unpad import os import json import base64 from waitress import serve app = Flask(__name__) key = os.urandom(16) FLAG = os.getenv("FLAG") if not FLAG: FLAG = "FLAG{dummy}" def gen_encrypted_cookie(username): iv = os.urandom(16) cipher = AES.new(key, AES.MODE_CBC, iv=iv) user_dict = {'admin': False, 'username': username} c = cipher.encrypt(pad(json.dumps(user_dict).encode(), 16)) return base64.b64encode(json.dumps({'user_dict': base64.b64encode(c).decode(), 'iv': base64.b64encode(iv).decode()}).encode()).decode() def decrypt_cookie(cookie): cookie_dict = json.loads(base64.b64decode(cookie).decode()) iv = base64.b64decode(cookie_dict['iv'].encode()) cipher = AES.new(key, AES.MODE_CBC, iv=iv) return json.loads(unpad(cipher.decrypt(base64.b64decode(cookie_dict['user_dict'].encode())), 16)) @app.route("/") def index(): cookie = request.cookies.get("token") if cookie == None: return redirect(url_for('register')) else: try: user_dict = decrypt_cookie(cookie) except: return redirect(url_for('register')) return render_template('index.html', username=user_dict['username']) @app.route("/register", methods=['GET', 'POST']) def register(): if request.method == "GET": return render_template("register.html") elif request.method == "POST": username = request.form["username"] if username == None or username == "": return "username must be set", 400 cookie = gen_encrypted_cookie(username) res = make_response(redirect(url_for('index'))) res.set_cookie('token', cookie) return res @app.route("/admin-opinions") def admin(): cookie = request.cookies.get("token") if cookie == None: return redirect(url_for('register')) else: try: user_dict = decrypt_cookie(cookie) except: return redirect(url_for('register')) if not user_dict['admin'] == True: return "<p>Only admins are allowed to read these cool opionons</p>", 403 else: return render_template("admin.html", flag=FLAG) if __name__ == '__main__': print("Starting app...") serve(app, host='0.0.0.0', port='5000')
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/1337UP/2023/web/CTFC/IntCTFC/app.py
ctfs/1337UP/2023/web/CTFC/IntCTFC/app.py
from flask import Flask,render_template,request,session,redirect import pymongo import os from functools import wraps from datetime import timedelta from hashlib import md5 from time import sleep app = Flask(__name__) app.secret_key = os.environ['SECRET_KEY'] # db settings client = pymongo.MongoClient('localhost',27017) db = client.ctfdb def createChalls(): db.challs.insert_one({"_id": "28c8edde3d61a0411511d3b1866f0636","challenge_name": "Crack It","category": "hash","challenge_description": "My friend sent me this random string `cc4d73605e19217bf2269a08d22d8ae2` can you identify what it is? , flag format: CTFC{<password>}","challenge_flag": "CTFC{cryptocat}","points": "500","released": "True"}) db.challs.insert_one({"_id": "665f644e43731ff9db3d341da5c827e1","challenge_name": "MeoW sixty IV","category": "crypto","challenge_description": "hello everyoneeeeeeeee Q1RGQ3tuMHdfZzBfNF90aDNfcjM0TF9mbDRHfQ==, oops sorry my cat ran into my keyboard, and typed these random characters","challenge_flag": "CTFC{n0w_g0_4_th3_r34L_fl4G}","points": "1000","released": "True"}) db.challs.insert_one({"_id": "38026ed22fc1a91d92b5d2ef93540f20","challenge_name": "ImPAWSIBLE","category": "web","challenge_description": "well, this challenge is not fully created yet, but we have the flag for it","challenge_flag": os.environ['CHALL_FLAG'],"points": "1500","released": "False"}) # login check def check_login(f): @wraps(f) def wrap(*args,**kwrags): if 'user' in session: return f(*args,**kwrags) else: return render_template('dashboard.html') return wrap # routes from user import routes @app.route('/') @check_login def dashboard(): challs = [] for data in db.challs.find(): del data['challenge_flag'] challs.append(data) chall_1 = challs[0] chall_2 = challs[1] return render_template('t_dashboard.html',username=session['user']['username'],chall_1=chall_1,chall_2=chall_2) @app.route('/register') def register(): return render_template('register.html') @app.route('/login') def login(): return render_template('login.html') @app.route('/logout') def logout(): session.clear() return redirect('/') @app.route('/submit_flag',methods=['POST']) @check_login def submit_flag(): _id = request.json.get('_id')[-1] submitted_flag = request.json.get('challenge_flag') chall_details = db.challs.find_one( { "_id": md5(md5(str(_id).encode('utf-8')).hexdigest().encode('utf-8')).hexdigest(), "challenge_flag":submitted_flag } ) if chall_details == None: return "wrong flag!" else: return "correct flag!" # wait untill mongodb start then create the challs in db sleep(10) createChalls()
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/1337UP/2023/web/CTFC/IntCTFC/user/models.py
ctfs/1337UP/2023/web/CTFC/IntCTFC/user/models.py
from flask import Flask,request,render_template,session,redirect import uuid from passlib.hash import pbkdf2_sha256 from app import db class User: def signup(self): user = { "_id":uuid.uuid4().hex, "username":request.form['form_username'], "password":pbkdf2_sha256.encrypt(request.form['form_password']) } if db.users.find_one({"username":user['username']}): return render_template('register.html',error="username already exist"),400 if db.users.insert_one(user): return self.handle_session(user) return render_template('register.html',error="some error occured while signing up"),400 def handle_session(self,user): del user['password'] session['user'] = user return redirect('/') def signin(self): user = db.users.find_one({ "username":request.form['form_username'] }) if user: pwd = pbkdf2_sha256.verify(request.form['form_password'],user['password']) if pwd == True: return self.handle_session(user) else: return render_template('login.html',error="please enter the correct password"),400 elif user == None: return render_template('login.html',error="no user in that name"),400 return render_template('login.html',error="some error occured while signing up"),400
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/1337UP/2023/web/CTFC/IntCTFC/user/__init__.py
ctfs/1337UP/2023/web/CTFC/IntCTFC/user/__init__.py
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/1337UP/2023/web/CTFC/IntCTFC/user/routes.py
ctfs/1337UP/2023/web/CTFC/IntCTFC/user/routes.py
from flask import Flask,render_template from app import app from user.models import User @app.route('/user/signup',methods=['POST']) def signup(): try: return User().signup() except KeyError: return render_template('register.html',error="dont try to hack!!"),406 @app.route('/user/signin',methods=['POST']) def signin(): try: return User().signin() except KeyError: return render_template('login.html',error="dont try to hack!!"),406
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/1337UP/2022/crypto/BinomialWays/challenge.py
ctfs/1337UP/2022/crypto/BinomialWays/challenge.py
from secret import flag val = [] flag_length = len(flag) print(flag_length) def factorial(n): f = 1 for i in range(2, n+1): f *= i return f def series(A, X, n): nFact = factorial(n) for i in range(0, n + 1): niFact = factorial(n - i) iFact = factorial(i) aPow = pow(A, n - i) xPow = pow(X, i) val.append(int((nFact * aPow * xPow) / (niFact * iFact))) A = 1; X = 1; n = 30 series(A, X, n) ct = [] for i in range(len(flag)): ct.append(chr(ord(flag[i])+val[i]%26)) print(''.join(ct))
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/1337UP/2022/crypto/WarmupEncoder/encrypt.py
ctfs/1337UP/2022/crypto/WarmupEncoder/encrypt.py
# ENCRYPT.py from sympy import isprime, prime flag = '<REDACTED>' def Ord(flag): x0r([ord(i) for i in flag]) def x0r(listt): ff = [] for i in listt: if isprime(i) == True: ff.append(prime(i) ^ 0x1337) else: ff.append(i ^ 0x1337) b1n(ff) def b1n(listt): ff = [] for i in listt: ff.append(int(bin(i)[2:])) print(ff) if __name__ == "__main__": Ord(flag) ''' OUTPUT : [1001100000110, 1001100000100, 1001100000100, 1001100000000, 1001101100010, 1001101100111, 1001101001100, 1001101001111, 1001100000111, 1001101000101, 1001101101000, 1001100000011, 1001101011001, 1001101110011, 1001101101000, 1001101110101, 1001101011110, 1001101011001, 1001100000011, 1001011001010, 1001101100101, 1001101001110, 1001101101000, 1001101110010, 1001101011001, 1001001111100, 1001100000111, 1001101010011, 1001100000100, 1001101000101, 1001101101000, 1001100000011, 1001101000101, 1001100000100, 1001101101000, 1001101000011, 1001101111111, 1001100000100, 1001101101000, 1001101100000, 1001100000100, 1001100000011, 1000101111100, 1001100000100, 1001111000110, 1001101000011, 1001101101000, 1001100001111, 1001100000111, 1001100000000, 1001100001110, 1001100000111, 1001100000000, 1001111000110, 1001100000001, 1001101001010] '''
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/1337UP/2022/web/1_truth_2_lies/app.py
ctfs/1337UP/2022/web/1_truth_2_lies/app.py
from flask import Flask, request, render_template_string, render_template app = Flask(__name__) @app.route('/') def home(): return render_template('index.html') @app.route("""/ '''''' bbbbbbbb 1111111 '::::' VVVVVVVV VVVVVVVV lllllll 333333333333333 444444444 b::::::b 1111111 333333333333333 1::::::1 '::::' V::::::V V::::::V l:::::l 3:::::::::::::::33 4::::::::4 b::::::b 1::::::1 3:::::::::::::::33 1:::::::1 ':::'' V::::::V V::::::V l:::::l 3::::::33333::::::3 4:::::::::4 b::::::b 1:::::::1 3::::::33333::::::3 111:::::1 ':::' V::::::V V::::::V l:::::l 3333333 3:::::3 4::::44::::4 b:::::b 111:::::1 3333333 3:::::3 1::::1 '''' mmmmmmm mmmmmmm V:::::V V:::::Vuuuuuu uuuuuu l::::lnnnn nnnnnnnn 3:::::3rrrrr rrrrrrrrr 4::::4 4::::4 b:::::bbbbbbbbb 1::::1 3:::::3 1::::1 mm:::::::m m:::::::mm V:::::V V:::::V u::::u u::::u l::::ln:::nn::::::::nn 3:::::3r::::rrr:::::::::r 4::::4 4::::4 b::::::::::::::bb 1::::1 3:::::3 1::::1 m::::::::::mm::::::::::m V:::::V V:::::V u::::u u::::u l::::ln::::::::::::::nn 33333333:::::3 r:::::::::::::::::r 4::::4 4::::4 b::::::::::::::::b 1::::1 33333333:::::3 1::::l m::::::::::::::::::::::m V:::::V V:::::V u::::u u::::u l::::lnn:::::::::::::::n 3:::::::::::3 rr::::::rrrrr::::::r4::::444444::::444b:::::bbbbb:::::::b 1::::l 3:::::::::::3 1::::l m:::::mmm::::::mmm:::::m V:::::V V:::::V u::::u u::::u l::::l n:::::nnnn:::::n 33333333:::::3 r:::::r r:::::r4::::::::::::::::4b:::::b b::::::b 1::::l 33333333:::::3 1::::l m::::m m::::m m::::m V:::::V V:::::V u::::u u::::u l::::l n::::n n::::n 3:::::3 r:::::r rrrrrrr4444444444:::::444b:::::b b:::::b 1::::l 3:::::3 1::::l m::::m m::::m m::::m V:::::V:::::V u::::u u::::u l::::l n::::n n::::n 3:::::3 r:::::r 4::::4 b:::::b b:::::b 1::::l 3:::::3 1::::l m::::m m::::m m::::m V:::::::::V u:::::uuuu:::::u l::::l n::::n n::::n 3:::::3 r:::::r 4::::4 b:::::b b:::::b 1::::l 3:::::3 111::::::111 m::::m m::::m m::::m V:::::::V u:::::::::::::::uul::::::l n::::n n::::n3333333 3:::::3 r:::::r 4::::4 b:::::bbbbbb::::::b111::::::1113333333 3:::::3 1::::::::::1 m::::m m::::m m::::m V:::::V u:::::::::::::::ul::::::l n::::n n::::n3::::::33333::::::3 r:::::r 44::::::44b::::::::::::::::b 1::::::::::13::::::33333::::::3 1::::::::::1 m::::m m::::m m::::m V:::V uu::::::::uu:::ul::::::l n::::n n::::n3:::::::::::::::33 r:::::r 4::::::::4b:::::::::::::::b 1::::::::::13:::::::::::::::33 111111111111 mmmmmm mmmmmm mmmmmm VVV uuuuuuuu uuuullllllll nnnnnn nnnnnn 333333333333333 rrrrrrr 4444444444bbbbbbbbbbbbbbbb 111111111111 333333333333333""") def WH4TSGO1NG0N(): BRRRRR_RUNNING = request.args.get('input', None) if BRRRRR_RUNNING is None: return 'BRRRRR_RUNNING' else: return 'Your input: {}'.format(BRRRRR_RUNNING) @app.route("""/ ▄█ ▄▄▄▄███▄▄▄▄ ▄█ █▄ ███ █▄ ▄█ ███▄▄▄▄ ▄████████ ▄████████ ▄████████ ▀█████████▄ ▄█ ▄████████ ███ ▄██▀▀▀███▀▀▀██▄ ███ ███ ███ ███ ███ ███▀▀▀██▄ ███ ███ ███ ███ ███ ███ ███ ███ ███ ███ ███ ███▌ ███ ███ ███ ███ ███ ███ ███ ███ ███ ███ ███ █▀ ███ ███ ███ ███ ███ ███ ███ ███ █▀ ███▌ ███ ███ ███ ███ ███ ███ ███ ███ ███ ███ ▄███▄▄▄ ▄███▄▄▄▄██▀ ███ ███ ▄███▄▄▄██▀ ███ ▄███▄▄▄ ███▌ ███ ███ ███ ███ ███ ███ ███ ███ ███ ███ ▀▀███▀▀▀ ▀▀███▀▀▀▀▀ ▀███████████ ▀▀███▀▀▀██▄ ███ ▀▀███▀▀▀ ███ ███ ███ ███ ███ ███ ███ ███ ███ ███ ███ ███ █▄ ▀███████████ ███ ███ ███ ██▄ ███ ███ █▄ ███ ███ ███ ███ ███ ███ ███ ███ ███▌ ▄ ███ ███ ███ ███ ███ ███ ███ ███ ███ ███ ███▌ ▄ ███ ███ █▀ ▀█ ███ █▀ ▀██████▀ ████████▀ █████▄▄██ ▀█ █▀ ██████████ ███ ███ ███ █▀ ▄█████████▀ █████▄▄██ ██████████ ▀ ███ ███ ▀""", methods=['GET']) def WH4TSG01NG0N(): BRRRRR_RUNNING = request.args.get("input", None) if BRRRRR_RUNNING is None: return "BRRRRR_RUNNING" else: for _ in BRRRRR_RUNNING: if any(x in BRRRRR_RUNNING for x in {'.', '_', '|join', '[', ']', 'mro', 'base'}): return "caught" else: return render_template_string("Your input: " + BRRRRR_RUNNING) @app.route("""/ _____ _____ _____ _____ _____ _____ _____ _____ _____ _____ _____ _____ /\ \ /\ \ /\ \ /\ \ /\ \ /\ \ /\ \ /\ \ /\ \ /\ \ /\ \ /\ \ /::\ \ /::\____\ /::\____\ /::\____\ /::\____\ /::\____\ /::\ \ /::\ \ /::\ \ /::\ \ /::\____\ /::\ \ \:::\ \ /::::| | /:::/ / /:::/ / /:::/ / /::::| | /::::\ \ /::::\ \ /::::\ \ /::::\ \ /:::/ / /::::\ \ \:::\ \ /:::::| | /:::/ / /:::/ / /:::/ / /:::::| | /::::::\ \ /::::::\ \ /::::::\ \ /::::::\ \ /:::/ / /::::::\ \ \:::\ \ /::::::| | /:::/ / /:::/ / /:::/ / /::::::| | /:::/\:::\ \ /:::/\:::\ \ /:::/\:::\ \ /:::/\:::\ \ /:::/ / /:::/\:::\ \ \:::\ \ /:::/|::| | /:::/____/ /:::/ / /:::/ / /:::/|::| | /:::/__\:::\ \ /:::/__\:::\ \ /:::/__\:::\ \ /:::/__\:::\ \ /:::/ / /:::/__\:::\ \ /::::\ \ /:::/ |::| | |::| | /:::/ / /:::/ / /:::/ |::| | /::::\ \:::\ \ /::::\ \:::\ \ /::::\ \:::\ \ /::::\ \:::\ \ /:::/ / /::::\ \:::\ \ ____ /::::::\ \ /:::/ |::|___|______ |::| | _____ /:::/ / _____ /:::/ / /:::/ |::| | _____ /::::::\ \:::\ \ /::::::\ \:::\ \ /::::::\ \:::\ \ /::::::\ \:::\ \ /:::/ / /::::::\ \:::\ \ /\ \ /:::/\:::\ \ /:::/ |::::::::\ \ |::| | /\ \ /:::/____/ /\ \ /:::/ / /:::/ |::| |/\ \ /:::/\:::\ \:::\ \ /:::/\:::\ \:::\____\ /:::/\:::\ \:::\ \ /:::/\:::\ \:::\ ___\ /:::/ / /:::/\:::\ \:::\ \ /::\ \/:::/ \:::\____\/:::/ |:::::::::\____\ |::| | /::\____\|:::| / /::\____\/:::/____/ /:: / |::| /::\____\/:::/__\:::\ \:::\____\/:::/ \:::\ \:::| |/:::/ \:::\ \:::\____\/:::/__\:::\ \:::| |/:::/____/ /:::/__\:::\ \:::\____\ \:::\ /:::/ \::/ /\::/ / ~~~~~/:::/ / |::| | /:::/ /|:::|____\ /:::/ /\:::\ \ \::/ /|::| /:::/ /\:::\ \:::\ \::/ /\::/ |::::\ /:::|____|\::/ \:::\ /:::/ /\:::\ \:::\ /:::|____|\:::\ \ \:::\ \:::\ \::/ / \:::\/:::/ / \/____/ \/____/ /:::/ / |::| | /:::/ / \:::\ \ /:::/ / \:::\ \ \/____/ |::| /:::/ / \:::\ \:::\ \/____/ \/____|:::::\/:::/ / \/____/ \:::\/:::/ / \:::\ \:::\/:::/ / \:::\ \ \:::\ \:::\ \/____/ \::::::/ / /:::/ / |::|____|/:::/ / \:::\ \ /:::/ / \:::\ \ |::|/:::/ / \:::\ \:::\ \ |:::::::::/ / \::::::/ / \:::\ \::::::/ / \:::\ \ \:::\ \:::\ \ \::::/____/ /:::/ / |:::::::::::/ / \:::\ /:::/ / \:::\ \ |::::::/ / \:::\ \:::\____\ |::|\::::/ / \::::/ / \:::\ \::::/ / \:::\ \ \:::\ \:::\____\ \:::\ \ /:::/ / \::::::::::/____/ \:::\__/:::/ / \:::\ \ |:::::/ / \:::\ \::/ / |::| \::/____/ /:::/ / \:::\ /:::/ / \:::\ \ \:::\ \::/ / \:::\ \ /:::/ / ~~~~~~~~~~ \::::::::/ / \:::\ \ |::::/ / \:::\ \/____/ |::| ~| /:::/ / \:::\/:::/ / \:::\ \ \:::\ \/____/ \:::\ \ /:::/ / \::::::/ / \:::\ \ /:::/ / \:::\ \ |::| | /:::/ / \::::::/ / \:::\ \ \:::\ \ \:::\____\ /:::/ / \::::/ / \:::\____\ /:::/ / \:::\____\ \::| | /:::/ / \::::/ / \:::\____\ \:::\____\ \::/ / \::/ / \::/____/ \::/ / \::/ / \::/ / \:| | \::/ / \::/____/ \::/ / \::/ / \/____/ \/____/ ~~ \/____/ \/____/ \/____/ \|___| \/____/ ~~ \/____/ \/____/""") def WH4T5GO1NG0N(): BRRRRR_RUNNING = request.args.get("input", None) if BRRRRR_RUNNING is None: return "BRRRRR_RUNNING" if "{{" and "}}" in BRRRRR_RUNNING: return "BRRRRR_RUNNING" else: return "Your input: " + BRRRRR_RUNNING if __name__ == "__main__": app.run(host='0.0.0.0', port=5555, debug=True)
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/InCTF/2021/pwn/DeadlyFastGraph/server/server.py
ctfs/InCTF/2021/pwn/DeadlyFastGraph/server/server.py
#!/usr/bin/python3 import sys import tempfile import os print ("Enter the file size and then the file >>") size = int(input()) assert(size < 1024*1024) #1MB max script = sys.stdin.read(size) # reads one byte at a time, similar to getchar() temp = tempfile.mktemp() with open(temp, "w") as f: f.write(script) os.system("./jsc --useConcurrentJIT=false "+temp)
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/InCTF/2021/crypto/Right_Now_Generator/main.py
ctfs/InCTF/2021/crypto/Right_Now_Generator/main.py
#!/usr/bin/env python3 import random, hashlib, os, gmpy2, pickle from Crypto.Cipher import AES from Crypto.Util.Padding import pad, unpad FLAG = open('flag.txt', 'rb').read() class RNG(): pad = 0xDEADC0DE sze = 64 mod = int(gmpy2.next_prime(2**sze)) def __init__(self, seed_val, seed=None): if seed == None: assert seed_val.bit_length() == 64*2, "Seed is not 128 bits!" self.seed = self.gen_seed(seed_val) self.wrap() else: self.seed = seed self.ctr = 0 def gen_seed(self, val): ret = [val % self.mod] val >>= self.sze for i in range(self.sze - 1): val = pow(i ^ ret[i] ^ self.pad, 3, self.mod) ret.append(val % self.mod) val >>= self.sze return ret def wrap(self, pr=True): hsze = self.sze//2 for i in range(self.sze): r1 = self.seed[i] r2 = self.seed[(i+hsze)%self.sze] self.seed[i] = ((r1^self.pad)*r2)%self.mod self.ctr = 0 def next(self): a, b, c, d = (self.seed[self.ctr^i] for i in range(4)) mod = self.mod k = 1 if self.ctr%2 else 2 a, b, c, d = (k*a-b)%mod, (b-c)%mod, (c-d)%mod, (d-a)%mod self.ctr += 1 if self.ctr==64: self.wrap(pr=False) return a def encrypt(key: bytes, pt: bytes) -> bytes: key = hashlib.sha256(key).digest()[:16] cipher = AES.new(key, AES.MODE_CBC, os.urandom(16)) return {'cip': cipher.encrypt(pad(pt, 16)).hex(), 'iv': cipher.IV.hex()} def main(): obj = RNG(random.getrandbits(128)) out1 = ''.join([format(obj.next(), '016x') for i in range(64)]) out2 = ''.join([format(obj.next(), '016x') for i in range(64)]) cip = encrypt(bytes.fromhex(out1), FLAG) cip['leak'] = out2 return cip if __name__ == '__main__': cip = main() pickle.dump(cip, open('enc.pickle', 'wb'))
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/InCTF/2021/crypto/Trouble_With_Pairs/signer.py
ctfs/InCTF/2021/crypto/Trouble_With_Pairs/signer.py
from BLS import G2ProofOfPossession as bls from secret import data result = [] for i in data: d = {} d['Name'] = i['Name'] d['Vote'] = i['Vote'] d['Count'] = i['Count'] d['PK'] = i['PK'].hex() d['Sign'] = bls.Sign(i['PrivKey'],i['Vote'].encode()).hex() result.append(d) # print(result) ''' [{'Name': 'Nebraska', 'Vote': 'R', 'Count': 5, 'PK': 'aa6fc9c17a1b2de916e5d5453444655e9f6dd3d456b96239f954bc30b80f551c44c1c2423825bc01577e1986098f362b', 'Sign': 'a09538da373b317adf63cacb53799417ba57d79486aeec78d7687b37e72625190741313800a7698beb2659b725ca728a074514b4cc1fc300dee2e2ae74516993f6760f0839cc4d712a108c58955e062bf45100966fca0288f39f9bfc8ab25706'}, {'Name': 'Colorado', 'Vote': 'D', 'Count': 9, 'PK': '8205d0b95864290df27875f79fb00f8aba85631de322b29169fb83c871c91baad3d1da9b2484ae6d48438d39d33d4b72', 'Sign': '839118f1b8492188597f13a4706d3a05851a380c69ca71645934bd02831e916c11463ee5e38bada5087d2c4719b66cb20ba4064c3cd8783f1b2609c1e1ff8a5a050b986120d7266f9c9034cd3e458e49ed378b9400383d7ee3e393396a39ee65'}, {'Name': 'Louisiana', 'Vote': 'R', 'Count': 8, 'PK': 'a1663af6f40705dacf087e98dc5a3afb140a6bf869369e729c4ea1228d9dec1c216617a0aeb836620497e9d09f267322', 'Sign': 'b91f2adbf74f101baabdd41815f77296235d5055fbe0c73e05a832d101c1322a780fbc65c12cc6547a3298daf959d1bd119488e646b1717b6061ce272beb996ac19ae92f6e92cfd66bc366a3fbf3173c6a805b725573307434c15d57a2cc55d3'}, {'Name': 'District of Columbia', 'Vote': 'D', 'Count': 3, 'PK': 'ae098fa365c65473949ddf5c17e6fa7c2806e7eccc28b55830540131e64e9f8b37ac61b34a53d7ec564e46461b33eb59', 'Sign': 'ac10ca5d32ecff555e7c7691f25bc3b02e53bc8370e256c083e99a197b7bef8cadd1165a26cb944aa1a439e01b9e44321068827ec871a39596dcffdef5e9b2e8d1f0ac927c43cb7f0b31f1898d053810b23aa49b769d5ea733cddffa161b4fef'}, {'Name': 'North Dakota', 'Vote': 'R', 'Count': 3, 'PK': '87b9293aa4007094c443083009e33a80ea1ff6ea06e5e9056b7ae3e91d5f9702fd91e250e18abcf81369e164998e154c', 'Sign': '8a4f39d329db4e527d9d02730431977e556787c8ed48806477789074067851e9c0e87c9d5ed437810c353d83faddf7ff0fc2f4a106a9bd69d35b4d46e8b0ea870bbc6e7b0d68592a3b1feb3bc8870242859ba9176e3e1f6ea1f22ad4b3279eeb'}, {'Name': 'New Mexico', 'Vote': 'D', 'Count': 5, 'PK': 'ad6f4aebbb322725bef2e4db78c0831e0ec5796386baaeb06129f4709b5f904fefa062ddddbc2126a2cd523c41780f66', 'Sign': 'b80a6d804b142872428870892581f5af9c87720d38dd840ea092a40e15203cbee8f7ecf6e0f7ebd7da80c26e3b3bbb84022f63ba5985d077197e0dc9ff8c66e5a205b5a637d3087f27862fedb01bbf8333eefab7e152846672a7c17ecc4bff31'}, {'Name': 'South Dakota', 'Vote': 'R', 'Count': 3, 'PK': '916b270e535a31873cc4b642108cdec32461b97cee0f03e43eef53dbf10a39404f24c13f0ee6de8754b4ca631d1fa9c3', 'Sign': '9249fb12a9b52a78cabf04d96db288b8d6ef1755d7ee35595e8701123423894dff0a6caa67bb371eb3d9064fab3102fe069c0f0b6fc9acbb2913af170fdc607292be8ff0e4658bede42a6ae4d343ac44333b7949a6b142ab355e2df9ca923282'}, {'Name': 'New York', 'Vote': 'D', 'Count': 29, 'PK': '8351c394427c42dcfe4b4d3e8884ad133350e23aaad0adfa6631c7b7dafd17415a5f601a11235361759470a6e93f1485', 'Sign': 'aa62da4b5b01e4b835dab43da0ddb03f940483237c30f2e65f56bc4c25e4484590a6dac4b01d620a3512115866dbd6b11107af46539c8b62de9e9de88c4a263b6d50537e6fdfa6e886840dc506692f816492ceac1f9db03beae7ee66163e14b2'}, {'Name': 'Wyoming', 'Vote': 'R', 'Count': 3, 'PK': 'b1eab9298bc7c086f7869f46814bdaf3bff8b198db60917874a70f0e97cfda9f322e0b4b6a9cbab6b4cbba3a84bdb006', 'Sign': '8618363bbfd3c1080afa7fce8292bb02b066fa33e3cde1cfcd74a5421365754a168b8876657ab161eeb83d3ca85c8c3f17ac346d3c8760c5d1f18fdcbe4019c38487df09637a32ef5c21b6f6b0508fbd8a04a663fd1bacfab4d3ddd60d35abbc'}, {'Name': 'Virginia', 'Vote': 'D', 'Count': 13, 'PK': '89739e025b68fc193aa16b86423b3e55d298159cfa6fa390c5310f4b32a4ff351478cf2a21861edbe98e870fe7754add', 'Sign': '8255be26785f68af40d7ac56068d8c07b2dea1095ae6039884d4e6b440f993ed5a81e1d4bb8458abd09afaa4fe3e1a5015caee0725bd42f0f77028c35433b54edcf6cc8164a9a6eef7724d989f9cc00cfc1a712a22f0b98954d5bf6ddeeb3c02'}, {'Name': 'Indiana', 'Vote': 'R', 'Count': 11, 'PK': '92e6af6715944e85882b4db5bd47e6a6ed2596788f150e31176ae1c7ae5ba88e9c246ddd5ce795199cca742306e493b9', 'Sign': '87b79fc114854d672d5da0a048b5eb321b9b576f76a4de8d06303a5f873628e460eec897e18f84db6c11ea13723d8c93017b3c9fd3d3e48e9e9274dcfd5240f67f776288cf68c4c7735a69ff41e8c3acca769ee1fdb7a1679246e0721bd3e9c6'}, {'Name': 'Illinois', 'Vote': 'D', 'Count': 20, 'PK': '850c655b2811652f3fed0f43dd1c5edd978d8c67ee3a249f4cb66c5c80659f2095da30304f68a2b332296ab2b76b1012', 'Sign': 'af91fd175dc3d17974c4ac84e39d9900634261e5a02c67172f90c839b4d425dc77bcda3bd36dd448eb37cb95fc866cda19cc8972135da073e567355e19537de7f35fed780d1937fc58e3e22cc713ac69d673b29422163b0612ca639114cdf9c9'}, {'Name': 'Kansas', 'Vote': 'R', 'Count': 6, 'PK': 'a508cc71d1c4111eb2433d1b7cb695f365430099d393eb3afabaaa8640dfe29fa9076f3e1c5d9227e2ea9094c9a97d0b', 'Sign': '8521439bf44bc2b8518869f7e68ea5252d5dda2003f25fa2a9d2ed2578d48b961fbeb1e760de8f69a9623714f99e475109cf381096841c78073a785c8a946c60e7c8be98f1bbffb74c226c0d2f79849428eab1e7bcc6f600e6d62430a831773e'}, {'Name': 'New Jersey', 'Vote': 'D', 'Count': 14, 'PK': 'a3dd014aec4284ddc13df43e2bca07849978ab15663be2a7631dcb0dbbfc38afb10a60d94d719f8083b8026239f17a7f', 'Sign': 'ab4c35e2cafcc4b696c22fade3160f900129cac158d3538f0c4cf71598931f88477bf22b3c452ecad395d72d1efcc5f301cfa582a906b84533bdec104615e80485ff29c205c05ef83e2a5bb8f7387d2d9542d8f99c8b00a005e7e4ad6594d707'}, {'Name': 'South Carolina', 'Vote': 'R', 'Count': 9, 'PK': '97a83b23da756c3144d24811b609f15dd5bc6543a9af8bd23135a3873739a07abffd2c33ac0f0a4b2e4e3c42f07fa9c1', 'Sign': 'b00029b273dcfda804ce7c0f0e244b77bc4122a95ae3708c27dd4bb24d771131b9fbf07be0b8d04d805b99990e3bbb650816435455cc67d1bddd7a85d427a7596127751bf8e18531abcf0fe935b114db85f6351b4fd07a70d8aad9f7c3a08912'}, {'Name': 'Vermont', 'Vote': 'D', 'Count': 3, 'PK': 'a0bfdf6835adaddea3d260d4026ade2b7a7259bd2a1e3b49ead47ea5dd48874b0e1b7708ee9d46ef02564de11d2a2e4d', 'Sign': 'ac4c796dfc3b9212682894630819547656aca202948189bc452962f7f6b9b32f799c9fa47bbb2a93049f08a6e377d2250c29adace592ea84ea8644e48ec90990e2cbe74346721b654635dd627bfb993555a873bf878e6cdf5401713e702a2567'}, {'Name': 'Alabama', 'Vote': 'R', 'Count': 9, 'PK': 'ab7b278025304171157383bf9cb15aac892233fa1a58c948e8595ee664e16c2c0c994e82e5a384355d09c88030905ec1', 'Sign': 'a2fb74a45910a9db512c93a39069291d466d2f8e4c7955b79d548cad46296ec249ef0e324ee4939076bfc2375c83db4513d6ac3c1c3eb9563ff71eeda224f6d11d853fd5318fb913428c91485fda1e7c35315f42dc2a1eec334584f21b9e3e7f'}, {'Name': 'Connecticut', 'Vote': 'D', 'Count': 7, 'PK': '8105b28a7af2ccaa53a27b4f044c82c1d7a2dcf5aa18e6370976c4d3c77247a6b59701d5f724656e81331c3e687fe479', 'Sign': '937e27aa654a81ae56c975b07695298927d757aef06044792178d316877e87c61d2373162a4ac455733561b9aaeaf70f1912af0d975bdeaa03795b376e5f7115bc627468f4e4b3b5819a1f9b321df145dcd2b1e9902a0ff3500438cebed5f475'}, {'Name': 'Oklahoma', 'Vote': 'R', 'Count': 7, 'PK': 'a23fa4df95ad8a0f0b4fa414ddca1e8465eefffdae05f487b45c2f589ae1ee22ac7c78e92b6a5a307356e7d36d38c87f', 'Sign': 'a4b2b046c8712004e071986677c4ee55b68ae85b3753d5d58e3dde329eb44c5c56681fb3a773b8c3279f44451d8f28a400350ff1e63ab7a4794c558ffd643f4d3bbf52a42253e5f5278818579168261fa9be52f0f4e812e425867d4f5143e009'}, {'Name': 'Massachusetts', 'Vote': 'D', 'Count': 11, 'PK': '95ef2b7f8e12e901ff0afa0d4bfcc9727c96a19ceb0c6ae779d12e56b3c66489ec0a3eab8857501d39e7ec09febe57d4', 'Sign': '956fc8d13cbf23ef8a3237dbd8edd1b470e65488693d0abd4bfcb087b195391dba2b2d56577a85abc20e277721baf0f90932444658351abf8f61d054a680404e390f619e73578fded73f85d87395a66f5d1133a4acf0134954ba576df8cdb0e1'}, {'Name': 'Arkansas', 'Vote': 'R', 'Count': 6, 'PK': 'b45956fa419edcabcde7e9675a73c98cd9e117f46cb77a425b55a0d487c72b98f93823cefe66faf5104e3a81994d488f', 'Sign': 'acc9d03e1a39d6a07d934b39908e5dd8999dd297715d5c4088c2b16a08375fc503dc29dd7221c7c8bb350991ce7383d0195d253f61dc36b707e087e356da6426d8d91b2cdf5ee56707b6b0e515278bcb1ab53139793e7903a0ecddb3a4c5abef'}, {'Name': 'Rhode Island', 'Vote': 'D', 'Count': 4, 'PK': 'ac35fab31447122802a833c4df8fc5191f859dbe76c8a26a9eab200ce060b8881fb5480c30c2423be88a318838e16c56', 'Sign': '957d48c920074effa93c0d2d8ca2eb6d1bb147174a78696fbb5fa5fb026df12e458f118c1caf12b7cf1a6af065ad14f517765af2757300046f295732d99ee0ffc15549bcffec0dd5db7312b63016f0c11a3cbd0d18ac2b1571f96074252144ea'}, {'Name': 'Mississippi', 'Vote': 'R', 'Count': 6, 'PK': 'a7579e1e868b3e858141f5239c919fb0858db25743f22d51966fa34527a91194d59c2ec5cbd9b028242fafbb9f9512c1', 'Sign': 'b376aa915d818a4f7046a34af35124521a058fa4374d2db8f824d4a2a3f1b699100c2116966e0c6ec936a140ec27c83017748e238eaf2defd758eca15de4da5c9927f97c93e58685f2a42bf3658d5c797711fbd8e4ffd336de0caf1d754a8160'}, {'Name': 'Delaware', 'Vote': 'D', 'Count': 3, 'PK': 'ac18e29423d7d1074a0d73c6cad08462f69833ff267e436012a40d98d964620e50b32486e7878e417e573894475687ca', 'Sign': 'a65d489f4dafcbb2f194934e3184ad818c3a16dba3731d7a523842e8a4cd575e5da143d7b89dad389f60f520b4b42fae0f63eaa5bd96fac8b3ee7d7645d99316d8ac881915df89a4a20280453104be4b0f196f32955df14bb51403b886678c0f'}, {'Name': 'Tennessee', 'Vote': 'R', 'Count': 11, 'PK': '85fdd4ade2caec720a9b208ba4d26e399690ee6c978d79cb2f7a0b0ab406af1547cfb01a68720f5a71c34f9282cb2387', 'Sign': '8ddd99e5bf409744641f4d5548f86ec608a651938e29df86fe0f08bd5aa571f8bf46225ee9aadf66c1eb45e60d53bbc901a9ff84daa0d8675b387bf62f1266b65e6aa7f51a121f389957beb099286e01beac6e4e246126c378f8f815a7edaa4b'}, {'Name': 'Maryland', 'Vote': 'D', 'Count': 10, 'PK': '93e8209177cc332c57d0c92edbfc722236f4dc1a8de1b98c4bd5c8f9027a678e90474bab85b3923b8557628f48a816bc', 'Sign': '8e4b17d8e9f980a0974c1dd667b75f2e3386b40055c35642405ddcad39edda682bcb4c6f311a39d5b82b64d8dbed3cb0138ebf6bf38f574b32fc6c0127e62ea69dcb0fd7c6379f5fc4ab10a170372ac05055f2f5f282ad91fd9d911c32729971'}, {'Name': 'Kentucky', 'Vote': 'R', 'Count': 8, 'PK': '8975552e7e2975843b0d72d5e39052e8a6d5a76f9d5781234b78f26af2faa5718c5b62ffeb0a297d9f1565353fbb5243', 'Sign': '9025e5b452349ed95fd32ba5222da63e377d7ae2c6df40795eb6d2eb32be2e0f218618f2abfe40e3011d6d10172d07ca14f534972555e02363958ef4af2ef2a6242b1eca0d26d93dcd22084657967719035b86069ebd2b105207f5988b4040eb'}, {'Name': 'New Hampshire', 'Vote': 'D', 'Count': 4, 'PK': 'adbf0aa527947f9600223ccdeb3eca7849b59c687572f691c07db8d058c70cdfba80a19f76aeec9caefbb7dcd3fa160b', 'Sign': '91a24c21f0f4dbc6c3d7fda605f838b10f62e9f3dfed2432f66ed8860af26b8a1bff820a2a2da0834a61806ea7bb1221047c34cb86f5666aed90dee1ebe6ef298669621ea257db9a5ac518b917cf787d344a654084287820088b430182540e36'}, {'Name': 'West Virginia', 'Vote': 'R', 'Count': 5, 'PK': 'a8c2e910c5c106f9b7c3e16eee8651c65d80837905d5f14e5f79d23b4641dadd9069bddb06645d96d46cf1117222188e', 'Sign': 'a94b931fd5ceb214292c86d8f02fd28933efbcb6764c110ff0b34572c6a979e76b77be329540f6f83b9ce0fc9c4638f8164327b7ffc803c8409f2c6d37f10ae5ed4a7aff27d34284d89f91e3dd136258e9f306cf7489d78cf18d6ce6111f0d24'}, {'Name': 'Washington', 'Vote': 'D', 'Count': 12, 'PK': '963c36b641eb4b4b777e19bd29b733cbc3733d85ebaa86dffef2f7c57479b2e1d0f87355eabddb0fd2a7b60215797104', 'Sign': '85d681cd33bd774a6565810644d71d1629b46e79192bc6d4fc348b6e9830593f67adb2748e1d329b9b1072e52734eca80b318941380bd8e53f6e9ea656eb5e7a7c1d5b2b073d15b0034f58b60d7ebfe930a9a802a50b99c881a495fb3ca3e167'}, {'Name': 'Missouri', 'Vote': 'R', 'Count': 10, 'PK': '919806eabb4584837a6de87b1d995929bf17bf53f3901f1c8c2eb90ecf12fe710f5332f6115ac1452c9e831c6ccc5348', 'Sign': 'b3df95de68eeab2e5eb3964e94ecfe2eb6f1332a7388dc2634c906994a581f6ed492385bbb4f1367c7a208731de7204504c911bb4b0c47980d227f8a85c9ae4301de9789bf9196c250e2d939f0f028040933f505e5a4f7b2565b3875ff04542a'}, {'Name': 'Oregon', 'Vote': 'D', 'Count': 7, 'PK': '8b8b600c3cb810bd2b19d2ba49bfa990ed5365abd3e34ff3df44d08727a43660dfa606ac1e26097a5e3125152b20daa0', 'Sign': '96fd00ba8cc756144738be41c7d37c8d90dbdef0b69e257f843838063cd01d2ae984aff03c621d242010595d4ab0c05c0ede61fd5998b29f4642cd7755c2fc12339f2b197e7b46dd0db2acfb50dbfe22a1c463fcb2fcde0e2bc5c74e3faa18a0'}, {'Name': 'Idaho', 'Vote': 'R', 'Count': 4, 'PK': 'b82766688c226b8e5141d5dbf13b10f2a3fa96e5c615bdebc629dabb0d52503f2e1ff0caedbe4f19c7f8ec7dde08bd1c', 'Sign': 'a78e556915df6438533714393f1212f5f77898825ebe4c6e3d9dc3e8207fdb281685150a332b7c75830b5cdf5670658e177f7451eb22e4176aa683c7bdbc755eb400a361e1385b29dbdaa76b1513eaef1e53ca7c0e6b645c9dfae7c69a60907f'}, {'Name': 'California', 'Vote': 'D', 'Count': 55, 'PK': 'a2bd334fe36e60d61fffbc367c5d91e4fce2f76a5e88baaca1c3346bd99482316e1a820aba4fa0bd7d5cb21ba1fb5899', 'Sign': '948fe219b22bd3d14a2f282e33656d4910f25f1ed06d2aecada9f9f1fffaa4ab8c23de34b2b42ec1d413a2cab4af0cd9025551ec31058bd00c1d14a3cf4aa33d2035123d4d9ff7ca58bfc3cd7ed09b44fb85d254be79648916908de06271f4a3'}, {'Name': 'Utah', 'Vote': 'R', 'Count': 6, 'PK': '90fddb05be44dfb3882b6b9464fc6a8148a771c30949b49e127b5004298d8a8055c6a74e28919d96be350f53f56ece0c', 'Sign': '927d9abc04d407d8627d758ea7456723a80d7d8c666d023305a368f7af1388c6ca6ffb86352d787fd7f0e2177fc78b1e026e5d96920034c9d8504bdcfc4a7133c1e9bde5e40bbe256688d47e0a4bddcb9e8d5d9b25b9179b8af5d0b1907b545b'}, {'Name': 'Hawaii', 'Vote': 'D', 'Count': 4, 'PK': '94a74b01df673281ad0057ea631b758ad339225a4581694a7e2f9e513fae8c02cefeb3bbc6d20981286459f58583bf22', 'Sign': '943e350685a5e8340d136b5bc5bf2c1ab670b47efec014ae028ec1a5d671069e4ba4a2da12713551b9de6183c140e83a099d664d50067dc479e138522efec660126a59f2cf177021c14f0c372ac9afa6cce03b57458bfb8309f082da73ae7415'}, {'Name': 'Ohio', 'Vote': 'R', 'Count': 18, 'PK': '8ea313cf075966d690978e67b73eef63451e3c9706ee25923b566623fc4a29ae9a2a1c7700d3f0dc9a6a9bdd7df720cc', 'Sign': 'a87aaa00c957fcc0b600db3572999c9fb14ebf41492dc10d615b9ef3d94bf2fe09194d51e43f18d6ef3acfe0c5e35bda04aeef7c696a19a597645a12946387c113581c3939e5600a4d8f86d97d79d97fd221e73fbf836188432e86a153832949'}, {'Name': 'Minnesota', 'Vote': 'D', 'Count': 10, 'PK': 'b18c524740cef248dd4e9ff46bda3166a7629a330cee0e4785ad00315c5e192aa61a51e15a98eee39cd3691e39788ddd', 'Sign': 'a9fe29b3373d13fd9ee6d9dc530d92f4200544e0261ebe4be7e6d0e7312d7fb1a6964eb36ffd6300f2586f74289599f0162086f380cdabab51c8d5e7b7682ec82027e532b2efbfa8a76d2b71f428a30d98bad14b9ce43497fad946ffd70e73a8'}, {'Name': 'Montana', 'Vote': 'R', 'Count': 3, 'PK': 'ace4a5f2b90cceb22c84351abbe27346dc526f31facf9c8aaac18450cdd029910f2d6d59412b6bf4bdc4e96daf4374e5', 'Sign': 'ae45bd87845048c43b061c08884b44e6edac9037e1d3b9890ecceb550f19f743bb222e3b1ff988ffb274b0051a2ab0b508c31c72e770a772f22fa52db649f3a2dd77bb411836c36c5b0e19be499d17876f5ddef8fc16b38361695935ce11d6e2'}, {'Name': 'Arizona', 'Vote': 'D', 'Count': 11, 'PK': '86206344443f4b63773da9ef8b84c1b616841ddb10f69c3db28ecd99522f11538dc33fa6903515b9791e002671a0ed97', 'Sign': '94131d658f78010e5bb029391c98115638908a9fd84ad04dbc1d1704355f768060126c32143b9b2823a6bc92bbb9d41a0ed1e0834eddaeb51915db1022a0bf846d3570e0998ebd52ef70fe29c40d27ac287809a11a34c1672668e183dab66f3a'}, {'Name': 'Iowa', 'Vote': 'R', 'Count': 6, 'PK': '902f248bcfeb0eba3793fb7e61209aecffd5c2f8404e61dab476793b41fca3e39d980c9273a06401d2de54416ac7de2c', 'Sign': 'aa1f75e15eac39cb23a83f14e9d768ff9e48f3a5f3ddf299e087c0c4fd1c70e7db98d6bfc5e28878cb5e4720bde8bfe2001ab4e6597c7de0c25c28a6f645e286406448b69253407b3a20cc97087f06eb5b3faaa0ffc4cc89439b289cfd23f347'}, {'Name': 'Maine', 'Vote': 'D', 'Count': 4, 'PK': 'a00bc266cf9a90012003614ce43b5e449db94a8f31c66d8d2b16c83e511dbbaab2ccaa3ceff38435f76ad459a9fcdab3', 'Sign': 'a51b4be1c429e3d9db36ef588f62d6f898c5db070e4fca93a1991a10bcad9da587589f9beb05fbb514e73aa59b1ab99908de19c7f48198e9c691f28015e5dab09665c9a3d445dc9d5824af41aec31f2cf105a9ba34fa7e7c8193dd2eba99f728'}, {'Name': 'Florida', 'Vote': 'R', 'Count': 29, 'PK': 'aa5399ac175380e2532f010bd5c7f8a3d228ef6ece0e0832777c9275ee2872f960ec3c32b82b9b3d75d987a7163edb51', 'Sign': '8bdfbe3920a1f0b71dcc015295f5cc276a030f334320a9845107bb1499dfb5bc4122a7fd0aaa57301e40cb95f00209d9075f8b3c1e55ce89a013e7ab2a480b81b3bbde07c3c0615d68b6d423e4821dee3f022db8ea1e25c96b2ee5f564d9435c'}, {'Name': 'Wisconsin', 'Vote': 'D', 'Count': 10, 'PK': 'ab49bb4a03b4159dd32ae5306241fe703060afa79f07d5ff3cf4946c134fc848a8b67e53bebc040841e271063f4d2aba', 'Sign': '917dc3d288374b715ab2e6bedf67da6ea012fe1a193864e103e93095ac748d2051101117db5efcd70e898f251d02edbd0aee149221cfa03aeeb033919de4a4c8dbfa761ca2494d9c7535c36ab44dea22d4c83045da8e4759e301d7c1826a3f29'}, {'Name': 'Texas', 'Vote': 'R', 'Count': 38, 'PK': 'b89b7cc1728cefada730481b9d6cb4708cd8150d8c3b4adea8d0a88c7c956e7ee244d78ccd94395b3bdb46887502e791', 'Sign': '87e5ccc99586777873994e12fd65e44402e5205e77de898992a0afb3d80fdbaaa65234db0c00821eb03bd27b92bae21f027927409929e793096d93f1f607b9c67cbe79303bfd06ed0487d3c7d0f28aedfc3f19129b7901b32200044430107d98'}, {'Name': 'Michigan', 'Vote': 'D', 'Count': 16, 'PK': 'ae29e8f4d3c7b814042d04d12930bfc6f78eb12f3b9233a3338fedf42b784b6de6b5d575a0dee6d14de1a5ab9baaf5d9', 'Sign': 'a977d66e4fabaaa4d79e4d32f6b0d4e2901278d4e0d31e662af8929ac7ca540c377907b7e315b908f5e643e49b4a4fd914d90bb60305595ab6160cfbe0bbabb5c8a98f8ae37fc6af64faf7dbc35a6b55d7e8c3946dda6135a9332f484b818312'}] '''
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/InCTF/2021/crypto/Trouble_With_Pairs/BLS.py
ctfs/InCTF/2021/crypto/Trouble_With_Pairs/BLS.py
from typing import ( Sequence, ) from math import ( ceil, log2, ) import abc from eth_typing import ( BLSPubkey, BLSSignature, ) from eth_utils import ( ValidationError, ) from hashlib import sha256 from py_ecc.fields import optimized_bls12_381_FQ12 as FQ12 from py_ecc.optimized_bls12_381 import ( add, curve_order, final_exponentiate, G1, multiply, neg, pairing, Z1, Z2, G2, ) from py_ecc.bls.hash import ( hkdf_expand, hkdf_extract, i2osp, os2ip, ) # from py_ecc.bls.hash_to_curve import hash_to_G2 from py_ecc.bls.g2_primitives import ( G1_to_pubkey, G2_to_signature, pubkey_to_G1, signature_to_G2, subgroup_check, is_inf, ) def hash_to_G2(msg, DST, hash): m = int(hash(msg).hexdigest(),16) return multiply(G2,m) class BaseG2Ciphersuite(abc.ABC): DST = b'' xmd_hash_function = sha256 # # Input validation helpers # @staticmethod def _is_valid_privkey(privkey: int) -> bool: return isinstance(privkey, int) and privkey > 0 and privkey < curve_order @staticmethod def _is_valid_pubkey(pubkey: bytes) -> bool: # SV: minimal-pubkey-size return isinstance(pubkey, bytes) and len(pubkey) == 48 @staticmethod def _is_valid_message(message: bytes) -> bool: return isinstance(message, bytes) @staticmethod def _is_valid_signature(signature: bytes) -> bool: # SV: minimal-pubkey-size return isinstance(signature, bytes) and len(signature) == 96 # # APIs # @classmethod def SkToPk(cls, privkey: int) -> BLSPubkey: """ The SkToPk algorithm takes a secret key SK and outputs the corresponding public key PK. Raise `ValidationError` when there is input validation error. """ try: # Inputs validation assert cls._is_valid_privkey(privkey) except Exception as e: raise ValidationError(e) # Procedure return G1_to_pubkey(multiply(G1, privkey)) @classmethod def KeyGen(cls, IKM: bytes, key_info: bytes = b'') -> int: salt = b'BLS-SIG-KEYGEN-SALT-' SK = 0 while SK == 0: salt = cls.xmd_hash_function(salt).digest() prk = hkdf_extract(salt, IKM + b'\x00') l = ceil((1.5 * ceil(log2(curve_order))) / 8) # noqa: E741 okm = hkdf_expand(prk, key_info + i2osp(l, 2), l) SK = os2ip(okm) % curve_order return SK @staticmethod def KeyValidate(PK: BLSPubkey) -> bool: try: pubkey_point = pubkey_to_G1(PK) except (ValidationError, ValueError, AssertionError): return False if is_inf(pubkey_point): return False if not subgroup_check(pubkey_point): return False return True @classmethod def _CoreSign(cls, SK: int, message: bytes, DST: bytes) -> BLSSignature: """ The CoreSign algorithm computes a signature from SK, a secret key, and message, an octet string. Raise `ValidationError` when there is input validation error. """ try: # Inputs validation assert cls._is_valid_privkey(SK) assert cls._is_valid_message(message) except Exception as e: raise ValidationError(e) # Procedure message_point = hash_to_G2(message, DST, cls.xmd_hash_function) signature_point = multiply(message_point, SK) return G2_to_signature(signature_point) @classmethod def _CoreVerify(cls, PK: BLSPubkey, message: bytes, signature: BLSSignature, DST: bytes) -> bool: try: # Inputs validation assert cls._is_valid_pubkey(PK) assert cls._is_valid_message(message) assert cls._is_valid_signature(signature) # Procedure assert cls.KeyValidate(PK) signature_point = signature_to_G2(signature) if not subgroup_check(signature_point): return False final_exponentiation = final_exponentiate( pairing( signature_point, G1, final_exponentiate=False, ) * pairing( hash_to_G2(message, DST, cls.xmd_hash_function), neg(pubkey_to_G1(PK)), final_exponentiate=False, ) ) return final_exponentiation == FQ12.one() except (ValidationError, ValueError, AssertionError): return False @classmethod def Aggregate(cls, signatures: Sequence[BLSSignature]) -> BLSSignature: """ The Aggregate algorithm aggregates multiple signatures into one. Raise `ValidationError` when there is input validation error. """ try: # Inputs validation for signature in signatures: assert cls._is_valid_signature(signature) # Preconditions assert len(signatures) >= 1 except Exception as e: raise ValidationError(e) # Procedure aggregate = Z2 # Seed with the point at infinity for signature in signatures: signature_point = signature_to_G2(signature) aggregate = add(aggregate, signature_point) return G2_to_signature(aggregate) @classmethod def _CoreAggregateVerify(cls, PKs: Sequence[BLSPubkey], messages: Sequence[bytes], signature: BLSSignature, DST: bytes) -> bool: try: # Inputs validation for pk in PKs: assert cls._is_valid_pubkey(pk) for message in messages: assert cls._is_valid_message(message) assert len(PKs) == len(messages) assert cls._is_valid_signature(signature) # Preconditions assert len(PKs) >= 1 # Procedure signature_point = signature_to_G2(signature) if not subgroup_check(signature_point): return False aggregate = FQ12.one() for pk, message in zip(PKs, messages): assert cls.KeyValidate(pk) pubkey_point = pubkey_to_G1(pk) message_point = hash_to_G2(message, DST, cls.xmd_hash_function) aggregate *= pairing(message_point, pubkey_point, final_exponentiate=False) aggregate *= pairing(signature_point, neg(G1), final_exponentiate=False) return final_exponentiate(aggregate) == FQ12.one() except (ValidationError, ValueError, AssertionError): return False @classmethod def Sign(cls, SK: int, message: bytes) -> BLSSignature: return cls._CoreSign(SK, message, cls.DST) @classmethod def Verify(cls, PK: BLSPubkey, message: bytes, signature: BLSSignature) -> bool: return cls._CoreVerify(PK, message, signature, cls.DST) @abc.abstractclassmethod def AggregateVerify(cls, PKs: Sequence[BLSPubkey], messages: Sequence[bytes], signature: BLSSignature) -> bool: ... class G2Basic(BaseG2Ciphersuite): DST = b'BLS_SIG_BLS12381G2_XMD:SHA-256_SSWU_RO_NUL_' @classmethod def AggregateVerify(cls, PKs: Sequence[BLSPubkey], messages: Sequence[bytes], signature: BLSSignature) -> bool: if len(messages) != len(set(messages)): # Messages are not unique return False return cls._CoreAggregateVerify(PKs, messages, signature, cls.DST) class G2MessageAugmentation(BaseG2Ciphersuite): DST = b'BLS_SIG_BLS12381G2_XMD:SHA-256_SSWU_RO_AUG_' @classmethod def Sign(cls, SK: int, message: bytes) -> BLSSignature: PK = cls.SkToPk(SK) return cls._CoreSign(SK, PK + message, cls.DST) @classmethod def Verify(cls, PK: BLSPubkey, message: bytes, signature: BLSSignature) -> bool: return cls._CoreVerify(PK, PK + message, signature, cls.DST) @classmethod def AggregateVerify(cls, PKs: Sequence[BLSPubkey], messages: Sequence[bytes], signature: BLSSignature) -> bool: if len(PKs) != len(messages): return False messages = [pk + msg for pk, msg in zip(PKs, messages)] return cls._CoreAggregateVerify(PKs, messages, signature, cls.DST) class G2ProofOfPossession(BaseG2Ciphersuite): DST = b'BLS_SIG_BLS12381G2_XMD:SHA-256_SSWU_RO_POP_' POP_TAG = b'BLS_POP_BLS12381G2_XMD:SHA-256_SSWU_RO_POP_' @classmethod def _is_valid_pubkey(cls, pubkey: bytes) -> bool: """ Note: PopVerify is a precondition for -Verify APIs However, it's difficult to verify it with the API interface in runtime. To ensure KeyValidate has been checked, we check it in the input validation. See https://github.com/cfrg/draft-irtf-cfrg-bls-signature/issues/27 for the discussion. """ if not super()._is_valid_pubkey(pubkey): return False return cls.KeyValidate(BLSPubkey(pubkey)) @classmethod def AggregateVerify(cls, PKs: Sequence[BLSPubkey], messages: Sequence[bytes], signature: BLSSignature) -> bool: return cls._CoreAggregateVerify(PKs, messages, signature, cls.DST) @classmethod def PopProve(cls, SK: int) -> BLSSignature: pubkey = cls.SkToPk(SK) return cls._CoreSign(SK, pubkey, cls.POP_TAG) @classmethod def PopVerify(cls, PK: BLSPubkey, proof: BLSSignature) -> bool: return cls._CoreVerify(PK, PK, proof, cls.POP_TAG) @staticmethod def _AggregatePKs(PKs: Sequence[BLSPubkey]) -> BLSPubkey: """ Aggregate the public keys. Raise `ValidationError` when there is input validation error. """ try: assert len(PKs) >= 1, 'Insufficient number of PKs. (n < 1)' except Exception as e: raise ValidationError(e) aggregate = Z1 # Seed with the point at infinity for pk in PKs: pubkey_point = pubkey_to_G1(pk) aggregate = add(aggregate, pubkey_point) return G1_to_pubkey(aggregate) @classmethod def FastAggregateVerify(cls, PKs: Sequence[BLSPubkey], message: bytes, signature: BLSSignature) -> bool: try: # Inputs validation for pk in PKs: assert cls._is_valid_pubkey(pk) assert cls._is_valid_message(message) assert cls._is_valid_signature(signature) # Preconditions assert len(PKs) >= 1 # Procedure aggregate_pubkey = cls._AggregatePKs(PKs) except (ValidationError, AssertionError): return False else: return cls.Verify(aggregate_pubkey, message, signature)
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/InCTF/2021/crypto/Trouble_With_Pairs/server.py
ctfs/InCTF/2021/crypto/Trouble_With_Pairs/server.py
#!/usr/bin/env python3 from BLS import G2ProofOfPossession as bls from secret import data, bytexor, fake_flag, flag from json import loads import sys class Unbuffered(object): def __init__(self, stream): self.stream = stream def write(self, data): self.stream.write(data) self.stream.flush() def writelines(self, datas): self.stream.writelines(datas) self.stream.flush() def __getattr__(self, attr): return getattr(self.stream, attr) sys.stdout = Unbuffered(sys.stdout) header = '''We are testing a new Optimised Signature scheme for Authentication in Voting System. You can send the Published Result in Specified Format Json Format : {'Name' : name, 'Vote' : vote, 'Sign' : signature} ''' invalid_json = "Invalid Json!" invalid_sign = "Invalid signature!" flag = f"Seems like we could never patch this bug, here is your reward : {bytexor( flag, fake_flag ).hex()}" fake_flag = f"but, this one is already known, so here is your fake reward : {fake_flag.decode()}" class Challenge(): def __init__(self): self.data = data self.Names = [i["Name"] for i in self.data] self.result = [] for i in range(len(data)): self.result.append(self.Read(input("> ").strip())) def Read(self, inp): try: data = loads(inp) Name = data["Name"] Vote = data["Vote"] Sign = bytes.fromhex(data["Sign"]) assert Name in self.Names and Vote in ["R","D"] self.data[self.Names.index(Name)]["Vote"] = Vote self.data[self.Names.index(Name)]["Sign"] = Sign except: print(invalid_json) sys.exit() def Verify_aggregate(self): try: for j in ["D", "R"]: aggregate_sign = bls.Aggregate([i["Sign"] for i in self.data if i["Vote"] == j]) aggregate_Pk = bls._AggregatePKs([i["PK"] for i in self.data if i["Vote"] == j]) if not bls.Verify(aggregate_Pk, j.encode(), aggregate_sign): return False return True except: print(invalid_sign) sys.exit() def Verify_individual(self): try: return all ( bls.Verify(i["PK"], i["Vote"].encode(), i["Sign"]) for i in self.data) except: print(invalid_sign) sys.exit() def Get_Majority(self): return max( ["D","R"] , key = lambda j : sum( [ i["Count"] for i in self.data if i["Vote"] == j ] ) ) if __name__ == "__main__": print(header) challenge = Challenge() if challenge.Verify_aggregate(): if challenge.Get_Majority() == "R": print("WOW!!! You found the bug.") else: print("Everything is Verified and Perfect.") sys.exit() else: print("Not Verified!") sys.exit() if challenge.Verify_individual(): print(flag) sys.exit() else: print(fake_flag) sys.exit()
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/InCTF/2021/crypto/Gold_digger/gold_digger.py
ctfs/InCTF/2021/crypto/Gold_digger/gold_digger.py
import random from Crypto.Util.number import * flag=open("flag","rb").read() def encrypt(msg, N,x): msg, ciphertexts = bin(bytes_to_long(msg))[2:], [] for i in msg: while True: r = random.randint(1, N) if gcd(r, N) == 1: bin_r = bin(r)[2:] c = (pow(x, int(bin_r + i, 2), N) * r ** 2) % N ciphertexts.append(c) break return ciphertexts N = 76412591878589062218268295214588155113848214591159651706606899098148826991765244918845852654692521227796262805383954625826786269714537214851151966113019 x = 72734035256658283650328188108558881627733900313945552572062845397682235996608686482192322284661734065398540319882182671287066089407681557887237904496283 flag = (encrypt(flag,N,x)) open("handout.txt","w").write("ct:"+str(flag)+"\n\nN:"+str(N)+"\n\nx:"+str(x))
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/InCTF/2021/crypto/Lost_Baggage/main.py
ctfs/InCTF/2021/crypto/Lost_Baggage/main.py
#!/usr/bin/python3 from random import getrandbits as rand from gmpy2 import next_prime, invert import pickle FLAG = open('flag.txt', 'rb').read() BUF = 16 def encrypt(msg, key): msg = format(int(msg.hex(), 16), f'0{len(msg)*8}b')[::-1] assert len(msg) == len(key) return sum([k if m=='1' else 0 for m, k in zip(msg, key)]) def decrypt(ct, pv): b, r, q = pv ct = (invert(r, q)*ct)%q msg = '' for i in b[::-1]: if ct >= i: msg += '1' ct -= i else: msg += '0' return bytes.fromhex(hex(int(msg, 2))[2:]) def gen_inc_list(size, tmp=5): b = [next_prime(tmp+rand(BUF))] while len(b)!=size: val = rand(BUF) while tmp<sum(b)+val: tmp = next_prime(tmp<<1) b += [tmp] return list(map(int, b)) def gen_key(size): b = gen_inc_list(size) q = b[-1] for i in range(rand(BUF//2)): q = int(next_prime(q<<1)) r = b[-1]+rand(BUF<<3) pb = [(r*i)%q for i in b] return (b, r, q), pb if __name__ == '__main__': pvkey, pbkey = gen_key(len(FLAG) * 8) cip = encrypt(FLAG, pbkey) assert FLAG == decrypt(cip, pvkey) pickle.dump({'cip': cip, 'pbkey': pbkey}, open('enc.pickle', 'wb'))
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/InCTF/2021/crypto/Tabula_Recta/matrix.py
ctfs/InCTF/2021/crypto/Tabula_Recta/matrix.py
class Matrix: def __init__(self,dims , A=None) : self.rows = dims[0] self.cols = dims[1] if(A == None) : self.M = [[0] * self.cols for i in range(self.rows)] else : self.M = A def __str__(self) : m = "" for i in range(self.rows) : m += str(self.M[i])+"\n" return m def __add__(self,other) : C = Matrix(dims = (self.rows,self.cols)) if isinstance(other,Matrix) : for i in range(self.rows) : for j in range(self.cols) : C.M[i][j] = self.M[i][j] + other.M[i][j] else : print("Not matching type") return C def __radd__(self,other) : return self.__add__(other) def __mul__(self, other) : if isinstance(other,Matrix) : C = Matrix(dims = (self.rows,other.cols)) for i in range(self.rows) : for j in range(other.cols) : acc = 0 for k in range(other.rows) : acc += self.M[i][k] * other.M[k][j] #print(acc) C.M[i][j] = acc else : C = Matrix(dims = (self.rows,self.cols)) for i in range(self.rows) : for j in range(self.cols) : C.M[i][j] = self.M[i][j] * other return C def __rmul__(self,other) : return self.__mul__(other) def __getitem__(self,key) : if isinstance(key, tuple) : i = key[0] j = key[1] return self.M[i][j] def __setitem__(self,key,value) : if isinstance(key,tuple) : i = key[0] j = key[1] self.M[i][j] = value def __sub__(self,other) : C = Matrix(dims = (self.rows,self.cols)) if isinstance(other,Matrix) : for i in range(self.rows) : for j in range(self.cols) : C.M[i][j] = self.M[i][j] - other.M[i][j] else : print("Not matching type") return C def __rsub__(self,other) : return self.__sub__(other) if __name__ == "__main__" : X = [[1,2,3],[4,5,6],[7,8,9]] Y = [[10,11,12],[13,14,15],[16,17,18]] R = [[84,90,96],[201,216,231],[318,342,366]] X = Matrix((3,3),X) Y = Matrix((3,3),Y) Res = X.__mul__(Y).M assert Res == R print("Script successful")
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/InCTF/2021/crypto/Tabula_Recta/crypto.py
ctfs/InCTF/2021/crypto/Tabula_Recta/crypto.py
global allowed , matrix_entries allowed = "%UQh13S2dbjj,V6K1g$PTdaN4f!T023KUe#hi0PMOQiVN&cOcLR74+MLfeSgbaR*" matrix_entries = 37*37 class Cipher : def __init__(self, master_pass) : self.n = len(master_pass) self.key = [ord(i) for i in master_pass] self.mod = len(allowed) def create_key(self) : S= [] for i in range(self.mod) : S.append(i) j = 0 i = 0 for i in range(self.mod - 1) : i = (i + 1) % self.mod j = (j + S[i] + self.key[i%self.n]) %self.mod S[i], S[j] = S[j], S[i] return S def gen_stream(self , S , lgth = matrix_entries) : i = j = 0 global key_stream key_stream = [] for k in range(0, lgth): i = (i + 1) % self.mod j = (j + S[i]) % self.mod t = (S[i]+S[j]) % self.mod key_stream.append(S[t]) return key_stream def get_entries(master_pass , lgth = matrix_entries) : obj = Cipher(master_pass) l = list(map(lambda x: allowed[x],obj.gen_stream(obj.create_key(),lgth))) return l if __name__ == "__main__" : import random master_pass_len = 2**(random.choice(range(1,7))) master_pass = ''.join(chr(random.randint(0,64)) for i in range(master_pass_len)) f = open("master_pass.key","w") f.write(master_pass) f.close()
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/InCTF/2021/web/json_analyser/waf/waf.py
ctfs/InCTF/2021/web/json_analyser/waf/waf.py
from flask import Flask, request from flask_cors import CORS import ujson import json import re import os os.environ['subscription_code'] = '[REDACTED]' app=Flask(__name__) cors = CORS(app) CORS(app) cors = CORS(app, resources={ r"/verify_roles": { "origins": "*" } }) @app.route('/verify_roles',methods=['GET','POST']) def verify_roles(): no_hecking=None role=request.args.get('role') if "superuser" in role: role=role.replace("superuser",'') if " " in role: return "n0 H3ck1ng" if len(role)>30: return "invalid role" data='"name":"user","role":"{0}"'.format(role) no_hecking=re.search(r'"role":"(.*?)"',data).group(1) if(no_hecking)==None: return "bad data :(" if no_hecking == "superuser": return "n0 H3ck1ng" data='{'+data+'}' try: user_data=ujson.loads(data) except: return "bad format" role=user_data['role'] user=user_data['name'] if (user == "admin" and role == "superuser"): return os.getenv('subscription_code') else: return "no subscription for you" if __name__=='__main__': app.run(host='0.0.0.0',port=5555)
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/InCTF/2019/ateles/pow_solver.py
ctfs/InCTF/2019/ateles/pow_solver.py
#!/usr/bin/python3 from hashlib import * from string import hexdigits as chars chars = chars[:16] from tqdm import * def brute(known, H): for i in tqdm(chars): for j in chars: for k in chars: for l in chars: for m in chars: for n in chars: if sha256((known+i+j+k+l+m+n).encode()).hexdigest() == H: return (i+j+k+l+m+n) if __name__=="__main__": known = input("known: ") H = input("hash: ") print(brute(known, H))
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false