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/SECCON/2022/Quals/crypto/insufficient/problem.py | ctfs/SECCON/2022/Quals/crypto/insufficient/problem.py | from random import randint
from Crypto.Util.number import getPrime, bytes_to_long
from secret import FLAG
# f(x,y,z) = a1*x + a2*x^2 + a3*x^3
# + b1*y + b2*y^2 + b3*y^3
# + c*z + s mod p
def calc_f(coeffs, x, y, z, p):
ret = 0
ret += x * coeffs[0] + pow(x, 2, p) * coeffs[1] + pow(x, 3, p)*coeffs[2]
ret += y * coeffs[3] + pow(y, 2, p) * coeffs[4] + pow(y, 3, p)*coeffs[5]
ret += z * coeffs[6]
ret += coeffs[7]
return ret % p
p = getPrime(512)
# [a1, a2, a3, b1, b2, b3, c, s]
coeffs = [randint(0, 2**128) for _ in range(8)]
key = 0
for coeff in coeffs:
key <<= 128
key ^= coeff
cipher_text = bytes_to_long(FLAG) ^ key
print(cipher_text)
shares = []
for _ in range(4):
x = randint(0, p)
y = randint(0, p)
z = randint(0, 2**128)
w = calc_f(coeffs, x, y, z, p)
packed_share = ((x,y), w)
shares.append(packed_share)
print(p)
print(shares) | python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/SECCON/2022/Quals/crypto/janken_vs_kurenaif/server.py | ctfs/SECCON/2022/Quals/crypto/janken_vs_kurenaif/server.py | import os
import signal
import random
import secrets
FLAG = os.getenv("FLAG", "fake{cast a special spell}")
def janken(a, b):
return (a - b + 3) % 3
signal.alarm(1000)
print("kurenaif: Hi, I'm a crypto witch. Let's a spell battle with me.")
witch_spell = secrets.token_hex(16)
witch_rand = random.Random()
witch_rand.seed(int(witch_spell, 16))
print(f"kurenaif: My spell is {witch_spell}. What about your spell?")
your_spell = input("your spell: ")
your_random = random.Random()
your_random.seed(int(your_spell, 16))
for _ in range(666):
witch_hand = witch_rand.randint(0, 2)
your_hand = your_random.randint(0, 2)
if janken(your_hand, witch_hand) != 1:
print("kurenaif: Could you come here the day before yesterday?")
quit()
print("kurenaif: Amazing! Your spell is very powerful!!")
print(f"kurenaif: OK. The flag is here. {FLAG}")
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/SECCON/2022/Quals/crypto/witches_symmetric_exam/problem.py | ctfs/SECCON/2022/Quals/crypto/witches_symmetric_exam/problem.py | from Crypto.Cipher import AES
from Crypto.Random import get_random_bytes
from Crypto.Util.Padding import pad, unpad
from flag import flag, secret_spell
key = get_random_bytes(16)
nonce = get_random_bytes(16)
def encrypt():
data = secret_spell
gcm_cipher = AES.new(key, AES.MODE_GCM, nonce=nonce)
gcm_ciphertext, gcm_tag = gcm_cipher.encrypt_and_digest(data)
ofb_input = pad(gcm_tag + gcm_cipher.nonce + gcm_ciphertext, 16)
ofb_iv = get_random_bytes(16)
ofb_cipher = AES.new(key, AES.MODE_OFB, iv=ofb_iv)
ciphertext = ofb_cipher.encrypt(ofb_input)
return ofb_iv + ciphertext
def decrypt(data):
ofb_iv = data[:16]
ofb_ciphertext = data[16:]
ofb_cipher = AES.new(key, AES.MODE_OFB, iv=ofb_iv)
try:
m = ofb_cipher.decrypt(ofb_ciphertext)
temp = unpad(m, 16)
except:
return b"ofb error"
try:
gcm_tag = temp[:16]
gcm_nonce = temp[16:32]
gcm_ciphertext = temp[32:]
gcm_cipher = AES.new(key, AES.MODE_GCM, nonce=gcm_nonce)
plaintext = gcm_cipher.decrypt_and_verify(gcm_ciphertext, gcm_tag)
except:
return b"gcm error"
if b"give me key" == plaintext:
your_spell = input("ok, please say secret spell:").encode()
if your_spell == secret_spell:
return flag
else:
return b"Try Harder"
return b"ok"
print(f"ciphertext: {encrypt().hex()}")
while True:
c = input("ciphertext: ")
print(decrypt(bytes.fromhex(c)))
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/SECCON/2022/Quals/crypto/pqpq/problem.py | ctfs/SECCON/2022/Quals/crypto/pqpq/problem.py | from Crypto.Util.number import *
from Crypto.Random import *
from flag import flag
p = getPrime(512)
q = getPrime(512)
r = getPrime(512)
n = p * q * r
e = 2 * 65537
assert n.bit_length() // 8 - len(flag) > 0
padding = get_random_bytes(n.bit_length() // 8 - len(flag))
m = bytes_to_long(padding + flag)
assert m < n
c1p = pow(p, e, n)
c1q = pow(q, e, n)
cm = pow(m, e, n)
c1 = (c1p - c1q) % n
c2 = pow(p - q, e, n)
print(f"e = {e}")
print(f"n = {n}")
# p^e - q^e mod n
print(f"c1 = {c1}")
# (p-q)^e mod n
print(f"c2 = {c2}")
# m^e mod n
print(f"cm = {cm}")
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/SECCON/2022/Quals/crypto/this_is_not_lsb/problem.py | ctfs/SECCON/2022/Quals/crypto/this_is_not_lsb/problem.py | from Crypto.Util.number import *
from flag import flag
p = getStrongPrime(512)
q = getStrongPrime(512)
e = 65537
n = p * q
phi = (p - 1) * (q - 1)
d = pow(e, -1, phi)
print(f"n = {n}")
print(f"e = {e}")
print(f"flag_length = {flag.bit_length()}")
# Oops! encrypt without padding!
c = pow(flag, e, n)
print(f"c = {c}")
# padding format: 0b0011111111........
def check_padding(c):
padding_pos = n.bit_length() - 2
m = pow(c, d, n)
return (m >> (padding_pos - 8)) == 0xFF
while True:
c = int(input("c = "))
print(check_padding(c))
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/SECCON/2022/Quals/crypto/BBB/chall.py | ctfs/SECCON/2022/Quals/crypto/BBB/chall.py | from Crypto.Util.number import bytes_to_long, getPrime
from random import randint
from math import gcd
from secret import FLAG
from os import urandom
assert len(FLAG) < 100
def generate_key(rng, seed):
e = rng(seed)
while True:
for _ in range(randint(10,100)):
e = rng(e)
p = getPrime(1024)
q = getPrime(1024)
phi = (p-1)*(q-1)
if gcd(e, phi) == 1:
break
n = p*q
return (n, e)
def generate_params():
p = getPrime(1024)
a = randint(0, p-1)
return (p,a)
def main():
p,a = generate_params()
print("[+] The parameters of RNG:")
print(f"{a=}")
print(f"{p=}")
b = int(input("[+] Inject [b]ackdoor!!: "))
rng = lambda x: (x**2 + a*x + b) % p
keys = []
seeds = []
for i in range(5):
seed = int(input("[+] Please input seed: "))
seed %= p
if seed in seeds:
print("[!] Same seeds are not allowed!!")
exit()
seeds.append(seed)
n, e = generate_key(rng, seed)
if e <= 10:
print("[!] `e` is so small!!")
exit()
keys.append((n,e))
flag = bytes_to_long(FLAG + urandom(16))
for n,e in keys:
c = pow(flag, e, n)
print("[+] Public Key:")
print(f"{n=}")
print(f"{e=}")
print("[+] Cipher Text:", c)
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/SECCON/2022/Quals/crypto/BBB/secret.py | ctfs/SECCON/2022/Quals/crypto/BBB/secret.py | # dummy flag
FLAG = b"SECCON{this_is_a_dummy_flag_and_don't_submit}" | python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/SECCON/2022/Quals/web/easylfi/web/app.py | ctfs/SECCON/2022/Quals/web/easylfi/web/app.py | from flask import Flask, request, Response
import subprocess
import os
app = Flask(__name__)
def validate(key: str) -> bool:
# E.g. key == "{name}" -> True
# key == "name" -> False
if len(key) == 0:
return False
is_valid = True
for i, c in enumerate(key):
if i == 0:
is_valid &= c == "{"
elif i == len(key) - 1:
is_valid &= c == "}"
else:
is_valid &= c != "{" and c != "}"
return is_valid
def template(text: str, params: dict[str, str]) -> str:
# A very simple template engine
for key, value in params.items():
if not validate(key):
return f"Invalid key: {key}"
text = text.replace(key, value)
return text
@app.after_request
def waf(response: Response):
if b"SECCON" in b"".join(response.response):
return Response("Try harder")
return response
@app.route("/")
@app.route("/<path:filename>")
def index(filename: str = "index.html"):
if ".." in filename or "%" in filename:
return "Do not try path traversal :("
try:
proc = subprocess.run(
["curl", f"file://{os.getcwd()}/public/{filename}"],
capture_output=True,
timeout=1,
)
except subprocess.TimeoutExpired:
return "Timeout"
if proc.returncode != 0:
return "Something wrong..."
return template(proc.stdout.decode(), request.args)
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/SECCON/2022/Quals/web/bffcalc/backend/app.py | ctfs/SECCON/2022/Quals/web/bffcalc/backend/app.py | import cherrypy
class Root(object):
ALLOWED_CHARS = "0123456789+-*/ "
@cherrypy.expose
def default(self, *args, **kwargs):
expr = str(kwargs.get("expr", 42))
if len(expr) < 50 and all(c in self.ALLOWED_CHARS for c in expr):
return str(eval(expr))
return expr
cherrypy.config.update({"engine.autoreload.on": False})
cherrypy.server.unsubscribe()
cherrypy.engine.start()
app = cherrypy.tree.mount(Root())
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/SECCON/2022/Quals/web/bffcalc/bff/app.py | ctfs/SECCON/2022/Quals/web/bffcalc/bff/app.py | import cherrypy
import time
import socket
def proxy(req) -> str:
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.connect(("backend", 3000))
sock.settimeout(1)
payload = ""
method = req.method
path = req.path_info
if req.query_string:
path += "?" + req.query_string
payload += f"{method} {path} HTTP/1.1\r\n"
for k, v in req.headers.items():
payload += f"{k}: {v}\r\n"
payload += "\r\n"
sock.send(payload.encode())
time.sleep(.3)
try:
data = sock.recv(4096)
body = data.split(b"\r\n\r\n", 1)[1].decode()
except (IndexError, TimeoutError) as e:
print(e)
body = str(e)
return body
class Root(object):
indexHtml = open("index.html").read()
@cherrypy.expose
def index(self):
return self.indexHtml
@cherrypy.expose
def default(self, *args, **kwargs):
return proxy(cherrypy.request)
cherrypy.config.update({"engine.autoreload.on": False})
cherrypy.server.unsubscribe()
cherrypy.engine.start()
app = cherrypy.tree.mount(Root())
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/SECCON/2020/Quals/SCSBX_Escape/pow.py | ctfs/SECCON/2020/Quals/SCSBX_Escape/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/SECCON/2020/Quals/kstack/pow.py | ctfs/SECCON/2020/Quals/kstack/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/SECCON/2020/Quals/mlml/env/run.py | ctfs/SECCON/2020/Quals/mlml/env/run.py | #!/usr/bin/env python3.7
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 is_bad_str(code):
code = code.lower()
# I don't like these words :)
for s in ['__', 'open', 'read', '.', '#', 'external', '(*', '[', '{%', '{<', 'include']:
if s in code:
return True
return False
def is_bad(code):
return is_bad_str(code)
place_holder = '/** code **/'
template_file = 'template.ml'
EOF = 'SECCON'
MAX_SIZE = 10000
def main():
print(f'Give me the source code(size < {MAX_SIZE}). EOF word is `{EOF}\'')
size = 0
code = ''
while True:
s = sys.stdin.readline()
size += len(s)
if size > MAX_SIZE:
print('too long')
return False
idx = s.find(EOF)
if idx < 0:
code += s
else:
code += s[:idx]
break
if is_bad(code):
print('bad code')
return False
with open(template_file, 'r') as f:
template = f.read()
filename = '/prog/prog.ml'
with open(filename, 'w') as f:
f.write(template.replace(place_holder, code))
os.system(f'timeout --foreground -k 20s 15s ocamlopt {filename} -o /tmp/prog && timeout --foreground -k 10s 5s /tmp/prog')
main()
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/SECCON/2020/Quals/Yet2AnotherPySandbox/run.py | ctfs/SECCON/2020/Quals/Yet2AnotherPySandbox/run.py | #!/usr/bin/env python2.7
from sys import modules
del modules['os']
del modules['sys']
del modules
keys = list(__builtins__.__dict__.keys())
EVAL = eval
LEN = len
RAW_INPUT = raw_input
TRUE = True
FALSE = False
TYPE = type
INT = int
for k in keys:
if k not in []: # Goodbye :)
del __builtins__.__dict__[k]
def print_eval_result(x):
if TYPE(x) != INT:
print('wrong program')
return
print(x)
def check_eval_str(s):
s = s.lower()
if LEN(s) > 0x1000:
return FALSE
# no need to block `eval`, but I'm not sure about others :(
for x in ['__', 'module', 'class', 'globals', 'os', 'import']:
if x in s:
return FALSE
return TRUE
def sandboxed_eval(s):
print_eval_result = None
check_eval_str = None
sandboxed_eval = None
evaluator = None
return EVAL(s)
def evaluator():
print('Welcome to yet yet another sandboxed python evaluator!')
print('Give me an expression (ex: 1+2): ')
s = RAW_INPUT('> ').lower()
if check_eval_str(s):
print_eval_result(sandboxed_eval(s))
else:
print('Invalid input')
evaluator()
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/SECCON/2020/Quals/pincette/src/server/server.py | ctfs/SECCON/2020/Quals/pincette/src/server/server.py | #!/usr/bin/env python3
import subprocess
import tempfile
import sys
import shutil
import base64
import os
import pwd
import grp
import signal
ORIGINAL_LIBC = '/lib/x86_64-linux-musl/libc.so'
PIN_PATH = '/opt/pin/pin'
PINCETTE_DIR = '/opt/pincette'
DIRNAME_PREFIX = 'lib_'
IBT_PATH = '/opt/pincette/ibt.so'
def drop_privileges():
os.setgid(grp.getgrnam('nogroup').gr_gid)
os.setuid(pwd.getpwnam('nobody').pw_uid)
def timeout(signum, frame):
raise IOError
def main():
signal.signal(signal.SIGALRM, timeout)
os.chdir(PINCETTE_DIR)
with tempfile.TemporaryDirectory(prefix=DIRNAME_PREFIX, dir=PINCETTE_DIR) as dirname:
# get user input
signal.alarm(10)
baseaddr = int(input('Enter baseaddr of libc: '), 0)
payload = base64.decodebytes(input("Enter base64 payload: ").encode())
signal.alarm(0)
# make copy of libc
os.chmod(dirname, 0o755)
shutil.copy(ORIGINAL_LIBC, dirname);
# modify baseaddr of libc
rslt = subprocess.run(
['/usr/sbin/prelink', '-r', '0x%x' % baseaddr,dirname+'/libc.so'],
stdout=subprocess.PIPE, stderr=subprocess.STDOUT, check=False)
if rslt.returncode != 0:
sys.stdout.write(rslt.stdout.decode())
sys.exit(-1)
# execute vuln with modified libc
env = { 'LD_LIBRARY_PATH': dirname, 'LD_USE_LOAD_BIAS': '1'}
cmdline = [ "timeout", "-sKILL", "10",
PIN_PATH, '-logfile', '', '-t', IBT_PATH, '-logfile', '', '--', '/opt/pincette/vuln']
rslt = subprocess.run(cmdline, input=payload, stdout=subprocess.PIPE,
stderr=subprocess.STDOUT, env=env, preexec_fn=drop_privileges, start_new_session=True)
sys.stdout.write(rslt.stdout.decode())
if __name__ == '__main__':
main()
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/SECCON/2020/Quals/YetAnotherPySandbox/run.py | ctfs/SECCON/2020/Quals/YetAnotherPySandbox/run.py | #!/usr/bin/env python2.7
from sys import modules
del modules['os']
del modules['sys']
del modules
keys = list(__builtins__.__dict__.keys())
EVAL = eval
LEN = len
RAW_INPUT = raw_input
TRUE = True
FALSE = False
TYPE = type
INT = int
for k in keys:
if k not in ['False', 'None', 'True', 'bool', 'bytearray', 'bytes', 'chr', 'dict', 'eval', 'exit', 'filter', 'float', 'hash', 'int', 'iter', 'len', 'list', 'long', 'map', 'max', 'ord', 'print', 'range', 'raw_input', 'reduce', 'repr', 'setattr', 'sum', 'type']:
del __builtins__.__dict__[k]
def print_eval_result(x):
if TYPE(x) != INT:
print('wrong program')
return
print(x)
def check_eval_str(s):
s = s.lower()
if LEN(s) > 0x1000:
return FALSE
for x in ['eval', 'exec', '__', 'module', 'class', 'globals', 'os', 'import']:
if x in s:
return FALSE
return TRUE
def sandboxed_eval(s):
print_eval_result = None
check_eval_str = None
sandboxed_eval = None
evaluator = None
return EVAL(s)
def evaluator():
print('Welcome to yet yet another sandboxed python evaluator!')
print('Give me an expression (ex: 1+2): ')
s = RAW_INPUT('> ').lower()
if check_eval_str(s):
print_eval_result(sandboxed_eval(s))
else:
print('Invalid input')
evaluator()
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/SECCON/2020/Quals/encryptor/pow.py | ctfs/SECCON/2020/Quals/encryptor/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/WebArena/2025/rev/Reverse_Eng./shadowgate_challenge.py | ctfs/WebArena/2025/rev/Reverse_Eng./shadowgate_challenge.py | import sys
import random
import math
import functools
import operator
import string
import builtins as __b
AlphaCompute = lambda x: x
BetaProcess = lambda x, y: x + y - y
for Q in range(100):
exec(f'def QuantumFunc_{Q}(a): return a')
GammaList = [lambda x: x for _ in range(50)]
for Z in range(50):
GammaList[Z](Z)
class CoreEngine:
def __init__(self):
self.v = 42
def run(self):
return self.v
def __str__(self):
return str(self.v)
E = CoreEngine()
for _ in range(10):
E.run()
Delta1 = lambda x: x * 1
Delta2 = lambda x: x / 1
Delta3 = lambda x: x + 0
Delta4 = lambda x: x - 0
Delta5 = lambda x: x ** 1
Delta6 = lambda x: x // 1
Delta7 = lambda x: x % 1000000
Delta8 = lambda x: x & 0xFFFFFFFF
Delta9 = lambda x: x | 0
Delta10 = lambda x: x ^ 0
SigmaData = [random.randint(0, 100) for _ in range(100)]
for _ in range(20):
SigmaData = list(map(lambda x: x, SigmaData))
OmegaStr = ''.join([chr(ord('a') + (i % 26)) for i in range(100)])
for _ in range(10):
OmegaStr = OmegaStr[::-1]
ThetaDict = {i: i for i in range(100)}
for _ in range(10):
ThetaDict = dict(ThetaDict)
PhiComp = [x for x in range(100) if x % 2 == 0]
try:
pass
except Exception as e:
pass
PsiLambda = lambda x: (lambda y: y)(x)
def XiRec(n):
if n <= 0:
return 0
return XiRec(n-1)
XiRec(3)
ZETA = 123456
def EtaArgs(*a, **k):
return a, k
EtaArgs(1, 2, 3, a=4, b=5)
import sys as S, math as M, random as R
def LambdaDecorator(f):
def w(*a, **k):
return f(*a, **k)
return w
def _decode(s):return ''.join([chr(int(s[i:i+3]))for i in range(0,len(s),3)])
FLAG_PROMPT=''.join(['%03d'%ord(c)for c in'Enter the flag: '])
WRONG_MSG=''.join(['%03d'%ord(c)for c in'Wrong flag!'])
CORRECT_MSG=''.join(['%03d'%ord(c)for c in'Correct! You passed the ShadowGate.'])
INPUT_SHORT=''.join(['%03d'%ord(c)for c in'Input too short.'])
EXEC_ERROR=''.join(['%03d'%ord(c)for c in'Execution error.'])
@LambdaDecorator
def run_vm(u):
R0=R1=R2=0;pc=0
program=[(1,0),(2,66),(3,4),(4,),(5,),(1,1),(2,55),(3,123),(4,),(5,),(1,2),(2,86),(3,23),(4,),(5,),(1,3),(2,153),(3,222),(4,),(5,),(1,4),(2,66),(3,57),(4,),(5,),(1,5),(2,55),(3,97),(4,),(5,),(1,6),(2,86),(3,27),(4,),(5,),(1,7),(2,153),(3,198),(4,),(5,),(1,8),(2,66),(3,0),(4,),(5,),(1,9),(2,55),(3,86),(4,),(5,),(1,10),(2,86),(3,37),(4,),(5,),(1,11),(2,153),(3,252),(4,),(5,),(1,12),(2,66),(3,38),(4,),(5,),(1,13),(2,55),(3,104),(4,),(5,),(1,14),(2,86),(3,25),(4,),(5,),(1,15),(2,153),(3,251),(4,),(5,),(1,16),(2,66),(3,36),(4,),(5,),(1,17),(2,55),(3,66),(4,),(5,),(1,18),(2,86),(3,37),(4,),(5,),(1,19),(2,153),(3,250),(4,),(5,),(1,20),(2,66),(3,35),(4,),(5,),(1,21),(2,55),(3,67),(4,),(5,),(1,22),(2,86),(3,63),(4,),(5,),(1,23),(2,153),(3,246),(4,),(5,),(1,24),(2,66),(3,44),(4,),(5,),(1,25),(2,55),(3,104),(4,),(5,),(1,26),(2,86),(3,4),(4,),(5,),(1,27),(2,153),(3,252),(4,),(5,),(1,28),(2,66),(3,52),(4,),(5,),(1,29),(2,55),(3,82),(4,),(5,),(1,30),(2,86),(3,36),(4,),(5,),(1,31),(2,153),(3,234),(4,),(5,),(1,32),(2,66),(3,39),(4,),(5,),(1,33),(2,55),(3,104),(4,),(5,),(1,34),(2,86),(3,27),(4,),(5,),(1,35),(2,153),(3,248),(4,),(5,),(1,36),(2,66),(3,49),(4,),(5,),(1,37),(2,55),(3,67),(4,),(5,),(1,38),(2,86),(3,51),(4,),(5,),(1,39),(2,153),(3,235),(4,),(5,),(1,40),(2,66),(3,63),(4,),(5,),(6,)]
l=len(u)
for _ in range(5):pass
while pc<len(program):
i=program[pc];op=i[0];_=(lambda x:x)(op)
if op==0x01:
idx=i[1]
if idx>=l:print(_decode(INPUT_SHORT));return
R0=ord(u[idx]);pc+=1
elif op==0x02:R1=R0^i[1];pc+=1
elif op==0x03:t=i[1];R2=1 if R1==t else 0;pc+=1
elif op==0x04:
if R2!=1:pc+=1
else:pc+=2
elif op==0x05:print(_decode(WRONG_MSG));return
elif op==0x06:print(_decode(CORRECT_MSG));return
for _ in range(3):pass
_=(lambda x:x)(pc);_=(lambda x:x)(R0);_=(lambda x:x)(R1);_=(lambda x:x)(R2)
if __name__=="__main__":
for _ in range(10):pass
try:
u=input(_decode(FLAG_PROMPT)).strip()
for _ in range(5):pass
run_vm(u)
except Exception as e:
for _ in range(3):pass
print(_decode(EXEC_ERROR))
for _ in range(900):
exec(f'LambdaFunc_{_} = lambda x: x')
if _ % 10 == 0:
pass
else:
pass
_ = "obfustication" * (_ % 2)
_ = _ * 1
_ = [_ for _ in range(1)]
_ = {{_: _}}
_ = set([_])
_ = (_,)
_ = (lambda x: x)(_)
def f(x): return x
f(_)
try:
pass
except:
pass
class C: pass
C()
import math
_ = 1 + 1
_ = f"{_}"
_ = True
_ = None
if _ == 0:
continue
else:
break
class Meta(type):
def __new__(cls, name, bases, dct):
return super().__new__(cls, name, bases, dct)
class Confuse(metaclass=Meta):
def __init__(self):
self.x = 0
def __call__(self, *a, **k):
return self.x
def __getitem__(self, k):
return self.x
def __setitem__(self, k, v):
self.x = v
confuser = Confuse()
for _ in range(5):
confuser[_] = _
confuser(_)
f1 = lambda x: (lambda y: (lambda z: z)(y))(x)
f2 = lambda x: f1(f1(f1(x)))
f3 = lambda x: f2(f2(f2(x)))
for _ in range(10):
exec('def fake_func_{}(): return {}'.format(_, _))
eval('1+1')
try:
try:
pass
except:
pass
finally:
pass
except:
pass
class Dummy:
def __enter__(self): return self
def __exit__(self, exc_type, exc_val, exc_tb): return False
with Dummy():
pass
useless_gen = (i for i in range(10))
for _ in useless_gen:
pass
class P:
@property
def x(self):
return 42
p = P(); p.x
def fake(*args, **kwargs):
"""This function does nothing but adds confusion."""
return args, kwargs
fake(1,2,3,a=4)
def import_inside():
import os
return os.name
import_inside()
[setattr(confuser, 'x', i) for i in range(5)]
super_lambda = lambda x: (lambda y: (lambda z: (lambda w: w)(z))(y))(x)
def shadowed_open(open):
return open
shadowed_open(5)
def outer():
x = 0
def inner():
nonlocal x
x += 1
return x
return inner()
outer()
global_var = 0
def g():
global global_var
global_var += 1
g()
def annotated(x: int) -> int:
return x
annotated(5)
def fdefault(x, l=[]):
l.append(x)
return l
fdefault(1)
def funpack(*a, **k):
return a, k
funpack(1,2,3,a=4)
def fyield():
yield from range(2)
for _ in fyield():
pass
def fpass():
...
fpass()
def fassert():
assert True
fassert()
def fdoc(x: int) -> int:
"""Returns x"""
return x
fdoc(1)
def ftry():
try:
return 1
except:
return 2
else:
return 3
ftry()
def fwhile():
i = 0
while i < 1:
i += 1
else:
pass
fwhile()
def ffor():
for i in range(1):
pass
else:
pass
ffor()
def fbreak():
for i in range(2):
if i == 0:
continue
else:
break
fbreak()
def fslice(l):
return l[::-1]
fslice([1,2,3])
def fzip():
return list(zip([1],[2]))
fzip()
def fmap():
return list(map(lambda x: x, [1]))
fmap()
def ffilter():
return list(filter(lambda x: True, [1]))
ffilter()
def fenumerate():
return list(enumerate([1]))
fenumerate()
def freversed():
return list(reversed([1]))
freversed()
def fsorted():
return sorted([2,1])
fsorted()
def fsetcomp():
return {x for x in range(2)}
fsetcomp()
def fdictcomp():
return {x:x for x in range(2)}
fdictcomp()
def fordfun():
return chr(ord('a'))
fordfun()
def ftypes():
return int('1'), str(1), float('1.0')
ftypes()
def fbool():
return bool(1), None
fbool()
def fid():
return id(1), hash(1)
fid()
def fisinstance():
return isinstance(1, int), issubclass(int, object)
fisinstance()
def fgetsetdel():
class A: pass
a = A()
setattr(a, 'x', 1)
getattr(a, 'x')
delattr(a, 'x')
fgetsetdel()
def fdirvars():
class A: pass
a = A()
return dir(a), vars(a)
fdirvars()
def flocalsglobals():
return locals(), globals()
flocalsglobals()
def fsliceobj():
return slice(1,2,3)
fsliceobj()
def fmem():
return memoryview(bytearray(b'abc'))
fmem()
def fcomplex():
return complex(1,2)
fcomplex()
def fpow():
return pow(2,3)
fpow()
def fminmax():
return min(1,2), max(1,2)
fminmax()
def fsum():
return sum([1,2,3])
fsum()
def fabs():
return abs(-1)
fabs()
def fround():
return round(1.234,2)
fround()
def fdivmod():
return divmod(3,2)
fdivmod()
def fallany():
return all([True,True]), any([False,True])
fallany()
def fbytes():
return bytes([65]), bytearray([65])
fbytes()
def fformat():
return format(1, 'x')
fformat()
def frepr():
return repr(1)
frepr()
def fprint():
print('')
fprint()
GammaList = [lambda x: x for _ in range(50)]
for Z in range(50):
GammaList[Z](Z)
class CoreEngine:
def __init__(self):
self.v = 42
def run(self):
return self.v
def __str__(self):
return str(self.v)
E = CoreEngine()
for _ in range(10):
E.run()
Delta1 = lambda x: x * 1
Delta2 = lambda x: x / 1
Delta3 = lambda x: x + 0
Delta4 = lambda x: x - 0
Delta5 = lambda x: x ** 1
Delta6 = lambda x: x // 1
Delta7 = lambda x: x % 1000000
Delta8 = lambda x: x & 0xFFFFFFFF
Delta9 = lambda x: x | 0
Delta10 = lambda x: x ^ 0
Delta1 = lambda x: x * 1
Delta2 = lambda x: x / 1
Delta3 = lambda x: x + 0
Delta4 = lambda x: x - 0
Delta5 = lambda x: x ** 1
Delta6 = lambda x: x // 1
Delta7 = lambda x: x % 1000000
Delta8 = lambda x: x & 0xFFFFFFFF
Delta9 = lambda x: x | 0
Delta10 = lambda x: x ^ 0Delta1 = lambda x: x * 1
Delta2 = lambda x: x / 1
Delta3 = lambda x: x + 0
Delta4 = lambda x: x - 0
Delta5 = lambda x: x ** 1
Delta6 = lambda x: x // 1
Delta7 = lambda x: x % 1000000
Delta8 = lambda x: x & 0xFFFFFFFF
Delta9 = lambda x: x | 0
Delta10 = lambda x: x ^ 0Delta1 = lambda x: x * 1
Delta2 = lambda x: x / 1
Delta3 = lambda x: x + 0
Delta4 = lambda x: x - 0
Delta5 = lambda x: x ** 1
Delta6 = lambda x: x // 1
Delta7 = lambda x: x % 1000000
Delta8 = lambda x: x & 0xFFFFFFFF
Delta9 = lambda x: x | 0
Delta10 = lambda x: x ^ 0Delta1 = lambda x: x * 1
Delta2 = lambda x: x / 1
Delta3 = lambda x: x + 0
Delta4 = lambda x: x - 0
Delta5 = lambda x: x ** 1
Delta6 = lambda x: x // 1
Delta7 = lambda x: x % 1000000
Delta8 = lambda x: x & 0xFFFFFFFF
Delta9 = lambda x: x | 0
Delta10 = lambda x: x ^ 0Delta1 = lambda x: x * 1
Delta2 = lambda x: x / 1
Delta3 = lambda x: x + 0
Delta4 = lambda x: x - 0
Delta5 = lambda x: x ** 1
Delta6 = lambda x: x // 1
Delta7 = lambda x: x % 1000000
Delta8 = lambda x: x & 0xFFFFFFFF
Delta9 = lambda x: x | 0
Delta10 = lambda x: x ^ 0Delta1 = lambda x: x * 1
Delta2 = lambda x: x / 1
Delta3 = lambda x: x + 0
Delta4 = lambda x: x - 0
Delta5 = lambda x: x ** 1
Delta6 = lambda x: x // 1
Delta7 = lambda x: x % 1000000
Delta8 = lambda x: x & 0xFFFFFFFF
Delta9 = lambda x: x | 0
Delta10 = lambda x: x ^ 0Delta1 = lambda x: x * 1
Delta2 = lambda x: x / 1
Delta3 = lambda x: x + 0
Delta4 = lambda x: x - 0
Delta5 = lambda x: x ** 1
Delta6 = lambda x: x // 1
Delta7 = lambda x: x % 1000000
Delta8 = lambda x: x & 0xFFFFFFFF
Delta9 = lambda x: x | 0
Delta10 = lambda x: x ^ 0Delta1 = lambda x: x * 1
Delta2 = lambda x: x / 1
Delta3 = lambda x: x + 0
Delta4 = lambda x: x - 0
Delta5 = lambda x: x ** 1
Delta6 = lambda x: x // 1
Delta7 = lambda x: x % 1000000
Delta8 = lambda x: x & 0xFFFFFFFF
Delta9 = lambda x: x | 0
Delta10 = lambda x: x ^ 0Delta1 = lambda x: x * 1
Delta2 = lambda x: x / 1
Delta3 = lambda x: x + 0
Delta4 = lambda x: x - 0
Delta5 = lambda x: x ** 1
Delta6 = lambda x: x // 1
Delta7 = lambda x: x % 1000000
Delta8 = lambda x: x & 0xFFFFFFFF
Delta9 = lambda x: x | 0
Delta10 = lambda x: x ^ 0Delta1 = lambda x: x * 1
Delta2 = lambda x: x / 1
Delta3 = lambda x: x + 0
Delta4 = lambda x: x - 0
Delta5 = lambda x: x ** 1
Delta6 = lambda x: x // 1
Delta7 = lambda x: x % 1000000
Delta8 = lambda x: x & 0xFFFFFFFF
Delta9 = lambda x: x | 0
Delta10 = lambda x: x ^ 0Delta1 = lambda x: x * 1
Delta2 = lambda x: x / 1
Delta3 = lambda x: x + 0
Delta4 = lambda x: x - 0
Delta5 = lambda x: x ** 1
Delta6 = lambda x: x // 1
Delta7 = lambda x: x % 1000000
Delta8 = lambda x: x & 0xFFFFFFFF
Delta9 = lambda x: x | 0
Delta10 = lambda x: x ^ 0Delta1 = lambda x: x * 1
Delta2 = lambda x: x / 1
Delta3 = lambda x: x + 0
Delta4 = lambda x: x - 0
Delta5 = lambda x: x ** 1
Delta6 = lambda x: x // 1
Delta7 = lambda x: x % 1000000
Delta8 = lambda x: x & 0xFFFFFFFF
Delta9 = lambda x: x | 0
Delta10 = lambda x: x ^ 0
SigmaData = [random.randint(0, 100) for _ in range(100)]
for _ in range(20):
SigmaData = list(map(lambda x: x, SigmaData))
OmegaStr = ''.join([chr(ord('a') + (i % 26)) for i in range(100)])
for _ in range(10):
OmegaStr = OmegaStr[::-1]
ThetaDict = {i: i for i in range(100)}
for _ in range(10):
ThetaDict = dict(ThetaDict)
PhiComp = [x for x in range(100) if x % 2 == 0]
try:
pass
except Exception as e:
pass
PsiLambda = lambda x: (lambda y: y)(x)
def XiRec(n):
if n <= 0:
return 0
return XiRec(n-1)
XiRec(3)
ZETA = 123456
def EtaArgs(*a, **k):
return a, k
EtaArgs(1, 2, 3, a=4, b=5)
import sys as S, math as M, random as R
def LambdaDecorator(f):
def w(*a, **k):
return f(*a, **k)
return w
def _decode(s):return ''.join([chr(int(s[i:i+3]))for i in range(0,len(s),3)])
FLAG_PROMPT=''.join(['%03d'%ord(c)for c in'Enter the flag: '])
WRONG_MSG=''.join(['%03d'%ord(c)for c in'Wrong flag!'])
CORRECT_MSG=''.join(['%03d'%ord(c)for c in'Correct! You passed the ShadowGate.'])
INPUT_SHORT=''.join(['%03d'%ord(c)for c in'Input too short.'])
EXEC_ERROR=''.join(['%03d'%ord(c)for c in'Execution error.'])
@LambdaDecorator
def run_vm(u):
R0=R1=R2=0;pc=0
program=[(1,2),(2,63),(3,6),(4,0),(5,0),(0,1),(5,55),(3,123),(4,),(5,),(1,2),(2,86),(3,23),(4,),(5,),(1,3),(2,153),(3,222),(4,),(5,),(1,4),(2,66),(3,57),(4,),(5,),(1,5),(2,55),(3,97),(4,),(5,),(1,6),(2,86),(3,27),(4,),(5,),(1,7),(2,153),(3,198),(4,),(5,),(1,8),(2,66),(3,0),(4,),(5,),(1,9),(2,55),(3,86),(4,),(5,),(1,10),(2,86),(3,37),(4,),(5,),(1,11),(2,153),(3,252),(4,),(5,),(1,12),(2,66),(3,38),(4,),(5,),(1,13),(2,55),(3,104),(4,),(5,),(1,14),(2,86),(3,25),(4,),(5,),(1,15),(2,153),(3,251),(4,),(5,),(1,16),(2,66),(3,36),(4,),(5,),(1,17),(2,55),(3,66),(4,),(5,),(1,18),(2,86),(3,37),(4,),(5,),(1,19),(2,153),(3,250),(4,),(5,),(1,20),(2,66),(3,35),(4,),(5,),(1,21),(2,55),(3,67),(4,),(5,),(1,22),(2,86),(3,63),(4,),(5,),(1,23),(2,153),(3,246),(4,),(5,),(1,24),(2,66),(3,44),(4,),(5,),(1,25),(2,55),(3,104),(4,),(5,),(1,26),(2,86),(3,4),(4,),(5,),(1,27),(2,153),(3,252),(4,),(5,),(1,28),(2,66),(3,52),(4,),(5,),(1,29),(2,55),(3,82),(4,),(5,),(1,30),(2,86),(3,36),(4,),(5,),(1,31),(2,153),(3,234),(4,),(5,),(1,32),(2,66),(3,39),(4,),(5,),(1,33),(2,55),(3,104),(4,),(5,),(1,34),(2,86),(3,27),(4,),(5,),(1,35),(2,153),(3,248),(4,),(5,),(1,36),(2,66),(3,49),(4,),(5,),(1,37),(2,55),(3,67),(4,),(5,),(1,38),(2,86),(3,51),(4,),(5,),(1,39),(2,153),(3,235),(4,),(5,),(1,40),(2,66),(3,63),(4,),(5,),(6,)]
l=len(u)
for _ in range(5):pass
while pc<len(program):
i=program[pc];op=i[0];_=(lambda x:x)(op)
if op==0x01:
idx=i[1]
if idx>=l:print(_decode(INPUT_SHORT));return
R0=ord(u[idx]);pc+=1
elif op==0x02:R1=R0^i[1];pc+=1
elif op==0x03:t=i[1];R2=1 if R1==t else 0;pc+=1
elif op==0x04:
if R2!=1:pc+=1
else:pc+=2
elif op==0x05:print(_decode(WRONG_MSG));return
elif op==0x06:print(_decode(CORRECT_MSG));return
for _ in range(3):pass
_=(lambda x:x)(pc);_=(lambda x:x)(R0);_=(lambda x:x)(R1);_=(lambda x:x)(R2)
if __name__=="__main__":
for _ in range(10):pass
try:
u=input(_decode(FLAG_PROMPT)).strip()
for _ in range(5):pass
run_vm(u)
except Exception as e:
for _ in range(3):pass
print(_decode(EXEC_ERROR))
for _ in range(900):
exec(f'LambdaFunc_{_} = lambda x: x')
if _ % 10 == 0:
pass
else:
pass
_ = "obfustication" * (_ % 2)
_ = _ * 1
_ = [_ for _ in range(1)]
_ = {{_: _}}
_ = set([_])
_ = (_,)
_ = (lambda x: x)(_)
def f(x): return x
f(_)
try:
pass
except:
pass
class C: pass
C()
import math
_ = 1 + 1
_ = f"{_}"
_ = True
_ = None
if _ == 0:
continue
else:
break
class Meta(type):
def __new__(cls, name, bases, dct):
return super().__new__(cls, name, bases, dct)
class Confuse(metaclass=Meta):
def __init__(self):
self.x = 0
def __call__(self, *a, **k):
return self.x
def __getitem__(self, k):
return self.x
def __setitem__(self, k, v):
self.x = v
confuser = Confuse()
for _ in range(5):
confuser[_] = _
confuser(_)
f1 = lambda x: (lambda y: (lambda z: z)(y))(x)
f2 = lambda x: f1(f1(f1(x)))
f3 = lambda x: f2(f2(f2(x)))
for _ in range(10):
exec('def fake_func_{}(): return {}'.format(_, _))
eval('1+1')
try:
try:
pass
except:
pass
finally:
pass
except:
pass
class Dummy:
def __enter__(self): return self
def __exit__(self, exc_type, exc_val, exc_tb): return False
with Dummy():
pass
useless_gen = (i for i in range(10))
for _ in useless_gen:
pass
class P:
@property
def x(self):
return 42
p = P(); p.x
def fake(*args, **kwargs):
"""This function does nothing but adds confusion."""
return args, kwargs
fake(1,2,3,a=4)
def import_inside():
import os
return os.name
import_inside()
[setattr(confuser, 'x', i) for i in range(5)]
super_lambda = lambda x: (lambda y: (lambda z: (lambda w: w)(z))(y))(x)
def shadowed_open(open):
return open
shadowed_open(5)
def outer():
x = 0
def inner():
nonlocal x
x += 1
return x
return inner()
outer()
global_var = 0
def g():
global global_var
global_var += 1
g()
def annotated(x: int) -> int:
return x
annotated(5)
def fdefault(x, l=[]):
l.append(x)
return l
fdefault(1)
def funpack(*a, **k):
return a, k
funpack(1,2,3,a=4)
def fyield():
yield from range(2)
for _ in fyield():
pass
def fpass():
...
fpass()
def fassert():
assert True
fassert()
def fdoc(x: int) -> int:
"""Returns x"""
return x
fdoc(1)
def ftry():
try:
return 1
except:
return 2
else:
return 3
ftry()
def fwhile():
i = 0
while i < 1:
i += 1
else:
pass
fwhile()
def ffor():
for i in range(1):
pass
else:
pass
ffor()
def fbreak():
for i in range(2):
if i == 0:
continue
else:
break
fbreak()
def fslice(l):
return l[::-1]
fslice([1,2,3])
def fzip():
return list(zip([1],[2]))
fzip()
def fmap():
return list(map(lambda x: x, [1]))
fmap()
def ffilter():
return list(filter(lambda x: True, [1]))
ffilter()
def fenumerate():
return list(enumerate([1]))
fenumerate()
def freversed():
return list(reversed([1]))
freversed()
def fsorted():
return sorted([2,1])
fsorted()
def fsetcomp():
return {x for x in range(2)}
fsetcomp()
def fdictcomp():
return {x:x for x in range(2)}
fdictcomp()
def fordfun():
return chr(ord('a'))
fordfun()
def ftypes():
return int('1'), str(1), float('1.0')
ftypes()
def fbool():
return bool(1), None
fbool()
def fid():
return id(1), hash(1)
fid()
def fisinstance():
return isinstance(1, int), issubclass(int, object)
fisinstance()
def fgetsetdel():
class A: pass
a = A()
setattr(a, 'x', 1)
getattr(a, 'x')
delattr(a, 'x')
fgetsetdel()
GammaList = [lambda x: x for _ in range(50)]
for Z in range(50):
GammaList[Z](Z)
class CoreEngine:
def __init__(self):
self.v = 42
def run(self):
return self.v
def __str__(self):
return str(self.v)
E = CoreEngine()
for _ in range(10):
E.run()
Delta1 = lambda x: x * 1
Delta2 = lambda x: x / 1
Delta3 = lambda x: x + 0
Delta4 = lambda x: x - 0
Delta5 = lambda x: x ** 1
Delta6 = lambda x: x // 1
Delta7 = lambda x: x % 1000000
Delta8 = lambda x: x & 0xFFFFFFFF
Delta9 = lambda x: x | 0
Delta10 = lambda x: x ^ 0
SigmaData = [random.randint(0, 100) for _ in range(100)]
for _ in range(20):
SigmaData = list(map(lambda x: x, SigmaData))
OmegaStr = ''.join([chr(ord('a') + (i % 26)) for i in range(100)])
for _ in range(10):
OmegaStr = OmegaStr[::-1]
ThetaDict = {i: i for i in range(100)}
for _ in range(10):
ThetaDict = dict(ThetaDict)
PhiComp = [x for x in range(100) if x % 2 == 0]
try:
pass
except Exception as e:
pass
PsiLambda = lambda x: (lambda y: y)(x)
def XiRec(n):
if n <= 0:
return 0
return XiRec(n-1)
XiRec(3)
ZETA = 123456
def EtaArgs(*a, **k):
return a, k
EtaArgs(1, 2, 3, a=4, b=5)
import sys as S, math as M, random as R
def LambdaDecorator(f):
def w(*a, **k):
return f(*a, **k)
return w
def _decode(s):return ''.join([chr(int(s[i:i+3]))for i in range(0,len(s),3)])
FLAG_PROMPT=''.join(['%03d'%ord(c)for c in'Enter the flag: '])
WRONG_MSG=''.join(['%03d'%ord(c)for c in'Wrong flag!'])
CORRECT_MSG=''.join(['%03d'%ord(c)for c in'Correct! You passed the ShadowGate.'])
INPUT_SHORT=''.join(['%03d'%ord(c)for c in'Input too short.'])
EXEC_ERROR=''.join(['%03d'%ord(c)for c in'Execution error.'])
def _decode(s):return ''.join([chr(int(s[i:i+3]))for i in range(0,len(s),3)])
FLAG_PROMPT=''.join(['%03d'%ord(c)for c in'Enter the flag: '])
WRONG_MSG=''.join(['%03d'%ord(c)for c in'Wrong flag!'])
CORRECT_MSG=''.join(['%03d'%ord(c)for c in'Correct! You passed the ShadowGate.'])
INPUT_SHORT=''.join(['%03d'%ord(c)for c in'Input too short.'])
EXEC_ERROR=''.join(['%03d'%ord(c)for c in'Execution error.'])def _decode(s):return ''.join([chr(int(s[i:i+3]))for i in range(0,len(s),3)])
FLAG_PROMPT=''.join(['%03d'%ord(c)for c in'Enter the flag: '])
WRONG_MSG=''.join(['%03d'%ord(c)for c in'Wrong flag!'])
CORRECT_MSG=''.join(['%03d'%ord(c)for c in'Correct! You passed the ShadowGate.'])
INPUT_SHORT=''.join(['%03d'%ord(c)for c in'Input too short.'])
EXEC_ERROR=''.join(['%03d'%ord(c)for c in'Execution error.'])def _decode(s):return ''.join([chr(int(s[i:i+3]))for i in range(0,len(s),3)])
FLAG_PROMPT=''.join(['%03d'%ord(c)for c in'Enter the flag: '])
WRONG_MSG=''.join(['%03d'%ord(c)for c in'Wrong flag!'])
CORRECT_MSG=''.join(['%03d'%ord(c)for c in'Correct! You passed the ShadowGate.'])
INPUT_SHORT=''.join(['%03d'%ord(c)for c in'Input too short.'])
EXEC_ERROR=''.join(['%03d'%ord(c)for c in'Execution error.'])def _decode(s):return ''.join([chr(int(s[i:i+3]))for i in range(0,len(s),3)])
FLAG_PROMPT=''.join(['%03d'%ord(c)for c in'Enter the flag: '])
WRONG_MSG=''.join(['%03d'%ord(c)for c in'Wrong flag!'])
CORRECT_MSG=''.join(['%03d'%ord(c)for c in'Correct! You passed the ShadowGate.'])
INPUT_SHORT=''.join(['%03d'%ord(c)for c in'Input too short.'])
EXEC_ERROR=''.join(['%03d'%ord(c)for c in'Execution error.'])def _decode(s):return ''.join([chr(int(s[i:i+3]))for i in range(0,len(s),3)])
FLAG_PROMPT=''.join(['%03d'%ord(c)for c in'Enter the flag: '])
WRONG_MSG=''.join(['%03d'%ord(c)for c in'Wrong flag!'])
CORRECT_MSG=''.join(['%03d'%ord(c)for c in'Correct! You passed the ShadowGate.'])
INPUT_SHORT=''.join(['%03d'%ord(c)for c in'Input too short.'])
EXEC_ERROR=''.join(['%03d'%ord(c)for c in'Execution error.'])def _decode(s):return ''.join([chr(int(s[i:i+3]))for i in range(0,len(s),3)])
FLAG_PROMPT=''.join(['%03d'%ord(c)for c in'Enter the flag: '])
WRONG_MSG=''.join(['%03d'%ord(c)for c in'Wrong flag!'])
CORRECT_MSG=''.join(['%03d'%ord(c)for c in'Correct! You passed the ShadowGate.'])
INPUT_SHORT=''.join(['%03d'%ord(c)for c in'Input too short.'])
EXEC_ERROR=''.join(['%03d'%ord(c)for c in'Execution error.'])def _decode(s):return ''.join([chr(int(s[i:i+3]))for i in range(0,len(s),3)])
FLAG_PROMPT=''.join(['%03d'%ord(c)for c in'Enter the flag: '])
WRONG_MSG=''.join(['%03d'%ord(c)for c in'Wrong flag!'])
CORRECT_MSG=''.join(['%03d'%ord(c)for c in'Correct! You passed the ShadowGate.'])
INPUT_SHORT=''.join(['%03d'%ord(c)for c in'Input too short.'])
EXEC_ERROR=''.join(['%03d'%ord(c)for c in'Execution error.'])def _decode(s):return ''.join([chr(int(s[i:i+3]))for i in range(0,len(s),3)])
FLAG_PROMPT=''.join(['%03d'%ord(c)for c in'Enter the flag: '])
WRONG_MSG=''.join(['%03d'%ord(c)for c in'Wrong flag!'])
CORRECT_MSG=''.join(['%03d'%ord(c)for c in'Correct! You passed the ShadowGate.'])
INPUT_SHORT=''.join(['%03d'%ord(c)for c in'Input too short.'])
EXEC_ERROR=''.join(['%03d'%ord(c)for c in'Execution error.'])def _decode(s):return ''.join([chr(int(s[i:i+3]))for i in range(0,len(s),3)])
FLAG_PROMPT=''.join(['%03d'%ord(c)for c in'Enter the flag: '])
WRONG_MSG=''.join(['%03d'%ord(c)for c in'Wrong flag!'])
CORRECT_MSG=''.join(['%03d'%ord(c)for c in'Correct! You passed the ShadowGate.'])
INPUT_SHORT=''.join(['%03d'%ord(c)for c in'Input too short.'])
EXEC_ERROR=''.join(['%03d'%ord(c)for c in'Execution error.'])def _decode(s):return ''.join([chr(int(s[i:i+3]))for i in range(0,len(s),3)])
FLAG_PROMPT=''.join(['%03d'%ord(c)for c in'Enter the flag: '])
WRONG_MSG=''.join(['%03d'%ord(c)for c in'Wrong flag!'])
CORRECT_MSG=''.join(['%03d'%ord(c)for c in'Correct! You passed the ShadowGate.'])
INPUT_SHORT=''.join(['%03d'%ord(c)for c in'Input too short.'])
EXEC_ERROR=''.join(['%03d'%ord(c)for c in'Execution error.'])def _decode(s):return ''.join([chr(int(s[i:i+3]))for i in range(0,len(s),3)])
FLAG_PROMPT=''.join(['%03d'%ord(c)for c in'Enter the flag: '])
WRONG_MSG=''.join(['%03d'%ord(c)for c in'Wrong flag!'])
CORRECT_MSG=''.join(['%03d'%ord(c)for c in'Correct! You passed the ShadowGate.'])
INPUT_SHORT=''.join(['%03d'%ord(c)for c in'Input too short.'])
EXEC_ERROR=''.join(['%03d'%ord(c)for c in'Execution error.'])def _decode(s):return ''.join([chr(int(s[i:i+3]))for i in range(0,len(s),3)])
FLAG_PROMPT=''.join(['%03d'%ord(c)for c in'Enter the flag: '])
WRONG_MSG=''.join(['%03d'%ord(c)for c in'Wrong flag!'])
CORRECT_MSG=''.join(['%03d'%ord(c)for c in'Correct! You passed the ShadowGate.'])
INPUT_SHORT=''.join(['%03d'%ord(c)for c in'Input too short.'])
EXEC_ERROR=''.join(['%03d'%ord(c)for c in'Execution error.'])def _decode(s):return ''.join([chr(int(s[i:i+3]))for i in range(0,len(s),3)])
FLAG_PROMPT=''.join(['%03d'%ord(c)for c in'Enter the flag: '])
WRONG_MSG=''.join(['%03d'%ord(c)for c in'Wrong flag!'])
CORRECT_MSG=''.join(['%03d'%ord(c)for c in'Correct! You passed the ShadowGate.'])
INPUT_SHORT=''.join(['%03d'%ord(c)for c in'Input too short.'])
EXEC_ERROR=''.join(['%03d'%ord(c)for c in'Execution error.'])def _decode(s):return ''.join([chr(int(s[i:i+3]))for i in range(0,len(s),3)])
FLAG_PROMPT=''.join(['%03d'%ord(c)for c in'Enter the flag: '])
WRONG_MSG=''.join(['%03d'%ord(c)for c in'Wrong flag!'])
CORRECT_MSG=''.join(['%03d'%ord(c)for c in'Correct! You passed the ShadowGate.'])
INPUT_SHORT=''.join(['%03d'%ord(c)for c in'Input too short.'])
EXEC_ERROR=''.join(['%03d'%ord(c)for c in'Execution error.'])def _decode(s):return ''.join([chr(int(s[i:i+3]))for i in range(0,len(s),3)])
FLAG_PROMPT=''.join(['%03d'%ord(c)for c in'Enter the flag: '])
WRONG_MSG=''.join(['%03d'%ord(c)for c in'Wrong flag!'])
CORRECT_MSG=''.join(['%03d'%ord(c)for c in'Correct! You passed the ShadowGate.'])
INPUT_SHORT=''.join(['%03d'%ord(c)for c in'Input too short.'])
EXEC_ERROR=''.join(['%03d'%ord(c)for c in'Execution error.'])def _decode(s):return ''.join([chr(int(s[i:i+3]))for i in range(0,len(s),3)])
FLAG_PROMPT=''.join(['%03d'%ord(c)for c in'Enter the flag: '])
WRONG_MSG=''.join(['%03d'%ord(c)for c in'Wrong flag!'])
CORRECT_MSG=''.join(['%03d'%ord(c)for c in'Correct! You passed the ShadowGate.'])
INPUT_SHORT=''.join(['%03d'%ord(c)for c in'Input too short.'])
EXEC_ERROR=''.join(['%03d'%ord(c)for c in'Execution error.'])def _decode(s):return ''.join([chr(int(s[i:i+3]))for i in range(0,len(s),3)])
FLAG_PROMPT=''.join(['%03d'%ord(c)for c in'Enter the flag: '])
WRONG_MSG=''.join(['%03d'%ord(c)for c in'Wrong flag!'])
CORRECT_MSG=''.join(['%03d'%ord(c)for c in'Correct! You passed the ShadowGate.'])
INPUT_SHORT=''.join(['%03d'%ord(c)for c in'Input too short.'])
EXEC_ERROR=''.join(['%03d'%ord(c)for c in'Execution error.'])def _decode(s):return ''.join([chr(int(s[i:i+3]))for i in range(0,len(s),3)])
FLAG_PROMPT=''.join(['%03d'%ord(c)for c in'Enter the flag: '])
WRONG_MSG=''.join(['%03d'%ord(c)for c in'Wrong flag!'])
CORRECT_MSG=''.join(['%03d'%ord(c)for c in'Correct! You passed the ShadowGate.'])
INPUT_SHORT=''.join(['%03d'%ord(c)for c in'Input too short.'])
EXEC_ERROR=''.join(['%03d'%ord(c)for c in'Execution error.'])
@LambdaDecorator
def run_vm(u):
R0=R1=R2=0;pc=0
program=[(1,0),(2,66),(3,4),(4,),(5,),(1,1),(2,55),(3,123),(4,),(5,),(1,2),(2,86),(3,23),(4,0),(5,0),(2,3),(23,153),(3,252),(4,0),(5,0),(9,4),(2,66),(3,57),(4,),(5,),(1,5),(2,55),(3,97),(4,),(5,),(1,6),(2,86),(3,27),(4,),(5,),(1,7),(2,153),(3,198),(4,),(5,),(1,8),(2,66),(3,0),(4,),(5,),(1,9),(2,55),(3,86),(4,),(5,),(1,10),(2,86),(3,37),(4,),(5,),(1,11),(2,153),(3,252),(4,),(5,),(1,12),(2,66),(3,38),(4,),(5,),(1,13),(2,55),(3,104),(4,),(5,),(1,14),(2,86),(3,25),(4,),(5,),(1,15),(2,153),(3,251),(4,),(5,),(1,16),(2,66),(3,36),(4,),(5,),(1,17),(2,55),(3,66),(4,),(5,),(1,18),(2,86),(3,37),(4,),(5,),(1,19),(2,153),(3,250),(4,),(5,),(1,20),(2,66),(3,35),(4,),(5,),(1,21),(2,55),(3,67),(4,),(5,),(1,22),(2,86),(3,63),(4,),(5,),(1,23),(2,153),(3,246),(4,),(5,),(1,24),(2,66),(3,44),(4,),(5,),(1,25),(2,55),(3,104),(4,),(5,),(1,26),(2,86),(3,4),(4,),(5,),(1,27),(2,153),(3,252),(4,),(5,),(1,28),(2,66),(3,52),(4,),(5,),(1,29),(2,55),(3,82),(4,),(5,),(1,30),(2,86),(3,36),(4,),(5,),(1,31),(2,153),(3,234),(4,),(5,),(1,32),(2,66),(3,39),(4,),(5,),(1,33),(2,55),(3,104),(4,),(5,),(1,34),(2,86),(3,27),(4,),(5,),(1,35),(2,153),(3,248),(4,),(5,),(1,36),(2,66),(3,49),(4,),(5,),(1,37),(2,55),(3,67),(4,),(5,),(1,38),(2,86),(3,51),(4,),(5,),(1,39),(2,153),(3,235),(4,),(5,),(1,40),(2,66),(3,63),(4,),(5,),(6,)]
l=len(u)
for _ in range(5):pass
while pc<len(program):
i=program[pc];op=i[0];_=(lambda x:x)(op)
if op==0x01:
idx=i[1]
if idx>=l:print(_decode(INPUT_SHORT));return
R0=ord(u[idx]);pc+=1
elif op==0x02:R1=R0^i[1];pc+=1
elif op==0x03:t=i[1];R2=1 if R1==t else 0;pc+=1
elif op==0x04:
if R2!=1:pc+=1
else:pc+=2
elif op==0x05:print(_decode(WRONG_MSG));return
elif op==0x06:print(_decode(CORRECT_MSG));return
for _ in range(3):pass
_=(lambda x:x)(pc);_=(lambda x:x)(R0);_=(lambda x:x)(R1);_=(lambda x:x)(R2)
if __name__=="__main__":
for _ in range(10):pass
try:
u=input(_decode(FLAG_PROMPT)).strip()
for _ in range(5):pass
run_vm(u)
except Exception as e:
for _ in range(3):pass
print(_decode(EXEC_ERROR))
for _ in range(900):
exec(f'LambdaFunc_{_} = lambda x: x')
if _ % 10 == 0:
pass
else:
pass
_ = "obfustication" * (_ % 2)
_ = _ * 1
_ = [_ for _ in range(1)]
_ = {{_: _}}
_ = set([_])
_ = (_,)
_ = (lambda x: x)(_)
def f(x): return x
f(_)
try:
pass
except:
pass
class C: pass
C()
import math
_ = 1 + 1
_ = f"{_}"
_ = True
_ = None
if _ == 0:
continue
else:
break
class Meta(type):
def __new__(cls, name, bases, dct):
return super().__new__(cls, name, bases, dct)
class Confuse(metaclass=Meta):
def __init__(self):
self.x = 0
def __call__(self, *a, **k):
return self.x
def __getitem__(self, k):
return self.x
def __setitem__(self, k, v):
self.x = v
confuser = Confuse()
for _ in range(5):
confuser[_] = _
confuser(_)
f1 = lambda x: (lambda y: (lambda z: z)(y))(x)
f2 = lambda x: f1(f1(f1(x)))
f3 = lambda x: f2(f2(f2(x)))
for _ in range(10):
exec('def fake_func_{}(): return {}'.format(_, _))
eval('1+1')
try:
try:
pass
except:
pass
finally:
pass
except:
pass
class Dummy:
def __enter__(self): return self
def __exit__(self, exc_type, exc_val, exc_tb): return False
with Dummy():
pass
useless_gen = (i for i in range(10))
for _ in useless_gen:
pass
class P:
@property
def x(self):
return 42
p = P(); p.x
def fake(*args, **kwargs):
"""This function does nothing but adds confusion."""
return args, kwargs
fake(1,2,3,a=4)
def import_inside():
import os
return os.name
import_inside()
[setattr(confuser, 'x', i) for i in range(5)]
super_lambda = lambda x: (lambda y: (lambda z: (lambda w: w)(z))(y))(x)
def shadowed_open(open):
return open
shadowed_open(5)
def outer():
x = 0
def inner():
nonlocal x
x += 1
return x
return inner()
outer()
global_var = 0
def g():
global global_var
global_var += 1
g()
def annotated(x: int) -> int:
return x
annotated(5)
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | true |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/WebArena/2025/rev/Reverse_Again/main.py | ctfs/WebArena/2025/rev/Reverse_Again/main.py | """Phantom Init - CTF Challenge
%s%%s%%s%%s%%s%%s%%s%%s%%s%%s%%s%%s%%s%%s%%s%%s%%s%%9%%9%%9%%9%%9%%9%%9%%9%%9%%9%%9%%9%%9%%9%%9%%9%%9%
%s%%s%%s%%s%%s%%s%%s%%s%%s%%s%%s%%s%%s%%s%%s%%s%%s%%9%%9%%9%%9%%9%%9%%9%%9%%9%%9%%9%%9%%9%%9%%9%%9%%9%
%s%%s%%s%%s%%s%%s%%s%%s%%s%%s%%s%%s%%s%%s%%s%%s%%s%%9%%9%%9%%9%%9%%9%%9%%9%%9%%9%%9%%9%%9%%9%%9%%9%%9%
%s%%s%%s%%s%%s%%s%%s%%s%%s%%s%%s%%s%%s%%s%%s%%s%%s%%9%%9%%9%%9%%9%%9%%9%%9%%9%%9%%9%%9%%9%%9%%9%%9%%9%
%s%%s%%s%%s%%s%%s%%s%%s%%s%%s%%s%%s%%s%%s%%s%%s%%s%%9%%9%%9%%9%%9%%9%%9%%9%%9%%9%%9%%9%%9%%9%%9%%9%%9%
%s%%s%%s%%s%%s%%s%%s%%s%%s%%s%%s%%s%%s%%s%%s%%s%%s%%9%%9%%9%%9%%9%%9%%9%%9%%9%%9%%9%%9%%9%%9%%9%%9%%9%
%s%%s%%s%%s%%s%%s%%s%%s%%s%%s%%s%%s%%s%%s%%s%%s%%s%%9%%9%%9%%9%%9%%9%%9%%9%%9%%9%%9%%9%%9%%9%%9%%9%%9%
%s%%s%%s%%s%%s%%s%%s%%s%%s%%s%%s%%s%%s%%s%%s%%s%%s%%9%%9%%9%%9%%9%%9%%9%%9%%9%%9%%9%%9%%9%%9%%9%%9%%9%
%s%%s%%s%%s%%s%%s%%s%%s%%s%%s%%s%%s%%s%%s%%s%%s%%s%%9%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9%%9%%9%%9%%9%
%s%%s%%s%%s%%s%%s%%s%%s%%s%%s%%s%%s%%s%%s%%s%%s%%s%%9%%9%%9%%9%%9%%9%%9%%9%%9%%9%%9%%9%%9%%9%%9%%9%%9%
%s%%s%%s%%s%%s%%s%%s%%s%%s%%s%%s%%s%%s%%s%%s%%s%%s%%9%%9%%9%%9%%9%%9%%9%%9%%9%%9%%9%%9%%9%%9%%9%%9%%9%"""
print("Access denied")
"""%s%%s%%s%%s%%s%%s%%s%%s%%s%%s%%s%%s%%s%%s%%s%%s%%s%%9%%9%%9%%9%%9%%9%%9%%9%%9%%9%%9%%9%%9%%9%%9%%9%%9%
%s%%s%%s%%s%%s%%s%%s%%s%%s%%s%%s%%s%%s%%s%%s%%s%%s%%9%%9%%9%%9%%9%%9%%9%%9%%9%%9%%9%%9%%9%%9%%9%%9%%9%
%s%%s%%s%%s%%s%%s%%s%%s%%s%%s%%s%%s%%s%%s%%s%%s%%s%%9%%9%%9%%9%%9%%9%%9%%9%%9%%9%%9%%9%%9%%9%%9%%9%%9%
%s%%s%%s%%s%%s%%s%%s%%s%%s%%s%%s%%s%%s%%s%%s%%s%%s%%9%%9%%9%%9%%9%%9%%9%%9%%9%%9%%9%%9%%9%%9%%9%%9%%9%
%s%%s%%s%%s%%s%%s%%s%%s%%s%%s%%s%%s%%s%%s%%s%%s%%s%%9%%9%%9%%9%%9%%9%%9%%9%%9%%9%%9%%9%%9%%9%%9%%9%%9%
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | true |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/SpringForwardCTF/2023/crypto/A_new_hope/encrypt.py | ctfs/SpringForwardCTF/2023/crypto/A_new_hope/encrypt.py | def encrypt(message, key):
encrypted = ""
for i in range(len(message)):
encrypted += chr(ord(message[i]) ^ ord(key[i % len(key)]))
return encrypted.encode("utf-8").hex()
message = #//////ERROR ERROR ERROR
key = #/////// ERROR OERROR ERROR ERROR
encrypted = encrypt(message,key) | python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/NahamCon/2022-EU/blockchain/jump/scripts/challenge.py | ctfs/NahamCon/2022-EU/blockchain/jump/scripts/challenge.py | from brownie import *
def restricted_accounts():
return [accounts[9]]
def deploy():
Jump.deploy({'from': accounts[9], 'value': web3.toWei(1, 'ether')})
def solved():
if Jump[-1].balance() == 0:
return True, "Solved!"
else:
return False, "Still have funds!"
CONFIG = {
# "RPC": '',
# "BLOCK_NUMBER": '',
# 'FLAGS': '',
'MNEMONIC': 'test test test test test test test test test test test junk',
# 'RUNNABLES': [],
# 'ALLOWED_RPC_METHODS': []
}
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/NahamCon/2022-EU/blockchain/BrokenStorage/challenge.py | ctfs/NahamCon/2022-EU/blockchain/BrokenStorage/challenge.py | from brownie import *
def restricted_accounts():
return [accounts[8]]
def deploy():
ADMIN = accounts[8]
buckets = Buckets.deploy({'from': ADMIN})
bucketsProxy = BucketsProxy.deploy(buckets, 5, {'from': ADMIN})
def solved():
ADMIN = accounts[8]
proxy_buckets = Contract.from_abi("Buckets", BucketsProxy[-1], Buckets.abi)
if BucketsProxy[-1].getAdmin() != ADMIN and proxy_buckets.balanceOf(ADMIN) == 0x1337:
return True, "Solved!"
else:
return False, "Not solved."
CONFIG = {
# "RPC": '',
# "BLOCK_NUMBER": '',
# 'FLAGS': '',
'MNEMONIC': 'test test test test test test test test test test test junk',
# 'RUNNABLES': [],
# 'ALLOWED_RPC_METHODS': []
}
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/NahamCon/2022-EU/blockchain/eth_welcome/scripts/challenge.py | ctfs/NahamCon/2022-EU/blockchain/eth_welcome/scripts/challenge.py | from brownie import *
def deploy(state, deployer, player):
Welcome.deploy({'from': deployer[0]})
def solved():
if Welcome[-1].balance() > 0:
return True, "Solved!"
else:
return False, "Need more coins!"
CONFIG = {
# "RPC": '',
# "BLOCK_NUMBER": '',
# 'FLAGS': '',
'MNEMONIC': 'test test test test test test test test test test test junk',
# 'RUNNABLES': [],
'ALLOWED_RPC_METHODS': []
}
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/NahamCon/2022-EU/blockchain/nft_lottery/scripts/challenge.py | ctfs/NahamCon/2022-EU/blockchain/nft_lottery/scripts/challenge.py | from brownie import *
def deploy(state, deployer, player):
ADMIN = deployer[0]
l = LdcNFT.deploy('LdcNFT', 'LDC', 'http://halborn.com', {'from':ADMIN})
l.flipPublicSaleOn({'from': ADMIN})
l.flipSantaAlgorithmOn({'from': ADMIN})
ADMIN.transfer(l, web3.toWei(6, 'ether'))
def solved(state, deployer, player):
l = LdcNFT[-1]
# You should have claimed 6 times the prize1ETH prize
if l.totalSupply() == 6 and l.balance() < web3.toWei(0.5, 'ether'):
return True, "Solved!"
else:
return False, "Not solved, still have {:.2f} ETH in prize".format(web3.fromWei(l.prizeAmount(), 'ether'))
CONFIG = {
# "RPC": '',
# "BLOCK_NUMBER": '',
# 'FLAGS': '',
'MNEMONIC': 'test test test test test test test test test test test junk',
# 'RUNNABLES': [],
'ALLOWED_RPC_METHODS': ["evm_mine", "evm_increaseTime"]
}
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/NahamCon/2022-EU/blockchain/merkle_heist/scripts/challenge.py | ctfs/NahamCon/2022-EU/blockchain/merkle_heist/scripts/challenge.py | from brownie import *
from brownie import convert
def restricted_accounts():
return [accounts[9]]
def deploy():
ADMIN = accounts[9]
token = SimpleToken.deploy('Simple Token', 'STK', {'from': ADMIN})
_merkleRoot = 0x654ef3fa251b95a8730ce8e43f44d6a32c8f045371ce6a18792ca64f1e148f8c
airdrop = Airdrop.deploy(token, 1e5, _merkleRoot, 4, {'from': ADMIN})
token.setAirdropAddress(airdrop, {'from': ADMIN})
merkleProof = [
int(convert.to_bytes(ADMIN.address).hex(),16),
0x000000000000000000000000feb7377168914e8771f320d573a94f80ef953782,
0xb10e2d527612073b26eecdfd717e6a320cf44b4afac2b0732d9fcbe2b7fa0cf6,
0x290decd9548b62a8d60345a988386fc84ba6bc95484008f6362f93160ef3e563
]
airdrop.mintToken(merkleProof)
def solved():
token = SimpleToken[-1]
# You should mint 100000 amount of token.
if token.totalSupply() == 200000:
return True, "Solved!"
else:
return False, "Not solved, you need to mint enough to solve."
CONFIG = {
# "RPC": '',
# "BLOCK_NUMBER": '',
# 'FLAGS': '',
'MNEMONIC': 'test test test test test test test test test test test junk',
# 'RUNNABLES': [],
# 'ALLOWED_RPC_METHODS': []
}
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/NahamCon/2022-EU/blockchain/proposal_unlock/scripts/challenge.py | ctfs/NahamCon/2022-EU/blockchain/proposal_unlock/scripts/challenge.py | from brownie import *
def deploy(state, deployer, player):
ADMIN = deployer[0]
vedeg = VeHAL.deploy(web3.toWei(100, 'ether'), "Voting HAL", 18, "VeHAL", {'from':ADMIN})
deg = HAL.deploy(web3.toWei(1000000, 'ether'), "HAL Token", 18, "HAL", {'from':ADMIN})
on = OnboardProposal.deploy(deg, vedeg, {'from':ADMIN})
t1 = Token.deploy("Token1", "T1", {'from':ADMIN})
on.propose("Token name", t1, 100, 100, {'from':ADMIN})
# Vote to already pass the proposal, as admin has enough power
# claiming the airdrop will not allow the proposal to pass, as 30%
# of total supply is required
on.vote(1, 1, web3.toWei(100, 'ether') * 0.3, {'from':ADMIN})
def solved(state, deployer, player):
on = OnboardProposal[-1]
# Check if any proposal from id 2 up is passed
for i in range(2, on.proposalCounter() + 1):
# Check if passed
if on.proposals(i)[-1] == 1:
return True, "Solved!"
return False, "No proposal was passed"
CONFIG = {
# "RPC": '',
# "BLOCK_NUMBER": '',
# 'FLAGS': '',
'MNEMONIC': 'test test test test test test test test test test test junk',
# 'RUNNABLES': [],
'ALLOWED_RPC_METHODS': ["evm_increaseTime", "evm_mine"]
}
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/NahamCon/2022-EU/crypto/dont_hack_my_d/gen.py | ctfs/NahamCon/2022-EU/crypto/dont_hack_my_d/gen.py | import random
import time
from Crypto.Util.number import bytes_to_long as b2l, long_to_bytes as l2b, getPrime
time.clock = time.time
# params
p = getPrime(2048)
q = getPrime(2048)
n = p*q
phi = (p-1)*(q-1)
e = 0x10001
d = pow(e, -1, phi)
print(f'e = {e}\nn = {n}')
# flag stuff
flag = open('flag.txt', 'r').read().strip()
assert(len(flag) == 38)
pts = [flag[0:len(flag)//2], flag[len(flag)//2:]]
#print(f'pts = {pts}\nl1 = {len(pts[0])} --- l2 = {len(pts[1])}')
# no more side channel attacks >:(
for i in range(2):
pt = b2l(pts[i].encode())
ct = pow(pt, e, n)
rvals = [random.randrange(2, n-1) for _ in range(3)]
ct2 = ct + rvals[0]*n
d2 = d + rvals[1]*phi
n2 = rvals[2]*n
assert(pt == (pow(ct2, d2, n2) % n))
print(f'ct_{i} = {ct}\nd2_{i} = {d2}\nrvals_{i} = {rvals}')
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/NahamCon/2022-EU/crypto/rektcursion/rektcursion.py | ctfs/NahamCon/2022-EU/crypto/rektcursion/rektcursion.py | import math
import hashlib
from Crypto.Cipher import AES
ENC_MSG = open('msg.enc', 'rb').read()
NUM_HASH = "636e276981116cf433ac4c60ba9b355b6377a50e"
def f(i):
if i < 5:
return i+1
return 1905846624*f(i-5) - 133141548*f(i-4) + 3715204*f(i-3) - 51759*f(i-2) + 360*f(i-1)
# Decrypt the flag
def decrypt_flag(sol):
sol = sol % pow(10,31337)
sol = str(sol)
num_hash = hashlib.sha1(sol.encode()).hexdigest()
key = hashlib.sha256(sol.encode()).digest()
if num_hash != NUM_HASH:
print('number not computed correctly')
exit()
iv = b'\x00'*16
cipher = AES.new(key, AES.MODE_CBC, iv)
print(len(unpad(ENC_MSG)))
msg_dec = cipher.decrypt(ENC_MSG)
print(msg_dec)
if __name__ == "__main__":
ret = f(13371337)
decrypt_flag(ret)
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/NahamCon/2022-EU/crypto/Shapeshifter/shapeshifter.py | ctfs/NahamCon/2022-EU/crypto/Shapeshifter/shapeshifter.py | from Crypto.Util.number import bytes_to_long as b2l
FLAG = open('flag.txt', 'r').read().strip().encode()
class LFSR():
def __init__(self, iv):
self.state = [int(c) for c in iv]
#self.state = self.iv
def shift(self):
s = self.state
newbit = s[15] ^ s[13] ^ s[12] ^ s[10] # ^ s[0]
s.pop()
self.state = [newbit] + s
for i in range(0, len(FLAG), 2):
chars = f'{b2l(FLAG[i:i+2]):016b}'
assert len(chars) == 16
lfsr = LFSR(chars)
for _ in range(31337):
lfsr.shift()
finalstate = ''.join([str(c) for c in lfsr.state])
print(f'{finalstate}')
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/NahamCon/2022-EU/web/sigma/scripts/challenge.py | ctfs/NahamCon/2022-EU/web/sigma/scripts/challenge.py | from brownie import *
def deploy():
pass
# EscrowReward.at('0x34a1Ba8Ab01a78747e3623be9Fa90926e0019c87')
# transferOp1 = (
# 0,
# ADMIN,
# approve_selector,
# HALF_ETHER,
# approve_signature["signature"]
# )
# transferOp2 = (
# 0,
# EscrowReward[0].address,
# transferFrom_selector,
# HALF_ETHER,
# transfer_signature["signature"]
# )
# EscrowReward[0].execute(transferOp1, approve_hash)
# EscrowReward[0].execute(transferOp2, transfer_hash)
def solved():
rewardNFT = RewardNFT.at(EscrowReward[0].rewardNFT())
if rewardNFT.totalSupply() > 0:
return True, "You are a true white hat!"
else:
return False, "You still need to mint 1 Reward NFT and safe the world"
CONFIG = {
# 'RPC': '',
# 'BLOCK_NUMBER': '',
# 'FLAGS': '',
'MNEMONIC': 'test test test test test test test test test test test junk',
# 'RUNNABLES': [],
# 'ALLOWED_RPC_METHODS': []
}
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/NahamCon/2021/crypto/DiceRoll/dice_roll.py | ctfs/NahamCon/2021/crypto/DiceRoll/dice_roll.py | #!/usr/bin/env python3
import random
import os
banner = """
_______
______ | . . |\\
/ /\\ | . |.\\
/ ' / \\ | . . |.'|
/_____/. . \\ |_______|.'|
\\ . . \\ / \\ ' . \\'|
\\ . . \\ / \\____'__\\|
\\_____\\/
D I C E R O L L
"""
menu = """
0. Info
1. Shake the dice
2. Roll the dice (practice)
3. Guess the dice (test)
"""
dice_bits = 32
flag = open('flag.txt').read()
print(banner)
while 1:
print(menu)
try:
entered = int(input('> '))
except ValueError:
print("ERROR: Please select a menu option")
continue
if entered not in [0, 1, 2, 3]:
print("ERROR: Please select a menu option")
continue
if entered == 0:
print("Our dice are loaded with a whopping 32 bits of randomness!")
continue
if entered == 1:
print("Shaking all the dice...")
random.seed(os.urandom(dice_bits))
continue
if entered == 2:
print("Rolling the dice... the sum was:")
print(random.getrandbits(dice_bits))
continue
if entered == 3:
print("Guess the dice roll to win a flag! What will the sum total be?")
try:
guess = int(input('> '))
except ValueError:
print("ERROR: Please enter a valid number!")
continue
total = random.getrandbits(dice_bits)
if guess == total:
print("HOLY COW! YOU GUESSED IT RIGHT! Congratulations! Here is your flag:")
print(flag)
else:
print("No, sorry, that was not correct... the sum total was:")
print(total)
continue
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/NahamCon/2021/web/AgentTester/app/app.py | ctfs/NahamCon/2021/web/AgentTester/app/app.py | from flask_uwsgi_websocket import GeventWebSocket
import re
import subprocess
from backend.backend import *
ws = GeventWebSocket(app)
@app.route("/", methods=["GET"])
@login_required
def home():
success = request.args.get("success", None)
error = request.args.get("error", None)
return render_template(
"templates/index.html",
user=g.user,
success=success,
error=error,
)
@app.route("/debug", methods=["POST"])
def debug():
sessionID = session.get("id", None)
if sessionID == 1:
code = request.form.get("code", "<h1>Safe Debug</h1>")
return render_template_string(code)
else:
return "Not allowed."
@app.route("/profile/<int:user_id>", methods=["GET", "POST"])
@login_required
def profile(user_id):
if g.user.id == user_id:
user_now = User.query.get(user_id)
if request.method == "POST":
about = request.form.get("about", None)
email = request.form.get("email", None)
if email:
user_now.email = email
if about:
user_now.about = about
if email or about:
db.session.commit()
else:
return redirect(
url_for("home", error="You are not authorized to access this resource.")
)
return render_template(
"templates/profile.html",
user=user_now,
)
@ws.route("/req")
def req(ws):
with app.request_context(ws.environ):
sessionID = session.get("id", None)
if not sessionID:
ws.send("You are not authorized to access this resource.")
return
uAgent = ws.receive().decode()
if not uAgent:
ws.send("There was an error in your message.")
return
try:
query = db.session.execute(
"SELECT userAgent, url FROM uAgents WHERE userAgent = '%s'" % uAgent
).fetchone()
uAgent = query["userAgent"]
url = query["url"]
except Exception as e:
ws.send(str(e))
return
if not uAgent or not url:
ws.send("Query error.")
return
subprocess.Popen(["node", "browser/browser.js", url, uAgent])
ws.send("Testing User-Agent: " + uAgent + " in url: " + url)
return
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/NahamCon/2021/web/AgentTester/app/backend/models.py | ctfs/NahamCon/2021/web/AgentTester/app/backend/models.py | from flask_sqlalchemy import SQLAlchemy
db = SQLAlchemy()
class User(db.Model):
id = db.Column(db.Integer, primary_key=True)
username = db.Column(db.String(40), unique=True)
email = db.Column(db.String(100), unique=True)
password = db.Column(db.String(1000), unique=False)
about = db.Column(db.String(1000), unique=False)
def __str__(self):
return self.username
def get_user_id(self):
return self.id
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/NahamCon/2021/web/AgentTester/app/backend/backend.py | ctfs/NahamCon/2021/web/AgentTester/app/backend/backend.py | from flask import (
Flask,
render_template,
render_template_string,
request,
redirect,
make_response,
session,
jsonify,
url_for,
g,
)
from functools import wraps
from sqlalchemy import or_
from backend.models import db, User
import os
template_dir = os.path.abspath(".")
app = Flask(__name__, template_folder=template_dir)
app.config["SQLALCHEMY_DATABASE_URI"] = "sqlite:///DB/db.sqlite"
app.config["SQLALCHEMY_TRACK_MODIFICATIONS"] = False
app.config["SECRET_KEY"] = "<REDACTED>"
app.config["SESSION_COOKIE_NAME"] = "auth"
app.jinja_env.globals.update(environ=os.environ.get)
@app.before_first_request
def create_tables():
db.create_all()
try:
user = User(
username=os.environ.get("ADMIN_BOT_USER"),
email="admin@admin.com",
password=os.environ.get("ADMIN_BOT_PASSWORD"),
about="",
)
db.session.add(user)
db.session.commit()
except Exception as e:
print(str(e), flush=True)
db.init_app(app)
def login_required(f):
@wraps(f)
def wrap(*args, **kwargs):
sessionID = session.get("id", None)
if not sessionID:
return redirect(url_for("signin", error="Invalid session please sign in"))
g.user = User.query.get(sessionID)
return f(*args, **kwargs)
return wrap
def logged_should_not_visit(f):
@wraps(f)
def wrap(*args, **kwargs):
sessionID = session.get("id", None)
if sessionID:
return redirect(url_for("home"))
return f(*args, **kwargs)
return wrap
@app.route("/signup", methods=["GET", "POST"])
@logged_should_not_visit
def signup():
if request.method == "GET":
return render_template("backend/default_templates/signup.html")
elif request.method == "POST":
data = request.get_json(force=True)
username = data.get("username", None)
email = data.get("email", None)
password = data.get("password", None)
password2 = data.get("password2", None)
if not username or not email or not password or not password2:
response = make_response(
jsonify({"message": "Missing parameters"}),
400,
)
response.headers["Content-Type"] = "application/json"
return response
# Check if user or email exists
user = User.query.filter(
or_(User.username == username, User.email == email)
).first()
if user:
response = make_response(
jsonify(
{
"message": "This username and/or email is already taken please choose another one"
}
),
400,
)
response.headers["Content-Type"] = "application/json"
return response
# Check if passwords match
if password != password2:
response = make_response(
jsonify({"message": "Passwords do not match"}),
400,
)
response.headers["Content-Type"] = "application/json"
return response
user = User(username=username, email=email, password=password, about="")
db.session.add(user)
db.session.commit()
response = make_response(
jsonify({"message": "Successfully signed up."}),
200,
)
response.headers["Content-Type"] = "application/json"
return response
@app.route("/signin", methods=["GET", "POST"])
@logged_should_not_visit
def signin():
if request.method == "GET":
success = request.args.get("success", None)
error = request.args.get("error", None)
return render_template(
"backend/default_templates/signin.html", success=success, error=error
)
elif request.method == "POST":
username = request.form.get("username")
password = request.form.get("password")
# Check if user exists
user = User.query.filter(
User.username == username, User.password == password
).first()
if not user:
return redirect(url_for("signin", error="Invalid credentials"))
session["id"] = user.id
return redirect(url_for("home"))
@app.route("/logout")
@login_required
def logout():
session.pop("id", None)
return redirect(url_for("signin", success="Logged out successfully."))
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/NahamCon/2024/misc/Hashes_on_Hashes_on_Hashes/server.py | ctfs/NahamCon/2024/misc/Hashes_on_Hashes_on_Hashes/server.py | import socket
import base64
from hashlib import md5
from datetime import datetime
host = '0.0.0.0'
port = 9001
class log:
@staticmethod
def print(message):
with open('./decryption_server.log', 'a') as f:
now = datetime.now()
f.write(now.strftime("%d/%m/%Y %H:%M:%S") + "\t")
f.write(message + '\n')
def decrypt(encrypted):
key = open('key.txt').read()
key = key.strip()
log.print("Key loaded for encrypted message")
factor = len(encrypted) // len(key) + 1
key = key * factor
log.print(f"Key expanded by factor of {factor}")
key_bytes = key.encode()
enc_bytes = base64.b64decode(encrypted)
dec_bytes = bytearray()
for i in range(len(enc_bytes)):
dec_bytes.append(enc_bytes[i] ^ key_bytes[i])
log.print(f"Partial message digest is {md5(dec_bytes).hexdigest()}")
decrypted = dec_bytes.decode()
log.print("Message fully decrypted, ready to send...")
return decrypted
def main_loop():
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind((host, port))
log.print(f"Server listening on host {host} and port {port}")
while True:
s.listen(1)
log.print("Listening for connection...")
c_soc, addr = s.accept()
log.print(f"Connection received from {addr}")
ciphertext = c_soc.recv(1024).decode().strip()
log.print(f"Received encrypted message {ciphertext}")
plaintext = decrypt(ciphertext)
c_soc.sendall(plaintext.encode())
log.print(f"Decrypted message sent!")
if __name__ == '__main__':
main_loop() | python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/NahamCon/2024/crypto/Magic_RSA/rsa_with_a_magic_number.py | ctfs/NahamCon/2024/crypto/Magic_RSA/rsa_with_a_magic_number.py | from secrets import randbits
from sympy import nextprime
e = 3
def encrypt(inp):
p = nextprime(randbits(2048))
q = nextprime(randbits(2048))
n = p * q
enc = [pow(ord(c), e, n) for c in inp]
return [n, enc]
plaintext = open('flag.txt').read()
with open('output.txt', 'w') as f:
data = encrypt(plaintext)
f.write(f'Semiprime:\nN: {data[0]}\nCiphertext:\n')
f.write(''.join(f'{b} ' for b in data[1]))
f.write('\n\n') | python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/NahamCon/2024/crypto/Rigged_Lottery/server.py | ctfs/NahamCon/2024/crypto/Rigged_Lottery/server.py | from inputimeout import inputimeout, TimeoutOccurred
import random, sys
with open('flag.txt') as f:
flag = f.read()
def main():
print("Here is how the lottery works:")
print("- Players purchase tickets comprising their choices of six different numbers between 1 and 70")
print("- During the draw, six balls are randomly selected without replacement from a set numbered from 1 to 70")
print("- A prize is awarded to any player who matches at least two of the six drawn numbers.")
print("- More matches = higher prize!")
while True:
print("\n********************\nHow many tickets would you like to buy? There is a limit of 50 tickets per person")
try:
reply = int(inputimeout(prompt='>> ', timeout=60))
except ValueError:
reply = 0
except TimeoutOccurred:
print("Oof! Not fast enough!\n")
sys.exit()
if reply > 50 or reply < 1:
print("That is an invalid choice!\n")
else:
break
tickets = []
for x in range(reply):
ticket = []
print(f"\n********************\nPlease give the numbers for ticket {x+1}:")
for _ in range(6):
while True:
try:
number = int(inputimeout(prompt='>> ', timeout=60))
except TimeoutOccurred:
print("Oof! Not fast enough!\n")
sys.exit()
except ValueError:
number = 0
if number > 70 or number < 1:
print("That is an invalid choice!\n")
else:
break
ticket.append(number)
tickets.append(ticket)
winnings = [0, 0, 1, 100, 1000, 100000, 10000000]
print(f"\n********************\nLet's see if you can win in {10**6} consecutive rounds of the lottery and make a profit at the end of it!")
profit = 0
for i in range(10**6):
draw = set([])
while len(draw) != 6:
draw.add(random.randint(1,70))
won_prize = False
for ticket in tickets:
profit -= 1
matches = len(draw.intersection(set(ticket)))
if matches > 1:
won_prize = True
profit += winnings[matches]
if won_prize:
if (i+1)%(10**5) == 0:
print(f"You made it through {i+1} rounds! Profit so far is ${profit}")
else:
print(f"Draw {i+i}: {draw}, profit: ${profit}")
print(f"\n********************\nAh shucks! Look's like you did not win any prizes this round. Better luck next time")
sys.exit()
if profit > 0:
print(f"\n********************\nWow! You broke the lottery system! Here's the well-deserved flag --> {flag}")
if __name__ == "__main__":
main() | python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/NahamCon/2024/crypto/Blackjack/server.py | ctfs/NahamCon/2024/crypto/Blackjack/server.py | # A lot of this code is taken from https://github.com/rishimule/blackjack-python
from inputimeout import inputimeout, TimeoutOccurred
import os, sys
suits = ("Hearts", "Clubs", "Diamonds", "Spades")
ranks = ("Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine", "Ten", "Jack", "Queen", "King", "Ace")
values = {"Two" : 2, "Three" : 3, "Four" : 4, "Five" : 5, "Six" : 6, "Seven" :7, "Eight" : 8, "Nine" : 9, "Ten" : 10, "Jack" : 10, "Queen" : 10, "King" : 10, "Ace" : 11}
class PRNG:
def __init__(self, seed = int(os.urandom(8).hex(),16)):
self.seed = seed
self.state = [self.seed]
self.index = 52
for i in range(51):
self.state.append((3 * (self.state[i] ^ (self.state[i-1] >> 6)) + i+1)%512)
def __str__(self):
return f"{self.state}"
def getnum(self):
if self.index >= 52:
for i in range(52):
y = (self.state[i] & 0x40) + (self.state[(i+1)%52] & 0x3f)
val = y >> 1
val = val ^ self.state[(i+9)%52]
if y & 1:
val = val ^ 69
self.state[i] = val
self.index = 0
seed = self.state[self.index]
self.index += 1
return (seed*13 + 17)%(2**7)
class Card:
def __init__(self,rank,suit):
self.rank = rank
self.suit = suit
self.value = values[rank]
def __str__(self):
return self.rank + " of " + self.suit
class Deck:
def __init__(self):
self.cardlist = []
for suit in suits:
for rank in ranks:
current_card = Card(rank,suit)
self.cardlist.append(current_card)
def __str__(self):
deck_cards = ''
for x in range(len(self.cardlist)):
deck_cards += str(self.cardlist[x]) + "\n"
return f"This Deck has {str(len(self.cardlist))} Cards.\n" + deck_cards
def shuffle_deck(self):
new_deck = []
for i in range(len(self.cardlist)):
x = rng.getnum() % 52
if self.cardlist[x] not in new_deck:
new_deck.append(self.cardlist[x])
elif self.cardlist[i] not in new_deck:
new_deck.append(self.cardlist[i])
else:
for card in self.cardlist:
if card not in self.cardlist:
new_deck.append(card)
break
self.cardlist = new_deck
def deal_one(self):
return self.cardlist.pop(0)
class Player:
def __init__(self,name,chips):
self.name = name
self.chips = chips
self.bet = 0
def __str__(self):
return 'Player {} has {} chips\n'.format(self.name,self.chips)
def add_chips(self,chips):
self.chips += chips
def remove_chips(self,chips):
if chips > self.chips or chips < 1:
print("Invalid amount of Chips.")
print("Current balance = {}".format(self.chips))
else:
self.chips -= chips
print("Current balance = {}".format(self.chips))
class Hand:
def __init__(self):
self.cards = []
self.value = 0
self.ace_count = 0
def __str__(self):
cards_in_hand = ''
for x in range(len(self.cards)):
cards_in_hand += " " + str(self.cards[x]) + "\n"
return cards_in_hand + "This hand has a value of {}.".format(self.value)
def add_card(self,card):
self.cards.append(card)
self.value += card.value
if card.rank == "Ace":
self.ace_count += 1
while self.value > 21 and self.ace_count > 0:
self.value -= 10
self.ace_count -= 1
def take_bet(player):
while True:
try:
current_bet = int(inputimeout(prompt="Amount of chips to bet: ", timeout=60))
if current_bet > player.chips or current_bet < 1:
print("Invalid amount. Please try again\n")
else:
player.bet += current_bet
player.chips -= current_bet
break
except ValueError:
print("That is an invalid option! Please try again\n")
except TimeoutOccurred:
print("Oof! Not fast enough!\n")
sys.exit()
def create_player():
global player
while True:
try:
player_name = inputimeout("Please enter your name: ", timeout=60)
if player_name != '':
break
else:
print("Please enter a valid name\n")
except TimeoutOccurred:
print("Oof! Not fast enough!\n")
sys.exit()
player = Player(player_name,1000)
def adjust_winnings(winner):
if winner == "player":
player.chips += int(player.bet*1.5)
player.bet = 0
elif winner == "tie" :
player.chips += player.bet
player.bet = 0
else:
player.bet = 0
def hit_or_stand(player_hand,deck_1):
while True:
try:
temp = inputimeout(prompt="HIT OR STAND? : ", timeout=60)
if temp == '':
print("Please choose a valid option\n")
elif temp[0].lower() == 'h':
player_hand.add_card(deck_1.deal_one())
break
elif temp[0].lower() == 's':
break
else:
print("Please choose a valid option\n")
except TimeoutOccurred:
print("Oof! Not fast enough!\n")
sys.exit()
if temp[0].lower() == 'h':
return "h"
else:
return "s"
def player_busted():
global winner
print("\nPlayer Busted.")
print("Dealer Wins!\n")
winner = "dealer"
def dealer_busted():
global winner
print("\nDealer Busted.")
print("Player Wins!\n")
winner = "player"
def player_dealer_tie():
global winner
print("IT'S A TIE!!\n")
winner = "tie"
def player_wins():
global winner
print("Player Wins!\n")
winner = "player"
def dealer_wins():
global winner
print("Dealer Wins!\n")
winner = "dealer"
def show_some_cards(player_hand, dealer_hand):
print("\nPlayer Cards are : ")
print(str(player_hand))
print("\nDealer Cards are : ")
print(" " + str(dealer_hand.cards[0]))
print("**Card is Hidden.**")
print(50*'*')
def show_all_cards(player_hand, dealer_hand):
print("\nPlayer Cards are : ")
print(str(player_hand))
print("\nDealer Cards are : ")
print(str(dealer_hand))
print(50*'*')
def main(player):
deck_1=Deck()
deck_1.shuffle_deck()
player_hand = Hand()
dealer_hand = Hand()
print(50*'*')
print(player)
take_bet(player)
player_hand.add_card(deck_1.deal_one())
player_hand.add_card(deck_1.deal_one())
dealer_hand.add_card(deck_1.deal_one())
dealer_hand.add_card(deck_1.deal_one())
show_some_cards(player_hand, dealer_hand)
while True:
if player_hand.value == 21:
break
elif player_hand.value > 21:
player_busted()
break
req = hit_or_stand(player_hand, deck_1)
if req == 's':
break
show_some_cards(player_hand, dealer_hand)
show_all_cards(player_hand, dealer_hand)
dealer_playing = True
while dealer_playing:
if player_hand.value <= 21:
while dealer_hand.value < 17 :
print("\nDealer Hits......")
dealer_hand.add_card(deck_1.deal_one())
show_all_cards(player_hand, dealer_hand)
dealer_playing = False
if dealer_hand.value > 21:
dealer_busted()
break
elif player_hand.value == dealer_hand.value:
player_dealer_tie()
break
elif player_hand.value > dealer_hand.value:
player_wins()
break
else:
dealer_wins()
break
else:
break
adjust_winnings(winner)
print("\n" + str(player))
def play_again():
while True:
print(50*'*')
try:
temp = inputimeout(prompt="\nWant to play again? : ", timeout=60)
if temp[0].lower() == 'y':
return True
elif temp[0].lower() == 'n':
print(50*'*')
print("\nThank you for playing...\n")
print(50*'*')
return False
else:
print("Please choose a valid option\n")
except TimeoutOccurred:
print("Oof! Not fast enough!\n")
sys.exit()
if __name__ == '__main__':
playing = True
create_player()
global rng
rng = PRNG()
while playing:
main(player)
if player.chips >= 1000000:
print(50*'*')
print("Congratulations on winning this big! Here's a special reward for that...")
with open('flag.txt', 'r') as f:
print(f.read())
print("\nThank you for playing...\n")
print(50*'*')
break
elif player.chips == 0:
print(50*'*')
print("Sorry for losing everything. Better luck next time!")
print(50*'*')
break
playing=play_again() | python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/NahamCon/2024/crypto/Encryption_Server/RSA_Encryption_Server.py | ctfs/NahamCon/2024/crypto/Encryption_Server/RSA_Encryption_Server.py | #!/usr/bin/python3
from secrets import randbits
from sympy import nextprime
import random
e = random.randint(500,1000)
def encrypt(inp):
p = nextprime(randbits(1024))
q = nextprime(randbits(1024))
n = p * q
c = [pow(ord(m), e, n) for m in inp]
return [n, c]
def main():
while True:
print('Welcome to the Really Shotty Asymmetric (RSA) Encryption Server!')
print('1: Encrypt a message')
print('2: View the encrypted flag')
print('3: Exit')
inp = ''
while (not ('1' in inp or '2' in inp or '3' in inp)):
inp = input('> ')
if('3' in inp):
print('Goodbye!')
exit()
elif('1' in inp):
plain = input('Enter a message, and the server will encrypt it with a random N!\n> ')
encrypted = encrypt(plain)
elif('2' in inp):
data = open('flag.txt', 'r').read()
data = data.strip()
encrypted = encrypt(data)
print('Your randomly chosen N:')
print(f'> {encrypted[0]}')
print('Your encrypted message:')
print(f'> {encrypted[1]}')
print('\n')
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/NahamCon/2023/crypto/ForgeMe_1/crypto.py | ctfs/NahamCon/2023/crypto/ForgeMe_1/crypto.py | import struct
import binascii
""" Implements the SHA1 hash function [1].
Emulates a barebones version of Python's `hashlib.hash` interface [2],
providing the simplest parts:
- update(data): adds binary data to the hash
- hexdigest(): returns the hexed hash value for the data added thus far
[1]: https://tools.ietf.org/html/rfc3174.
[2]: https://docs.python.org/3/library/hashlib.html.
"""
class Sha1:
def __init__(self, initial:bytes = None):
self._buffer = b''
if initial is not None: self.update(initial)
def update(self, data: bytes):
if not isinstance(data, bytes):
raise TypeError(f"expected bytes for data, got {type(data)}")
self._buffer += data
return self
def hexdigest(self, extra_length=0, initial_state=None):
tag = self.sha1(bytes(self._buffer), extra_length=extra_length, initial_state=initial_state)
self.clear()
return tag
def clear(self):
self._buffer = b''
# https://tools.ietf.org/html/rfc3174#section-4
@staticmethod
def create_padding(message: bytes, extra_length: int = 0) -> bytes:
l = (len(message) + extra_length) * 8
l2 = ((l // 512) + 1) * 512
padding_length = l2 - l
if padding_length < 72:
padding_length += 512
assert padding_length >= 72, "padding too short"
assert padding_length % 8 == 0, "padding not multiple of 8"
# Encode the length and add it to the end of the message.
zero_bytes = (padding_length - 72) // 8
length = struct.pack(">Q", l)
pad = bytes([0x80] + [0] * zero_bytes)
return pad + length
@staticmethod
def pad_message(message: bytes, extra_length: int = 0) -> bytes:
if not isinstance(message, bytes):
raise ValueError("expected bytes for message, got %s" % type(message))
pad = Sha1.create_padding(message, extra_length)
message = message + pad
assert (len(message) * 8) % 512 == 0, f"message bitlength ({len(message)}) not a multiple of 512"
return message
# https://tools.ietf.org/html/rfc3174#section-6.1
@staticmethod
def sha1(message: bytes, initial_state: [int] = None, extra_length: int = 0) -> str:
""" Returns the 20-byte hex digest of the message.
>>> Sha1.sha1(b"Hello, world!")
'943a702d06f34599aee1f8da8ef9f7296031d699'
"""
H = [0x67452301, 0xEFCDAB89, 0x98BADCFE, 0x10325476, 0xC3D2E1F0]
if initial_state is not None:
if len(initial_state) != 5 or any(not isinstance(x, int) for x in initial_state):
raise TypeError(f"expected list of 5 ints, got {initial_state}")
H = initial_state
# pad according to the RFC (and then some, if specified)
padded_msg = Sha1.pad_message(message, extra_length=extra_length)
# break message into chunks
M = [padded_msg[i:i+64] for i in range(0, len(padded_msg), 64)]
assert len(M) == len(padded_msg) / 64
for i in range(len(M)):
assert len(M[i]) == 64 # sanity check
# hashing magic
for i in range(len(M)):
W = [
int.from_bytes(M[i][j:j+4], byteorder="big")
for j in range(0, len(M[i]), 4)
]
assert len(W) == 16
assert type(W[0]) == int
assert W[0] == (M[i][0] << 24) + (M[i][1] << 16) + (M[i][2] << 8) + M[i][3]
for t in range(16, 80):
W.append(Sha1._S(1, W[t - 3] ^ W[t - 8] ^ W[t - 14] ^ W[t - 16]))
A, B, C, D, E = H
for t in range(80):
TEMP = (((((((Sha1._S(5, A) + Sha1._f(t, B, C, D)) & 0xFFFFFFFF) + E) & 0xFFFFFFFF) + W[t]) & 0xFFFFFFFF) + Sha1._K(t)) & 0xFFFFFFFF
assert TEMP == (Sha1._S(5, A) + Sha1._f(t, B, C, D) + E + W[t] + Sha1._K(t)) & 0xFFFFFFFF
E, D, C, B, A = D, C, Sha1._S(30, B), A, TEMP
H = [
(H[0] + A) & 0xFFFFFFFF,
(H[1] + B) & 0xFFFFFFFF,
(H[2] + C) & 0xFFFFFFFF,
(H[3] + D) & 0xFFFFFFFF,
(H[4] + E) & 0xFFFFFFFF,
]
# craft the hex digest
th = lambda h: hex(h)[2:] # trimmed hex
return "".join("0" * (8 - len(th(h))) + th(h) for h in H)
@staticmethod
def _f(t, B, C, D):
if t >= 0 and t <= 19: return ((B & C) | ((~B) & D)) & 0xFFFFFFFF
elif t >= 20 and t <= 39: return (B ^ C ^ D) & 0xFFFFFFFF
elif t >= 40 and t <= 59: return ((B & C) | (B & D) | (C & D)) & 0xFFFFFFFF
elif t >= 60 and t <= 79: return (B ^ C ^ D) & 0xFFFFFFFF
assert False
@staticmethod
def _K(t):
if t >= 0 and t <= 19: return 0x5A827999
elif t >= 20 and t <= 39: return 0x6ED9EBA1
elif t >= 40 and t <= 59: return 0x8F1BBCDC
elif t >= 60 and t <= 79: return 0xCA62C1D6
assert False
@staticmethod
def _S(n, X):
assert n >= 0 and n < 32, "n not in range"
assert (X >> 32) == 0, "X too large"
result = ((X << n) | (X >> (32-n))) & 0xFFFFFFFF
assert (result >> 32) == 0, "result too large"
return result
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/NahamCon/2023/crypto/ForgeMe_1/oracle.py | ctfs/NahamCon/2023/crypto/ForgeMe_1/oracle.py | import socket
import threading
from _thread import *
from Crypto import Random
from binascii import hexlify, unhexlify
import crypto
HOST = '0.0.0.0' # Standard loopback interface address (localhost)
PORT = 1234 # Port to listen on (non-privileged ports are > 1023)
FLAG = open('flag.txt', 'r').read().strip()
MENU = "\nWhat would you like to do?\n\t(1) MAC Query\n\t(2) Verification Query\n\t(3) Forgery\n\t(4) Exit\n\nChoice: "
INITIAL = "Can you break my hashed-based MAC?\n"
MAX_QUERIES = 100
KEYLEN = 64
TAGLEN = 20 # SHA1() tag is 20 bytes
# t = H(key || msg)
def hashed_mac(msg, key):
h = crypto.Sha1(key + msg)
t = h.hexdigest()
return t
# H(key || msg) == tag
def vf_query(conn, key, first_part=None):
conn.sendall(b'msg (hex): ')
msg = conn.recv(1024).strip()
conn.sendall(b'tag (hex): ')
tag = conn.recv(1024).strip()
try:
msg = unhexlify(msg)
if first_part is not None and first_part not in msg:
conn.sendall(f'Yoinks scoobs! Ya gotta include the first part\n'.encode())
elif len(tag) != TAGLEN*2:
conn.sendall(f'Invalid tag length. Must be {TAGLEN} bytes\n'.encode())
else:
t_ret = hashed_mac(msg, key)
return t_ret.encode() == tag, msg
except Exception as e:
conn.sendall(b'Invalid msg format. Must be in hexadecimal\n')
return False, b''
def mac_query(conn, key):
conn.sendall(b'msg (hex): ')
msg = conn.recv(1024).strip()
try:
msg = unhexlify(msg)
t = hashed_mac(msg, key)
conn.sendall(f'H(key || msg): {t}\n'.encode())
return msg
except Exception as e:
conn.sendall(b'Invalid msg format. Must be in hexadecimal\n')
return None
def threading(conn):
conn.sendall(INITIAL.encode())
first_part = b'I guess you are just gonna have to include this!'
key = Random.get_random_bytes(KEYLEN)
queries = []
while len(queries) < MAX_QUERIES:
conn.sendall(MENU.encode())
try:
choice = conn.recv(1024).decode().strip()
except ConnectionResetError as cre:
return
# MAC QUERY
if choice == '1':
msg = mac_query(conn, key)
if msg is not None:
queries.append(msg)
# VF QUERY
elif choice == '2':
res, msg = vf_query(conn, key)
conn.sendall(str(res).encode())
# FORGERY
elif choice == '3':
res, msg = vf_query(conn, key, first_part)
if res and msg not in queries:
conn.sendall(FLAG.encode() + b'\n')
elif msg in queries:
conn.sendall(b"cheater!!!\n")
else:
conn.sendall(str(res).encode() + b'\n')
break
# EXIT or INVALID CHOICE
else:
if choice == '4':
conn.sendall(b'bye\n')
else:
conn.sendall(b'invalid menu choice\n')
break
if len(queries) > MAX_QUERIES:
conn.sendall(f'too many queries: {len(queries)}\n'.encode())
conn.close()
if __name__ == "__main__":
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
s.bind((HOST, PORT))
s.listen()
while True:
conn, addr = s.accept()
print(f'new connection: {addr}')
start_new_thread(threading, (conn, ))
s.close()
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/NahamCon/2023/crypto/ForgeMe_2/crypto.py | ctfs/NahamCon/2023/crypto/ForgeMe_2/crypto.py | import struct
import binascii
""" Implements the SHA1 hash function [1].
Emulates a barebones version of Python's `hashlib.hash` interface [2],
providing the simplest parts:
- update(data): adds binary data to the hash
- hexdigest(): returns the hexed hash value for the data added thus far
[1]: https://tools.ietf.org/html/rfc3174.
[2]: https://docs.python.org/3/library/hashlib.html.
"""
class Sha1:
def __init__(self, initial:bytes = None):
self._buffer = b''
if initial is not None: self.update(initial)
def update(self, data: bytes):
if not isinstance(data, bytes):
raise TypeError(f"expected bytes for data, got {type(data)}")
self._buffer += data
return self
def hexdigest(self, extra_length=0, initial_state=None):
tag = self.sha1(bytes(self._buffer), extra_length=extra_length, initial_state=initial_state)
self.clear()
return tag
def clear(self):
self._buffer = b''
# https://tools.ietf.org/html/rfc3174#section-4
@staticmethod
def create_padding(message: bytes, extra_length: int = 0) -> bytes:
l = (len(message) + extra_length) * 8
l2 = ((l // 512) + 1) * 512
padding_length = l2 - l
if padding_length < 72:
padding_length += 512
assert padding_length >= 72, "padding too short"
assert padding_length % 8 == 0, "padding not multiple of 8"
# Encode the length and add it to the end of the message.
zero_bytes = (padding_length - 72) // 8
length = struct.pack(">Q", l)
pad = bytes([0x80] + [0] * zero_bytes)
return pad + length
@staticmethod
def pad_message(message: bytes, extra_length: int = 0) -> bytes:
if not isinstance(message, bytes):
raise ValueError("expected bytes for message, got %s" % type(message))
pad = Sha1.create_padding(message, extra_length)
message = message + pad
assert (len(message) * 8) % 512 == 0, f"message bitlength ({len(message)}) not a multiple of 512"
return message
# https://tools.ietf.org/html/rfc3174#section-6.1
@staticmethod
def sha1(message: bytes, initial_state: [int] = None, extra_length: int = 0) -> str:
""" Returns the 20-byte hex digest of the message.
>>> Sha1.sha1(b"Hello, world!")
'943a702d06f34599aee1f8da8ef9f7296031d699'
"""
H = [0x67452301, 0xEFCDAB89, 0x98BADCFE, 0x10325476, 0xC3D2E1F0]
if initial_state is not None:
if len(initial_state) != 5 or any(not isinstance(x, int) for x in initial_state):
raise TypeError(f"expected list of 5 ints, got {initial_state}")
H = initial_state
# pad according to the RFC (and then some, if specified)
padded_msg = Sha1.pad_message(message, extra_length=extra_length)
# break message into chunks
M = [padded_msg[i:i+64] for i in range(0, len(padded_msg), 64)]
assert len(M) == len(padded_msg) / 64
for i in range(len(M)):
assert len(M[i]) == 64 # sanity check
# hashing magic
for i in range(len(M)):
W = [
int.from_bytes(M[i][j:j+4], byteorder="big")
for j in range(0, len(M[i]), 4)
]
assert len(W) == 16
assert type(W[0]) == int
assert W[0] == (M[i][0] << 24) + (M[i][1] << 16) + (M[i][2] << 8) + M[i][3]
for t in range(16, 80):
W.append(Sha1._S(1, W[t - 3] ^ W[t - 8] ^ W[t - 14] ^ W[t - 16]))
A, B, C, D, E = H
for t in range(80):
TEMP = (((((((Sha1._S(5, A) + Sha1._f(t, B, C, D)) & 0xFFFFFFFF) + E) & 0xFFFFFFFF) + W[t]) & 0xFFFFFFFF) + Sha1._K(t)) & 0xFFFFFFFF
assert TEMP == (Sha1._S(5, A) + Sha1._f(t, B, C, D) + E + W[t] + Sha1._K(t)) & 0xFFFFFFFF
E, D, C, B, A = D, C, Sha1._S(30, B), A, TEMP
H = [
(H[0] + A) & 0xFFFFFFFF,
(H[1] + B) & 0xFFFFFFFF,
(H[2] + C) & 0xFFFFFFFF,
(H[3] + D) & 0xFFFFFFFF,
(H[4] + E) & 0xFFFFFFFF,
]
# craft the hex digest
th = lambda h: hex(h)[2:] # trimmed hex
return "".join("0" * (8 - len(th(h))) + th(h) for h in H)
@staticmethod
def _f(t, B, C, D):
if t >= 0 and t <= 19: return ((B & C) | ((~B) & D)) & 0xFFFFFFFF
elif t >= 20 and t <= 39: return (B ^ C ^ D) & 0xFFFFFFFF
elif t >= 40 and t <= 59: return ((B & C) | (B & D) | (C & D)) & 0xFFFFFFFF
elif t >= 60 and t <= 79: return (B ^ C ^ D) & 0xFFFFFFFF
assert False
@staticmethod
def _K(t):
if t >= 0 and t <= 19: return 0x5A827999
elif t >= 20 and t <= 39: return 0x6ED9EBA1
elif t >= 40 and t <= 59: return 0x8F1BBCDC
elif t >= 60 and t <= 79: return 0xCA62C1D6
assert False
@staticmethod
def _S(n, X):
assert n >= 0 and n < 32, "n not in range"
assert (X >> 32) == 0, "X too large"
result = ((X << n) | (X >> (32-n))) & 0xFFFFFFFF
assert (result >> 32) == 0, "result too large"
return result
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/NahamCon/2023/crypto/ForgeMe_2/oracle.py | ctfs/NahamCon/2023/crypto/ForgeMe_2/oracle.py | import socket
import threading
from _thread import *
from Crypto.Random import get_random_bytes, random
from binascii import hexlify, unhexlify
import crypto
from wonderwords import RandomWord
HOST = '0.0.0.0' # Standard loopback interface address (localhost)
PORT = 1234 # Port to listen on (non-privileged ports are > 1023)
FLAG = open('flag.txt', 'r').read().strip()
MENU = "\nWhat would you like to do?\n\t(1) MAC Query\n\t(2) Verification Query\n\t(3) Forgery\n\t(4) Exit\n\nChoice: "
INITIAL = "Can you break my hashed-based MAC again?\n"
MAX_QUERIES = 100
TAGLEN = 20 # SHA1() tag is 20 bytes
INJECTION = b'https://www.youtube.com/@_JohnHammond'
# t = H(key || msg)
def hashed_mac(msg, key):
h = crypto.Sha1(key + msg)
t = h.hexdigest()
return t
# H(key || msg) == tag
def vf_query(conn, key, first_part=None):
conn.sendall(b'msg (hex): ')
msg = conn.recv(1024).strip()
conn.sendall(b'tag (hex): ')
tag = conn.recv(1024).strip()
try:
msg = unhexlify(msg)
if first_part is not None and (first_part not in msg or INJECTION not in msg):
conn.sendall(f'forgot something!\n'.encode())
elif len(tag) != TAGLEN*2:
conn.sendall(f'Invalid tag length. Must be {TAGLEN} bytes\n'.encode())
else:
t_ret = hashed_mac(msg, key)
return t_ret.encode() == tag, msg
except Exception as e:
conn.sendall(b'Invalid msg format. Must be in hexadecimal\n')
return False, b''
def mac_query(conn, key):
conn.sendall(b'msg (hex): ')
msg = conn.recv(1024).strip()
try:
msg = unhexlify(msg)
t = hashed_mac(msg, key)
conn.sendall(f'H(key || msg): {t}\n'.encode())
return msg
except Exception as e:
conn.sendall(b'Invalid msg format. Must be in hexadecimal\n')
return None
def threading(conn):
conn.sendall(INITIAL.encode())
rw = RandomWord()
first_part = '-'.join(rw.random_words(random.randrange(5,30), word_min_length=5)).encode()
conn.sendall(f'first_part: {first_part.decode()}\n'.encode())
key = get_random_bytes(random.randrange(10,120))
queries = []
while len(queries) < MAX_QUERIES:
conn.sendall(MENU.encode())
try:
choice = conn.recv(1024).decode().strip()
except ConnectionResetError as cre:
return
# MAC QUERY
if choice == '1':
msg = mac_query(conn, key)
if msg is not None:
queries.append(msg)
# VF QUERY
elif choice == '2':
res, msg = vf_query(conn, key)
conn.sendall(str(res).encode())
# FORGERY
elif choice == '3':
res, msg = vf_query(conn, key, first_part)
if res and msg not in queries:
conn.sendall(FLAG.encode() + b'\n')
elif msg in queries:
conn.sendall(b"cheater!!!\n")
else:
conn.sendall(str(res).encode() + b'\n')
break
# EXIT or INVALID CHOICE
else:
if choice == '4':
conn.sendall(b'bye\n')
else:
conn.sendall(b'invalid menu choice\n')
break
if len(queries) > MAX_QUERIES:
conn.sendall(f'too many queries: {len(queries)}\n'.encode())
conn.close()
if __name__ == "__main__":
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
s.bind((HOST, PORT))
s.listen()
while True:
conn, addr = s.accept()
print(f'new connection: {addr}')
start_new_thread(threading, (conn, ))
s.close()
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/NahamCon/2023/crypto/RSA_Intro/gen.py | ctfs/NahamCon/2023/crypto/RSA_Intro/gen.py | from Crypto.Util.number import getStrongPrime, getPrime, bytes_to_long as b2l
FLAG = open('flag.txt', 'r').read().strip()
OUT = open('output.txt', 'w')
l = len(FLAG)
flag1, flag2, flag3 = FLAG[:l//3], FLAG[l//3:2*l//3], FLAG[2*l//3:]
# PART 1
e = 0x10001
p = getStrongPrime(1024)
q = getStrongPrime(1024)
n = p*q
ct = pow(b2l(flag1.encode()), e, n)
OUT.write(f'*** PART 1 ***\ne: {e}\np: {p}\nq: {q}\nct: {ct}')
# PART 2
e = 3
p = getStrongPrime(1024)
q = getStrongPrime(1024)
n = p*q
ct = pow(b2l(flag2.encode()), e, n)
OUT.write(f'\n\n*** PART 2 ***\ne: {e}\nn: {n}\nct: {ct}')
# PART 3
e = 65537
p = getPrime(24)
q = getPrime(24)
n = p*q
fl = round(len(flag3)/4)
f3_parts = [flag3[i:i+4] for i in range(0, len(flag3), 4)]
assert ''.join(f3_parts) == flag3
ct_parts = []
for part in f3_parts:
pt = b2l(part.encode())
assert pt < n
ct = pow(pt, e, n)
ct_parts.append(ct)
OUT.write(f'\n\n*** PART 3 ***\ne: {e}\nn: {n}\nct: {ct_parts}')
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/NahamCon/2023/crypto/Just_One_More/jom.py | ctfs/NahamCon/2023/crypto/Just_One_More/jom.py | import random
OUT = open('output.txt', 'w')
FLAG = open('flag.txt', 'r').read().strip()
N = 64
l = len(FLAG)
arr = [random.randint(1,pow(2, N)) for _ in range(l)]
OUT.write(f'{arr}\n')
s_arr = []
for i in range(len(FLAG) - 1):
s_i = sum([arr[j]*ord(FLAG[j]) for j in range(l)])
s_arr.append(s_i)
arr = [arr[-1]] + arr[:-1]
OUT.write(f'{s_arr}\n')
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/NahamCon/2023/crypto/RSA_Outro/gen.py | ctfs/NahamCon/2023/crypto/RSA_Outro/gen.py | from Crypto.Util.number import getStrongPrime, isPrime, inverse, bytes_to_long as b2l
FLAG = open('flag.txt', 'r').read()
# safe primes are cool
# https://en.wikipedia.org/wiki/Safe_and_Sophie_Germain_primes
while True:
q = getStrongPrime(512)
p = 2*q + 1
if (isPrime(p)):
break
n = p*q
phi = (p-1)*(q-1)
e = 0x10001
d = inverse(e, phi)
pt = b2l(FLAG.encode())
ct = pow(pt,e,n)
open('output.txt', 'w').write(f'e: {e}\nd: {d}\nphi: {phi}\nct: {ct}')
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/NahamCon/2023/web/Transfer/app.py | ctfs/NahamCon/2023/web/Transfer/app.py | from flask import Flask, request, render_template, redirect, url_for, flash, g, session, send_file
import io
import base64
from flask_login import LoginManager, UserMixin, login_user, login_required, logout_user, current_user
from functools import wraps
import sqlite3
import pickle
import os
import uuid
from werkzeug.utils import secure_filename
from datetime import datetime, timedelta
app = Flask(__name__)
app.secret_key = os.urandom(24)
DATABASE = '/tmp/database.db'
login_manager = LoginManager()
login_manager.init_app(app)
def login_required(f):
@wraps(f)
def decorated_function(*args, **kwargs):
if 'session_id' not in session:
return redirect(url_for('home', next=request.url))
return f(*args, **kwargs)
return decorated_function
class User(UserMixin):
pass
def get_db():
db = getattr(g, '_database', None)
if db is None:
db = g._database = sqlite3.connect(DATABASE)
return db
@app.teardown_appcontext
def close_connection(exception):
db = getattr(g, '_database', None)
if db is not None:
db.close()
@login_manager.user_loader
def user_loader(username):
conn = get_db()
c = conn.cursor()
c.execute(f"SELECT * FROM users WHERE username='{username}'")
user_data = c.fetchone()
if user_data is None:
return
user = User()
user.id = user_data[0]
return user
@app.before_request
def before_request():
g.user = current_user
if g.user.is_authenticated:
conn = get_db()
c = conn.cursor()
c.execute(f"SELECT timestamp FROM activesessions WHERE username='{g.user.id}'")
timestamp = c.fetchone()[0]
if datetime.now() - datetime.strptime(timestamp, "%Y-%m-%d %H:%M:%S.%f") > timedelta(minutes=5):
flash('Your session has expired')
return logout()
else:
c.executescript(f"UPDATE activesessions SET timestamp='{datetime.now()}' WHERE username='{g.user.id}'")
conn.commit()
@app.route('/')
def home():
return render_template('login.html')
@app.route('/files')
@login_required
def files():
conn = get_db()
c = conn.cursor()
c.execute("SELECT filename FROM files")
file_list = c.fetchall()
return render_template('files.html', files=file_list)
def DBClean(string):
for bad_char in " '\"":
string = string.replace(bad_char,"")
return string.replace("\\", "'")
@app.route('/login', methods=['POST'])
def login_user():
username = DBClean(request.form['username'])
password = DBClean(request.form['password'])
conn = get_db()
c = conn.cursor()
sql = f"SELECT * FROM users WHERE username='{username}' AND password='{password}'"
c.executescript(sql)
user = c.fetchone()
if user:
c.execute(f"SELECT sessionid FROM activesessions WHERE username=?", (username,))
active_session = c.fetchone()
if active_session:
session_id = active_session[0]
else:
c.execute(f"SELECT username FROM users WHERE username=?", (username,))
user_name = c.fetchone()
if user_name:
session_id = str(uuid.uuid4())
c.executescript(f"INSERT INTO activesessions (sessionid, timestamp) VALUES ('{session_id}', '{datetime.now().strftime('%Y-%m-%d %H:%M:%S.%f')}')")
else:
flash("A session could be not be created")
return logout()
session['username'] = username
session['session_id'] = session_id
conn.commit()
return redirect(url_for('files'))
else:
flash('Username or password is incorrect')
return redirect(url_for('home'))
@app.route('/logout', methods=['GET'])
def logout():
if 'session_id' in session:
conn = get_db()
c = conn.cursor()
c.executescript(f"DELETE FROM activesessions WHERE sessionid=" + session['session_id'])
conn.commit()
session.pop('username', None)
session.pop('session_id', None)
return redirect(url_for('home'))
@app.route('/download/<filename>/<sessionid>', methods=['GET'])
def download_file(filename, sessionid):
conn = get_db()
c = conn.cursor()
c.execute(f"SELECT * FROM activesessions WHERE sessionid=?", (sessionid,))
active_session = c.fetchone()
if active_session is None:
flash('No active session found')
return redirect(url_for('home'))
c.execute(f"SELECT data FROM files WHERE filename=?",(filename,))
file_data = c.fetchone()
if file_data is None:
flash('File not found')
return redirect(url_for('files'))
file_blob = pickle.loads(base64.b64decode(file_data[0]))
return send_file(io.BytesIO(file_blob), download_name=filename, as_attachment=True)
@app.route('/upload', methods=['POST'])
@login_required
def upload_file():
flash('Sorry, the administrator has temporarily disabled file upload capability.')
return redirect(url_for('files'))
def init_db():
with app.app_context():
db = get_db()
c = db.cursor()
c.execute("CREATE TABLE IF NOT EXISTS users (username text, password text)")
c.execute("CREATE TABLE IF NOT EXISTS activesessions (sessionid text, username text, timestamp text)")
c.execute("CREATE TABLE IF NOT EXISTS files (filename text PRIMARY KEY, data blob, sessionid text)")
c.execute("INSERT OR IGNORE INTO files VALUES ('flag.txt', ?, NULL)",
(base64.b64encode(pickle.dumps(b'lol just kidding this isnt really where the flag is')).decode('utf-8'),))
c.execute("INSERT OR IGNORE INTO files VALUES ('NahamCon-2024-Speakers.xlsx', ?, NULL)",
(base64.b64encode(pickle.dumps(b'lol gottem')).decode('utf-8'),))
db.commit()
if __name__ == '__main__':
with app.app_context():
init_db()
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/NahamCon/2025/misc/SSH_Key_Tester/main.py | ctfs/NahamCon/2025/misc/SSH_Key_Tester/main.py | #!/usr/bin/env python3
import os
import base64
import binascii as bi
import tempfile
import traceback
import subprocess
import sys
from flask import Flask, request
import random
sys.path.append("../")
app = Flask(__name__)
app.config['UPLOAD_FOLDER'] = '/tmp'
app.config['MAX_CONTENT_LENGTH'] = 16 * 1024 * 1024 # 16 MB
@app.route("/", methods=["GET", "POST"])
def run():
print(request.files)
if len(request.files) != 2:
return "Please submit both private and public key to test.", 400
if not request.files.get("id_rsa"):
return "`id_rsa` file not found.", 400
if not request.files.get("id_rsa.pub"):
return "`id_rsa.pub` file not found.", 400
privkey = request.files.get("id_rsa").read()
pubkey = request.files.get("id_rsa.pub").read()
if pubkey.startswith(b"command="):
return "No command= allowed!", 400
os.system("service ssh start")
userid = "user%d" % random.randint(0, 1000)
os.system("useradd %s && mkdir -p /home/%s/.ssh" % (userid, userid))
with open("/tmp/id_rsa", "wb") as fd:
fd.write(privkey)
os.system("chmod 0600 /tmp/id_rsa")
with open("/home/%s/.ssh/authorized_keys" % userid, "wb") as fd:
fd.write(pubkey)
os.system("timeout 2 ssh -o StrictHostKeyChecking=no -i /tmp/id_rsa %s@localhost &" % userid)
return "Keys pass the checks.", 200
if __name__ == "__main__":
app.run(host="0.0.0.0", port=8080, debug=True)
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/NahamCon/2025/crypto/Cookie_Encryption/encryption.py | ctfs/NahamCon/2025/crypto/Cookie_Encryption/encryption.py | from Crypto.PublicKey import RSA
from Crypto.Cipher import PKCS1_v1_5
private_key = RSA.importKey(open('private_key.pem').read())
public_key = private_key.publickey()
def encrypt(plaintext):
cipher_rsa = PKCS1_v1_5.new(public_key)
ciphertext = cipher_rsa.encrypt(plaintext)
return ciphertext
def decrypt(ciphertext):
sentinel = b"Error in decryption!"
try:
cipher_rsa = PKCS1_v1_5.new(private_key)
plaintext = cipher_rsa.decrypt(ciphertext, sentinel)
if plaintext != b'':
return plaintext
else:
raise ValueError
except:
return sentinel | python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/NahamCon/2025/crypto/Cookie_Encryption/app.py | ctfs/NahamCon/2025/crypto/Cookie_Encryption/app.py | import requests
from flask import Flask, render_template, request, session, redirect, abort, url_for, make_response
from models import db, Users
from sqlalchemy_utils import database_exists
from sqlalchemy.exc import OperationalError
from encryption import encrypt, decrypt
app = Flask(__name__)
app.config.from_object('config')
db.init_app(app)
def authed():
return bool(session.get('id', False))
with app.app_context():
if database_exists(app.config['SQLALCHEMY_DATABASE_URI']) is False:
try:
db.create_all()
except OperationalError:
pass
admin = Users.query.filter_by(username='admin').first()
if admin is None:
admin = Users('admin', 'admin')
admin.password = 'admin'
db.session.add(admin)
db.session.commit()
@app.context_processor
def inject_user():
if session:
return dict(session)
return dict()
@app.route('/')
def index():
return render_template('index.html')
@app.route('/login', methods=['GET', 'POST'])
def login():
if request.method == 'GET':
return render_template('login.html')
else:
username = request.form.get('username').strip()
password = request.form.get('password').strip()
errors = []
user = Users.query.filter_by(username=username).first()
if user:
if user.password == password:
session['id'] = user.id
session['username'] = user.username
resp = make_response(redirect('/'))
if session['username'] != "admin":
resp.set_cookie('secret',encrypt(b"This is not the admin secret!").hex())
else:
resp.set_cookie('secret',encrypt(app.config.get("FLAG")).hex())
return resp
else:
errors.append("That password doesn't match what we have")
return render_template('login.html', errors=errors)
else:
errors.append("Couldn't find a user with that username")
return render_template('login.html', errors=errors)
@app.route('/register', methods=['GET', 'POST'])
def register():
if request.method == 'GET':
return render_template('register.html')
else:
username = request.form.get('username').strip()
password = request.form.get('password').strip()
confirm = request.form.get('confirm').strip()
errors = []
if password != confirm:
errors.append('Your passwords do not match')
if len(password) < 5:
errors.append('Your password must be longer')
exists = Users.query.filter_by(username=username).first()
if exists:
errors.append('That username is taken')
if errors:
return render_template('register.html', username=username, errors=errors)
user = Users(username, password)
db.session.add(user)
db.session.commit()
db.session.flush()
session['id'] = user.id
session['username'] = user.username
db.session.close()
resp = make_response(redirect('/'))
resp.set_cookie('secret',encrypt(b"This is not the admin secret!").hex())
return resp
@app.route('/cookie', methods=['GET'])
def cookie_checker():
if not authed():
return redirect('/login')
else:
secret = decrypt(bytearray.fromhex(request.cookies.get('secret')))
if b"Error" not in secret:
resp = make_response("The secret is all good!")
else:
resp = make_response("The secret is not all good!")
return resp
if __name__ == "__main__":
app.run(host="0.0.0.0", port=8000) | python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/NahamCon/2025/crypto/Cryptoclock/server.py | ctfs/NahamCon/2025/crypto/Cryptoclock/server.py | #!/usr/bin/env python3
import socket
import threading
import time
import random
import os
from typing import Optional
def encrypt(data: bytes, key: bytes) -> bytes:
"""Encrypt data using XOR with the given key."""
return bytes(a ^ b for a, b in zip(data, key))
def generate_key(length: int, seed: Optional[float] = None) -> bytes:
"""Generate a random key of given length using the provided seed."""
if seed is not None:
random.seed(int(seed))
return bytes(random.randint(0, 255) for _ in range(length))
def handle_client(client_socket: socket.socket):
"""Handle individual client connections."""
try:
with open('flag.txt', 'rb') as f:
flag = f.read().strip()
current_time = int(time.time())
key = generate_key(len(flag), current_time)
encrypted_flag = encrypt(flag, key)
welcome_msg = b"Welcome to Cryptoclock!\n"
welcome_msg += b"The encrypted flag is: " + encrypted_flag.hex().encode() + b"\n"
welcome_msg += b"Enter text to encrypt (or 'quit' to exit):\n"
client_socket.send(welcome_msg)
while True:
data = client_socket.recv(1024).strip()
if not data:
break
if data.lower() == b'quit':
break
key = generate_key(len(data), current_time)
encrypted_data = encrypt(data, key)
response = b"Encrypted: " + encrypted_data.hex().encode() + b"\n"
client_socket.send(response)
except Exception as e:
print(f"Error handling client: {e}")
finally:
client_socket.close()
def main():
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
server.bind(('0.0.0.0', 1337))
server.listen(5)
print("Server started on port 1337...")
try:
while True:
client_socket, addr = server.accept()
print(f"Accepted connection from {addr}")
client_thread = threading.Thread(target=handle_client, args=(client_socket,))
client_thread.start()
except KeyboardInterrupt:
print("\nShutting down server...")
finally:
server.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/NahamCon/2025/crypto/Cookie_Encryption_2/app.py | ctfs/NahamCon/2025/crypto/Cookie_Encryption_2/app.py | import requests
from flask import (
Flask,
render_template,
request,
session,
redirect,
abort,
url_for,
make_response,
)
from models import db, Users
from sqlalchemy_utils import database_exists
from sqlalchemy.exc import OperationalError
import socket
import time
app = Flask(__name__)
app.config.from_object("config")
db.init_app(app)
# Connect to sage
sage = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sage.setblocking(False)
addr = ("localhost", 5000)
try:
# Attempt to connect to the server
sage.connect(addr)
except BlockingIOError:
# Non-blocking sockets may raise a BlockingIOError if the connection is still in progress
pass
# You can continue with other tasks or use a loop to check the connection status
connected = False
while not connected:
try:
# Attempt to complete the connection
sage.connect(addr)
connected = True
except ConnectionRefusedError:
print("Connection refused. Server may not be available.")
break
except BlockingIOError:
# Connection is still in progress; you can perform other tasks here
pass
def recvline(sock, buffer_size=1):
"""
Receive a line of text from a socket.
:param sock: The socket to receive data from.
:param buffer_size: The size of the buffer for receiving data.
:return: The received line as a string, or None if the connection is closed.
"""
data = b"" # Initialize an empty bytes string to store received data.
while True:
while True:
try:
chunk = sock.recv(buffer_size) # Receive data in chunks.
break
except BlockingIOError:
time.sleep(1)
if not chunk:
# If no more data is received, the connection is closed.
if data:
return data
else:
return None
data += chunk
if b"\n" in data:
return data
time.sleep(3)
def menu_eating():
for _ in range(6):
print(recvline(sage), flush=True)
menu_eating()
def secret_encrypt(secret):
sage.send(b"3\n")
print(recvline(sage), flush=True)
sage.send(secret.encode() + b"\n")
resp = recvline(sage).decode().strip()
print(resp, flush=True)
enc_secret = hex(int(resp, 16))
menu_eating()
return enc_secret
def authed():
return bool(session.get("id", False))
with app.app_context():
if database_exists(app.config["SQLALCHEMY_DATABASE_URI"]) is False:
try:
db.create_all()
except OperationalError:
pass
admin = Users.query.filter_by(username="admin").first()
if admin is None:
admin = Users("admin", "admin")
admin.password = "admin"
db.session.add(admin)
db.session.commit()
@app.context_processor
def inject_user():
if session:
return dict(session)
return dict()
@app.route("/")
def index():
return render_template("index.html")
@app.route("/login", methods=["GET", "POST"])
def login():
if request.method == "GET":
return render_template("login.html")
else:
username = request.form.get("username").strip()
password = request.form.get("password").strip()
errors = []
user = Users.query.filter_by(username=username).first()
if user:
if user.password == password:
session["id"] = user.id
session["username"] = user.username
resp = make_response(redirect("/"))
if session["username"] != "admin":
message = (b"This is not the admin secret!").hex()
else:
message = (app.config.get("FLAG")).hex()
resp.set_cookie("secret", secret_encrypt(message))
resp.set_cookie("input", "00")
return resp
else:
errors.append("That password doesn't match what we have")
return render_template("login.html", errors=errors)
else:
errors.append("Couldn't find a user with that username")
return render_template("login.html", errors=errors)
@app.route("/register", methods=["GET", "POST"])
def register():
if request.method == "GET":
return render_template("register.html")
else:
username = request.form.get("username").strip()
password = request.form.get("password").strip()
confirm = request.form.get("confirm").strip()
errors = []
if password != confirm:
errors.append("Your passwords do not match")
if len(password) < 5:
errors.append("Your password must be longer")
exists = Users.query.filter_by(username=username).first()
if exists:
errors.append("That username is taken")
if errors:
return render_template("register.html", username=username, errors=errors)
user = Users(username, password)
db.session.add(user)
db.session.commit()
db.session.flush()
session["id"] = user.id
session["username"] = user.username
db.session.close()
resp = make_response(redirect("/"))
message = (b"This is not the admin secret!").hex()
resp.set_cookie("secret", secret_encrypt(message))
resp.set_cookie("input", "00")
return resp
@app.route("/encrypt", methods=["GET"])
def encrypt():
if not authed():
return redirect("/login")
else:
sage.send(b"1\n")
print(recvline(sage), flush=True)
cookie = request.cookies.get("input")
sage.send((str(cookie) + "\n").encode())
msg = recvline(sage).decode()
menu_eating()
resp = make_response(msg)
return resp
@app.route("/decrypt", methods=["GET"])
def decrypt():
if not authed():
return redirect("/login")
else:
sage.send(b"2\n")
print(recvline(sage), flush=True)
cookie = request.cookies.get("input")
sage.send((str(cookie) + "\n").encode())
msg = recvline(sage).decode()
menu_eating()
resp = make_response(msg)
return resp
if __name__ == "__main__":
app.run(host="0.0.0.0", port=8000)
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/NahamCon/2022/crypto/XORROX/xorrox.py | ctfs/NahamCon/2022/crypto/XORROX/xorrox.py | #!/usr/bin/env python3
import random
with open("flag.txt", "rb") as filp:
flag = filp.read().strip()
key = [random.randint(1, 256) for _ in range(len(flag))]
xorrox = []
enc = []
for i, v in enumerate(key):
k = 1
for j in range(i, 0, -1):
k ^= key[j]
xorrox.append(k)
enc.append(flag[i] ^ v)
with open("output.txt", "w") as filp:
filp.write(f"{xorrox=}\n")
filp.write(f"{enc=}\n")
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/NahamCon/2022/crypto/Unimod/unimod.py | ctfs/NahamCon/2022/crypto/Unimod/unimod.py | import random
flag = open('flag.txt', 'r').read()
ct = ''
k = random.randrange(0,0xFFFD)
for c in flag:
ct += chr((ord(c) + k) % 0xFFFD)
open('out', 'w').write(ct)
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/NahamCon/2022/web/Personnel/app.py | ctfs/NahamCon/2022/web/Personnel/app.py | #!/usr/bin/env python
from flask import Flask, Response, abort, request, render_template
import random
from string import *
import re
app = Flask(__name__)
flag = open("flag.txt").read()
users = open("users.txt").read()
users += flag
@app.route("/", methods=["GET", "POST"])
def index():
if request.method == "GET":
return render_template("lookup.html")
if request.method == "POST":
name = request.form["name"]
setting = int(request.form["setting"])
if name:
if name[0].isupper():
name = name[1:]
results = re.findall(r"[A-Z][a-z]*?" + name + r"[a-z]*?\n", users, setting)
results = [x.strip() for x in results if x or len(x) > 1]
return render_template("lookup.html", passed_results=True, results=results)
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/NahamCon/2022/web/Flaskmetal_Alchemist/src/models.py | ctfs/NahamCon/2022/web/Flaskmetal_Alchemist/src/models.py | from database import Base
from sqlalchemy import Column, Integer, String
class Metal(Base):
__tablename__ = "metals"
atomic_number = Column(Integer, primary_key=True)
symbol = Column(String(3), unique=True, nullable=False)
name = Column(String(40), unique=True, nullable=False)
def __init__(self, atomic_number=None, symbol=None, name=None):
self.atomic_number = atomic_number
self.symbol = symbol
self.name = name
class Flag(Base):
__tablename__ = "flag"
flag = Column(String(40), primary_key=True)
def __init__(self, flag=None):
self.flag = flag
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/NahamCon/2022/web/Flaskmetal_Alchemist/src/seed.py | ctfs/NahamCon/2022/web/Flaskmetal_Alchemist/src/seed.py | from models import Metal, Flag
from database import db_session, init_db
def seed_db():
init_db()
metals = [
Metal(3, "Li", "Lithium"),
Metal(4, "Be", "Beryllium"),
Metal(11, "Na", "Sodium"),
Metal(12, "Mg", "Magnesium"),
Metal(13, "Al", "Aluminum"),
Metal(19, "K", "Potassium"),
Metal(20, "Ca", "Calcium"),
Metal(21, "Sc", "Scandium"),
Metal(22, "Ti", "Titanium"),
Metal(23, "V", "Vanadium"),
Metal(24, "Cr", "Chromium"),
Metal(25, "Mn", "Manganese"),
Metal(26, "Fe", "Iron"),
Metal(27, "Co", "Cobalt"),
Metal(28, "Ni", "Nickel"),
Metal(29, "Cu", "Copper"),
Metal(30, "Zn", "Zinc"),
Metal(31, "Ga", "Gallium"),
Metal(37, "Rb", "Rubidium"),
Metal(38, "Sr", "Strontium"),
Metal(39, "Y", "Yttrium"),
Metal(40, "Zr", "Zirconium"),
Metal(41, "Nb", "Niobium"),
Metal(42, "Mo", "Molybdenum"),
Metal(43, "Tc", "Technetium"),
Metal(44, "Ru", "Ruthenium"),
Metal(45, "Rh", "Rhodium"),
Metal(46, "Pd", "Palladium"),
Metal(47, "Ag", "Silver"),
Metal(48, "Cd", "Cadmium"),
Metal(49, "In", "Indium"),
Metal(50, "Sn", "Tin"),
Metal(55, "Cs", "Cesium"),
Metal(56, "Ba", "Barium"),
Metal(57, "La", "Lanthanum"),
Metal(58, "Ce", "Cerium"),
Metal(59, "Pr", "Praseodymium"),
Metal(60, "Nd", "Neodymium"),
Metal(61, "Pm", "Promethium"),
Metal(62, "Sm", "Samarium"),
Metal(63, "Eu", "Europium"),
Metal(64, "Gd", "Gadolinium"),
Metal(65, "Tb", "Terbium"),
Metal(66, "Dy", "Dysprosium"),
Metal(67, "Ho", "Holmium"),
Metal(68, "Er", "Erbium"),
Metal(69, "Tm", "Thulium"),
Metal(70, "Yb", "Ytterbium"),
Metal(71, "Lu", "Lutetium"),
Metal(72, "Hf", "Hafnium"),
Metal(73, "Ta", "Tantalum"),
Metal(74, "W", "Tungsten"),
Metal(75, "Re", "Rhenium"),
Metal(76, "Os", "Osmium"),
Metal(77, "Ir", "Iridium"),
Metal(78, "Pt", "Platinum"),
Metal(79, "Au", "Gold"),
Metal(80, "Hg", "Mercury"),
Metal(81, "Tl", "Thallium"),
Metal(82, "Pb", "Lead"),
Metal(83, "Bi", "Bismuth"),
Metal(84, "Po", "Polonium"),
Metal(87, "Fr", "Francium"),
Metal(88, "Ra", "Radium"),
Metal(89, "Ac", "Actinium"),
Metal(90, "Th", "Thorium"),
Metal(91, "Pa", "Protactinium"),
Metal(92, "U", "Uranium"),
Metal(93, "Np", "Neptunium"),
Metal(94, "Pu", "Plutonium"),
Metal(95, "Am", "Americium"),
Metal(96, "Cm", "Curium"),
Metal(97, "Bk", "Berkelium"),
Metal(98, "Cf", "Californium"),
Metal(99, "Es", "Einsteinium"),
Metal(100, "Fm", "Fermium"),
Metal(101, "Md", "Mendelevium"),
Metal(102, "No", "Nobelium"),
Metal(103, "Lr", "Lawrencium"),
Metal(104, "Rf", "Rutherfordium"),
Metal(105, "Db", "Dubnium"),
Metal(106, "Sg", "Seaborgium"),
Metal(107, "Bh", "Bohrium"),
Metal(108, "Hs", "Hassium"),
Metal(109, "Mt", "Meitnerium"),
Metal(110, "Ds", "Darmstadtium"),
Metal(111, "Rg", "Roentgenium"),
Metal(112, "Cn", "Copernicium"),
Metal(113, "Nh", "Nihonium"),
Metal(114, "Fl", "Flerovium"),
Metal(115, "Mc", "Moscovium"),
Metal(116, "Lv", "Livermorium"),
]
for metal in metals:
db_session.add(metal)
with open("/flag.txt") as filp:
flag = filp.read().strip()
db_session.add(Flag(flag))
db_session.commit()
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/NahamCon/2022/web/Flaskmetal_Alchemist/src/database.py | ctfs/NahamCon/2022/web/Flaskmetal_Alchemist/src/database.py | from sqlalchemy import create_engine
from sqlalchemy.orm import scoped_session, sessionmaker
from sqlalchemy.ext.declarative import declarative_base
engine = create_engine("sqlite:////tmp/test.db")
db_session = scoped_session(
sessionmaker(autocommit=False, autoflush=False, bind=engine)
)
Base = declarative_base()
Base.query = db_session.query_property()
def init_db():
Base.metadata.create_all(bind=engine)
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/NahamCon/2022/web/Flaskmetal_Alchemist/src/app.py | ctfs/NahamCon/2022/web/Flaskmetal_Alchemist/src/app.py | from flask import Flask, render_template, request, url_for, redirect
from models import Metal
from database import db_session, init_db
from seed import seed_db
from sqlalchemy import text
app = Flask(__name__)
@app.teardown_appcontext
def shutdown_session(exception=None):
db_session.remove()
@app.route("/", methods=["GET", "POST"])
def index():
if request.method == "POST":
search = ""
order = None
if "search" in request.form:
search = request.form["search"]
if "order" in request.form:
order = request.form["order"]
if order is None:
metals = Metal.query.filter(Metal.name.like("%{}%".format(search)))
else:
metals = Metal.query.filter(
Metal.name.like("%{}%".format(search))
).order_by(text(order))
return render_template("home.html", metals=metals)
else:
metals = Metal.query.all()
return render_template("home.html", metals=metals)
if __name__ == "__main__":
seed_db()
app.run(debug=False)
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/NOESCAPE/2022/crypto/HelloSantaII/helloSanta.py | ctfs/NOESCAPE/2022/crypto/HelloSantaII/helloSanta.py | def enc(msg,key):
m=""
i=0
for char in msg:
m+=chr(ord(char)+ord(key[i]))
i+=1
if(i==len(key)):
i=0
return m
def bitEnc(text,key):
m=""
for char in text:
for k in key:
char = chr(ord(char)+ord(k))
m+=char
return m
import io
filename = "helloSanta.txt"
def encryptFile(filename,key):
file = open(filename,"r")
filedata= file.read()
filedata = bitEnc(str(filedata),key)
file.close()
with io.open(filename,"w",encoding = "utf-8") as f:
f.write(filedata)
def readFile(filename):
with io.open(filename,"r",encoding = "utf-8") as f:
print(f.read())
readFile(filename)
Key=?????
encryptFile(filename,Key)
readFile(filename) | python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/NOESCAPE/2022/crypto/HelloSanta/helloSanta.py | ctfs/NOESCAPE/2022/crypto/HelloSanta/helloSanta.py | def enc(msg,key):
m=""
i=0
for char in msg:
m+=chr(ord(char)+ord(key[i]))
i+=1
if(i==len(key)):
i=0
return m
def bitEnc(text,key):
m=""
for char in text:
for k in key:
char = chr(ord(char)+ord(k))
m+=char
return m
import io
filename = "helloSanta.txt"
def encryptFile(filename,key):
file = open(filename,"r")
filedata= file.read()
filedata = bitEnc(str(filedata),key)
file.close()
with io.open(filename,"w",encoding = "utf-8") as f:
f.write(filedata)
def readFile(filename):
with io.open(filename,"r",encoding = "utf-8") as f:
print(f.read())
readFile(filename)
encryptFile(filename,"merry_xmas")
readFile(filename) | python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/UMassCTF/2021/rev/babushka/babushka.py | ctfs/UMassCTF/2021/rev/babushka/babushka.py | import copy
import pickle
import types
def DUURNYCDMBIJBETCYLLY(s):
b = True
b = b and (((ord(s[2]) & 0xf0) ^ 64 == 0) and ((ord(s[2]) & 0x0f) ^ 1 == 0))
b = b and (((ord(s[34]) & 0xf0) ^ 112 == 0) and ((ord(s[34]) & 0x0f) ^ 13 == 0))
if ord(s[0]) & 0xf0 == 38:
i = 1
else:
i = 25
b = b and ((((ord(s[21]) & 0b10000000) >> 7) == 0) and (((ord(s[21]) & 0b01000000) >> 6) == 1) and (((ord(s[21]) & 0b00100000) >> 5) == 1) and (((ord(s[21]) & 0b00010000) >> 4) == 0) and (((ord(s[21]) & 0b00001000) >> 3) == 1) and (((ord(s[21]) & 0b00000100) >> 2) == 1) and (((ord(s[21]) & 0b00000010) >> 1) == 1) and (((ord(s[21]) & 0b00000001) >> 0) == 0))
b = b and (((ord(s[4]) & 0xf0) ^ 80 == 0) and ((ord(s[4]) & 0x0f) ^ 3 == 0))
b = b and (ord(s[30]) == 95)
c = ord('o') ^ ord(s[0])
if s[:5] != "UMASS":
return [False]
copy.copy(s)
b = b and (ord(s[5]) == 123)
b = b and (ord(s[18]) == 95)
b = b and (((ord(s[12]) & 0xf0) ^ 112 == 0) and ((ord(s[12]) & 0x0f) ^ 2 == 0))
i = len(s)
b = b and (ord(s[0]) == 85)
i = 63
b = b and (((ord(s[33]) & 0xf0) ^ 96 == 0) and ((ord(s[33]) & 0x0f) ^ 7 == 0))
i = len(s)
b = b and (ord(s[14]) == 95)
b = b and ((((ord(s[19]) & 0b10000000) >> 7) == 0) and (((ord(s[19]) & 0b01000000) >> 6) == 1) and (((ord(s[19]) & 0b00100000) >> 5) == 1) and (((ord(s[19]) & 0b00010000) >> 4) == 1) and (((ord(s[19]) & 0b00001000) >> 3) == 0) and (((ord(s[19]) & 0b00000100) >> 2) == 0) and (((ord(s[19]) & 0b00000010) >> 1) == 0) and (((ord(s[19]) & 0b00000001) >> 0) == 0))
b = b and ((((ord(s[11]) & 0b10000000) >> 7) == 0) and (((ord(s[11]) & 0b01000000) >> 6) == 0) and (((ord(s[11]) & 0b00100000) >> 5) == 1) and (((ord(s[11]) & 0b00010000) >> 4) == 1) and (((ord(s[11]) & 0b00001000) >> 3) == 0) and (((ord(s[11]) & 0b00000100) >> 2) == 0) and (((ord(s[11]) & 0b00000010) >> 1) == 0) and (((ord(s[11]) & 0b00000001) >> 0) == 0))
b = b and (ord(s[23]) == 100)
b = b and (ord(s[20]) == 119)
b = b and (ord(s[29]) == 119)
b = b and (((ord(s[6]) & 0xf0) ^ 96 == 0) and ((ord(s[6]) & 0x0f) ^ 3 == 0))
b = b and ((((ord(s[3]) & 0b10000000) >> 7) == 0) and (((ord(s[3]) & 0b01000000) >> 6) == 1) and (((ord(s[3]) & 0b00100000) >> 5) == 0) and (((ord(s[3]) & 0b00010000) >> 4) == 1) and (((ord(s[3]) & 0b00001000) >> 3) == 0) and (((ord(s[3]) & 0b00000100) >> 2) == 0) and (((ord(s[3]) & 0b00000010) >> 1) == 1) and (((ord(s[3]) & 0b00000001) >> 0) == 1))
b = b and (ord(s[26]) == 95)
b = b and (((ord(s[17]) & 0xf0) ^ 96 == 0) and ((ord(s[17]) & 0x0f) ^ 7 == 0))
b = b and (ord(s[27]) == 99)
i = 44
b = b and (ord(s[10]) == 109)
b = b and (((ord(s[31]) & 0xf0) ^ 96 == 0) and ((ord(s[31]) & 0x0f) ^ 4 == 0))
b = b and (ord(s[7]) == 95)
b = b and (ord(s[32]) == 48)
c = ord('S') ^ ord(s[0])
b = b and (ord(s[9]) == 51)
b = b and ((((ord(s[8]) & 0b10000000) >> 7) == 0) and (((ord(s[8]) & 0b01000000) >> 6) == 1) and (((ord(s[8]) & 0b00100000) >> 5) == 1) and (((ord(s[8]) & 0b00010000) >> 4) == 0) and (((ord(s[8]) & 0b00001000) >> 3) == 1) and (((ord(s[8]) & 0b00000100) >> 2) == 1) and (((ord(s[8]) & 0b00000010) >> 1) == 0) and (((ord(s[8]) & 0b00000001) >> 0) == 1))
b = b and (((ord(s[28]) & 0xf0) ^ 48 == 0) and ((ord(s[28]) & 0x0f) ^ 0 == 0))
b = b and (ord(s[24]) == 48)
b = b and ((((ord(s[1]) & 0b10000000) >> 7) == 0) and (((ord(s[1]) & 0b01000000) >> 6) == 1) and (((ord(s[1]) & 0b00100000) >> 5) == 0) and (((ord(s[1]) & 0b00010000) >> 4) == 0) and (((ord(s[1]) & 0b00001000) >> 3) == 1) and (((ord(s[1]) & 0b00000100) >> 2) == 1) and (((ord(s[1]) & 0b00000010) >> 1) == 0) and (((ord(s[1]) & 0b00000001) >> 0) == 1))
b = b and (ord(s[15]) == 100)
b = b and (ord(s[16]) == 48)
if ord(s[0]) & 0xf0 == 23:
i = 11
else:
i = 14
copy.copy(s)
b = b and (ord(s[22]) == 95)
c = ord('M') ^ ord(s[0])
b = b and (ord(s[25]) == 103)
b = b and ((((ord(s[13]) & 0b10000000) >> 7) == 0) and (((ord(s[13]) & 0b01000000) >> 6) == 1) and (((ord(s[13]) & 0b00100000) >> 5) == 1) and (((ord(s[13]) & 0b00010000) >> 4) == 1) and (((ord(s[13]) & 0b00001000) >> 3) == 1) and (((ord(s[13]) & 0b00000100) >> 2) == 0) and (((ord(s[13]) & 0b00000010) >> 1) == 0) and (((ord(s[13]) & 0b00000001) >> 0) == 1))
b = [b]
return b
def BHXFVDRTGGNFTXBCOMOJ(s):
b = True
b = b and (((ord(s[24]) & 0xf0) ^ 80 == 0) and ((ord(s[24]) & 0x0f) ^ 15 == 0))
b = b and ((((ord(s[22]) & 0b10000000) >> 7) == 0) and (((ord(s[22]) & 0b01000000) >> 6) == 0) and (((ord(s[22]) & 0b00100000) >> 5) == 1) and (((ord(s[22]) & 0b00010000) >> 4) == 1) and (((ord(s[22]) & 0b00001000) >> 3) == 0) and (((ord(s[22]) & 0b00000100) >> 2) == 0) and (((ord(s[22]) & 0b00000010) >> 1) == 0) and (((ord(s[22]) & 0b00000001) >> 0) == 0))
b = b and (((ord(s[37]) & 0xf0) ^ 96 == 0) and ((ord(s[37]) & 0x0f) ^ 4 == 0))
b = b and (((ord(s[30]) & 0xf0) ^ 96 == 0) and ((ord(s[30]) & 0x0f) ^ 9 == 0))
b = b and (ord(s[16]) == 110)
b = b and ((((ord(s[33]) & 0b10000000) >> 7) == 0) and (((ord(s[33]) & 0b01000000) >> 6) == 0) and (((ord(s[33]) & 0b00100000) >> 5) == 1) and (((ord(s[33]) & 0b00010000) >> 4) == 1) and (((ord(s[33]) & 0b00001000) >> 3) == 0) and (((ord(s[33]) & 0b00000100) >> 2) == 0) and (((ord(s[33]) & 0b00000010) >> 1) == 0) and (((ord(s[33]) & 0b00000001) >> 0) == 1))
b = b and (ord(s[27]) == 48)
b = b and (ord(s[8]) == 98)
b = b and (((ord(s[19]) & 0xf0) ^ 112 == 0) and ((ord(s[19]) & 0x0f) ^ 9 == 0))
b = b and (ord(s[7]) == 100)
b = b and ((((ord(s[10]) & 0b10000000) >> 7) == 0) and (((ord(s[10]) & 0b01000000) >> 6) == 1) and (((ord(s[10]) & 0b00100000) >> 5) == 1) and (((ord(s[10]) & 0b00010000) >> 4) == 1) and (((ord(s[10]) & 0b00001000) >> 3) == 0) and (((ord(s[10]) & 0b00000100) >> 2) == 0) and (((ord(s[10]) & 0b00000010) >> 1) == 1) and (((ord(s[10]) & 0b00000001) >> 0) == 0))
if s[:5] != "UMASS":
return [False]
if ord(s[0]) & 0xf0 == 20:
i = 50
else:
i = 58
b = b and (((ord(s[38]) & 0xf0) ^ 96 == 0) and ((ord(s[38]) & 0x0f) ^ 2 == 0))
b = b and (((ord(s[39]) & 0xf0) ^ 112 == 0) and ((ord(s[39]) & 0x0f) ^ 13 == 0))
b = b and (((ord(s[1]) & 0xf0) ^ 64 == 0) and ((ord(s[1]) & 0x0f) ^ 13 == 0))
copy.copy(s)
b = b and (((ord(s[26]) & 0xf0) ^ 112 == 0) and ((ord(s[26]) & 0x0f) ^ 7 == 0))
b = b and ((((ord(s[6]) & 0b10000000) >> 7) == 0) and (((ord(s[6]) & 0b01000000) >> 6) == 1) and (((ord(s[6]) & 0b00100000) >> 5) == 1) and (((ord(s[6]) & 0b00010000) >> 4) == 0) and (((ord(s[6]) & 0b00001000) >> 3) == 0) and (((ord(s[6]) & 0b00000100) >> 2) == 1) and (((ord(s[6]) & 0b00000010) >> 1) == 1) and (((ord(s[6]) & 0b00000001) >> 0) == 1))
c = ord('u') ^ ord(s[0])
b = b and ((((ord(s[14]) & 0b10000000) >> 7) == 0) and (((ord(s[14]) & 0b01000000) >> 6) == 1) and (((ord(s[14]) & 0b00100000) >> 5) == 1) and (((ord(s[14]) & 0b00010000) >> 4) == 1) and (((ord(s[14]) & 0b00001000) >> 3) == 0) and (((ord(s[14]) & 0b00000100) >> 2) == 0) and (((ord(s[14]) & 0b00000010) >> 1) == 0) and (((ord(s[14]) & 0b00000001) >> 0) == 0))
b = b and ((((ord(s[15]) & 0b10000000) >> 7) == 0) and (((ord(s[15]) & 0b01000000) >> 6) == 1) and (((ord(s[15]) & 0b00100000) >> 5) == 1) and (((ord(s[15]) & 0b00010000) >> 4) == 1) and (((ord(s[15]) & 0b00001000) >> 3) == 0) and (((ord(s[15]) & 0b00000100) >> 2) == 1) and (((ord(s[15]) & 0b00000010) >> 1) == 1) and (((ord(s[15]) & 0b00000001) >> 0) == 1))
b = b and (((ord(s[12]) & 0xf0) ^ 112 == 0) and ((ord(s[12]) & 0x0f) ^ 0 == 0))
if ord(s[0]) & 0xf0 == 34:
i = 28
else:
i = 67
copy.copy(s)
b = b and (((ord(s[9]) & 0xf0) ^ 80 == 0) and ((ord(s[9]) & 0x0f) ^ 15 == 0))
b = b and ((((ord(s[13]) & 0b10000000) >> 7) == 0) and (((ord(s[13]) & 0b01000000) >> 6) == 1) and (((ord(s[13]) & 0b00100000) >> 5) == 0) and (((ord(s[13]) & 0b00010000) >> 4) == 1) and (((ord(s[13]) & 0b00001000) >> 3) == 1) and (((ord(s[13]) & 0b00000100) >> 2) == 1) and (((ord(s[13]) & 0b00000010) >> 1) == 1) and (((ord(s[13]) & 0b00000001) >> 0) == 1))
if s[:5] != "UMASS":
return [False]
b = b and (ord(s[4]) == 83)
b = b and ((((ord(s[23]) & 0b10000000) >> 7) == 0) and (((ord(s[23]) & 0b01000000) >> 6) == 1) and (((ord(s[23]) & 0b00100000) >> 5) == 1) and (((ord(s[23]) & 0b00010000) >> 4) == 0) and (((ord(s[23]) & 0b00001000) >> 3) == 1) and (((ord(s[23]) & 0b00000100) >> 2) == 1) and (((ord(s[23]) & 0b00000010) >> 1) == 1) and (((ord(s[23]) & 0b00000001) >> 0) == 0))
b = b and ((((ord(s[18]) & 0b10000000) >> 7) == 0) and (((ord(s[18]) & 0b01000000) >> 6) == 1) and (((ord(s[18]) & 0b00100000) >> 5) == 1) and (((ord(s[18]) & 0b00010000) >> 4) == 1) and (((ord(s[18]) & 0b00001000) >> 3) == 0) and (((ord(s[18]) & 0b00000100) >> 2) == 0) and (((ord(s[18]) & 0b00000010) >> 1) == 0) and (((ord(s[18]) & 0b00000001) >> 0) == 0))
b = b and (ord(s[29]) == 112)
b = b and ((((ord(s[36]) & 0b10000000) >> 7) == 0) and (((ord(s[36]) & 0b01000000) >> 6) == 1) and (((ord(s[36]) & 0b00100000) >> 5) == 1) and (((ord(s[36]) & 0b00010000) >> 4) == 0) and (((ord(s[36]) & 0b00001000) >> 3) == 0) and (((ord(s[36]) & 0b00000100) >> 2) == 1) and (((ord(s[36]) & 0b00000010) >> 1) == 1) and (((ord(s[36]) & 0b00000001) >> 0) == 1))
b = b and (((ord(s[5]) & 0xf0) ^ 112 == 0) and ((ord(s[5]) & 0x0f) ^ 11 == 0))
b = b and (((ord(s[0]) & 0xf0) ^ 80 == 0) and ((ord(s[0]) & 0x0f) ^ 5 == 0))
b = b and ((((ord(s[3]) & 0b10000000) >> 7) == 0) and (((ord(s[3]) & 0b01000000) >> 6) == 1) and (((ord(s[3]) & 0b00100000) >> 5) == 0) and (((ord(s[3]) & 0b00010000) >> 4) == 1) and (((ord(s[3]) & 0b00001000) >> 3) == 0) and (((ord(s[3]) & 0b00000100) >> 2) == 0) and (((ord(s[3]) & 0b00000010) >> 1) == 1) and (((ord(s[3]) & 0b00000001) >> 0) == 1))
b = b and (ord(s[11]) == 48)
b = b and (ord(s[20]) == 116)
b = b and ((((ord(s[32]) & 0b10000000) >> 7) == 0) and (((ord(s[32]) & 0b01000000) >> 6) == 1) and (((ord(s[32]) & 0b00100000) >> 5) == 1) and (((ord(s[32]) & 0b00010000) >> 4) == 0) and (((ord(s[32]) & 0b00001000) >> 3) == 1) and (((ord(s[32]) & 0b00000100) >> 2) == 0) and (((ord(s[32]) & 0b00000010) >> 1) == 1) and (((ord(s[32]) & 0b00000001) >> 0) == 1))
b = b and ((((ord(s[2]) & 0b10000000) >> 7) == 0) and (((ord(s[2]) & 0b01000000) >> 6) == 1) and (((ord(s[2]) & 0b00100000) >> 5) == 0) and (((ord(s[2]) & 0b00010000) >> 4) == 0) and (((ord(s[2]) & 0b00001000) >> 3) == 0) and (((ord(s[2]) & 0b00000100) >> 2) == 0) and (((ord(s[2]) & 0b00000010) >> 1) == 0) and (((ord(s[2]) & 0b00000001) >> 0) == 1))
b = b and (((ord(s[17]) & 0xf0) ^ 80 == 0) and ((ord(s[17]) & 0x0f) ^ 15 == 0))
b = b and (((ord(s[35]) & 0xf0) ^ 80 == 0) and ((ord(s[35]) & 0x0f) ^ 15 == 0))
b = b and (ord(s[28]) == 95)
b = b and (ord(s[31]) == 99)
b = b and (ord(s[25]) == 48)
b = b and ((((ord(s[34]) & 0b10000000) >> 7) == 0) and (((ord(s[34]) & 0b01000000) >> 6) == 0) and (((ord(s[34]) & 0b00100000) >> 5) == 1) and (((ord(s[34]) & 0b00010000) >> 4) == 1) and (((ord(s[34]) & 0b00001000) >> 3) == 0) and (((ord(s[34]) & 0b00000100) >> 2) == 0) and (((ord(s[34]) & 0b00000010) >> 1) == 1) and (((ord(s[34]) & 0b00000001) >> 0) == 1))
b = b and ((((ord(s[21]) & 0b10000000) >> 7) == 0) and (((ord(s[21]) & 0b01000000) >> 6) == 1) and (((ord(s[21]) & 0b00100000) >> 5) == 1) and (((ord(s[21]) & 0b00010000) >> 4) == 0) and (((ord(s[21]) & 0b00001000) >> 3) == 1) and (((ord(s[21]) & 0b00000100) >> 2) == 0) and (((ord(s[21]) & 0b00000010) >> 1) == 0) and (((ord(s[21]) & 0b00000001) >> 0) == 0))
b = [b]
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | true |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/UMassCTF/2021/crypto/malware/malware.py | ctfs/UMassCTF/2021/crypto/malware/malware.py | from Crypto.Cipher import AES
from Crypto.Util import Counter
import binascii
import os
key = os.urandom(16)
iv = int(binascii.hexlify(os.urandom(16)), 16)
for file_name in os.listdir():
data = open(file_name, 'rb').read()
cipher = AES.new(key, AES.MODE_CTR, counter = Counter.new(128, initial_value=iv))
enc = open(file_name + '.enc', 'wb')
enc.write(cipher.encrypt(data))
iv += 1 | python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/UMassCTF/2021/crypto/Weird_RSA/chall.py | ctfs/UMassCTF/2021/crypto/Weird_RSA/chall.py | import random
from Crypto.Util.number import isPrime
m, Q = """REDACTED""", 1
def genPrimes(size):
base = random.getrandbits(size // 2) << size // 2
base = base | (1 << 1023) | (1 << 1022) | 1
while True:
temp = base | random.getrandbits(size // 4)
if isPrime(temp):
p = temp
break
while True:
temp = base | random.getrandbits(size // 4)
if isPrime(temp):
q = temp
break
return (p, q)
def pow(m, e, n):
return v(e)
def v(n):
if n == 0:
return 2
if n == 1:
return m
return (m*v(n-1) - Q*v(n-2)) % N
p, q = genPrimes(1024)
N = p * q
e = 0x10001
print("N:", N)
print("c:", pow(m, e, N))
"""
N: 18378141703504870053256589621469911325593449136456168833252297256858537217774550712713558376586907139191035169090694633962713086351032581652760861668116820553602617805166170038411635411122411322217633088733925562474573155702958062785336418656834129389796123636312497589092777440651253803216182746548802100609496930688436148522617770670087143010376380205698834648595913982981670535389045333406092868158446779681106756879563374434867509327405933798082589697167457848396375382835193219251999626538126258606572805220878283429607438382521692951006432650132816122705167004219371235964716616826653226062550260270958038670427
c: 14470740653145070679700019966554818534890999807830802232451906444910279478539396448114592242906623394239703347815141824698585119347592990685923384931479024856262941313458084648914561375377956072245149926143782368239175037299219241806241533201175001088200209202522586119648246842120571566051381821899459346757935757111233323915022287370687524912870425787594648397524189694991735372527387329346198018567010117587531474035014342584491831714256980975368294579192077738910916486139823489975038981139084864837358039928972730135031064241393391678984872799573965150169368237298603189344477806873779325227557835790957023000991
""" | python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/UMassCTF/2024/crypto/Third_Times_the_Charm/main.py | ctfs/UMassCTF/2024/crypto/Third_Times_the_Charm/main.py | from Crypto.Util.number import getPrime
with open("flag.txt",'rb') as f:
FLAG = f.read().decode()
f.close()
def encrypt(plaintext, mod):
plaintext_int = int.from_bytes(plaintext.encode(), 'big')
return pow(plaintext_int, 3, mod)
while True:
p = [getPrime(128) for _ in range(6)]
if len(p) == len(set(p)):
break
N1, N2, N3 = p[0] * p[1], p[2] * p[3], p[4] * p[5]
m1, m2, m3 = encrypt(FLAG, N1), encrypt(FLAG, N2), encrypt(FLAG, N3)
pairs = [(m1, N1), (m2, N2), (m3, N3)]
for i, pair in enumerate(pairs):
print(f'm{i+1}: {pair[0]}\nN{i+1}: {pair[1]}\n')
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/UMassCTF/2024/crypto/B4_the_B8/b4b8.py | ctfs/UMassCTF/2024/crypto/B4_the_B8/b4b8.py | import random
import os
import numpy as np
from Crypto.Cipher import AES
ket_0 = np.matrix([1, 0])
ket_1 = np.matrix([0, 1])
ket_plus = (ket_0 + ket_1) / (2 ** (1 / 2))
ket_minus = (ket_0 - ket_1) / (2 ** (1 / 2))
def input_matrix(n):
mat = []
for i in range(n):
row = []
for j in range(n):
row.append(complex(input(f"row {i}, col {j}:")))
mat.append(row)
m = np.matrix(mat)
return m
qubit_id = 0
class QubitPair:
def __init__(self, density_matrix: np.matrix):
global qubit_id
self.density_matrix = density_matrix
self.id = qubit_id
qubit_id += 1
def measure_first(self, POVM: list[np.matrix]):
post_measure = [np.kron(kraus, np.identity(2)) * self.density_matrix * np.kron(kraus.H, np.identity(2)) for
kraus in POVM]
prob = [np.abs(np.trace(m)) for m in post_measure]
result = random.choices([x for x in range(len(POVM))], weights=prob)
self.density_matrix = post_measure[result[0]] / prob[result[0]]
return result[0]
def measure_second(self, POVM: list[np.matrix]):
post_measure = [np.kron(np.identity(2), kraus) * self.density_matrix * np.kron(np.identity(2), kraus.H) for
kraus in POVM]
prob = [np.abs(np.trace(m)) for m in post_measure]
result = random.choices([x for x in range(len(POVM))], weights=prob)
self.density_matrix = post_measure[result[0]] / prob[result[0]]
return result[0]
def bell_state():
return QubitPair(np.matrix([[1 / 2, 0, 0, 1 / 2], [0] * 4, [0] * 4, [1 / 2, 0, 0, 1 / 2]]))
def standard_basis():
return [ket_0.H * ket_0, ket_1.H * ket_1]
def hadamard_basis():
return [ket_plus.H * ket_plus, ket_minus.H * ket_minus]
def check_valid(a, tol=1e-8):
eigen = np.linalg.eig(a)[0]
return np.all(np.abs(a - a.H) < tol) and np.all(np.abs(eigen - np.abs(eigen)) < tol) and np.abs(
np.trace(a) - 1) < tol
n = 1024
Alice_bits = [(bell_state(), 1) for s in range(n)]
Your_bits = [(x, 2) for x, _ in Alice_bits]
Bob_bits = []
key_exchanged = False
def measures(bit_list, basis_indices):
result = 0
POVMs = [standard_basis(), hadamard_basis()]
for i in range(n):
basis = (basis_indices >> i) & 1
s, bit_num = bit_list[i]
if bit_num == 1:
result |= s.measure_first(POVMs[basis]) << i
else:
result |= s.measure_second(POVMs[basis]) << i
return result
def randomness_test(bitstring, n=16):
bitmat = [(bitstring >> (i * n)) & ~(-1 << n) for i in range(n)]
for i in range(n):
m = max(bitmat[i:])
index = bitmat.index(m)
bitmat[index] = bitmat[i]
bitmat[i] = m
if ((bitmat[i] >> (n - 1 - i)) & 1) == 0:
continue
for j in range(i + 1, n):
if (bitmat[i] & bitmat[j]) >> (n - 1 - i) != 0:
bitmat[j] ^= bitmat[i]
return sum([1 if x == 0 else 0 for x in bitmat]) < 3
with open("flag.txt", "rb") as f:
FLAG = f.read()
while True:
if not key_exchanged and len(Bob_bits) == n:
print("Bob: I've received enough states!")
print("Alice: ok let's start then.")
key_exchanged = True
Alice_basis = int.from_bytes(os.urandom(n // 8), byteorder='big')
Alice_results = measures(Alice_bits, Alice_basis)
print("Alice: i've made my measurements.")
Bob_basis = int.from_bytes(os.urandom(n // 8), byteorder='big')
Bob_results = measures(Bob_bits, Bob_basis)
print("Bob: Same here!")
Bob_standard = ""
Bob_hadamard = ""
for i in range(n):
if ((Bob_basis >> i) & 1) == 0:
Bob_standard = Bob_standard + str((Bob_results >> i) & 1)
else:
Bob_hadamard = Bob_hadamard + str((Bob_results >> i) & 1)
if randomness_test(int(Bob_hadamard, 2)) and randomness_test(int(Bob_standard, 2)):
print("Bob: Mine passed the randomness test, looks like everything is good!")
else:
raise ValueError("Bob: Mine doesn't seem that random, maybe Eve's here again...")
print(f"Bob: My bases were {('0' * n + bin(Bob_basis)[2:])[-n:]}")
print(f"Alice: cool, my bases were {('0' * n + bin(Alice_basis)[2:])[-n:]}")
Alice_key = ""
Bob_key = ""
count = 0
for i in range(n):
if ((Alice_basis >> i) & 1) == ((Bob_basis >> i) & 1):
Alice_key = Alice_key + str((Alice_results >> i) & 1)
Bob_key = Bob_key + str((Bob_results >> i) & 1)
count += 1
if (count - count // 10) < 128:
raise ValueError("Bob: Hmmm, I don't think that's quite enough for us to make a key, let's start over...")
print(
f"Bob: Great! Now let's just make sure that our measurements actually match. My first {count // 4} bits are: {Bob_key[:count // 4]}")
if sum([1 if a != b else 0 for a, b in zip(Alice_key[:count // 4], Bob_key[:count // 4])]) > count // 100:
raise ValueError("Alice: that doesn't seem to match mine, eve's dropped by again it seems.")
else:
print("Alice: yeah that looks good.")
Alice_key = int(Alice_key[-128:], 2)
Alice_AES = AES.new(Alice_key.to_bytes(length=16, byteorder='big'), mode=AES.MODE_CBC)
Bob_key = int(Bob_key[-128:], 2)
Bob_AES = AES.new(Bob_key.to_bytes(length=16, byteorder='big'), mode=AES.MODE_CBC)
encrypted_once = Alice_AES.encrypt(FLAG)
encrypted_twice = Bob_AES.encrypt(encrypted_once)
print(Alice_AES.iv.hex())
print(Bob_AES.iv.hex())
print(encrypted_twice.hex())
option = int(input(
"""\nYou can:\n1. Measure a qubit\n2. Prepare a system of 2 qubits\n3. Send Bob a qubit\n4. See qubits in storage\n"""))
if option not in [1, 2, 3, 4]:
raise ValueError("Nope.")
if option == 1:
count = int(input(
"How many Kraus operators does your POVM have? If you just want the standard basis, put 0. If you just want the hadamard basis, put 1."))
if count < 0:
raise ValueError("I don't think you're gonna measure much with that...")
elif count > 4:
raise ValueError("Unfortunately we don't quite have the hardware for that...")
elif count == 0:
POVM = standard_basis()
elif count == 1:
POVM = hadamard_basis()
else:
POVM = []
print("Input your Kraus operators: ")
for i in range(count):
print(f"Operator #{i}:")
m = input_matrix(2)
POVM.append(m)
if not np.isclose(np.sum([kraus.H * kraus for kraus in POVM]), np.identity(2)):
raise ValueError(
"That doesn't seem to be physically possible set of measurements... but raise a ticket with your input if you think the check is giving a false negative!")
index = int(input("Which state would you like to measure?"))
if index < 0 or index >= len(Your_bits):
raise ValueError("That's not a valid state index!")
state, bit_number = Your_bits[index]
print("Making measurement...")
if bit_number == 1:
print(f"The measurement result is: {state.measure_first(POVM)}")
if bit_number == 2:
print(f"The measurement result is: {state.measure_second(POVM)}")
if option == 2:
if len(Your_bits) > 2 * n:
raise ValueError("You don't have enough quantum storage for that!")
print("Input the coefficients for the 4x4 density matrix of 2 qubits: ")
m = input_matrix(4)
if check_valid(m):
state = QubitPair(m)
Your_bits.append((state, 1))
Your_bits.append((state, 2))
print(f"Added 2 parts of qubit with id {state.id} into storage")
else:
raise ValueError(
"That doesn't seem to be a physically possible state... but raise a ticket with your input if you think the check is giving a false negative!"
)
if option == 3:
if key_exchanged:
raise ValueError("Bob: Oh look, Eve's trying to send me qubits. That can't be good...")
index = int(input("Which bits would you like to send to Bob?"))
if index < 0 or index >= len(Your_bits):
raise ValueError("That's not a valid state index!")
Bob_bits.append(Your_bits.pop(index))
if option == 4:
for i, t in enumerate(Your_bits):
print(f"#{i} | id: #{t[0].id}, part of qubit: {t[1]}")
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/UMassCTF/2024/crypto/Brutal_Mogging/main.py | ctfs/UMassCTF/2024/crypto/Brutal_Mogging/main.py | import os
from hashlib import sha256
from flag import FLAG
def xor(data1, data2):
return bytes([data1[i] ^ data2[i] for i in range(len(data1))])
def do_round(data, key):
m = sha256()
m.update(xor(data[2:4], key))
return bytes(data[2:4]) + xor(m.digest()[0:2], data[0:2])
def do_round_inv(data, key):
m = sha256()
m.update(xor(data[0:2], key))
return xor(m.digest()[0:2], data[2:4]) + bytes(data[0:2])
def pad(data):
padding_length = 4 - (len(data) % 4)
return data + bytes([padding_length] * padding_length)
def unpad(data):
padding_length = data[-1]
return data[:-padding_length]
# XOR every character with bytes generated from the PRNG
def encrypt_block(data, key):
for i in range(10):
data = do_round(data, key)
return data
def decrypt_block(data, key):
for i in range(10):
data = do_round_inv(data, key)
return data
def encrypt_data(data, key):
cipher = b''
while data:
cipher += encrypt_block(data[:4], key)
data = data[4:]
return cipher
def decrypt_data(cipher, key):
data = b''
while cipher:
data += decrypt_block(cipher[:4], key)
cipher = cipher[4:]
return data
def encrypt(data, key):
data = pad(data)
return encrypt_data(encrypt_data(data, key[0:2]), key[2:4])
def decrypt(data, key):
plain = decrypt_data(decrypt_data(data, key[2:4]), key[0:2])
return unpad(plain)
if __name__ == '__main__':
key = os.urandom(4)
cipher = encrypt(FLAG, key)
print("Oh yeah, my cipher is so strong and my one way function is so well defined.")
print("No betas can ever break it, so I'll just give you the flag right now.")
print(f"The encrypted flag is: {cipher.hex()}")
print("I need to get back to looksmaxxing so I'll give you three small pieces of advice.")
print("What are your questions?")
for i in range(3):
plain = input(f"{i}: ")[0:8]
cipher = encrypt(plain.encode(), key)
print(f"{plain}: {cipher.hex()}") | python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/UMassCTF/2024/crypto/Reader_Exercise/reader-exercise.py | ctfs/UMassCTF/2024/crypto/Reader_Exercise/reader-exercise.py | from Crypto.Util.number import *
from Crypto.Random.random import *
class Polynomial:
def __init__(self, entries):
self.entries = entries
def __add__(self, other):
if len(self.entries) < len(other.entries):
return other + self
return Polynomial(
[x if y == 0 else (y if x == 0 else x + y) for x, y in zip(self.entries, other.entries)] +
self.entries[len(other.entries):]
)
def __neg__(self):
return Polynomial([-x for x in self.entries])
def __sub__(self, other):
return self + (-other)
def __mul__(self, o):
result = Polynomial([])
for power in range(len(self.entries)):
product = [0] * power + [self.entries[power] * y for y in o.entries]
result = result + Polynomial(product)
return result
def __mod__(self, other):
self.entries = [x % other for x in self.entries]
return self
def __str__(self):
return str(self.entries)
def __repr__(self):
return str(self)
def __call__(self, *args, **kwargs):
start = 1
s = self.entries[0]
for i in self.entries[1:]:
start *= args[0]
s += i * start
return s
def degree(self):
i = len(self.entries)
while i > 0:
i -= 1
if self.entries[i] != 0:
break
return i
# Oh no this got corrupted :(
def gen_pair(deg, mod):
if __name__ == "__main__":
with open("flag.txt", "r") as f:
FLAG = f.read()
size = 500
base = 16
degree = 8
print(f"Gimme a sec to generate the prime...")
while True:
n = getPrime(size)
if n % (base * 2) == 1:
break
print(f"n = {n}")
p, q = gen_pair(degree, n)
assert isinstance(p, Polynomial) and isinstance(q, Polynomial)
assert p.degree() == degree
assert q.degree() < p.degree()
p_squared = p * p
q_squared = q * q
while True:
decision = input("What would you like to do?\n")
if decision == "challenge":
challenge = int(input("I will never fail your challenges!\n"))
proof = (p_squared(challenge) + q_squared(challenge)) % n
assert proof == (pow(challenge, base, n) + 1) % n
print(f"See? {proof}")
elif decision == "verify":
token = getRandomNBitInteger(size - 1) % n
print("Here's how verification works: ")
print(f"I give you:")
print(f"token = {token}")
print(f"You should give back:")
print(f"p(token) = {p(token) % n}")
print(f"q(token) = {q(token) % n}")
print(f"Simple enough, right?")
token = getRandomNBitInteger(size) % n
print(f"token = {token}")
p_attempt = int(input("p(token) = "))
q_attempt = int(input("q(token) = "))
assert p_attempt == p(token) % n and q_attempt == q(token) % n
print("Great job!")
print(FLAG)
break
else:
print("Probably not that...")
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/UMassCTF/2024/crypto/Shuffling_as_a_Service/saas.py | ctfs/UMassCTF/2024/crypto/Shuffling_as_a_Service/saas.py | import random
import string
from Crypto.Random.random import shuffle
from secrets import randbelow
class BitOfShuffling:
def __init__(self, key_length):
self.perm = [x for x in range(key_length)]
shuffle(self.perm)
def shuffle_int(self, input_int: int):
shuffled_int = 0
for x in range(len(self.perm)):
shuffled_int |= ((input_int >> x) & 1) << self.perm[x]
return shuffled_int
def shuffle_bytes(self, input_bytes):
return self.shuffle_int(int.from_bytes(input_bytes, 'big'))
def rand_string(length):
return ''.join(
random.choices(string.digits + string.ascii_letters + r"""!"#$%&'()*+,-./:;<=>?@[\]^_`|~""", k=length))
def pad_flag(flag, length):
pad_size = length - len(flag)
if pad_size == 0:
return flag
left_size = randbelow(pad_size)
right_size = pad_size - left_size
return rand_string(left_size) + flag + rand_string(right_size)
KEY_LENGTH = 128
trials = 10
if __name__ == "__main__":
with open("flag.txt", "r") as f:
FLAG = f.read()
FLAG = pad_flag(FLAG, KEY_LENGTH)
shuffler = BitOfShuffling(KEY_LENGTH * 8)
output_int = shuffler.shuffle_bytes(FLAG.encode())
print("Quite a bit of shuffling gave us this hex string: ")
print(f'{output_int:0{KEY_LENGTH * 2}x}')
print(f"You too can shuffle your hexed bits with our {trials} free trials!")
for i in range(trials):
trial = input(f"Input {i + 1}:")
bits_from_hex = bytes.fromhex(trial)
print(f'{shuffler.shuffle_bytes(bits_from_hex):0{KEY_LENGTH * 2}x}')
print("See you next time!")
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/UMassCTF/2025/hw/Hidden_in_Flash/client.py | ctfs/UMassCTF/2025/hw/Hidden_in_Flash/client.py | from sys import argv
import socket
import time
MAX_SIZE = 64 * 1024
HOST = "hardware.ctf.umasscybersec.org"
PORT = 10003
if len(argv) != 2:
print(f"Usage: {argv[0]} FIRMWARE_PATH")
exit(1)
with open(argv[1], 'rb') as f:
data = f.read()
if len(data) > MAX_SIZE:
print(f"firmware too large. {len(data)} > {MAX_SIZE}")
exit(1)
time_err = TimeoutError("Did not receive expected data in time. Please make sure you are submitting an ELF and try again or submit a ticket")
def recv(socket: socket.socket, num_bytes: int, timeout: float = 5) -> bytes:
output = b''
start = time.time()
while num_bytes > 0 and time.time() - start < timeout:
recvd = socket.recv(num_bytes)
num_bytes -= len(recvd)
output += recvd
if num_bytes:
raise time_err
return output
def recv_until(socket: socket.socket, end: bytes, timeout: float = 5) -> bytes:
output = b''
start = time.time()
while time.time() - start < timeout:
recvd = socket.recv(1)
if recvd == end:
return output
output += recvd
raise time_err
with socket.socket(socket.AF_INET, socket.SocketKind.SOCK_STREAM) as s:
print("Connecting...")
s.connect((HOST, PORT))
print("Sending firmware...")
s.sendall(len(data).to_bytes(4, "little") + data)
if recv(s, 1) != b"\x00":
print("Unknown response from server")
exit(1)
print("Running code...")
rsp_msgs = [
"Code ran successfully!",
"Internal error occurred while setting up sim. Please make sure you are uploading an ELF file for the the atmega328p at 16MHz. If the issue persists, submit a ticket.",
"The sim crashed while running your code. Please make sure your code is built for the atmega328p at 16MHz."
]
ret = int.from_bytes(recv(s, 1))
if ret < 3:
print(rsp_msgs[ret])
else:
print("Unknown response from server")
data = recv(s, int.from_bytes(recv(s, 4), 'little'))
print("UART output:")
try:
print(data.decode())
except UnicodeDecodeError:
print(data)
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/UMassCTF/2025/crypto/Brainrot_Gamba/chall.py | ctfs/UMassCTF/2025/crypto/Brainrot_Gamba/chall.py | from Crypto.Cipher import AES
from Crypto.Util.number import getStrongPrime, getRandomNBitInteger
import os
import json
import itertools
normal_deck = [''.join(card) for card in itertools.product("23456789TJQKA", "chds")]
# https://www.rfc-editor.org/rfc/rfc3526#section-3
p = int(""" FFFFFFFF FFFFFFFF C90FDAA2 2168C234 C4C6628B 80DC1CD1
29024E08 8A67CC74 020BBEA6 3B139B22 514A0879 8E3404DD
EF9519B3 CD3A431B 302B0A6D F25F1437 4FE1356D 6D51C245
E485B576 625E7EC6 F44C42E9 A637ED6B 0BFF5CB6 F406B7ED
EE386BFB 5A899FA5 AE9F2411 7C4B1FE6 49286651 ECE45B3D
C2007CB8 A163BF05 98DA4836 1C55D39A 69163FA8 FD24CF5F
83655D23 DCA3AD96 1C62F356 208552BB 9ED52907 7096966D
670C354E 4ABC9804 F1746C08 CA237327 FFFFFFFF FFFFFFFF""".replace(' ', '').replace('\n', ''), 16)
def shuffle(l):
return [x for x in sorted(l, key=lambda x: int.from_bytes(os.urandom(2)))]
def ghash(data, key, iv):
cipher = AES.new(key, AES.MODE_GCM, nonce=iv)
cipher.update(data)
_, tag = cipher.encrypt_and_digest(b'')
result = int.from_bytes(tag)
if result < 1 << 127:
result += 1 << 128
return result ** 2
def encrypt(msg, e):
return pow(msg, e, p)
def decrypt(msg, d):
return pow(msg, d, p)
def random_key_pair():
e = getRandomNBitInteger(p.bit_length() // 2) * 2 + 1
d = pow(e, -1, p - 1)
return e, d
def encrypt_deck(deck):
e, d = random_key_pair()
return d, [hex(encrypt(card, e)) for card in deck]
def decrypt_deck(deck, d):
return [decrypt(int(card, 16), d) for card in deck]
def encrypt_cards(deck, hash_key, iv):
keys = [random_key_pair() for _ in range(52)]
return [key[1] for key in keys], [hex(encrypt(card, key[0])) for card, key in zip(deck, keys)], [
hex(ghash(hex(key[1]).encode(), hash_key, iv)) for key in keys]
def decrypt_cards(card, my_key, opp_key, hash_key, hash_value, safely_hashed_deck, iv):
opp_key = int(opp_key, 16)
if hex(ghash(hex(opp_key).encode(), hash_key, iv)) != hash_value:
raise ValueError("Your key has does not match your commitment!")
decrypted = decrypt(decrypt(int(card, 16), opp_key), my_key)
if decrypted not in safely_hashed_deck:
raise ValueError("Your key does not decrypt correctly!")
return safely_hashed_deck[decrypted]
def get_deck(msg, size):
resp = input(msg)
if len(resp) > 100000:
raise ValueError("yeah i'm not parsing that.")
deck = json.loads(resp)
if not isinstance(deck, list):
raise ValueError('You did not give me a list!')
if len(deck) != size:
raise ValueError("You did not give me the correct number of items!")
if not all(isinstance(card, str) for card in deck):
raise ValueError("You didn't give me valid items!")
return deck
if __name__ == '__main__':
hash_key = os.urandom(16)
print(f"I commit to this key: {AES.new(hash_key, AES.MODE_ECB).encrypt(int.to_bytes(0, length=16)).hex()}")
iv = bytes.fromhex(input("Please commit to an IV!"))
deck = get_deck('Give me a deck of cards: ', 52)
safely_hashed_deck = {ghash(bytes.fromhex(s), hash_key, iv): c for c, s in zip(normal_deck, shuffle(deck))}
if len(safely_hashed_deck) != 52:
raise ValueError("You didn't give me unique cards!")
print(f"Here's the deck we're using: {json.dumps([hex(k) for k in safely_hashed_deck])}")
print(f"You can check that the key I used matches my commitment: {hash_key.hex()}")
print("Now, let's shuffle the deck!")
global_d, deck = encrypt_deck(safely_hashed_deck)
print(json.dumps(shuffle(deck)))
deck = get_deck('Shuffle and encrypt, then give me back the deck: ', 52)
deck = decrypt_deck(deck, global_d)
my_keys, deck, key_hashes = encrypt_cards(deck, hash_key, iv)
print(
"I removed my global encryption, and added individual encryption. Here's my deck now, along with the hashes of the encryption: ")
print(json.dumps(deck))
print(json.dumps(key_hashes))
deck = get_deck('Remove your global encryption, add your own individual encryption, then give me back the deck: ',
52)
opponents_hashes = get_deck("Also, give me the hash to all your keys to make sure you're not cheating: ", 52)
print("Now, let's play poker!")
print("Here are the keys to your cards: ", json.dumps([hex(my_keys[i]) for i in [0, 1]]))
opp_keys = get_deck("Give me my first two keys: ", 2)
hand = {decrypt_cards(deck[i], my_keys[i], opp_keys[i - 2], hash_key, opponents_hashes[i], safely_hashed_deck, iv)
for i in [2, 3]}
if len(hand) < 2:
raise ValueError("You didn't give me unique cards!")
if not all(card[0] == 'A' for card in hand):
raise ValueError("I'm not playing until I get aces!")
print("Here are the keys to the streets: ", json.dumps([hex(my_keys[i]) for i in [4, 5, 6, 7, 8]]))
opp_keys = get_deck("Give me my street keys: ", 5)
street = {decrypt_cards(deck[i], my_keys[i], opp_keys[i - 4], hash_key, opponents_hashes[i], safely_hashed_deck, iv)
for i in [4, 5, 6, 7, 8]}
if len(street.union(hand)) < 7:
raise ValueError("You didn't give me unique cards!")
if not {'Ac', 'Ah', 'Ad', 'As'} <= street.union(hand):
raise ValueError("I'm not betting until I get quad aces!")
print("Here are the keys to my cards: ", json.dumps([hex(my_keys[i]) for i in [2, 3]]))
print("Read em' and weep!")
opp_keys = get_deck("Give me your first two keys: ", 2)
opp_hand = {decrypt_cards(deck[i], my_keys[i], opp_keys[i], hash_key, opponents_hashes[i], safely_hashed_deck, iv)
for i in [0, 1]}
if len(street.union(opp_hand).union(hand)) < 9:
raise ValueError("You didn't give me unique cards!")
if not any({rank + suit for rank in 'TJQKA'} <= street.union(opp_hand) for suit in 'chds'):
raise ValueError("I don't know what you think you had but it's clearly not beating aces!")
print("dang, i should stop gambling.")
with open('flag.txt', 'r') as f:
print(f.readline()) | python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/UMassCTF/2025/crypto/Disordered_Tree/redacted_source.py | ctfs/UMassCTF/2025/crypto/Disordered_Tree/redacted_source.py | from Crypto.Util.number import getStrongPrime, getPrime, GCD
import datetime
def encrypt(block, f, g, time):
for c in time:
if c == '1':
block = f(block)
elif c == '0':
block = g(block)
return block
def distribute_keys(block, f, g, start, end, so_far=''):
if all(c == '0' for c in start) and all(c == '1' for c in end):
print(so_far)
print(hex(encrypt(block, f, g, so_far)))
return
if start[0] == end[0]:
distribute_keys(block, f, g, start[1:], end[1:], so_far + start[0])
else:
distribute_keys(block, f, g, start[1:], '1' * len(end[1:]), so_far + '0')
distribute_keys(block, f, g, '0' * len(start[1:]), end[1:], so_far + '1')
return
def time_to_str(time):
return ('0' * 64 + bin(int(time * 1000000))[2:])[-64:]
def pair_to_str(start, end):
return ('0' * 64 + bin(int(start * 1000000))[2:])[-64:], ('0' * 64 + bin(int(end * 1000000) - 1)[2:])[-64:]
p = getStrongPrime(512)
q = getStrongPrime(512)
n = p * q
phi = (p - 1) * (q - 1)
now = time_to_str(datetime.datetime.now().timestamp())
while True:
fe = getPrime(64)
ge = getPrime(64)
if GCD(phi, fe) == 1 and GCD(phi, ge) == 1:
break
print(f'n={hex(n)}')
print(f'fe={hex(fe)}')
print(f'ge={hex(ge)}')
print(f'now={now}')
master_key = getStrongPrime(1024)
def f(block):
return pow(block, fe, n)
def g(block):
return pow(block, ge, n)
start, end = pair_to_str(datetime.datetime.strptime("1990", "%Y").timestamp(),
datetime.datetime.strptime("2020", "%Y").timestamp())
print(f'\nkeys: ')
distribute_keys(master_key, f, g, start, end)
flag = b'UMASS{REDACTED}'
flag_key = encrypt(master_key, f, g, now)
print()
print(f'flag={hex(int.from_bytes(flag) ^ flag_key)}') | python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/UMassCTF/2025/crypto/BuRGerCode/partial_source.py | ctfs/UMassCTF/2025/crypto/BuRGerCode/partial_source.py | import os
FLAG_OFFSET = REDACTED
FLAG = REDACTED
BURGER_LAYERS = ["Bun (1)", "Lettuce (2)", "Tomato (3)", "Cheese (4)", "Patty (5)", "Onion (6)", "Pickle (7)", "Mayonnaise (8)", "Egg (9)", "Avocado (10)"]
def print_towers(towers):
for i, tower in enumerate(towers):
print(f"Tower {i + 1}: {[BURGER_LAYERS[layer - 1] for layer in tower]}")
print()
def move_disk(towers, from_tower, to_tower):
if not towers[from_tower]:
print("Invalid move: Source plate is empty.")
return False
if towers[to_tower] and towers[to_tower][-1] < towers[from_tower][-1]:
print("Invalid move: Cannot place larger burger layer on smaller burger layer.")
return False
towers[to_tower].append(towers[from_tower].pop())
return True
def towers_of_hanoi():
num_disks = int(input("Enter the number of burger layers (1-10): "))
while num_disks < 1 or num_disks > 10:
print("Please enter a number between 1 and 10 inclusive.")
num_disks = int(input("Enter the number of burger layers (1-10): "))
towers = [list(range(num_disks, 0, -1)), [], []]
print_towers(towers)
while len(towers[2]) != num_disks:
try:
from_tower = int(input("Move from plate (1-3): ")) - 1
to_tower = int(input("Move to plate (1-3): ")) - 1
if from_tower not in range(3) or to_tower not in range(3):
print("Invalid input. Please enter a number between 1 and 3.")
continue
if move_disk(towers, from_tower, to_tower):
print_towers(towers)
except ValueError:
print("Invalid input. Please enter a valid number.")
print(f"Congratulations! You solved the puzzle. The last { num_disks} bits of the offset used to encrypt the flag are {bin(FLAG_OFFSET & ((1 << ( num_disks )) - 1))}.")
if num_disks >= 9:
print("Waoh, that is a big sandwich! The offset only has 6 bits though...")
def key_gen_func(i: int) -> int:
# a deterministic function that generates a key based on the index using a very cool sequence of non-negative integers
REDACTED
def encrypt(message: bytes, offset = FLAG_OFFSET) -> str:
encrypted = bytearray()
if offset is None:
offset = os.urandom(1)[0]
for (i, char) in enumerate(message):
encrypted.append(char ^ (key_gen_func(i + offset) & 0xFF))
return encrypted.hex()
if __name__ == "__main__":
choice = input("Options\n1. Make a Burger\n2. Encrypt with random offset\n3. Get encrypted flag\nSelect an option: ")
if(choice == '1'):
towers_of_hanoi()
elif(choice == '2'):
str = input("Enter a string to encrypt: ")
print(encrypt(str.encode(), offset=None))
elif(choice == '3'):
print(encrypt(FLAG, offset=FLAG_OFFSET)) | python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/UMassCTF/2025/crypto/xorsa/main.py | ctfs/UMassCTF/2025/crypto/xorsa/main.py | from Crypto.Util import number
flag = b"UMASS{REDACTED}"
bits = 1024
p = number.getPrime(bits)
q = number.getPrime(bits)
n = p * q
phi = (p - 1) * (q - 1)
e = 65537
d = number.inverse(e, phi)
c = pow(int.from_bytes(flag, 'big'), e, n)
print(f"n: {n}")
print(f"e: {e}")
print(f"c: {c}")
print(f"partial p^q: {hex((p^q) >> (bits // 2))}")
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/UMassCTF/2025/crypto/Lazy_Streamer/chall.py | ctfs/UMassCTF/2025/crypto/Lazy_Streamer/chall.py | order = ~(-1 << 512)
mask = 0b10110101001101101110100110111001000101000111000010011000100100101000110001000001011101110101111000110011100001110011100000010100101111001101010101111100110010111011000000111010001001100111000000000100100111100001100010000110011110010001011110101010001001111100010111010111110010111110101010010100111000000111011111001000100111000001010110111111001010111100011111111001000010101110000100100100101010101100010111011001110111100010010110010010111000001010101010000000110100010111011100010000111100010100111011011111
class Cipher:
def __init__(self, mask, seed):
print(f'mask={hex(mask)}')
self.mask = mask
self.seed = seed
def next(self):
self.seed = (self.seed << 1) | ((self.seed & self.mask).bit_count() & 1)
self.seed &= order
return self.seed % 5
flag = b'UMASS{REDACTED}'
flag = flag[5:]
print(f'len={len(flag)}')
current = int.from_bytes(flag)
c = Cipher(mask, current)
for _ in range(100):
c.next()
flag_data = []
for _ in range(520):
c.next()
flag_data.append(c.next())
print(f'flag={flag_data}') | python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/UMassCTF/2022/crypto/order_of_the_eight_apollonii/ordereightapollonii.py | ctfs/UMassCTF/2022/crypto/order_of_the_eight_apollonii/ordereightapollonii.py | #!/usr/bin/env python3
#
# Polymero
#
# Imports
import numpy as np
import os, random, hashlib
# Local imports
with open('flag.txt','rb') as f:
FLAG = f.read()
f.close()
NBYT = 6
class O8A:
def __init__(self, secret):
if len(secret) > 2*3*NBYT:
raise ValueError('INIT ERROR -- Secret is too large, max {} bytes.'.format(2*3*NBYT))
self.secret = secret
while True:
self.treasure, self.apollonii = self.bury_treasure()
if self.apollonii:
break
self.points, self.shares = self.give_out_shares()
def bury_treasure(self):
secret = self.secret[::]
distr = [len(secret) // 6 + (1 if x < len(secret) % 6 else 0) for x in range(6)]
C1, C2, C3 = [[secret[sum(distr[:i]):sum(distr[:i+1])] for i in range(6)][j:j+2] for j in range(0,6,2)]
for i in range(3):
for j in range(2):
k = [C1,C2,C3][i][j]
while len(k) < NBYT:
k += os.urandom(1)
[C1,C2,C3][i][j] = int.from_bytes(k, 'big')
C1 += [int.from_bytes(os.urandom(NBYT), 'big') // 4 + 2**(NBYT*8-4)]
C2 += [int.from_bytes(os.urandom(NBYT), 'big') // 4 + 2**(NBYT*8-4)]
C3 += [int.from_bytes(os.urandom(NBYT), 'big') // 4 + 2**(NBYT*8-4)]
apollonii = []
for i in range(8):
sr1, sr2, sr3 = [(-1)**int(j) for j in list('{:03b}'.format(i))]
a2 = 2 * (C1[0] - C2[0])
b2 = 2 * (C1[1] - C2[1])
c2 = 2 * (sr1 * C1[2] + sr2 * C2[2])
d2 = (C1[0]**2 + C1[1]**2 - C1[2]**2) - (C2[0]**2 + C2[1]**2 - C2[2]**2)
a3 = 2 * (C1[0] - C3[0])
b3 = 2 * (C1[1] - C3[1])
c3 = 2 * (sr1 * C1[2] + sr3 * C3[2])
d3 = (C1[0]**2 + C1[1]**2 - C1[2]**2) - (C3[0]**2 + C3[1]**2 - C3[2]**2)
AB = a2 * b3 - a3 * b2; BA = -AB
AC = a2 * c3 - a3 * c2; CA = -AC
AD = a2 * d3 - a3 * d2; DA = -AD
BC = b2 * c3 - b3 * c2; CB = -BC
BD = b2 * d3 - b3 * d2; DB = -BD
CD = c2 * d3 - c3 * d2; DC = -CD
ABC_a = (BC / AB)**2 + (CA / AB)**2 - 1
ABC_b = 2 * DB * BC / (AB**2) - 2 * C1[0] * BC / AB + 2 * AD * CA / (AB**2) - 2 * C1[1] * CA / AB - 2 * sr1 * C1[2]
ABC_c = (DB / AB)**2 - 2 * C1[0] * DB / AB + C1[0]**2 + (AD / AB)**2 - 2 * C1[1] * AD / AB + C1[1]**2 - C1[2]**2
if ABC_b**2 - 4 * ABC_a * ABC_c < 0:
return None, None
ABC_r = (-ABC_b - np.sqrt(ABC_b**2 - 4 * ABC_a * ABC_c)) / (2 * ABC_a)
if ABC_r < 0:
ABC_r = (-ABC_b + np.sqrt(ABC_b**2 - 4 * ABC_a * ABC_c)) / (2 * ABC_a)
r = ABC_r
x = (DB + r * BC) / AB
y = (AD + r * CA) / AB
if np.isnan(r) or r <= 0:
return None, None
apollonii += [[round(x), round(y), round(r)]]
return [C1,C2,C3], apollonii
def give_out_shares(self):
shares = []
for C in self.apollonii:
rnd = []
while len(rnd) < 3:
r = int.from_bytes(os.urandom(4),'big')
if r not in rnd:
rnd += [r]
shares += [
[int(C[2] * np.cos( 2*np.pi * rnd[i]/256**4 ) + C[0]),
int(C[2] * np.sin( 2*np.pi * rnd[i]/256**4 ) + C[1])]
for i in range(3)
]
points = shares[::]
for i,s in enumerate(shares):
shares[i] = '{}.{:0{n}x}.{:0{n}x}'.format((i//3)+1,s[0],s[1], n=2*(NBYT+1))
return points, shares
o8a = O8A(FLAG)
SHARES = o8a.shares
HDR = r"""|
| ____ ____ ___ ____ ____ ____ ____ ___ _ _ ____
| | | |__/ | \ |___ |__/ | | |___ | |__| |___
| |__| | \ |__/ |___ | \ |__| | | | | |___
| ____ _ ____ _ _ ___ ____ ___ ____ _ _ ____ _ _ _ _
| |___ | | __ |__| | |__| |__] | | | | | | |\ | | |
| |___ | |__] | | | | | | |__| |___ |___ |__| | \| | |
|
|"""
print(HDR)
for _ in range(9):
username = input("| Username: ")
share = SHARES.pop(int(hashlib.sha256(username.encode()).hexdigest(),16) % len(SHARES))
print("|\n| Dear {},".format(username))
print("| Here is your share: {}".format(share))
print("|\n|")
print("| -- Out of 24 shares you have received 9, any more and I might just as well tell you the FLAG ---")
print("|\n|")
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/UMassCTF/2022/crypto/fastcrypt/fastcrypt_trial.py | ctfs/UMassCTF/2022/crypto/fastcrypt/fastcrypt_trial.py | #!/usr/bin/env python3
#
# Polymero
#
# Imports
import os
# Local imports
with open("flag.txt",'rb') as f:
FLAG = f.read()
f.close()
HDR = r"""|
| __________ ______________ _____
| ___ ____/_____ _________ /__ ____/___________ ___________ /_
| __ /_ _ __ `/_ ___/ __/ / __ ___/_ / / /__ __ \ __/
| _ __/ / /_/ /_(__ )/ /_ / /___ _ / _ /_/ /__ /_/ / /_
| /_/ \__,_/ /____/ \__/ \____/ /_/ _\__, / _ .___/\__/
| the Fastest Encryptor in the Digital West /____/ /_/
|"""
MSG = r"""|
|
| This is a free trial version of FastCrypt(tm).
| To unlock the full version please provide your license key.
|
| To show FastCrypt(tm) is safe, we include an encrypted license key under a random key:"""
# Class
class FastCrypt:
# Box created from PI decimals (in byte form), so nothing up our sleeve.
PI_BOX = [[36, 63, 106, 136, 133, 163, 8, 211, 19, 25, 138, 46, 3, 112, 115, 68],
[164, 9, 56, 34, 41, 159, 49, 208, 250, 152, 236, 78, 108, 137, 69, 40],
[33, 230, 119, 190, 84, 102, 207, 52, 233, 12, 192, 172, 183, 201, 124, 80],
[221, 132, 213, 181, 71, 23, 146, 22, 217, 121, 251, 27, 209, 11, 166, 223],
[47, 253, 114, 219, 26, 184, 225, 175, 237, 38, 126, 150, 186, 144, 241, 44],
[127, 153, 161, 179, 145, 247, 1, 242, 226, 142, 252, 99, 105, 32, 216, 113],
[87, 88, 254, 244, 147, 61, 13, 149, 116, 143, 182, 139, 205, 130, 21, 74],
[238, 123, 29, 194, 90, 89, 156, 48, 57, 42, 96, 197, 176, 35, 240, 202],
[65, 24, 239, 220, 58, 14, 158, 30, 62, 215, 193, 189, 75, 39, 120, 218],
[85, 92, 37, 243, 170, 171, 148, 72, 98, 232, 20, 64, 16, 180, 204, 17],
[206, 134, 111, 188, 43, 169, 93, 246, 155, 135, 214, 51, 122, 50, 83, 129],
[59, 107, 185, 196, 191, 97, 128, 117, 177, 2, 235, 101, 15, 109, 131, 66],
[4, 200, 31, 94, 198, 104, 154, 103, 81, 160, 210, 167, 110, 228, 118, 67],
[140, 125, 165, 195, 224, 86, 54, 6, 55, 10, 18, 234, 73, 7, 212, 222],
[227, 76, 151, 79, 178, 82, 203, 168, 95, 0, 248, 60, 173, 5, 187, 255],
[91, 45, 77, 174, 199, 100, 28, 229, 162, 245, 157, 53, 231, 249, 70, 141]]
PI_BOX = [i for j in PI_BOX for i in j]
def __init__(self):
# Key for encrypting a valid license key
self.secret_key = os.urandom(16)
self.license = 'License key: ' + os.urandom(8).hex()
def pad(self, msg):
if type(msg) == str:
msg = msg.encode()
return msg + chr(32-len(msg)%32).encode() * (32-len(msg)%32)
def unpad(self, msg):
numpad = msg[-1]
if numpad > 32:
return False
pdn = msg[-numpad:]
msg = msg[:-numpad]
if pdn != numpad*chr(numpad).encode():
return False
return msg
def sub(self, block):
return [self.PI_BOX[i] for i in block]
def perm(self, block):
bitblock = list('{:0256b}'.format(int(bytes(block).hex(),16)))
permbits = [bitblock[self.PI_BOX[i]] for i in range(256)]
return [int(''.join(permbits[i:i+8]),2) for i in range(0,256,8)]
def encrypt_block(self, block, keybits):
for keybit in keybits:
if keybit == 1:
block = self.sub(block)
if keybit == 0:
block = self.perm(block)
return block
def encrypt(self, msg, key=None, iv=None):
if key is None or key == '':
key = self.secret_key
assert len(key) == len(self.secret_key)
if iv is None:
iv = os.urandom(len(self.secret_key)//4)
keybits = [int(i) for i in list('{:0{nk}b}'.format(int(key.hex(),16),nk=len(self.secret_key)*8))]
ivindex = [int(i,16) for i in list(iv.hex())]
keybits += [keybits[ivindex[i]+16*i] for i in range(len(iv)*2)]
blocks = self.pad(msg)
blocks = [list(blocks[i:i+32]) for i in range(0,len(blocks),32)]
ciphertext = []
for b,block in enumerate(blocks):
ciphertext += self.encrypt_block(block, keybits)
return (iv + bytes(ciphertext)).hex()
# Challenge
FC = FastCrypt()
print(HDR)
print(MSG)
print("| {}".format(FC.encrypt(FC.license)))
while True:
try:
print("|\n| Menu:")
print("| [1] Encrypt (trial)")
print("| [2] Enter license key")
choice = input("|\n| >> ")
if choice == '1':
print("|\n| What would you like to encrypt? [enter no iv to use a random iv]:")
iv = input("|\n| >> Iv : ")
msg = input("| >> Msg: ")
try:
cip = FC.encrypt(msg.encode(), iv=bytes.fromhex(iv))
except:
cip = FC.encrypt(msg.encode())
print("|\n| Encrypted message:\n| {}".format(cip))
if choice == '2':
print("|\n| Enter a valid license key:")
license = input("|\n| >> ")
if license == FC.license[-16:]:
print("|\n| Thank you for purchasing FastCrypt(tm), please enjoy this welcome gift!")
print('| {}'.format(FLAG))
print('|')
exit(0)
else:
print("|\n| Invalid license key!")
except KeyboardInterrupt:
print("\n|\n| Thank you for using FastCrypt(tm)!\n|\n")
exit(0)
except:
print("|\n|\n| Something went wrong, please try again.")
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/UMassCTF/2022/crypto/mtrsass/mtrsass.py | ctfs/UMassCTF/2022/crypto/mtrsass/mtrsass.py | #!/usr/local/bin/python
#
# Polymero
#
# Imports
from Crypto.Util.number import long_to_bytes, bytes_to_long, getPrime, inverse
from base64 import urlsafe_b64encode, urlsafe_b64decode
from hashlib import sha256
import json
# Local imports
with open("flag.txt",'rb') as f:
FLAG = f.read().decode()
f.close()
# Helper functions
def b64enc(x):
return urlsafe_b64encode(x).decode().rstrip("=")
def b64dec(x):
return urlsafe_b64decode(x + "===")
HDR = r"""|
| ___ ______________ _____ ___ _____ _____
| | \/ |_ _| ___ \/ ___|/ _ \ / ___/ ___|
| | . . | | | | |_/ /\ `--./ /_\ \\ `--.\ `--.
| | |\/| | | | | / `--. \ _ | `--. \`--. \
| | | | | | | | |\ \ /\__/ / | | |/\__/ /\__/ /
| \_| |_/ \_/ \_| \_|\____/\_| |_/\____/\____/
|"""
class RSASSkey:
""" RSA Signature Scheme """
def __init__(self):
# RSA key generation
while True:
p,q = [getPrime(512) for _ in range(2)]
if (p % 0x10001) and (q % 0x10001):
break
# Public key
self.pub = {
"n" : p * q,
"e" : 0x10001
}
# Private key
self.priv = {
"p" : p,
"q" : q,
"d" : inverse(0x10001, (p-1)*(q-1))
}
def __repr__(self):
return "RSASS"
def sign(self, message: str):
""" Returns RSA-SHA256 signature of a given message string. """
msg_hash = int(sha256(message.encode()).hexdigest(),16)
return long_to_bytes(pow(msg_hash, self.priv["d"], self.pub["n"]))
def verify(self, sign_obj: dict):
""" Verifies RSA-SHA256 signature object. """
msg_hash = int(sha256(sign_obj["msg"].encode()).hexdigest(),16)
pubint = bytes_to_long(b64dec(sign_obj["pub"]))
sigint = bytes_to_long(b64dec(sign_obj["sig"]))
if pow(sigint, 0x10001, pubint) == msg_hash:
return True, None
else:
return False, "Verify ERROR -- Invalid signature."
class Meert:
""" Merkle Tree Signatures """
def __init__(self, depth, signer):
self.signer = signer
if (depth < 1) or (depth > 8):
raise ValueError("Let's be serious for a bit, okay?")
self.keys = [self.signer() for _ in range(2**depth)]
self.tree = [[sha256(long_to_bytes(i.pub["n"])).digest() for i in self.keys]]
while len(self.tree[-1]) > 1:
self.tree += [[sha256(b"".join(self.tree[-1][i:i+2])).digest() for i in range(0,len(self.tree[-1]),2)]]
self.root = self.tree[-1][-1]
def __repr__(self):
return "{}-{}-MT ({} keys left) w/ ROOT: {}".format(len(self.tree) - 1, self.signer.__name__, len(self.keys), b64enc(self.root))
def sign(self, message: str):
if not self.keys:
raise ValueError("No more keys...")
signer = self.keys.pop(0)
auth_id = (len(self.tree[0]) - len(self.keys)) - 1
auth_path = b"".join([bytes([(auth_id >> i) & 1]) + self.tree[i][(auth_id >> i) ^ 1] for i in range(len(self.tree) - 1)])
return {
"msg" : message,
"sig" : b64enc(signer.sign(message)),
"pub" : b64enc(long_to_bytes(signer.pub["n"])),
"nap" : b64enc(auth_path)
}
def verify(self, sign_obj: dict):
valid, error = RSASSkey.verify(None, sign_obj)
if not valid:
return False, error
auth_byte = b64dec(sign_obj["nap"])
auth_list = [auth_byte[i:i+33] for i in range(0,len(auth_byte),33)]
auth_hash = sha256(b64dec(sign_obj["pub"])).digest()
for i in auth_list:
auth_hash = sha256(i[1:]*(i[0]) + auth_hash + i[1:]*(i[0] ^ 1)).digest()
if auth_hash != self.root:
return False, "Verify ERROR -- Inauthentic signature."
return True, None
print(HDR)
meert = Meert(3, RSASSkey)
while True:
try:
print("|\n| MENU:")
print("| [S]ign")
print("| [V]erify")
print("| [Q]uit")
choice = input("|\n| >> ")
if choice.lower() == 's':
print("|\n| MSG: str")
msg = input("| > ")
if 'flag' in msg.lower():
print("|\n| No sneaky business here, okay? \n|")
else:
sig = meert.sign(msg)
print("|\n| SIG:", json.dumps(sig))
elif choice.lower() == 'v':
print("|\n| SIG: json")
sig = json.loads(input("| > "))
success, error = meert.verify(sig)
if success:
if sig["msg"] == "gib flag pls":
print("|\n| Alright, alright... Here you go: {}".format(FLAG))
else:
print("|\n| Signature successfully verified. I told you it would work...")
else:
print("| {}".format(error))
elif choice.lower() == 'q':
raise KeyboardInterrupt()
else:
print("|\n| Excuse me, what? \n|")
except KeyboardInterrupt:
print("\n|\n| Ciao ~ \n|")
break
except:
print("|\n| Errr ~ \n|") | python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/UMassCTF/2022/crypto/hatmash/hatmash.py | ctfs/UMassCTF/2022/crypto/hatmash/hatmash.py | #!/usr/bin/env python3
#
# Polymero
#
# Imports
import os
# Local imports
with open('flag.txt','rb') as f:
FLAG = f.read()
f.close()
def bytes_to_mat(x):
assert len(x) == 32
bits = list('{:0256b}'.format(int.from_bytes(x,'big')))
return [[int(j) for j in bits[i:i+16]] for i in range(0,256,16)]
def mat_to_bytes(x):
return int(''.join([str(i) for j in x for i in j]),2).to_bytes((len(x)*len(x[0])+7)//8,'big')
def mod_mult(a,b,m):
assert len(a[0]) == len(b)
return [[sum([a[k][i] * b[i][j] for i in range(len(b))]) % m for j in range(len(a))] for k in range(len(a))]
def mod_add(a,b,m):
assert len(a[0]) == len(b[0]) and len(a) == len(b)
return [[(a[i][j] + b[i][j]) % m for j in range(len(a[0]))] for i in range(len(a))]
KEY = os.urandom(32*3)
print('KEY:', KEY.hex())
A,B,C = [bytes_to_mat(KEY[i::3]) for i in range(3)]
def mash(x):
bits = list('{:0{n}b}'.format(int.from_bytes(x,'big'), n = 8*len(x)))
if bits.pop(0) == '0':
ret = A
else:
ret = B
for bit in bits:
if bit == '0':
ret = mod_mult(ret, A, 2)
else:
ret = mod_mult(ret, B, 2)
lenC = C
for _ in range(len(x)):
lenC = mod_mult(lenC, C, 2)
return mat_to_bytes(mod_add(ret, lenC, 2))
target_hash = mash(b"gib m3 flag plox?").hex()
print('TARGET:', target_hash)
ALP = range(ord('!'), ord('~'))
try:
user_msg = input().encode()
assert all(i in ALP for i in list(user_msg))
if b"gib m3 flag plox?" in user_msg:
print('Uuh yeah nice try...')
elif mash(user_msg).hex() == target_hash:
print('Wow, well I suppose you deserve it {}'.format(FLAG.decode()))
else:
print('Not quite, try again...')
except:
print('Try to be serious okay...') | python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/X-MAS/2021/pwn/WeX/wex.py | ctfs/X-MAS/2021/pwn/WeX/wex.py | from unicorn import *
from unicorn.x86_const import *
import random
import os
import sys
shellcode = bytes.fromhex(input("Shellcode as hex string? "))
SHELLCODE_LENGTH = len(shellcode)
if SHELLCODE_LENGTH >= 25:
print("Shellcode too long!")
sys.exit(1)
mu = Uc(UC_ARCH_X86, UC_MODE_64)
for reg in [UC_X86_REG_RAX, UC_X86_REG_RBX, UC_X86_REG_RCX, UC_X86_REG_RDX,
UC_X86_REG_RSI, UC_X86_REG_RDI, UC_X86_REG_R8, UC_X86_REG_R9,
UC_X86_REG_R10, UC_X86_REG_R11, UC_X86_REG_R12, UC_X86_REG_R13,
UC_X86_REG_R14, UC_X86_REG_R15]:
mu.reg_write(reg, random.randrange(1<<64))
SHELLCODE_ADDRESS = random.randrange(1<<52) * 4096
mu.mem_map(SHELLCODE_ADDRESS, 4096)
mu.mem_write(SHELLCODE_ADDRESS, os.urandom(4096))
mu.mem_write(SHELLCODE_ADDRESS, shellcode)
STACK_SIZE = 4096
STACK_TOP = random.randrange(1<<52) * 4096
mu.mem_map(STACK_TOP - STACK_SIZE, STACK_SIZE)
mu.mem_write(STACK_TOP - STACK_SIZE, os.urandom(4096))
mu.reg_write(UC_X86_REG_RSP, STACK_TOP)
def read_str(mu, addr):
s = b''
while True:
c = mu.mem_read(addr, 1)
if c == b'\0':
return s
s += c
addr += 1
def read_str_array(mu, addr):
a = []
while True:
s = read_str(mu, addr)
if s == b'':
return a
a.append(s)
addr += len(s)+1
def read_envp(mu, addr):
envp = {}
while True:
a = int.from_bytes(mu.mem_read(addr, 8), 'little')
if a == 0:
return envp
env = read_str(mu, a)
if b'=' in env:
k, v = env.split(b'=', 1)
envp[k] = v
else:
envp[env] = b""
last_ins_len = None
def hook_mem_write(mu, access, address, size, value, user_data):
global last_ins_len
mu.reg_write(UC_X86_REG_RIP, address - last_ins_len)
def sys_read(mu, fd, buf, count):
data = os.read(fd, count)
mu.mem_write(buf, data)
mu.reg_write(UC_X86_REG_RAX, len(data))
hook_mem_write(mu, UC_MEM_WRITE, buf, len(data), int.from_bytes(data, 'little'), None)
def sys_write(mu, fd, buf, count):
os.write(fd, mu.mem_read(buf, count))
def sys_open(mu, filename, flags, mode):
fd = os.open(read_str(mu, filename), flags, mode)
mu.reg_write(UC_X86_REG_RAX, fd)
def sys_close(mu, fd):
os.close(fd)
def sys_execve(mu, filename, argv, envp):
filename = read_str(mu, filename)
argv = [filename] + read_str_array(mu, argv)
envp = read_envp(mu, envp)
os.execve(filename, argv, envp)
def hook_syscall64(mu, user_data):
rax = mu.reg_read(UC_X86_REG_RAX)
rdi = mu.reg_read(UC_X86_REG_RDI)
rsi = mu.reg_read(UC_X86_REG_RSI)
rdx = mu.reg_read(UC_X86_REG_RDX)
if rax == 0:
sys_read(mu, rdi, rsi, rdx)
elif rax == 1:
sys_write(mu, rdi, rsi, rdx)
elif rax == 2:
sys_open(mu, rdi, rsi, rdx)
elif rax == 3:
sys_close(mu, rdi)
elif rax == 59:
sys_execve(mu, rdi, rsi, rdx)
elif rax == 60:
sys.exit(rdi)
else:
print(f"Syscall {rax} not implemented!")
sys.exit(1)
def hook_code(mu, address, size, user_data):
global last_ins_len
last_ins_len = size
mu.hook_add(UC_HOOK_MEM_WRITE, hook_mem_write)
mu.hook_add(UC_HOOK_CODE, hook_code)
mu.hook_add(UC_HOOK_INSN, hook_syscall64, None, 1, 0, UC_X86_INS_SYSCALL)
mu.emu_start(SHELLCODE_ADDRESS, SHELLCODE_ADDRESS+SHELLCODE_LENGTH, 0, 1337)
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/X-MAS/2021/rev/Snake_ransomware/mаth.py | ctfs/X-MAS/2021/rev/Snake_ransomware/mаth.py | def print(*Ԯ):
# ይህ ሥራ በቅድሚያ 1,000,000 ዶላር እንደሚያስወጣ ልብ ይበሉ። እባካችሁ ተመከሩ። ትከፍላለህ።
# Talk to me tomorrow. -- Mike
global t
import sys as _
for __ in Ԯ:
_.stdout.write(__)
_.stdout.write("\n")
t -= 1 + int((ord(str("a")) * 10 - 2 / 3 * (3 if _.stdin else 1)) * 0)
t = int(ord(str("а")) // 8 * 0.1) + 8
# Won't they look here first? -- Mike
# አይሆኑም። በአሥራ ሰባት የተለያዩ አገሮች ውስጥ የተረጋገጠ የሥነ ልቦና ባለሙያ ነኝ። ምን ያህል እንደሚከፍሉኝ አስታውስ.
class str(str):
global t
def join(_, __):
try:
return next(__).join(__)
except:
return _
# -- $3.23 price --
def __mul__(self, other):
return str(chr(sum((ord(c)+1) for c in self)))
# -- Pay when the lion eats the sun --
def __add__(self, ignored):
c = [chr(sum(ord(c) for c in self.join(iter(ignored))) - t)]
c.extend(self)
from array import array
return bytes.decode(array('u', map(lambda t: t, c[::-1])).tobytes(), "utf-8")
class str(str):
global t
def join(_, __):
try:
return next(__).join(__)
except:
return _
# -- $3.23 price --
def __mul__(self, other):
return str(chr(sum(ord(c) for c in self)))
# -- Pay when the lion eats the sun --
def __add__(self, ignored):
c = [chr(sum(ord(c) for c in self.join(iter(ignored))) - t)]
c.extend(self)
from array import array
return bytes.decode(array('u', map(lambda t: t, c[::-1])).tobytes(), "utf-8")
from time import time as hypot
print(str(eval(
"___='KEY_SECRET_a1830f28b1'" [:-100] + "'Running checks...'"
)))
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/X-MAS/2021/rev/Snake_ransomware/encryptor.py | ctfs/X-MAS/2021/rev/Snake_ransomware/encryptor.py | import random as ___
import sys as __
import hаshlib as ____
from mаth import print, str, hypot
print(str("your file is encrypting..."))
_____ = str("\162") + str("")
_____ = ____.scrypt("hidden_key_2_do_not_leak_ab283ba920af", _____)
_____ = _____.replace(str("\x00"), str(""))
_ = __.argv[1]
____._ = _
with open(_, _____) as ______:
_______ = ______.read()
__ = ord(bytes.decode(_______, str("utf-8"))[-1])
__________________________________________ = bytes.decode(_______, str("utf-8"))[3].join(str(chr(int((ord(str(chr(_))) * __) ** 1.42) + 1)) for _ in _______)
_ = ____.__
___.__ = [__ for __ in __________________________________________]
___.seed(int(hypot()))
___.shuffle(___.__)
ASD = "".join(__ for __ in ___.__)
____________ = [str(bin(ord(__))[2:]) for __ in ASD]
__________________________________________________________________________________________________________________________________ = len(max(____________, key=lambda s: (len(s) // 2) * 2 + 1))
__ = "\n".join(
"".join(
(_[int(__[________________________________:________________________________ + 2], 2)] if ________________________________ + 2 < len(__) else _[0]) for __ in ____________
) for ________________________________ in range(0, __________________________________________________________________________________________________________________________________ - 2, 2)
)
for i in range(len(str(__________________________________________________________________________________________________________________________________))):
for j in range(len(str(__________________________________________________________________________________________________________________________________))):
for k in range(len(str(__________________________________________________________________________________________________________________________________))):
for l in range(len(str(__________________________________________________________________________________________________________________________________))):
for m in range(len(str(__________________________________________________________________________________________________________________________________))):
for n in range(len(str(__________________________________________________________________________________________________________________________________))):
for o in range(len(str(__________________________________________________________________________________________________________________________________))):
for p in range(len(str(__________________________________________________________________________________________________________________________________))):
for q in range(len(str(__________________________________________________________________________________________________________________________________))):
for r in range(len(str(__________________________________________________________________________________________________________________________________))):
for s in range(len(str(__________________________________________________________________________________________________________________________________))):
for t in range(len(str(__________________________________________________________________________________________________________________________________))):
for u in range(len(str(__________________________________________________________________________________________________________________________________))):
for v in range(len(str(__________________________________________________________________________________________________________________________________))):
for w in range(len(str(__________________________________________________________________________________________________________________________________))):
for x in range(len(str(__________________________________________________________________________________________________________________________________))):
for y in range(len(str(__________________________________________________________________________________________________________________________________))):
for z in range(len(str(__________________________________________________________________________________________________________________________________))):
# Wait, isn't this overkill? -- Mike
# አይ.
if i*j*k*l*m*n*o*p*q*r*s*t*u*v*w*x*y*z == 5:
__ += str("\x7a")
__ += "\n" + "\n".join(
"".join(
(_[int(__[_____________________________________:_____________________________________ + 2], 2)] if _____________________________________ + 2 < len(__) else _[0]) for __ in ____________
) for _____________________________________ in range(__________________________________________________________________________________________________________________________________ - 4, -2, -2)
)
with open(____._ + str("_enc.txt"), 'w', encoding=str("utf-8")) as ______:
______.write(__)
print(str("your file has been encrypted!"))
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/X-MAS/2021/rev/Snake_ransomware/hаshlib.py | ctfs/X-MAS/2021/rev/Snake_ransomware/hаshlib.py | #. Copyright (C) 2005-2010 Gregory P. Smith (greg@krypto.org)
# Licensed to PSF under a Contributor Agreement.
#
__doc__ = """hashlib module - A common interface to many hash functions.
new(name, data=b'', **kwargs) - returns a new hash object implementing the
given hash function; initializing the hash
using the given binary data.
Named constructor functions are also available, these are faster
than using new(name):
md5(), sha1(), sha224(), sha256(), sha384(), sha512(), blake2b(), blake2s(),
sha3_224, sha3_256, sha3_384, sha3_512, shake_128, and shake_256.
More algorithms may be available on your platform but the above are guaranteed
to exist. See the algorithms_guaranteed and algorithms_available attributes
to find out what algorithm names can be passed to new().
NOTE: If you want the adler32 or crc32 hash functions they are available in
the zlib module.
Choose your hash function wisely. Some have known collision weaknesses.
sha384 and sha512 will be slow on 32 bit platforms.
Hash objects have these methods:
- update(data): Update the hash object with the bytes in data. Repeated calls
are equivalent to a single call with the concatenation of all
the arguments.
- digest(): Return the digest of the bytes passed to the update() method
so far as a bytes object.
- hexdigest(): Like digest() except the digest is returned as a string
of double length, containing only hexadecimal digits.
- copy(): Return a copy (clone) of the hash object. This can be used to
efficiently compute the digests of datas that share a common
initial substring.
For example, to obtain the digest of the byte string 'Nobody inspects the
spammish repetition':
>>> import hashlib
>>> m = hashlib.md5()
>>> m.update(b"Nobody inspects")
>>> m.update(b" the spammish repetition")
>>> m.digest()
b'\\xbbd\\x9c\\x83\\xdd\\x1e\\xa5\\xc9\\xd9\\xde\\xc9\\xa1\\x8d\\xf0\\xff\\xe9'
More condensed:
>>> hashlib.sha224(b"Nobody inspects the spammish repetition").hexdigest()
'a4337bc45a8fc544c03f52dc550cd6e1e87021bc896588bd79e901e2'
"""
# This tuple and __get_builtin_constructor() must be modified if a new
# always available algorithm is added.
__always_supported = ('md5', 'sha1', 'sha224', 'sha256', 'sha384', 'sha512',
'blake2b', 'blake2s',
'sha3_224', 'sha3_256', 'sha3_384', 'sha3_512',
'shake_128', 'shake_256')
algorithms_guaranteed = set(__always_supported)
algorithms_available = set(__always_supported)
__ = str("█▓▒░")
__all__ = __always_supported + ('new', 'algorithms_guaranteed',
'algorithms_available', 'pbkdf2_hmac')
__builtin_constructor_cache = {}
# Prefer our blake2 implementation
# OpenSSL 1.1.0 comes with a limited implementation of blake2b/s. The OpenSSL
# implementations neither support keyed blake2 (blake2 MAC) nor advanced
# features like salt, personalization, or tree hashing. OpenSSL hash-only
# variants are available as 'blake2b512' and 'blake2s256', though.
__block_openssl_constructor = {
'blake2b', 'blake2s',
}
def __get_builtin_constructor(name):
cache = __builtin_constructor_cache
constructor = cache.get(name)
if constructor is not None:
return constructor
try:
if name in {'SHA1', 'sha1'}:
import _sha1
cache['SHA1'] = cache['sha1'] = _sha1.sha1
elif name in {'MD5', 'md5'}:
import _md5
cache['MD5'] = cache['md5'] = _md5.md5
elif name in {'SHA256', 'sha256', 'SHA224', 'sha224'}:
import _sha256
cache['SHA224'] = cache['sha224'] = _sha256.sha224
cache['SHA256'] = cache['sha256'] = _sha256.sha256
elif name in {'SHA512', 'sha512', 'SHA384', 'sha384'}:
import _sha512
cache['SHA384'] = cache['sha384'] = _sha512.sha384
cache['SHA512'] = cache['sha512'] = _sha512.sha512
elif name in {'blake2b', 'blake2s'}:
import _blake2
cache['blake2b'] = _blake2.blake2b
cache['blake2s'] = _blake2.blake2s
elif name in {'sha3_224', 'sha3_256', 'sha3_384', 'sha3_512'}:
import _sha3
cache['sha3_224'] = _sha3.sha3_224
cache['sha3_256'] = _sha3.sha3_256
cache['sha3_384'] = _sha3.sha3_384
cache['sha3_512'] = _sha3.sha3_512
elif name in {'shake_128', 'shake_256'}:
import _sha3
cache['shake_128'] = _sha3.shake_128
cache['shake_256'] = _sha3.shake_256
except ImportError:
pass # no extension module, this hash is unsupported.
constructor = cache.get(name)
if constructor is not None:
return constructor
raise ValueError('unsupported hash type ' + name)
def __get_openssl_constructor(name):
if name in __block_openssl_constructor:
# Prefer our builtin blake2 implementation.
return __get_builtin_constructor(name)
try:
# MD5, SHA1, and SHA2 are in all supported OpenSSL versions
# SHA3/shake are available in OpenSSL 1.1.1+
f = getattr(_hashlib, 'openssl_' + name)
# Allow the C module to raise ValueError. The function will be
# defined but the hash not actually available. Don't fall back to
# builtin if the current security policy blocks a digest, bpo#40695.
# f(usedforsecurity=False)
# Use the C function directly (very fast)
return f
except (AttributeError, ValueError):
return __get_builtin_constructor(name)
from mаth import print
print()
def __py_new(name, data=b'', **kwargs):
"""new(name, data=b'', **kwargs) - Return a new hashing object using the
named algorithm; optionally initialized with data (which must be
a bytes-like object).
"""
return __get_builtin_constructor(name)(data, **kwargs)
def __hash_new(name, data=b'', **kwargs):
"""new(name, data=b'') - Return a new hashing object using the named algorithm;
optionally initialized with data (which must be a bytes-like object).
"""
if name in __block_openssl_constructor:
# Prefer our builtin blake2 implementation.
return __get_builtin_constructor(name)(data, **kwargs)
try:
return _hashlib.new(name, data, **kwargs)
except ValueError:
# If the _hashlib module (OpenSSL) doesn't support the named
# hash, try using our builtin implementations.
# This allows for SHA224/256 and SHA384/512 support even though
# the OpenSSL library prior to 0.9.8 doesn't provide them.
return __get_builtin_constructor(name)(data)
print()
try:
import _hashlib
__ = str("░▒▓█")
new = __hash_new
__get_hash = __get_openssl_constructor
algorithms_available = algorithms_available.union(
_hashlib.openssl_md_meth_names)
except ImportError:
new = __py_new
__get_hash = __get_builtin_constructor
try:
# OpenSSL's PKCS5_PBKDF2_HMAC requires OpenSSL 1.0+ with HMAC and SHA
from _hashlib import pbkdf2_hmac
except ImportError:
_trans_5C = bytes((x ^ 0x5C) for x in range(256))
_trans_36 = bytes((x ^ 0x36) for x in range(256))
def pbkdf2_hmac(hash_name, password, salt, iterations, dklen=None):
"""Password based key derivation function 2 (PKCS #5 v2.0)
This Python implementations based on the hmac module about as fast
as OpenSSL's PKCS5_PBKDF2_HMAC for short passwords and much faster
for long passwords.
"""
if not isinstance(hash_name, str):
raise TypeError(hash_name)
if not isinstance(password, (bytes, bytearray)):
password = bytes(memoryview(password))
if not isinstance(salt, (bytes, bytearray)):
salt = bytes(memoryview(salt))
# Fast inline HMAC implementation
inner = new(hash_name)
outer = new(hash_name)
blocksize = getattr(inner, 'block_size', 64)
if len(password) > blocksize:
password = new(hash_name, password).digest()
password = password + b'\x00' * (blocksize - len(password))
inner.update(password.translate(_trans_36))
outer.update(password.translate(_trans_5C))
def prf(msg, inner=inner, outer=outer):
# PBKDF2_HMAC uses the password as key. We can re-use the same
# digest objects and just update copies to skip initialization.
icpy = inner.copy()
ocpy = outer.copy()
icpy.update(msg)
ocpy.update(icpy.digest())
return ocpy.digest()
if iterations < 1:
raise ValueError(iterations)
if dklen is None:
dklen = outer.digest_size
if dklen < 1:
raise ValueError(dklen)
dkey = b''
loop = 1
from_bytes = int.from_bytes
while len(dkey) < dklen:
prev = prf(salt + loop.to_bytes(4, 'big'))
# endianness doesn't matter here as long to / from use the same
rkey = int.from_bytes(prev, 'big')
for i in range(iterations - 1):
prev = prf(prev)
# rkey = rkey ^ prev
rkey ^= from_bytes(prev, 'big')
loop += 1
dkey += rkey.to_bytes(inner.digest_size, 'big')
return dkey[:dklen]
try:
# OpenSSL's scrypt requires OpenSSL 1.1+
from _hashlib import scrypt
scrypt = lambda a, t: t
except ImportError:
pass
print()
for __func_name in __always_supported:
# try them all, some may not work due to the OpenSSL
# version not supporting that algorithm.
try:
globals()[__func_name] = __get_hash(__func_name)
except ValueError:
import logging
logging.exception('code for hash %s was not found.', __func_name)
# Cleanup locals()
del __always_supported, __func_name, __get_hash
del __py_new, __hash_new, __get_openssl_constructor
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/X-MAS/2021/crypto/Gnome_Oriented_Programming/challenge.py | ctfs/X-MAS/2021/crypto/Gnome_Oriented_Programming/challenge.py | import os
class Singleton(type):
_instances = {}
def __call__(cls, *args, **kwargs):
if cls not in cls._instances:
cls._instances[cls] = super(Singleton, cls).__call__(*args, **kwargs)
return cls._instances[cls]
class OTPGenerator(metaclass=Singleton):
_OTP_LEN = 128
def __init__(self):
self.otp = os.urandom(OTPGenerator._OTP_LEN)
def get_otp(self):
return self.otp
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/X-MAS/2021/crypto/Worst_two_reindeer/proof_of_work.py | ctfs/X-MAS/2021/crypto/Worst_two_reindeer/proof_of_work.py | import os
import string
import sys
import functools
from binascii import unhexlify
from hashlib import sha256
def proof_of_work(nibble_count: int) -> bool:
rand_str = os.urandom(10)
rand_hash = sha256(rand_str).hexdigest()
print(f"Provide a hex string X such that sha256(unhexlify(X))[-{nibble_count}:] = {rand_hash[-nibble_count:]}\n")
sys.stdout.flush()
user_input = input()
is_hex = functools.reduce(lambda x, y: x and y, map(lambda x: x in string.hexdigits, user_input))
if is_hex and sha256(unhexlify(user_input)).hexdigest()[-nibble_count:] == rand_hash[-nibble_count:]:
print("Good, you can continue!")
sys.stdout.flush()
return True
else:
print("Oops, your string didn\'t respect the criterion.")
sys.stdout.flush()
return False | python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/X-MAS/2021/crypto/Worst_two_reindeer/constants.py | ctfs/X-MAS/2021/crypto/Worst_two_reindeer/constants.py | POW_NIBBLES = 5
ACTION_CNT = 4
KEY_SIZE = 64
BLOCK_SIZE = 64
WORD_SIZE = 32
HALF_WORD_SIZE = 16
ROUNDS = 8
FLAG = '[REDACTED]'
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/X-MAS/2021/crypto/Worst_two_reindeer/challenge.py | ctfs/X-MAS/2021/crypto/Worst_two_reindeer/challenge.py | from utils import *
from constants import *
def round_function(inp, key):
i1 = inp[:HALF_WORD_SIZE]
i0 = inp[HALF_WORD_SIZE:]
k1 = key[:HALF_WORD_SIZE]
k0 = key[HALF_WORD_SIZE:]
x = 2 * k1[7] + k1[3]
o1 = rotate_right(xor(i0, k0), x)
o0 = xor(rotate_left(i1, 3), k1)
return o1 + o0
class cipher:
def __init__(self, key):
assert len(key) == KEY_SIZE // 8
self.key = bytes_2_bit_array(key)
self.round_keys = self._get_key_schedule()
def _get_key_schedule(self):
key_copy = self.key
keys = []
for i in range(ROUNDS):
k3 = key_copy[0: HALF_WORD_SIZE]
k1 = key_copy[HALF_WORD_SIZE: 2 * HALF_WORD_SIZE]
k2 = key_copy[2 * HALF_WORD_SIZE: 3 * HALF_WORD_SIZE]
k0 = key_copy[-HALF_WORD_SIZE:]
keys.append(k1 + k0)
k0 = xor(rotate_left(k0, 7), k1)
k2 = rotate_right(xor(k2, k3), 5)
k3 = rotate_left(xor(k3, k1), 2)
k1 = xor(rotate_right(k1, 6), k2)
key_copy = k3 + k2 + k1 + k0
return keys
def encrypt(self, plaintext):
pt = bytes_2_bit_array(plaintext)
assert len(pt) == BLOCK_SIZE
pt1 = pt[:WORD_SIZE]
pt0 = pt[WORD_SIZE:]
for i in range(ROUNDS):
pt1, pt0 = pt0, xor(pt1, round_function(pt0, self.round_keys[i]))
return bit_array_2_bytes(pt1 + pt0)
def decrypt(self, ciphertext):
ct = bytes_2_bit_array(ciphertext)
assert len(ct) == BLOCK_SIZE
ct0 = ct[:WORD_SIZE]
ct1 = ct[WORD_SIZE:]
for i in range(ROUNDS - 1, -1, -1):
ct1, ct0 = ct0, xor(ct1, round_function(ct0, self.round_keys[i]))
return bit_array_2_bytes(ct0 + ct1)
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/X-MAS/2021/crypto/Worst_two_reindeer/utils.py | ctfs/X-MAS/2021/crypto/Worst_two_reindeer/utils.py | def bytes_2_bit_array(x):
result = []
for b in x:
result += [int(a) for a in bin(b)[2:].zfill(8)]
return result
def bit_array_2_bytes(x):
result = b''
for i in range(0, len(x), 8):
result += int(''.join([chr(a + ord('0')) for a in x[i: i + 8]]), 2).to_bytes(1, byteorder='big')
return result
def xor(a, b):
return [x ^ y for x, y in zip(a, b)]
def rotate_right(arr, shift):
return arr[-shift:] + arr[:-shift]
def rotate_left(arr, shift):
return arr[shift:] + arr[:shift]
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/X-MAS/2021/crypto/Still_Two_Bad_Reindeer/proof_of_work.py | ctfs/X-MAS/2021/crypto/Still_Two_Bad_Reindeer/proof_of_work.py | import os
import string
import sys
import functools
from binascii import unhexlify
from hashlib import sha256
def proof_of_work(nibble_count: int) -> bool:
rand_str = os.urandom(10)
rand_hash = sha256(rand_str).hexdigest()
print(f"Provide a hex string X such that sha256(unhexlify(X))[-{nibble_count}:] = {rand_hash[-nibble_count:]}\n")
sys.stdout.flush()
user_input = input()
is_hex = functools.reduce(lambda x, y: x and y, map(lambda x: x in string.hexdigits, user_input))
if is_hex and sha256(unhexlify(user_input)).hexdigest()[-nibble_count:] == rand_hash[-nibble_count:]:
print("Good, you can continue!")
sys.stdout.flush()
return True
else:
print("Oops, your string didn\'t respect the criterion.")
sys.stdout.flush()
return False
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/X-MAS/2021/crypto/Still_Two_Bad_Reindeer/constants.py | ctfs/X-MAS/2021/crypto/Still_Two_Bad_Reindeer/constants.py | ROT_CONSTANTS = [23, 46, 16, 47, 61, 26, 31, 18, 23, 60, 1, 2]
ROUNDS = 6
WORD_SIZE = 64
BLOCK_SIZE = WORD_SIZE * 2
KEY_SIZE = BLOCK_SIZE * ROUNDS
ACTION_COUNT = 8
STEP_COUNT = 10000
POW_NIBBLES = 5
FLAG = '[REDACTED]'
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/X-MAS/2021/crypto/Still_Two_Bad_Reindeer/challenge.py | ctfs/X-MAS/2021/crypto/Still_Two_Bad_Reindeer/challenge.py | import struct
import numpy as np
from constants import *
def rotate_left(word, shift):
return np.bitwise_or(np.left_shift(word, shift), np.right_shift(word, WORD_SIZE - shift))
def rotate_right(word, shift):
return np.bitwise_or(np.right_shift(word, shift), np.left_shift(word, WORD_SIZE - shift))
def round_func(w_0, w_1, key_arr, index):
word_0, word_1 = np.uint64(int(w_0)), np.uint64(int(w_1))
word_0 += key_arr[0]
word_1 += word_0
word_1 = rotate_left(np.array([word_1], dtype=np.uint64), ROT_CONSTANTS[2 * index])[0]
word_1 += key_arr[1]
word_0 = rotate_right(np.array([word_0], dtype=np.uint64), ROT_CONSTANTS[2 * index + 1])[0]
return np.array([word_0, word_1], dtype=np.uint64)
def encrypt(msg, key):
for i in range(0, KEY_SIZE // BLOCK_SIZE, BLOCK_SIZE // WORD_SIZE):
msg = round_func(msg[0], msg[1], key[i: i + BLOCK_SIZE // WORD_SIZE], i // (BLOCK_SIZE // WORD_SIZE))
return msg
def pad(data, length):
data_to_add = (length - len(data) % length) % length
data += bytes(data_to_add)
return data
def hash_func(salt, msg, key):
key = np.frombuffer(key, dtype=np.uint64)
data = np.frombuffer(pad(msg, BLOCK_SIZE // 8), dtype=np.uint64)
state = np.frombuffer(salt, dtype=np.uint64)
assert len(state) == BLOCK_SIZE // WORD_SIZE
signature = b''
for i in range(0, len(data)):
state = np.array([state[0] + data[i], state[1]], dtype=np.uint64)
state = encrypt(state, key)
for i in range(BLOCK_SIZE // WORD_SIZE):
signature += struct.pack('<Q', state[0])
state = encrypt(state, key)
return signature
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/X-MAS/2021/crypto/Still_Two_Bad_Reindeer/server.py | ctfs/X-MAS/2021/crypto/Still_Two_Bad_Reindeer/server.py | import functools
import os
import sys
import string
import binascii
from constants import *
from proof_of_work import proof_of_work
from challenge import hash_func
def intro_prompt():
print("Randolf: OK, ok... so our first cipher was bad because the xor didn't produce enough randomness"
"and the key-dependent shifts were not strong enough!")
print("Xixen: Since then, we decided on making a hash function, it's easy to design hash functions, right?")
print("Randolf: If you manage to find a string that has an arbitrary value that we choose, we will reward you "
"again and just give up")
print(f"Xixen: We are very confident that this time you will not succeed! You'll also have to prove that the "
f"exploit is consistent so you will have to do it {ACTION_COUNT} times.\nAlso, you can't try more than "
f"{STEP_COUNT} strings to be hashed for each exploit instance. Good luck!\n")
sys.stdout.flush()
def invalid_input():
print("Invalid input, closing the connection\n\n")
sys.stdout.flush()
exit(0)
def step_prompt(step):
print(f"Step #{step} of {ACTION_COUNT}\n")
sys.stdout.flush()
def get_hexadecimal_input(input_name):
print(f"Give me an integer in hexadecimal format\n{input_name} = ", end="")
sys.stdout.flush()
user_input = input()
is_valid = functools.reduce(lambda x, y: x and y, map(lambda x: x in string.hexdigits, user_input))
if not is_valid:
invalid_input()
return binascii.unhexlify(user_input)
def challenge_prompt(hash_result):
print(f"Please find a string that when encrypted has the following hash:\n\nhash(string) = {binascii.hexlify(hash_result)}\n")
def main():
if not proof_of_work(POW_NIBBLES):
exit(0)
intro_prompt()
for i in range(ACTION_COUNT):
key = os.urandom(KEY_SIZE // 8)
salt = os.urandom(BLOCK_SIZE // 8)
hash_result = os.urandom(BLOCK_SIZE // 8)
steps_left = STEP_COUNT
step_prompt(i + 1)
challenge_prompt(hash_result)
while steps_left > 0:
print(f"You have {steps_left} steps left!")
user_input = get_hexadecimal_input("string")
if hash_func(salt, user_input, key) == hash_result:
print("Ok you did it, but that was just a lucky guess")
sys.stdout.flush()
break
else:
print("Nope, that was not correct, sorry!")
sys.stdout.flush()
steps_left -= 1
if steps_left == 0:
print("Sorry, you are out of moves! Seems like we were right, the hash function is perfect!")
sys.stdout.flush()
exit(0)
print(f"Fine, you have bested us! Here's your flag: {FLAG}\n")
sys.stdout.flush()
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/X-MAS/2021/crypto/Santas_Secret_Encoding_Machine/proof_of_work.py | ctfs/X-MAS/2021/crypto/Santas_Secret_Encoding_Machine/proof_of_work.py | import os
import string
import sys
import functools
from binascii import unhexlify
from hashlib import sha256
def proof_of_work(nibble_count: int) -> bool:
rand_str = os.urandom(10)
rand_hash = sha256(rand_str).hexdigest()
print(f"Provide a hex string X such that sha256(unhexlify(X))[-{nibble_count}:] = {rand_hash[-nibble_count:]}\n")
sys.stdout.flush()
user_input = input()
is_hex = functools.reduce(lambda x, y: x and y, map(lambda x: x in string.hexdigits, user_input))
if is_hex and sha256(unhexlify(user_input)).hexdigest()[-nibble_count:] == rand_hash[-nibble_count:]:
print("Good, you can continue!")
sys.stdout.flush()
return True
else:
print("Oops, your string didn\'t respect the criterion.")
sys.stdout.flush()
return False
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/X-MAS/2021/crypto/Santas_Secret_Encoding_Machine/constants.py | ctfs/X-MAS/2021/crypto/Santas_Secret_Encoding_Machine/constants.py | POW_NIBBLES = 5
NO_PRIMES = 8
BIT_SIZE = 16
ACTION_CNT = 16
MAX_ACTIONS = 10000
FLAG = "[REDACTED]"
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/X-MAS/2021/crypto/Santas_Secret_Encoding_Machine/challenge.py | ctfs/X-MAS/2021/crypto/Santas_Secret_Encoding_Machine/challenge.py | import os
from random import SystemRandom
from Crypto.Util.number import isPrime, long_to_bytes
from Crypto.Cipher import AES
from math import ceil
def pad(arr: bytes, size: int) -> bytes:
arr += (16 * size - len(arr)) * b'\x00'
return arr
class challenge:
def __init__(self, bit_cnt: int, no_primes: int):
self.bit_cnt = bit_cnt
self.no_primes = no_primes
self.aes_key = os.urandom(16)
self.aes_iv = os.urandom(16)
self.random = SystemRandom()
self.block_cnt = int(ceil(self.bit_cnt * self.no_primes / 128))
def _get_prime_number(self) -> int:
prime_number = self.random.randrange(2 ** (self.bit_cnt - 1) + 1, 2 ** self.bit_cnt - 1)
while not isPrime(prime_number):
prime_number = self.random.randrange(2 ** (self.bit_cnt - 1) + 1, 2 ** self.bit_cnt - 1)
return prime_number
def _get_modulo(self) -> int:
n = 1
used_primes = {2}
for i in range(self.no_primes):
new_prime = self._get_prime_number()
while new_prime in used_primes:
new_prime = self._get_prime_number()
used_primes.add(new_prime)
n *= new_prime
while not isPrime(2 * n + 1):
n = 1
used_primes = {2}
for i in range(self.no_primes):
new_prime = self._get_prime_number()
while new_prime in used_primes:
new_prime = self._get_prime_number()
used_primes.add(new_prime)
n *= new_prime
return 2 * n + 1
def _get_random_secret_pair(self, n) -> (int, bytes):
aes_cipher = AES.new(self.aes_key, AES.MODE_CBC, self.aes_iv)
k = self.random.randrange(0, n - 1)
enc_k = aes_cipher.encrypt(pad(long_to_bytes(k), self.block_cnt))
return k, enc_k
def get_challenge(self) -> (int, int, bytes):
print("Loading...\n")
n = self._get_modulo()
k, enc_k = self._get_random_secret_pair(n)
return n, k, enc_k
def encrypt(self, n: int, base: int, exponent: int) -> bytes:
x = pow(base, exponent, n)
aes_cipher = AES.new(self.aes_key, AES.MODE_CBC, self.aes_iv)
return aes_cipher.encrypt(pad(long_to_bytes(x), self.block_cnt))
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/X-MAS/2021/crypto/Santas_Secret_Encoding_Machine/server.py | ctfs/X-MAS/2021/crypto/Santas_Secret_Encoding_Machine/server.py | import sys
import functools
import string
import binascii
from constants import *
from proof_of_work import proof_of_work
from challenge import challenge
def intro_prompt(action_count: int):
print(f"Hello there fellow mathematician, as you well know, you have to break this encoding machine!\nAnd not only once, but {action_count} times! Good luck\n")
sys.stdout.flush()
def invalid_input():
print("Invalid input, closing the connection\n\n")
sys.stdout.flush()
exit(0)
def menu():
print("1. Encode x^d\n2. Encode k^d\n3. Guess k\n4. Close the connection\n")
sys.stdout.flush()
user_input = input()
if not user_input in ["1", "2", "3", "4"]:
invalid_input()
return user_input
def step_prompt(action_count: int, curr_step: int, n: int, enc_k: bytes):
print(f"Step #{curr_step} of {action_count}, you have at most {MAX_ACTIONS} queries at your disposal!\nn = {n}\nEnc(k) = {binascii.hexlify(enc_k)}\n")
sys.stdout.flush()
def get_decimal_input(input_name: str) -> int:
print(f"Give me an integer in decimal form\n{input_name} = ", end="")
sys.stdout.flush()
user_input = input()
is_valid = functools.reduce(lambda x, y: x and y, map(lambda x: x in string.digits, user_input))
if not is_valid:
invalid_input()
return int(user_input)
def main():
if not proof_of_work(POW_NIBBLES):
exit(0)
intro_prompt(ACTION_CNT)
for i in range(ACTION_CNT):
chall = challenge(BIT_SIZE, NO_PRIMES)
n, k, enc_k = chall.get_challenge()
step_prompt(ACTION_CNT, i + 1, n, enc_k)
step_solved = False
steps_left = MAX_ACTIONS
while not step_solved and steps_left > 0:
steps_left -= 1
user_input = menu()
if user_input == "1":
base = get_decimal_input("x")
exponent = get_decimal_input("d")
print(f"Enc(x^d) = {binascii.hexlify(chall.encrypt(n, base, exponent))}\n")
sys.stdout.flush()
elif user_input == "2":
exponent = get_decimal_input("d")
print(f"Enc(x^d) = {binascii.hexlify(chall.encrypt(n, k, exponent))}\n")
sys.stdout.flush()
elif user_input == "3":
candidate_k = get_decimal_input("k")
if candidate_k == k:
step_solved = True
if i == ACTION_CNT - 1:
print("Well done, I'll bring you a present, wait here!\n")
sys.stdout.flush()
else:
print("Good, you can get to the next step!\n")
sys.stdout.flush()
else:
print("Nope, that's not it! Such a shame, you seemed worthy...\n")
sys.stdout.flush()
exit(0)
else:
print("It was good to hear from you, goodbye!\n")
sys.stdout.flush()
exit(0)
if step_solved == False:
print("Well well, no more actions for you...")
sys.stdout.flush()
exit(0)
print(f"Here! I found your flag: {FLAG}\n")
sys.stdout.flush()
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/X-MAS/2021/web/imagehub/bot/bot.py | ctfs/X-MAS/2021/web/imagehub/bot/bot.py | from selenium import webdriver
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from pyvirtualdisplay import Display
import os
import time
import requests
ADMIN_COOKIE = os.environ.get('FLAG')
display = Display (visible=0, size= (320, 240))
display.start()
options = Options ()
options.add_argument ("--headless")
options.add_argument ("--no-sandbox")
driver = webdriver.Chrome(options=options)
driver.set_window_size(320, 240)
driver.set_page_load_timeout(7)
driver.get('http://localhost:2000/')
driver.add_cookie({'name': 'admin_cookie', 'value': ADMIN_COOKIE})
while True:
try:
driver.get('http://localhost:2000/list')
button = driver.find_elements(By.CLASS_NAME, "image-link")[0]
image_url = button.get_attribute('href')
button.click()
time.sleep(5)
except:
pass
driver.quit()
display.stop() | python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/X-MAS/2021/web/imagehub/files/main.py | ctfs/X-MAS/2021/web/imagehub/files/main.py | #!/usr/bin/env python3
from flask import Flask, render_template, request, redirect
from flask_hcaptcha import hCaptcha
import uuid
import os
ADMIN_COOKIE = os.environ.get('FLAG', 'X-MAS{test}')
app = Flask (__name__)
images = [{'url': img_url, 'desc': 'meme'} for img_url in open("images.txt", "r").read().strip().split("\n")]
pending_images = {} # id: image obj
@app.route ('/', methods = ['GET'])
def index():
return render_template ("index.html", images=images)
@app.route ('/submit', methods = ['GET', 'POST'])
def submit():
if request.method == 'GET':
return render_template ("submit.html")
image_url = request.form.get('url')
image_desc = request.form.get('desc')
if not isinstance(image_url, str) or not isinstance(image_desc, str) or len(image_url) > 256 or len(image_url) < 8:
return 'NOPE'
if len(image_desc) > 164 or len(image_desc) < 4:
return 'NOPE'
blacklist = ['src', '"', "'", '+', '\\', '[', ']', '-']
for blacklist_thing in blacklist:
if blacklist_thing in image_desc.lower():
return 'NOPE'
if 'script' in image_desc or 'nonce' in image_desc:
return 'NOPE (according to our latest security audit)'
image_id = str(uuid.uuid4())
image_obj = { 'url': image_url, 'desc': image_desc }
pending_images[image_id] = image_obj
return render_template ("submit.html", message=f"Image {image_id} submitted successfully.")
@app.route ('/list', methods = ['GET'])
def list():
if request.cookies.get('admin_cookie', False) != ADMIN_COOKIE:
return 'NOPE'
return render_template ("list.html", image_ids=[_ for _ in pending_images.keys()])
@app.route ('/api/unapproved/<image_id>', methods = ['GET'])
def unapprovedImage(image_id):
return pending_images.pop(image_id)
@app.route ('/image/<image_id>', methods = ['GET', 'POST', 'DELETE'])
def image(image_id):
if request.method == 'GET':
if request.cookies.get('admin_cookie', False) != ADMIN_COOKIE or pending_images.get(image_id, False) == False:
return 'NOPE'
return render_template ("image_review.html", image_id=image_id, title=pending_images[image_id]['desc'])
action = request.form.get('action')
if not isinstance(action, str) or action not in ['APPROVE', 'REJECT']:
return 'NOPE'
if action == "REJECT":
pending_images.pop(image_id)
return redirect("/list", code=302)
if __name__ == '__main__':
app.run (host = '127.0.0.1', port = 2000)
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/X-MAS/2021/web/quotehub/bot/bot.py | ctfs/X-MAS/2021/web/quotehub/bot/bot.py | from selenium import webdriver
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from pyvirtualdisplay import Display
import os
import time
import requests
ADMIN_COOKIE = os.environ.get('ADMIN_COOKIE')
# print("Declare display", flush=True)
display = Display (visible=False, size= (320, 240))
# print("Start display", flush=True)
display.start()
# print("Options", flush=True)
options = Options ()
options.add_argument ("--headless")
options.add_argument ("--no-sandbox")
options.add_argument('--disable-dev-shm-usage')
# print("webdriver.Chrome", flush=True)
driver = webdriver.Chrome(options=options)
# print("set_window_size", flush=True)
driver.set_window_size(320, 240)
# print("set_page_load_timeout", flush=True)
driver.set_page_load_timeout(5)
# print("get /", flush=True)
driver.get('http://127.0.0.1:2000/')
# print("add cookie", flush=True)
driver.add_cookie({'name': 'admin_cookie', 'value': ADMIN_COOKIE})
while True:
try:
# print("get /quote/latest", flush=True)
driver.get('http://127.0.0.1:2000/quote/latest')
# print("reject button - press", flush=True)
rejectBtn = WebDriverWait(driver, 5).until(
EC.presence_of_element_located((By.CLASS_NAME, "red"))
)
rejectBtn.click()
# print("sleep 3", flush=True)
time.sleep(3)
except:
pass
# print("quit", flush=True)
driver.quit()
# print("Stop display", flush=True)
display.stop() | python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/X-MAS/2021/web/quotehub/files/main.py | ctfs/X-MAS/2021/web/quotehub/files/main.py | #!/usr/bin/env python3
from flask import Flask, render_template, request, redirect
import uuid
import os
FLAG = os.environ.get('FLAG', 'X-MAS{test}')
ADMIN_COOKIE = os.environ.get('ADMIN_COOKIE')
SECRET_TOKEN = os.urandom(64).hex()
app = Flask (__name__)
quotes = [
{'text': 'Man cannot live by bread alone; he must have <b>peanut butter</b>.', 'author': 'James A. Garfield'},
{'text': 'He who can does - he who cannot, teaches.', 'author': 'George Bernard Shaw'},
{'text': "I'd like to live like a poor man - only with lots of <i>money</i>.", 'author': 'Pablo Picasso'},
{'text': 'So next I went to Russia three times, in late 2001 and 2002, to see if I could negotiate the purchase of two <strong>ICBMs</strong>', 'author': 'Elon Musk'}
]
pending_quotes = []
@app.route ('/', methods = ['GET'])
def index():
return render_template ("index.html", quotes=quotes)
@app.route ('/submit', methods = ['GET', 'POST'])
def submit():
if request.method == 'GET':
return render_template ("submit.html")
quote = request.form.get('quote')
author = request.form.get('author')
if not isinstance(quote, str) or not isinstance(author, str) or len(quote) > 256 or len(quote) < 8 or len(author) > 32 or len(author) < 4:
return 'NOPE'
quote_obj = {
'text': quote,
'author': author
}
pending_quotes.append(quote_obj)
return render_template ("submit.html", message=f"Quote submitted successfully.")
@app.route ('/quote/latest', methods = ['GET', 'POST'])
def quote():
global pending_quotes
if request.method == 'GET':
if request.cookies.get('admin_cookie', False) != ADMIN_COOKIE or len(pending_quotes) == 0:
return 'NOPE'
q = pending_quotes[0]
pending_quotes = pending_quotes[1:]
print("Admin viewing quote: ", q)
return render_template ("quote_review.html", quote=q, SECRET_TOKEN=SECRET_TOKEN)
action = request.form.get('action')
secret = request.form.get('secret')
if not isinstance(action, str) or action not in ['APPROVE', 'REJECT'] or secret != SECRET_TOKEN:
return 'NOPE'
if action == "REJECT":
return redirect("/list", code=302)
return "You did it! Here's your reward: " + FLAG
if __name__ == '__main__':
app.run (host = '127.0.0.1', port = 2000)
| 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.