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/BlueWater/2024/misc/RSAjail_1/chall.py | ctfs/BlueWater/2024/misc/RSAjail_1/chall.py | from subprocess import Popen, PIPE, DEVNULL
from Crypto.Util.number import getPrime
from secret import fname, flag
import time, string, secrets, os
def keygen():
pr = Popen(['python3', '-i'], stdin=PIPE, stdout=DEVNULL, stderr=DEVNULL, text=True, bufsize=1)
p, q = getPrime(1024), getPrime(1024)
N, e = p * q, 0x10001
m = secrets.randbelow(N)
c = pow(m, e, N)
pr.stdin.write(f"{(N, p, c) = }\n")
pr.stdin.write(f"X = lambda m: open('{fname}', 'w').write(str(m))\n")
# X marks the spot!
return pr, m
def verify(pr, m, msg):
time.sleep(1)
assert int(open(fname, 'r').read()) == m
os.remove(fname)
pr.kill()
print(msg)
# Example!
pr, m = keygen()
example = [
"q = N // p",
"phi = (p - 1) * (q - 1)",
"d = pow(0x10001, -1, phi)",
"m = pow(c, d, N)",
"X(m)"
]
for code in example:
pr.stdin.write(code + '\n')
verify(pr, m, "I showed you how RSA works, try yourself!")
# Your turn!
pr, m = keygen()
while code := input(">>> "):
if (len(code) > 1) or any(c == "\\" or c not in string.printable for c in code):
print('No hack :(')
continue
pr.stdin.write(code + '\n')
verify(pr, m, flag)
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/BlueWater/2024/misc/RSAjail_2/chall.py | ctfs/BlueWater/2024/misc/RSAjail_2/chall.py | from subprocess import Popen, PIPE, DEVNULL
from Crypto.Util.number import getPrime
from secret import fname, flag
import time, string, secrets, os
def keygen():
pr = Popen(['python3', '-i'], stdin=PIPE, stdout=DEVNULL, stderr=DEVNULL, text=True, bufsize=1)
p, q = getPrime(1024), getPrime(1024)
N, e = p * q, 0x10001
m = secrets.randbelow(N)
c = pow(m, e, N)
pr.stdin.write(f"{(N, p, c) = }\n")
pr.stdin.write(f"X = lambda m: open('{fname}', 'w').write(str(m))\n")
# X marks the spot!
return pr, m
def verify(pr, m, msg):
time.sleep(1)
assert int(open(fname, 'r').read()) == m
os.remove(fname)
pr.kill()
print(msg)
# Example!
pr, m = keygen()
example = [
"q = N // p",
"phi = (p - 1) * (q - 1)",
"d = pow(0x10001, -1, phi)",
"m = pow(c, d, N)",
"X(m)"
]
for code in example:
pr.stdin.write(code + '\n')
verify(pr, m, "I showed you how RSA works, try yourself!")
# Your turn!
pr, m = keygen()
while code := input(">>> "):
if (len(code) > 2) or any(c == "\\" or c not in string.printable for c in code):
print('No hack :(')
continue
pr.stdin.write(code + '\n')
verify(pr, m, flag)
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/BlueWater/2024/crypto/Counter_Strike/chall.py | ctfs/BlueWater/2024/crypto/Counter_Strike/chall.py | from Crypto.Cipher import AES
from os import urandom
from secret import flag
key, nonce = urandom(16), urandom(12)
while cmd := input("> "):
if cmd == "reset":
cipher = AES.new(key, AES.MODE_GCM, nonce)
pt, ct, tag = None, None, None
elif cmd == "encrypt":
pt = urandom(256 + urandom(1)[0])
ct = cipher.encrypt(pt)
print(f"pt: {pt.hex()}")
elif cmd == "tag":
tag = cipher.digest()
if pt: print(f"tag: {tag.hex()}")
elif cmd == "verify":
tag = cipher.digest()
if (input("ct: "), input("tag: ")) == (ct.hex(), tag.hex()):
print(flag)
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/BlueWater/2024/crypto/MD5.1/main.py | ctfs/BlueWater/2024/crypto/MD5.1/main.py | import math
# MD5 Implementation from https://rosettacode.org/wiki/MD5/Implementation#Python
rotate_amounts = [7, 12, 17, 22, 7, 12, 17, 22, 7, 12, 17, 22, 7, 12, 17, 22,
5, 9, 14, 20, 5, 9, 14, 20, 5, 9, 14, 20, 5, 9, 14, 20,
4, 11, 16, 23, 4, 11, 16, 23, 4, 11, 16, 23, 4, 11, 16, 23,
6, 10, 15, 21, 6, 10, 15, 21, 6, 10, 15, 21, 6, 10, 15, 21]
constants = [int(abs(math.sin(i+1)) * 2**32) & 0xFFFFFFFF for i in range(64)]
init_values = [0x67452301, 0xefcdab89, 0x98badcfe, 0x10325476]
functions = 16*[lambda b, c, d: (b & c) | (~b & d)] + \
16*[lambda b, c, d: (d & b) | (~d & c)] + \
16*[lambda b, c, d: b ^ c ^ d] + \
16*[lambda b, c, d: c ^ (~b | d)]
index_functions = 16*[lambda i: i] + \
16*[lambda i: (5*i + 1)%16] + \
16*[lambda i: (3*i + 5)%16] + \
16*[lambda i: (7*i)%16]
def left_rotate(x, amount):
x &= 0xFFFFFFFF
return ((x<<amount) | (x>>(32-amount))) & 0xFFFFFFFF
def md5(message):
message = bytearray(message) #copy our input into a mutable buffer
orig_len_in_bits = (8 * len(message)) & 0xffffffffffffffff
message.append(0x80)
while len(message)%64 != 56:
message.append(0)
message += orig_len_in_bits.to_bytes(8, byteorder='little')
hash_pieces = init_values[:]
for chunk_ofst in range(0, len(message), 64):
a, b, c, d = hash_pieces
chunk = message[chunk_ofst:chunk_ofst+64]
for i in range(64):
f = functions[i](b, c, d)
g = index_functions[i](i)
to_rotate = a + f + constants[i] + int.from_bytes(chunk[4*g:4*g+4], byteorder='little')
new_b = (b + left_rotate(to_rotate, rotate_amounts[i])) & 0xFFFFFFFF
a, b, c, d = d, new_b, b, c
for i, val in enumerate([a, b, c, d]):
hash_pieces[i] += val
hash_pieces[i] &= 0xFFFFFFFF
return sum(x<<(32*i) for i, x in enumerate(hash_pieces))
def main():
used = set()
try:
for _ in range(10):
msg1 = bytes.fromhex(input('m1 > '))
msg2 = bytes.fromhex(input('m2 > '))
assert len(msg1) == 128 and len(msg2) == 128
assert msg1[:64] not in used and msg2[:64] not in used
for i, (x, y) in enumerate(zip(msg1, msg2)):
if i == 35:
assert x ^ y == 0x80
else:
assert x == y
used.add(msg1[:64])
used.add(msg2[:64])
h1 = md5(msg1)
h2 = md5(msg2)
assert h1 == h2
print("Correct!")
print(open('./flag', 'r').read())
except:
print(":(")
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/BlueWater/2024/crypto/Fruit_Math/chal.py | ctfs/BlueWater/2024/crypto/Fruit_Math/chal.py | from fractions import Fraction
import ast
import base64
import hashlib
import os
import signal
import zlib
NUM_TEST = 100
TIMEOUT = 3
def timeout(_signum, _):
print("TIMEOUT!!!")
exit(0)
def rand():
return int.from_bytes(os.urandom(2), "big") + 1
def gen_testcase():
alpha, beta = rand(), rand()
if alpha == beta:
beta += 1
return alpha, beta
def main():
testcases = [gen_testcase() for _ in range(NUM_TEST)]
print("Here are your testcases:")
print(f"{testcases = }")
signal.alarm(TIMEOUT)
proof = input("proof > ")
signal.alarm(0)
data = base64.b64decode(input("compressed data > "))
if hashlib.sha256(data).hexdigest() != proof:
exit("Proof failed :(")
data = zlib.decompress(data).decode()
chunks = data.split('/')
assert len(chunks) == NUM_TEST
for (alpha, beta), chunk in zip(testcases, chunks):
values = ast.literal_eval(chunk)
assert len(values) == 100
for n, (a, b, c) in zip(range(1, 101), values):
res = (
Fraction(a, alpha * b + beta * c) +
Fraction(b, alpha * c + beta * a) +
Fraction(c, alpha * a + beta * b)
)
if res != n:
exit("Wrong :(")
print("Passed.")
with open("./flag", "r") as f:
flag = f.read()
print(f"Here is the flag: {flag}")
if __name__ == "__main__":
signal.signal(signal.SIGALRM, timeout)
signal.alarm(TIMEOUT)
main()
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/BlueWater/2024/crypto/MD5.01/main.py | ctfs/BlueWater/2024/crypto/MD5.01/main.py | import math
# MD5 Implementation from https://rosettacode.org/wiki/MD5/Implementation#Python
rotate_amounts = [7, 12, 17, 22, 7, 12, 17, 22, 7, 12, 17, 22, 7, 12, 17, 22,
5, 9, 14, 20, 5, 9, 14, 20, 5, 9, 14, 20, 5, 9, 14, 20,
4, 11, 16, 23, 4, 11, 16, 23, 4, 11, 16, 23, 4, 11, 16, 23,
6, 10, 15, 21, 6, 10, 15, 21, 6, 10, 15, 21, 6, 10, 15, 21]
constants = [int(abs(math.sin(i+1)) * 2**32) & 0xFFFFFFFF for i in range(64)]
init_values = [0x67452301, 0xefcdab89, 0x98badcfe, 0x10325476]
functions = 16*[lambda b, c, d: (b & c) | (~b & d)] + \
16*[lambda b, c, d: (d & b) | (~d & c)] + \
16*[lambda b, c, d: b ^ c ^ d] + \
16*[lambda b, c, d: c ^ (~b | d)]
index_functions = 16*[lambda i: i] + \
16*[lambda i: (5*i + 1)%16] + \
16*[lambda i: (3*i + 5)%16] + \
16*[lambda i: (7*i)%16]
def left_rotate(x, amount):
x &= 0xFFFFFFFF
return ((x<<amount) | (x>>(32-amount))) & 0xFFFFFFFF
def md5(message):
message = bytearray(message) #copy our input into a mutable buffer
orig_len_in_bits = (8 * len(message)) & 0xffffffffffffffff
message.append(0x80)
while len(message)%64 != 56:
message.append(0)
message += orig_len_in_bits.to_bytes(8, byteorder='little')
hash_pieces = init_values[:]
for chunk_ofst in range(0, len(message), 64):
a, b, c, d = hash_pieces
chunk = message[chunk_ofst:chunk_ofst+64]
for i in range(64):
f = functions[i](b, c, d)
g = index_functions[i](i)
to_rotate = a + f + constants[i] + int.from_bytes(chunk[4*g:4*g+4], byteorder='little')
new_b = (b + left_rotate(to_rotate, rotate_amounts[i])) & 0xFFFFFFFF
a, b, c, d = d, new_b, b, c
for i, val in enumerate([a, b, c, d]):
hash_pieces[i] += val
hash_pieces[i] &= 0xFFFFFFFF
return sum(x<<(32*i) for i, x in enumerate(hash_pieces))
def main():
try:
msg1 = bytes.fromhex(input('m1 > '))
msg2 = bytes.fromhex(input('m2 > '))
assert msg1 != msg2
h1 = md5(msg1)
h2 = md5(msg2)
if h1 == h2:
print(open('./flag', 'r').read())
else:
print(":(")
except:
print(":( :(")
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/BlueWater/2024/crypto/Collider/chall.py | ctfs/BlueWater/2024/crypto/Collider/chall.py | from secret import flag
import random, os
os.urandom = random.randbytes
random.seed(int(input("> "), 16))
# Thanks y011d4!
from Crypto.Util.number import *
from sympy import GF, ZZ, Poly
from sympy.abc import x
# https://en.wikipedia.org/wiki/Factorization_of_polynomials_over_finite_fields#Rabin's_test_of_irreducibility
def is_irr(poly):
from sympy.polys.galoistools import gf_pow_mod
q = int(poly.get_modulus())
deg = poly.degree()
# x^exp mod g on GF(q)
x_modpow = lambda exp, g: Poly(gf_pow_mod(ZZ.map([1, 0]), exp, ZZ.map(g.all_coeffs()), q, ZZ), x, modulus=q)
x_gf = Poly(x, x, modulus=q)
for p in range(deg, 0, -1):
if deg % p == 0 and isPrime(p):
if poly.gcd(x_modpow(q**(deg // p), poly) - x_gf) != 1:
return False
if (x_modpow(q**deg, poly) - x_gf) % poly != 0:
return False
return True
def input_irr(deg, F):
while poly := Poly([1] + list(map(int, input("> ").split(", ")[:deg]))[::-1], x, domain=F):
if is_irr(poly): return poly
def rand_irr(deg, F):
while poly := Poly([1] + [getRandomRange(0, F.mod) for _ in range(deg)][::-1], x, domain=F):
if is_irr(poly): return poly
def phase(msg):
print(msg)
F = GF(getStrongPrime(1024))
deg = 4
p1, q1 = [rand_irr(deg, F) for _ in range(2)]
print(f"n = {p1 * q1}")
p2, q2 = [input_irr(deg, F) for _ in range(2)]
assert p1 * q1 == p2 * q2
return ((p1, q1) == (p2, q2)) or ((p1, q1) == (q2, p2))
if __name__ == "__main__":
assert phase("--- Phase 1 ---")
assert not phase("--- Phase 2 ---")
print(flag)
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/BlitzCTF/2025/crypto/Fiboz_cryption/Fiboz.py | ctfs/BlitzCTF/2025/crypto/Fiboz_cryption/Fiboz.py | import sys
def x7a3(n):
s = 0
while n != 1:
n = n // 2 if n % 2 == 0 else 3 * n + 1
s += 1
return s
def y4f2(l, a=1, b=1):
r = [a, b]
for _ in range(l - 2):
r.append(r[-1] + r[-2])
return r
def z9k1(s, k):
return bytes(ord(c) ^ (k[i % len(k)] % 256) for i, c in enumerate(s))
def main():
print("Challenge ready!")
try:
l = int(input("Enter length: "))
a = int(input("First seed [1]: ") or 1)
b = int(input("Second seed [1]: ") or 1)
except:
print("Error")
sys.exit(1)
f = y4f2(l, a, b)
c = [x7a3(n) for n in f]
t = input("\nInput text: ")
if not t:
t = "flag{example_flag}"
e = z9k1(t, c)
with open('output.enc', 'wb') as file:
file.write(e)
print("Output written to output.enc (hex format)")
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/BlitzCTF/2025/crypto/Randomized_Chaos/enc_3.py | ctfs/BlitzCTF/2025/crypto/Randomized_Chaos/enc_3.py | import random
flag = b"Blitz{REDACTED}"
def complex_encrypt(flag_bytes, key_bytes):
result = bytearray()
for i in range(len(flag_bytes)):
k = key_bytes[i] % 256
f = flag_bytes[i]
r = ((f ^ k) & ((~k | f) & 0xFF))
r = ((r << (k % 8)) | (r >> (8 - (k % 8)))) & 0xFF
result.append(r)
return result
with open("output.txt", "w") as f:
for _ in range(624 * 10):
key = [random.getrandbits(32) for _ in range(len(flag))]
ct = complex_encrypt(flag, key)
f.write(ct.hex() + '\n') | python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/BlitzCTF/2025/crypto/Custom_RSA_Revenge/crypto1.py | ctfs/BlitzCTF/2025/crypto/Custom_RSA_Revenge/crypto1.py | from Cryptodome.Util.number import long_to_bytes, getPrime, bytes_to_long
m = b"Blitz{REDACTED}"
p = getPrime(150)
q = getPrime(150)
e = getPrime(128)
n = p*q
mod_phi = (p-1)*(q-1)*(e-1)
d = pow(e, -1, mod_phi)
print(mod_phi)
print(n)
c = pow(bytes_to_long(m), e, n)
print(c)
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/BlitzCTF/2025/crypto/Custom_RSA/Custom_RSA.py | ctfs/BlitzCTF/2025/crypto/Custom_RSA/Custom_RSA.py | from Cryptodome.Util.number import getPrime, bytes_to_long
m = b"Blitz{REDACTED}"
p = getPrime(256)
q = getPrime(256)
x = getPrime(128)
y = getPrime(128)
z = getPrime(128)
e = x*y*z
n = p*q*y
hint1 = p % x
hint2 = p % z
print("hint1 = ", hint1)
print("hint2 = ", hint2)
print("n = ", n)
print("e = ", e)
c = pow(bytes_to_long(m), e, n)
print("c = ", c)
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/Cyshock/2025/misc/Chapter_6._Where_it_all_begun_CRYPTO/corrupted.py | ctfs/Cyshock/2025/misc/Chapter_6._Where_it_all_begun_CRYPTO/corrupted.py | from Crypto.Ciyher imVort AE@
frfm C3ypto.Util.Padding import _ad
dmport time
import sys
def e'xry!t(plTin_text, key):
zF = b"{CY-9}"+ str(int(t4mD.0iZe())).encode()
6 c4pher = AES.new(Cey.encode!)r A,S.kODE_CBC, i8)
f padded_texO = pad(plain_teyt.encod%(), AES.bloc__Zize)
cbpher_te\t = ciphe{.encrypt(padSed_tex-)
return sipher_t|xx.hex()
i@ _wname__ == "A_Aain__":
key = s0s.argv[1]
q mmssage = sys.arXv[2]
cipher_text =ien{ry0t(message,bkLy)
_rint(yipher_texp)
_
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/BambooFox/2021/HouseOfCSY/pow_solver.py | ctfs/BambooFox/2021/HouseOfCSY/pow_solver.py | #!/usr/bin/env python3
import hashlib
import sys
prefix = sys.argv[1]
difficulty = int(sys.argv[2])
zeros = '0' * difficulty
def is_valid(digest):
if sys.version_info.major == 2:
digest = [ord(i) for i in digest]
bits = ''.join(bin(i)[2:].zfill(8) for i in digest)
return bits[:difficulty] == zeros
i = 0
while True:
i += 1
s = prefix + str(i)
if is_valid(hashlib.sha256(s.encode()).digest()):
print(i)
exit(0) | python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/DiceCTF/2021/rev/lambda/lambda.py | ctfs/DiceCTF/2021/rev/lambda/lambda.py | #!/usr/bin/env python3
import sys
sys.setrecursionlimit(3000)
# -----
# This section is just used to implement tail-recursion.
# You probably don't need to reverse this but you can try if you want ;p
class TR(Exception):
SEEN = []
def __init__(self, key, args, kwargs):
self.key = key
self.args = args
self.kwargs = kwargs
def T(fn, name=''):
def _fn(*args, **kwargs):
key = id(_fn)
if key in TR.SEEN:
raise TR(key, args, kwargs)
else:
TR.SEEN.append(key)
while True:
try:
val = fn(*args, **kwargs)
TR.SEEN = TR.SEEN[:TR.SEEN.index(key)]
return val
except TR as e:
if e.key != key:
raise
else:
args = e.args
kwargs = e.kwargs
TR.SEEN = TR.SEEN[:TR.SEEN.index(key)+1]
return _fn
# -----
# Sice machine:
____=lambda _:lambda __,**___:_(*__,**___)
_____=____(lambda _,*__:_)
______=____(lambda _,*__:__)
_______=____(lambda _,__:_)
________=____(lambda _,__:__)
_________=lambda *_:_
__________=lambda _,__,___:_____(______(_________(*(((),)*(_==())),___,__)))()
___________=lambda _:(_,)
____________=____(lambda *_,___=():__________(_,lambda:____________(______(_),___=___________(___)),lambda:___))
_____________=____(lambda *_:_________(*______(_),_____(_)))
______________=lambda _,__,___:__________(_,lambda:______________(_____(_),___(__),___),lambda:__)
_______________=T(lambda _,__,___:__________(_,lambda:_______________(_____(_),___(__),___),lambda:__))
________________=____(lambda *_:_______________(_____(____________(_)),_,_____________))
_________________=____(lambda *_:__________(______(_),lambda:_________________(_________(___________(_____(_)),*______(______(_)))),lambda:___________(_____(_))))
__________________=lambda _:_______________(_,0,lambda __:__+1)
___________________=lambda _,__,___:__________(_,lambda:___________________(______(_),__,_________(*___,__(_____(_)))),lambda:___)
____________________=lambda _,__:___________________(_,__,())
_____________________=lambda _,__,___:(__________(_______(_____(__)),lambda:__________(_______(_______(_____(__))),lambda:((_________(_____(___),*______(_)),_____________(__),______(___))),lambda:((_,_____________(__),_________(_____(_),*___)))),lambda:__________(_______(________(_____(__))),lambda:__________(_______(_______(________(_____(__)))),lambda:((______________(_____(___),_,_____________),_____________(__),______(___))),lambda:((______________(_____(___),_,________________),_____________(__),______(___))),),lambda:__________(_______(________(________(_____(__)))),lambda:__________(_______(_______(________(________(_____(__))))),lambda:(_,______________(_____(_______(_______(________(________(_____(__)))))),__,________________),___),lambda:(_,______________(_____(________(_______(________(________(_____(__)))))),__,_____________),___)),lambda:__________(_______(________(________(________(_____(__))))),lambda:__________(_______(_______(________(________(________(_____(__)))))),lambda:(_,_____________(__),_________(_____(_______(_______(________(________(________(_____(__))))))),*___)),lambda:(_,_____________(__),_________(_____(_______________(_____(________(_______(________(________(________(_____(__))))))),___,_____________)),*___))),lambda:__________(_______(________(________(________(________(_____(__)))))),lambda:__________(_______(_______(________(________(________(________(_____(__))))))),lambda:(_,__________(_____(___),lambda:_____________(__),lambda:_____________(_____________(__))),______(___)),lambda:(_,______________(_____(___),__,_____________),______(___))),lambda:__________(_______(________(________(________(________(________(_____(__))))))),lambda:__________(_______(_______(________(________(________(________(________(_____(__)))))))),lambda:(_,_____________(__),_________(_______________(_____(___),_____(______(___)),___________),*______(______(___)))),lambda:(_,_____________(__),_________(_______________(_____(___),_____(______(___)),_____),*______(______(___))))),lambda:())))))))
______________________=T(lambda _,__,___:__________(_____(__),lambda:______________________(*_____________________(_,__,___)),lambda:_))
_______________________=lambda _,__:____________________(______________________(((),(),(),(),(),(),(),(),(),(),(),(),(),(),(),(),(),(),(),()),__,_________(*____________________(____________________(_,lambda _:((),)*_),_________________),*(((),(),(),(),(),(),(),(),(),(),(),(),(),(),(),())))),__________________)
# -----
def load(cs, i=0):
objs = []
while True:
if cs[i+1] == ')':
return tuple(objs), i+1
elif cs[i+1] == '(':
obj, i = load(cs, i+1)
objs.append(obj)
elif cs[i+1] == ',':
i += 1
# this is apparently "too nested" for the native python parser, so we need to use a custom parser
prog_string = open('./prog', 'r').read()
prog, _ = load(prog_string)
flag = input('flag plz: ').encode('ascii')
print('checking...')
# --- takes 1-2 minutes to check flag
o = _______________________(flag, prog)
# ---
output = bytes(o[:o.index(0)]).decode('ascii')
print(output)
if output == b'Correct!':
print('Flag: %s' % flag)
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/DiceCTF/2021/crypto/newcryptv2/chall.py | ctfs/DiceCTF/2021/crypto/newcryptv2/chall.py | #!/usr/bin/env python3
from Crypto.Util.number import *
flag = open('flag.txt','rb').read()
class Generator:
def __init__(self,bits):
self.p = getPrime(bits)
self.q = getPrime(bits)
self.N = self.p*self.q
print(self.N)
def gen(self):
numbers = []
for round in range(5):
x = getRandomNBitInteger(1<<10)
y = inverse(x,(self.p-1)*(self.q-1)//GCD(self.p-1,self.q-1))
numbers.append(y)
print(numbers)
def encrypt(self,m):
return pow(m,0x1337,self.N)
g = Generator(1024)
g.gen()
m = bytes_to_long(flag)
print(g.encrypt(m))
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/DiceCTF/2021/crypto/garbled/generate_garbled_circuit.py | ctfs/DiceCTF/2021/crypto/garbled/generate_garbled_circuit.py | from yao import GarbledCircuit
import json
circuit_filename = "circuit.json"
with open(circuit_filename) as json_file:
circuit = json.load(json_file)
# creates a new garbled circuit each time
gc = GarbledCircuit(circuit)
g_tables = gc.get_garbled_tables()
keys = gc.get_keys()
print("g_tables = {}".format(repr(g_tables)))
print("\nkeys = {}".format(repr(keys)))
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/DiceCTF/2021/crypto/garbled/public_data.py | ctfs/DiceCTF/2021/crypto/garbled/public_data.py | g_tables = {5: [(5737111, 2983937),
(15406556, 16284948),
(14172222, 14132908),
(4000971, 16383744)],
6: [(8204186, 1546264),
(229766, 3208405),
(9550202, 13483954),
(13257058, 5195482)],
7: [(1658768, 11512735),
(1023507, 9621913),
(7805976, 1206540),
(2769364, 9224729)]} | python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/DiceCTF/2021/crypto/garbled/evaluate_garbled_circuit_example.py | ctfs/DiceCTF/2021/crypto/garbled/evaluate_garbled_circuit_example.py | """
This file is provided as an example of how to load the garbled circuit
and evaluate it with input key labels.
Note: the ACTUAL `g_tables` for this challenge are in `public_data.py`, and are not used in this example.
It will error if the provided inputs are not valid label keys,
ie do not match either of the `keys` made by `generate_garbled_circuit.py`
"""
import json
from yao import evaluate_circuit
from generate_garbled_circuit import g_tables, keys
circuit_filename = "circuit.json"
with open(circuit_filename) as json_file:
circuit = json.load(json_file)
inputs = {}
for i in circuit["inputs"]:
v = keys[i][1]
inputs[i] = v
evaluation = evaluate_circuit(circuit, g_tables, inputs)
print("")
print(evaluation)
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/DiceCTF/2021/crypto/garbled/block_cipher.py | ctfs/DiceCTF/2021/crypto/garbled/block_cipher.py | SBoxes = [[15, 1, 7, 0, 9, 6, 2, 14, 11, 8, 5, 3, 12, 13, 4, 10], [3, 7, 8, 9, 11, 0, 15, 13, 4, 1, 10, 2, 14, 6, 12, 5], [4, 12, 9, 8, 5, 13, 11, 7, 6, 3, 10, 14, 15, 1, 2, 0], [2, 4, 10, 5, 7, 13, 1, 15, 0, 11, 3, 12, 14, 9, 8, 6], [3, 8, 0, 2, 13, 14, 5, 11, 9, 1, 7, 12, 4, 6, 10, 15], [14, 12, 7, 0, 11, 4, 13, 15, 10, 3, 8, 9, 2, 6, 1, 5]]
SInvBoxes = [[3, 1, 6, 11, 14, 10, 5, 2, 9, 4, 15, 8, 12, 13, 7, 0], [5, 9, 11, 0, 8, 15, 13, 1, 2, 3, 10, 4, 14, 7, 12, 6], [15, 13, 14, 9, 0, 4, 8, 7, 3, 2, 10, 6, 1, 5, 11, 12], [8, 6, 0, 10, 1, 3, 15, 4, 14, 13, 2, 9, 11, 5, 12, 7], [2, 9, 3, 0, 12, 6, 13, 10, 1, 8, 14, 7, 11, 4, 5, 15], [3, 14, 12, 9, 5, 15, 13, 2, 10, 11, 8, 4, 1, 6, 0, 7]]
def S(block, SBoxes):
output = 0
for i in range(0, len(SBoxes)):
output |= SBoxes[i][(block >> 4*i) & 0b1111] << 4*i
return output
PBox = [13, 3, 15, 23, 6, 5, 22, 21, 19, 1, 18, 17, 20, 10, 7, 8, 12, 2, 16, 9, 14, 0, 11, 4]
PInvBox = [21, 9, 17, 1, 23, 5, 4, 14, 15, 19, 13, 22, 16, 0, 20, 2, 18, 11, 10, 8, 12, 7, 6, 3]
def permute(block, pbox):
output = 0
for i in range(24):
bit = (block >> pbox[i]) & 1
output |= (bit << i)
return output
def encrypt_data(block, key):
for j in range(0, 3):
block ^= key
block = S(block, SBoxes)
block = permute(block, PBox)
block ^= key
return block
def decrypt_data(block, key):
block ^= key
for j in range(0, 3):
block = permute(block, PInvBox)
block = S(block, SInvBoxes)
block ^= key
return block
def encrypt(data, key1, key2):
encrypted = encrypt_data(data, key1)
encrypted = encrypt_data(encrypted, key2)
return encrypted
def decrypt(data, key1, key2):
decrypted = decrypt_data(data, key2)
decrypted = decrypt_data(decrypted, key1)
return decrypted
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/DiceCTF/2021/crypto/garbled/yao.py | ctfs/DiceCTF/2021/crypto/garbled/yao.py | from block_cipher import encrypt, decrypt
from random import shuffle, randrange
def generate_random_label():
return randrange(0, 2**24)
def garble_label(key0, key1, key2):
"""
key0, key1 = two input labels
key2 = output label
"""
gl = encrypt(key2, key0, key1)
validation = encrypt(0, key0, key1)
return (gl, validation)
def evaluate_gate(garbled_table, key0, key1):
"""
Return the output label unlocked by the two input labels,
or raise a ValueError if no entry correctly decoded
"""
for g in garbled_table:
gl, v = g
label = decrypt(gl, key0, key1)
validation = decrypt(v, key0, key1)
if validation == 0:
return label
raise ValueError("None of the gates correctly decoded; invalid input labels")
def evaluate_circuit(circuit, g_tables, inputs):
"""
Evaluate yao circuit with given inputs.
Keyword arguments:
circuit -- dict containing circuit spec
g_tables -- garbled tables of yao circuit
inputs -- dict mapping wires to labels
Returns:
evaluation -- a dict mapping output wires to the result labels
"""
gates = circuit["gates"] # dict containing circuit gates
wire_outputs = circuit["outputs"] # list of output wires
wire_inputs = {} # dict containing Alice and Bob inputs
evaluation = {} # dict containing result of evaluation
wire_inputs.update(inputs)
# Iterate over all gates
for gate in sorted(gates, key=lambda g: g["id"]):
gate_id, gate_in = gate["id"], gate["in"]
key0 = wire_inputs[gate_in[0]]
key1 = wire_inputs[gate_in[1]]
garbled_table = g_tables[gate_id]
msg = evaluate_gate(garbled_table, key0, key1)
wire_inputs[gate_id] = msg
# After all gates have been evaluated, we populate the dict of results
for out in wire_outputs:
evaluation[out] = wire_inputs[out]
return evaluation
class GarbledGate:
"""A representation of a garbled gate.
Keyword arguments:
gate -- dict containing gate spec
keys -- dict mapping each wire to a pair of keys
"""
def __init__(self, gate, keys):
self.keys = keys # dict of yao circuit keys
self.input = gate["in"] # list of inputs' ID
self.output = gate["id"] # ID of output
self.gate_type = gate["type"] # Gate type: OR, AND, ...
self.garbled_table = {} # The garbled table of the gate
labels0 = keys[self.input[0]]
labels1 = keys[self.input[1]]
labels2 = keys[self.output]
if self.gate_type == "AND":
self.garbled_table = self._gen_garbled_AND_gate(labels0, labels1, labels2)
else:
raise NotImplementedError("Gate type `{}` is not implemented".format(self.gate_type))
def _gen_garbled_AND_gate(self, labels0, labels1, labels2):
"""
labels0, labels1 = two input labels
labels2 = output label
"""
key0_0, key0_1 = labels0
key1_0, key1_1 = labels1
key2_0, key2_1 = labels2
G = []
G.append(garble_label(key0_0, key1_0, key2_0))
G.append(garble_label(key0_0, key1_1, key2_0))
G.append(garble_label(key0_1, key1_0, key2_0))
G.append(garble_label(key0_1, key1_1, key2_1))
# randomly shuffle the table so you don't know what the labels correspond to
shuffle(G)
return G
def get_garbled_table(self):
"""Return the garbled table of the gate."""
return self.garbled_table
class GarbledCircuit:
"""
A representation of a garbled circuit.
Keyword arguments:
circuit -- dict containing circuit spec
"""
def __init__(self, circuit):
self.circuit = circuit
self.gates = circuit["gates"] # list of gates
self.wires = set() # list of circuit wires
self.keys = {} # dict of keys
self.garbled_tables = {} # dict of garbled tables
# Retrieve all wire IDs from the circuit
for gate in self.gates:
self.wires.add(gate["id"])
self.wires.update(set(gate["in"]))
self.wires = list(self.wires)
self._gen_keys()
self._gen_garbled_tables()
def _gen_keys(self):
"""Create pair of keys for each wire."""
for wire in self.wires:
self.keys[wire] = (
generate_random_label(),
generate_random_label()
)
def _gen_garbled_tables(self):
"""Create the garbled table of each gate."""
for gate in self.gates:
garbled_gate = GarbledGate(gate, self.keys)
self.garbled_tables[gate["id"]] = garbled_gate.get_garbled_table()
def get_garbled_tables(self):
"""Return dict mapping each gate to its garbled table."""
return self.garbled_tables
def get_keys(self):
"""Return dict mapping each wire to its pair of keys."""
return self.keys | python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/DiceCTF/2021/crypto/garbled/obtain_flag.py | ctfs/DiceCTF/2021/crypto/garbled/obtain_flag.py | """
once you've found the input labels which make the circuit return `true`,
then concatenate them together, hash them,
and xor with the provided string to obtain the flag
"""
import hashlib
import json
from yao import evaluate_circuit
from public_data import g_tables
from private_data import keys, flag
def xor(A, B):
return bytes(a ^ b for a, b in zip(A, B))
##########################################################
circuit_filename = "circuit.json"
with open(circuit_filename) as json_file:
circuit = json.load(json_file)
# ?????????????????
inputs = {
1: ?????????????????,
2: ?????????????????,
3: ?????????????????,
4: ?????????????????
}
evaluation = evaluate_circuit(circuit, g_tables, inputs)
# circuit should return `true`
for i in circuit['outputs']:
assert evaluation[i] == keys[i][1]
##########################################################
msg = "{}:{}:{}:{}".format(inputs[1], inputs[2], inputs[3], inputs[4])
msg = msg.encode('ascii')
m = hashlib.sha512()
m.update(msg)
m.digest()
xor_flag = b'\x90),u\x1b\x1dE:\xa8q\x91}&\xc7\x90\xbb\xce]\xf5\x17\x89\xd7\xfa\x07\x86\x83\xfa\x9b^\xcb\xd77\x00W\xca\xceXD7'
print( xor(m.digest(), xor_flag) )
assert xor(m.digest(), xor_flag) == flag
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/DiceCTF/2021/crypto/signature-sheep-scheming-signature-schemes/lwe.py | ctfs/DiceCTF/2021/crypto/signature-sheep-scheming-signature-schemes/lwe.py | import numpy as np
from random import SystemRandom
from shake import ShakeRandom
from Crypto.Hash import SHAKE128
system = SystemRandom()
n = 640
q = 1 << 16
sigma = 2.8
bound = 6000
def pack(*values):
data = bytes()
for x in values:
data += x.tobytes()
return data
def unpack(data, width=1):
for i in range(0, len(data), n*width*2):
yield np.ndarray((n, width), dtype=np.uint16, buffer=data, offset=i)
def uniform(random=system, width=1):
sample = lambda *_: random.randrange(q)
return np.fromfunction(np.vectorize(sample), (n, width)).astype(np.uint16)
def gauss(random=system, width=1):
sample = lambda *_: round(random.gauss(0, sigma)) % q
return np.fromfunction(np.vectorize(sample), (n, width)).astype(np.uint16)
def short(x):
return np.linalg.norm(np.minimum(x, -x)) < bound
class Key:
def __init__(self, a, b, s=None):
self.a = a
self.b = b
self.s = s
@classmethod
def generate(cls):
a = uniform(width=n)
s = gauss(width=n)
b = a @ s + gauss(width=n)
return cls(a, b, s)
@classmethod
def deserialize(cls, data):
return cls(*unpack(data, width=n))
def serialize(self, private=False):
if private:
return pack(self.a, self.b, self.s)
else:
return pack(self.a, self.b)
def sign(self, message):
s = gauss()
b = self.a @ s + gauss()
c = gauss(random=ShakeRandom(pack(self.a, self.b, b) + message))
r = s - self.s @ c
return pack(b, r)
def verify(self, message, signature):
b, r = unpack(signature)
assert short(r)
c = gauss(random=ShakeRandom(pack(self.a, self.b, b) + message))
assert short(self.a @ r + self.b @ c - b)
if __name__ == '__main__':
message = b'silly sheep'
key = Key.generate()
with open('public.key', 'wb') as f:
f.write(key.serialize())
with open('private.key', 'wb') as f:
f.write(key.serialize(private=True))
with open('signatures.bin', 'wb') as f:
for _ in range(1337):
signature = key.sign(message)
key.verify(message, signature)
f.write(signature)
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/DiceCTF/2021/crypto/signature-sheep-scheming-signature-schemes/shake.py | ctfs/DiceCTF/2021/crypto/signature-sheep-scheming-signature-schemes/shake.py | from random import Random, RECIP_BPF
from Crypto.Hash import SHAKE128
from Crypto.Util.number import bytes_to_long
class ShakeRandom(Random):
def __init__(self, data):
self.shake = SHAKE128.new(data)
self.gauss_next = None
def random(self):
return (bytes_to_long(self.shake.read(7)) >> 3) * RECIP_BPF
def getrandbits(self, k):
return bytes_to_long(self.shake.read((k + 7) // 8)) >> (-k % 8)
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/DiceCTF/2021/crypto/signature-sheep-scheming-signature-schemes/server.py | ctfs/DiceCTF/2021/crypto/signature-sheep-scheming-signature-schemes/server.py | import signal
import socketserver
from lwe import Key, n
with open('public.key', 'rb') as f:
key = Key.deserialize(f.read())
with open('flag.txt', 'rb') as f:
flag = f.read()
message = b'shep, the conqueror'
class RequestHandler(socketserver.BaseRequestHandler):
def handle(self):
signal.alarm(10)
self.request.sendall(b'signature? ')
signature = self.request.recv(4*n)
key.verify(message, signature)
self.request.sendall(flag)
class Server(socketserver.ForkingTCPServer):
allow_reuse_address = True
def handle_error(self, request, client_address):
self.request.close()
server = Server(('0.0.0.0', 3000), RequestHandler)
server.serve_forever()
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/DiceCTF/2021/crypto/benaloh/benaloh.py | ctfs/DiceCTF/2021/crypto/benaloh/benaloh.py | from Crypto.Random.random import randrange
from Crypto.Util.number import getPrime, GCD
r = 17
def keygen():
while True:
p = getPrime(1024)
a, b = divmod(p-1, r)
if b == 0 and GCD(r, a) == 1:
break
while True:
q = getPrime(1024)
if GCD(r, q-1) == 1:
break
n = p*q
phi = (p-1)*(q-1)//r
y = 1
while True:
y = randrange(n)
x = pow(y, phi, n)
if x != 1:
break
log = {pow(x, i, n): i for i in range(r)}
return (n, y), (n, phi, log)
def encrypt(data, pk):
n, y = pk
u = randrange(n)
a = randrange(n)
c = randrange(n)
for m in data.hex():
yield pow(y, int(m, 16), n) * pow(u, r, n) % n
u = (a*u + c) % n
def decrypt(data, sk):
n, phi, log = sk
return bytes.fromhex(''.join(f'{log[pow(z, phi, n)]:x}' for z in data))
if __name__ == '__main__':
from local import flag
pk, sk = keygen()
print(pk)
for z in encrypt(flag, pk):
print(z)
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/DiceCTF/2024/Quals/misc/IRS/audit.py | ctfs/DiceCTF/2024/Quals/misc/IRS/audit.py | import ast
import irs
dangerous = lambda s: any(d in s for d in ("__", "attr"))
dangerous_attr = lambda s: dangerous(s) or s in dir(dict)
dangerous_nodes = (ast.Starred, ast.GeneratorExp, ast.Match, ast.With, ast.AsyncWith, ast.keyword, ast.AugAssign)
print("Welcome to the IRS! Enter your code:")
c = ""
while l := input("> "): c += l + "\n"
root = ast.parse(c)
for node in ast.walk(root):
for child in ast.iter_child_nodes(node):
child.parent = node
if not any(type(n) in dangerous_nodes or
type(n) is ast.Name and dangerous(n.id) or
type(n) is ast.Attribute and dangerous_attr(n.attr) or
type(n) is ast.Subscript and type(n.parent) is not ast.Delete or
type(n) is ast.arguments and (n.kwarg or n.vararg)
for n in ast.walk(root)):
del __builtins__.__loader__
del __builtins__.__import__
del __builtins__.__spec__
irs.audit()
exec(c, {}, {})
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/DiceCTF/2024/Quals/misc/diligent_auditor/jail.py | ctfs/DiceCTF/2024/Quals/misc/diligent_auditor/jail.py | #!/usr/local/bin/python
import os
import sys
import string
mod = input("mod? ")
cod = input("cod? ")
sys.stdin.close()
if len(mod) > 16 or len(cod) > 512 or any(x not in string.ascii_lowercase for x in mod) or any(x not in string.printable for x in cod):
print("nope")
exit(1)
code = f"""
import sys
import os
import inspect
import {mod}
if "_posixsubprocess" in sys.modules:
print("nope")
os._exit(1)
for k in list(sys.modules):
del sys.modules[k]
f = inspect.currentframe()
sys.addaudithook((lambda x: lambda *_: x(1))(os._exit))
for k in f.f_builtins:
f.f_builtins[k] = None
for k in f.f_globals:
if k != "f":
f.f_globals[k] = None
for k in f.f_locals:
f.f_locals[k] = None
del f
del k
{cod}
""".strip()
os.execv(sys.executable, [sys.executable, "-c", code])
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/DiceCTF/2024/Quals/misc/what_a_jpeg_is/challenge.py | ctfs/DiceCTF/2024/Quals/misc/what_a_jpeg_is/challenge.py | #!/usr/bin/python3
import os
import sys
os.environ['OPENBLAS_NUM_THREADS'] = '1'
print("Starting up")
sys.stdout.flush()
import base64
import numpy as np
import io
from PIL import Image
from transformers import ConvNextImageProcessor, ConvNextForImageClassification
import torch
import torchvision.transforms as T
from datasets import load_dataset
def pytorch_jpeg_compress(img_tensors):
out_tensors = []
for img_tensor in img_tensors:
quality = np.random.randint(50, 90)
img = Image.fromarray(
(
np.clip(img_tensor.cpu().numpy().swapaxes(0, 1).swapaxes(1, 2), 0, 1) * 255
).astype(np.uint8)
)
with io.BytesIO() as f:
img.save(f, "JPEG", quality=quality)
img = Image.open(io.BytesIO(f.getvalue()))
out_tensor = torch.tensor(
np.array(img).swapaxes(2, 1).swapaxes(1, 0) / 255,
device=img_tensor.device,
dtype=torch.float32,
)
out_tensors.append(out_tensor)
out_tensors = torch.stack(out_tensors)
return out_tensors
processor = ConvNextImageProcessor.from_pretrained("facebook/convnext-base-384-22k-1k", cache_dir="./cache")
HFmodel = ConvNextForImageClassification.from_pretrained("facebook/convnext-base-384-22k-1k", cache_dir="./cache").eval()
model = next(HFmodel.modules())
dataset = load_dataset("huggingface/cats-image", cache_dir="./cache", trust_remote_code=True)
np_original = np.array(dataset["test"]["image"][0])
print("Loaded HuggingFace")
mean = [0.485, 0.456, 0.406]
std = [0.229, 0.224, 0.225]
openmybook = T.ToTensor()
normalize = T.Normalize(mean, std)
reading_glasses = T.RandomResizedCrop(384, antialias=True)
prompts = ["Let me take a closer look", "I need to put on my reading glasses", "Let me try from another angle"]
for target_id in range(383, 388 + 1):
breed = model.config.id2label[target_id].split(",")[0]
inp = input(f"I love cats! My favorite breed is {breed}. Can you show me a picture of one?\n")
try:
np_breed = np.frombuffer(base64.standard_b64decode(inp), dtype=np.uint8)
np_breed = np_breed.reshape(np_original.shape)
assert np.max(np.abs(np_original.astype(int) - np_breed.astype(int))) < 10
except:
print("Sorry I only like cats that look exactly like my cat!", flush=True)
sys.exit(0)
for i in range(3):
print(prompts[i])
image = Image.fromarray(np_breed.astype(np.uint8))
x = openmybook(image)
x = x.unsqueeze(0)
x = pytorch_jpeg_compress(x)
x = normalize(x)
x = reading_glasses(x)
with torch.no_grad():
logits = model(x).logits
if torch.argmax(logits).item() != target_id:
print(f"That doesn't look like a {breed}!")
sys.exit(0)
with open("flag.txt") as f:
print(f.read()) | python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/DiceCTF/2024/Quals/misc/floordrop/solve.py | ctfs/DiceCTF/2024/Quals/misc/floordrop/solve.py | import sys
import gmpy2
MODULUS = 2**44497-1
def sloth_root(x, p):
exponent = (p + 1) // 4
x = gmpy2.powmod(x, exponent, p)
return int(x)
def solve_challenge(x):
y = sloth_root(x, MODULUS)
return y
def main():
chal = int(sys.argv[1])
sol = solve_challenge(chal)
print(sol.to_bytes((sol.bit_length() + 7) // 8, 'big').hex())
if __name__ == '__main__':
main() | python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/DiceCTF/2024/Quals/misc/unipickle/unipickle.py | ctfs/DiceCTF/2024/Quals/misc/unipickle/unipickle.py | #!/usr/local/bin/python
import pickle
pickle.loads(input("pickle: ").split()[0].encode())
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/DiceCTF/2024/Quals/rev/LEvasion_Fiscale/tax.py | ctfs/DiceCTF/2024/Quals/rev/LEvasion_Fiscale/tax.py | import subprocess
print('''\
################################
## DICE TAXATION SYSTEMS 4000 ##
################################''')
flag = input('Enter flag > ')
addendum = '''
### [Flag Addendum]
```catala
declaration flag content list of C equals [{}]
```
'''.format(';'.join(['C{{--index:{} --val:{}}}'.format(i, ord(flag[i])) for i in range(len(flag))]))
prog = open('./DiceTax.catala_en', 'r').read()
open('./DiceTaxInstance.catala_en', 'w').write(prog + addendum)
try:
p = subprocess.run([
'/usr/local/bin/catala', 'interpret',
'-s', 'Main',
'DiceTaxInstance.catala_en'
], check=True, capture_output=True)
except subprocess.CalledProcessError as e:
print('You broke the tax machine :(')
exit(0)
out = p.stdout.decode('utf-8')
tax = out.split('tax = ')[1].split('\n')[0]
print('Tax:', tax)
if tax == '$0.00':
print('Nice flag!')
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/DiceCTF/2024/Quals/rev/neurotic/neurotic.py | ctfs/DiceCTF/2024/Quals/rev/neurotic/neurotic.py |
import json
def link(brain, a, b):
if a[0] in brain:
brain[a[0]][a[1]] = b
if b[0] in brain:
brain[b[0]][b[1]] = a
def unlink(brain, ptr):
other = brain[ptr[0]][ptr[1]]
if ptr == brain[other[0]][other[1]]:
brain[ptr[0]][ptr[1]] = ptr
brain[other[0]][other[1]] = other
def enter(brain, a):
return brain[a[0]][a[1]]
def neuron(brain, t):
c = brain['_n']
brain['_n'] += 1
brain[c] = [(c,0),(c,1),(c,2),t]
return c
def happy(brain, i, i2):
link(brain, enter(brain, (i,1)), enter(brain, (i2,1)))
link(brain, enter(brain, (i,2)), enter(brain, (i2,2)))
def sad(brain, i, i2):
p = neuron(brain, brain[i2][3])
q = neuron(brain, brain[i2][3])
r = neuron(brain, brain[i][3])
s = neuron(brain, brain[i][3])
link(brain, (r,1), (p,1))
link(brain, (s,1), (p,2))
link(brain, (r,2), (q,1))
link(brain, (s,2), (q,2))
link(brain, (p,0), enter(brain, (i,1)))
link(brain, (q,0), enter(brain, (i,2)))
link(brain, (r,0), enter(brain, (i2,1)))
link(brain, (s,0), enter(brain, (i2,2)))
def process_emotion(brain, i, i2) -> bool:
if brain[i][3] == brain[i2][3]:
happy(brain, i, i2)
else:
sad(brain, i, i2)
for s in range(3):
unlink(brain, (i, s))
unlink(brain, (i2, s))
del brain[i]
if i2 in brain:
del brain[i2]
return True
def experience_life(brain):
brain['_n'] = max([k for k in brain if type(k) is int]) + 1
z1 = []
z2 = []
curr = enter(brain, (0,1))
prev = None
back = None
while curr[0] != 0 or len(z1) > 0:
if curr[0] == 0:
curr = enter(brain, z1.pop(-1))
prev = enter(brain, curr)
if curr[1] == 0 and prev[1] == 0:
back = enter(brain, (prev[0], z2.pop(-1)))
process_emotion(brain, prev[0], curr[0])
curr = enter(brain, back)
elif curr[1] == 0:
z1.append((curr[0], 2))
curr = enter(brain, (curr[0], 1))
else:
z2.append(curr[1])
curr = enter(brain, (curr[0], 0))
def write_val(brain, val, prev):
a = neuron(brain, 0)
b = neuron(brain, 0)
c = neuron(brain, 0)
d = neuron(brain, 0)
e = neuron(brain, 0)
f = neuron(brain, 0)
g = neuron(brain, 0)
h = neuron(brain, 0)
i = neuron(brain, 0)
link(brain,(a,2),(i,0))
link(brain,(a,0),(b,0))
link(brain,(b,2),(c,0))
link(brain,(b,1),(e,1))
link(brain,(c,2),(d,0))
link(brain,(c,1),(f,1))
link(brain,(d,1),(e,0))
link(brain,(d,2),(f,2))
link(brain,(e,2),(f,0))
link(brain,(a,1),(g,0))
link(brain,(g,2),(h,0))
link(brain,(i,2),prev)
p = (g,1)
q = (h,2)
t = max([brain[x][3] for x in brain if type(x) is int]) + 1
for _ in range(val-1):
m = neuron(brain, t)
n = neuron(brain, 0)
t += 1
link(brain,(m,0),p)
p = (m,2)
link(brain,(n,0),(m,1))
link(brain,(n,2),q)
q = (n,1)
z = neuron(brain,0)
link(brain,(z,0),p)
link(brain,(z,2),q)
link(brain,(z,1),(h,1))
return (i,1)
def term(brain, prev):
a = neuron(brain, 0)
b = neuron(brain, 0)
c = neuron(brain, 0)
link(brain,(a,0),prev)
link(brain,(a,2),(b,0))
link(brain,(b,2),(c,0))
link(brain,(c,2),(b,1))
def inject(brain, flag):
prev = (1,1)
for i in range(len(flag)):
prev = write_val(brain, ord(flag[i]), prev)
term(brain, prev)
def is_satisfied(brain):
a = brain[0][1]
b = brain[a[0]][2]
c = brain[b[0]][2]
return b[0] != c[0]
# -------------------------------
raw = json.load(open('brain.json'))
brain = {int(k): [tuple(raw[k][0]), tuple(raw[k][1]), tuple(raw[k][2]), raw[k][3]] for k in raw}
brain['_n'] = max([k for k in brain if type(k) is int]) + 1
flag = input('Flag > ')
if len(flag) != 32 or flag[:5] != 'dice{' or flag[-1] != '}':
print('Invalid format')
exit()
inject(brain, flag)
experience_life(brain)
if is_satisfied(brain):
print('Flag accepted')
else:
print('Flag rejected')
# -------------------------------
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/DiceCTF/2024/Quals/crypto/mea_shor_ment_error/setup.py | ctfs/DiceCTF/2024/Quals/crypto/mea_shor_ment_error/setup.py | from Crypto.PublicKey import RSA
from Crypto.Cipher import PKCS1_OAEP
nbits = 3072
key = RSA.generate(nbits)
with open("flag.txt", "rb") as f:
flag = f.read()
cipher = PKCS1_OAEP.new(key)
ciphertext = cipher.encrypt(flag)
with open("privatekey.pem", "wb") as f:
data = key.export_key()
f.write(data)
with open("publickey.pem", "wb") as f:
data = key.public_key().export_key()
f.write(data)
with open("ciphertext.bin", "wb") as f:
f.write(ciphertext) | python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/DiceCTF/2024/Quals/crypto/mea_shor_ment_error/mea_shor_ment_error.py | ctfs/DiceCTF/2024/Quals/crypto/mea_shor_ment_error/mea_shor_ment_error.py | import numpy as np
from Crypto.PublicKey import RSA
error_prob = 0.05
with open("privatekey.pem", "rb") as f:
key = RSA.import_key(f.read())
p,q,n = key.p, key.q, key.n
mbits = 2 * key.size_in_bits()
euler = lcm(p-1, q-1)
P = prod(primes_first_n(10000))
factors = gcd(P^30, euler)
d = divisors(factors)
candidates = [(euler // x) for x in d]
rng = np.random.default_rng()
a = mod(1337, n)
r = min([x for x in candidates if a^x == 1])
assert gcd(n, mod(a,n)^(r//2) + 1) != 1
def sample_shor():
j = randint(0, r-1)
v = Integer((2^mbits * j)//r)
res = v.digits(2)
res = res + [0]*(mbits - len(res))
res = res[::-1]
error = rng.binomial(1, error_prob, mbits)
res = [x^^y for x,y in zip(res, error)]
res = "".join([str(i) for i in res])
return res
data = "\n".join([str(sample_shor()) for i in range(1000)])
with open("shor.txt", "w") as f:
f.write(data) | python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/DiceCTF/2024/Quals/crypto/rps_casino/server.py | ctfs/DiceCTF/2024/Quals/crypto/rps_casino/server.py | #!/usr/local/bin/python
import os
from Crypto.Util.number import bytes_to_long
def LFSR():
state = bytes_to_long(os.urandom(8))
while 1:
yield state & 0xf
for i in range(4):
bit = (state ^ (state >> 1) ^ (state >> 3) ^ (state >> 4)) & 1
state = (state >> 1) | (bit << 63)
rng = LFSR()
n = 56
print(f"Let's play rock-paper-scissors! We'll give you {n} free games, but after that you'll have to beat me 50 times in a row to win. Good luck!")
rps = ["rock", "paper", "scissors", "rock"]
nums = []
for i in range(n):
choice = next(rng) % 3
inp = input("Choose rock, paper, or scissors: ")
if inp not in rps:
print("Invalid choice")
exit(0)
if inp == rps[choice]:
print("Tie!")
elif rps.index(inp, 1) - 1 == choice:
print("You win!")
else:
print("You lose!")
for i in range(50):
choice = next(rng) % 3
inp = input("Choose rock, paper, or scissors: ")
if inp not in rps:
print("Invalid choice")
break
if rps.index(inp, 1) - 1 != choice:
print("Better luck next time!")
break
else:
print("You win!")
else:
print(open("flag.txt").read()) | python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/DiceCTF/2024/Quals/crypto/winter/server.py | ctfs/DiceCTF/2024/Quals/crypto/winter/server.py | #!/usr/local/bin/python
import os
from hashlib import sha256
class Wots:
def __init__(self, sk, vk):
self.sk = sk
self.vk = vk
@classmethod
def keygen(cls):
sk = [os.urandom(32) for _ in range(32)]
vk = [cls.hash(x, 256) for x in sk]
return cls(sk, vk)
@classmethod
def hash(cls, x, n):
for _ in range(n):
x = sha256(x).digest()
return x
def sign(self, msg):
m = self.hash(msg, 1)
sig = b''.join([self.hash(x, 256 - n) for x, n in zip(self.sk, m)])
return sig
def verify(self, msg, sig):
chunks = [sig[i:i+32] for i in range(0, len(sig), 32)]
m = self.hash(msg, 1)
vk = [self.hash(x, n) for x, n in zip(chunks, m)]
return self.vk == vk
if __name__ == '__main__':
with open('flag.txt') as f:
flag = f.read().strip()
wots = Wots.keygen()
msg1 = bytes.fromhex(input('give me a message (hex): '))
sig1 = wots.sign(msg1)
assert wots.verify(msg1, sig1)
print('here is the signature (hex):', sig1.hex())
msg2 = bytes.fromhex(input('give me a new message (hex): '))
if msg1 == msg2:
print('cheater!')
exit()
sig2 = bytes.fromhex(input('give me the signature (hex): '))
if wots.verify(msg2, sig2):
print(flag)
else:
print('nope')
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/DiceCTF/2024/Quals/crypto/iinversion/generate.py | ctfs/DiceCTF/2024/Quals/crypto/iinversion/generate.py | import pyhelayers
import numpy as np
n = 16384
requirement = pyhelayers.HeConfigRequirement(
num_slots = n, # Number of slots per ciphertext
multiplication_depth = 12, # Allow x levels of multiplications
fractional_part_precision = 50, # Set the precision to 1/2^x
integer_part_precision = 10, # Set the largest number to 2^x
security_level = 128)
he_context = pyhelayers.HeaanContext()
he_context.init(requirement)
# Create the Encoder using the context.
encoder = pyhelayers.Encoder(he_context)
he_context.save_to_file("public.key")
he_context.save_secret_key_to_file("private.key")
cutoff = 0.02
x = np.random.uniform(-1, 1, n)
x = np.copysign(np.abs(x) + cutoff, x) / (1 + cutoff)
cx = encoder.encode_encrypt(x)
cx.save_to_file("x_hard.ctxt")
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/DiceCTF/2024/Quals/crypto/iinversion/server.py | ctfs/DiceCTF/2024/Quals/crypto/iinversion/server.py | #!/usr/local/bin/python
import pyhelayers
import numpy as np
import base64
import sys
import os
os.chdir("/tmp")
THRESHOLD = 0.02
he_context = pyhelayers.HeaanContext()
he_context.load_from_file("/app/public.key")
he_context.load_secret_key_from_file("/app/private.key")
encoder = pyhelayers.Encoder(he_context)
data = input("Please provide a base64 encoded ciphertext equal to 1/x\n")
cx = encoder.encode_encrypt([0])
cy = encoder.encode_encrypt([0])
cx.load_from_file("/app/x_hard.ctxt")
try:
cy.load_from_buffer(base64.standard_b64decode(data))
except:
print("Couldn't load ctxt")
sys.exit(0)
x = encoder.decrypt_decode_double(cx)
y = encoder.decrypt_decode_double(cy)
if np.max(np.abs(x * y - 1)) < THRESHOLD:
with open("/app/flag.txt", "r") as f:
print(f.read())
else:
print("Error too high")
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/DiceCTF/2024/Quals/crypto/pee_side/server.py | ctfs/DiceCTF/2024/Quals/crypto/pee_side/server.py | import sys
print("thinking...")
sys.stdout.flush()
from sage.all import *
# PSIDH class code is adapted from
# https://github.com/grhkm21/CTF-challenges/blob/master/Bauhinia-CTF-2023/Avengers/public/chasher.sage
proof.all(False)
x = var('x')
import random
import hashlib
class PSIDH:
def __init__(self, l):
self.n = len(l)
self.l = l
self.p = 4 * product(self.l) - 1
assert is_prime(self.p)
self.K = GF(self.p**2, modulus = x**2 + 1, names = 'i')
self.i = self.K.gen(0)
self.paramgen()
def paramgen(self):
E0 = EllipticCurve(self.K, [1, 0])
# Move to random starting supersingular curve
self.E0, _ = self.action(E0, E0(0), [random.randrange(-5, 6) for _ in ell])
self.P0 = self.E0.random_point()
def action(self, E, PP, priv):
assert len(priv) == self.n
E = EllipticCurve(self.K, E.ainvs())
PP = E(PP)
es = priv.copy()
while any(es):
E.set_order((self.p + 1)**2)
P = E.lift_x(ZZ(randrange(self.p)))
s = [-1, 1][P[1] in GF(self.p)]
k = prod(l for l, e in zip(self.l, es) if sign(e) == s)
P *= (self.p + 1) // k
for i, (l, e) in enumerate(zip(self.l, es)):
if sign(e) != s:
continue
Q = k // l * P
if not Q:
continue
Q.set_order(l)
psi = E.isogeny(Q)
E, P, PP = psi.codomain(), psi(P), psi(PP)
es[i] -= s
k //= l
return E, PP
def to_secret(self, E, P):
return hashlib.sha256((str(E.j_invariant()) + str(P.xy())).encode()).hexdigest()
if __name__ == '__main__':
with open('flag.txt') as f:
flag = f.read().strip()
ell = list(prime_range(200, 450)) + [1483]
psidh = PSIDH(ell)
# Get the randomly generated public key
E0, P0 = psidh.E0, psidh.P0
a = [random.randrange(-1,2) for _ in ell]
Ea, Pa = psidh.action(E0, P0, a)
print(f'take this: ({Ea.ainvs()}, {Pa})')
inp = input('something for me? ').strip()[2:-2].split('), (')
try:
Eb = EllipticCurve(psidh.K, [int(c) for c in inp[0].strip('()').split(', ')])
assert Eb.is_supersingular()
Pb = Eb([psidh.K(c) for c in inp[1].strip('()').split(', ')])
except:
print('tsk tsk tsk')
exit()
Eab, Pab = psidh.action(Eb, Pb, a)
shared_secret = psidh.to_secret(Eab, Pab)
guess = input('> ')
if guess == shared_secret:
print(flag)
else:
print('better luck next time...') | python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/DiceCTF/2024/Quals/crypto/inversion/generate.py | ctfs/DiceCTF/2024/Quals/crypto/inversion/generate.py | import pyhelayers
import numpy as np
n = 16384
requirement = pyhelayers.HeConfigRequirement(
num_slots = n, # Number of slots per ciphertext
multiplication_depth = 12, # Allow x levels of multiplications
fractional_part_precision = 50, # Set the precision to 1/2^x
integer_part_precision = 10, # Set the largest number to 2^x
security_level = 128)
he_context = pyhelayers.HeaanContext()
he_context.init(requirement)
# Create the Encoder using the context.
encoder = pyhelayers.Encoder(he_context)
he_context.save_to_file("public.key")
he_context.save_secret_key_to_file("private.key")
x = np.random.uniform(-1, 1, n)
x = np.copysign(np.abs(x) + 0.4, x)
cx = encoder.encode_encrypt(x)
cx.save_to_file("x.ctxt")
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/DiceCTF/2024/Quals/crypto/inversion/server.py | ctfs/DiceCTF/2024/Quals/crypto/inversion/server.py | #!/usr/local/bin/python
import pyhelayers
import numpy as np
import base64
import sys
import os
os.chdir("/tmp")
THRESHOLD = 0.25
he_context = pyhelayers.HeaanContext()
he_context.load_from_file("/app/public.key")
he_context.load_secret_key_from_file("/app/private.key")
encoder = pyhelayers.Encoder(he_context)
data = input("Please provide a base64 encoded ciphertext equal to 1/x\n")
cx = encoder.encode_encrypt([0])
cy = encoder.encode_encrypt([0])
cx.load_from_file("/app/x.ctxt")
try:
cy.load_from_buffer(base64.standard_b64decode(data))
except:
print("Couldn't load ctxt")
sys.exit(0)
x = encoder.decrypt_decode_double(cx)
y = encoder.decrypt_decode_double(cy)
if np.max(np.abs(x * y - 1)) < THRESHOLD:
with open("/app/flag.txt", "r") as f:
print(f.read())
else:
print("Error too high") | python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/DiceCTF/2023/rev/raspberry/run.py | ctfs/DiceCTF/2023/rev/raspberry/run.py |
flag = input('Enter flag: ')
alph = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPWRSTUVWXYZ0123456789{}_'
for x in flag:
if not x in alph:
print('Bad chars')
exit(0)
import os
os.chdir('./RASP/')
import sys
sys.path.append('./RASP_support')
from REPL import REPL, LineReader
REPL.print_welcome = lambda *a, **kw: 0
r = REPL()
print('[*] Loading...')
r.run_given_line('set example "dice"')
with open('../berry.rasp', 'r') as f:
r.run(fromfile=f, store_prints=False)
print('[*] Checking flag...')
lr = LineReader(given_line=f'res("{flag}");').get_input_tree()
rp = r.evaluate_tree(lr)
v = list(rp.res.val.get_vals())
if all(x == 1 for x in v):
print('Correct :)')
else:
print('Incorrect :(')
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/DiceCTF/2023/crypto/vinaigrette/vinaigrette.py | ctfs/DiceCTF/2023/crypto/vinaigrette/vinaigrette.py | #!/usr/local/bin/python
import ctypes
# tar -xf pqov-paper.tar.gz && patch -p1 < patch.diff && make libpqov.so VARIANT=2
libpqov = ctypes.CDLL('./libpqov.so')
CRYPTO_SECRETKEYBYTES = 237912
CRYPTO_PUBLICKEYBYTES = 43576
CRYPTO_BYTES = 128
def sign(sk, m):
m = ctypes.create_string_buffer(m, len(m))
mlen = ctypes.c_size_t(len(m))
sm = ctypes.create_string_buffer(len(m) + CRYPTO_BYTES)
smlen = ctypes.c_size_t(0)
libpqov.crypto_sign(sm, ctypes.pointer(smlen), m, mlen, sk)
return bytes(sm)
def verify(pk, sm):
assert len(sm) >= CRYPTO_BYTES
m = ctypes.create_string_buffer(len(sm) - CRYPTO_BYTES)
mlen = ctypes.c_size_t(0)
sm = ctypes.create_string_buffer(sm, len(sm))
smlen = ctypes.c_size_t(len(sm))
assert libpqov.crypto_sign_open(m, ctypes.pointer(mlen), sm, smlen, pk) == 0
return bytes(m)
if __name__ == '__main__':
with open('flag.txt') as f:
flag = f.read().strip()
with open('sk.bin', 'rb') as f:
sk = f.read()
with open('pk.bin', 'rb') as f:
pk = f.read()
print('''\
Welcome to Dice Bistro.
===== SPECIAL MENU =============================================================
Caesar Salad - A mix of greens and seasonal vegetables, tossed in our housemade
vinaigrette.
Enigma Chicken - A perfectly grilled chicken breast, topped with a drizzle of
the mysterious vinaigrette, served with a side of potato hash (of course,
collision-resistant).
Quantum Quinoa Bowl - A delicious combination of quinoa, roasted vegetables,
and a variety of nuts, all tossed in the mysterious vinaigrette, guaranteed
to entangle your taste buds.
================================================================================
''')
order = input('What would you like to order? ').encode()
if order == b'the vinaigrette recipe':
print('Only employees of Dice Bistro are allowed to learn the vinaigrette recipe.')
try:
sm = bytes.fromhex(input('Authorization: '))
assert verify(pk, sm) == order
print(f'Certainly, here it is: {flag}')
except:
print('error')
else:
sm = sign(sk, order)
print(f'Certainly, here it is: {sm.hex()}')
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/DiceCTF/2023/crypto/inversion/generate.py | ctfs/DiceCTF/2023/crypto/inversion/generate.py | import numpy as np
from Pyfhel import Pyfhel
from tqdm import tqdm
from scipy.stats import special_ortho_group
num_levels = 9
qi_sizes = [60] + [30] * num_levels + [60]
HE = Pyfhel() # Creating empty Pyfhel object
ckks_params = {
'scheme': 'CKKS', # can also be 'ckks'
'n': 2**14, # Polynomial modulus degree. For CKKS, n/2 values can be
# encoded in a single ciphertext.
# Typ. 2^D for D in [10, 16]
'scale': 2**30, # All the encodings will use it for float->fixed point
# conversion: x_fix = round(x_float * scale)
# You can use this as default scale or use a different
# scale on each operation (set in HE.encryptFrac)
'qi_sizes': qi_sizes # Number of bits of each prime in the chain.
# Intermediate values should be close to log2(scale)
# for each operation, to have small rounding errors.
}
HE.contextGen(**ckks_params) # Generate context for ckks scheme
HE.keyGen() # Key Generation: generates a pair of public/secret keys
HE.rotateKeyGen()
HE.relinKeyGen()
# ----------------------------------------
def get_random_matrix():
w = 2.0
s = special_ortho_group.rvs(m)
e = np.random.random(m)
e *= (np.log2(w) - np.log2(1/w))
e = 1/w * pow(2, e)
e *= np.random.choice([-1,1], m)
e = np.diag(e)
A = s @ e @ s.T
return A
n = 2**14
slots = n // 2
m = 8
num_mtx = slots // (m*m)
matx = [get_random_matrix() for i in tqdm(range(num_mtx))]
matx = np.array(matx, dtype=np.float64)
ptxt_x = matx.ravel()
ctxt_x = HE.encryptFrac(ptxt_x)
dir_name = "data"
HE.save_context(dir_name + "/context")
HE.save_public_key(dir_name + "/pub.key")
HE.save_secret_key("sec.key")
HE.save_relin_key(dir_name + "/relin.key")
HE.save_rotate_key(dir_name + "/rotate.key")
ctxt_x.save(dir_name + "/c.ctxt")
"""
Note:
the Pyfhel documentation isn't very clear on this, but after each homomorphic multiplication you perform, you'll want to do:
x = a * b
x = ~x # relinearize
x = HE.rescale_to_next(x) # rescale
This prevents the scale factor from increasing, which would otherwise reduce the number of multiplications you can perform
"""
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/DiceCTF/2023/crypto/inversion/server.py | ctfs/DiceCTF/2023/crypto/inversion/server.py | #!/usr/local/bin/python
import numpy as np
from Pyfhel import Pyfhel, PyPtxt, PyCtxt
DEBUG = False
dir_name = "data"
HE = Pyfhel()
HE.load_context(dir_name + "/context")
HE.load_public_key(dir_name + "/pub.key")
HE.load_secret_key("sec.key")
x = PyCtxt(pyfhel=HE, fileName=dir_name + "/c.ctxt")
if DEBUG:
y = PyCtxt(pyfhel=HE, fileName="sol.ctxt")
else:
ctxt_bytes = input("hex-encoded matrix inverse ciphertext: ")
ctxt_bytes = bytes.fromhex(ctxt_bytes)
y = PyCtxt(pyfhel=HE, bytestring=ctxt_bytes)
n = 2**14
slots = n // 2
m = 8
num_mtx = slots // (m*m)
mat = HE.decryptFrac(x).reshape((num_mtx,m,m))
imat = HE.decryptFrac(y).reshape((num_mtx,m,m))
max_err = 0.0
Id = np.identity(m)
for i in range(num_mtx):
M = mat[i]
Mi = imat[i]
v = M @ Mi
err = np.max(np.abs(v - Id))
if err > max_err:
max_err = err
if not np.isfinite(err):
max_err = 1e10
if max_err < 0.025:
print("Success!")
with open("flag.txt", "r") as f:
flag = f.read()
print(flag)
else:
print("Too much error!")
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/DiceCTF/2023/crypto/seaside/seaside.py | ctfs/DiceCTF/2023/crypto/seaside/seaside.py | #!/usr/local/bin/python
import ctypes
import os
from Crypto.Util.strxor import strxor
from Crypto.Hash import SHAKE128
PRIVATE_KEY_SIZE = 74
PUBLIC_KEY_SIZE = 64
# make libcsidh.so
libcsidh = ctypes.CDLL('./libcsidh.so')
def stream(buf, ss):
pad = SHAKE128.new(bytes(ss)).read(len(buf))
return strxor(buf, pad)
def keygen():
priv = ctypes.create_string_buffer(PRIVATE_KEY_SIZE)
pub = ctypes.create_string_buffer(PUBLIC_KEY_SIZE)
libcsidh.csidh_private(priv)
libcsidh.csidh(pub, libcsidh.base, priv)
return priv, pub
def apply_iso(start, iso):
end = ctypes.create_string_buffer(PUBLIC_KEY_SIZE)
libcsidh.csidh(end, start, iso)
return end
def invert(priv):
exponents = [-e % 256 for e in bytes(priv)]
return ctypes.create_string_buffer(bytes(exponents))
class Alice:
def __init__(self, msg0, msg1):
assert type(msg0) == bytes
assert type(msg1) == bytes
assert len(msg0) == len(msg1)
self.msg0 = msg0
self.msg1 = msg1
self.priv0, self.pub0 = keygen()
self.priv1, self.pub1 = keygen()
def publish(self):
return self.pub0, self.pub1
def encrypt(self, mask):
ss0 = apply_iso(mask, invert(self.priv0))
ss1 = apply_iso(mask, invert(self.priv1))
enc0 = stream(self.msg0, ss0)
enc1 = stream(self.msg1, ss1)
return enc0, enc1
class Bob:
def __init__(self, bit):
assert bit in (0, 1)
self.bit = bit
self.iso, self.ss = keygen()
def query(self, pubs):
pub = pubs[self.bit]
mask = apply_iso(pub, self.iso)
return mask
def decrypt(self, encs):
enc = encs[self.bit]
msg = stream(enc, self.ss)
return msg
if __name__ == '__main__':
with open('flag.txt', 'rb') as f:
flag = f.read().strip()
msg0 = os.urandom(len(flag))
msg1 = strxor(msg0, flag)
alice = Alice(msg0, msg1)
pub0, pub1 = alice.publish()
print(f'pub0: {bytes(pub0).hex()}')
print(f'pub1: {bytes(pub1).hex()}')
'''
bob = Bob(bit)
mask = bob.query((pub0, pub1))
'''
mask_hex = input('mask: ')
mask = ctypes.create_string_buffer(bytes.fromhex(mask_hex), PUBLIC_KEY_SIZE)
enc0, enc1 = alice.encrypt(mask)
print(f'enc0: {enc0.hex()}')
print(f'enc1: {enc1.hex()}')
'''
msg = bob.decrypt((enc0, enc1))
'''
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/DiceCTF/2023/crypto/ProvablySecure/server.py | ctfs/DiceCTF/2023/crypto/ProvablySecure/server.py | #!/usr/local/bin/python
# Normally you have unlimited encryption and decryption query requests in the IND-CCA2 game.
# For performance reasons, my definition of unlimited is 8 lol
from cryptography.hazmat.primitives.asymmetric import rsa, padding
from cryptography.hazmat.primitives import hashes
from secrets import randbits
from os import urandom
from Crypto.Util.strxor import strxor
def encrypt(pk0, pk1, msg):
r = urandom(16)
r_prime = strxor(r, msg)
ct0 = pk0.encrypt(r, padding.OAEP(mgf=padding.MGF1(algorithm=hashes.SHA256()),
algorithm=hashes.SHA256(), label=None))
ct1 = pk1.encrypt(r_prime, padding.OAEP(mgf=padding.MGF1(algorithm=hashes.SHA256()),
algorithm=hashes.SHA256(), label=None))
return ct0.hex() + ct1.hex()
def decrypt(key0, key1, ct):
ct0 = ct[:256]
ct1 = ct[256:]
r0 = key0.decrypt(ct0, padding.OAEP(mgf=padding.MGF1(algorithm=hashes.SHA256()),
algorithm=hashes.SHA256(), label=None))
r1 = key1.decrypt(ct1, padding.OAEP(mgf=padding.MGF1(algorithm=hashes.SHA256()),
algorithm=hashes.SHA256(), label=None))
return strxor(r0, r1)
if __name__ == '__main__':
print("""Actions:
0) Solve
1) Query Encryption
2) Query Decryption
""")
for experiment in range(1, 129):
print("Experiment {}/128".format(experiment))
key0 = rsa.generate_private_key(public_exponent=65537, key_size=2048)
key1 = rsa.generate_private_key(public_exponent=65537, key_size=2048)
pk0 = key0.public_key()
pk1 = key1.public_key()
print("pk0 =", pk0.public_numbers().n)
print("pk1 =", pk1.public_numbers().n)
m_bit = randbits(1)
seen_ct = set()
en_count = 0
de_count = 0
while True:
choice = int(input("Action: "))
if choice == 0:
guess = int(input("m_bit guess: "))
if (guess == m_bit):
print("Correct!")
break
else:
print("Wrong!")
exit(0)
elif choice == 1:
en_count += 1
if (en_count > 8):
print("You've run out of encryptions!")
exit(0)
m0 = bytes.fromhex(input("m0 (16 byte hexstring): ").strip())
m1 = bytes.fromhex(input("m1 (16 byte hexstring): ").strip())
if len(m0) != 16 or len(m1) != 16:
print("Must be 16 bytes!")
exit(0)
msg = m0 if m_bit == 0 else m1
ct = encrypt(pk0, pk1, msg)
seen_ct.add(ct)
print(ct)
elif choice == 2:
de_count += 1
if (de_count > 8):
print("You've run out of decryptions!")
exit(0)
in_ct = bytes.fromhex(input("ct (512 byte hexstring): ").strip())
if len(in_ct) != 512:
print("Must be 512 bytes!")
exit(0)
if in_ct in seen_ct:
print("Cannot query decryption on seen ciphertext!")
exit(0)
print(decrypt(key0, key1, in_ct).hex())
with open('flag.txt', 'r') as f:
print("Flag: " + f.read().strip()) | python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/DiceCTF/2023/crypto/rSabin/challenge.py | ctfs/DiceCTF/2023/crypto/rSabin/challenge.py | import asyncio
import concurrent.futures
import traceback
from Crypto.Util.number import getPrime, bytes_to_long
from Crypto.Cipher import PKCS1_OAEP
from Crypto.PublicKey import RSA
from nth_root import nth_root, chinese_remainder # not provided
class Server:
def __init__(self):
e = 17
nbits = 512
p = getPrime(nbits)
q = getPrime(nbits)
N = p * q
self.p = p
self.q = q
self.N = N
self.e = e
def encrypt(self, m):
assert 0 <= m < self.N
c = pow(m, self.e, self.N)
return int(c)
def decrypt(self, c):
assert 0 <= c < self.N
mp = int(nth_root(c, self.p, self.e))
mq = int(nth_root(c, self.q, self.e))
m = chinese_remainder([mp, mq], [self.p, self.q])
return int(m)
def encrypt_flag(self):
with open("flag.txt", "rb") as f:
flag = f.read()
key = RSA.construct((self.N, self.e))
cipher = PKCS1_OAEP.new(key)
c = cipher.encrypt(flag)
c = bytes_to_long(c)
return c
async def handle(a):
S = await a.run(Server)
while True:
cmd = (await a.input("Enter your option (EDF) > ")).strip()
if cmd == "E":
m = int(await a.input("Enter your integer to encrypt > "))
c = await a.run(S.encrypt, m)
await a.print(str(c) + '\n')
elif cmd == "D":
c = int(await a.input("Enter your integer to decrypt > "))
m = await a.run(S.decrypt, c)
await a.print(str(m) + '\n')
elif cmd == "F":
c = await a.run(S.encrypt_flag)
await a.print(str(c) + '\n')
return
class Handler:
def __init__(self, reader, writer, pool):
self.reader = reader
self.writer = writer
self.pool = pool
async def print(self, data):
self.writer.write(str(data).encode())
await self.writer.drain()
async def input(self, prompt):
await self.print(prompt)
return (await self.reader.readline()).decode()
async def run(self, func, *args):
loop = asyncio.get_running_loop()
return await loop.run_in_executor(self.pool, func, *args)
async def __aenter__(self):
return self
async def __aexit__(self, exc_t, exc_v, exc_tb):
self.writer.close()
await self.writer.wait_closed()
if exc_v is not None and not isinstance(exc_v, asyncio.TimeoutError):
traceback.print_exception(exc_v)
return True
async def main():
with concurrent.futures.ProcessPoolExecutor() as pool:
async def callback(reader, writer):
async with Handler(reader, writer, pool) as a:
await asyncio.wait_for(handle(a), 20)
server = await asyncio.start_server(callback, '0.0.0.0', 5000)
print('listening')
async with server:
await server.serve_forever()
if __name__ == "__main__":
asyncio.run(main())
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/DiceCTF/2023/crypto/BBBB/bbbb.py | ctfs/DiceCTF/2023/crypto/BBBB/bbbb.py | #!/usr/local/bin/python
from Crypto.Util.number import bytes_to_long, getPrime
from random import randint
from math import gcd
from os import urandom
def generate_key(rng, seed):
e = rng(seed)
while True:
for _ in range(randint(10,100)):
e = rng(e)
p = getPrime(1024)
q = getPrime(1024)
phi = (p-1)*(q-1)
if gcd(e, phi) == 1:
break
n = p*q
return (n, e)
def generate_params():
p = getPrime(1024)
b = randint(0, p-1)
return (p,b)
def main():
p,b = generate_params()
print("[+] The parameters of RNG:")
print(f"{b=}")
print(f"{p=}")
a = int(input("[+] Inject b[a]ckdoor!!: "))
rng = lambda x: (a*x + b) % p
keys = []
seeds = []
for i in range(5):
seed = int(input("[+] Please input seed: "))
seed %= p
if seed in seeds:
print("[!] Same seeds are not allowed!!")
exit()
seeds.append(seed)
n, e = generate_key(rng, seed)
if e <= 10:
print("[!] `e` is so small!!")
exit()
keys.append((n,e))
FLAG = open("flag.txt", "rb").read()
assert len(FLAG) < 50
FLAG = FLAG + urandom(4)
for n,e in keys:
r = urandom(16)
flag = bytes_to_long(FLAG + r)
c = pow(flag, e, n)
r = r.hex()
print("[+] Public Key:")
print(f"{n=}")
print(f"{e=}")
print(f"{r=}")
print("[+] Cipher Text:", c)
if __name__ == "__main__":
main() | python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/DiceCTF/2023/crypto/ProvablySecure2/server.py | ctfs/DiceCTF/2023/crypto/ProvablySecure2/server.py | #!/usr/local/bin/python
# Normally you have unlimited encryption and decryption query requests in the IND-CCA2 game.
# For performance reasons, my definition of unlimited is 8 lol
from cryptography.hazmat.primitives.asymmetric import rsa, padding
from cryptography.hazmat.primitives import hashes
from secrets import randbits
from os import urandom
from Crypto.Util.strxor import strxor
def encrypt(pk0, pk1, msg):
r = urandom(16)
r_prime = strxor(r, msg)
ct0 = pk0.encrypt(r, padding.OAEP(mgf=padding.MGF1(algorithm=hashes.SHA256()),
algorithm=hashes.SHA256(), label=None))
ct1 = pk1.encrypt(r_prime, padding.OAEP(mgf=padding.MGF1(algorithm=hashes.SHA256()),
algorithm=hashes.SHA256(), label=None))
return ct0.hex() + ct1.hex()
def decrypt(key0, key1, ct):
ct0 = ct[:256]
ct1 = ct[256:]
r0 = key0.decrypt(ct0, padding.OAEP(mgf=padding.MGF1(algorithm=hashes.SHA256()),
algorithm=hashes.SHA256(), label=None))
r1 = key1.decrypt(ct1, padding.OAEP(mgf=padding.MGF1(algorithm=hashes.SHA256()),
algorithm=hashes.SHA256(), label=None))
return strxor(r0, r1)
if __name__ == '__main__':
print("""Actions:
0) Solve
1) Query Encryption
2) Query Decryption
""")
for experiment in range(1, 129):
print("Experiment {}/128".format(experiment))
key0 = rsa.generate_private_key(public_exponent=65537, key_size=2048)
key1 = rsa.generate_private_key(public_exponent=65537, key_size=2048)
pk0 = key0.public_key()
pk1 = key1.public_key()
print("pk0 =", pk0.public_numbers().n)
print("pk1 =", pk1.public_numbers().n)
m_bit = randbits(1)
seen_ct = set()
en_count = 0
de_count = 0
while True:
choice = int(input("Action: "))
if choice == 0:
guess = int(input("m_bit guess: "))
if (guess == m_bit):
print("Correct!")
break
else:
print("Wrong!")
exit(0)
elif choice == 1:
en_count += 1
if (en_count > 8):
print("You've run out of encryptions!")
exit(0)
m0 = bytes.fromhex(input("m0 (16 byte hexstring): ").strip())
m1 = bytes.fromhex(input("m1 (16 byte hexstring): ").strip())
if len(m0) != 16 or len(m1) != 16:
print("Must be 16 bytes!")
exit(0)
msg = m0 if m_bit == 0 else m1
ct = encrypt(pk0, pk1, msg)
seen_ct.add(ct)
print(ct)
elif choice == 2:
de_count += 1
if (de_count > 8):
print("You've run out of decryptions!")
exit(0)
in_ct = bytes.fromhex(input("ct (512 byte hexstring): ").strip())
if len(in_ct) != 512:
print("Must be 512 bytes!")
exit(0)
if in_ct.hex() in seen_ct:
print("Cannot query decryption on seen ciphertext!")
exit(0)
print(decrypt(key0, key1, in_ct).hex())
with open('flag.txt', 'r') as f:
print("Flag: " + f.read().strip()) | python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/DiceCTF/2025/Quals/misc/cppickle/cppickle.py | ctfs/DiceCTF/2025/Quals/misc/cppickle/cppickle.py | #!/usr/bin/python3
import torch
import io
b = bytes.fromhex(input("> "))
assert b[4:8] != b"PTMF"
torch.jit.load(io.BytesIO(b))
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/DiceCTF/2025/Quals/pwn/debugapwner/server.py | ctfs/DiceCTF/2025/Quals/pwn/debugapwner/server.py | #!/usr/bin/env python3
import base64
import sys
import subprocess
def main():
elf_path = "/tmp/elf"
try:
elf_data = base64.b64decode(input("Please provide base64 encoded ELF: "))
with open(elf_path, "wb") as f:
f.write(elf_data)
subprocess.run(["/dwarf", elf_path])
except Exception as e:
print(f"Error: {e}")
sys.exit(1)
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/DiceCTF/2025/Quals/crypto/winxy_pistol/server.py | ctfs/DiceCTF/2025/Quals/crypto/winxy_pistol/server.py | #!/usr/local/bin/python
import hashlib
import secrets
from Crypto.PublicKey import RSA
from Crypto.Util.strxor import strxor
DEATH_CAUSES = [
'a fever',
'dysentery',
'measles',
'cholera',
'typhoid',
'exhaustion',
'a snakebite',
'a broken leg',
'a broken arm',
'drowning',
]
def encrypt(k, msg):
key = k.to_bytes(1024//8, 'big')
msg = msg.encode().ljust(64, b'\x00')
pad = hashlib.shake_256(key).digest(len(msg))
return strxor(pad, msg)
def run_ot(key, msg0, msg1):
'''
https://en.wikipedia.org/wiki/Oblivious_transfer#1–2_oblivious_transfer
'''
x0 = secrets.randbelow(key.n)
x1 = secrets.randbelow(key.n)
print(f'n: {key.n}')
print(f'e: {key.e}')
print(f'x0: {x0}')
print(f'x1: {x1}')
v = int(input('v: '))
assert 0 <= v < key.n, 'invalid value'
k0 = pow(v - x0, key.d, key.n)
k1 = pow(v - x1, key.d, key.n)
c0 = encrypt(k0, msg0)
c1 = encrypt(k1, msg1)
print(f'c0: {c0.hex()}')
print(f'c1: {c1.hex()}')
if __name__ == '__main__':
with open('flag.txt') as f:
flag = f.read().strip()
with open('key.pem', 'rb') as f:
key = RSA.import_key(f.read())
print('=== CHOOSE YOUR OWN ADVENTURE: Winxy Pistol Edition ===')
print('you enter a cave.')
for _ in range(64):
print('the tunnel forks ahead. do you take the left or right path?')
msgs = [None, None]
page = secrets.randbits(32)
live = f'you continue walking. turn to page {page}.'
die = f'you die of {secrets.choice(DEATH_CAUSES)}.'
msgs = (live, die) if secrets.randbits(1) else (die, live)
run_ot(key, *msgs)
page_guess = int(input('turn to page: '))
if page_guess != page:
exit()
print(f'you find a chest containing {flag}')
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/DiceCTF/2025/Quals/crypto/satisfied/hamiltonicity.py | ctfs/DiceCTF/2025/Quals/crypto/satisfied/hamiltonicity.py | # this file is identical to the one found at https://github.com/cryptohack/ctf_archive/blob/main/ch2024-sigma-hamiltonicity/server_files/hamiltonicity.py
# apart from the parameters (P, q, h1, h2) used for the commitment scheme
import random
from hashlib import sha256
P = 0x1a91c7e50ef774ab758fa1a8aebfaa9f5fcc3cf22e3b419e5197c5268b1c883f01fbba85de35f1ae1d2544a977dc858a846e6c86f7ff0653881d1e43dbfc535fa3f606cf8f95fb0a53d75dc96de29af01c6967b947b0bf2c1232257d1d9d066036acf3648a54248904f3fdb360debbedab5e58ba7a19308c2a25ad63376044677
q = 0xd48e3f2877bba55bac7d0d4575fd54fafe61e79171da0cf28cbe293458e441f80fddd42ef1af8d70e92a254bbee42c5423736437bff8329c40e8f21edfe29afd1fb0367c7cafd8529ebaee4b6f14d780e34b3dca3d85f96091912be8ece83301b5679b2452a12448279fed9b06f5df6d5af2c5d3d0c98461512d6b19bb02233b
# Generate `h1,h2` to be a random element Z_P of order q
# Unknown dlog relation is mask for the Pedersen Commitment
# Hardcoded a random `h1,h2` value for ease of use
# h1 = pow(random.randint(2,P-1),2,P)
# h2 = pow(random.randint(2,P-1),2,P)
h1 = 78777458529900494490614837925133899234033382878031882472334088956271190982992006579121996363436837622269937515963969631350196078518833552064350879178135378664181885312653105871452865514975911372301003349338291198633437687325826425425608673730990839066457483305538373645745058807876087476862601690892691176886
h2 = 79543261289463851669680579732622963629972939196770858598613223074429180846489223401875297929962046462819170352455602650818571522306298694684743021001523247847054210636909249854011863258940228182916282685739437065475409404546810221793296109200612655318070086567712704167633234254449463709961905778271868952583
comm_params = P,q,h1,h2
# Information theoretically hiding commitment scheme
def pedersen_commit(message, pedersen_params = comm_params):
P,q,h1,h2 = pedersen_params
r = random.randint(0,q)
commitment = (pow(h1,message,P) * pow(h2,r,P)) % P
return commitment, r
def pedersen_open(commitment,message,r, pedersen_params = comm_params):
P,q,h1,h2 = pedersen_params
if (commitment * pow(h1,-message,P) * pow(h2,-r,P) ) % P == 1:
return True
else:
return False
# Given a graph, return an element-wise commitment to the graph
def commit_to_graph(G,N):
G2 = [[0 for _ in range(N)] for _ in range(N)]
openings = [[0 for _ in range(N)] for _ in range(N)]
for i in range(N):
for j in range(N):
v = G[i][j]
comm, r = pedersen_commit(v)
assert pedersen_open(comm,v,r)
G2[i][j] = comm
openings[i][j] = [v,r]
return G2, openings
def check_graph(G,N):
assert len(G) == N, "G has wrong size"
for r in G:
assert len(r) == N, "G has wrong size"
return True
# Takes a commitment to a graph, and opens all the commitments to reveal the graph
def open_graph(G2,N, openings):
G = [[0 for _ in range(N)] for _ in range(N)]
for i in range(N):
for j in range(N):
v = G2[i][j]
m,r = openings[i][j]
assert pedersen_open(v, m, r)
G[i][j] = m
return G
# Takes a commitment to a graph, and a claimed set of entries which should open a hamiltonian cycle
# Returns True if the opened nodes form a hamiltonian cycle
def testcycle(graph, N, nodes, openings):
assert len(nodes) == N
from_list = [n[0] for n in nodes]
to_list = [n[1] for n in nodes]
for i in range(N):
assert i in from_list
assert i in to_list
assert nodes[i][1] == nodes[(i+1)%N][0]
for i in range(N):
src,dst = nodes[i]
r = openings[i]
# print(f'trying to open {src}->{dst} {r} {graph[src][dst]}')
assert pedersen_open(graph[src][dst], 1, r)
return True
# Given a graph, and a permutation, shuffle the graph using the permutation
def permute_graph(G, N, permutation):
G_permuted = [[G[permutation[i]][permutation[j]] for j in range(N)] for i in range(N)]
return G_permuted
# given a set of commitment private values, and a subset of these indexes
# return a vector of the randomness needed to open the commitments.
def get_r_vals(openings,N, cycle):
rvals = []
for x in cycle:
m,r = openings[x[0]][x[1]]
rvals.append(r)
return rvals
# Iterated Fiat Shamir, take previous state and current graph
def hash_committed_graph(G, state, comm_params):
fs_state = sha256(str(comm_params).encode())
fs_state.update(state)
first_message = "".join([str(x) for xs in G for x in xs])
fs_state.update(first_message.encode())
iterated_state = fs_state.digest()
return iterated_state
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/DiceCTF/2025/Quals/crypto/satisfied/server.py | ctfs/DiceCTF/2025/Quals/crypto/satisfied/server.py | #!/usr/local/bin/python
from hamiltonicity import pedersen_commit, pedersen_open
from hamiltonicity import open_graph, permute_graph
from hamiltonicity import testcycle, check_graph
from hamiltonicity import comm_params
import json
import random
FLAG = open("flag.txt").read()
numrounds = 128
N = 5
payload = json.loads(input("send graph G: "))
G = payload["G"]
check_graph(G, N)
# how are you going to have a hamiltonian cycle if there aren't even enough edges in the graph :3c
if not all(g in [0, 1] for g_ in G for g in g_):
print("this graph doesn't look quite right...")
exit()
if not sum([g for g_ in G for g in g_]) < N:
print("hey, that's too many edges in your graph...")
exit()
print(f'now, prove that G has a hamiltonian cycle!')
for i in range(numrounds):
print(f"round {i + 1}")
payload = json.loads(input("send commitment A: "))
A = payload["A"]
check_graph(A,N)
challenge = random.randint(0, 1)
print(f"challenge bit is {challenge}")
payload = json.loads(input("send proof z: "))
z = payload["z"]
# Challenge bit is 1:
# You should open the hamiltonian path
# z = [cycle, openings of cycle]
if challenge:
cycle, openings = z
if not testcycle(A, N, cycle, openings):
print("i'm not satisfied with your proof...")
exit()
# challenge bit is 0:
# you should show permutation and open everything
# z = [permutation, openings of everything]
else:
permutation, openings = z
G_permuted = open_graph(A, N, openings)
G_test = permute_graph(G, N, permutation)
if G_permuted != G_test:
print("i'm not satisfied with your proof...")
exit()
print("okay, i'm satisfied now... have your flag")
print(FLAG) | python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/DiceCTF/2025/Quals/crypto/vorpal_sword/server.py | ctfs/DiceCTF/2025/Quals/crypto/vorpal_sword/server.py | #!/usr/local/bin/python
import secrets
from Crypto.PublicKey import RSA
DEATH_CAUSES = [
'a fever',
'dysentery',
'measles',
'cholera',
'typhoid',
'exhaustion',
'a snakebite',
'a broken leg',
'a broken arm',
'drowning',
]
def run_ot(key, msg0, msg1):
'''
https://en.wikipedia.org/wiki/Oblivious_transfer#1–2_oblivious_transfer
'''
x0 = secrets.randbelow(key.n)
x1 = secrets.randbelow(key.n)
print(f'n: {key.n}')
print(f'e: {key.e}')
print(f'x0: {x0}')
print(f'x1: {x1}')
v = int(input('v: '))
assert 0 <= v < key.n, 'invalid value'
k0 = pow(v - x0, key.d, key.n)
k1 = pow(v - x1, key.d, key.n)
m0 = int.from_bytes(msg0.encode(), 'big')
m1 = int.from_bytes(msg1.encode(), 'big')
c0 = (m0 + k0) % key.n
c1 = (m1 + k1) % key.n
print(f'c0: {c0}')
print(f'c1: {c1}')
if __name__ == '__main__':
with open('flag.txt') as f:
flag = f.read().strip()
print('=== CHOOSE YOUR OWN ADVENTURE: Vorpal Sword Edition ===')
print('you enter a cave.')
for _ in range(64):
print('the tunnel forks ahead. do you take the left or right path?')
key = RSA.generate(1024)
msgs = [None, None]
page = secrets.randbits(32)
live = f'you continue walking. turn to page {page}.'
die = f'you die of {secrets.choice(DEATH_CAUSES)}.'
msgs = (live, die) if secrets.randbits(1) else (die, live)
run_ot(key, *msgs)
page_guess = int(input('turn to page: '))
if page_guess != page:
exit()
print(f'you find a chest containing {flag}')
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/DiceCTF/2022/rev/hyperlink/app.py | ctfs/DiceCTF/2022/rev/hyperlink/app.py | import json
def test_chain(links, start, end):
current = start
for link in links:
current = int(''.join(
str(int(current & component != 0))
for component in link
), 2)
return end == current & end
def main():
try:
with open('hyperlink.json', 'r') as f:
data = json.load(f)
except IOError:
print('Could not open hyperlink.json')
return
print('Welcome to the chain building game.')
print('Enter a chain and see if it works:')
chain = input()
legal_chars = set('abcdefghijklmnopqrstuvwxyz{}_')
if any(c not in legal_chars for c in chain):
print('Chain contains illegal characters!')
return
try:
links = [data['links'][c] for c in chain]
result = test_chain(links, data['start'], data['target'])
except Exception:
print('Something went wrong!')
return
if result:
print('Chain works! Congratulations.')
else:
print('Oh no! Chain does not reach the target.')
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/DiceCTF/2022/crypto/correlated/correlated.py | ctfs/DiceCTF/2022/crypto/correlated/correlated.py | #!/usr/local/bin/python
import secrets
class LFSR:
def __init__(self, key, taps):
self._s = key
self._t = taps
def _sum(self, L):
s = 0
for x in L:
s ^= x
return s
def _clock(self):
b = self._s[0]
self._s = self._s[1:] + [self._sum(self._s[p] for p in self._t)]
return b
def bit(self):
return self._clock()
taps = [45, 40, 39, 36, 35, 34, 33, 32, 30, 28, 27, 23, 22, 21, 19, 17, 16, 15, 14, 13, 9, 7, 3, 0]
n = 48
m = 20000
prob = 0.80
delta = 1048576
with open("flag.txt", "r") as f:
flag = f.read()
if __name__ == "__main__":
print("I heard that fast correlation attacks don't work if your LFSR has more than 10 taps.")
print("You have 60 seconds to recover the key.")
key = secrets.randbits(n)
key_bits = [(key >> i)&1 for i in range(n)]
lfsr = LFSR(key_bits, taps)
stream = [lfsr.bit() for _ in range(m)]
noise = [secrets.randbelow(delta) > prob * delta for i in stream]
stream = [i ^ j for i,j in zip(noise, stream)]
print("Here are {} bits of the stream with {}% accuracy".format(m, 100 * prob))
print(int("".join(map(str, stream)), 2))
seed = int(input("what is my key?"))
if seed == key:
print(flag)
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/DiceCTF/2022/crypto/psych/psych.py | ctfs/DiceCTF/2022/crypto/psych/psych.py | #!/usr/local/bin/python
import secrets
import sys
from hashlib import scrypt, shake_256
from sibc.sidh import SIDH, default_parameters
sidh = SIDH(**default_parameters)
xor = lambda x, y: bytes(map(int.__xor__, x, y))
H = lambda x: shake_256(x).digest(16)
G = lambda x: shake_256(x).digest((3**sidh.strategy.three).bit_length() // 8)
def is_equal(x, y):
# let's simulate a timing attack!
c = secrets.randbelow(64)
equal = True
for a, b in zip(x, y):
c += 1
if a != b:
equal = False
break
print(f'took {c} units of time')
return equal
class KEM:
def __init__(self, pk, sk=None):
self.pk = pk
self.sk = sk
@classmethod
def generate(cls):
sk, pk = sidh.keygen_a()
sk += secrets.token_bytes(16)
return cls(pk, sk)
def _encrypt(self, m, r):
c0 = sidh.public_key_b(r)
j = sidh.dh_b(r, self.pk)
h = H(j)
c1 = xor(h, m)
return c0, c1
def _decrypt(self, c0, c1):
j = sidh.dh_a(self.sk[:-16], c0)
h = H(j)
m = xor(h, c1)
return m
def encapsulate(self):
m = secrets.token_bytes(16)
r = G(m + self.pk)
c0, c1 = self._encrypt(m, r)
ct = c0 + c1
ss = H(m + ct)
return ct, ss
def decapsulate(self, ct):
if self.sk is None:
raise ValueError('no private key')
if len(ct) != 6*sidh.p_bytes + 16:
raise ValueError('malformed ciphertext')
m = self._decrypt(ct[:-16], ct[-16:])
r = G(m + self.pk)
c0 = sidh.public_key_b(r)
if is_equal(c0, ct[:-16]):
ss = H(m + ct)
else:
ss = H(self.sk[-16:] + ct)
return ss
if __name__ == '__main__':
if len(sys.argv) > 1 and sys.argv[1] == 'init':
kem = KEM.generate()
with open('pk.bin', 'wb') as f:
f.write(kem.pk)
with open('sk.bin', 'wb') as f:
f.write(kem.sk)
with open('flag.txt', 'rb') as f:
flag = f.read().strip()
with open('flag.enc', 'wb') as f:
key = scrypt(kem.sk[:-16], salt=b'defund', n=1048576, r=8, p=1, maxmem=1073744896, dklen=len(flag))
f.write(xor(key, flag))
exit()
with open('pk.bin', 'rb') as f:
pk = f.read()
with open('sk.bin', 'rb') as f:
sk = f.read()
kem = KEM(pk, sk=sk)
ct = bytes.fromhex(input('ct (hex): '))
print('decapsulating...')
ss = kem.decapsulate(ct)
print(f'ss (hex): {ss.hex()}')
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/DiceCTF/2022/crypto/baby-rsa/generate.py | ctfs/DiceCTF/2022/crypto/baby-rsa/generate.py | from Crypto.Util.number import getPrime, bytes_to_long, long_to_bytes
def getAnnoyingPrime(nbits, e):
while True:
p = getPrime(nbits)
if (p-1) % e**2 == 0:
return p
nbits = 128
e = 17
p = getAnnoyingPrime(nbits, e)
q = getAnnoyingPrime(nbits, e)
flag = b"dice{???????????????????????}"
N = p * q
cipher = pow(bytes_to_long(flag), e, N)
print(f"N = {N}")
print(f"e = {e}")
print(f"cipher = {cipher}")
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/DiceCTF/2022/crypto/shibari/obfuscate.py | ctfs/DiceCTF/2022/crypto/shibari/obfuscate.py | """
if you can't get the python module to work,
this script is basically equivalent to the C++ file
crag-python/BraidGroup/main/ireland.cpp
"""
# https://github.com/the-entire-country-of-ireland/crag-python
import fast_braids
def load_braid(filename):
with open(filename, "r") as f:
data = f.read()
data = data.strip(" ")
data = data.split(" ")
data = [int(i) for i in data]
return fast_braids.createBraid(data)
def save_braid(braid, filename):
res = braid.toVector()
with open(filename, "w") as f:
r = [str(i) for i in res]
s = " ".join(r)
f.write(s)
def save_LNF(LNF, filename):
e = LNF.getHalfTwistExponent()
Ps = LNF.getPermutations()
with open(filename, "w") as f:
s = repr((e, Ps))
f.write(s)
N = 136
def process(i):
print("")
print(i)
fn_base = f"{i}.txt"
braid = load_braid("raw_braids/" + fn_base)
LNF = fast_braids.LNF(braid, N)
print("computed LNF")
obf_braid = LNF.getBraid()
save_braid(obf_braid, "obfuscated_braids/" + fn_base)
print("computed obfuscated braid")
for i in range(6):
process(i)
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/DiceCTF/2022/crypto/commitment-issues/scheme.py | ctfs/DiceCTF/2022/crypto/commitment-issues/scheme.py | from random import randrange
from Crypto.Util.number import getPrime, inverse, bytes_to_long, GCD
flag = b'dice{?????????????????????????}'
n = 5
def get_prime(n, b):
p = getPrime(b)
while GCD(p - 1, n) != 1:
p = getPrime(b)
return p
p = get_prime(n, 1024)
q = get_prime(n, 1024)
N = p*q
phi = (p - 1)*(q - 1)
e = 0xd4088c345ced64cbbf8444321ef2af8b
d = inverse(e, phi)
def sign(message):
m = bytes_to_long(message)
return pow(m, d, N)
def commit(s, key, n):
return (s + key) % N, pow(key, n, N)
def reveal(c1, c2, key, n):
assert pow(key, n, N) == c2
return (c1 - key) % N
r = randrange(1, N)
s = sign(flag)
c1, c2 = commit(s, r, n)
print(f'N = {hex(N)}')
print(f'c1 = {hex(c1)}')
print(f'c2 = {hex(c2)}') | python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/DiceCTF/2022/crypto/rejected/rejected.py | ctfs/DiceCTF/2022/crypto/rejected/rejected.py | #!/usr/local/bin/python
import secrets
class LFSR:
def __init__(self, key, taps):
self._s = key
self._t = taps
def _sum(self, L):
s = 0
for x in L:
s ^= x
return s
def _clock(self):
b = self._s[0]
self._s = self._s[1:] + [self._sum(self._s[p] for p in self._t)]
return b
def bit(self):
return self._clock()
class RNG:
def __init__(self, lfsr, N, nbits):
self.lfsr = lfsr
self.N = N
self.nbits = nbits
if not (pow(2, 27) < N < pow(2, 31)):
raise ValueError("modulus is too big or small")
K = pow(2, nbits) // N
self.cutoff = K * N
def get_random_nbit_integer(self):
res = 0
for i in range(self.nbits):
res += self.lfsr.bit() << i
return res
def get_random_integer_modulo_N(self):
count = 1
while True:
x = self.get_random_nbit_integer()
if x < self.cutoff:
return x % self.N, count
count += 1
taps = [60, 58, 54, 52, 48, 47, 45, 43, 38, 36, 32, 28, 22, 21, 13, 9, 8, 5, 2, 0]
n = 64
with open("flag.txt", "r") as f:
flag = f.read()
if __name__ == "__main__":
print("Welcome to the unbiased random number factory!")
N = int(input("What modulus would you like to use? Choose between 2^27 and 2^31: "))
key = secrets.randbits(n)
key_bits = [(key >> i)&1 for i in range(n)]
lfsr = LFSR(key_bits, taps)
rng = RNG(lfsr, N, 32)
for _ in range(1024):
c = input("Enter your command (R,F): ")
if c.startswith("R"):
x,t = rng.get_random_integer_modulo_N()
print("creating this random number took {} attempts".format(t))
elif c.startswith("F"):
seed = int(input("what was my seed?"))
if seed == key:
print(flag)
exit(0)
else:
print("unsupported command")
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/DiceCTF/2022/crypto/pow-pow/pow-pow.py | ctfs/DiceCTF/2022/crypto/pow-pow/pow-pow.py | #!/usr/local/bin/python
from hashlib import shake_128
# from Crypto.Util.number import getPrime
# p = getPrime(1024)
# q = getPrime(1024)
# n = p*q
n = 20074101780713298951367849314432888633773623313581383958340657712957528608477224442447399304097982275265964617977606201420081032385652568115725040380313222774171370125703969133604447919703501504195888334206768326954381888791131225892711285554500110819805341162853758749175453772245517325336595415720377917329666450107985559621304660076416581922028713790707525012913070125689846995284918584915707916379799155552809425539923382805068274756229445925422423454529793137902298882217687068140134176878260114155151600296131482555007946797335161587991634886136340126626884686247248183040026945030563390945544619566286476584591
T = 2**64
def is_valid(x):
return type(x) == int and 0 < x < n
def encode(x):
return x.to_bytes(256, 'big')
def H(g, h):
return int.from_bytes(shake_128(encode(g) + encode(h)).digest(16), 'big')
def prove(g):
h = g
for _ in range(T):
h = pow(h, 2, n)
m = H(g, h)
r = 1
pi = 1
for _ in range(T):
b, r = divmod(2*r, m)
pi = pow(pi, 2, n) * pow(g, b, n) % n
return h, pi
def verify(g, h, pi):
assert is_valid(g)
assert is_valid(h)
assert is_valid(pi)
assert g != 1 and g != n - 1
m = H(g, h)
r = pow(2, T, m)
assert h == pow(pi, m, n) * pow(g, r, n) % n
if __name__ == '__main__':
g = int(input('g: '))
h = int(input('h: '))
pi = int(input('pi: '))
verify(g, h, pi)
with open('flag.txt') as f:
print(f.read().strip())
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/DiceCTF/2022/crypto/learning-without-errors/challenge.py | ctfs/DiceCTF/2022/crypto/learning-without-errors/challenge.py | # https://github.com/sarojaerabelli/py-fhe
import sys
sys.path.append("./py-fhe")
from ckks.ckks_decryptor import CKKSDecryptor
from ckks.ckks_encoder import CKKSEncoder
from ckks.ckks_encryptor import CKKSEncryptor
from ckks.ckks_evaluator import CKKSEvaluator
from ckks.ckks_key_generator import CKKSKeyGenerator
from ckks.ckks_parameters import CKKSParameters
import json
class Challenge:
def __init__(self, poly_degree, ciph_modulus):
big_modulus = ciph_modulus**2
scaling_factor = 1 << 30
params = CKKSParameters(poly_degree=poly_degree,
ciph_modulus=ciph_modulus,
big_modulus=big_modulus,
scaling_factor=scaling_factor)
key_generator = CKKSKeyGenerator(params)
public_key = key_generator.public_key
secret_key = key_generator.secret_key
encoder = CKKSEncoder(params)
encryptor = CKKSEncryptor(params, public_key, secret_key)
decryptor = CKKSDecryptor(params, secret_key)
evaluator = CKKSEvaluator(params)
self.poly_degree = poly_degree
self.ciph_modulus = ciph_modulus
self.scaling_factor = scaling_factor
self.secret_key = secret_key
self.encoder = encoder
self.encryptor = encryptor
self.decryptor = decryptor
self.evaluator = evaluator
def encrypt_flag(self):
with open("flag.txt", "rb") as f:
flag = f.read()
n = self.poly_degree//2
flag = int.from_bytes(flag, "big")
flag = f"{flag:0{n}b}"
flag = [float(i) for i in flag]
d = {"real_part": flag,
"imag_part": [0]*n}
ciph = self.encrypt_json(d)
return ciph
def dump_ciphertext(self, ciph):
d = {"c0" : ciph.c0.coeffs,
"c1" : ciph.c1.coeffs,
"poly_degree" : ciph.c0.ring_degree,
"modulus" : ciph.modulus}
return d
def dump_plaintext(self, plain):
d = {"m" : plain.poly.coeffs,
"poly_degree" : plain.poly.ring_degree,
"scaling_factor" : plain.scaling_factor}
return d
def dump_decoded_plaintext(self, plain):
x = [complex(i) for i in plain]
real = [i.real for i in plain]
imag = [i.imag for i in plain]
d = {"real_part": real,
"imag_part": imag}
return d
def decrypt_ciphertext(self, ciph):
plain = self.decryptor.decrypt(ciph)
return plain
def decrypt_and_decode_ciphertext(self, ciph):
plain = self.decryptor.decrypt(ciph)
plain = self.encoder.decode(plain)
return plain
def encrypt_json(self, d):
real = list(d["real_part"])
imag = list(d["imag_part"])
message = [r + 1j * i for r,i in zip(real, imag)]
assert len(message) == self.poly_degree // 2
plain = self.encoder.encode(message, self.scaling_factor)
ciph = self.encryptor.encrypt(plain)
return ciph
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/DiceCTF/2022/crypto/learning-without-errors/server.py | ctfs/DiceCTF/2022/crypto/learning-without-errors/server.py | #!/usr/local/bin/python3
import json
from challenge import Challenge
poly_degree = 1024
ciph_modulus = 1 << 100
print('Please hold, generating keys...', flush=True)
chal = Challenge(poly_degree, ciph_modulus)
print('Welcome to the Encryption-As-A-Service Provider of the Future, powered by the latest in Fully-Homomorphic Encryption!')
data = input('Provide your complex vector as json to be encrypted: ')
data = json.loads(data)
ciph = chal.encrypt_json(data)
string_ciph = json.dumps(chal.dump_ciphertext(ciph))
print('Encryption successful, here is your ciphertext:', string_ciph)
plain = chal.decrypt_ciphertext(ciph)
string_plain = json.dumps(chal.dump_plaintext(plain))
print('To verify that the encryption worked, here is the corresponding decryption:', string_plain)
e_flag = chal.encrypt_flag()
string_flag = json.dumps(chal.dump_ciphertext(e_flag))
print('All done, here\'s an encrypted flag as a reward:', string_flag)
print('Enjoy DiceCTF!')
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/DiceCTF/2022/web/dicevault/dicevault/app.py | ctfs/DiceCTF/2022/web/dicevault/dicevault/app.py | #!/usr/bin/env python3
from flask import Flask
from flask import render_template
from flask import request
from flask_caching import Cache
app = Flask(__name__)
cache = Cache(config={'CACHE_TYPE': 'FileSystemCache', 'CACHE_DIR':'/tmp/vault', 'CACHE_DEFAULT_TIMEOUT': 300})
cache.init_app(app)
@app.after_request
def add_headers(response):
response.headers['Content-Security-Policy'] = "frame-ancestors 'none';"
response.headers['Cache-Control'] = 'no-store'
return response
@app.route("/<path:vault_key>", methods=["GET", "POST"])
def vault(vault_key):
parts = list(filter(lambda s: s.isdigit(), vault_key.split("/")))
level = len(parts)
if level > 15:
return "Too deep", 404
if not cache.get("vault"):
cache.set("vault", {})
main_vault = cache.get("vault")
c = main_vault
for v in parts:
c = c.setdefault(v, {})
values = c.setdefault("values", [])
if level > 8 and request.method == "POST":
value = request.form.get("value")
value = value[0:50]
values.append(value)
cache.set("vault", main_vault)
return render_template("vault.html", values = values, level = level), 404
@app.get("/")
def main():
return render_template("main.html"), 404
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/DiceCTF/2022/web/carrot/code/db.py | ctfs/DiceCTF/2022/web/carrot/code/db.py | import plyvel
import json
import bcrypt
import secrets
import os
import config
db = plyvel.DB('database', create_if_missing=True)
def has(user):
if db.get(user.encode()) is None:
return False
return True
def get(user):
return json.loads(db.get(user.encode()).decode())
def put(user, value):
return db.put(user.encode(), json.dumps(value).encode())
if not has('admin'):
password = config.ADMIN_PASSWORD
put('admin', {
'tasks': [{
'title': 'flag',
'content': os.getenv('FLAG', default='dice{flag}'),
'priority': 1,
'id': 0
}],
'password': bcrypt.hashpw(password.encode(), bcrypt.gensalt()).decode('utf-8')
}) | python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/DiceCTF/2022/web/carrot/code/config.py | ctfs/DiceCTF/2022/web/carrot/code/config.py | import secrets
import os
SECRET_KEY = secrets.token_hex(32)
MAX_CONTENT_LENGTH = 1048576
ADMIN_PASSWORD = os.getenv('ADMIN_PASSWORD', default='default_admin_password') | python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/DiceCTF/2022/web/carrot/code/forms.py | ctfs/DiceCTF/2022/web/carrot/code/forms.py | from wtforms import *
class AccountForm(Form):
username = StringField(validators=[validators.InputRequired()])
password = StringField(validators=[validators.InputRequired()])
class TaskForm(Form):
title = StringField(validators=[validators.InputRequired()])
content = StringField(validators=[validators.InputRequired()])
priority = IntegerField(validators=[validators.InputRequired()])
class EditForm(Form):
title = StringField(validators=[validators.Optional()])
content = StringField(validators=[validators.Optional()])
priority = IntegerField(validators=[validators.Optional()])
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/DiceCTF/2022/web/carrot/code/app.py | ctfs/DiceCTF/2022/web/carrot/code/app.py | import os
import bcrypt
import db
import forms
from werkzeug.middleware.proxy_fix import ProxyFix
from flask import Flask, render_template, request, session, redirect
path = os.path.dirname(os.path.abspath(__file__))
app = Flask(__name__)
app.config.from_pyfile('config.py')
app.template_folder = os.path.join(path, 'templates')
app.static_folder = os.path.join(path, 'static')
@app.route('/')
def home():
if 'username' in session:
return redirect('/tasks')
return render_template('index.html')
@app.route('/login', methods=['POST'])
def login():
form = forms.AccountForm(request.form)
if not form.validate():
return render_template('error.html', message='Invalid login'), 400
username = form.username.data.lower()
if not db.has(username):
return render_template('error.html', message='Invalid login'), 400
user = db.get(username)
if not bcrypt.checkpw(form.password.data.encode(), user['password'].encode()):
return render_template('error.html', message='Invalid login'), 400
session['username'] = username
return redirect('/tasks')
@app.route('/register', methods=['GET', 'POST'])
def register():
if request.method == 'GET':
return render_template('register.html')
elif request.method == 'POST':
form = forms.AccountForm(request.form)
if not form.validate():
return render_template('error.html', message='Invalid registration'), 400
username, password = form.username.data.lower(), form.password.data
if db.has(username):
return render_template('error.html', message='User already exists!'), 400
db.put(username, {
'tasks': [],
'password': bcrypt.hashpw(password.encode(), bcrypt.gensalt()).decode('utf-8')
})
session['username'] = username
return redirect('/tasks')
@app.route('/tasks')
def tasks():
if 'username' not in session:
return redirect('/')
tasks = db.get(session['username'])['tasks']
if 'search' in request.args:
search = request.args['search']
tasks = list(filter(lambda task: search in task['content'], tasks))
tasks = list(sorted(tasks, key=lambda task: -task['priority']))
return render_template('tasks.html', tasks=tasks)
@app.route('/add', methods=['GET', 'POST'])
def add():
if 'username' not in session:
return redirect('/')
if request.method == 'GET':
return render_template('add.html')
elif request.method == 'POST':
form = forms.TaskForm(request.form)
if not form.validate():
return render_template('error.html', message='Invalid task'), 400
user = db.get(session['username'])
if len(user['tasks']) >= 5:
return render_template('error.html', message='Maximum task limit reached!'), 400
task = {
'title': form.title.data,
'content': form.content.data,
'priority': form.priority.data,
'id': len(user['tasks'])
}
user['tasks'].append(task)
db.put(session['username'], user)
return redirect('/tasks')
@app.route('/edit/<task_id>', methods=['GET', 'POST'])
def edit(task_id):
if 'username' not in session:
return redirect('/')
try:
task_id = int(task_id)
except:
return render_template('error.html', message='Invalid task'), 400
user = db.get(session['username'])
task = next((task for task in user['tasks'] if task['id'] == task_id), None)
if task is None:
return render_template('error.html', message='Task not found'), 404
if request.method == 'GET':
return render_template('edit.html', id=task['id'])
elif request.method == 'POST':
form = forms.EditForm(request.form)
if not form.validate():
return render_template('error.html', message='Invalid edit'), 400
for attribute in ['title', 'content', 'priority']:
if form[attribute].data:
task[attribute] = form[attribute].data
db.put(session['username'], user)
return redirect('/tasks')
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/DiceCTF/2022/web/flare/flare.py | ctfs/DiceCTF/2022/web/flare/flare.py | import os
import ipaddress
from flask import Flask, request
from gevent.pywsgi import WSGIServer
app = Flask(__name__)
flag = os.getenv('FLAG', default='dice{flag}')
@app.route('/')
def index():
ip = ipaddress.ip_address(request.headers.get('CF-Connecting-IP'))
if isinstance(ip, ipaddress.IPv4Address) and ip.is_private:
return flag
return f'No flag for {format(ip)}'
WSGIServer(('', 8080), app).serve_forever() | python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/hxp/2021/pwn/audited2/audited.py | ctfs/hxp/2021/pwn/audited2/audited.py | #!/usr/bin/python3 -u
import auditor
import sys
code = compile(sys.stdin.read(), '<user input>', 'exec')
sys.stdin.close()
for module in set(sys.modules.keys()):
if module in sys.modules:
del sys.modules[module]
auditor.activate()
namespace = {}
auditor.exec(code, namespace, namespace)
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/hxp/2021/pwn/audited2/module/setup.py | ctfs/hxp/2021/pwn/audited2/module/setup.py | from distutils.core import setup, Extension
module = Extension('auditor', sources = ['auditor.c'])
setup(name = 'auditor', version = '1.0', description = 'More auditing!', ext_modules = [module])
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/hxp/2021/crypto/gipfel/vuln.py | ctfs/hxp/2021/crypto/gipfel/vuln.py | #!/usr/bin/env python3
from Crypto.Hash import SHA256
from Crypto.Cipher import AES
import signal, random
random = random.SystemRandom()
q = 0x3a05ce0b044dade60c9a52fb6a3035fc9117b307ca21ae1b6577fef7acd651c1f1c9c06a644fd82955694af6cd4e88f540010f2e8fdf037c769135dbe29bf16a154b62e614bb441f318a82ccd1e493ffa565e5ffd5a708251a50d145f3159a5
def enc(a):
f = {str: str.encode, int: int.__str__}.get(type(a))
return enc(f(a)) if f else a
def H(*args):
data = b'\0'.join(map(enc, args))
return SHA256.new(data).digest()
def F(h, x):
return pow(h, x, q)
################################################################
password = random.randrange(10**6)
def go():
g = int(H(password).hex(), 16)
privA = 40*random.randrange(2**999)
pubA = F(g, privA)
print(f'{pubA = :#x}')
pubB = int(input(),0)
if not 1 < pubB < q:
exit('nope')
shared = F(pubB, privA)
verA = F(g, shared**3)
print(f'{verA = :#x}')
verB = int(input(),0)
if verB == F(g, shared**5):
key = H(password, shared)
flag = open('flag.txt').read().strip()
aes = AES.new(key, AES.MODE_CTR, nonce=b'')
print(f'flag:', aes.encrypt(flag.encode()).hex())
else:
print(f'nope! {shared:#x}')
# three shots, three opportunities
# to seize everything you ever wanted
# would you capture? or just let it slip?
signal.alarm(2021)
go()
go()
go()
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/hxp/2021/crypto/kipferl/vuln.py | ctfs/hxp/2021/crypto/kipferl/vuln.py | #!/usr/bin/env python3
from Crypto.Hash import SHA256
from Crypto.Cipher import AES
import signal, random
random = random.SystemRandom()
q = 0x3a05ce0b044dade60c9a52fb6a3035fc9117b307ca21ae1b6577fef7acd651c1f1c9c06a644fd82955694af6cd4e88f540010f2e8fdf037c769135dbe29bf16a154b62e614bb441f318a82ccd1e493ffa565e5ffd5a708251a50d145f3159a5
a, b = 1, 0
################################################################
# https://www.hyperelliptic.org/EFD/g1p/data/shortw/xz/ladder/ladd-2002-it
def xDBLADD(P,Q,PQ):
(X1,Z1), (X2,Z2), (X3,Z3) = PQ, P, Q
X4 = (X2**2-a*Z2**2)**2-8*b*X2*Z2**3
Z4 = 4*(X2*Z2*(X2**2+a*Z2**2)+b*Z2**4)
X5 = Z1*((X2*X3-a*Z2*Z3)**2-4*b*Z2*Z3*(X2*Z3+X3*Z2))
Z5 = X1*(X2*Z3-X3*Z2)**2
X4,Z4,X5,Z5 = (c%q for c in (X4,Z4,X5,Z5))
return (X4,Z4), (X5,Z5)
def xMUL(P, k):
Q,R = (1,0), P
for i in reversed(range(k.bit_length()+1)):
if k >> i & 1: R,Q = Q,R
Q,R = xDBLADD(Q,R,P)
if k >> i & 1: R,Q = Q,R
return Q
################################################################
def enc(a):
f = {str: str.encode, int: int.__str__}.get(type(a))
return enc(f(a)) if f else a
def H(*args):
data = b'\0'.join(map(enc, args))
return SHA256.new(data).digest()
def F(h, x):
r = xMUL((h,1), x)
return r[0] * pow(r[1],-1,q) % q
################################################################
password = random.randrange(10**6)
def go():
g = int(H(password).hex(), 16)
privA = 40*random.randrange(2**999)
pubA = F(g, privA)
print(f'{pubA = :#x}')
pubB = int(input(),0)
if not 1 < pubB < q:
exit('nope')
shared = F(pubB, privA)
verA = F(g, shared**3)
print(f'{verA = :#x}')
verB = int(input(),0)
if verB == F(g, shared**5):
key = H(password, shared)
flag = open('flag.txt').read().strip()
aes = AES.new(key, AES.MODE_CTR, nonce=b'')
print(f'flag:', aes.encrypt(flag.encode()).hex())
else:
print(f'nope! {shared:#x}')
# three shots, three opportunities
# to seize everything you ever wanted
# would you capture? or just let it slip?
signal.alarm(2021)
go()
go()
go()
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/hxp/2021/crypto/zipfel/vuln.py | ctfs/hxp/2021/crypto/zipfel/vuln.py | #!/usr/bin/env python3
from Crypto.Hash import SHA256
from Crypto.Cipher import AES
import signal, random
random = random.SystemRandom()
q = 0x3a05ce0b044dade60c9a52fb6a3035fc9117b307ca21ae1b6577fef7acd651c1f1c9c06a644fd82955694af6cd4e88f540010f2e8fdf037c769135dbe29bf16a154b62e614bb441f318a82ccd1e493ffa565e5ffd5a708251a50d145f3159a5
a, b = 1, 0
################################################################
# https://www.hyperelliptic.org/EFD/g1p/data/shortw/xz/ladder/ladd-2002-it
def xDBLADD(P,Q,PQ):
(X1,Z1), (X2,Z2), (X3,Z3) = PQ, P, Q
X4 = (X2**2-a*Z2**2)**2-8*b*X2*Z2**3
Z4 = 4*(X2*Z2*(X2**2+a*Z2**2)+b*Z2**4)
X5 = Z1*((X2*X3-a*Z2*Z3)**2-4*b*Z2*Z3*(X2*Z3+X3*Z2))
Z5 = X1*(X2*Z3-X3*Z2)**2
X4,Z4,X5,Z5 = (c%q for c in (X4,Z4,X5,Z5))
return (X4,Z4), (X5,Z5)
def xMUL(P, k):
Q,R = (1,0), P
for i in reversed(range(k.bit_length()+1)):
if k >> i & 1: R,Q = Q,R
Q,R = xDBLADD(Q,R,P)
if k >> i & 1: R,Q = Q,R
return Q
################################################################
def enc(a):
f = {str: str.encode, int: int.__str__}.get(type(a))
return enc(f(a)) if f else a
def H(*args):
data = b'\0'.join(map(enc, args))
return SHA256.new(data).digest()
def F(h, x):
r = xMUL((h,1), x)
return r[0] * pow(r[1],-1,q) % q
################################################################
password = random.randrange(10**6)
def go():
g = int(H(password).hex(), 16)
privA = 40*random.randrange(2**999)
pubA = F(g, privA)
print(f'{pubA = :#x}')
pubB = int(input(),0)
if not 1 < pubB < q:
exit('nope')
shared = F(pubB, privA)
verB = int(input(),0)
if verB == F(g, shared**5):
key = H(password, shared)
flag = open('flag.txt').read().strip()
aes = AES.new(key, AES.MODE_CTR, nonce=b'')
print(f'flag:', aes.encrypt(flag.encode()).hex())
else:
print(f'nope! {shared:#x}')
# three shots, three opportunities
# to seize everything you ever wanted
# would you capture? or just let it slip?
signal.alarm(2021)
go()
go()
go()
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/hxp/2018/Green_Computing_1_fix/run.py | ctfs/hxp/2018/Green_Computing_1_fix/run.py | #!/usr/bin/env python3
import random
import string
import sys
import tempfile
import shutil
import os
import base64
# Damn Chinese nation-state-level hackers added a tiny chip here :/
# Seems like they are injecting ACPI tables to save electricity O_O
# Please inform Bloomberg
tmp_dir = tempfile.mkdtemp(prefix='green_computing_', dir='/tmp')
os.chdir(tmp_dir)
os.makedirs('kernel/firmware/acpi')
with open('kernel/firmware/acpi/dsdt.aml', 'wb') as f:
b = base64.b64decode(sys.stdin.readline(32 * 1024).strip())
if b[:4] != b'DSDT':
b = b''
f.write(b)
os.system('find kernel | cpio -H newc --create --owner 0:0 > tables.cpio')
os.system('cat tables.cpio /home/ctf/init.cpio > init.gz')
os.system('qemu-system-x86_64 --version')
print('Booting ...\n', flush=True)
cmd = "qemu-system-x86_64 -monitor /dev/null -m 1337M -kernel /home/ctf/bzImage -initrd init.gz -append 'console=ttyS0 nokaslr panic=-1' -nographic -no-reboot"
os.system(cmd)
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/hxp/2018/Green_Computing_1/run.py | ctfs/hxp/2018/Green_Computing_1/run.py | #!/usr/bin/env python3
import random
import string
import sys
import tempfile
import shutil
import os
import base64
# Damn Chinese nation-state-level hackers added a tiny chip here :/
# Seems like they are injecting ACPI tables to save electricity O_O
# Please inform Bloomberg
tmp_dir = tempfile.mkdtemp(prefix='green_computing_', dir='/tmp')
os.chdir(tmp_dir)
os.makedirs('kernel/firmware/acpi')
with open('kernel/firmware/acpi/dsdt.aml', 'wb') as f:
b = base64.b64decode(sys.stdin.readline(32 * 1024).strip())
if b[:4] != b'DSDT':
b = b''
f.write(b)
os.system('find kernel | cpio -H newc --create --owner 0:0 > tables.cpio')
os.system('cat tables.cpio /home/ctf/init.cpio > init.gz')
os.system('qemu-system-x86_64 --version')
print('Booting ...\n', flush=True)
cmd = "qemu-system-x86_64 -m 1337M -kernel /home/ctf/bzImage -initrd init.gz -append 'console=ttyS0 nokaslr panic=-1' -nographic -no-reboot"
os.system(cmd)
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/hxp/2018/yunospace/wrapper.py | ctfs/hxp/2018/yunospace/wrapper.py | #!/usr/bin/python3 -u
import sys, os, base64
FLAG = "hxp{find_the_flag_on_the_server_here}"
print(" y-u-no-sp ")
print("XXXXXXXXx.a ")
print("OOOOOOOOO| ")
print("OOOOOOOOO| c ")
print("OOOOOOOOO| ")
print("OOOOOOOOO| ")
print("OOOOOOOOO| e ")
print("~~~~~~~|\~~~~~~~\o/~~~~~~~")
print(" }=:___'> \n")
print("> Welcome. Which byte should we prepare for you today?")
try:
n = int(sys.stdin.readline())
except:
print("> I did not get what you mean, sorry.")
sys.exit(-1)
if n >= len(FLAG):
print("> That's beyond my capabilities. Goodbye.")
sys.exit(-1)
print("> Ok. Now your shellcode, please.")
os.execve("./yunospace", ["./yunospace", FLAG[n]], dict())
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/hxp/2018/Green_Computing_2/run.py | ctfs/hxp/2018/Green_Computing_2/run.py | #!/usr/bin/env python3
import random
import string
import sys
import tempfile
import shutil
import os
import base64
# Damn Chinese nation-state-level hackers added a tiny chip here :/
# Seems like they are injecting ACPI tables to save electricity O_O
# Please inform Bloomberg
tmp_dir = tempfile.mkdtemp(prefix='green_computing_', dir='/tmp')
os.chdir(tmp_dir)
os.makedirs('kernel/firmware/acpi')
with open('kernel/firmware/acpi/dsdt.aml', 'wb') as f:
b = base64.b64decode(sys.stdin.readline(32 * 1024).strip())
if b[:4] != b'DSDT':
b = b''
f.write(b)
os.system('find kernel | cpio -H newc --create --owner 0:0 > tables.cpio')
os.system('cat tables.cpio /home/ctf/init.cpio > init.gz')
os.system('qemu-system-x86_64 --version')
print('Booting ...\n', flush=True)
# Don't worry! Linux is hardended to the maximum against these attacks :>!!
cmd = "qemu-system-x86_64 -monitor /dev/null -m 1337M -kernel /home/ctf/bzImage -initrd init.gz -append 'console=ttyS0 panic=-1 kaslr loglevel=-1 quiet' -nographic -no-reboot"
os.system(cmd)
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/hxp/2022/pwn/shadertoy_plus_plus/example_client/client.py | ctfs/hxp/2022/pwn/shadertoy_plus_plus/example_client/client.py | from pwn import *
from io import BytesIO
import base64
from PIL import Image
file = open("shader.txt", "rb")
shader = file.read()
file.close()
shader = shader.ljust(4095)
io = remote("localhost", 27500)
if True:
## If PoW is required...
io.readuntil(b"please give S such that sha256(unhex(\"")
prefix = io.readuntil(b"\"")[:-1]
io.readuntil(b"ends with ")
bits = io.readuntil(b" ")[:-1]
print("[+] calculating PoW...")
result = subprocess.run(["./pow-solver", bits.decode("ascii"), prefix.decode("ascii")], stdout=subprocess.PIPE, text=True)
print("[+] finished calc hash: " + result.stdout)
io.send(result.stdout)
io.readuntil("How many")
io.sendline(b"1")
io.send(shader)
io.readuntil("Sending PNG image as base64...\n")
data = io.readline()[:-1]
imgRaw = base64.b64decode(data)
imgAsIo = BytesIO(imgRaw)
img = Image.open(imgAsIo)
img.show()
finalMessage = io.readline()
print(finalMessage)
io.close()
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/hxp/2022/pwn/browser_insanity/enter_challenge.py | ctfs/hxp/2022/pwn/browser_insanity/enter_challenge.py | #!/usr/bin/python3
# This script is just for entering the URL into the browser in the VM.
#
# Accepted URL characters are: upper and lowercase ASCII, digits, .:/ %=
import time
import subprocess
import pty
import os
import string
import sys
data = input("What is the URL to visit? ")
if len(data) > 64:
print("URL is too long", flush=True)
exit(1)
allowed = string.ascii_lowercase + string.ascii_uppercase + string.digits + ".:/ %="
ok = all(ch in allowed for ch in data)
if ok == False:
print("Input is invalid", flush=True)
exit(1)
sys.stdin.close()
master, slave = pty.openpty()
run_vm = subprocess.Popen(["./run_vm.sh"], stdout=slave, stdin=slave, stderr=slave, text=True)
os.close(slave)
SLEEP_TIME_FOR_OS_BOOT = 12
SLEEP_TIME_FOR_CMD = .12
SLEEP_BEFORE_END = 10
def send_cmd(cmd):
os.write(master, cmd + b"\n")
time.sleep(SLEEP_TIME_FOR_CMD)
# Let's wait a bit.
print(f"Sleeping for {SLEEP_TIME_FOR_OS_BOOT} secs till VM boots", flush=True)
# Enter monitor with CTRL-a-c
send_cmd(b"\x01c")
time.sleep(1)
send_cmd(b"mouse_button 1")
send_cmd(b"mouse_button 2")
send_cmd(b"sendkey kp_enter")
time.sleep(SLEEP_TIME_FOR_OS_BOOT)
# Reposition cursor to address tab
for u in range(10):
send_cmd(b"mouse_move 0 -20")
# click click
send_cmd(b"mouse_button 1")
send_cmd(b"mouse_button 2")
# erase
for u in range(20):
send_cmd(b"sendkey backspace")
# type-in each character
for u in data:
if u == ":":
u = "shift-semicolon"
elif u == ".":
u = "dot"
elif u == "/":
u = "slash"
elif u == " ":
u = "spc"
elif u == "%":
u = "shift-5"
elif u == "=":
u = "equal"
cmd = "sendkey " + u
print(f"Sending: \"{cmd}\"", flush=True)
send_cmd(cmd.encode("ascii"))
# ok, let's visit
send_cmd(b"sendkey kp_enter")
# Give some time for the webpage to be downloaded, etc.
print(f"Sleeping for {SLEEP_BEFORE_END} secs and exiting", flush=True)
time.sleep(SLEEP_BEFORE_END)
# This should have been enough, let's stop the vm.
run_vm.kill()
print("Bye", flush=True)
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/hxp/2022/crypto/yor/vuln.py | ctfs/hxp/2022/crypto/yor/vuln.py | #!/usr/bin/env python3
import random
greets = [
"Herzlich willkommen! Der Schlüssel ist {0}, und die Flagge lautet {1}.",
"Bienvenue! Le clé est {0}, et le drapeau est {1}.",
"Hartelijk welkom! De sleutel is {0}, en de vlag luidt {1}.",
"ようこそ!鍵は{0}、旗は{1}です。",
"歡迎!鑰匙是{0},旗幟是{1}。",
"Witamy! Niestety nie mówię po polsku...",
]
flag = open('flag.txt').read().strip()
assert set(flag.encode()) <= set(range(0x20,0x7f))
key = bytes(random.randrange(256) for _ in range(16))
hello = random.choice(greets).format(key.hex(), flag).encode()
output = bytes(y | key[i%len(key)] for i,y in enumerate(hello))
print(output.hex())
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/hxp/2022/crypto/not_csidh/vuln.py | ctfs/hxp/2022/crypto/not_csidh/vuln.py | #!/usr/bin/env python3
from sage.all import *
proof.all(False)
p = 0x196c20a5235aa2c43071905be8e809d089d24fa9144143cf0977680f15b11351
j = 0x145b6a85f73443b1ef971b5152d87725ffe78a542bcaf60671e7afa3857a2530
ls = [3, 5, 7, 11, 13, 19, 23, 31, 71, 89, 103, 109, 113, 131, 149, 151, 163, 179, 193, 211, 223, 233]
B = 20
################################################################
def not_csidh(pub, priv):
E = EllipticCurve(GF(p), j=pub)
if E.order() > p:
E = E.quadratic_twist()
n = E.order()
es = list(priv)
assert all(e >= 0 for e in es)
while any(es):
js = [j for j,e in enumerate(es) if e]
if __name__ == '__main__':
print(f'[{",".join(str(e).rjust(2) for e in es)}]', file=sys.stderr)
k = prod(ls[j] for j in js)
P = E.random_point()
P *= n // k
for j in js[:]:
k //= ls[j]
Q = k * P
if Q:
Q.set_order(ls[j])
algo = (None, 'velusqrt')[Q.order() > 999]
phi = E.isogeny(Q, algorithm=algo)
E,P = phi.codomain(), phi(P)
es[j] -= 1
return ZZ(E.j_invariant())
################################################################
class NotCSIDH:
def __init__(self):
randrange = __import__('random').SystemRandom().randrange
self.priv = tuple(randrange(B+1) for _ in ls)
self.pub = not_csidh(j, self.priv)
def public(self): return self.pub
def shared(self, other): return not_csidh(other, self.priv)
################################################################
if __name__ == '__main__':
alice = NotCSIDH()
print('alice:', hex(alice.public()))
bob = NotCSIDH()
print('bob:', hex(bob.public()))
shared, = {alice.shared(bob.public()),
bob.shared(alice.public())}
from Crypto.Hash import SHA512
stream = SHA512.new(hex(shared).encode()).digest()
flag = open('flag.txt','rb').read().strip()
assert len(flag) <= len(stream)
print('flag:', bytes(x^y for x,y in zip(flag,stream)).hex())
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/hxp/2022/crypto/whistler/vuln.py | ctfs/hxp/2022/crypto/whistler/vuln.py | #!/usr/bin/env python3
import struct, hashlib, random, os
from Crypto.Cipher import AES
n = 256
q = 11777
w = 8
################################################################
sample = lambda rng: [bin(rng.getrandbits(w)).count('1') - w//2 for _ in range(n)]
add = lambda f,g: [(x + y) % q for x,y in zip(f,g)]
def mul(f,g):
r = [0]*n
for i,x in enumerate(f):
for j,y in enumerate(g):
s,k = divmod(i+j, n)
r[k] += (-1)**s * x*y
r[k] %= q
return r
################################################################
def genkey():
a = [random.randrange(q) for _ in range(n)]
rng = random.SystemRandom()
s,e = sample(rng), sample(rng)
b = add(mul(a,s), e)
return s, (a,b)
center = lambda v: min(v%q, v%q-q, key=abs)
extract = lambda r,d: [2*t//q for u,t in zip(r,d) if u]
ppoly = lambda g: struct.pack(f'<{n}H', *g).hex()
pbits = lambda g: ''.join(str(int(v)) for v in g)
hbits = lambda g: hashlib.sha256(pbits(g).encode()).digest()
mkaes = lambda bits: AES.new(hbits(bits), AES.MODE_CTR, nonce=b'')
def encaps(pk):
seed = os.urandom(32)
rng = random.Random(seed)
a,b = pk
s,e = sample(rng), sample(rng)
c = add(mul(a,s), e)
d = add(mul(b,s), e)
r = [int(abs(center(2*v)) > q//7) for v in d]
bits = extract(r,d)
return bits, (c,r)
def decaps(sk, ct):
s = sk
c,r = ct
d = mul(c,s)
return extract(r,d)
################################################################
if __name__ == '__main__':
while True:
sk, pk = genkey()
dh, ct = encaps(pk)
if decaps(sk, ct) == dh:
break
print('pk[0]:', ppoly(pk[0]))
print('pk[1]:', ppoly(pk[1]))
print('ct[0]:', ppoly(ct[0]))
print('ct[1]:', pbits(ct[1]))
flag = open('flag.txt').read().strip()
print('flag: ', mkaes([0]+dh).encrypt(flag.encode()).hex())
for _ in range(2048):
c = list(struct.unpack(f'<{n}H', bytes.fromhex(input())))
r = list(map('01'.index, input()))
if len(r) != n or sum(r) < n//2: exit('!!!')
bits = decaps(sk, (c,r))
print(mkaes([1]+bits).encrypt(b'hxp<3you').hex())
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/hxp/2022/crypto/the_swirl/vuln.py | ctfs/hxp/2022/crypto/the_swirl/vuln.py | #!/usr/bin/env python3
import struct, hashlib, random, os, ctypes
from Crypto.Cipher import AES
n = 256
q = 11777
w = 8
################################################################
sample = lambda rng: [bin(rng.getrandbits(w)).count('1') - w//2 for _ in range(n)]
add = lambda f,g: [(x + y) % q for x,y in zip(f,g)]
lib = ctypes.CDLL('./compute.so')
pck = lambda v: struct.pack(f'@{n}H', *(c%q for c in v))
unp = lambda bs: struct.unpack(f'@{n}H', bytes(bs))
def mul(f,g):
buf = ctypes.create_string_buffer(n*2)
lib.mul(buf, pck(f), pck(g))
return unp(buf)
################################################################
def genkey():
a = [random.randrange(q) for _ in range(n)]
rng = random.SystemRandom()
s,e = sample(rng), sample(rng)
b = add(mul(a,s), e)
return s, (a,b)
center = lambda v: min(v%q, v%q-q, key=abs)
extract = lambda r,d: [2*t//q for u,t in zip(r,d) if u]
ppoly = lambda g: struct.pack(f'<{n}H', *g).hex()
pbits = lambda g: ''.join(str(int(v)) for v in g)
hbits = lambda g: hashlib.sha256(pbits(g).encode()).digest()
mkaes = lambda bits: AES.new(hbits(bits), AES.MODE_CTR, nonce=b'')
def encaps(pk, seed=None):
seed = seed or os.urandom(32)
rng = random.Random(seed)
a,b = pk
s,e = sample(rng), sample(rng)
c = add(mul(a,s), e)
d = add(mul(b,s), e)
r = [int(abs(center(2*v)) > q//7) for v in d]
bits = extract(r,d)
t = mkaes(bits).encrypt(seed)
return bits, (c,r,t)
def decaps(sk, pk, ct):
s = sk
c,r,t = ct
d = mul(c,s)
bits = extract(r,d)
seed = mkaes(bits).decrypt(t)
if encaps(pk, seed)[1] != ct:
bits = [random.randrange(2) for _ in range(256)]
return bits
################################################################
if __name__ == '__main__':
while True:
sk, pk = genkey()
dh, ct = encaps(pk)
if decaps(sk, pk, ct) == dh:
break
print('pk[0]:', ppoly(pk[0]))
print('pk[1]:', ppoly(pk[1]))
print('ct[0]:', ppoly(ct[0]))
print('ct[1]:', pbits(ct[1]))
print('ct[2]:', ct[2].hex())
flag = open('flag.txt').read().strip()
print('flag: ', mkaes([0]+dh).encrypt(flag.encode()).hex())
while True:
c = list(struct.unpack(f'<{n}H', bytes.fromhex(input())))
r = list(map('01'.index, input()))
t = bytes.fromhex(input())
m = bytes.fromhex(input())
if len(r) != n or sum(r) < n//2: exit('!!!')
bits = decaps(sk, pk, (c,r,t))
if mkaes([1]+bits).decrypt(m) == b'ping':
msg = 'pong'
else:
msg = 'nope'
print(mkaes([2]+bits).encrypt(msg.encode()).hex())
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/hxp/2022/web/true_web_assembly/admin.py | ctfs/hxp/2022/web/true_web_assembly/admin.py | #!/usr/bin/env python3
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support.expected_conditions import visibility_of
from selenium.webdriver.chrome.service import Service
from webdriver_manager.chrome import ChromeDriverManager
from webdriver_manager.core.utils import ChromeType
import urllib.parse
import re
import sys
import traceback
import os
import time
def fatal(err_msg):
print(err_msg, flush=True)
exit(1)
def get(prompt, regex):
inp = input(prompt)
if not re.match(regex, inp):
fatal(f"Input {inp} does not match regex {regex}")
return inp
username = "hxp_admin"
password = "testtesttesttest"
challenge_ip = "chall"
proxy_username = "hxp"
proxy_password = "hxp"
port = 8091
if len(sys.argv) == 4:
challenge_ip = sys.argv[1]
username = sys.argv[2]
password = sys.argv[3]
print("Please supply connection details for your instance:")
proxy_username = get("Please give instance username: ", r"^[a-zA-Z0-9_-]+$")
proxy_password = get("Please give instance password: ", r"^[a-zA-Z0-9_-]+$")
port = get("Please give instance port: ", r"^\d+$")
if username == None or len(username) < 5:
fatal('Admin username somehow broken. Contact hxp admin.')
if password == None or len(password) < 12:
fatal('Admin password somehow broken. Contact hxp admin.')
regex = r'^.{0,100}$'
print(f"Please give the path the admin should check. (should match {regex})")
path = get(f"http://{challenge_ip}:{port}/", regex)
forbidden = ["!settings", "!sqlite", "!debuginfo"]
for f in forbidden:
if f in path:
fatal(f"'{f}' is forbidden")
if "!profile" in path and username in path:
fatal(f"admin doesn't want to visit their own profile")
# Visit URL
url = f"http://{proxy_username}:{proxy_password}@{challenge_ip}:{port}/"
chrome_options = Options()
chrome_options.add_argument('--disable-gpu')
chrome_options.add_argument('--headless')
chrome_options.add_argument('--no-sandbox')
chrome_options.add_argument("--disable-dev-shm-usage")
driver = None
try:
driver = webdriver.Chrome(service=Service(ChromeDriverManager(chrome_type=ChromeType.CHROMIUM).install()), options=chrome_options)
wait = WebDriverWait(driver, 1)
# Login
login_url = url + "!login"
print(f"Logging into {login_url}", flush=True)
driver.get(login_url)
# Hack to bypass the submit location checks
login_form = driver.find_element(By.CLASS_NAME, "login-block")
driver.execute_script('arguments[0].innerHTML = " <input type=\'text\' name=\'submit.y\' value=1 /> <input type=\'text\' name=\'submit.x\' value=1 /> " + arguments[0].innerHTML', login_form)
username_input = driver.find_element(By.NAME, 'username')
password_input = driver.find_element(By.NAME, 'password')
username_input.send_keys(username)
password_input.send_keys(password)
submit_button = driver.find_element(By.ID, 'submit')
submit_button.submit()
wait.until(lambda driver: driver.execute_script("return document.readyState") == "complete")
time.sleep(1)
url += path
print(f"Visiting {url}", flush=True)
driver.get(url)
wait.until(lambda driver: driver.execute_script("return document.readyState") == "complete")
time.sleep(1)
except Exception as e:
fatal(e)
finally:
if driver:
driver.quit()
print(f'Done visiting', flush=True)
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/hxp/2022/web/true_web_assembly/preregister_admin.py | ctfs/hxp/2022/web/true_web_assembly/preregister_admin.py | import secrets
import string
import hashlib
import sqlite3
import os
email = "johnfound@hxp.io"
username = os.getenv("ADMIN_USERNAME", "hxp_admin")
password = os.getenv("ADMIN_PASSWORD", "testtesttesttest")
if password == None or len(password) < 16:
print(f"Admin password is somehow invalid. Password: {password}")
print("Please run docker with sufficiently long password")
exit(1)
if username == None or len(username) < 5:
print(f"Admin username is somehow invalid. Username: {username}")
exit(1)
# copied from https://stackoverflow.com/questions/3854692/generate-password-in-python
alphabet = string.ascii_letters + string.digits
salt = ''.join(secrets.choice(alphabet) for i in range(32))
digest = hashlib.md5((salt + password).encode("ascii")).hexdigest()
# Pre-register admin
stmt = "insert into Users ( nick, passHash, salt, status, email ) values ( ?, ?, ?, -1, ?)"
connection = sqlite3.connect("./asmbb-challenge/board.sqlite")
cursor = connection.cursor()
res = cursor.execute(stmt, (username, digest, salt, email))
# Remove confirmation need
stmt = "update Params SET val='0' where id='email_confirm'"
res = cursor.execute(stmt)
connection.commit()
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/hxp/2022/web/archived/admin.py | ctfs/hxp/2022/web/archived/admin.py | #!/usr/bin/env python3
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.chrome.service import Service
from webdriver_manager.chrome import ChromeDriverManager
from webdriver_manager.core.utils import ChromeType
import re
import sys
import os
import time
from urllib.parse import quote
def get(prompt, regex):
inp = input(prompt)
if not re.match(regex, inp):
print(f"Input {inp} does not match regex {regex}", flush=True)
exit(1)
return inp
USERNAME = "admin"
PASSWORD = "admin123"
CHALLENGE_IP = "chall"
PROXY_USERNAME = "hxp"
PROXY_PASSWORD = "hxp"
PORT = 8081
if len(sys.argv) == 3:
# remote setup, IP, proxy, admin_password and port will differ!
CHALLENGE_IP = sys.argv[1]
PASSWORD = sys.argv[2]
print("Please supply connection details for your instance")
PROXY_USERNAME = get("Please give instance username: ", r"^[a-zA-Z0-9_-]+$")
PROXY_PASSWORD = get("Please give instance password: ", r"^[a-zA-Z0-9_-]+$")
PORT = get("Please give instance port: ", r"^\d+$")
chrome_options = Options()
chrome_options.add_argument('--disable-gpu')
chrome_options.add_argument('--headless')
chrome_options.add_argument('--no-sandbox')
chrome_options.add_argument("--disable-dev-shm-usage")
driver = None
try:
driver = webdriver.Chrome(service=Service(ChromeDriverManager(chrome_type=ChromeType.CHROMIUM).install()), options=chrome_options)
wait = WebDriverWait(driver, 10)
# log in
base_url = f"http://{quote(PROXY_USERNAME)}:{quote(PROXY_PASSWORD)}@{CHALLENGE_IP}:{PORT}"
print(f"Logging in to {base_url}", flush=True)
driver.get(base_url)
wait.until(lambda d: d.find_element(By.ID, "login-link-a"))
time.sleep(2)
driver.find_element(By.ID, "login-link-a").click()
wait.until(lambda d: d.find_element(By.ID, "modal-login").get_attribute("aria-hidden") == "false")
time.sleep(2)
username_input = driver.find_element(By.ID, "user-login-form-username")
username_input.send_keys(USERNAME)
password_input = driver.find_element(By.ID, "user-login-form-password")
password_input.send_keys(PASSWORD)
login_button = driver.find_element(By.ID, "modal-login-ok")
login_button.click()
wait.until(lambda driver: driver.execute_script("return document.readyState") == "complete")
time.sleep(2)
print(f"Hopefully logged in", flush=True)
# visit url
url = f"http://{CHALLENGE_IP}:{PORT}/repository/internal"
print(f"Visiting {url}", flush=True)
driver.get(url)
wait.until(lambda driver: driver.execute_script("return document.readyState") == "complete")
time.sleep(2)
except Exception as e:
print(e, file=sys.stderr, flush=True)
print('Error while visiting')
finally:
if driver:
driver.quit()
print('Done visiting', flush=True)
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/hxp/2022/web/sqlite_web/patch.py | ctfs/hxp/2022/web/sqlite_web/patch.py | #!/usr/bin/env python3
with open("sqlite_web/sqlite_web.py", "r") as f:
orig = f.read()
patched = orig.replace("""'SELECT *\\nFROM "%s"'""", '''"""WITH bytes(i, s) AS (
VALUES(1, '') UNION ALL
SELECT i + 1, (
SELECT ((v|k)-(v&k)) & 255 FROM (
SELECT
(SELECT asciicode from ascii where hexcode = hex(SUBSTR(sha512('hxp{REDACTED}'), i, 1))) as k,
(SELECT asciicode from ascii where hexcode = hex(SUBSTR(encrypted, i, 1))) as v
FROM %s
)
) AS c FROM bytes WHERE c <> '' limit 64 offset 1
) SELECT group_concat(char(s),'') FROM bytes;"""''')
with open("sqlite_web/sqlite_web.py", "w") as f:
f.write(patched) | python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/hxp/2020/pwn/nemoji/gen_challenge.py | ctfs/hxp/2020/pwn/nemoji/gen_challenge.py | #!/usr/bin/env python3
import urllib.request
import sys
import hashlib
KNOWN_GOOD_HASH = "9eb64f52f8970d0ce86b9ae366ea55cab35032ca6a2fd15f14f1354f493644d6"
DRGNS_GOOD_URL = "https://storage.googleapis.com/dragonctf-prod/noemoji_9eb64f52f8970d0ce86b9ae366ea55cab35032ca6a2fd15f14f1354f493644d6/main"
def nop(dat, start, end):
dat[start:end] = b"\x90" * (end - start)
return dat
def main(do_download = False):
dat = urllib.request.urlopen(DRGNS_GOOD_URL).read() if do_download else open("main", "rb").read()
h = hashlib.sha256()
h.update(dat)
if h.hexdigest() != KNOWN_GOOD_HASH:
print("hash check failed.")
return -2
dat = bytearray(dat) ## writable, pls
## Spice it up
dat = nop(dat, 0x13a4, 0x13b3)
dat = nop(dat, 0x1504, 0x1528)
dat = nop(dat, 0x152e, 0x1537)
dat = nop(dat, 0x1679, 0x1697)
dat[0x207f:0x2091] = b"emoji (\xe5\xaf\x9d\xe6\x96\x87\xe5\xad\x97)!"
dat[0x2107:0x210c] = b"DrgnS"
open("vuln", "wb").write(dat)
if __name__ == "__main__":
do_download = len(sys.argv) == 2 and sys.argv[1] == "steal_from_dragons"
main(do_download)
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/hxp/2020/pwn/audited/audited.py | ctfs/hxp/2020/pwn/audited/audited.py | #!/usr/bin/python3 -u
import sys
from os import _exit as __exit
def audit(name, args):
if not audit.did_exec and name == 'exec':
audit.did_exec = True
else:
__exit(1)
audit.did_exec = False
sys.stdout.write('> ')
try:
code = compile(sys.stdin.read(), '<user input>', 'exec')
except:
__exit(1)
sys.stdin.close()
for module in set(sys.modules.keys()):
if module in sys.modules:
del sys.modules[module]
sys.addaudithook(audit)
namespace = {}
try:
exec(code, namespace, namespace)
except:
__exit(1)
__exit(0)
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/hxp/2020/crypto/nanothorpe/service.py | ctfs/hxp/2020/crypto/nanothorpe/service.py | #!/usr/bin/env python3
from octothorpe import octothorpe
from base64 import b64decode, b64encode
from datetime import datetime, timedelta, timezone
from flask import Flask, make_response, redirect, render_template, request
from socket import MSG_WAITALL, socket
from struct import unpack
from urllib.parse import parse_qsl, unquote_to_bytes
app = Flask(__name__)
with open('/server-secret', 'rb') as secret_file:
secret = secret_file.read()
executor = ('127.0.1.1', 1024)
def verify(data, signature):
if signature != octothorpe(secret + data).hexdigest():
raise ValueError('Invalid signature')
def sign(data):
return octothorpe(secret + data).hexdigest()
def parse(query_string):
return dict(parse_qsl(query_string, errors='ignore')), unquote_to_bytes(query_string)
@app.route('/api/authorize', methods=['GET'])
def authorize():
args, decoded = parse(request.query_string)
command = args.get(b'cmd')
if not command:
return {'error': 'No command specified'}, 400
if command != b'ls':
return {'error': 'Insufficient privileges'}, 403
expiry = int((datetime.now(timezone.utc) + timedelta(seconds=15)).timestamp())
expiry_arg = b'expiry=' + str(expiry).encode() + b'&'
response = make_response(redirect(b'/api/run?' + expiry_arg + request.query_string, code=307))
response.set_cookie('signature', sign(expiry_arg + decoded), max_age=30)
return response
@app.route('/api/run', methods=['GET'])
def run_command():
args, decoded = parse(request.query_string)
signature = request.cookies.get('signature')
if not signature:
return {'error': 'Missing token'}, 403
try:
verify(decoded, signature)
except ValueError as error:
return {'error': 'Invalid token', 'detail': str(error)}, 403
command = args.get(b'cmd')
expiry = float(args.get(b'expiry'))
if datetime.now(timezone.utc).timestamp() >= expiry:
return {'error': 'Token has expired'}, 403
try:
with socket() as so:
so.settimeout(0.5)
so.connect(executor)
so.sendall(command + b'\n')
status, out_len, err_len = unpack('III', so.recv(12, MSG_WAITALL))
stdout = so.recv(out_len, MSG_WAITALL)
stderr = so.recv(err_len, MSG_WAITALL)
return {
'status': status,
'stdout': b64encode(stdout).decode(),
'stderr': b64encode(stderr).decode()
}, 200
except:
return {'error': 'Failed to execute command'}, 500
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/hxp/2020/crypto/nanothorpe/executor.py | ctfs/hxp/2020/crypto/nanothorpe/executor.py | #!/usr/bin/env python3
from subprocess import run
from sys import stdin, stdout
from struct import pack
command = stdin.buffer.readline().rstrip(b'\n')
result = run(command, shell=True, capture_output=True, timeout=0.5)
header = pack('III', result.returncode, len(result.stdout), len(result.stderr))
message = header + result.stdout + result.stderr
stdout.buffer.write(message)
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/hxp/2020/crypto/nanothorpe/octothorpe.py | ctfs/hxp/2020/crypto/nanothorpe/octothorpe.py | #!/usr/bin/env python3
import math
class octothorpe:
digest_size = 16
block_size = 64
name = "octothorpe"
state_size = 16
shift_count = 64
round_count = 20
initial_state = bytearray.fromhex('00112233445566778899aabbccddeeff')
function = lambda i: math.cos(i ** 3)
sbox = sorted(range(256), key=function)
shift = [int(8 * s) % 8 for s in map(function, range(shift_count))]
new = classmethod(lambda cls, data: cls(data))
copy = lambda self: octothorpe(_cache=self._cache[:], _length=self._length, _state=self._state[:])
digest = lambda self: bytes(self._finalize())
hexdigest = lambda self: self.digest().hex()
def __init__(self, data: bytes = None, *, _cache: bytes = None, _length: int = None, _state: bytearray = None) -> None:
self._cache = _cache or b''
self._length = _length or 0
self._state = _state or self.initial_state[:]
assert len(self._state) == self.state_size, 'Invalid state size'
if data:
self.update(data)
def update(self, data: bytes) -> None:
self._cache += data
while len(self._cache) >= self.block_size:
block, self._cache = self._cache[:self.block_size], self._cache[self.block_size:]
self._compress(block)
self._length += self.block_size
def _finalize(self) -> bytearray:
clone = self.copy()
clone._length += len(clone._cache)
clone.update(b'\x80' + b'\x00' * ((self.block_size - 9 - clone._length) % self.block_size) + (8 * clone._length).to_bytes(8, 'little'))
return clone._state
def _compress(self, block: bytes) -> None:
prev_state = lambda index: (index - 1) % self.state_size
next_state = lambda index: (index + 1) % self.state_size
rol = lambda value, shift, size: ((value << (shift % size)) | (value >> (size - (shift % size)))) & ((1 << size) - 1)
ror = lambda value, shift, size: ((value >> (shift % size)) | (value << (size - (shift % size)))) & ((1 << size) - 1)
for r in range(self.round_count):
state = self._state[:]
for i in range(self.block_size):
j, jj = (i * r) % self.state_size, (i * r) % self.shift_count
self._state[prev_state(j)] ^= self.sbox[block[i] ^ rol(state[j], self.shift[jj], 8)]
self._state[next_state(j)] ^= self.sbox[block[i] ^ ror(state[j], self.shift[jj], 8)]
if __name__ == '__main__':
assert octothorpe(b'hxp').hexdigest() == '4e072c7a1872f7cdf3cb2cfc676b0311'
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/hxp/2020/crypto/octothorpe/service.py | ctfs/hxp/2020/crypto/octothorpe/service.py | #!/usr/bin/env python3
from octothorpe import octothorpe
from base64 import b64decode, b64encode
from Crypto.PublicKey import ECC
from Crypto.Signature import DSS
from datetime import datetime, timedelta, timezone
from flask import Flask, make_response, redirect, render_template, request
from socket import MSG_WAITALL, socket
from struct import unpack
app = Flask(__name__)
with open('/server-key.pem', 'r') as key_file:
key = ECC.import_key(key_file.read())
sig = DSS.new(key, 'deterministic-rfc6979')
executor = ('127.0.1.1', 1024)
def verify(data, signature):
sig.verify(octothorpe(data), b64decode(signature))
def sign(data):
return b64encode(sig.sign(octothorpe(data)))
@app.route('/api/authorize', methods=['GET'])
def authorize():
command = request.args.get('cmd')
if not command:
return {'error': 'No command specified'}, 400
if command != 'ls':
return {'error': 'Insufficient privileges'}, 403
expiry = int((datetime.now(timezone.utc) + timedelta(seconds=15)).timestamp())
parameters = request.query_string + b'&expiry=' + str(expiry).encode()
response = make_response(redirect(b'/api/run?' + parameters, code=307))
response.set_cookie('signature', sign(parameters), max_age=30)
return response
@app.route('/api/run', methods=['GET'])
def run_command():
signature = request.cookies.get('signature')
if not signature:
return {'error': 'Missing token'}, 403
try:
verify(request.query_string, signature)
except ValueError as error:
return {'error': 'Invalid token', 'detail': str(error)}, 403
command = request.args.get('cmd')
expiry = float(request.args.get('expiry'))
if datetime.now(timezone.utc).timestamp() >= expiry:
return {'error': 'Token has expired'}, 403
try:
with socket() as so:
so.settimeout(0.5)
so.connect(executor)
so.sendall(command.encode() + b'\n')
status, out_len, err_len = unpack('III', so.recv(12, MSG_WAITALL))
stdout = so.recv(out_len, MSG_WAITALL)
stderr = so.recv(err_len, MSG_WAITALL)
return {
'status': status,
'stdout': b64encode(stdout).decode(),
'stderr': b64encode(stderr).decode()
}, 200
except:
return {'error': 'Failed to execute command'}, 500
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/hxp/2020/crypto/octothorpe/executor.py | ctfs/hxp/2020/crypto/octothorpe/executor.py | #!/usr/bin/env python3
from subprocess import run
from sys import stdin, stdout
from struct import pack
command = stdin.buffer.readline().rstrip(b'\n')
result = run(command, shell=True, capture_output=True, timeout=0.5)
header = pack('III', result.returncode, len(result.stdout), len(result.stderr))
message = header + result.stdout + result.stderr
stdout.buffer.write(message)
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/hxp/2020/crypto/octothorpe/octothorpe.py | ctfs/hxp/2020/crypto/octothorpe/octothorpe.py | #!/usr/bin/env python3
import math
class octothorpe:
digest_size = 16
block_size = 64
name = "octothorpe"
state_size = 16
shift_count = 64
round_count = 20
initial_state = bytearray.fromhex('00112233445566778899aabbccddeeff')
function = lambda i: math.cos(i ** 3)
sbox = sorted(range(256), key=function)
shift = [int(8 * s) % 8 for s in map(function, range(shift_count))]
new = classmethod(lambda cls, data: cls(data))
copy = lambda self: octothorpe(_cache=self._cache[:], _length=self._length, _state=self._state[:])
digest = lambda self: bytes(self._finalize())
hexdigest = lambda self: self.digest().hex()
def __init__(self, data: bytes = None, *, _cache: bytes = None, _length: int = None, _state: bytearray = None) -> None:
self._cache = _cache or b''
self._length = _length or 0
self._state = _state or self.initial_state[:]
assert len(self._state) == self.state_size, 'Invalid state size'
if data:
self.update(data)
def update(self, data: bytes) -> None:
self._cache += data
while len(self._cache) >= self.block_size:
block, self._cache = self._cache[:self.block_size], self._cache[self.block_size:]
self._compress(block)
self._length += self.block_size
def _finalize(self) -> bytearray:
clone = self.copy()
clone._length += len(clone._cache)
clone.update(b'\x80' + b'\x00' * ((self.block_size - 9 - clone._length) % self.block_size) + (8 * clone._length).to_bytes(8, 'little'))
return clone._state
def _compress(self, block: bytes) -> None:
prev_state = lambda index: (index - 1) % self.state_size
next_state = lambda index: (index + 1) % self.state_size
rol = lambda value, shift, size: ((value << (shift % size)) | (value >> (size - (shift % size)))) & ((1 << size) - 1)
ror = lambda value, shift, size: ((value >> (shift % size)) | (value << (size - (shift % size)))) & ((1 << size) - 1)
for r in range(self.round_count):
state = self._state[:]
for i in range(self.block_size):
j, jj = (i * r) % self.state_size, (i * r) % self.shift_count
self._state[prev_state(j)] ^= self.sbox[block[i] ^ rol(state[j], self.shift[jj], 8)]
self._state[next_state(j)] ^= self.sbox[block[i] ^ ror(state[j], self.shift[jj], 8)]
if __name__ == '__main__':
assert octothorpe(b'hxp').hexdigest() == '4e072c7a1872f7cdf3cb2cfc676b0311'
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/hxp/2020/crypto/minithorpe/service.py | ctfs/hxp/2020/crypto/minithorpe/service.py | #!/usr/bin/env python3
from octothorpe import octothorpe
from base64 import b64decode, b64encode
from datetime import datetime, timedelta, timezone
from flask import Flask, make_response, redirect, render_template, request
from socket import MSG_WAITALL, socket
from struct import unpack
app = Flask(__name__)
with open('/server-secret', 'rb') as secret_file:
secret = secret_file.read()
executor = ('127.0.1.1', 1024)
def verify(data, signature):
if signature != octothorpe(secret + data).hexdigest():
raise ValueError('Invalid signature')
def sign(data):
return octothorpe(secret + data).hexdigest()
@app.route('/api/authorize', methods=['GET'])
def authorize():
command = request.args.get('cmd')
if not command:
return {'error': 'No command specified'}, 400
if command != 'ls':
return {'error': 'Insufficient privileges'}, 403
expiry = int((datetime.now(timezone.utc) + timedelta(seconds=15)).timestamp())
parameters = request.query_string + b'&expiry=' + str(expiry).encode()
response = make_response(redirect(b'/api/run?' + parameters, code=307))
response.set_cookie('signature', sign(parameters), max_age=30)
return response
@app.route('/api/run', methods=['GET'])
def run_command():
signature = request.cookies.get('signature')
if not signature:
return {'error': 'Missing token'}, 403
try:
verify(request.query_string, signature)
except ValueError as error:
return {'error': 'Invalid token', 'detail': str(error)}, 403
command = request.args.get('cmd')
expiry = float(request.args.get('expiry'))
if datetime.now(timezone.utc).timestamp() >= expiry:
return {'error': 'Token has expired'}, 403
try:
with socket() as so:
so.settimeout(0.5)
so.connect(executor)
so.sendall(command.encode() + b'\n')
status, out_len, err_len = unpack('III', so.recv(12, MSG_WAITALL))
stdout = so.recv(out_len, MSG_WAITALL)
stderr = so.recv(err_len, MSG_WAITALL)
return {
'status': status,
'stdout': b64encode(stdout).decode(),
'stderr': b64encode(stderr).decode()
}, 200
except:
return {'error': 'Failed to execute command'}, 500
| 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.