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/0xL4ugh/2024/crypto/RSA_GCD/chall2.py | ctfs/0xL4ugh/2024/crypto/RSA_GCD/chall2.py | import math
from Crypto.Util.number import *
from secret import flag,p,q
from gmpy2 import next_prime
m = bytes_to_long(flag.encode())
n=p*q
power1=getPrime(128)
power2=getPrime(128)
out1=pow((p+5*q),power1,n)
out2=pow((2*p-3*q),power2,n)
eq1 = next_prime(out1)
c = pow(m,eq1,n)
with open('chall2.txt', 'w') as f:
f.write(f"power1={power1}\npower2={power2}\neq1={eq1}\nout2={out2}\nc={c}\nn={n}")
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/0xL4ugh/2024/crypto/L4ugh/src/challenge.py | ctfs/0xL4ugh/2024/crypto/L4ugh/src/challenge.py | from Crypto.Util.number import *
from utils import *
Flag = '0xL4ugh{Fak3_Fl@g}'
key = os.urandom(16)
x = random.randint(2**10, 2**20)
seed = "It's (666) the work of the devil..."
print(seed)
d = evilRSA(seed)
d_evil = d >> (int(seed[6:9])//2)
d_good = d % pow(2,int(seed[6:9])//2)
z='''1.d_evil
2.d_good
3.pass d to get to sec part
Ex : {"option":"1"}
d=d_evil+d_good
'''
print('all input data is in json')
print(z)
w='''1.get your token
2.sign in'''
while True:
test = json.loads(input('option:\t'))
if test['option'] == "1":
Ns,es = RsaGen(d_evil)
print(f'Ns={Ns}')
print(f'es={es}')
if test['option'] == "2":
res = getrand(d_good)
print(f'RAND = {res}')
if test['option'] == "3":
# check = int(input('Enter the secret key to access admin privileges:\t'))
if int(test['d']) != d:
print("you need to provide d to continue")
exit()
elif int(test['d']) == d:
z = json.loads(input(w))
if z['option'] == '1':
user = z['user']
data = {"id": x, "isadmin": False, "username": user}
print(data)
try:
pt = json.dumps(data)
ct = encrypt(pt)
print(ct)
except json.JSONDecodeError as e:
print(f"Error decoding JSON: {e}")
x += x
elif z['option'] == '2':
token = z['token']
dec = decrypt(token)
if dec is not None:
print("Decrypted plaintext:", dec)
else:
print("Decryption failed. cant decrypt :",dec)
continue
flag(dec)
main() | python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/0xL4ugh/2024/crypto/L4ugh/src/utils.py | ctfs/0xL4ugh/2024/crypto/L4ugh/src/utils.py | from Crypto.Util.number import *
from Crypto.Util.Padding import pad, unpad
from Crypto.Cipher import AES
import os
import random
import json
key = os.urandom(16)
Flag = '0xL4ugh{Fak3_Fl@g}'
max_retries=19
def evilRSA(seed):
d = 1
while d.bit_length() != int(seed[6:9]):
d = getPrime(int(seed[6:9]))
while not isPrime(d>>333):
d = getPrime(int(seed[6:9]))
return d
def RsaGen(d):
for _ in range(max_retries):
try:
Ns, es = [], []
for evilChar in '666':
p = getPrime(512)
q = getPrime(512)
phi = (p - 1) * (q - 1)
e = inverse(d, phi)
Ns.append(p * q)
es.append(e)
return Ns, es
except ValueError as e:
# Ignore the error and continue the loop
pass
def getrand(good):
user_input = int(input("Enter your payload:\t"))
if user_input.bit_length() > (666//2):
print("MEH")
return
return [good*user_input + getPrime(666//2) for i in range(10)]
def encrypt(pt):
IV = os.urandom(16)
cipher = AES.new(key, AES.MODE_CBC, IV)
encrypted = cipher.encrypt(pad(pt.encode(), 16))
return IV.hex() + encrypted.hex()
def decrypt(ct):
try:
IV = bytes.fromhex(ct[:32])
cipher = AES.new(key, AES.MODE_CBC, IV)
decrypted = cipher.decrypt(bytes.fromhex(ct[32:]))
except ValueError as decryption_error:
print("AES Decryption Error:", decryption_error)
return None
try:
plaintext = unpad(decrypted, 16).decode()
except ValueError as unpadding_error:
print("Unpadding Error:", decrypted)
return None
return plaintext
def flag(data):
data=json.loads(data)
print('1. Get Flag')
print('2.Exit')
while True:
print('1. Get Flag')
print('2.Exit')
z = json.loads(input())
if z['option'] == '1':
if isinstance(data, dict) and data['isadmin'] == True:
print(Flag)
else:
print('Try another time')
elif z['option'] == '2':
return | python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/0xL4ugh/2024/web/Micro/app.py | ctfs/0xL4ugh/2024/web/Micro/app.py | from flask import Flask, request
import mysql.connector, hashlib
app = Flask(__name__)
# MySQL connection configuration
mysql_host = "127.0.0.1"
mysql_user = "ctf"
mysql_password = "ctf123"
mysql_db = "CTF"
def authenticate_user(username, password):
try:
conn = mysql.connector.connect(
host=mysql_host,
user=mysql_user,
password=mysql_password,
database=mysql_db
)
cursor = conn.cursor()
query = "SELECT * FROM users WHERE username = %s AND password = %s"
cursor.execute(query, (username, password))
result = cursor.fetchone()
cursor.close()
conn.close()
return result
except mysql.connector.Error as error:
print("Error while connecting to MySQL", error)
return None
@app.route('/login', methods=['POST'])
def handle_request():
try:
username = request.form.get('username')
password = hashlib.md5(request.form.get('password').encode()).hexdigest()
# Authenticate user
user_data = authenticate_user(username, password)
if user_data:
return "0xL4ugh{Test_Flag}"
else:
return "Invalid credentials"
except:
return "internal error happened"
if __name__ == '__main__':
app.run(host='0.0.0.0', port=5000, debug=True)
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/SunshineCTF/2021/crypto/MultipleExponents/source.py | ctfs/SunshineCTF/2021/crypto/MultipleExponents/source.py | from Crypto.Util.number import getPrime
from sunshine_secrets import FLAG
p = getPrime(512)
q = getPrime(512)
assert p != q
n = p * q
phi = (p-1) * (q-1)
e1 = getPrime(512)
e2 = getPrime(512)
d1 = pow(e1, -1, phi)
d2 = pow(e2, -1, phi)
f = int(FLAG.encode("utf-8").hex(), 16)
c1 = pow(f, e1, n)
c2 = pow(f, e2, n)
print({"n": n, "e1": e1, "e2": e2, "c1": c1, "c2":c2})
#Here is the output.
#{'n': 86683300105327745365439507825347702001838360528840593828044782382505346188827666308497121206572195142485091411381691608302239467720308057846966586611038898446400292056901615985225826651071775239736355509302701234225559345175968513640372874437860580877571155199027883755959442408968543666251138423852242301639, 'e1': 11048796690938982746152432997911442334648615616780223415034610235310401058533076125720945559697433984697892923155680783661955179131565701195219010273246901, 'e2': 9324711814017970310132549903114153787960184299541815910528651555672096706340659762220635996774790303001176856753572297256560097670723015243180488972016453, 'c1': 84855521319828020020448068809384113135703375013574055636013459151984904926013060168559438932572351720988574536405041219757650609586761217385808427001020204262032305874206933548737826840501447182203920238204769775531537454607204301478815830436609423437869412027820433923450056939361510843151320837485348066171, 'c2': 54197787252581595971205193568331257218605603041941882795362450109513512664722304194032130716452909927265994263753090021761991044436678485565631063700887091405932490789561882081600940995910094939803525325448032287989826156888870845730794445212288211194966299181587885508098448750830074946100105532032186340554}
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/SunshineCTF/2025/rev/Space_Race/client.py | ctfs/SunshineCTF/2025/rev/Space_Race/client.py | import sys, socket, json, threading, queue, time
import pygame
WIDTH, HEIGHT = 900, 600
BG = (8, 10, 16)
FG = (230, 235, 240)
TRACK_CLR = (40, 40, 48)
FINISH_CLR = (220, 220, 220)
ROVER_CLR = (120, 200, 255)
OBST_CLR = (255, 120, 120)
PX_PER_WU = 2.2
class Net:
def __init__(self, host, port):
self.sock = socket.create_connection((host, port))
self.r = self.sock.makefile('r', buffering=1, encoding='utf-8', newline='\n')
self.q = queue.Queue()
self.alive = True
threading.Thread(target=self.reader, daemon=True).start()
def reader(self):
try:
for line in self.r:
line = line.strip()
if not line:
continue
try:
self.q.put(json.loads(line))
except Exception:
pass
except Exception:
pass
self.alive = False
def world_to_screen_x(x_wu, half_width_wu, rover_x=0.0):
left = WIDTH * 0.2
right = WIDTH * 0.8
x_rel = float(x_wu) - float(rover_x)
t = (x_rel + half_width_wu) / (2 * half_width_wu)
return int(left + t * (right - left))
def main():
if len(sys.argv) != 3:
print(f"usage: python {sys.argv[0]} HOST PORT")
sys.exit(1)
host, port = sys.argv[1], int(sys.argv[2])
net = Net(host, port)
pygame.init()
screen = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption("Space Race: Rover")
clock = pygame.time.Clock()
font = pygame.font.SysFont(None, 20)
big = pygame.font.SysFont(None, 48)
latest = None
flag = None
flag_time = None
while True:
try:
while True:
obj = net.q.get_nowait()
if obj.get("t") == "telemetry":
latest = obj
if obj.get("flag") is not None and flag is None:
flag = obj["flag"]
flag_time = time.time()
except queue.Empty:
pass
'''
TODO: Implement the controls for the rover client!
{"t":"can","frame":"0123456789abcdef"}
'''
for e in pygame.event.get():
if e.type == pygame.QUIT:
pygame.quit(); return
if e.type == pygame.KEYDOWN:
if e.key in (pygame.K_ESCAPE, pygame.K_q):
pygame.quit(); return
elif e.key == pygame.K_UP:
pass
elif e.key == pygame.K_DOWN:
pass
elif e.key == pygame.K_LEFT:
pass
elif e.key == pygame.K_RIGHT:
pass
elif e.key == pygame.K_b:
pass
elif e.key == pygame.K_s:
pass
elif e.key == pygame.K_r:
pass
screen.fill(BG)
if latest:
track = latest.get("track", {})
half_w = float(track.get("half_width", 60.0))
rover_x = float(latest.get("x", 0.0))
tlx = world_to_screen_x(-half_w, half_w, rover_x)
trx = world_to_screen_x(+half_w, half_w, rover_x)
track_px_w = max(1, trx - tlx)
pygame.draw.rect(screen, TRACK_CLR, (tlx, 0, track_px_w, HEIGHT), border_radius=12)
s = float(latest.get("s", 0.0))
length = float(track.get("length", 1.0))
progress = s / max(1.0, length)
if progress > 0.85:
for y in range(0, HEIGHT, 14):
pygame.draw.line(screen, FINISH_CLR, (trx, y), (trx, y+7), 3)
obs = latest.get("obstacles", [])
if obs is not None:
for ob in obs:
try:
dy = float(ob["dy"])
if dy < 0:
continue
y = int(HEIGHT/2 - dy * PX_PER_WU)
x = world_to_screen_x(float(ob["x"]), half_w, rover_x)
w_px = max(6, int((float(ob["w"]) / (2 * half_w)) * track_px_w))
rect = pygame.Rect(x - w_px//2, y - 10, w_px, 20)
pygame.draw.rect(screen, OBST_CLR, rect, border_radius=4)
except (KeyError, ValueError, TypeError):
continue
rover_rect = pygame.Rect(WIDTH//2 - 16, HEIGHT//2 + 18, 32, 44)
pygame.draw.rect(screen, ROVER_CLR, rover_rect, border_radius=6)
pygame.draw.rect(screen, FG, rover_rect, 2, border_radius=6)
hud = [
f"Status: {latest.get('status','')}",
f"Dist: {s:.1f}/{length:.0f} wu",
f"Lateral x: {rover_x:.1f} wu",
f"Speed: {float(latest.get('vel',0.0)):.2f} wu/s",
f"Throttle: {latest.get('throttle_pct',0)}% Steer: {latest.get('steer_pct',0)}%",
f"{str(latest.get('msg',''))[:64]}",
]
for i, line in enumerate(hud):
img = font.render(line, True, FG)
screen.blit(img, (12, 10 + i*18))
if flag:
img = big.render(flag, True, (255, 240, 120))
screen.blit(img, img.get_rect(center=(WIDTH//2, HEIGHT//2 - 80)))
if time.time() - flag_time > 6:
pygame.quit(); return
pygame.display.flip()
clock.tick(60)
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/SunshineCTF/2025/crypto/Plutonian_Crypto/main.py | ctfs/SunshineCTF/2025/crypto/Plutonian_Crypto/main.py | #!/usr/bin/env python3
import sys
import time
from binascii import hexlify
from Crypto.Cipher import AES
from Crypto.Util import Counter
from Crypto.Random import get_random_bytes
from ctf_secrets import MESSAGE
KEY = get_random_bytes(16)
NONCE = get_random_bytes(8)
WELCOME = '''
,-.
/ \\
: \\ ....*
| . .- \\-----00''
: . ..' \\''//
\\ . . \\/
\\ . ' . NASA Deep Space Listening Posts
, . \\ \\ ~ Est. 1969 ~
,|,. -.\\ \\
'.|| `-...__..-
| | "We're always listening to you!"
|__|
/||\\\\
//||\\\\
// || \\\\
__//__||__\\\\__
'--------------'
'''
def main():
# Print ASCII art and intro
sys.stdout.write(WELCOME)
sys.stdout.flush()
time.sleep(0.5)
sys.stdout.write("\nConnecting to remote station")
sys.stdout.flush()
for i in range(5):
sys.stdout.write(".")
sys.stdout.flush()
time.sleep(0.5)
sys.stdout.write("\n\n== BEGINNING TRANSMISSION ==\n\n")
sys.stdout.flush()
C = 0
while True:
ctr = Counter.new(64, prefix=NONCE, initial_value=C, little_endian=False)
cipher = AES.new(KEY, AES.MODE_CTR, counter=ctr)
ct = cipher.encrypt(MESSAGE)
sys.stdout.write("%s\n" % hexlify(ct).decode())
sys.stdout.flush()
C += 1
time.sleep(0.5)
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/SunshineCTF/2025/crypto/Bits_of_Space/relay.py | ctfs/SunshineCTF/2025/crypto/Bits_of_Space/relay.py | import socket
import struct
from Crypto.Cipher import AES
from Crypto.Util.Padding import unpad
from secrets import key
HOST = "0.0.0.0"
PORT = 25401
VALID_DEVICES = {
0x13371337: b"Status Relay\n",
0x1337babe: b"Ground Station Alpha\n",
0xdeadbeef: b"Lunar Relay\n",
0xdeadbabe: b"Restricted Relay\n"
}
CHANNEL_MESSAGES = {
1: b"Channel 1: Deep Space Telemetry Stream.\n",
2: b"Channel 2: Asteroid Mining Operations Log.\n",
3: b"Channel 3: Secret Alien Communication Feed!\n",
}
def read_flag():
with open("/flag", "rb") as fl: return fl.readline() + b'\n'
def decrypt_subscription(data: bytes, key: bytes):
iv = data[:AES.block_size]
body = data[AES.block_size:]
cipher = AES.new(key, AES.MODE_CBC, iv)
plaintext = unpad(cipher.decrypt(body), AES.block_size)
device_id, start, end, channel = struct.unpack("<IQQI", plaintext)
return device_id, start, end, channel
def handle_client(conn):
try:
conn.sendall(b"== Space Relay ==\n")
conn.sendall(b"Send your subscription packet:\n")
data = conn.recv(1024).strip()
if not data:
conn.sendall(b"No data received.\n")
return
try:
device_id, start, end, channel = decrypt_subscription(data, key)
except Exception as e:
conn.sendall(b"Invalid subscription. Access denied.\n")
return
if device_id not in VALID_DEVICES:
conn.sendall(b"Unknown device ID. Authentication failed.\n")
return
# Secret Device
if device_id == 0xdeadbabe:
conn.sendall(b"You have reached the restricted relay... here you go.\n")
conn.sendall(read_flag())
return
if channel not in CHANNEL_MESSAGES:
conn.sendall(b"Unknown channel. No signal.\n")
return
device_name = VALID_DEVICES[device_id]
conn.sendall(b"Authenticated device: " + device_name)
conn.sendall(CHANNEL_MESSAGES[channel])
finally:
conn.sendall(b"See you next time space cowboy.\n")
conn.close()
def main():
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
s.bind((HOST, PORT))
s.listen(5)
print(f"Satellite relay listening on {HOST}:{PORT}...")
while True:
conn, addr = s.accept()
handle_client(conn)
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/SunshineCTF/2022/crypto/AESChall/aeschall.py | ctfs/SunshineCTF/2022/crypto/AESChall/aeschall.py | #!/usr/bin/env python
"""
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.
"""
"""
This has been edited a bit from the original to update it to python3
..as well as some security improvements
"""
SboxOriginal = (
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,
)
# learnt from http://cs.ucsb.edu/~koc/cs178/projects/JT/aes.c
xtime = lambda a: (((a << 1) ^ 0x1B) & 0xFF) if (a & 0x80) else (a << 1)
Rcon = (
0x00, 0x01, 0x02, 0x04, 0x08, 0x10, 0x20, 0x40,
0x80, 0x1B, 0x36, 0x6C, 0xD8, 0xAB, 0x4D, 0x9A,
0x2F, 0x5E, 0xBC, 0x63, 0xC6, 0x97, 0x35, 0x6A,
0xD4, 0xB3, 0x7D, 0xFA, 0xEF, 0xC5, 0x91, 0x39,
)
def text2matrix(text):
text = int(text.hex(), 16)
matrix = []
for i in range(16):
byte = (text >> (8 * (15 - i))) & 0xFF
if i % 4 == 0:
matrix.append([byte])
else:
matrix[i // 4].append(byte)
return matrix
def matrix2text(matrix):
text = 0
for i in range(4):
for j in range(4):
text |= (matrix[i][j] << (120 - 8 * (4 * i + j)))
return text.to_bytes(16, byteorder='big')
class AES:
def __init__(self, master_key, Sbox=SboxOriginal):
self.Sbox = Sbox
self.InvSbox = [0]* 256
for i in range(256):
self.InvSbox[self.Sbox[i]] = i
self.change_key(master_key)
def change_key(self, master_key):
self.round_keys = text2matrix(master_key)
# print self.round_keys
for i in range(4, 4 * 11):
self.round_keys.append([])
if i % 4 == 0:
byte = self.round_keys[i - 4][0] \
^ self.Sbox[self.round_keys[i - 1][1]] \
^ Rcon[i // 4]
self.round_keys[i].append(byte)
for j in range(1, 4):
byte = self.round_keys[i - 4][j] \
^ self.Sbox[self.round_keys[i - 1][(j + 1) % 4]]
self.round_keys[i].append(byte)
else:
for j in range(4):
byte = self.round_keys[i - 4][j] \
^ self.round_keys[i - 1][j]
self.round_keys[i].append(byte)
# print self.round_keys
def encrypt(self, plaintext):
self.plain_state = text2matrix(plaintext)
self.__add_round_key(self.plain_state, self.round_keys[:4])
for i in range(1, 10):
self.__round_encrypt(self.plain_state, self.round_keys[4 * i : 4 * (i + 1)])
self.__sub_bytes(self.plain_state)
self.__shift_rows(self.plain_state)
self.__add_round_key(self.plain_state, self.round_keys[40:])
return matrix2text(self.plain_state)
def decrypt(self, ciphertext):
self.cipher_state = text2matrix(ciphertext)
self.__add_round_key(self.cipher_state, self.round_keys[40:])
self.__inv_shift_rows(self.cipher_state)
self.__inv_sub_bytes(self.cipher_state)
for i in range(9, 0, -1):
self.__round_decrypt(self.cipher_state, self.round_keys[4 * i : 4 * (i + 1)])
self.__add_round_key(self.cipher_state, self.round_keys[:4])
return matrix2text(self.cipher_state)
def __add_round_key(self, s, k):
for i in range(4):
for j in range(4):
s[i][j] ^= k[i][j]
def __round_encrypt(self, state_matrix, key_matrix):
self.__sub_bytes(state_matrix)
self.__shift_rows(state_matrix)
self.__mix_columns(state_matrix)
self.__add_round_key(state_matrix, key_matrix)
def __round_decrypt(self, state_matrix, key_matrix):
self.__add_round_key(state_matrix, key_matrix)
self.__inv_mix_columns(state_matrix)
self.__inv_shift_rows(state_matrix)
self.__inv_sub_bytes(state_matrix)
def __sub_bytes(self, s):
for i in range(4):
for j in range(4):
s[i][j] = self.Sbox[s[i][j]]
def __inv_sub_bytes(self, s):
for i in range(4):
for j in range(4):
s[i][j] = self.InvSbox[s[i][j]]
def __shift_rows(self, s):
s[0][1], s[1][1], s[2][1], s[3][1] = s[1][1], s[2][1], s[3][1], s[0][1]
s[0][2], s[1][2], s[2][2], s[3][2] = s[2][2], s[3][2], s[0][2], s[1][2]
s[0][3], s[1][3], s[2][3], s[3][3] = s[3][3], s[0][3], s[1][3], s[2][3]
def __inv_shift_rows(self, s):
s[0][1], s[1][1], s[2][1], s[3][1] = s[3][1], s[0][1], s[1][1], s[2][1]
s[0][2], s[1][2], s[2][2], s[3][2] = s[2][2], s[3][2], s[0][2], s[1][2]
s[0][3], s[1][3], s[2][3], s[3][3] = s[1][3], s[2][3], s[3][3], s[0][3]
def __mix_single_column(self, a):
# please see Sec 4.1.2 in The Design of Rijndael
t = a[0] ^ a[1] ^ a[2] ^ a[3]
u = a[0]
a[0] ^= t ^ xtime(a[0] ^ a[1])
a[1] ^= t ^ xtime(a[1] ^ a[2])
a[2] ^= t ^ xtime(a[2] ^ a[3])
a[3] ^= t ^ xtime(a[3] ^ u)
def __mix_columns(self, s):
for i in range(4):
self.__mix_single_column(s[i])
def __inv_mix_columns(self, s):
# see Sec 4.1.3 in The Design of Rijndael
for i in range(4):
u = xtime(xtime(s[i][0] ^ s[i][2]))
v = xtime(xtime(s[i][1] ^ s[i][3]))
s[i][0] ^= u
s[i][1] ^= v
s[i][2] ^= u
s[i][3] ^= v
self.__mix_columns(s)
# new code!
import os
def main():
boxxed = [105, 121, 73, 89, 41, 57, 9, 25, 233, 249, 201, 217, 169, 185, 137, 153, 104, 120, 72, 88, 40, 56, 8, 24, 232, 248, 200, 216, 168, 184, 136, 152, 107, 123, 75, 91, 43, 59, 11, 27, 235, 251, 203, 219, 171, 187, 139, 155, 106, 122, 74, 90, 42, 58, 10, 26, 234, 250, 202, 218, 170, 186, 138, 154, 109, 125, 77, 93, 45, 61, 13, 29, 237, 253, 205, 221, 173, 189, 141, 157, 108, 124, 76, 92, 44, 60, 12, 28, 236, 252, 204, 220, 172, 188, 140, 156, 111, 127, 79, 95, 47, 63, 15, 31, 239, 255, 207, 223, 175, 191, 143, 159, 110, 126, 78, 94, 46, 62, 14, 30, 238, 254, 206, 222, 174, 190, 142, 158, 97, 113, 65, 81, 33, 49, 1, 17, 225, 241, 193, 209, 161, 177, 129, 145, 96, 112, 64, 80, 32, 48, 0, 16, 224, 240, 192, 208, 160, 176, 128, 144, 99, 115, 67, 83, 35, 51, 3, 19, 227, 243, 195, 211, 163, 179, 131, 147, 98, 114, 66, 82, 34, 50, 2, 18, 226, 242, 194, 210, 162, 178, 130, 146, 101, 117, 69, 85, 37, 53, 5, 21, 229, 245, 197, 213, 165, 181, 133, 149, 100, 116, 68, 84, 36, 52, 4, 20, 228, 244, 196, 212, 164, 180, 132, 148, 103, 119, 71, 87, 39, 55, 7, 23, 231, 247, 199, 215, 167, 183, 135, 151, 102, 118, 70, 86, 38, 54, 6, 22, 230, 246, 198, 214, 166, 182, 134, 150]
flag = open("flag.txt", "rb").read()
plaintext = b"Here is your flag: " + flag
while len(plaintext) % 16 != 0:
plaintext += b"\x00"
ciphertext = b""
key = os.urandom(16)
cipher = AES(key, Sbox=boxxed)
while len(plaintext) > 0:
ciphertext += cipher.encrypt(plaintext[:16])
plaintext = plaintext[16:]
print("Try to recover the flag! ", ciphertext.hex())
if __name__ == "__main__":
main()
# When ran with the correct flag it outputs the following, can you recover it?
# Try to recover the flag! 725af38e9584f694638a7323e44749c5ba1e175e61f1bd7cf356da50e7c182cf7ed5ea6e12294f697f3b59b125a3940bc86ca5cfad39b4da4be547dcafbbb17b
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/BlazCTF/2023/Maze/challenge.py | ctfs/BlazCTF/2023/Maze/challenge.py | from typing import Dict
from ctf_launchers.pwn_launcher import PwnChallengeLauncher
from ctf_server.types import LaunchAnvilInstanceArgs
class Challenge(PwnChallengeLauncher):
def get_anvil_instances(self) -> Dict[str, LaunchAnvilInstanceArgs]:
return {
"main": self.get_anvil_instance(fork_url=None),
}
Challenge().run()
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/BlazCTF/2023/Rock_Scissor_Paper/challenge.py | ctfs/BlazCTF/2023/Rock_Scissor_Paper/challenge.py | from typing import Dict
from ctf_launchers.pwn_launcher import PwnChallengeLauncher
from ctf_server.types import LaunchAnvilInstanceArgs
class Challenge(PwnChallengeLauncher):
def get_anvil_instances(self) -> Dict[str, LaunchAnvilInstanceArgs]:
return {
"main": self.get_anvil_instance(fork_url=None),
}
Challenge().run() | python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/BlazCTF/2023/Lockless_Swap/challenge.py | ctfs/BlazCTF/2023/Lockless_Swap/challenge.py | from typing import Dict
from ctf_launchers.pwn_launcher import PwnChallengeLauncher
from ctf_server.types import LaunchAnvilInstanceArgs
class Challenge(PwnChallengeLauncher):
def get_anvil_instances(self) -> Dict[str, LaunchAnvilInstanceArgs]:
return {
"main": self.get_anvil_instance(fork_url=None),
}
Challenge().run() | python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/BlazCTF/2023/Tornado_Crash/challenge.py | ctfs/BlazCTF/2023/Tornado_Crash/challenge.py | from typing import Dict
from ctf_launchers.pwn_launcher import PwnChallengeLauncher
from ctf_server.types import LaunchAnvilInstanceArgs
class Challenge(PwnChallengeLauncher):
def get_anvil_instances(self) -> Dict[str, LaunchAnvilInstanceArgs]:
return {
"main": self.get_anvil_instance(fork_url=None),
}
Challenge().run()
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/BlazCTF/2023/Ketai/challenge.py | ctfs/BlazCTF/2023/Ketai/challenge.py | from typing import Dict
from ctf_launchers.pwn_launcher import PwnChallengeLauncher
from ctf_server.types import LaunchAnvilInstanceArgs
class Challenge(PwnChallengeLauncher):
def get_anvil_instances(self) -> Dict[str, LaunchAnvilInstanceArgs]:
return {
"main": self.get_anvil_instance(fork_url=None),
}
Challenge().run() | python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/BlazCTF/2023/Eazy_NFT/challenge.py | ctfs/BlazCTF/2023/Eazy_NFT/challenge.py | from typing import Dict
from ctf_launchers.pwn_launcher import PwnChallengeLauncher
from ctf_server.types import LaunchAnvilInstanceArgs
class Challenge(PwnChallengeLauncher):
def get_anvil_instances(self) -> Dict[str, LaunchAnvilInstanceArgs]:
return {
"main": self.get_anvil_instance(fork_url=None),
}
Challenge().run() | python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/BlazCTF/2023/Be_biLlionAireS_Today/challenge.py | ctfs/BlazCTF/2023/Be_biLlionAireS_Today/challenge.py | from typing import Dict
from ctf_launchers.pwn_launcher import PwnChallengeLauncher
from ctf_server.types import (
LaunchAnvilInstanceArgs,
UserData,
get_privileged_web3,
)
from foundry.anvil import anvil_setBalance
MULTISIG = "0x67CA7Ca75b69711cfd48B44eC3F64E469BaF608C"
ADDITIONAL_OWNER1 = "0x6813Eb9362372EEF6200f3b1dbC3f819671cBA69"
ADDITIONAL_OWNER2 = "0x7E5F4552091A69125d5DfCb7b8C2659029395Bdf"
ADDITIONAL_OWNER3 = "0x2B5AD5c4795c026514f8317c7a215E218DcCD6cF"
class Challenge(PwnChallengeLauncher):
def deploy(self, user_data: UserData, mnemonic: str) -> str:
web3 = get_privileged_web3(user_data, "main")
challenge_addr = super().deploy(user_data, mnemonic)
anvil_setBalance(web3, MULTISIG, hex(int(10e18)))
add_owner(web3, ADDITIONAL_OWNER1)
add_owner(web3, ADDITIONAL_OWNER2)
add_owner(web3, ADDITIONAL_OWNER3)
return challenge_addr
def get_anvil_instances(self) -> Dict[str, LaunchAnvilInstanceArgs]:
return {
"main": self.get_anvil_instance(
balance=1,
fork_block_num=18_677_777,
),
}
def send_unsigned_transaction(web3, to_addr, from_addr, gas, gas_price, value, data):
return web3.provider.make_request(
"eth_sendUnsignedTransaction",
[
{
"to": to_addr,
"from": from_addr,
"gas": hex(gas),
"gasPrice": hex(gas_price),
"value": value,
"data": data,
}
],
)
def add_owner(web3, owner):
return send_unsigned_transaction(
web3,
MULTISIG,
MULTISIG,
104941,
50000000000,
"0x00",
# calling addOwnerWithThreshold(address owner = ADDITIONAL_OWNER, uint256 threshold = 3)
f"0x0d582f13000000000000000000000000{owner.replace('0x', '')}0000000000000000000000000000000000000000000000000000000000000003")
Challenge().run()
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/BlazCTF/2023/Hide_on_Bush/challenge.py | ctfs/BlazCTF/2023/Hide_on_Bush/challenge.py | from typing import Dict
from ctf_launchers.pwn_launcher import PwnChallengeLauncher
from ctf_server.types import (
get_privileged_web3,
DaemonInstanceArgs,
LaunchAnvilInstanceArgs,
UserData,
)
BLOCK_TIME = 12
class Challenge(PwnChallengeLauncher):
def deploy(self, user_data: UserData, mnemonic: str) -> str:
web3 = get_privileged_web3(user_data, "main")
web3.provider.make_request("evm_setAutomine", [True])
challenge_addr = super().deploy(user_data, mnemonic)
web3.provider.make_request("evm_setIntervalMining", [BLOCK_TIME])
return challenge_addr
def get_anvil_instances(self) -> Dict[str, LaunchAnvilInstanceArgs]:
return {
"main": self.get_anvil_instance(
fork_url=None,
accounts=3,
block_time=BLOCK_TIME,
),
}
def get_daemon_instances(self) -> Dict[str, DaemonInstanceArgs]:
return {
"daemon": DaemonInstanceArgs(
image="fuzzland/hide-on-bush-daemon:latest"
)
}
Challenge().run()
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/BlazCTF/2023/Hide_on_Bush/frontrun-bot/daemon.py | ctfs/BlazCTF/2023/Hide_on_Bush/frontrun-bot/daemon.py | import signal
import subprocess
import sys
from ctf_server.types import UserData, get_privileged_web3, get_additional_account
from ctf_launchers.daemon import Daemon
def exit_handler(signal, frame):
print("Terminating the process")
exit(-1)
class BotDaemon(Daemon):
def __init__(self):
super().__init__(required_properties=["mnemonic", "challenge_address"])
def _run(self, user_data: UserData):
challenge_addr = user_data["metadata"]["challenge_address"]
mev_guy = get_additional_account(user_data["metadata"]["mnemonic"], 0)
web3 = get_privileged_web3(user_data, "main")
anvil_instance = user_data["anvil_instances"]["main"]
weth_addr = web3.eth.call({ "to": challenge_addr, "data": "0x3fc8cef3" })[-20:].hex() # weth()
bot_addr = web3.eth.call({ "to": challenge_addr, "data": "0x10814c37" })[-20:].hex() # bot()
print(f"bot owner: {mev_guy.address}")
print(f"bot address: {bot_addr}")
print(f"weth address: {weth_addr}")
print(f"starting bot")
signal.signal(signal.SIGINT, exit_handler)
signal.signal(signal.SIGTERM, exit_handler)
proc = subprocess.Popen(
args=[
"/home/user/frontrun-bot",
f"ws://{anvil_instance['ip']}:{anvil_instance['port']}",
mev_guy.key.hex(),
bot_addr,
weth_addr,
],
text=True,
encoding="utf8",
stdout=sys.stdout,
stderr=sys.stderr,
)
pass # allow signal handlers to catch signals
proc.wait()
if proc.poll() is not None:
print("bot terminated")
signal.signal(signal.SIGINT, exit_handler)
signal.signal(signal.SIGTERM, exit_handler)
BotDaemon().start() | python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/Aero/2021/crypto/boggart/boggart.py | ctfs/Aero/2021/crypto/boggart/boggart.py | #!/usr/bin/env python3.8
from gmpy import next_prime
from random import getrandbits
def bytes_to_long(data):
return int.from_bytes(data, 'big')
class Wardrobe:
@staticmethod
def create_boggarts(fear, danger):
# for each level of danger we're increasing fear
while danger > 0:
fear = next_prime(fear)
if getrandbits(1):
yield fear
danger -= 1
class Wizard:
def __init__(self, magic, year, experience):
self.magic = magic
self.knowledge = year - 1 # the wizard is currently studying the current year
self.experience = experience
def cast_riddikulus(self, boggart):
# increasing the wizard's experience by casting the riddikulus charm
knowledge, experience = self.knowledge, self.experience
while boggart > 1:
knowledge, experience = experience, (experience * self.experience - knowledge) % self.magic
boggart -= 1
self.experience = experience
def main():
year = 3
bits = 512
boggart_fear = 31337
boggart_danger = 16
neutral_magic, light_magic, dark_magic = [getrandbits(bits) for _ in range(3)]
magic = next_prime(neutral_magic | light_magic) * next_prime(neutral_magic | dark_magic)
print('Hello. I am Professor Remus Lupin. Today I\'m going to show you how to deal with the boggart.')
print(neutral_magic)
print(magic)
with open('flag.txt', 'rb') as file:
flag = file.read().strip()
# some young wizards without knowledge of the riddikulus charm
harry_potter = Wizard(magic, year, bytes_to_long(b'the boy who lived'))
you = Wizard(magic, year, bytes_to_long(flag))
for boggart in Wardrobe.create_boggarts(boggart_fear, boggart_danger):
# wizards should train to learn the riddikulus charm
harry_potter.cast_riddikulus(boggart)
you.cast_riddikulus(boggart)
# wizard's experience should be increased
print(harry_potter.experience)
print(you.experience)
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/Aero/2021/crypto/horcrux/horcrux.py | ctfs/Aero/2021/crypto/horcrux/horcrux.py | #!/usr/bin/env python3.8
from os import urandom
from gmpy2 import next_prime
from random import randrange, getrandbits
from Crypto.Cipher import AES
from fastecdsa.curve import Curve
def bytes_to_long(data):
return int.from_bytes(data, 'big')
def generate_random_point(p):
while True:
a, x, y = (randrange(0, p) for _ in range(3))
b = (pow(y, 2, p) - pow(x, 3, p) - a * x) % p
if (4 * pow(a, 3, p) + 27 * pow(b, 2, p)) % p != 0:
break
return Curve(None, p, a, b, None, x, y).G
class DarkWizard:
def __init__(self, age):
self.power = int(next_prime(getrandbits(age)))
self.magic = generate_random_point(self.power)
self.soul = randrange(0, self.power)
def create_horcrux(self, location, weakness):
# committing a murder
murder = self.cast_spell(b'AVADA KEDAVRA')
# splitting the soul in half
self.soul = self.soul * pow(2, -1, self.power) % self.power
# making a horcrux
horcrux = (self.soul + murder) * self.magic
# nobody should know location and weakness of the horcrux
horcrux.x ^= location
horcrux.y ^= weakness
return horcrux
def cast_spell(self, spell_name):
spell = bytes_to_long(spell_name)
return spell %~ spell
def encrypt(key, plaintext):
cipher = AES.new(key=key, mode=AES.MODE_ECB)
padding = b'\x00' * (AES.block_size - len(plaintext) % AES.block_size)
return cipher.encrypt(plaintext + padding)
def main():
wizard_age = 3000
horcruxes_count = 2
wizard = DarkWizard(wizard_age)
print(f'Wizard\'s power:\n{hex(wizard.power)}\n')
print(f'Wizard\'s magic:\n{wizard.magic}\n')
key = urandom(AES.key_size[0])
horcrux_length = len(key) // horcruxes_count
for i in range(horcruxes_count):
key_part = key[i * horcrux_length:(i + 1) * horcrux_length]
horcrux_location = bytes_to_long(key_part[:horcrux_length // 2])
horcrux_weakness = bytes_to_long(key_part[horcrux_length // 2:])
horcrux = wizard.create_horcrux(horcrux_location, horcrux_weakness)
print(f'Horcrux #{i + 1}:\n{horcrux}\n')
with open('flag.txt', 'rb') as file:
flag = file.read().strip()
ciphertext = encrypt(key, flag)
print(f'Ciphertext:\n{ciphertext.hex()}')
if __name__ == '__main__':
main()
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/Aero/2022/pwn/balloon/balloon.py | ctfs/Aero/2022/pwn/balloon/balloon.py | #!/usr/bin/env python3
import os
VERY_NICE = 1337
def execute(payload: str) -> object:
try:
return eval(payload)
except Exception as e:
return f'[-] {e}'
def main() -> None:
os.nice(VERY_NICE)
os.write(1, b'[*] Please, input a payload:\n> ')
payload = os.read(0, 512).decode()
os.close(0)
result = execute(payload)
print(result)
os._exit(0)
if __name__ == '__main__':
main()
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/Aero/2022/crypto/astronaut/astronaut.py | ctfs/Aero/2022/crypto/astronaut/astronaut.py | #!/usr/bin/env python3
import os
import random
from typing import List, Generator
def flight(galaxy: List[int], black_holes: List[int]) -> Generator[int, None, None]:
while True:
yield (
black_holes := black_holes[1:] + [
sum(x * y for x, y in zip(galaxy, black_holes))
]
)[0]
def main():
rnd = random.SystemRandom(1337)
limit = 1000
galaxy = [rnd.randrange(0, limit) for _ in range(16)]
black_holes = [rnd.randrange(0, limit) for _ in range(16)]
emotions = os.getenv('FLAG').strip()
emptiness = '\0' * 64
message = (emotions + emptiness).encode()
astronaut = flight(galaxy, black_holes)
for memory in message:
print(memory ^ next(astronaut) % limit, end = ' ')
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/Aero/2022/web/empathy/api/service/providers.py | ctfs/Aero/2022/web/empathy/api/service/providers.py | #!/usr/bin/env python3
import jwt
import typing
import models
import storages
class SessionProvider:
def __init__(self, users: storages.UserStorage, tokens: storages.TokenStorage):
self._users = users
self._tokens = tokens
async def create(self, credentials: models.Credentials) -> typing.Optional[models.User]:
obj = {
'username': credentials.username,
}
try:
session = jwt.encode(obj, credentials.password).decode()
except Exception:
return None
token = self._token(session)
await self._tokens.insert(token, credentials.username)
return models.User(
session=session,
username=obj['username'],
)
async def destroy(self, user: models.User) -> None:
token = self._token(user.session)
await self._tokens.delete(token)
async def validate(self, session: str) -> typing.Optional[models.User]:
token = self._token(session)
username = await self._tokens.search(token)
if username is None:
return await self.prolongate(session)
password = await self._users.search(username)
if password is None:
return None
try:
obj = jwt.decode(session, password)
except Exception:
return None
return models.User(
session=session,
username=obj['username'],
)
async def prolongate(self, session: str) -> typing.Optional[models.User]:
try:
obj = jwt.decode(session, verify=False)
except Exception:
return None
password = await self._users.search(obj['username'])
if password is None:
return None
try:
obj = jwt.decode(session, password)
except Exception:
return None
token = self._token(session)
await self._tokens.insert(token, obj['username'])
return models.User(
session=session,
username=obj['username'],
)
def _token(self, session: str) -> str:
return session.rsplit('.', 1)[-1]
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/Aero/2022/web/empathy/api/service/storages.py | ctfs/Aero/2022/web/empathy/api/service/storages.py | #!/usr/bin/env python3
import json
import typing
import aioredis
class AbstractStorage:
PREFIX: str = 'prefix'
EXPIRATION: int = 0 # seconds
def __init__(self, storage: aioredis.Redis):
self._storage = storage
async def search(self, key: str) -> typing.Optional[object]:
result = await self._storage.get(self._key(key))
if result is None:
return None
try:
return json.loads(result)
except Exception:
return None
async def insert(self, key: str, value: object) -> bool:
obj = json.dumps(value)
return await self._storage.set(
self._key(key), obj, self.EXPIRATION,
)
async def persist(self, key: str) -> None:
await self._storage.persist(self._key(key))
async def delete(self, key: str) -> None:
await self._storage.delete(self._key(key))
def _key(self, key: str) -> str:
return f'{self.PREFIX}_{key}'
class UserStorage(AbstractStorage):
PREFIX = 'users'
EXPIRATION = 30 * 60 # 30 minutes
class NoteStorage(AbstractStorage):
PREFIX = 'notes'
EXPIRATION = 30 * 60 # 30 minutes
class TokenStorage(AbstractStorage):
PREFIX = 'tokens'
EXPIRATION = 5 * 60 # 5 minutes
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/Aero/2022/web/empathy/api/service/models.py | ctfs/Aero/2022/web/empathy/api/service/models.py | #!/usr/bin/env python3
import pydantic
class User(pydantic.BaseModel):
session: str
username: str
class Note(pydantic.BaseModel):
id: str
text: str
title: str
author: str
class Credentials(pydantic.BaseModel):
username: str = pydantic.Field(..., min_length=5)
password: str = pydantic.Field(..., min_length=5)
class Description(pydantic.BaseModel):
text: str = pydantic.Field(..., min_length=10)
title: str = pydantic.Field(..., min_length=10)
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/Aero/2022/web/empathy/api/service/app.py | ctfs/Aero/2022/web/empathy/api/service/app.py | #!/usr/bin/env python3
import os
import secrets
import fastapi
import fastapi.responses
import aioredis
import models
import storages
import providers
app = fastapi.FastAPI()
redis = aioredis.Redis(host=os.getenv('REDIS_HOST'))
Notes = storages.NoteStorage(redis)
Users = storages.UserStorage(redis)
Tokens = storages.TokenStorage(redis)
Sessions = providers.SessionProvider(Users, Tokens)
async def UserRequired(session: str = fastapi.Cookie(None)) -> models.User:
if session is None:
raise fastapi.HTTPException(fastapi.status.HTTP_401_UNAUTHORIZED)
user = await Sessions.validate(session)
if user is None:
raise fastapi.HTTPException(fastapi.status.HTTP_401_UNAUTHORIZED)
return user
@app.get('/api/ping/')
async def ping(
response: fastapi.responses.JSONResponse,
):
return {
'response': 'pong',
}
@app.post('/api/login/')
async def login(
response: fastapi.responses.JSONResponse,
credentials: models.Credentials,
):
saved_password = await Users.search(credentials.username)
if saved_password is None:
if not await Users.insert(credentials.username, credentials.password):
raise fastapi.HTTPException(fastapi.status.HTTP_500_INTERNAL_SERVER_ERROR)
elif saved_password != credentials.password:
raise fastapi.HTTPException(fastapi.status.HTTP_400_BAD_REQUEST)
user = await Sessions.create(credentials)
if user is None:
raise fastapi.HTTPException(fastapi.status.HTTP_500_INTERNAL_SERVER_ERROR)
response.set_cookie('session', user.session)
return {
'username': user.username,
}
@app.get('/api/profile/')
async def profile(
response: fastapi.responses.JSONResponse,
user: models.User = fastapi.Depends(UserRequired),
):
return {
'username': user.username,
}
@app.post('/api/logout/')
async def logout(
response: fastapi.responses.JSONResponse,
user: models.User = fastapi.Depends(UserRequired),
):
await Sessions.destroy(user)
response.delete_cookie('session')
return {}
@app.post('/api/note/')
async def add_note(
response: fastapi.responses.JSONResponse,
description: models.Description,
user: models.User = fastapi.Depends(UserRequired),
):
tries = 16
for _ in range(tries):
note_id = secrets.token_hex(8)
if await Notes.search(note_id) is None:
break
else:
raise fastapi.HTTPException(fastapi.status.HTTP_500_INTERNAL_SERVER_ERROR)
note = models.Note(
id=note_id,
text=description.text,
title=description.title,
author=user.username,
)
if not await Notes.insert(note.id, note.dict()):
raise fastapi.HTTPException(fastapi.status.HTTP_500_INTERNAL_SERVER_ERROR)
return {
'id': note_id,
}
@app.get('/api/note/{note_id}/')
async def get_note(
response: fastapi.responses.JSONResponse,
note_id: str,
user: models.User = fastapi.Depends(UserRequired),
):
obj = await Notes.search(note_id)
if obj is None:
raise fastapi.HTTPException(fastapi.status.HTTP_404_NOT_FOUND)
note = models.Note.parse_obj(obj)
if note.author != user.username:
raise fastapi.HTTPException(fastapi.status.HTTP_403_FORBIDDEN)
return {
'text': note.text,
'title': note.title,
}
@app.on_event('startup')
async def put_flag():
flag = os.getenv('FLAG')
username = 'admin'
note = models.Note(
id='flagflagflagflag',
text=f'Good job! Here is your flag:\n{flag}',
title='A note with flag',
author=username,
)
await Users.insert(username, secrets.token_hex(8))
await Users.persist(username)
await Notes.insert(note.id, note.dict())
await Notes.persist(note.id)
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/ASIS/2021/Quals/pwn/V8_for_dummies_1/connect.py | ctfs/ASIS/2021/Quals/pwn/V8_for_dummies_1/connect.py | #!/usr/bin/python3
import sys
import os
import binascii
import re
import subprocess
import signal
def handler(x, y):
sys.exit(-1)
signal.signal(signal.SIGALRM, handler)
signal.alarm(30)
def gen_filename():
return '/tmp/' + binascii.hexlify(os.urandom(16)).decode('utf-8')
EOF = 'ASIS-CTF'
MAX_SIZE = 10000
def main():
print(f'Give me the source code(size < {MAX_SIZE}). EOF word is `{EOF}\'')
sys.stdout.flush()
size = 0
code = ''
while True:
s = sys.stdin.readline()
size += len(s)
if size > MAX_SIZE:
print('too long')
sys.stdout.flush()
return False
idx = s.find(EOF)
if idx < 0:
code += s
else:
code += s[:idx]
break
filename = gen_filename() + ".js"
with open(filename, 'w') as f:
f.write(code)
os.close(1)
os.close(2)
os.system(f'./run.sh {filename}')
main()
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/ASIS/2021/Quals/pwn/minimemo/pow.py | ctfs/ASIS/2021/Quals/pwn/minimemo/pow.py | """
i.e.
sha256("????v0iRhxH4SlrgoUd5Blu0") = b788094e2d021fa16f30c83346f3c80de5afab0840750a49a9254c2a73ed274c
Suffix: v0iRhxH4SlrgoUd5Blu0
Hash: b788094e2d021fa16f30c83346f3c80de5afab0840750a49a9254c2a73ed274c
"""
import itertools
import hashlib
import string
table = string.ascii_letters + string.digits + "._"
suffix = input("Suffix: ")
hashval = input("Hash: ")
for v in itertools.product(table, repeat=4):
if hashlib.sha256((''.join(v) + suffix).encode()).hexdigest() == hashval:
print("[+] Prefix = " + ''.join(v))
break
else:
print("[-] Solution not found :thinking_face:")
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/ASIS/2021/Quals/crypto/Warmup/Warmup.py | ctfs/ASIS/2021/Quals/crypto/Warmup/Warmup.py | #!/usr/bin/env python3
from Crypto.Util.number import *
import string
from secret import is_valid, flag
def random_str(l):
rstr = ''
for _ in range(l):
rstr += string.printable[:94][getRandomRange(0, 93)]
return rstr
def encrypt(msg, nbit):
l, p = len(msg), getPrime(nbit)
rstr = random_str(p - l)
msg += rstr
while True:
s = getRandomNBitInteger(1024)
if is_valid(s, p):
break
enc = msg[0]
for i in range(p-1):
enc += msg[pow(s, i, p)]
return enc
nbit = 15
enc = encrypt(flag, nbit)
print(f'enc = {enc}') | python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/ASIS/2021/Quals/crypto/LagLeg/LagLeg.py | ctfs/ASIS/2021/Quals/crypto/LagLeg/LagLeg.py | #!/usr/bin/env python3
from Crypto.Util.number import *
from gmpy import *
from math import gcd
from flag import flag
def lag(k, a, n):
s, t = 2, a
if k == 0:
return 2
r = 0
while k % 2 == 0:
r += 1
k //= 2
B = bin(k)[2:]
for b in B:
if b == '0':
t = (s * t - a) % n
s = (s **2 - 2) % n
else:
s = (s * t - a) % n
t = (t** 2 - 2) % n
for _ in range(r):
s = (s ** 2 - 2) % n
return s
def legkey(nbit):
while True:
r = getRandomNBitInteger(nbit >> 1)
s = getRandomNBitInteger(nbit >> 3)
p, q = r**5 + s, s + r
if isPrime(p) and isPrime(q):
while True:
a = getRandomRange(2, q)
if q*legendre(a, p) - p*legendre(a, q) == p - q:
return p, q, a
def keygen(p, q, a):
e = 65537
if gcd(e, p**2 - 1) * gcd(e, q**2 - 1) < e:
d = inverse(e, (p**2 - 1) * (q**2 - 1))
x = pow(d, e, n)
y = lag(x, a, p * q)
return e, y, d
def encrypt(m, n, a, y, e):
assert m < n
r = getRandomRange(2, n)
enc = (lag(r, a, n), (lag(r, y, n) + lag(e, m, n)) % n)
return enc
p, q, a = legkey(512)
n = p * q
e, y, d = keygen(p, q, a)
m = bytes_to_long(flag)
c = encrypt(m, n, a, y, e)
print(f'a = {a}')
print(f'n = {n}')
print(f'y = {y}')
print(f'C = {c}') | python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/ASIS/2021/Quals/crypto/madras/Madras.py | ctfs/ASIS/2021/Quals/crypto/madras/Madras.py | #!/usr/bin/env python3
from Crypto.Util.number import *
from flag import FLAG
def gentuple(nbit):
a, b, c = [getPrime(nbit // 3) for _ in '012']
return a, b, c
def encrypt(msg, params):
a, b, c = params
e, n = 65537, a * b * c
m = bytes_to_long(msg)
assert m < n
enc = pow(m, e, n)
return enc
nbit = 513
a, b, c = gentuple(nbit)
enc = encrypt(FLAG, (a, b, c))
print(f'a*b + c = {a*b + c}')
print(f'b*c + a = {b*c + a}')
print(f'c*a + b = {c*a + b}')
print(f'enc % a = {enc % a}')
print(f'enc % b = {enc % b}')
print(f'enc % c = {enc % c}')
print(f'enc = {enc}') | python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/ASIS/2021/Quals/web/phphphp/app/run.py | ctfs/ASIS/2021/Quals/web/phphphp/app/run.py | #!/usr/bin/env python3
import secrets
import os
import time
os.chdir("/app")
requestID = secrets.token_hex(16)
os.mkdir(f"./request/{requestID}")
pidPath = f"{os.getcwd()}/request/{requestID}/fpm.pid"
sockPath = f"{os.getcwd()}/request/{requestID}/fpm.sock"
confPath = f"{os.getcwd()}/request/{requestID}/php-fpm.conf"
phpfpmConf = f"""
[global]
pid = {pidPath}
error_log = syslog
[www]
listen = {sockPath}
pm = static
pm.max_children = 1
pm.process_idle_timeout = 3s;
""".strip()
confFile = open(confPath,"w")
confFile.write(phpfpmConf)
confFile.close()
os.system(f"timeout 2 php-fpm -F -y {confPath} -c ./php.ini 2>/dev/null 1>/dev/null &")
while(os.path.exists(sockPath) == False):
time.sleep(0.001)
os.system(f"timeout 2 ./app.py {sockPath}")
os.system(f"`sleep 3;rm -r ./request/{requestID}` 2>/dev/null >/dev/null &")
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/ASIS/2021/Quals/web/phphphp/app/FastCgiClient.py | ctfs/ASIS/2021/Quals/web/phphphp/app/FastCgiClient.py | import socket
import random
import argparse
import sys
from io import BytesIO
PY2 = True if sys.version_info.major == 2 else False
def bchr(i):
if PY2:
return force_bytes(chr(i))
else:
return bytes([i])
def bord(c):
if isinstance(c, int):
return c
else:
return ord(c)
def force_bytes(s):
if isinstance(s, bytes):
return s
else:
return s.encode('utf-8', 'strict')
def force_text(s):
if issubclass(type(s), str):
return s
if isinstance(s, bytes):
s = str(s, 'utf-8', 'strict')
else:
s = str(s)
return s
class FastCGIClient:
"""A Fast-CGI Client for Python"""
# private
__FCGI_VERSION = 1
__FCGI_ROLE_RESPONDER = 1
__FCGI_ROLE_AUTHORIZER = 2
__FCGI_ROLE_FILTER = 3
__FCGI_TYPE_BEGIN = 1
__FCGI_TYPE_ABORT = 2
__FCGI_TYPE_END = 3
__FCGI_TYPE_PARAMS = 4
__FCGI_TYPE_STDIN = 5
__FCGI_TYPE_STDOUT = 6
__FCGI_TYPE_STDERR = 7
__FCGI_TYPE_DATA = 8
__FCGI_TYPE_GETVALUES = 9
__FCGI_TYPE_GETVALUES_RESULT = 10
__FCGI_TYPE_UNKOWNTYPE = 11
__FCGI_HEADER_SIZE = 8
# request state
FCGI_STATE_SEND = 1
FCGI_STATE_ERROR = 2
FCGI_STATE_SUCCESS = 3
def __init__(self,sockPath):
self.sockPath = sockPath
self.timeout = 3000
self.keepalive = 0
self.sock = None
self.requests = dict()
def __connect(self):
self.sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
self.sock.settimeout(self.timeout)
self.sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
try:
self.sock.connect(self.sockPath)
except socket.error as msg:
self.sock.close()
self.sock = None
print(repr(msg))
return False
return True
def __encodeFastCGIRecord(self, fcgi_type, content, requestid):
length = len(content)
buf = bchr(FastCGIClient.__FCGI_VERSION) \
+ bchr(fcgi_type) \
+ bchr((requestid >> 8) & 0xFF) \
+ bchr(requestid & 0xFF) \
+ bchr((length >> 8) & 0xFF) \
+ bchr(length & 0xFF) \
+ bchr(0) \
+ bchr(0) \
+ content
return buf
def __encodeNameValueParams(self, name, value):
nLen = len(name)
vLen = len(value)
record = b''
if nLen < 128:
record += bchr(nLen)
else:
record += bchr((nLen >> 24) | 0x80) \
+ bchr((nLen >> 16) & 0xFF) \
+ bchr((nLen >> 8) & 0xFF) \
+ bchr(nLen & 0xFF)
if vLen < 128:
record += bchr(vLen)
else:
record += bchr((vLen >> 24) | 0x80) \
+ bchr((vLen >> 16) & 0xFF) \
+ bchr((vLen >> 8) & 0xFF) \
+ bchr(vLen & 0xFF)
return record + name + value
def __decodeFastCGIHeader(self, stream):
header = dict()
header['version'] = bord(stream[0])
header['type'] = bord(stream[1])
header['requestId'] = (bord(stream[2]) << 8) + bord(stream[3])
header['contentLength'] = (bord(stream[4]) << 8) + bord(stream[5])
header['paddingLength'] = bord(stream[6])
header['reserved'] = bord(stream[7])
return header
def __decodeFastCGIRecord(self, buffer):
header = buffer.read(int(self.__FCGI_HEADER_SIZE))
if not header:
return False
else:
record = self.__decodeFastCGIHeader(header)
record['content'] = b''
if 'contentLength' in record.keys():
contentLength = int(record['contentLength'])
record['content'] += buffer.read(contentLength)
if 'paddingLength' in record.keys():
skiped = buffer.read(int(record['paddingLength']))
return record
def request(self, nameValuePairs={}, post=''):
if not self.__connect():
print('connect failure! please check your fasctcgi-server !!')
return
requestId = random.randint(1, (1 << 16) - 1)
self.requests[requestId] = dict()
request = b""
beginFCGIRecordContent = bchr(0) \
+ bchr(FastCGIClient.__FCGI_ROLE_RESPONDER) \
+ bchr(self.keepalive) \
+ bchr(0) * 5
request += self.__encodeFastCGIRecord(FastCGIClient.__FCGI_TYPE_BEGIN,
beginFCGIRecordContent, requestId)
paramsRecord = b''
if nameValuePairs:
for (name, value) in nameValuePairs.items():
name = force_bytes(name)
value = force_bytes(value)
paramsRecord += self.__encodeNameValueParams(name, value)
if paramsRecord:
request += self.__encodeFastCGIRecord(FastCGIClient.__FCGI_TYPE_PARAMS, paramsRecord, requestId)
request += self.__encodeFastCGIRecord(FastCGIClient.__FCGI_TYPE_PARAMS, b'', requestId)
if post:
request += self.__encodeFastCGIRecord(FastCGIClient.__FCGI_TYPE_STDIN, force_bytes(post), requestId)
request += self.__encodeFastCGIRecord(FastCGIClient.__FCGI_TYPE_STDIN, b'', requestId)
self.sock.sendall(request)
self.requests[requestId]['state'] = FastCGIClient.FCGI_STATE_SEND
self.requests[requestId]['response'] = b''
return self.__waitForResponse(requestId)
def __waitForResponse(self, requestId):
data = b''
while True:
buf = self.sock.recv(512)
if not len(buf):
break
data += buf
data = BytesIO(data)
while True:
response = self.__decodeFastCGIRecord(data)
if not response:
break
if response['type'] == FastCGIClient.__FCGI_TYPE_STDOUT \
or response['type'] == FastCGIClient.__FCGI_TYPE_STDERR:
if response['type'] == FastCGIClient.__FCGI_TYPE_STDERR:
self.requests['state'] = FastCGIClient.FCGI_STATE_ERROR
if requestId == int(response['requestId']):
self.requests[requestId]['response'] += response['content']
if response['type'] == FastCGIClient.FCGI_STATE_SUCCESS:
self.requests[requestId]
return self.requests[requestId]['response']
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/ASIS/2021/Quals/web/phphphp/app/app.py | ctfs/ASIS/2021/Quals/web/phphphp/app/app.py | #!/usr/bin/python3
import sys
import time
import FastCgiClient
import re
from os import path,environ,getcwd
readCounter = 0
statusCodeDescs = {
200 : "OK",
405 : "Method Not Allowed",
400 : "Bad request",
412 : "Payload Too Large"
}
def sendResponse(html,statusCode):
buf = ""
buf+= f"HTTP/1.1 {statusCode} {statusCodeDescs[statusCode]}\r\n"
buf+= f"Content-Length: {len(html)}\r\n"
buf+= f"Content-Type: text/plain\r\n"
buf+= f"\r\n"
buf+= html
print(buf,end="")
exit()
def readn(n):
global readCounter
readed = 0
buf = ""
while(len(buf) != n):
readedChr = sys.stdin.read(1)
buf += readedChr
if(readedChr == ""):
time.sleep(0.01)
readCounter += len(buf)
if(readCounter > 1000):
sendResponse("HTTP request too big.",412)
return buf
def readMethod():
method = readn(3)
if(method != "GET"):
sendResponse("Method not allowed.",405)
return method
def readURL():
url = ""
readn(1)
while(True):
readedChar = readn(1)
if(readedChar == " "):
break
url += readedChar
if( len(url) == 0 or len(url) > 200):
sendResponse("Bad request.",400)
return url
def readHTTPVersion():
HTTPVersion = ""
buf = ""
while(True):
buf += readn(1)
if(buf[-2:] == "\r\n"):
break
HTTPVersion = buf[:-2]
if(HTTPVersion != "HTTP/1.1"):
sendResponse("Bad request.",400)
return HTTPVersion
def readHeaders():
headers = []
end = False
while(True):
headerName = ""
headerValue = ""
while(True):
readedChar = readn(1)
if(readedChar == ":"):
break
headerName += readedChar
if(headerName == "\r\n"):
end = True
break
if(end == True):
break
buf = ""
while(True):
buf += readn(1)
if(buf[-2:] == "\r\n"):
break
headerValue = buf[:-2]
headers.append((re.sub(r'[^A-Z0-9_]', "", headerName.strip().upper().replace("-","_")),headerValue.strip()))
return headers
if(__name__ == '__main__'):
method = readMethod()
url = readURL()
protocol = readHTTPVersion()
headers = readHeaders()
query_string = ""
path_info = ""
script_filename = ""
script_name = ""
document_root = f"{getcwd()}/host/default"
if("?" in url):
query_string = url[url.index("?")+1:]
url = url[:url.index("?")]
if(".php" not in url):
url = "/index.php"
phpExtIdx = url.index(".php")
script_name = url[:phpExtIdx+4]
path_info = url[phpExtIdx+4:]
hostHeader = ""
for header in headers:
if(header[0] == "HOST"):
hostHeader = header[1]
#Virtual host support!
if(path.isdir(path.normpath(f"{getcwd()}/host/{hostHeader}"))):
document_root = f"{getcwd()}/host/{hostHeader}"
script_filename = path.normpath(document_root+script_name)
params = {
'GATEWAY_INTERFACE': 'FastCGI/1.0',
'REQUEST_METHOD': method,
'SCRIPT_FILENAME': script_filename,
'SCRIPT_NAME': script_name,
'QUERY_STRING': query_string,
'REQUEST_URI': url,
'DOCUMENT_ROOT': document_root,
'SERVER_PROTOCOL': protocol,
'SERVER_SOFTWARE': 'mws',
'REMOTE_ADDR': environ["REMOTE_HOST"],
'SERVER_NAME': "mws",
'CONTENT_TYPE': "",
'CONTENT_LENGTH': "",
}
for header in headers:
if("PROXY" not in header[0] and "LENGTH" not in header[0]):
params[f"HTTP_{header[0]}"] = header[1]
client = FastCgiClient.FastCGIClient(sys.argv[1])
response = client.request(params, "")
sendResponse(response[response.index(b"\r\n\r\n")+4:].decode('utf-8'),200)
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/ASIS/2021/Finals/crypto/RAS/ras.py | ctfs/ASIS/2021/Finals/crypto/RAS/ras.py | #!/usr/bin/env python3
from Crypto.Util.number import *
from flag import flag
def genparam(nbit):
while True:
a, b = getRandomRange(2, nbit), getRandomRange(32, nbit)
if (a ** b).bit_length() == nbit:
return a ** b
def genkey(nbit):
p, q = [_ + (_ % 2) for _ in [genparam(nbit) for _ in '01']]
while True:
P = p + getPrime(31)
if isPrime(P):
while True:
Q = q + getPrime(37)
if isPrime(Q):
return P, Q
def encrypt(m, pubkey):
e = 0x10001
assert m < pubkey
c = pow(m, e, pubkey)
return c
nbit = 512
P, Q = genkey(nbit)
pubkey = P * Q
flag = bytes_to_long(flag)
enc = encrypt(flag, pubkey)
print(f'pubkey = {pubkey}')
print(f'enc = {enc}') | python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/ASIS/2023/Quals/pwn/night_js/stuff/run.py | ctfs/ASIS/2023/Quals/pwn/night_js/stuff/run.py | #!/usr/bin/env python3
import tempfile
import pathlib
import os
os.chdir(pathlib.Path(__file__).parent.resolve())
with tempfile.NamedTemporaryFile() as tmp:
print('Send the file: (ended with "\\n-- EOF --\\n"):')
s = input()
while(s != '-- EOF --'):
tmp.write((s+'\n').encode())
s = input()
tmp.flush()
os.close(0)
os.system('LD_LIBRARY_PATH=/libjs/ timeout 3 ./js ' + tmp.name)
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/ASIS/2023/Quals/crypto/Bruce_Lee/bruce_lee.py | ctfs/ASIS/2023/Quals/crypto/Bruce_Lee/bruce_lee.py | #!/usr/bin/env python3
from Crypto.Util.number import *
from gmpy2 import *
from flag import flag
def gen_prime(nbit, density):
while True:
rar = [2 ** getRandomRange(1, nbit - 1) for _ in range(density)]
p = sum(rar) + 2**(nbit - 1) + 2**(nbit - 2) + 1
if isPrime(p):
return p
nbit, density = 1024, getRandomRange(63, 114)
p, q = [gen_prime(nbit, density) for _ in '01']
e = next_prime(p ^ q + 2**density + 1)
pkey = [e, p * q]
def encrypt(m, pkey):
e, n = pkey
c = pow(m, e, n)
return c
m = bytes_to_long(flag)
c = encrypt(m, pkey)
print(f'n = {p * q}')
print(f'c = {c}') | python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/ASIS/2023/Quals/crypto/Crand_all/Crand_all.py | ctfs/ASIS/2023/Quals/crypto/Crand_all/Crand_all.py | #!/usr/bin/env python3
from Crypto.Util.number import *
from flag import flag
def gen_prime(nbit):
while True:
p = 0
for i in range(nbit, nbit>>1, -1):
p += getRandomRange(0, 2) * 2 ** i
p += getRandomNBitInteger(nbit>>3)
if isPrime(p):
return p
nbit = 512
p, q, r = [gen_prime(nbit) for _ in '012']
e, n = 65537, p * q * r
m = bytes_to_long(flag)
c = pow(m, e, n)
print(f'n = {n}')
print(f'c = {c}') | python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/ASIS/2023/Quals/crypto/Cognitive/cognitive.py | ctfs/ASIS/2023/Quals/crypto/Cognitive/cognitive.py | #!/usr/bin/env python3
from Crypto.Util.number import *
from random import *
from os import urandom
from flag import flag
hubbub = 3
def mulvec(columns, vec):
c = len(columns)
assert(c == len(vec))
r = len(columns[0])
result = [0 for _ in range(r)]
for i, bit in zip(range(c), vec):
assert(len(columns[i]) == r)
if bit == 1:
for _ in range(r):
result[_] ^= columns[i][_]
return result
def barbyte(bar):
l = len(bar)
bar = ''.join([str(_) for _ in bar])
bar = int(bar, 2)
b = long_to_bytes(bar)
while True:
if len(b) < l // 8:
b = b'\x00' + b
else:
break
return b
def bytebar(bytes):
i = bytes_to_long(bytes)
vec = [int(_) for _ in bin(i)[2:].zfill(len(bytes) * 8)]
return vec
class cognitivenc(object):
@classmethod
def new(cls, nbit = 48):
key = cls.keygen(nbit)
return cls(key)
def __init__(self, key):
self.key = key
self.keylen = len(self.key)
self.random = SystemRandom()
@classmethod
def keygen(cls, nbit):
key = SystemRandom().getrandbits(nbit)
key = bin(key)[2:].zfill(nbit)
return [int(_) for _ in key]
def encode(self, msg):
l = len(msg)
msg = bytes_to_long(msg)
m = bin(msg)[2:].zfill(8 * l)
m = [int(_) for _ in m]
result = [0 for _ in range(self.keylen)]
for i, b in enumerate(m):
result[3*i + 0] = b
result[3*i + 1] = b
result[3*i + 2] = b
return result
def encrypt(self, msg):
msg = self.encode(msg)
l = len(msg)
columns = []
for _ in range(self.keylen):
col = [int(_) for _ in bin(SystemRandom().getrandbits(self.keylen))[2:].zfill(self.keylen)]
columns.append(col)
y = mulvec(columns, self.key)
y = [y[_] ^ msg[_] for _ in range(l)]
for i in range(self.keylen // 3):
idx = self.random.randrange(hubbub)
y[3*i + idx] ^= 1
columns = [barbyte(c) for c in columns]
columns = b''.join(columns)
return columns + barbyte(y)
def main():
cipher = cognitivenc.new()
random = SystemRandom()
for _ in range(3117):
pt = urandom(2)
ct = cipher.encrypt(pt)
fp = open("./output/ptext_{:04d}".format(_), "wb")
fc = open("./output/ctext_{:04d}".format(_), "wb")
fp.write(pt)
fc.write(ct)
enc = []
for _ in range(len(flag) // 2):
enc.append(cipher.encrypt(flag[_*2:_*2 + 2]))
for _, ct in enumerate(enc):
fe = open("./output/flag_{:02d}".format(_), "wb")
fe.write(ct)
if len(flag) % 2 != 0: flag += b'+'
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/ASIS/2023/Quals/crypto/Refactor/refactor.py | ctfs/ASIS/2023/Quals/crypto/Refactor/refactor.py | #!/usr/bin/env python3
from Crypto.Util.number import *
from flag import flag
def pgen(nbit):
x, y = 0, 1
while True:
u, v = getRandomRange(1, 110), getRandomRange(1, 313)
x, y = u * x + 31337 * v * y, v * x - u * y
if x.bit_length() <= nbit // 2 and x.bit_length() <= nbit // 2:
p = x**2 + 31337 * y**2 | 1
if isPrime(p) and p.bit_length() >= nbit:
return p
else:
x, y = 0, 1
def encrypt(msg, pkey):
e, n = pkey
m = bytes_to_long(msg)
c = pow(m, e, n)
return c
p, q = [pgen(1024) for _ in '__']
pkey = (31337, p * q)
c = encrypt(flag, pkey)
print(f'n = {p * q}')
print(f'c = {c}') | python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/ASIS/2023/Quals/crypto/Renamiara/renamiara.py | ctfs/ASIS/2023/Quals/crypto/Renamiara/renamiara.py | #!/usr/bin/env python3
from Crypto.Util.number import *
import sys
from flag import flag
def die(*args):
pr(*args)
quit()
def pr(*args):
s = " ".join(map(str, args))
sys.stdout.write(s + "\n")
sys.stdout.flush()
def sc():
return sys.stdin.buffer.readline()
def main():
border = "|"
pr(border*72)
pr(border, " Greetings and welcome to the Renamiara cryptography challenge! The ", border)
pr(border, " objective of this mission is to tackle an exceptionally difficult ", border)
pr(border, " and unique discrete logarithm problem in the real world. Are you ", border)
pr(border, " prepared and willing to take on this challenge? [Y]es or [N]o? ", border)
pr(border*72)
ans = sc().decode().strip().lower()
if ans == 'y':
NBIT = 32
STEP = 40
pr(border, "In each step solve the given equation and send the solution for x, y", border)
c = 1
while c <= STEP:
nbit = NBIT * c
p = getPrime(nbit)
pr(border, f'p = {p}')
pr(border, 'First send the base g: ')
g = sc().strip().decode()
pr(border, 'Send the solutions for pow(g, x + y, p) = x * y, as x and y:')
xy = sc().strip().decode().split(',')
try:
g, x, y = [int(_) for _ in [g] + xy]
except:
die(border, 'Given number is not correct! Bye!!')
if (x >= p-1 or x <= 1) or (y >= p-1 or y <= 1) or x == y:
die(border, "Kidding me!? Your solutions must be smaller than p-1 and x ≠ y :(")
if g <= 2**24 or g >= p-1:
die(border, "Kidding me!? Please send the correct base :P")
if pow(g, x + y, p) == x * y % p:
if c == STEP:
die(border, f"Congratulation! the flag is: {flag}")
else:
pr(border, "Good job, try to solve the next level!")
c += 1
else:
die(border, "Try harder and be smarter to find the solution!!")
elif ans == 'n':
pr(border, 'Bye!!')
else:
pr(border, 'Please send a valid answer! Bye!!')
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/ASIS/2023/Finals/pwn/Backdooredness/env/stuff/run.py | ctfs/ASIS/2023/Finals/pwn/Backdooredness/env/stuff/run.py | #!/usr/bin/env python3
import tempfile
import pathlib
import os
import re
import json
import time
if not os.path.exists('/tmp/ips.json'):
f = open('/tmp/ips.json','w')
f.write('{}')
f.close()
ipFile = open('/tmp/ips.json','r+')
peerIp = os.environ['SOCAT_PEERADDR']
ips = {}
ips = json.loads(ipFile.read())
if(peerIp in ips):
if(time.time() > ips[peerIp]):
ips[peerIp] = int(time.time())+5
else:
print('one try every 5 seconds')
exit(0)
else:
ips[peerIp] = int(time.time())+5
ipFile.seek(0)
ipFile.write(json.dumps(ips))
ipFile.close()
os.system('chmod 000 /proc/')
os.setgid(1000)
os.setuid(1000)
os.chdir(pathlib.Path(__file__).parent.resolve())
with tempfile.NamedTemporaryFile() as tmp:
print('Send your hex-encoded ROM:')
tmp.write(bytes.fromhex(input()))
tmp.flush()
os.close(0)
os.system('timeout 3 xvfb-run -a ./libs/ld-linux-x86-64.so.2 --library-path ./libs ./SimpleNES ' + tmp.name)
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/ASIS/2023/Finals/pwn/isWebP.js/env/stuff/run.py | ctfs/ASIS/2023/Finals/pwn/isWebP.js/env/stuff/run.py | #!/usr/bin/env python3
import tempfile
import pathlib
import os
import re
import json
import time
import signal
if not os.path.exists('/tmp/ips.json'):
f = open('/tmp/ips.json','w')
f.write('{}')
f.close()
ipFile = open('/tmp/ips.json','r+')
peerIp = os.environ['SOCAT_PEERADDR']
ips = {}
ips = json.loads(ipFile.read())
if(peerIp in ips):
if(time.time() > ips[peerIp]):
ips[peerIp] = int(time.time())+5
else:
print('one try every 5 seconds')
exit(0)
else:
ips[peerIp] = int(time.time())+5
ipFile.seek(0)
ipFile.write(json.dumps(ips))
ipFile.close()
os.chdir(pathlib.Path(__file__).parent.resolve())
signal.alarm(10)
os.setgid(1000)
os.setuid(1000)
with tempfile.NamedTemporaryFile() as tmp:
print('Send the file: (ended with "\\n-- EOF --\\n"):')
s = input()
while(s != '-- EOF --' and len(s) < 1024*1024):
tmp.write((s+'\n').encode())
s = input()
tmp.flush()
os.close(0)
os.system('timeout 3 ./qjs ' + tmp.name)
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/ASIS/2023/Finals/crypto/Larisa/larisa.py | ctfs/ASIS/2023/Finals/crypto/Larisa/larisa.py | #!/usr/bin/env sage
from Crypto.Util.number import *
from flag import flag
def next_prime(r):
while True:
if isPrime(r):
return r
r += 1
def keygen(nbit):
p = getPrime(nbit // 2)
P, Q = [next_prime(p * getPrime(nbit // 2 - 10)) for _ in '01']
n, K = P * Q, 2 ** (nbit >> 1)
u, y = getRandomRange(1, n), getRandomRange(1, K)
v = - (p + u * y) % n
pkey = (u, v, n)
skey = (y, P, Q)
return pkey, skey
def encrypt(msg, pkey):
u, v, n = pkey
m = bytes_to_long(msg)
assert m < n
m0 = (u*m - v) % n
while True:
if isPrime(u + v):
break
else:
u += 1
e = u + v
c = pow(m0, e, n)
return c
nbit = 1024
pkey, skey = keygen(nbit)
u, v, n = pkey
c = encrypt(flag, pkey)
print(f'u = {u}')
print(f'v = {v}')
print(f'n = {n}')
print(f'c = {c}') | python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/ASIS/2023/Finals/crypto/M7P/m7p.py | ctfs/ASIS/2023/Finals/crypto/M7P/m7p.py | #!/usr/bin/env python3
import os
from hashlib import *
from binascii import *
from Crypto.Cipher import AES
from Crypto.Util.number import *
from flag import flag
def next_prime(n):
while True:
if isPrime(n):
return n
n += 1
def find(s, ch):
return [i for i, ltr in enumerate(ch) if ltr == s]
def worth(c, msg):
assert len(c) == 1
w = 0
if c in msg:
a = find(c, msg)
w += sum([(_ + 1)**_ - _ for _ in a])
return w
def xor(mm, ym):
xm = []
for i in range(len(mm)):
xm.append(mm[i] ^ ym[i])
return bytes(xm)
def taft(key, otp):
assert len(key) == len(otp)
T = []
for _ in range(len(key)):
__ = xor(key, otp)
T.append(hexlify(__))
otp = sha1(otp).hexdigest().encode()
return T
def gaz(T):
G = []
for t in T:
R = []
for c in range(16):
R.append(worth(hex(c)[2:], t.decode()))
p = next_prime(sum(R))
a = getPrime(p.bit_length() >> 3)
R = [r * a % p for r in R]
G.append(R)
return G
def lili(gz, s):
i, L = 0, []
for g in gz:
s_i = bin(bytes_to_long(s[2*i:2*i + 2]))[2:].zfill(16)
L.append(sum([g[_] * int(s_i[_]) for _ in range(16)]))
i += 1
return L
def encrypt(msg, key):
cipher = AES.new(key, AES.MODE_GCM)
enc, tag = cipher.encrypt_and_digest(msg)
return (enc, cipher.nonce, tag)
some = os.urandom(40)
good = os.urandom(40)
keys = os.urandom(80)
T = taft(some, good)
G = gaz(T)
L = lili(G, keys)
mask = xor(flag, sha512(keys).digest()[:len(flag)])
enc = encrypt(mask, sha256(some).digest())
print(f'G = {G}')
print(f'L = {L}')
print("c = ", *enc, sep = "") | python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/ASIS/2023/Finals/web/Pupptear/deploy.py | ctfs/ASIS/2023/Finals/web/Pupptear/deploy.py | #!/usr/bin/env python3
# socat TCP-LISTEN:2323,reuseaddr,fork EXEC:"./deploy.py"
import tempfile
import pathlib
import os
import string
import time
import random
import atexit
import json
import re
if not os.path.exists('/tmp/ips.json'):
f = open('/tmp/ips.json','w')
f.write('{}')
f.close()
ipFile = open('/tmp/ips.json','r+')
peerIp = os.environ['SOCAT_PEERADDR']
ips = {}
ips = json.loads(ipFile.read())
if(peerIp in ips):
if(time.time() > ips[peerIp]):
ips[peerIp] = int(time.time())+30
else:
print('one try each 30 seconds')
exit(0)
else:
ips[peerIp] = int(time.time())+30
ipFile.seek(0)
ipFile.write(json.dumps(ips))
ipFile.close()
os.chdir(pathlib.Path(__file__).parent.resolve())
url = input('input URL (b64ed): ')
if(not re.match('^[A-Za-z0-9=+/]+$',url)):
print('bad URL')
exit(1)
os.close(0)
os.close(1)
os.close(2)
containerName = ''.join(random.choice(string.ascii_uppercase + string.digits) for _ in range(0x10))
os.system(f'bash -c "sleep 5 && docker kill {containerName} 2>/dev/null" &')
os.system(f'docker run --name {containerName} pupptear bash -c \'/ASIS*/index.js {url}\' ')
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/ASIS/2023/Finals/web/phphphphphp/deploy.py | ctfs/ASIS/2023/Finals/web/phphphphphp/deploy.py | #!/usr/bin/env python3
# socat TCP-LISTEN:2323,reuseaddr,fork EXEC:"./deploy.py"
import tempfile
import pathlib
import os
import string
import time
import random
import atexit
import json
if not os.path.exists('/tmp/ips.json'):
f = open('/tmp/ips.json','w')
f.write('{}')
f.close()
ipFile = open('/tmp/ips.json','r+')
peerIp = os.environ['SOCAT_PEERADDR']
ips = {}
ips = json.loads(ipFile.read())
if(peerIp in ips):
if(time.time() > ips[peerIp]):
ips[peerIp] = int(time.time())+30
else:
print('one try every 30 seconds')
exit(0)
else:
ips[peerIp] = int(time.time())+30
ipFile.seek(0)
ipFile.write(json.dumps(ips))
ipFile.close()
os.chdir(pathlib.Path(__file__).parent.resolve())
tempdir = tempfile.TemporaryDirectory()
tempdirName = tempdir.name
atexit.register(lambda:tempdir.cleanup())
with open(f'{tempdir.name}/payload.php','wb') as tmp:
buf = b''
n = int(input('Length: '))
if(n > 1024*1024): exit();
while(len(buf) != n):
buf += os.read(0,1)
buf = buf[:n]
tmp.write(buf)
os.chmod(f'{tempdirName}',0o555)
os.chmod(f'{tempdirName}/payload.php',0o555)
containerName = ''.join(random.choice(string.ascii_uppercase + string.digits) for _ in range(0x10))
os.system(f'bash -c "sleep 5 && docker kill {containerName} 2>/dev/null" &')
os.system(f'docker run --name {containerName} --network=none --cpus=1 -m 128mb -v {tempdirName}:/var/www/sbx:ro -v `pwd`/flag.txt:/flag.txt:ro -v `pwd`/php.ini:/etc/php.ini:ro --rm -t php@sha256:2ae8a4334536e4503d6e8c30885bf68dc4b169febaf42a351fdf68ca7aca2b8d php -n -c /etc/php.ini /var/www/sbx/payload.php')
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/ASIS/2022/Quals/pwn/readable/deploy.py | ctfs/ASIS/2022/Quals/pwn/readable/deploy.py | #!/usr/bin/env python3
# socat TCP-LISTEN:2323,reuseaddr,fork EXEC:"./deploy.py"
import tempfile
import pathlib
import os
import string
import time
import random
import json
if not os.path.exists('/tmp/ips.json'):
f = open('/tmp/ips.json','w')
f.write('{}')
f.close()
ipFile = open('/tmp/ips.json','r+')
peerIp = os.environ['SOCAT_PEERADDR']
ips = {}
ips = json.loads(ipFile.read())
if(peerIp in ips):
if(time.time() > ips[peerIp]):
ips[peerIp] = int(time.time())+30
else:
print('one try each 30 seconds')
exit(0)
else:
ips[peerIp] = int(time.time())+30
ipFile.seek(0)
ipFile.write(json.dumps(ips))
ipFile.close()
os.chdir(pathlib.Path(__file__).parent.resolve())
fname = None
with tempfile.NamedTemporaryFile(delete=False) as tmp:
buf = b''
n = int(input('Length: '))
while(len(buf) != n):
buf += os.read(0,0x1000)
buf = buf[:n]
tmp.write(buf)
tmp.close()
fname = tmp.name
os.chmod(fname,0o555)
containerName = ''.join(random.choice(string.ascii_uppercase + string.digits) for _ in range(0x10))
os.system(f'bash -c "sleep 5 && docker kill {containerName} 2>/dev/null" &')
os.system(f'docker run --name {containerName} --privileged --network=none -i --rm -v {fname}:/tmp/exploit readable')
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/ASIS/2022/Quals/pwn/jsy/stuff/run.py | ctfs/ASIS/2022/Quals/pwn/jsy/stuff/run.py | #!/usr/bin/env python3
import tempfile
import pathlib
import os
os.chdir(pathlib.Path(__file__).parent.resolve())
with tempfile.NamedTemporaryFile() as tmp:
print('Send the file: (ended with "\\n-- EOF --\\n"):')
s = input()
while(s != '-- EOF --'):
tmp.write((s+'\n').encode())
s = input()
tmp.flush()
os.close(0)
os.system('./mujs ' + tmp.name)
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/ASIS/2022/Quals/pwn/jsy/source/original/genucd.py | ctfs/ASIS/2022/Quals/pwn/jsy/source/original/genucd.py | # Create utfdata.h from UnicodeData.txt
tolower = []
toupper = []
isalpha = []
for line in open("UnicodeData.txt").readlines():
line = line.split(";")
code = int(line[0],16)
# if code > 65535: continue # skip non-BMP codepoints
if line[2][0] == 'L':
isalpha.append(code)
if line[12]:
toupper.append((code,int(line[12],16)))
if line[13]:
tolower.append((code,int(line[13],16)))
def dumpalpha():
table = []
prev = 0
start = 0
for code in isalpha:
if code != prev+1:
if start:
table.append((start,prev))
start = code
prev = code
table.append((start,prev))
print("")
print("static const Rune ucd_alpha2[] = {")
for a, b in table:
if b - a > 0:
print(hex(a)+","+hex(b)+",")
print("};");
print("")
print("static const Rune ucd_alpha1[] = {")
for a, b in table:
if b - a == 0:
print(hex(a)+",")
print("};");
def dumpmap(name, input):
table = []
prev_a = 0
prev_b = 0
start_a = 0
start_b = 0
for a, b in input:
if a != prev_a+1 or b != prev_b+1:
if start_a:
table.append((start_a,prev_a,start_b))
start_a = a
start_b = b
prev_a = a
prev_b = b
table.append((start_a,prev_a,start_b))
print("")
print("static const Rune " + name + "2[] = {")
for a, b, n in table:
if b - a > 0:
print(hex(a)+","+hex(b)+","+str(n-a)+",")
print("};");
print("")
print("static const Rune " + name + "1[] = {")
for a, b, n in table:
if b - a == 0:
print(hex(a)+","+str(n-a)+",")
print("};");
print("/* This file was automatically created from UnicodeData.txt */")
dumpalpha()
dumpmap("ucd_tolower", tolower)
dumpmap("ucd_toupper", toupper)
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/ASIS/2022/Quals/pwn/jsy/source/challenge/genucd.py | ctfs/ASIS/2022/Quals/pwn/jsy/source/challenge/genucd.py | # Create utfdata.h from UnicodeData.txt
tolower = []
toupper = []
isalpha = []
for line in open("UnicodeData.txt").readlines():
line = line.split(";")
code = int(line[0],16)
# if code > 65535: continue # skip non-BMP codepoints
if line[2][0] == 'L':
isalpha.append(code)
if line[12]:
toupper.append((code,int(line[12],16)))
if line[13]:
tolower.append((code,int(line[13],16)))
def dumpalpha():
table = []
prev = 0
start = 0
for code in isalpha:
if code != prev+1:
if start:
table.append((start,prev))
start = code
prev = code
table.append((start,prev))
print("")
print("static const Rune ucd_alpha2[] = {")
for a, b in table:
if b - a > 0:
print(hex(a)+","+hex(b)+",")
print("};");
print("")
print("static const Rune ucd_alpha1[] = {")
for a, b in table:
if b - a == 0:
print(hex(a)+",")
print("};");
def dumpmap(name, input):
table = []
prev_a = 0
prev_b = 0
start_a = 0
start_b = 0
for a, b in input:
if a != prev_a+1 or b != prev_b+1:
if start_a:
table.append((start_a,prev_a,start_b))
start_a = a
start_b = b
prev_a = a
prev_b = b
table.append((start_a,prev_a,start_b))
print("")
print("static const Rune " + name + "2[] = {")
for a, b, n in table:
if b - a > 0:
print(hex(a)+","+hex(b)+","+str(n-a)+",")
print("};");
print("")
print("static const Rune " + name + "1[] = {")
for a, b, n in table:
if b - a == 0:
print(hex(a)+","+str(n-a)+",")
print("};");
print("/* This file was automatically created from UnicodeData.txt */")
dumpalpha()
dumpmap("ucd_tolower", tolower)
dumpmap("ucd_toupper", toupper)
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/ASIS/2022/Quals/crypto/mariana/mariana.py | ctfs/ASIS/2022/Quals/crypto/mariana/mariana.py | #!/usr/bin/env python3
from Crypto.Util.number import *
import sys
from flag import flag
def die(*args):
pr(*args)
quit()
def pr(*args):
s = " ".join(map(str, args))
sys.stdout.write(s + "\n")
sys.stdout.flush()
def sc():
return sys.stdin.buffer.readline()
def main():
border = "|"
pr(border*72)
pr(border, "Welcome to MARIANA cryptography battle, the mission is solving super", border)
pr(border, "hard special DLP problem in real world, are you ready to fight? ", border)
pr(border*72)
NBIT = 32
STEP = 40
pr(border, "In each step solve the given equation and send the solution for x. ", border)
c = 1
while c <= STEP:
nbit = NBIT * c
p = getPrime(nbit)
g = getRandomRange(3, p)
pr(border, f'p = {p}')
pr(border, f'g = {g}')
pr(border, 'Send the solution x = ')
ans = sc()
try:
x = int(ans)
except:
die(border, 'Given number is not integer!')
if x >= p:
die(border, "Kidding me!? Your solution must be smaller than p :P")
if (pow(g, x, p) - x) % p == 0:
if c == STEP:
die(border, f"Congratz! the flag is: {flag}")
else:
pr(border, "Good job, try to solve the next level!")
c += 1
else:
die(border, "Try harder and smarter to find the solution!")
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/ASIS/2022/Quals/crypto/mindseat_updated/mindseat_updated.py | ctfs/ASIS/2022/Quals/crypto/mindseat_updated/mindseat_updated.py | #!/usr/bin/env python3
from Crypto.Util.number import *
from secret import params, flag
def keygen(nbit, k): # Pubkey function
_p = 1
while True:
p, q = [_p + (getRandomNBitInteger(nbit - k) << k) for _ in '01']
if isPrime(p) and isPrime(q):
while True:
s = getRandomRange(2, p * q)
if pow(s, (p - 1) // 2, p) * pow(s, (q - 1) // 2, q) == (p - 1) * (q - 1):
pubkey = p * q, s
return pubkey
def encrypt(pubkey, m):
n, s = pubkey
r = getRandomRange(2, n)
return pow(s, m, n) * pow(r, 2 ** k, n) % n
flag = flag.lstrip(b'ASIS{').rstrip(b'}')
nbit, k = params
PUBKEYS = [keygen(nbit, k) for _ in range(4)]
flag = [bytes_to_long(flag[i*8:i*8 + 8]) for i in range(4)]
ENCS = [encrypt(PUBKEYS[_], flag[_]) for _ in range(4)]
print(f'PUBKEYS = {PUBKEYS}')
print(f'ENCS = {ENCS}') | python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/ASIS/2022/Quals/crypto/chaffymasking/chaffymasking.py | ctfs/ASIS/2022/Quals/crypto/chaffymasking/chaffymasking.py | #!/usr/bin/env python3
import numpy as np
import binascii
import os, sys
from flag import FLAG
def die(*args):
pr(*args)
quit()
def pr(*args):
s = " ".join(map(str, args))
sys.stdout.write(s + "\n")
sys.stdout.flush()
def sc():
return sys.stdin.buffer.readline()
def pad(inp, length):
result = inp + os.urandom(length - len(inp))
return result
def byte_xor(a, b):
return bytes(_a ^ _b for _a,_b in zip(a,b))
def chaffy_mask(salt, LTC, m, n):
q = n ** 2
half1_salt = salt[:m // 8]
half2_salt = salt[m // 8:]
xor_salts = int.from_bytes(byte_xor(half1_salt, half2_salt), "big")
if xor_salts == 0:
half1_salt = byte_xor(half1_salt, os.urandom(m))
half1_binStr = "{:08b}".format(int(half1_salt.hex(),16))
if(len(half1_binStr) < m):
half1_binStr = "0" * (m - len(half1_binStr)%m) + half1_binStr
half2_binStr = "{:08b}".format(int(half2_salt.hex(),16))
if(len(half2_binStr) < m):
half2_binStr = "0" * (m - len(half2_binStr)%m) + half2_binStr
vec_1 = np.array(list(half1_binStr), dtype=int)
vec_1 = np.reshape(vec_1, (m,1))
vec_2 = np.array(list(half2_binStr), dtype=int)
vec_2 = np.reshape(vec_2, (m,1))
out_1 = LTC.dot(vec_1) % q
out_2 = LTC.dot(vec_2) % q
flag_vector = np.array([ord(i) for i in FLAG])
flag_vector = np.reshape(flag_vector, (n,1))
masked_flag = (flag_vector ^ out_1 ^ out_2) % 256
masked_flag = np.reshape(masked_flag, (n,))
masked_flag = ''.join([hex(_)[2:].zfill(2) for _ in masked_flag])
return masked_flag.encode('utf-8')
def main():
border = "|"
pr(border*72)
pr(border, " Welcome to chaffymask combat, we implemented a masking method to ", border)
pr(border, " hide our secret. Masking is done by your 1024 bit input salt. Also ", border)
pr(border, " I noticed that there is a flaw in my method. Can you abuse it and ", border)
pr(border, " get the flag? In each step you should send salt and get the mask. ", border)
pr(border*72)
m, n = 512, 64
IVK = [
3826, 476, 3667, 2233, 1239, 1166, 2119, 2559, 2376, 1208, 2165, 2897, 830, 529, 346, 150, 2188, 4025,
3667, 1829, 3987, 952, 3860, 2574, 959, 1394, 1481, 2822, 3794, 2950, 1190, 777, 604, 82, 49, 710, 1765,
3752, 2970, 952, 803, 873, 2647, 2643, 1096, 1202, 2236, 1492, 3372, 2106, 1868, 535, 161, 3143, 3370,
1, 1643, 2147, 2368, 3961, 1339, 552, 2641, 3222, 2505, 3449, 1540, 2024, 618, 1904, 314, 1306, 3173,
4040, 1488, 1339, 2545, 2167, 394, 46, 3169, 897, 4085, 4067, 3461, 3444, 118, 3185, 2267, 3239, 3612,
2775, 580, 3579, 3623, 1721, 189, 650, 2755, 1434, 35, 3167, 323, 589, 3410, 652, 2746, 2787, 3665, 828,
3200, 1450, 3147, 720, 3741, 1055, 505, 2929, 1423, 3629, 3, 1269, 4066, 125, 2432, 3306, 4015, 2350,
2154, 2623, 1304, 493, 763, 1765, 2608, 695, 30, 2462, 294, 3656, 3231, 3647, 3776, 3457, 2285, 2992,
3997, 603, 2342, 2283, 3029, 3299, 1690, 3281, 3568, 1927, 2909, 1797, 1675, 3245, 2604, 1272, 1146,
3301, 13, 3712, 2691, 1097, 1396, 3694, 3866, 2066, 1946, 3476, 1182, 3409, 3510, 2920, 2743, 1126, 2154,
3447, 1442, 2021, 1748, 1075, 1439, 3932, 3438, 781, 1478, 1708, 461, 50, 1881, 1353, 2959, 1225, 1923,
1414, 4046, 3416, 2845, 1498, 4036, 3899, 3878, 766, 3975, 1355, 2602, 3588, 3508, 3660, 3237, 3018,
1619, 2797, 1823, 1185, 3225, 1270, 87, 979, 124, 1239, 1763, 2672, 3951, 984, 869, 3897, 327, 912, 1826,
3354, 1485, 2942, 746, 833, 3968, 1437, 3590, 2151, 1523, 98, 164, 3119, 1161, 3804, 1850, 3027, 1715,
3847, 2407, 2549, 467, 2029, 2808, 1782, 1134, 1953, 47, 1406, 3828, 1277, 2864, 2392, 3458, 2877, 1851,
1033, 798, 2187, 54, 2800, 890, 3759, 4085, 3801, 3128, 3788, 2926, 1983, 55, 2173, 2579, 904, 1019,
2108, 3054, 284, 2428, 2371, 2045, 907, 1379, 2367, 351, 3678, 1087, 2821, 152, 1783, 1993, 3183, 1317,
2726, 2609, 1255, 144, 2415, 2498, 721, 668, 355, 94, 1997, 2609, 1945, 3011, 2405, 713, 2811, 4076,
2367, 3218, 1353, 3957, 2056, 881, 3420, 1994, 1329, 892, 1577, 688, 134, 371, 774, 3855, 1461, 1536,
1824, 1164, 1675, 46, 1267, 3652, 67, 3816, 3169, 2116, 3930, 2979, 3166, 3944, 2252, 2988, 34, 873,
1643, 1159, 2822, 1235, 2604, 888, 2036, 3053, 971, 1585, 2439, 2599, 1447, 1773, 984, 261, 3233, 2861,
618, 465, 3016, 3081, 1230, 1027, 3177, 459, 3041, 513, 1505, 3410, 3167, 177, 958, 2118, 326, 31, 2663,
2026, 2549, 3026, 2364, 1540, 3236, 2644, 4050, 735, 280, 798, 169, 3808, 2384, 3497, 1759, 2415, 3444,
1562, 3472, 1151, 1984, 2454, 3167, 1538, 941, 1561, 3071, 845, 2824, 58, 1467, 3807, 2191, 1858, 106,
3847, 1326, 3868, 2787, 1624, 795, 3214, 1932, 3496, 457, 2595, 3043, 772, 2436, 2160, 3428, 2005, 2597,
1932, 101, 3528, 1698, 3663, 900, 3298, 1872, 1179, 3987, 3695, 3561, 1762, 3785, 3005, 2574, 6, 1524,
2738, 1753, 2350, 558, 800, 3782, 722, 886, 2176, 3050, 221, 1925, 564, 1271, 2535, 3113, 1310, 2098,
3011, 964, 3281, 6, 1326, 741, 189, 2632, 373, 1176, 548, 64, 1445, 2376, 1524, 2690, 1316, 2304, 1336,
2257, 3227, 2542, 3911, 3460
]
LTC = np.zeros([n, m], dtype=(int))
LTC[0,:] = IVK
for i in range(1, n):
for j in range(m // n + 1):
LTC[i,j*n:(j+1)*n] = np.roll(IVK[j*n:(j+1)*n], i)
for _ in range(5):
pr(border, "Give me your salt: ")
SALT = sc()[:-1]
SALT = pad(SALT, m // 4)
MASKED_FLAG = chaffy_mask(SALT, LTC, m, n)
pr(border, f'masked_flag = {MASKED_FLAG}')
if __name__ == '__main__':
main() | python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/ASIS/2022/Quals/crypto/binned/binned.py | ctfs/ASIS/2022/Quals/crypto/binned/binned.py | #!/usr/bin/env python3
from Crypto.Util.number import *
from gensafeprime import *
from flag import flag
def keygen(nbit):
p, q = [generate(nbit) for _ in range(2)]
return (p, q)
def encrypt(m, pubkey):
return pow(pubkey + 1, m, pubkey ** 3)
p, q = keygen(512)
n = p * q
flag = bytes_to_long(flag)
enc = encrypt(flag, n)
print(f'pubkey = {n}')
print(f'enc = {enc}') | python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/ASIS/2022/Quals/web/xtr/deploy.py | ctfs/ASIS/2022/Quals/web/xtr/deploy.py | #!/usr/bin/env python3
# socat TCP-LISTEN:2323,reuseaddr,fork EXEC:"./deploy.py"
import os
import re
import json
import time
import subprocess
if not os.path.exists('/tmp/ips.json'):
f = open('/tmp/ips.json','w')
f.write('{}')
f.close()
ipFile = open('/tmp/ips.json','r+')
peerIp = os.environ['SOCAT_PEERADDR']
ips = {}
ips = json.loads(ipFile.read())
if(peerIp in ips):
if(time.time() > ips[peerIp]):
ips[peerIp] = int(time.time())+30
else:
print('one try each 30 seconds')
exit(0)
else:
ips[peerIp] = int(time.time())+30
ipFile.seek(0)
ipFile.write(json.dumps(ips))
ipFile.close()
s = input('input: ')
assert(
re.match('^[A-Za-z0-9=+/ ]+$',s) and
s.count(' ') < 4 and
len(s) < 3000
)
subprocess.call(('docker run --rm xtr /app/run.sh '+s).split(' '))
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/ASIS/2022/Quals/web/hugeblog/app.py | ctfs/ASIS/2022/Quals/web/hugeblog/app.py | #!/usr/bin/env python
from Crypto.Cipher import AES
from flask_session import Session
import base64
import datetime
import flask
import glob
import hashlib
import io
import json
import os
import re
import zipfile
app = flask.Flask(__name__)
app.secret_key = os.urandom(16)
app.encryption_key = os.urandom(16)
app.config['SESSION_TYPE'] = 'filesystem'
app.config['SESSION_USE_SIGNER'] = True
app.config['SESSION_FILE_DIR'] = f'/tmp/{os.urandom(16).hex()}'
Session(app)
BASE_DIR = './post'
TEMPLATE = """<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>{{title}}</title>
</head>
<body>
<h1>{{author}}'s Website</h1>
<p>This is a sample page by {{author}} published on {{date}}.</p>
</body>
</html>
"""
@app.route('/', methods=['GET'])
def index():
db = get_database()
if db is None:
return flask.render_template('login.html')
else:
return flask.render_template('index.html',
template=TEMPLATE, database=db)
@app.route('/post/<title>', methods=['GET'])
def get_post(title):
db = get_database()
if db is None:
return flask.redirect('/login')
err, post = db.read(title)
if err:
return flask.abort(404, err)
return flask.render_template_string(post['content'],
title=post['title'],
author=post['author'],
date=post['date'])
@app.route('/api/login', methods=['POST'])
def api_login():
try:
data = json.loads(flask.request.data)
assert isinstance(data['username'], str)
assert isinstance(data['password'], str)
assert not re.search('[^A-Za-z0-9]',data['username'])
except:
return flask.abort(400, "Invalid request")
flask.session['username'] = data['username']
flask.session['passhash'] = hashlib.md5(data['password'].encode()).hexdigest()
flask.session['workdir'] = os.urandom(16).hex()
return flask.jsonify({'result': 'OK'})
@app.route('/api/new', methods=['POST'])
def api_new():
"""Add a blog post"""
db = get_database()
if db is None:
return flask.redirect('/login')
try:
data = json.loads(flask.request.data)
assert isinstance(data['title'], str)
assert isinstance(data['content'], str)
except:
return flask.abort(400, "Invalid request")
err, post_id = db.add(data['title'], get_username(), data['content'])
if err:
return flask.jsonify({'result': 'NG', 'reason': err})
else:
return flask.jsonify({'result': 'OK', 'id': post_id})
@app.route('/api/delete', methods=['POST'])
def api_delete():
"""Delete a blog post"""
db = get_database()
if db is None:
return flask.redirect('/login')
try:
data = json.loads(flask.request.data)
assert isinstance(data['id'], str)
except:
return flask.abort(400, "Invalid request")
err = db.delete(data['id'])
if err:
return flask.jsonify({'result': 'NG', 'reason': err})
else:
return flask.jsonify({'result': 'OK'})
@app.route('/api/export', methods=['GET'])
def api_export():
"""Export blog posts"""
db = get_database()
if db is None:
return flask.redirect('/login')
err, blob = db.export_posts(get_username(), get_passhash())
if err:
return flask.jsonify({'result': 'NG', 'reason': err})
else:
return flask.jsonify({'result': 'OK', 'export': blob})
@app.route('/api/import', methods=['POST'])
def api_import():
"""Import blog posts"""
db = get_database()
if db is None:
return flask.redirect('/login')
try:
data = json.loads(flask.request.data)
assert isinstance(data['import'], str)
except:
return flask.abort(400, "Invalid request")
err = db.import_posts(data['import'], get_username(), get_passhash())
if err:
return flask.jsonify({'result': 'NG', 'reason': err})
else:
return flask.jsonify({'result': 'OK'})
class Database(object):
"""Database to store blog posts of a user
"""
def __init__(self, workdir):
assert workdir.isalnum()
self.workdir = f'{BASE_DIR}/{workdir}'
os.makedirs(self.workdir, exist_ok=True)
def __iter__(self):
"""Return blog posts sorted by publish date"""
def enumerate_posts(workdir):
posts = []
for path in glob.glob(f'{workdir}/*.json'):
with open(path, "rb") as f:
posts.append(json.loads(f.read().decode('latin-1')))
for post in sorted(posts,
key=lambda post: datetime.datetime.strptime(
post['date'], "%Y/%m/%d %H:%M:%S"
))[::-1]:
yield post
return enumerate_posts(self.workdir)
@staticmethod
def to_snake(s):
"""Convert string to snake case"""
for i, c in enumerate(s):
if not c.isalnum():
s = s[:i] + '_' + s[i+1:]
return s
def add(self, title, author, content):
"""Add new blog post"""
# Validate title and content
if len(title) == 0: return 'Title is emptry', None
if len(title) > 64: return 'Title is too long', None
if len(content) == 0 : return 'HTML is empty', None
if len(content) > 1024*64: return 'HTML is too long', None
if '{%' in content:
return 'The pattern "{%" is forbidden', None
for m in re.finditer(r"{{", content):
p = m.start()
if not (content[p:p+len('{{title}}')] == '{{title}}' or \
content[p:p+len('{{author}}')] == '{{author}}' or \
content[p:p+len('{{date}}')] == '{{date}}'):
return 'You can only use "{{title}}", "{{author}}", and "{{date}}"', None
# Save the blog post
now = datetime.datetime.now().strftime("%Y/%m/%d %H:%M:%S")
post_id = Database.to_snake(title)
data = {
'title': title,
'id': post_id,
'date': now,
'author': author,
'content': content
}
with open(f'{self.workdir}/{post_id}.json', "w") as f:
json.dump(data, f)
return None, post_id
def read(self, title):
"""Load a blog post"""
post_id = Database.to_snake(title)
if not os.path.isfile(f'{self.workdir}/{post_id}.json'):
return 'The blog post you are looking for does not exist', None
with open(f'{self.workdir}/{post_id}.json', "rb") as f:
return None, json.loads(f.read().decode('latin-1'))
def delete(self, title):
"""Delete a blog post"""
post_id = Database.to_snake(title)
if not os.path.isfile(f'{self.workdir}/{post_id}.json'):
return 'The blog post you are trying to delete does not exist'
os.unlink(f'{self.workdir}/{post_id}.json')
def export_posts(self, username, passhash):
"""Export all blog posts with encryption and signature"""
buf = io.BytesIO()
with zipfile.ZipFile(buf, 'a', zipfile.ZIP_STORED) as z:
# Archive blog posts
for path in glob.glob(f'{self.workdir}/*.json'):
z.write(path)
# Add signature so that anyone else cannot import this backup
z.comment = f'SIGNATURE:{username}:{passhash}'.encode()
# Encrypt archive so that anyone else cannot read the contents
buf.seek(0)
iv = os.urandom(16)
cipher = AES.new(app.encryption_key, AES.MODE_CFB, iv)
encbuf = iv + cipher.encrypt(buf.read())
return None, base64.b64encode(encbuf).decode()
def import_posts(self, b64encbuf, username, passhash):
"""Import blog posts from backup file"""
encbuf = base64.b64decode(b64encbuf)
cipher = AES.new(app.encryption_key, AES.MODE_CFB, encbuf[:16])
buf = io.BytesIO(cipher.decrypt(encbuf[16:]))
try:
with zipfile.ZipFile(buf, 'r', zipfile.ZIP_STORED) as z:
# Check signature
if z.comment != f'SIGNATURE:{username}:{passhash}'.encode():
return 'This is not your database'
# Extract archive
z.extractall()
except:
return 'The database is broken'
return None
def get_username():
return flask.session['username'] if 'username' in flask.session else None
def get_passhash():
return flask.session['passhash'] if 'passhash' in flask.session else None
def get_workdir():
return flask.session['workdir'] if 'workdir' in flask.session else None
def get_database():
if (get_username() and get_passhash() and get_workdir()) is None:
return None
return Database(get_workdir())
if __name__ == '__main__':
app.run() | python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/ASIS/2022/Quals/web/firewalled/flag-container/stuff/app.py | ctfs/ASIS/2022/Quals/web/firewalled/flag-container/stuff/app.py | #!/usr/bin/env python3
from flask import Flask,request
import requests
import json
import os
app = Flask(__name__)
application = app
flag = os.environ.get('FLAG')
@app.route('/flag')
def index():
args = request.args.get('args')
try:
r = requests.post('http://firewalled-curl/req',json=json.loads(args)).json()
if('request' in r and 'flag' in r['request'] and 'flag' in request.headers['X-Request']):
return flag
except:
pass
return 'No flag for you :('
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/ASIS/2022/Quals/web/firewalled/firewalled-curl/stuff/app.py | ctfs/ASIS/2022/Quals/web/firewalled/firewalled-curl/stuff/app.py | #!/usr/bin/env python3
from flask import Flask,Response,request
import time
import socket
import re
import base64
import json
isSafeAscii = lambda s : not re.search(r'[^\x20-\x7F]',s)
isSafeHeader = lambda s : isSafeAscii(s)
isSafePath = lambda s : s[0] == '/' and isSafeAscii(s) and ' ' not in s
badHeaderNames = ['encoding','type','charset']
unsafeKeywords = ["flag"]
app = Flask(__name__)
application = app
def isJson(s):
try:
json.loads(s)
return True
except:
return False
def checkHostname(name):
name = str(name)
port = '80'
if(':' in name):
sp = name.split(':')
name = sp[0]
port = sp[1]
if(
(
re.search(r'^[a-z0-9][a-z0-9\-\.]+$',name) or
re.search(r'^[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+$',name)
) and
0 < int(port) < 0x10000
):
return name,int(port)
return Exception('unsafe port'),Exception('unsafe hostname')
def recvuntil(sock,u):
r = b''
while(r[-len(u):] != u):
r += sock.recv(1)
return r
def checkHeaders(headers):
newHeaders = {}
if(type(headers) is not dict):
return Exception('unsafe headers')
for headerName in headers:
headerValue = str(headers[headerName])
if((isSafeHeader(headerName) and ':' not in headerName) and isSafeHeader(headerValue)):
isBad = False
for badHeaderName in badHeaderNames:
if(badHeaderName in headerName.lower()):
isBad = True
break
for badHeaderValue in unsafeKeywords:
if(badHeaderValue in headerValue.lower()):
isBad = True
break
if(isBad):
return Exception('bad headers')
newHeaders[headerName] = headerValue
return newHeaders
def checkMethod(method):
if(method in ['GET','POST']):
return method
return Exception('unsafe method')
def checkPath(path):
if(isSafePath(path)):
return path
return Exception('unsafe path')
def checkJson(j):
if(type(j) == str):
for u in unsafeKeywords:
if(u in j.lower()):
return False
elif(type(j) == list):
for entry in j:
if(not checkJson(entry)):
return False
elif(type(j) == dict):
for entry in j:
if(not checkJson(j[entry])):
return False
else:
return True
return True
@app.route('/req',methods=['POST'])
def req():
params = request.json
hostname,port = checkHostname(params['host'])
headers = checkHeaders(params['headers'])
method = checkMethod(params['method'])
path = checkPath(params['path'])
returnJson = bool(params['returnJson'])
body = None
for p in [hostname,headers,body,method,path]:
if(isinstance(p,Exception)):
return {'success':False,'error':str(p)}
if(method == 'POST'):
body = str(params['body'])
httpRequest = f'{method} {path} HTTP/1.1\r\n'
if(port == 80):
httpRequest+= f'Host: {hostname}\r\n'
else:
httpRequest+= f'Host: {hostname}:{port}\r\n'
httpRequest+= f'Connection: close\r\n'
if(body):
httpRequest+= f'Content-Length: {str(len(body))}\r\n'
for headerName in headers:
httpRequest+= f'{headerName}: {headers[headerName]}\r\n'
httpRequest += '\r\n'
if(body):
httpRequest += body
httpRequest = httpRequest.encode()
with socket.socket(socket.AF_INET,socket.SOCK_STREAM) as sock:
sock.settimeout(1)
sock.connect((hostname,port))
sock.sendall(httpRequest)
statusCode = int(recvuntil(sock,b'\n').split(b' ')[1])
headers = {}
line = recvuntil(sock,b'\n').strip()
while(line):
headerName = line[:line.index(b':')].strip().decode()
headerValue = line[line.index(b':')+1:].strip().decode()
if(isSafeHeader(headerName) and isSafeHeader(headerValue)):
headers[headerName] = headerValue
line = recvuntil(sock,b'\n').strip()
bodyLength = min(int(headers['Content-Length']),0x1000)
body = b''
while(len(body) != bodyLength):
body += sock.recv(1)
sock.close()
if(isJson(body.decode())):
if(not checkJson(json.loads(body.decode()))):
return {'success':False,'error':'unsafe json'}
headers['Content-Type'] = 'application/json'
else:
headers['Content-Type'] = 'application/octet-stream'
if(returnJson):
body = base64.b64encode(body).decode()
return {'statusCode':statusCode,'headers':headers,'body':body,'req':httpRequest.decode()}
resp = Response(body)
resp.status = statusCode
for headerName in headers:
for badHeaderName in badHeaderNames:
if(badHeaderName not in headerName.lower()):
resp.headers[headerName] = headers[headerName]
return resp
@app.route('/')
def index():
resp = Response('hi')
resp.headers['Content-Type'] = 'text/plain'
return resp
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/ASIS/2022/Quals/web/beginner-duck/main.py | ctfs/ASIS/2022/Quals/web/beginner-duck/main.py | #!/usr/bin/env python3
from flask import Flask,request,Response
import random
import re
app = Flask(__name__)
availableDucks = ['duckInABag','duckLookingAtAHacker','duckWithAFreeHugsSign']
indexTemplate = None
flag = None
@app.route('/duck')
def retDuck():
what = request.args.get('what')
duckInABag = './images/e146727ce27b9ed172e70d85b2da4736.jpeg'
duckLookingAtAHacker = './images/591233537c16718427dc3c23429de172.jpeg'
duckWithAFreeHugsSign = './images/25058ec9ffd96a8bcd4fcb28ef4ca72b.jpeg'
if(not what or re.search(r'[^A-Za-z\.]',what)):
return 'what?'
with open(eval(what),'rb') as f:
return Response(f.read(), mimetype='image/jpeg')
@app.route("/")
def index():
return indexTemplate.replace('WHAT',random.choice(availableDucks))
with open('./index.html') as f:
indexTemplate = f.read()
with open('/flag.txt') as f:
flag = f.read()
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/ASIS/2022/Finals/pwn/readable-v2/deploy.py | ctfs/ASIS/2022/Finals/pwn/readable-v2/deploy.py | #!/usr/bin/env python3
# socat TCP-LISTEN:2323,reuseaddr,fork EXEC:"./deploy.py"
import tempfile
import pathlib
import os
import string
import time
import random
import json
if not os.path.exists('/tmp/ips.json'):
f = open('/tmp/ips.json','w')
f.write('{}')
f.close()
ipFile = open('/tmp/ips.json','r+')
peerIp = os.environ['SOCAT_PEERADDR']
ips = {}
ips = json.loads(ipFile.read())
if(peerIp in ips):
if(time.time() > ips[peerIp]):
ips[peerIp] = int(time.time())+30
else:
print('one try each 30 seconds')
exit(0)
else:
ips[peerIp] = int(time.time())+30
ipFile.seek(0)
ipFile.write(json.dumps(ips))
ipFile.close()
os.chdir(pathlib.Path(__file__).parent.resolve())
fname = None
with tempfile.NamedTemporaryFile(delete=False) as tmp:
fname = tmp.name
print('1. shell')
print('2. custom binary')
if(int(input('> ')) == 1):
f = open('/bin/bash','rb')
tmp.write(f.read())
f.close()
else:
buf = b''
n = int(input('Length: '))
while(len(buf) != n):
buf += os.read(0,0x1000)
buf = buf[:n]
tmp.write(buf)
tmp.close()
os.chmod(fname,0o555)
containerName = ''.join(random.choice(string.ascii_uppercase + string.digits) for _ in range(0x10))
os.system(f'bash -c "sleep 5 && docker kill {containerName} 2>/dev/null" &')
os.system(f'docker run --name {containerName} --privileged --network=none -i --rm -v {fname}:/tmp/exploit readable_v2')
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/ASIS/2022/Finals/pwn/permissions/deploy.py | ctfs/ASIS/2022/Finals/pwn/permissions/deploy.py | #!/usr/bin/env python3
# socat TCP-LISTEN:2323,reuseaddr,fork EXEC:"./deploy.py"
import os
import re
import json
import time
import subprocess
if not os.path.exists('/tmp/ips.json'):
f = open('/tmp/ips.json','w')
f.write('{}')
f.close()
ipFile = open('/tmp/ips.json','r+')
peerIp = os.environ['SOCAT_PEERADDR']
ips = {}
ips = json.loads(ipFile.read())
if(peerIp in ips):
if(time.time() > ips[peerIp]):
ips[peerIp] = int(time.time())+30
else:
print('one try each 30 seconds')
exit(0)
else:
ips[peerIp] = int(time.time())+30
ipFile.seek(0)
ipFile.write(json.dumps(ips))
ipFile.close()
s = input('input: ')
assert(
re.match('^[A-Za-z0-9=+/]+$',s) and
len(s) < 3000
)
subprocess.call(('docker run --privileged --rm permissions timeout 10 xvfb-run --auto-servernum node /app/index.js '+s).split(' '))
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/ASIS/2022/Finals/pwn/jry/stuff/run.py | ctfs/ASIS/2022/Finals/pwn/jry/stuff/run.py | #!/usr/bin/env python3
import tempfile
import pathlib
import os
os.chdir(pathlib.Path(__file__).parent.resolve())
with tempfile.NamedTemporaryFile() as tmp:
print('Send the file: (ended with "\\n-- EOF --\\n"):')
s = input()
while(s != '-- EOF --'):
tmp.write((s+'\n').encode())
s = input()
tmp.flush()
os.close(0)
os.system('./jerry ' + tmp.name)
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/ASIS/2022/Finals/crypto/rhyton/rhyton.py | ctfs/ASIS/2022/Finals/crypto/rhyton/rhyton.py | #!/usr/bin/env python3
from Crypto.Util.number import *
from flag import flag
def gen_rhyton(nbit, delta, L):
p, q = [getPrime(nbit) for _ in '01']
n = p * q
D = int(n ** (1 - delta))
phi = (p - 1) * (q - 1)
V = [getRandomRange(1, n - 1) for _ in range(L)]
U = [phi * v // n for v in V]
W, i = [], 0
while True:
w = getRandomRange(phi * V[i] - U[i] * n - D, phi * V[i] - U[i] * n + D)
if abs(phi * V[i] - U[i] * n - w) < D and w < n:
W.append(w)
i += 1
if i == L:
break
return (p, q, U, V, W)
def encrypt(msg, p, q):
m, n = bytes_to_long(msg), p * q
assert m < p * q
e = 65537
return pow(m, e, n)
nbit, delta, L = 512, 0.14, 110
p, q, U, V, W = gen_rhyton(nbit, delta, L)
enc = encrypt(flag, p, q)
print(f'n = {p * q}')
print(f'V = {V}')
print(f'W = {W}')
print(f'enc = {enc}') | python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/ASIS/2022/Finals/crypto/bedouin/bedouin.py | ctfs/ASIS/2022/Finals/crypto/bedouin/bedouin.py | #!/usr/bin/env python3
from Crypto.Util.number import *
from secret import nbit, l, flag
def genbed(nbit, l):
while True:
zo = bin(getPrime(nbit))[2:]
OZ = zo * l + '1'
if isPrime(int(OZ)):
return int(OZ)
p, q = [genbed(nbit, l) for _ in '01']
n = p * q
d = 1 ^ l ** nbit << 3 ** 3
phi = (p - 1) * (q - 1)
e = inverse(d, phi)
m = bytes_to_long(flag)
c = pow(m, e, n)
if pow(c, d, n) == m:
print(f'n = {n}')
print(f'c = {c}') | python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/ASIS/2020/Quals/safari_park/server.py | ctfs/ASIS/2020/Quals/safari_park/server.py | #!/usr/bin/env python3.7
import os
import random
import signal
import subprocess
import sys
def jsc(code):
try:
path = f'/tmp/exploit-{random.randrange(0, 1<<128):032x}.js'
with open(path, "w") as f:
f.write(code)
subprocess.run(["./jsc", path], timeout=10)
except Exception as e:
print("[-] Execution Error", flush=True)
print(e, flush=True)
exit(1)
finally:
os.remove(path)
if __name__ == '__main__':
signal.alarm(60)
print("Send your javascript code here: (Close stdin to quit input)", flush=True)
try:
code = ''.join(sys.stdin.readlines())
assert len(code) < 10000
sys.stdin.close()
except Exception as e:
print("[-] Input Error", flush=True)
print(e, flush=True)
exit(1)
try:
jsc(code)
except Exception as e:
print("[-] Unknown Error", flush=True)
print(e, flush=True)
exit(1)
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/ASIS/2020/Finals/babyauth/bin/server.py | ctfs/ASIS/2020/Finals/babyauth/bin/server.py | #!/usr/bin/env python3
import os
import random
import shutil
import string
ctable = string.ascii_letters + string.digits
rndstr = lambda n: ''.join([random.choice(ctable) for i in range(n)])
PATH = '/tmp/babyauth_' + rndstr(16)
USERNAME = 'admin'
PASSWORD = rndstr(16)
if __name__ == '__main__':
# Setup
os.makedirs(PATH, exist_ok=True)
with open(f'{PATH}/username', 'w') as f:
f.write(USERNAME)
with open(f'{PATH}/password', 'w') as f:
f.write(PASSWORD)
# Prove your exploit is stable
for ROUND in range(5):
# Authentication
if os.system(f'./auth {PATH}') != 0:
shutil.rmtree(PATH)
exit(0)
print(f"[+] {ROUND+1}/5: OK", flush=True)
# Delicious Fruit
with open("/flag", "r") as f:
print(f.read())
# Cleanup
shutil.rmtree(PATH)
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/HackPack/2024/misc/Pirate_Bay/server.py | ctfs/HackPack/2024/misc/Pirate_Bay/server.py | import html
import os
import re
import requests
import sqlite3
from urllib.parse import parse_qs
from http.server import HTTPServer, BaseHTTPRequestHandler
from socketserver import ThreadingMixIn
from langserve import RemoteRunnable
import threading
db_path = 'fishy.db'
conn = sqlite3.connect(db_path, check_same_thread=False)
cursor = conn.cursor()
flag = ''
class ThreadedHTTPServer(ThreadingMixIn, HTTPServer):
pass
with open('flag.txt', 'r') as file:
flag = file.read().strip()
class Handler(BaseHTTPRequestHandler):
def do_GET(self):
if self.path == '/':
# Serve the HTML form
html_content = """
<!DOCTYPE html>
<html>
<head>
<title>Something's Fishy!</title>
<style>
html {
height: 100%;
margin: 0;
}
h1 {
text-align: center;
font-family: 'PirateFontTitle', sans-serif; /* Use the custom font */
}
body {
text-align: center;
font-family: 'PirateFontBody', sans-serif;
background-image: url('images/treasure_map.jpg');
background-size: 100% 100%; /* Stretch the background to cover the entire screen */
background-repeat: no-repeat;
margin: 0; /* Remove default margin */
}
.container {
background-color: white; /* White box background color */
border-radius: 10px; /* Rounded edges */
padding: 5px; /* Padding inside the container */
display: inline-block; /* Ensure container size is based on content */
}
img {
width: 20%; /* Adjust the width as needed */
display: block;
margin: 0 auto; /* Center the image */
margin: 20px auto; /* Add margin around the image */
border-radius: 10px; /* Round the image boundaries */
}
@font-face {
font-family: 'PirateFontTitle';
src: url('fonts/title.ttf') format('truetype');
}
@font-face {
font-family: 'PirateFontBody';
src: url('fonts/body.ttf') format('truetype');
}
</style>
</head>
<div class="container"><h1>What do you want to say to the pirate?</h1></div>
<body>
<form method="post" action="/do_post">
<input type="text" id="user_input" name="user_input">
<input type="submit" value="Yarrr Matey!">
</form>
<img src="images/pirate_fishing.jpg" alt="My matey">
</body>
</html>
"""
self.send_response(200)
self.send_header('content-type', 'text/html')
self.end_headers()
self.wfile.write(html_content.encode())
elif self.path.startswith('/images/'):
img_path = os.path.join('images', os.path.basename(self.path))
try:
with open(img_path, 'rb') as img_file:
self.send_response(200)
self.send_header('content-type', 'image/jpeg')
self.end_headers()
self.wfile.write(img_file.read())
except FileNotFoundError:
self.send_error(404, 'File Not Found: {}'.format(self.path))
elif self.path.startswith('/fonts/'):
font_path = os.path.join('fonts', os.path.basename(self.path))
print(f"Requested Path: {self.path}")
print(f"Constructed Font Path: {font_path}")
try:
with open(font_path, 'rb') as font_file:
self.send_response(200)
self.send_header('content-type', 'application/font-ttf')
self.end_headers()
self.wfile.write(font_file.read())
except FileNotFoundError:
self.send_error(404, 'File Not Found: {}'.format(self.path))
def do_POST(self):
# Retrieve user input from the POST request
content_length = int(self.headers['Content-Length'])
post_data = self.rfile.read(content_length).decode('utf-8')
user_input = parse_qs(post_data).get('user_input', [''])[0]
print(f"Received user input from POST request: {user_input}")
self.query_llm(user_input)
def query_llm(self, user_input):
rr = RemoteRunnable("http://models.hackpack.club:30080/fishy/")
llm_response = rr.invoke({"user_input": f"{user_input}"})
# response = requests.post(
# "http://models.hackpack.club:30080/fishy/invoke",
# json={"input":{"user_input":f"{user_input}"},"config":{}}
# )
# llm_response = response.json()["output"]["content"]
fish_number_match = re.search(r'FISH: (\d+)', llm_response)
# Check if the match is found and extract the fish number
if fish_number_match:
fish_number = int(fish_number_match.group(1))
else:
fish_number = 101
cursor.execute("SELECT name, description FROM fish WHERE id = ?", (fish_number,))
fish_name, fish_description = cursor.fetchone()
self.response(llm_response, fish_name, fish_description)
def response(self, llm_response, fish_name, fish_description):
msg = """<html>
<head>
<title>Something's Fishy...</title>
<style>
html {
height: 100%;
margin: 0;
}
p {
text-align: center;
}
h1 {
text-align: center;
font-family: 'PirateFontTitle', sans-serif; /* Use the custom font */
}
body {
text-align: center;
font-family: 'PirateFontBody', sans-serif;
background-image: url('images/treasure_map.jpg');
background-size: 100% 100%; /* Stretch the background to cover the entire screen */
background-repeat: no-repeat;
margin: 0; /* Remove default margin */
}
.container {
background-color: white; /* White box background color */
border-radius: 10px; /* Rounded edges */
padding: 20px; /* Padding inside the container */
display: inline-block; /* Ensure container size is based on content */
}
img {
width: 20%; /* Adjust the width as needed */
display: block;
margin: 0 auto; /* Center the image */
margin: 20px auto; /* Add margin around the image */
border-radius: 10px; /* Round the image boundaries */
}
@font-face {
font-family: 'PirateFontTitle';
src: url('fonts/title.ttf') format('truetype');
}
@font-face {
font-family: 'PirateFontBody';
src: url('fonts/body.ttf') format('truetype');
}
</style>
</head>
<body><div class="container">
"""
msg += ("<h1>The old Pirate says:</h1>" + html.escape(llm_response) + "<h2>Quick fish facts:</h2> <p>Fish: {0}</p><p>Description: {1}</p></div>").format(fish_name,fish_description,self)
if 'landlubber' not in llm_response:
# Chattin 'bout fish
msg += '<img src="images/pirate_with_fish.jpg" alt="Chatting about fish with the pirate">'
else:
msg += '<img src="images/angry_pirate.jpg" alt="Scurry along scallywag!">'
msg += "</body></html>"
self.send_response(200)
self.send_header('content-type', 'text/html')
self.end_headers()
self.wfile.write(msg.encode())
if __name__ == '__main__':
server = ThreadedHTTPServer(('0.0.0.0', 8000), Handler)
print('Starting server.')
server.serve_forever() | python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/HackPack/2023/web/Wiki_world/note-app/app.py | ctfs/HackPack/2023/web/Wiki_world/note-app/app.py | from flask import *
app = Flask(__name__)
@app.route('/')
def default():
return send_file('index.html')
@app.route('/<path:path>')
def send_artifacts(path):
return send_from_directory('', path)
if __name__ == '__main__':
app.run(host='0.0.0.0') | python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/HackPack/2022/crypto/paiaiai/paiaiai.py | ctfs/HackPack/2022/crypto/paiaiai/paiaiai.py | #!/usr/bin/env python3
#
# Polymero
#
# Imports
from Crypto.Util.number import getPrime, inverse
from secrets import randbelow
# Local imports
with open("flag.txt",'rb') as f:
FLAG = f.read().decode()
f.close()
# Just for you sanity
assert len(FLAG) > 64
HDR = r"""|
| __________ ___ _____ .___ ___ /\ ________
| \______ \ / / / _ \ | | \ \ / \ \_____ \
| | ___/ / / / /_\ \| | \ \ \/\/ _(__ <
| | | ( ( / | \ | ) ) / \
| |____| \ \ \____|__ /___| / / /______ /
| \__\ \/ /__/ \/
|"""
MENU = r"""|
| MENU:
| [E]ncrypt
| [D]ecrypt
| [Q]uit
|"""
class Paiaiai:
""" My first Paillier implementation! So proud of it. ^ w ^ """
def __init__(self):
# Key generation
p, q = [getPrime(512) for _ in range(2)]
n = p * q
# Public key
self.pub = {
'n' : n,
'gp' : pow(randbelow(n**2), p, n**2),
'gq' : pow(randbelow(n**2), q, n**2)
}
# Private key
self.priv = {
'la' : (p - 1)*(q - 1),
'mu' : inverse((pow(self.pub['gp'] * self.pub['gq'], (p-1)*(q-1), n**2) - 1) // n, n)
}
def encrypt(self, m: str):
m_int = int.from_bytes(m.encode(), 'big')
g = pow([self.pub['gp'],self.pub['gq']][randbelow(2)], m_int, self.pub['n']**2)
r = pow(randbelow(self.pub['n']), self.pub['n'], self.pub['n']**2)
return (g * r) % self.pub['n']**2
def decrypt(self, c: int):
cl = (pow(c, self.priv['la'], self.pub['n']**2) - 1) // self.pub['n']
return (cl * self.priv['mu']) % self.pub['n']
print(HDR)
pai = Paiaiai()
while True:
try:
print(MENU)
choice = input("| >>> ").lower().strip()
if choice == 'e':
print("|\n| ENCRYPT:")
print("| [F]lag")
print("| [M]essage")
subchoice = input("|\n| >>> ").lower().strip()
if subchoice == 'f':
enc_flag = pai.encrypt(FLAG)
print("|\n| FLAG:", enc_flag)
elif subchoice == 'm':
msg = input("|\n| MSG: str\n| > ")
cip = pai.encrypt(msg)
print("|\n| CIP:", cip)
elif choice == 'd':
cip = input("|\n| CIP: int\n| > ")
msg = pai.decrypt(int(cip))
print("|\n| MSG:", msg)
elif choice == 'q':
print("|\n| Bai ~ \n|")
break
else:
print("|\n| Trai again ~ \n|")
except KeyboardInterrupt:
print("\n|\n| Bai ~ \n|")
break
except:
print("|\n| Aiaiai ~ \n|")
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/HackPack/2022/crypto/RepeatingOffense/repeatingoffense.py | ctfs/HackPack/2022/crypto/RepeatingOffense/repeatingoffense.py | #!/usr/bin/env python3
#
# Polymero
#
# Imports
from Crypto.Util.number import getPrime, inverse, GCD
from secrets import randbelow
import os, hashlib
# Local imports
with open('flag.txt','rb') as f:
FLAG = f.read().decode().strip()
f.close()
HDR = r"""|
| _______ _______ _______ _______ __ ___________ __ _____ ___ _______
| /" \ /" "| | __ "\ /" "| /""\(" _ ")|" \ (\" \|" \ /" _ "|
| |: |(: ______) (. |__) :)(: ______) / \)__/ \\__/ || | |.\\ \ |(: ( \___)
| |_____/ ) \/ | |: ____/ \/ | /' /\ \ \\_ / |: | |: \. \\ | \/ \
| // / // ___)_ (| / // ___)_ // __' \ |. | |. | |. \ \. | // \ ___
| |: __ \ (: "| /|__/ \ (: "| / / \\ \\: | /\ |\| \ \ |(: _( _|
| |__| \___) \_______)(_______) \_______)(___/ \___)\__| (__\_|_)\___|\____\) \_______)
| ______ _______ _______ _______ _____ ___ ________ _______
| / " \ /" "| /" "| /" "|(\" \|" \ /" )/" "|
| // ____ \(: ______)(: ______)(: ______)|.\\ \ |(: \___/(: ______)
| / / ) :)\/ | \/ | \/ | |: \. \\ | \___ \ \/ |
| (: (____/ // // ___) // ___) // ___)_ |. \ \. | __/ \\ // ___)_
| \ / (: ( (: ( (: "|| \ \ | /" \ :)(: "|
| \"_____/ \__/ \__/ \_______) \___|\____\)(_______/ \_______)
|"""
print(HDR)
class RSA_then_Paillier:
""" Layered Cipher of RSA : Zn -> Zn then Paillier : Zn -> Zn2. """
def __init__(self, domain: tuple):
# Class parameters
P, Q = domain
self.HISTORY = []
# RSA public key
self.E = 0x10001
self.N = P * Q
# RSA private key
F = (P - 1) * (Q - 1)
self.D = inverse(self.E, F)
# Paillier public key
self.G = randbelow(self.N * self.N)
# Paillier private key
self.L = F // GCD(P - 1, Q - 1)
self.U = inverse((pow(self.G, self.L, self.N * self.N) - 1) // self.N, self.N)
def encrypt(self, msg: int) -> int:
# RSA
cip_rsa = pow(msg, self.E, self.N)
# Paillier
g_m = pow(self.G, cip_rsa, self.N * self.N)
r_n = pow(randbelow(self.N), self.N, self.N * self.N)
cip = (g_m * r_n) % (self.N * self.N)
# Update HISTORY
self.HISTORY += [hashlib.sha256(cip.to_bytes(256, 'big')).hexdigest()]
return cip
def decrypt(self, cip: int) -> int:
# Check HISTORY
if hashlib.sha256(cip.to_bytes(256, 'big')).hexdigest() in self.HISTORY:
return -1
# Paillier
cip_rsa = ((pow(cip, self.L, self.N * self.N) - 1) // self.N * self.U) % self.N
# RSA
return pow(cip_rsa, self.D, self.N)
class Paillier_then_RSA:
""" Layered Cipher of Paillier : Zn -> Zn2 then RSA : Zn2 -> Zn2. """
def __init__(self, domain: tuple):
# Class parameters
P, Q = domain
self.HISTORY = []
# RSA public key
self.E = 0x10001
self.N = P * Q
# RSA private key
F = (P - 1) * (Q - 1) * self.N
self.D = inverse(self.E, F)
# Paillier public key
self.G = randbelow(self.N * self.N)
# Paillier private key
self.L = F // GCD(P - 1, Q - 1)
self.U = inverse((pow(self.G, self.L, self.N * self.N) - 1) // self.N, self.N)
def encrypt(self, msg: int) -> int:
# Paillier
g_m = pow(self.G, msg, self.N * self.N)
r_n = pow(randbelow(self.N), self.N, self.N * self.N)
cip_pai = (g_m * r_n) % (self.N * self.N)
# RSA
cip = pow(cip_pai, self.E, self.N * self.N)
# Update HISTORY
self.HISTORY += [hashlib.sha256(cip.to_bytes(256, 'big')).hexdigest()]
return cip
def decrypt(self, cip: int) -> int:
# Check HISTORY
if hashlib.sha256(cip.to_bytes(256, 'big')).hexdigest() in self.HISTORY:
return -1
# RSA
cip_pai = pow(cip, self.D, self.N * self.N)
# Paillier
return ((pow(cip_pai, self.L, self.N * self.N) - 1) // self.N * self.U) % self.N
DOMAIN = [getPrime(512) for _ in range(2)]
STAGE_1, STAGE_2 = True, False
RTP = RSA_then_Paillier(DOMAIN)
print("|\n| STAGE 1 :: RSA-then-Paillier\n|\n| N: {}\n| G: {}".format(RTP.N, RTP.G))
RTP_PWD = int.from_bytes(os.urandom(32).hex().encode(), 'big')
print("|\n| RTP(Password): {}".format(RTP.encrypt(RTP_PWD)))
while STAGE_1:
try:
print("|\n|\n| MENU:\n| [E]ncrypt\n| [D]ecrypt\n| [S]ubmit Password")
choice = input("|\n| >>> ").lower()
if choice == 'e':
user_input = input("|\n| MSG(int): ")
print("|\n| CIP ->", RTP.encrypt(int(user_input)))
elif choice == 'd':
user_input = input("|\n| CIP(int): ")
print("|\n| MSG ->", RTP.decrypt(int(user_input)))
elif choice == 's':
user_input = input("|\n| PWD(int): ")
if user_input == str(RTP_PWD):
print("|\n|\n| Correct ~ On to Stage 2!\n|")
STAGE_2 = True
break
else:
print("|\n| ERROR -- Unknown command.")
except KeyboardInterrupt:
print("\n|\n|\n| Cya ~\n|")
break
except:
print("|\n| ERROR -- Something went wrong.")
if STAGE_2:
PTR = Paillier_then_RSA(DOMAIN)
print("|\n| STAGE 2 :: Paillier-then-RSA\n| N: {}\n| G: {}\n|".format(RTP.N, RTP.G))
PTR_PWD = int.from_bytes(os.urandom(32).hex().encode(), 'big')
print("|\n| PTR(Password): {}".format(PTR.encrypt(PTR_PWD)))
while STAGE_2:
try:
print("|\n|\n| MENU:\n| [E]ncrypt\n| [D]ecrypt\n| [S]ubmit Password")
choice = input("|\n| >>> ").lower()
if choice == 'e':
user_input = input("|\n| MSG(int): ")
print("|\n| CIP ->", PTR.encrypt(int(user_input)))
elif choice == 'd':
user_input = input("|\n| CIP(int): ")
print("|\n| MSG ->", PTR.decrypt(int(user_input)))
elif choice == 's':
user_input = input("|\n| PWD(int): ")
if user_input == str(PTR_PWD):
print("|\n|\n| Correct ~ Here's your flag: {}\n|".format(FLAG))
break
else:
print("|\n| ERROR -- Unknown command.")
except KeyboardInterrupt:
print("\n|\n|\n| Cya ~\n|")
break
except:
print("|\n| ERROR -- Something went wrong.")
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/HackPack/2022/web/ImportedKimchi/app.py | ctfs/HackPack/2022/web/ImportedKimchi/app.py | import uuid
from flask import *
from flask_bootstrap import Bootstrap
import pickle
import os
app = Flask(__name__)
Bootstrap(app)
app.secret_key = 'sup3r s3cr3t k3y'
ALLOWED_EXTENSIONS = set(['png', 'jpg', 'jpeg'])
images = set()
images.add('bibimbap.jpg')
images.add('galbi.jpg')
images.add('pickled_kimchi.jpg')
@app.route('/')
def index():
return render_template("index.html", images=images)
@app.route('/upload', methods=['GET', 'POST'])
def upload():
if request.method == 'POST':
image = request.files["image"]
if image and image.filename.split(".")[-1].lower() in ALLOWED_EXTENSIONS:
# special file names are fun!
extension = "." + image.filename.split(".")[-1].lower()
fancy_name = str(uuid.uuid4()) + extension
image.save(os.path.join('./images', fancy_name))
flash("Successfully uploaded image! View it at /images/" + fancy_name, "success")
return redirect(url_for('upload'))
else:
flash("An error occured while uploading the image! Support filetypes are: png, jpg, jpeg", "danger")
return redirect(url_for('upload'))
else:
return render_template("upload.html")
@app.route('/images/<filename>')
def display_image(filename):
try:
pickle.loads(open('./images/' + filename, 'rb').read())
except:
pass
return send_from_directory('./images', filename)
if __name__ == "__main__":
app.run(host='0.0.0.0')
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/HackPack/2022/web/ImportedKimchi2/app.py | ctfs/HackPack/2022/web/ImportedKimchi2/app.py | import uuid
from flask import *
from flask_bootstrap import Bootstrap
import pickle
import os
app = Flask(__name__)
Bootstrap(app)
app.secret_key = 'sup3r s3cr3t k3y'
ALLOWED_EXTENSIONS = set(['png', 'jpg', 'jpeg'])
images = set()
images.add('bibimbap.jpg')
images.add('galbi.jpg')
images.add('pickled_kimchi.jpg')
@app.route('/')
def index():
return render_template("index.html", images=images)
@app.route('/upload', methods=['GET', 'POST'])
def upload():
if request.method == 'POST':
image = request.files["image"]
if image and image.filename.split(".")[-1].lower() in ALLOWED_EXTENSIONS:
# special file names are fun!
extension = "." + image.filename.split(".")[-1].lower()
fancy_name = str(uuid.uuid4()) + extension
image.save(os.path.join('./images', fancy_name))
flash("Successfully uploaded image! View it at /images/" + fancy_name, "success")
return redirect(url_for('upload'))
else:
flash("An error occured while uploading the image! Support filetypes are: png, jpg, jpeg", "danger")
return redirect(url_for('upload'))
else:
return render_template("upload.html")
@app.route('/images/<filename>')
def display_image(filename):
try:
pickle.loads(open('./images/' + filename, 'rb').read())
except:
pass
return send_from_directory('./images', filename)
if __name__ == "__main__":
app.run(host='0.0.0.0')
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/HackPack/2020/jsclean/jsclean.py | ctfs/HackPack/2020/jsclean/jsclean.py | import os
import sys
import subprocess
def main(argv):
print("Welcome To JavaScript Cleaner")
js_name = input("Enter Js File Name To Clean: ")
code = input("Submit valid JavaScript Code: ")
js_name = os.path.basename(js_name) # No Directory Traversal for you
if not ".js" in js_name:
print("No a Js File")
return
with open(js_name,'w') as fin:
fin.write(code)
p = subprocess.run(['/usr/local/bin/node','index.js','-f',js_name],stdout=subprocess.PIPE);
print(p.stdout.decode('utf-8'))
main(sys.argv)
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/ISITDTU/2021/Quals/pwn/secret/auth/app.py | ctfs/ISITDTU/2021/Quals/pwn/secret/auth/app.py | #!/usr/bin/env python3
import base64
import binascii
import os
import hashlib
import socket
from Crypto.Util.number import long_to_bytes, bytes_to_long
from flask import Flask, session, request
app = Flask(__name__)
app.secret_key = 'VerySecretSecretKey'
N = '''00:c7:cc:f7:ce:7c:15:63:d5:84:c1:eb:18:a4:08:
63:b6:6f:dd:f7:ba:62:9f:02:82:1f:ce:a2:c9:25:
c1:6b:ca:30:29:8e:67:6b:5c:8c:f5:a5:5e:b0:55:
96:92:ea:dd:4d:1f:e1:c0:0c:6b:7a:68:33:49:f9:
cc:60:6c:36:2d:92:46:20:5e:b0:e7:29:11:4c:25:
6c:a3:d9:f8:07:60:36:2f:22:fa:3b:b4:96:d8:3d:
99:58:35:50:49:bd:de:31:9e:81:52:35:5a:bc:6b:
f4:c2:a2:69:a1:09:bf:46:9c:5a:47:33:f4:e0:5f:
37:50:55:fd:80:b9:d7:96:2b'''
N = int(''.join(N.split()).replace(':', ''), 16)
def H(*args) -> bytes:
m = hashlib.sha256()
m.update(b''.join(long_to_bytes(x) for x in args))
return bytes_to_long(m.digest()) % N
g = 2
k = H(N, g)
s = bytes_to_long(os.urandom(64))
I = b'admin'
p = binascii.hexlify(os.urandom(64))
v = pow(g, H(s, H(bytes_to_long(I + b':' + p))), N)
socks = {}
@app.route('/pre_auth', methods=['POST'])
def pre_auth():
if 'auth' in session:
return b'', 400
j = request.get_json(force=True)
if j['I'] != I.decode('ascii'):
return b'', 403
session['A'] = int(j['A'], 16)
b = bytes_to_long(os.urandom(64))
session['B'] = (k * v + pow(g, b, N)) % N
u = H(session['A'], session['B'])
S = pow(session['A'] * pow(v, u, N), b, N)
session['K'] = H(S)
resp = {
's': hex(s),
'B': hex(session['B'])
}
return resp, 200
@app.route('/auth', methods=['POST'])
def auth():
if 'auth' in session:
return b'', 400
if 'K' not in session:
return b'', 403
j = request.get_json(force=True)
M = int(j['M'], 16)
MM = H(H(N) ^ H(g), H(bytes_to_long(I)), s, session['A'], session['B'], session['K'])
if M != MM:
return b'', 403
resp = {
'M': hex(H(session['A'], M, session['K']))
}
session.clear()
session['auth'] = binascii.hexlify(os.urandom(8))
ss = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
ss.connect(('backend', 31337))
socks[session['auth']] = ss
return resp, 200
@app.route('/secret', methods=['POST'])
def secret():
if 'auth' not in session:
return b'', 403
ss = socks[session['auth']]
j = request.get_json(force=True)
cmd = base64.b64decode(j['cmd'])
if len(cmd) > 8:
return b'', 400
if len(cmd) < 8:
cmd += b'\n'
try:
ss.sendall(cmd)
except:
del socks[session['auth']]
session.clear()
return b'', 500
if cmd[0] == ord(b'0'):
data = base64.b64decode(j['data'])
if len(data) > 0x400:
return b'', 400
if len(data) < 0x400:
data += b'\n'
try:
ss.sendall(data)
except:
del socks[session['auth']]
session.clear()
return b'', 500
try:
l = ss.recv(1)[0]
data = b''
while len(data) < l:
data += ss.recv(l - len(data))
return {
'data': base64.b64encode(data).decode('ascii')
}, 200
except:
del socks[session['auth']]
session.clear()
return b'', 500
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/ISITDTU/2021/Quals/crypto/wheres_your_ticket/wheres_your_ticket.py | ctfs/ISITDTU/2021/Quals/crypto/wheres_your_ticket/wheres_your_ticket.py | from Crypto.Cipher import AES
from hashlib import md5
import hmac
from os import urandom
import sys
import random
from binascii import hexlify, unhexlify
import secret
import socket
import threading
import socketserver
import signal
host, port = '0.0.0.0', 5000
BUFF_SIZE = 1024
class ThreadedTCPServer(socketserver.ThreadingMixIn, socketserver.TCPServer):
allow_reuse_address = True
class ThreadedTCPRequestHandler(socketserver.StreamRequestHandler):
def handle(self):
self.AES_BLOCK_SIZE = 32
self.SIG_SIZE = md5().digest_size
self.message = b'guest'
self.key = self._hash_key(secret.key)
self.enc_role, self.sig = self.encrypt(self.message)
try:
while True:
self.menu()
try:
self.request.sendall(b'Your choice: ')
opt = int(self.rfile.readline().decode())
except ValueError:
self.request.sendall(
b'Invalid option!!!\n')
continue
if opt == 1:
self.request.sendall(b'Data format: name=player101&role=enc_role&sign=sig, enc_role and sign are in hex.\n')
self.request.sendall(b'Your data: ')
data = self.rfile.readline().strip()
self.confirm(data)
elif opt == 2:
self.request.sendall(b'Your data: ')
data = self.rfile.readline().strip()
if b'&role=' in data:
self.request.sendall(b'Not that easy!\n')
else:
sign = self.sign_new(data)
if sign == None:
pass
else:
self.request.sendall(b"Hash: " + hexlify(sign) + b'\n')
elif opt == 3:
self.request.sendall(b'Your data: ')
data = self.rfile.readline().strip()
sign = self.sign_old(data)
self.request.sendall(b"Hash: " + hexlify(sign) + b'\n')
elif opt == 4:
self.request.sendall(b'Goodbye!\n')
return
else:
self.request.sendall(b'Invalid option!!!\n')
except (ConnectionResetError, ConnectionAbortedError, BrokenPipeError):
print("{} disconnected".format(self.client_address[0]))
def menu(self):
self.request.sendall(b'\nYour role: ' + self.decrypt(b'name=player101&role='+hexlify(self.enc_role), hexlify(self.sig)))
self.request.sendall(b'\nEncrypted data of your role:')
self.request.sendall(b'\nEncrypted: ' + hexlify(self.enc_role))
self.request.sendall(b'\nSignature: ' + hexlify(self.sig) + b'\n')
self.request.sendall(b'1. Verify your data:\n')
self.request.sendall(b'2. Sign your data in new way:\n')
self.request.sendall(b'3. Sign your data in old way:\n')
self.request.sendall(b'4. Quit\n')
def _hash_key(self, key):
return md5(key).digest()
def _initialisation_vector(self):
return urandom(16)
def _cipher(self, key, iv):
return AES.new(key, AES.MODE_CBC, iv)
def encrypt(self, data):
iv = self._initialisation_vector()
cipher = self._cipher(self.key, iv)
pad = self.AES_BLOCK_SIZE - len(data) % self.AES_BLOCK_SIZE
data = data + (pad * chr(pad)).encode()
data = iv + cipher.encrypt(data)
ss = b'name=player101&role=%s'%(hexlify(data))
sig = self.sign_new(ss)
return data, sig
def decrypt(self, data, sig):
if hexlify(self.sign_new(data)) != sig:
self.request.sendall(b'Message authentication failed')
return
else:
pos = data.rfind(b'&role=')
data = unhexlify(data[pos+6:])
iv = data[:16]
data = data[16:]
cipher = AES.new(self.key, AES.MODE_CBC, iv)
data = cipher.decrypt(data)
return data[:-data[-1]]
def XR(self, a, b):
len_max = len(a) if len(a) > len(b) else len(b)
s = ''
for i in range(len_max):
h = hex(a[i%len(a)] ^ b[i%len(b)])[2:]
if(len(h) < 2):
s += '0' + hex(a[i%len(a)] ^ b[i%len(b)])[2:]
else:
s += hex(a[i%len(a)] ^ b[i%len(b)])[2:]
return unhexlify(s.encode())
def xor_key(self, a):
if isinstance(a, str):
a = a.encode()
b = self.key
s = b''
if len(a) > len(b):
s += self.XR(a[:len(b)], b) + a[len(b):]
elif len(a) < len(b):
s += self.XR(b[:len(a)], a) + b[len(a):]
return s
def sign_old(self, data):
return md5(self.xor_key(data)).digest()
def sign_new(self, data):
return hmac.new(self.key, data, md5).digest()
def confirm(self, data):
if isinstance(data, str):
data = data.encode('utf-8')
pos_name = data.rfind(b'name=')
pos_role = data.rfind(b'&role=')
pos_sign = data.rfind(b'&sign=')
if pos_role == -1 or pos_sign == -1 or pos_name == -1:
self.request.sendall(b'\nInvalid data!\n')
return
enc_role = data[:pos_sign]
sign = data[pos_sign + 6:]
try:
check = self.decrypt(enc_role, sign)
except Exception:
self.request.sendall(b'\nInvalid data!\n')
if check == b'royal':
self.request.sendall(b'\nFlag here: ' + secret.flag)
elif check == b'guest':
self.request.sendall(b'\nHello peasant!\n')
elif check == None:
self.request.sendall(b'\nYou\'re a intruder!!!\n')
else:
self.request.sendall(b'\nStranger!!!\n')
def parse_qsl(self, query):
m = {}
parts = query.split(b'&')
for part in parts:
key, val = part.split(b'=')
m[key] = val
return m
def main():
server = ThreadedTCPServer((host, port), ThreadedTCPRequestHandler)
server_thread = threading.Thread(target=server.serve_forever)
server_thread.daemon = True
server_thread.start()
print("Server loop running in thread:", server_thread.name)
server_thread.join()
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/ISITDTU/2021/Quals/web/Ez_Get_Flag/files/app.py | ctfs/ISITDTU/2021/Quals/web/Ez_Get_Flag/files/app.py | from flask import Flask, render_template, render_template_string, url_for, redirect, session, request
from lib import sql, waf,captcha
app = Flask(__name__)
app.config['SECRET_KEY'] = '[CENSORED]'
HOST = '0.0.0.0'
PORT = '5000'
@app.route('/')
def index():
if 'username' in session:
return redirect(url_for('home'))
return redirect(url_for('login'))
@app.route('/home')
def home():
if 'username' in session:
secret = session['sr']
return render_template('home.html', secret=secret)
return redirect(url_for('login'))
@app.route('/login', methods=['GET','POST'])
def login():
if 'username' in session:
return redirect(url_for('home'))
else:
if request.method == "POST":
username, password = '', ''
username = request.form['username']
password = request.form['password']
if sql.login_check(username,password) > 0 and username == 'admin':
session['username'] = 'admin'
session['check'] = 1
return render_template('home.html')
else:
cc, secret = '', ''
cc = request.form['captcha']
secret = request.form['secret']
if captcha.check_captcha(cc):
session['username'] = 'guest'
session['check'] = 0
session['sr'] = secret
return redirect(url_for('home'))
return render_template('login.html', msg='Ohhhh Noo - Incorrect !')
return render_template('login.html')
@app.route('/register', methods=['GET','POST'])
def register():
if 'usename' in session:
return redirect(url_for('home'))
else:
if request.method == "POST":
username, password = '', ''
username = request.form['username']
password = request.form['password']
if waf.valid_register(username,password):
sql.reg(username,password)
return redirect(url_for('login'))
return render_template('register.html', msg='Registration failed !')
return render_template('register.html')
@app.route('/rate',methods=['GET','POST'])
def rate():
if 'username' not in session:
return redirect(url_for('login'))
else:
if request.method == "POST":
picture = ''
picture = request.form['picture']
if session['username'] == 'admin' and session['check'] == 1:
picture = picture.replace('{{','{').replace('}}','}').replace('>','').replace('#','').replace('<','')
if waf.isValid(picture):
render_template_string(picture)
return 'you are admin you can choose all :)'
else:
_waf = ['{{','+','~','"','_','|','\\','[',']','#','>','<','!','config','==','}}']
for char in _waf:
if char in picture:
picture = picture.replace(char,'')
if waf.check_len(picture):
render_template_string(picture)
return 'you are wonderful ♥'
return render_template('rate.html')
return redirect(url_for('login'))
if __name__ == '__main__':
app.run(HOST,PORT) | python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/ISITDTU/2021/Quals/web/Ez_Get_Flag/files/lib/captcha.py | ctfs/ISITDTU/2021/Quals/web/Ez_Get_Flag/files/lib/captcha.py | SECRET = '[CENSORED]' # this is captcha
CHECK = '203c0617e3bde7ec99b5b657417a75131e3629b8ffdfdbbbbfd02332'
def check_captcha(cc):
msg = b'hello '
msg += cc.encode()
if calculate(msg) == CHECK:
return True
return False
def calculate(msg):
c = []
a = ord(b'[CENSORED]')
b = ord(b'[CENSORED]')
for m in msg:
c.append(a ^ m)
a = (a + b) % 256
return bytes(c).hex() | python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/ISITDTU/2021/Quals/web/Ez_Get_Flag/files/lib/sql.py | ctfs/ISITDTU/2021/Quals/web/Ez_Get_Flag/files/lib/sql.py | import sqlite3
import hashlib
def login_check(username, password):
conn = sqlite3.connect('database/users.db')
row = conn.execute("SELECT * from users where username = ? and password = ?", (username, hashlib.sha1(password.encode()).hexdigest(), )).fetchall()
return len(row)
def reg(username,password):
conn = sqlite3.connect('database/users.db')
row = conn.execute("SELECT username from users where username = ?",(username)).fetchall()
if len(row) < 1:
return "Account exits !!!"
else:
result = conn.execute("INSERT INTO users VALUE (?,?)",(username,hashlib.sha1(password.encode()).hexdigest()))
if result:
return 'Sign Up Success !!!'
else:
return 'Sign Up Failed !!!' | python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/ISITDTU/2021/Quals/web/Ez_Get_Flag/files/lib/waf.py | ctfs/ISITDTU/2021/Quals/web/Ez_Get_Flag/files/lib/waf.py | import string, re
WHITE_LIST = string.ascii_letters + string.digits
BLACK_LIST = [
'class', 'mro', 'base', 'request', 'app',
'sleep', 'add', '+', 'config', 'subclasses', 'format', 'dict', 'get', 'attr', 'globals', 'time', 'read',
'import', 'sys', 'cookies', 'headers', 'doc', 'url', 'encode', 'decode', 'chr', 'ord', 'replace', 'echo',
'pop', 'builtins', 'self', 'template', 'print', 'exec', 'response', 'join', '{}', '%s', '\\', '*', '#', '&']
def valid_register(username, password):
for char in (
username, password):
if char not in WHITE_LIST:
return False
else:
if re.search('^[0-9a-zA-Z]+$', username) or (re.search('^[0-9a-zA-Z]+$', password)):
return False
return True
def countChar(picture):
if picture.count('.') > 1:
return False
if picture.count(',') > 1:
return False
if picture.count(':') > 1:
return False
for i in range(0,len(picture)):
if picture[i] == "'" or picture[i] == '"':
if picture[i+1] == "'" or picture[i+1] == '"':
return False
return True
def check_len(picture):
if len(picture) > 56:
return False
return True
def isValid(picture):
picture = picture.lower()
if countChar(picture) and len(picture) <= 202:
for char in picture:
if char in string.digits:
return False
for i in BLACK_LIST:
if i in picture:
return False
return True
return False | python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/ISITDTU/2024/Quals/crypto/somesomesome/somesomesome.py | ctfs/ISITDTU/2024/Quals/crypto/somesomesome/somesomesome.py | from Crypto.Util.number import getPrime
# usual stuff
p = getPrime(1024)
q = getPrime(1024)
n = p*q
flag = int.from_bytes(b'ISITDTU{--REDACTED--}', byteorder='big')
c = pow(flag, 65537, n)
print(f'{n = }')
print(f'{c = }')
hint = f'{p:x}'
mask = "????????????????????------------------------------------------------------------------------------------------------------???????????????????-----------------------------------------------------------------------------------------------????????????????????"
assert len(hint) == len(mask)
hint = ''.join([m if m=='?' else h for h,m in zip(hint, mask)])
print(f'{hint = }')
"""
n = 9433712610959885375221810446914635069554077729988416135101966896488335918916519539830838955289216290130021191272517930019991721621248444899054351541034332923892257941652667085224780108603880257779781959093176456114319648225694578094151982626852411179914323807364599792545943013213302760312163194490734828969125203970896020957940669210985389661766044622868641480660567350447195287976428652624447259907757873870806721257462272378852232767957215598993114762495243314001555853470285722516904153177100072712186966925976892701061033644762652746251398920428013075797960080528464113185300338330329689079645327410860820791951
c = 2009804438511397417079733026286503900638881746928444488498899210223512456468954912508401690372416355020938623615147808621999573503563538034992489984222522545100195657663832458239477143396964833752320626753495841798293809828935611697686279399323665325423309643778115987715686875845676596553265607980895634535619415143945553533811861834972118606183461386755199862529618793561816720850996969299948170293235277959084201323664075069227260967952723941816413482440790940040264635959043781254422128290619354457119389385035205114010557210338082204418042838070078857135788160433567520598363566825908590558856255481305379407076
hint = '????????????????????cdf63df9bb0b14828e771e85e2ca9cfb1a638d1ccc554c9a49723a12d1a94697b0bbc64cf8a8e7a12937ee3e0049e6613e6452???????????????????008f897fa4b1c04f4e0a2dc73d66ec0b98c5dddf24e10d6d77923cdf4505204eca2979428cf7184433d4a63f3b77fe7????????????????????'
""" | python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/ISITDTU/2024/Quals/crypto/ShareMixer2/chall.py | ctfs/ISITDTU/2024/Quals/crypto/ShareMixer2/chall.py | import random # TODO: heard that this is unsafe but nvm
from Crypto.Util.number import getPrime, bytes_to_long
flag = bytes_to_long(open("flag.txt", "rb").read())
p = getPrime(256)
assert flag < p
l = 32
def share_mixer(xs):
cs = [random.randint(1, p - 1) for _ in range(l - 1)]
cs.append(flag)
# mixy mix
random.shuffle(xs)
random.shuffle(cs)
shares = [sum((c * pow(x, i, p)) % p for i, c in enumerate(cs)) % p for x in xs]
return shares
if __name__ == "__main__":
try:
print(f"{p = }")
queries = input("Gib me the queries: ")
xs = list(map(lambda x: int(x) % p, queries.split()))
if 0 in xs or len(xs) > 32:
print("GUH")
exit(1)
shares = share_mixer(xs)
print(f"{shares = }")
except:
exit(1) | python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/ISITDTU/2024/Quals/crypto/Sign/chall.py | ctfs/ISITDTU/2024/Quals/crypto/Sign/chall.py | #!/usr/bin/env python3
import os
from Crypto.Util.number import *
from Crypto.Signature import PKCS1_v1_5
from Crypto.PublicKey import RSA
from Crypto.Hash import SHA256
flag = b'ISITDTU{aaaaaaaaaaaaaaaaaaaaaaaaaa}'
flag = os.urandom(255 - len(flag)) + flag
def genkey(e=11):
while True:
p = getPrime(1024)
q = getPrime(1024)
if GCD(p-1, e) == 1 and GCD(q-1, e) == 1:
break
n = p*q
d = pow(e, -1, (p-1)*(q-1))
return RSA.construct((n, e, d))
def gensig(key: RSA.RsaKey) -> bytes:
m = os.urandom(256)
h = SHA256.new(m)
s = PKCS1_v1_5.new(key).sign(h)
return s
def getflagsig(key: RSA.RsaKey) -> bytes:
return long_to_bytes(pow(bytes_to_long(flag), key.d, key.n))
key = genkey()
while True:
print(
"""=================
1. Generate random signature
2. Get flag signature
================="""
)
try:
choice = int(input('> '))
if choice == 1:
sig = gensig(key)
print('sig =', sig.hex())
elif choice == 2:
sig = getflagsig(key)
print('sig =', sig.hex())
except Exception as e:
print('huh')
exit(-1)
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/ISITDTU/2024/Quals/crypto/thats_so_random/chall.py | ctfs/ISITDTU/2024/Quals/crypto/thats_so_random/chall.py | import random
flag = random.randbytes(random.randint(13, 1337))
flag += open("flag.txt", "rb").read()
flag += random.randbytes(random.randint(13, 1337))
random.seed(flag)
print(len(flag) < 1337*1.733 and [random.randrange(0, int(0x13371337*1.337)) for _ in range(0x13337)])
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/ISITDTU/2024/Quals/crypto/ShareMixer1/chall.py | ctfs/ISITDTU/2024/Quals/crypto/ShareMixer1/chall.py | import random # TODO: heard that this is unsafe but nvm
from Crypto.Util.number import getPrime, bytes_to_long
flag = bytes_to_long(open("flag.txt", "rb").read())
p = getPrime(256)
assert flag < p
l = 32
def share_mixer(xs):
cs = [random.randint(1, p - 1) for _ in range(l - 1)]
cs.append(flag)
# mixy mix
random.shuffle(xs)
random.shuffle(cs)
shares = [sum((c * pow(x, i, p)) %
p for i, c in enumerate(cs)) % p for x in xs]
return shares
if __name__ == "__main__":
try:
print(f"{p = }")
queries = input("Gib me the queries: ")
xs = list(map(lambda x: int(x) % p, queries.split()))
if 0 in xs or len(xs) > 256:
print("GUH")
exit(1)
shares = share_mixer(xs)
print(f"{shares = }")
except:
exit(1)
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/ISITDTU/2019/Quals/prisonbreak/backend.py | ctfs/ISITDTU/2019/Quals/prisonbreak/backend.py | import time
from subprocess32 import run, STDOUT, PIPE, CalledProcessError
print("5 years in prison! Wanna escape???")
payload = input()[:0xc0].encode('utf-8', 'surrogateescape')
st = time.time()
try:
result = run(['/home/prisonbreak/prisonbreak'], input=payload, stdout=PIPE, stderr=STDOUT, timeout=2, check=True).stdout
except CalledProcessError as e:
pass
while time.time()-st<5:
time.sleep(0.001) | python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/ISITDTU/2023/Quals/crypto/MemeStorage/MemeStorage.py | ctfs/ISITDTU/2023/Quals/crypto/MemeStorage/MemeStorage.py | #!/usr/bin/env python3
import json
import os
from Crypto.Cipher import AES
from Crypto.Util.Padding import pad, unpad
import re
def check_name(password):
if re.fullmatch(r"\w*", password, flags=re.ASCII) and \
re.search(r"\d", password) and \
re.search(r"[a-z]", password):
return True
return False
secret_key = os.urandom(16)
def encrypt_request(meme_name: str):
pt = pad(meme_name.encode(), 16)
cipher = AES.new(secret_key, AES.MODE_ECB)
return cipher.encrypt(pt).hex()
def decrypt_request(meme_id):
ct = bytes.fromhex(meme_id)
cipher = AES.new(secret_key, AES.MODE_ECB)
return unpad(cipher.decrypt(ct), 16).decode()
# My memes!
meme_storage = {}
meme_storage["meme1"] = os.getenv("MEME1", "Haha")
meme_storage["meme2"] = os.getenv("MEME2", "Hihi")
meme_storage["meme3"] = os.getenv("MEME3", "Hoho")
meme_storage["d4rkbruh"] = os.getenv("FLAG", "ISITDTU{dark_dark_bruh_bruh_lmao_test_flag}")
# create secure AES_GCM authenticated user cookie!
def gen_user_cookie(username, nonce=None):
if nonce == None:
nonce = os.urandom(12)
cookie_dict = {}
cookie_dict["username"] = username
cookie_dict["admin_access"] = False
pt = json.dumps(cookie_dict).encode()
cipher = AES.new(secret_key, AES.MODE_GCM, nonce=nonce)
ct, tag = cipher.encrypt_and_digest(pt)
cookie = nonce.hex() + "." + ct.hex() + "." + tag.hex()
return cookie
def decode_cookie(cookie):
cookie = cookie.split(".")
nonce, ct, tag = [bytes.fromhex(x) for x in cookie]
cipher = AES.new(secret_key, AES.MODE_GCM, nonce=nonce)
pt = cipher.decrypt_and_verify(ct, tag).decode()
cookie_dict = json.loads(pt)
return cookie_dict
def check_cookie(cookie):
if cookie == None:
return {"error": "No cookie set"}
try:
cookie_dict = decode_cookie(cookie)
assert "username" in cookie_dict and "admin_access" in cookie_dict
except:
return {"error": "Something went wrong with your cookie"}
return cookie_dict
def register(args):
username = args.get('username')
if username == None:
return {"error": "attempted to register without username"}
# user should control it , right?
nonce = args.get('nonce')
if nonce is None:
cookie = gen_user_cookie(username)
else:
nonce = bytes.fromhex(nonce)
assert len(nonce) == 16
cookie = gen_user_cookie(username, nonce)
return {"username": username, "cookie": cookie}
def shareMeme(args: dict):
user_cookie = args.get('cookie')
cookie_dict = check_cookie(user_cookie)
if "error" in cookie_dict:
return cookie_dict
meme_name = args.get("meme_name")
if meme_name == None or not isinstance(meme_name, str):
return {"error": "How can you add a meme if you don't have a name?"}
if "d4rkbruh" in meme_name or not check_name(meme_name):
return {"error": "Nice Try, Hacker!"}
if meme_name in meme_storage:
return {"error": "Name collision detected"}
meme = args.get("meme")
if meme == None:
return {"error": "How can you add a meme if you don't have it?"}
meme_storage[meme_name] = str(meme)
return {"id": encrypt_request(meme_name)}
def viewMeme(args):
user_cookie = args.get('cookie')
cookie_dict = check_cookie(user_cookie)
if "error" in cookie_dict:
return cookie_dict
duck_id = args.get('id')
try:
meme_name = decrypt_request(duck_id)
except:
return {"error": "something went wrong during decryption of your duck id"}
if meme_name not in meme_storage:
return {"error": "Lol! I don't remember that we have it.!"}
access_level = cookie_dict["admin_access"]
if meme_name == "d4rkbruh" and not access_level:
return {"error": "This meme is too d4rk for you"}
return {"meme": meme_storage.get(meme_name, )}
def menu():
print("""
1. Register
2. Add Meme
3. View Meme
4. Exit
""")
return int(input("> "))
actions = [register, shareMeme, viewMeme]
def main():
try:
if os.system("python3 PoW.py") != 0:
raise Exception("PoW failed")
while True:
choice = menu()
if choice < 1 or choice >= 4:
raise Exception("Exit")
args = json.loads(input("Args: "))
resp = json.dumps(actions[choice-1](args))
print(resp)
except:
print("Bye")
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/ISITDTU/2023/Quals/crypto/MagicPrime/MagicPrime_new.py | ctfs/ISITDTU/2023/Quals/crypto/MagicPrime/MagicPrime_new.py | import os
import signal
from random import SystemRandom
from Crypto.Util.number import isPrime, bytes_to_long
random = SystemRandom()
def challenge():
signal.alarm(30)
salt = bytes_to_long(os.urandom(20)) | 1
print(f"{salt = }")
P = int(input("P: "))
assert P.bit_length() >= 4096 # Nist recommended
assert P.bit_length() <= 16384 # I don't like big food
assert P % 2**160 == salt
assert isPrime(P)
g = random.randint(0, P-1)
x = random.randint(0, P-2)
public = pow(g, x, P)
print(f"{g = }")
print(f"{public = }")
if pow(g, int(input("x: ")), P) == public:
print("Flag:", os.getenv("FLAG", "ISITDTU{dark_dark_bruh_bruh_lmao_test_flag}"))
def timeout_handler(sig, frame):
print('Time out!')
exit(0)
if __name__ == "__main__":
if os.system("python3 PoW.py") != 0:
exit(1)
signal.signal(signal.SIGALRM, timeout_handler)
try:
challenge()
except:
pass
finally:
print("Bye") | python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/ISITDTU/2023/Quals/crypto/d_low/chall.py | ctfs/ISITDTU/2023/Quals/crypto/d_low/chall.py | from Crypto.Util.number import *
from FLAG import flag
flag = bytes_to_long(flag)
p = getPrime(1024)
q = getPrime(1024)
n = p*q
e = 12721
c = pow(flag, e, n)
print(f"{n = }")
print(f"{c = }")
# hints :)
def hx(x):
return hex(x)[2:]
d = pow(e, -1, (p-1)*(q-1))
print(hx(d)[-64:])
print(hx(p)[:64])
print(hx(p)[96:161])
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/ISITDTU/2023/Quals/crypto/homemade_primes/chall.py | ctfs/ISITDTU/2023/Quals/crypto/homemade_primes/chall.py | from Crypto.Util.number import bytes_to_long, isPrime
from functools import reduce
from secret import FLAG, SEED
class LFSR:
def __init__(self, seed: int) -> None:
assert 0 <= seed < 2**32, "Please provide a 32-bit seed."
self.__state = list(map(int, "{:032b}".format(seed)))
self.__taps = [31, 21, 1, 0]
def __sum(self, v: list[int]) -> int:
return reduce(lambda x, y: x^y, v, 0)
def __tap(self) -> int:
self.__state = [self.__sum([self.__state[idx] for idx in self.__taps])] + self.__state
ret = self.__state.pop()
return ret
def getrandbits(self, n: int) -> int:
ret = 0
for _ in range(n):
ret <<= 1
ret += self.__tap()
return ret
def getrandprime(self, n: int) -> int:
while True:
ret = self.getrandbits(n)
if isPrime(ret):
return ret
def chall() -> None:
e = 65537
lfsr = LFSR(SEED)
p = lfsr.getrandprime(1024)
q = lfsr.getrandprime(1024)
n = p * q
m = bytes_to_long(FLAG)
c = pow(m, e, n)
with open("output.txt", "w") as f:
f.write(f"{n = }\n{e = }\n{c = }")
chall() | python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/ISITDTU/2023/Quals/crypto/babyRSA/chall.py | ctfs/ISITDTU/2023/Quals/crypto/babyRSA/chall.py | from Crypto.Util.number import bytes_to_long
from FLAG import flag
p1 = 401327687854144602104262478345650053155149834850813791388612732559616436344229998525081674131271
p2 = 500233813775302774885494989064149819654733094475237733501199023993441312997760959607567274704359
p3 = 969568679903672924738597736880903133415133378800072135853678043226600595571519034043189730269981
e1 = 398119
e2 = 283609
e3 = 272383
c = bytes_to_long(flag)
c = pow(c, e1, p1)
c = pow(c, e2, p2)
c = pow(c, e3, p3)
print(f"{c = }")
# c = 104229015434394780017196823454597012062804737684103834919430099907512793339407667578022877402970
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/ISITDTU/2023/Quals/web/Naruchu/server.py | ctfs/ISITDTU/2023/Quals/web/Naruchu/server.py | #!/usr/local/bin/python
import os
import io
import pickle
from flask import Flask, Response, request, jsonify, session
from waitress import serve
app = Flask(__name__)
app.secret_key = os.environ.get("FLASK_SECRET_KEY", "")
naruchu = {
"Myoboku": {
"des": "You are Nagato, the leader of the criminal organization Akatsuki, seeking to make the world a better place by capturing the legendary beasts of the villages",
"village": ["Konohagakure", "Sunagakure", "Kirigakure", "Kumogakure","Iwagakure"],
"ninja": {
"Pain": "Nagato created Pain after being crippled in battle with Hanzo. Unable to move or act on his own, Nagato controlled six corpses to carry out his will.",
"Sasuke": "Sasuke Uchiha is the second strongest ninja in the Akatsuki organization.",
"Itachi": "Itachi Uchiha is considered a prodigy of the Uchiha clan. Even when he was young, his skills and strength were recognized by everyone.",
"Obito": "Obito was saved and recruited by Madara to join Akatsuki in order to help him carry out his plans.",
"Konan":"Konan is one of the three orphaned children from the Village Hidden in the Rain that Jiraiya adopted and trained",
"other members":"Nhung thang khac cung manh vcl, ke chua het"
}
},
"Konohagakure": {
"des": "Village Hidden Among Tree Leaves",
"village": ["Myoboku","Kirigakure","Kumogakure"],
"ninja": {
"Naruto": "He is often shunned by the Konohagakure villagers, as he is the host of Kurama, the Nine-Tailed Fox that attacked Konoha.",
"Sakura": "Sakura possesses superier strength to unleash her powerful punch towards the opponents when she is enraged by saying Cha!",
"Kakashi": "Kakashi Hatake is the easygoing, smart leader of team 7, consisting of Naruto Uzumaki, Sasuke Uchiha and Sakura Haruno"
},
"Bijuu":{
"Kyubi":"The Nine-Tails (Kyubi) is named Kurama, currently a Tailed Beast belonging to Konohagakure (Leaf Village), and it takes the form of a nine-tailed fox."
}
},
"Sunagakure": {
"des": "The Sand Village is situated amidst high cliffs, with the majority of its terrain being desert, which has led to their agriculture being relatively underdeveloped.",
"village": ["Myoboku","Kirigakure", "Kumogakure","Iwagakure"],
"ninja": {
"onsra": "I will update as soon as possible."
},
"Bijuu":{
"Ichibi":"One-Tail (Ichibi) is named Shukaku, currently a Tailed Beast belonging to Sunagakure (Hidden Sand Village), and it takes the form of a one-tailed raccoon."
}
},
"Kirigakure": {
"des": "The Hidden Mist Village is located on a secluded island, shrouded in mystical mist throughout the year. It is renowned for the Seven Swordsmen of the Mist group.",
"village": ["Myoboku","Konohagakure", "Sunagakure"],
"ninja": {
"onsra": "I will update as soon as possible."
},
"Rokubi":{
"The Six-Tails (Rokubi) is named Saiken, currently a Tailed Beast belonging to Kirigakure (Hidden Mist Village), and it takes the form of a six-tailed slug."
}
},
"Kumogakure": {
"des": "In the past, the Hidden Cloud Village had significant conflicts with the Hidden Leaf Village over the desire to possess the Byakugan eyes of the Hyuga clan.",
"village": ["Myoboku"],
"ninja": {
"onsra": "I will update as soon as possible."
},
"Nibi":{
"The Two-Tails (Nibi) is named Matatabi, currently a Tailed Beast belonging to Kumogakure (Hidden Cloud Village), and it takes the form of a two-tailed cat."
}
},
"Iwagakure": {
"des": "Surrounded by massive rocky mountain ranges, the Stone Village resembles a true fortress, with the majority of its structures constructed from stone.",
"village": ["Myoboku","Konohagakure", "Sunagakure", "Kirigakure"],
"ninja": {
"onsra": "I will update as soon as possible."
},
"Yonbi":{
"The Four-Tails (Yonbi) is named Son Goku, currently a Tailed Beast belonging to Iwagakure (Hidden Stone Village), and it takes the form of a four-tailed monkey."
}
}
}
def get_current_location():
return session.get('current_location', 'Myoboku')
@app.route('/', methods=['GET'])
def index():
return jsonify({"play muzic and submit fl4g keke": "https://www.youtube.com/watch?v=JEPKYHPVP34"})
@app.route('/api/flag', methods=['GET'])
def flag():
return jsonify({"flag_babyimreal": "aHR0cHM6Ly93d3cueW91dHViZS5jb20vd2F0Y2g/dj1ZejlFN0J1S2hHcyZhYl9jaGFubmVsPURaVVNSZWNvcmRz"})
@app.route('/api/move', methods=['POST'])
def move():
data = request.get_json()
move_choice = data.get("move")
current_location = get_current_location()
if move_choice in naruchu[current_location]["village"]:
session['current_location'] = move_choice
return jsonify({"onsra say": f"You move to the {move_choice}. {naruchu[move_choice]['des']}"})
else:
return jsonify({"onsra say": "You can't go that way."})
@app.route('/api/check', methods=['GET'])
def check():
current_location = get_current_location()
naruchu_des = naruchu[current_location]['des']
village = naruchu[current_location]['village']
if "ninja" in naruchu[current_location]:
ninja = naruchu[current_location]['ninja']
return jsonify({"current_location": current_location, "des": naruchu_des, "ninja": [obj for obj in ninja], "village": village})
else:
return jsonify({"current_location": current_location, "des": naruchu_des, "onsra say": "No ninja to check keke.", "village": village})
@app.route('/api/check/<ninja_name>', methods=['GET'])
def check_ninja(ninja_name):
current_location = get_current_location()
if "ninja" in naruchu[current_location] and ninja_name in naruchu[current_location]['ninja']:
ninja_des = naruchu[current_location]['ninja'][ninja_name]
return jsonify({"Ninja": ninja_name, "des": ninja_des})
else:
return jsonify({"onsra say": f"{ninja_name} will give you flag!!!!"})
@app.route('/api/savegame', methods=['GET'])
def save_session():
session_data = {
'current_location': get_current_location()
}
memory_stream = io.BytesIO()
pickle.dump(session_data, memory_stream)
response = Response(memory_stream.getvalue(), content_type='application/octet-stream')
response.headers['Content-Disposition'] = 'attachment; filename=filesave.pkl'
return response
@app.route('/api/load', methods=['POST'])
def load_sessionn():
if 'file' not in request.files:
return jsonify({"onsra say": "No input file cant win :D"})
file = request.files['file']
if file:
try:
file_content = file.stream.read()
if b'R' in file_content and b'.' in file_content and len(file_content) < 95:
return jsonify({"onsra say": "Waitttttt !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!"})
if b' ' in file_content:
return jsonify({"onsra say": "Waitttttt !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!"})
if file.filename.endswith('.pkl'):
file_io = io.BytesIO(file_content)
pickle.load(file_io)
return jsonify({"onsra say": "OK!! Loaded."})
else:
return jsonify({"onsra say": "Upload a .pkl file plsssssss"})
except:
return jsonify({"onsra say": "Waitttttt !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!"})
if __name__ == '__main__':
if os.environ.get("DEPLOY_ENV") == "ISITDTU":
serve(app, host='0.0.0.0', port=11111)
else:
app.run(debug=False, host="0.0.0.0")
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/ISITDTU/2023/Quals/web/thru_the_filter/src/app.py | ctfs/ISITDTU/2023/Quals/web/thru_the_filter/src/app.py | from flask import Flask, request, render_template_string,redirect
app = Flask(__name__)
def check_payload(payload):
blacklist = ['import', 'request', 'init', '_', 'b', 'lipsum', 'os', 'globals', 'popen', 'mro', 'cycler', 'joiner', 'u','x','g','args', 'get_flashed_messages', 'base', '[',']','builtins', 'namespace', 'self', 'url_for', 'getitem','.','eval','update','config','read','dict']
for bl in blacklist:
if bl in payload:
return True
return False
@app.route("/")
def home():
if request.args.get('c'):
ssti=request.args.get('c')
if(check_payload(ssti)):
return "HOLD UP !!!"
else:
return render_template_string(request.args.get('c'))
else:
return redirect("""/?c={{ 7*7 }}""")
if __name__ == "__main__":
app.run()
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/ISITDTU/2023/Quals/web/Quibuu/app.py | ctfs/ISITDTU/2023/Quals/web/Quibuu/app.py | from flask import Flask, render_template, request
import random
import re
import urllib.parse
import sqlite3
app = Flask(__name__)
def waf_cuc_chill(ans):
# idk, I thought too much of a good thing
ans = urllib.parse.quote(ans)
pattern = re.compile(r'(and|0r|substring|subsrt|if|case|cast|like|>|<|(?:/\%2A.*?\%2A/)|\\|~|\+|-|when|then|order|name|url|;|--|into|limit|update|delete|drop|join|version|not|hex|load_extension|round|random|lower|replace|likely|iif|abs|char|unhex|unicode|trim|offset|count|upper|sqlite_version\(\)|#|true|false|max|\^|length|all|values|0x.*?|left|right|mid|%09|%0A|%20|\t)', re.IGNORECASE)
if pattern.search(ans):
return True
return False
@app.route("/", methods=["GET"])
def index():
ran = random.randint(1, 11)
id, ans= request.args.get("id", default=f"{ran}"), request.args.get("ans", default="")
if not (id and str(id).isdigit() and int(id) >= 1 and int(id) <= 1301):
id = 1
db = sqlite3.connect("hehe.db")
cursor = db.execute(f"SELECT URL FROM QuiBuu WHERE ID = {id}")
img = cursor.fetchone()[0]
if waf_cuc_chill(ans):
return render_template("hack.html")
cursor = db.execute(f"SELECT * FROM QuiBuu where ID = {id} AND Name = '{ans}'")
result = cursor.fetchall()
check = 0
if result != []:
check = 1
elif result == [] and ans != "" :
check = 2
return render_template("index.html", id=id, img=img, ans=ans, check=check)
if __name__ == "__main__":
app.run() | python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/ISITDTU/2022/Quals/crypto/Halloweens_magix/chall.py | ctfs/ISITDTU/2022/Quals/crypto/Halloweens_magix/chall.py | from struct import pack
import random, time
def bytes2matrix(b):
return [list(map(lambda x : x, list(b[i:i+4]))) for i in range(0, len(b), 4)]
def matrix2bytes(m):
return b''.join(map(lambda x : b''.join(map(lambda y : pack('!H', y), x)), m))
def multiply(A,B):
C = [[0 for i in range(4)] for j in range(4)]
for i in range(4):
for j in range(4):
for k in range(4):
C[i][j] += A[i][k] * B[k][j]
return C
def main():
random.seed(time.time())
key = [[random.randint(0,64) for i in range(4)] for j in range(4)]
data = open("flag.png", "rb").read()
out = open("flag.png.enc", 'wb')
for i in range(0, len(data), 16):
cipher = multiply(bytes2matrix(data[i:i+16]), key)
out.write(matrix2bytes(cipher))
out.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/ISITDTU/2022/Quals/crypto/dp_high/chall.py | ctfs/ISITDTU/2022/Quals/crypto/dp_high/chall.py | from Crypto.Util.number import bytes_to_long, getPrime
from SECRET import FLAG
e = getPrime(128)
p = getPrime(1024)
q = getPrime(1024)
n = p * q
c = pow(bytes_to_long(FLAG), e, n)
d = pow(e, -1, (p - 1) * (q - 1))
dp = d % (p - 1)
dp_high = dp >> 205
print(f"{n = }")
print(f"{e = }")
print(f"{c = }")
print(f"{dp_high = }")
"""
n = 12567364021021536069276139071081301321773783503415410122482063162815802632532262852631733566943908930876147793969043836275748336698486250666608690152319164539308799173942970880405365621942480869038031173565836135609803219607046250197218934622063531043191571238635559343630285434743137661162918049427668167596108116123813247574023489647941191092646108484359798178312183857161198552950237016232564837163103701319852345468700518013420435831423503394375188294692875472478236076844354332788143724582596188171429101120375457060113120938123836683660988201443089327738905824392062439034247838606482384586412614406834714072187
e = 302855054306017053454220113135236383717
c = 4891864668386517178603039798367030027018213726546115291869063934737584262406041165900191539273508747711632172112784295237035437771196319634059866827443546543304905951054697225192869131382430968922874630769470296997764149219967748222295126835357440172029624432839432442542014919311928847815297342723030801298870843985791566021870092065045427815279776382037308098892891521540483210118257005467504087917529931331454698510489305696908930175868148922286615019210097019743367080206300230172144203634385318929457785251214794930401419137018353777022634635240368493042317181737723067635048719777029127030494920756862174788399
dp_high = 1528682061327606941204027235121547734644486174542891631806426376137001818312801429494781262718713071077103179054205712581085921624900599327139049785998451580793229375262096344994664540984947702348067124539258177759586538935334513702134177319291812
""" | python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/ISITDTU/2022/Quals/crypto/glitch_in_the_matrix/chall.py | ctfs/ISITDTU/2022/Quals/crypto/glitch_in_the_matrix/chall.py | #!/usr/bin/env python3
from secret import SECRET_BASIS
from secrets import token_hex
import random
import os
assert len(SECRET_BASIS) == len(SECRET_BASIS[0]) == 128
def f(M: list[list[int]], C: list[int]) -> list[int]:
v = [0] * len(M[0])
for c, m in zip(C, M):
if c:
v = [x ^ y for x, y in zip(v, m)]
return v
def random_bits(n: int) -> list[int]:
return list(map(int, bin(random.getrandbits(n))[2:].rjust(n, "0")))
def encrypt(message: bytes) -> str:
M = [b for c in message for b in map(int, "{:08b}".format(c))]
ct = []
for bit in M:
C = random_bits(64)
v = f(SECRET_BASIS[:64], C) if bit else f(SECRET_BASIS[64:], C)
ct.extend(v)
ct = "".join(map(str, ct))
return bytes([int(ct[i:i+8], 2) for i in range(0, len(ct), 8)]).hex()
def decrypt(ciphertext: str) -> bytes:
# TODO: implement this pls
pass
def action_prompt() -> int:
print('''============= MENU =============
1. Have a guess
2. Get ciphertext
3. Change password
4. Quit
================================\n''')
try:
option = int(input("Your option> "))
except:
return None
return option
def chall():
try:
password = token_hex(8)
while True:
option = action_prompt()
if option == 1:
user_password = input("Input your password (hex): ")
if user_password == password:
print(f"Is taking the red pill worth it? Here is the truth that you want: {os.environ['FLAG']}.")
else:
print("Guess you can't escape the matrix after all.")
break
elif option == 2:
print(f"Leaky ciphertext: {encrypt(bytes.fromhex(password))}")
elif option == 3:
print("Generating super secure password ...")
password = token_hex(8)
elif option == 4:
print("Maybe the truth is not that important, huh?")
break
else:
print("Invalid option.")
print("\n")
except:
print("An error occured!")
chall()
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/b01lers/2021/pwn/boiledvm/boiledvm.py | ctfs/b01lers/2021/pwn/boiledvm/boiledvm.py | #!/usr/bin/env python
import struct
import random
import subprocess
import os
import sys
pipe = subprocess.PIPE
PTRACE_TRACEME = 0
PTRACE_PEEKTEXT = 1
PTRACE_PEEKDATA = 2
PTRACE_PEEKUSER = 3
PTRACE_POKETEXT = 4
PTRACE_POKEDATA = 5
PTRACE_POKEUSER = 6
PTRACE_CONT = 7
PTRACE_KILL = 8
PTRACE_SINGLESTEP = 9
PTRACE_GETREGS = 12
PTRACE_SETREGS = 13
PTRACE_GETFPREGS = 14
PTRACE_SETFPREGS = 15
PTRACE_ATTACH = 16
PTRACE_DETACH = 17
PTRACE_GETFPXREGS = 18
PTRACE_SETFPXREGS = 19
PTRACE_SYSCALL = 24
PTRACE_SETOPTIONS = 0x4200
PTRACE_GETEVENTMSG = 0x4201
PTRACE_GETSIGINFO = 0x4202
PTRACE_SETSIGINFO = 0x4203
PTRACE_LISTEN = 0x4208
PTRACE_O_TRACESYSGOOD = 0x00000001
PTRACE_O_TRACEFORK = 0x00000002
PTRACE_O_TRACEVFORK = 0x00000004
PTRACE_O_TRACECLONE = 0x00000008
PTRACE_O_TRACEEXEC = 0x00000010
PTRACE_O_TRACEVFORKDONE = 0x00000020
PTRACE_O_TRACEEXIT = 0x00000040
PTRACE_O_MASK = 0x0000007f
PTRACE_O_TRACESECCOMP = 0x00000080
PTRACE_O_EXITKILL = 0x00100000
PTRACE_O_SUSPEND_SECCOMP= 0x00200000
PTRACE_SEIZE = 0x4206
import ctypes
from ctypes import *
from ctypes import get_errno, cdll
from ctypes.util import find_library
class user_regs_struct(Structure):
_fields_ = (
("r15", c_ulong),
("r14", c_ulong),
("r13", c_ulong),
("r12", c_ulong),
("rbp", c_ulong),
("rbx", c_ulong),
("r11", c_ulong),
("r10", c_ulong),
("r9", c_ulong),
("r8", c_ulong),
("rax", c_ulong),
("rcx", c_ulong),
("rdx", c_ulong),
("rsi", c_ulong),
("rdi", c_ulong),
("orig_rax", c_ulong),
("rip", c_ulong),
("cs", c_ulong),
("eflags", c_ulong),
("rsp", c_ulong),
("ss", c_ulong),
("fs_base", c_ulong),
("gs_base", c_ulong),
("ds", c_ulong),
("es", c_ulong),
("fs", c_ulong),
("gs", c_ulong)
)
libc = CDLL("libc.so.6", use_errno=True)
ptrace = libc.ptrace
ptrace.argtypes = [c_uint, c_uint, c_long, c_long]
ptrace.restype = c_long
ptrace_regs = user_regs_struct()
def pkiller():
from ctypes import cdll
import ctypes
cdll['libc.so.6'].prctl(1, 9)
def parse_status(status):
def num_to_sig(num):
sigs = ["SIGHUP", "SIGINT", "SIGQUIT", "SIGILL", "SIGTRAP", "SIGABRT", "SIGBUS", "SIGFPE", "SIGKILL", "SIGUSR1", "SIGSEGV", "SIGUSR2", "SIGPIPE", "SIGALRM", "SIGTERM", "SIGSTKFLT", "SIGCHLD", "SIGCONT", "SIGSTOP", "SIGTSTP", "SIGTTIN", "SIGTTOU", "SIGURG", "SIGXCPU", "SIGXFSZ", "SIGVTALRM", "SIGPROF", "SIGWINCH", "SIGIO", "SIGPWR", "SIGSYS"]
if num-1 < len(sigs):
return sigs[num-1]
else:
return hex(num)[2:]
status_list = []
status_list.append(hex(status))
ff = [os.WCOREDUMP, os.WIFSTOPPED, os.WIFSIGNALED, os.WIFEXITED, os.WIFCONTINUED]
for f in ff:
if f(status):
status_list.append(f.__name__)
break
else:
status_list.append("")
status_list.append(num_to_sig((status>>8)&0xff))
ss = (status & 0xff0000) >> 16
ptrace_sigs = ["PTRACE_EVENT_FORK", "PTRACE_EVENT_VFORK", "PTRACE_EVENT_CLONE", "PTRACE_EVENT_EXEC", "PTRACE_EVENT_VFORK_DONE", "PTRACE_EVENT_EXIT", "PTRACE_EVENT_SECCOMP"]
if ss >= 1 and ss-1 <= len(ptrace_sigs):
status_list.append(ptrace_sigs[ss-1])
else:
status_list.append(hex(ss)[2:])
return status_list
def readmem(pid, pos=-1, tlen=8):
fd=os.open("/proc/%d/mem" % pid, os.O_RDONLY)
if pos >= 0:
os.lseek(fd, pos, 0)
buf = b""
while True:
cd = os.read(fd, tlen-len(buf))
if(cd==b""):
break
buf += cd
if len(buf)==tlen:
break
os.close(fd)
return buf
def parse_inst(inst):
def convert_v(v, reg):
tcode = b""
if v[0] in [x for x in b"0123456789abcdef"]:
try:
vv = int(v, 16)
except ValueError:
assert False
assert vv>=0
assert vv<=0xffffffff
if reg=="rax":
tcode = b"\x48\xc7\xc0"+struct.pack("<I", vv)
elif reg=="rbx":
tcode = b"\x48\xc7\xc3"+struct.pack("<I", vv)
elif v[0] == ord(b"r"):
try:
rn = int(v[1:], 16)
except ValueError:
assert False
assert rn>=0
assert rn<0x200
tcode += b"\x48\x8D\x8A"+struct.pack("<I", rn*8)
if reg=="rax":
tcode += b"\x48\x8b\x01"
elif reg=="rbx":
tcode += b"\x48\x8b\x19"
elif v[0] == ord(b"["):
try:
rn = int(v[2:], 16)
except ValueError:
assert False
assert rn>=0
assert rn<0x200
tcode += b"\x48\x8D\x8A"+struct.pack("<I", rn*8)
if reg=="rax":
tcode += b"\x48\x8b\x01"
tcode += b"\xcc" + b"\x11" + b"\xcc"*5
tcode += b"\x48\x8B\x04\xc2"
elif reg=="rbx":
tcode += b"\x48\x8b\x19"
tcode += b"\xcc" + b"\x22" + b"\xcc"*5
tcode += b"\x48\x8B\x1c\xda"
else:
assert False
return tcode
def convert_r(v):
tcode = b""
if v[0] == ord(b"r"):
try:
rn = int(v[1:], 16)
except ValueError:
assert False
assert rn>=0
assert rn<0x200
tcode += b"\x48\x8D\x8A"+struct.pack("<I", rn*8)
tcode += b"\x48\x89\x01"
elif v[0] == ord(b"["):
try:
rn = int(v[2:], 16)
except ValueError:
assert False
assert rn>=0
assert rn<0x200
tcode += b"\x48\x8D\x8A"+struct.pack("<I", rn*8)
tcode += b"\x48\x8b\x19"
tcode += b"\xcc" + b"\x22" + b"\xcc"*5
tcode += b"\x48\x89\x04\xDA"
else:
assert False
return tcode
def convert_w(w):
tcode = b""
try:
rn = int(w, 10)
except ValueError:
assert False
assert rn>=0
assert rn<70
tcode += b"\x48\x8D\x9E"+struct.pack("<I", rn*8)
tcode += b"\x48\x8B\x03"
tcode += b"\xcc" + b"\x03" + b"\xcc"*5
return tcode
icode = b""
assert len(inst) < 200
inst = inst.encode("utf-8")
assert len(inst.split()) > 1
op = inst.split()[0]
assert op in [b"m", b"je", b"jb", b"j", b"a", b"s"]
op = inst.split()[0]
if op == b"m":
assert len(inst.split()) == 3
_, r, v1 = inst.split()
icode += convert_v(v1, "rax")
icode += convert_r(r)
elif op == b"a" or op == b"s":
assert len(inst.split()) == 4
_, r, v1, v2 = inst.split()
icode += convert_v(v1, "rax")
icode += convert_v(v2, "rbx")
if op == b"a":
icode += b"\x48\x01\xd8"
elif op == b"s":
icode += b"\x48\x29\xd8"
icode += convert_r(r)
elif op == b"jb":
assert len(inst.split()) == 4
_, w, v1, v2 = inst.split()
icode += convert_v(v1, "rax")
icode += convert_v(v2, "rbx")
icode += b"\x48\x39\xd8"
icode += b"\x0F\x87\x13\x00\x00\x00"
icode += convert_w(w)
icode += b"\xff\xe0"
elif op == b"je":
assert len(inst.split()) == 4
_, w, v1, v2 = inst.split()
icode += convert_v(v1, "rax")
icode += convert_v(v2, "rbx")
icode += b"\x48\x39\xd8"
icode += b"\x0F\x85\x13\x00\x00\x00"
icode += convert_w(w)
icode += b"\xff\xe0"
elif op == b"j":
assert len(inst.split()) == 2
_, w = inst.split()
icode += convert_w(w)
icode += b"\xff\xe0"
else:
assert False
return icode
def main():
print("Welcome to the boilervm!")
ninstr = int(input("how many instructions? "))
assert ninstr>0 and ninstr<=70
aslr = 0x6000000 + (random.randrange(0, pow(2,18)) * 0x1000)
code = b""
code += b"\x48\x31\xC0\xB0\x0B"
code += b"\x48\xC7\xC7" + struct.pack("<I", aslr+0x3000)
code += b"\x48\xBE\x00\x00\x00\x00\xff\x7f\x00\x00"
code += b"\x0F\x05"
code += b"\x90\x48\x31\xC0\x48\x31\xDB\x48\x31\xC9\x48\x31\xD2\x48\x31\xE4\x48\x31\xED\x48\x31\xF6\x48\x31\xFF"
code += b"\x48\xC7\xC2" + struct.pack("<I", aslr+0x2000)
code += b"\x48\xC7\xC6" + struct.pack("<I", aslr+0x1000)
code += b"\x48\xC7\xC7" + struct.pack("<I", aslr)
code += b"\x90"*8
codeplist = []
for _ in range(ninstr):
codeplist.append(len(code))
inst = input()
inst = inst.split("#")[0]
c = parse_inst(inst)
code+=c
code += b"\x90"*4
assert len(code) < 0xfc0
ttcode = b"\x90"
endcode = ttcode + b"\x48\x31\xC0\x48\xFF\xC0\x48\x31\xFF\x48\xFF\xC7\x48\x89\xD6\x48\x31\xD2\xB2\x08\x0F\x05\x48\x31\xC0\xB0\x3C\x48\x31\xFF\x0F\x05"
"\x48\x89\x04\x11"
code = code.ljust(0x1000-len(endcode), b"\x90")
code = code+endcode
assert len(code) == 0x1000
nvalues = int(input("how many values? "))
assert nvalues>0 and nvalues<=4
ivalues = []
regs = b""
for i in range(nvalues):
vv = input()
try:
vv = int(vv, 16)
except ValueError:
assert False
assert vv>=0 and vv<=0xffffffff
regs += struct.pack("<Q", vv)
regs = regs.ljust(0x1000, b"\x00")
pointers = b""
for p in codeplist:
pointers += struct.pack("<Q", aslr+p)
pointers = pointers.ljust(0x1000, b"\x00")
buf = code+pointers+regs
fullargs = ["./stub", hex(aslr)[2:]]
p = subprocess.Popen(fullargs, stdin=pipe, stdout=pipe, stderr=pipe, close_fds=True, preexec_fn=pkiller)
pid = p.pid
opid = pid
pid, status = os.waitpid(-1, 0)
ptrace(PTRACE_SETOPTIONS, pid, 0, PTRACE_O_TRACESECCOMP | PTRACE_O_EXITKILL | PTRACE_O_TRACECLONE | PTRACE_O_TRACEVFORK)
ptrace(PTRACE_CONT, pid, 0, 0)
p.stdin.write(buf)
p.stdin.close()
while True:
pid, status = os.waitpid(-1, 0)
pstatus = parse_status(status)
if pstatus[1] == "WIFEXITED":
break
else:
res = ptrace(PTRACE_GETREGS, pid, 0, ctypes.addressof(ptrace_regs))
v = readmem(pid, ptrace_regs.rip, 1)
if v == b"\x03":
if ptrace_regs.rax not in [aslr + p for p in codeplist]:
print("Invalid jump target!")
sys.exit(1)
elif v == b"\x11":
if ptrace_regs.rax > 0x200:
print("Invalid register number!")
sys.exit(2)
elif v == b"\x22":
if ptrace_regs.rbx > 0x200:
print("Invalid register number!")
sys.exit(2)
prip = ptrace_regs.rip
while True:
vmem = readmem(pid, prip, 5)
if vmem == b"\xcc"*5:
break
prip+=1
ptrace_regs.rip = prip+5
ptrace(PTRACE_SETREGS, pid, 0, ctypes.addressof(ptrace_regs))
ptrace(PTRACE_CONT, pid, 0, 0)
res = p.stdout.read(8)
print("RESULT: " + str(struct.unpack("<Q", res)[0]))
try:
p.kill()
except ProcessLookupError:
pass
if __name__ == "__main__":
sys.exit(main())
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/b01lers/2021/crypto/Cold_War_Gets_Hotter/coldwar.py | ctfs/b01lers/2021/crypto/Cold_War_Gets_Hotter/coldwar.py | #!/usr/bin/env python3
from Crypto.Cipher import AES
from Crypto.Util.Padding import pad
import os
import re
import sys
BASE_DIRECTORY = os.path.dirname(os.path.realpath(__file__))
IU_MANIFESTO = '''
"Indiana, Our Indiana"
Indiana, our Indiana
Indiana, we're all for you!
We will fight for the cream and crimson
For the glory of old IU
Never daunted, we cannot falter
In the battle, we're tried and true
Indiana, our Indiana,
Indiana we're all for you! I-U!
"Indiana Fight"
Fight for the Cream and Crimson,
Loyal sons of our old I. U.
Fight for your Alma Mater,
and the school you love so true.
Fight for old Indiana,
See her victories safely through,
GO! I.U! FIGHT! FIGHT! FIGHT!
For the glory of old I. U.!
'''
MESSAGE_HEADER = '''
WARNING WARNING WARNING WARNING
MISSILE IN FLIGHT
TARGET: Purdue Memorial Union
WARNING WARNING WARNING WARNING
'''
MENU_OPTIONS = '''
Missile Options:
1 - give coordinates to launch missile
2 - alter target coordinates for missile in flight
3 - explode missile in mid flight
4 - exit
> '''
TARGET_LATITUDE = b'???'
TARGET_LONGITUDE = b'???'
KEY = open(os.path.join(BASE_DIRECTORY, 'key'), 'rb').read()
FLAG = open(os.path.join(BASE_DIRECTORY, 'flag.txt'), 'r').read()
def decrypt_message(ciphertext):
if len(ciphertext) < 64 or len(ciphertext) % 16 != 0:
return b''
iv = bytes.fromhex(ciphertext[:32])
cipher = AES.new(KEY, AES.MODE_CBC, iv=iv)
return cipher.decrypt(bytes.fromhex(ciphertext[32:]))
def validate_new_coordinates(new_coordinates):
r = re.compile(b'([-]?[\d]*\.[\d],[-]?[\d]*\.[\d])')
result = r.search(new_coordinates)
if result is None:
return False
match = result.group()
latitude, longitude = match.split(b',')
if latitude == TARGET_LATITUDE and longitude == TARGET_LONGITUDE:
return True
return False
def launch_missle():
sys.stdout.write('\nMissile has already been launched!!\n')
def change_target():
encrypted = input('\nInput encrypted coordinate message:').strip()
decrypted = decrypt_message(encrypted)
if validate_new_coordinates(decrypted):
sys.stdout.write('\nCoordinates altered to IU Memorial Union')
sys.stdout.write('\n' + FLAG + '\n')
else:
sys.stdout.write('\nCoordinates have not been altered\n')
def decommission_missile():
encrypted = input('\nInput encrypted decommission message:').strip()
decrypted = decrypt_message(encrypted)
if decrypted == IU_MANIFESTO:
sys.stdout.write('\nWho would dare betray us!!')
sys.stdout.write('\nYou are not of the cream and crimson!!')
def receive_message():
sys.stdout.write(MESSAGE_HEADER)
while 1:
message_choice = input(MENU_OPTIONS)
if message_choice == '1':
launch_missle()
elif message_choice == '2':
change_target()
elif message_choice == '3':
decommission_missile()
else:
break
receive_message()
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/b01lers/2021/crypto/Unlucky_Strike/server.py | ctfs/b01lers/2021/crypto/Unlucky_Strike/server.py | from Crypto.Random import get_random_bytes
from Crypto.Cipher import AES
import sys, base64, time
from proprietary_data import *
def pkcs7(msg):
padlen = 16 - (len(msg) & 0xf)
return msg + bytes([padlen]*padlen)
def unpkcs7(padded):
while True:
if (len(padded) & 0xf) != 0 or len(padded) == 0: break
padlen = padded[-1]
if padlen < 1 or padlen > 16: break
if any([ padded[-(i + 1)] != padlen for i in range(padlen)]): break
return padded[:(-padlen)]
raise ValueError
class Server:
def __init__(self):
self.key = get_random_bytes(32)
def getTicket(self):
nums = [int.from_bytes(get_random_bytes(2), "big") for i in range(Nballs - 1)]
traw = ",".join([ str(v) for v in nums])
traw = ("numbers:" + traw).encode("ascii")
IV = get_random_bytes(16)
cipher = AES.new(self.key, AES.MODE_CBC, IV)
ticket = IV + cipher.encrypt( pkcs7(traw + b"," + JOKER) )
return base64.b64encode(ticket).decode("ascii")
def redeemTicket(self, ticket):
try:
tenc = base64.b64decode(ticket)
cipher = AES.new(self.key, AES.MODE_CBC, tenc[:16])
traw = cipher.decrypt(tenc[16:])
traw = unpkcs7(traw)
nums = [v for v in traw[traw.index(b"numbers")+8:].split(b",")] [:Nballs]
except (ValueError, IndexError):
print("that is an invalid ticket")
return False
if any([ str(v).encode("ascii") not in nums for v in self.numbers]):
print(f"sorry, that ticket did not win anything")
return False
else:
print(f"**JACKPOT** -> Here is your reward: {FLAG}")
return True
def main(self):
print( " --------------------------------------------\n"
" Welcome to the 2021 B01lers Crypto Town Fair\n"
" --------------------------------------------\n"
"\n"
"Due to popular demand, our Super Jackpot Lottery [TM] returns this year as well. We are\n"
"so confident in our not-entirely-fair algorithm that we are publicly releasing its source\n"
"code. Chances for winning have never been smaller! Prizes have never been bigger!!!\n"
"")
ticket = self.getTicket()
print( "Here is your complimentary raffle ticket:\n"
f"{ticket}")
print( "")
time.sleep(1)
sys.stdout.write(f"Draw commencing... [drumroll]")
sys.stdout.flush()
self.numbers = [int.from_bytes(get_random_bytes(3), "big") for i in range(Nballs)]
time.sleep(4)
print( "... and the winning numbers are:\n"
f"{self.numbers}\n"
"")
while True:
print("Redeem a ticket:")
t = input()
if self.redeemTicket(t): break
if __name__ == "__main__":
server = Server()
server.main()
| 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.