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/b01lers/2024/blockchain/burgercoin/solve-pow.py | ctfs/b01lers/2024/blockchain/burgercoin/solve-pow.py | import hashlib,random
x = 100000000+random.randint(0,200000000000)
for i in range(x,x+20000000000):
m = hashlib.sha256()
ticket = str(i)
m.update(ticket.encode('ascii'))
digest1 = m.digest()
m = hashlib.sha256()
m.update(digest1 + ticket.encode('ascii'))
if m.hexdigest().startswith('0000000'):
print(i)
break
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/b01lers/2024/misc/TeXnically.../server-dist.py | ctfs/b01lers/2024/misc/TeXnically.../server-dist.py | import subprocess
from colorama import Fore, Style
with open("chal.tex", "w") as tex_file:
tex_file.write(rf"""
\documentclass{{article}}
%%%
% Redacted
%%%
\pagenumbering{{gobble}}
\lfoot{{ % Page number formatting
\hspace*{{\fill}} Page \arabic{{page}} % of \protect\pageref{{LastPage}}
}}
\newif\iflong
%%%
% Redacted
%%%
\begin{{document}}
%%%
% Redacted
%%%
""")
print("")
print(Fore.RED + "Insert your message in a LaTeX syntax. (For example, \\texttt{b01ler up!})")
print("")
print(Fore.RED + "Hit Enter once you are done.")
print(Style.RESET_ALL)
input_value = input()
print("")
print(Fore.RED + "Compiling...")
print(Fore.RED + "(This might take a while. Feel free to hit Enter multiple times if that'd reduce your anxiety lol.)")
tex_file.write(rf"""
Here is my response to your message. It should all be in text. I hope you can see it.
You said:
{input_value}
My reply:
%%%
% Redacted
%%%
\end{{document}}
""")
subprocess.run(["pdflatex", "chal.tex"], stdout=subprocess.DEVNULL)
print("")
print(Fore.RED + "This is what it looks like when the PDF file is converted to a txt file:")
print("")
print(Style.RESET_ALL)
# %%%
# % Redacted
# %%%
print(Fore.RED + "End of the file.")
print("")
print(Fore.RED + "Due to security reasons, we will not be giving you the PDF or log files. Sorry =(")
print("")
print(Style.RESET_ALL)
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/b01lers/2024/misc/cppjail/compile.py | ctfs/b01lers/2024/misc/cppjail/compile.py | #!/bin/env python3
import os
import time
# # local testing stuff
# input_code = []
# while True:
# try:
# line = input()
# except EOFError:
# break
# input_code.append(line)
# input_code = ' '.join(input_code)
input_code = input("Input your code: ")
if len(input_code) > 280:
print("jail must be less than 280 characters !!!")
exit()
banned_words = [
"#", "define", "include",
"//",
"ifndef", "ifdef",
"Lock", "Key",
"class", "struct",
"*", "int", "char", "short", "long",
" "
]
for word in banned_words:
if word in input_code:
print("You can't use " + word + " !!!")
exit()
code = ""
with open("cppjail.cpp", "r") as cjail:
code = cjail.read()
code = code.replace("/* you are here */", input_code)
with open("jail.cpp", "w") as cjail_final:
cjail_final.write(code)
success = os.system("g++ -o jail jail.cpp 2>&1")
if success != 0:
print("------ Compile errors, skipping")
exit()
# prevent bruteforce
time.sleep(5)
os.system("./jail 2>&1")
os.system("rm jail")
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/b01lers/2024/crypto/choose_the_param/chal.py | ctfs/b01lers/2024/crypto/choose_the_param/chal.py | #!/usr/bin/python3
from Crypto.Util.number import long_to_bytes, bytes_to_long, getPrime
import os
from secret import flag
padded_flag = os.urandom(200) + flag + os.urandom(200)
m = bytes_to_long(padded_flag)
def chal():
print("""Choose your parameter
Enter the bit length of the prime!
I'll choose two prime of that length, and encrypt the flag using rsa.
Try decrypt the flag!
""")
while True:
bits = input("Enter the bit length of your primes> ")
try:
bit_len = int(bits)
except:
print("please enter a valid intergar")
continue
p1 = getPrime(bit_len)
p2 = getPrime(bit_len)
n = p1 * p2
e = 65537
c = pow(m, e, n)
print(f"n = {n:x}")
print(f"e = {e:x}")
print(f"c = {c:x}")
if __name__ == "__main__":
chal()
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/b01lers/2024/crypto/shamir_for_dummies/server-dist.py | ctfs/b01lers/2024/crypto/shamir_for_dummies/server-dist.py | import os
import sys
import time
import math
import random
from Crypto.Util.number import getPrime, isPrime, bytes_to_long, long_to_bytes
def polynomial_evaluation(coefficients, x):
at_x = 0
for i in range(len(coefficients)):
at_x += coefficients[i] * (x ** i)
at_x = at_x % p
return at_x
flag = b'bctf{REDACTED}'
print("")
print("Thanks for coming in. I can really use your help.\n")
print("Like I said, my friend can only do additions. He technically can do division but he says he can only do it once a day.")
print("")
print("I need to share my secret using Shamir secret sharing. Can you craft the shares, in a way that my friend can recover it?\n")
print("")
print("Don't worry, I have the polynomial and I will do all the math for you.")
print("")
s = bytes_to_long(flag)
n = getPrime(4)
p = getPrime(512)
while p % n != 1:
p = getPrime(512)
print("Let's use \n")
print("n =", n)
print("k =", n)
print("p =", p)
print("")
coefficients = [s]
for i in range(1, n):
coefficients.append(random.randint(2, p-1))
print("Okay, I have my polynomial P(X) ready. Let me know when you are ready to generate shares with me.\n")
print("")
evaluation_points = []
shares = []
count = 1
while count < n+1:
print("Evaluate P(X) at X_{0} =".format(count))
print("> ", end="")
eval_point = int(input())
if eval_point % p == 0:
print("Lol, nice try. Bye.")
exit()
break
elif eval_point < 0 or eval_point > p:
print("Let's keep things in mod p. Please choose it again.")
else:
if eval_point not in evaluation_points:
evaluation_points.append(eval_point)
share = polynomial_evaluation(coefficients, eval_point)
shares.append(share)
count += 1
else:
print("You used that already. Let's use something else!")
print("Nice! Let's make sure we have enough shares.\n")
assert len(shares) == n
assert len(evaluation_points) == n
print("It looks like we do.\n")
print("By the way, would he have to divide with anything? (Put 1 if he does not have to)")
print("> ", end="")
some_factor = int(input())
print("Good. Let's send those over to him.")
for _ in range(3):
time.sleep(1)
print(".")
sys.stdout.flush()
sum_of_shares = 0
for s_i in shares:
sum_of_shares += s_i
sum_of_shares = sum_of_shares % p
sum_of_shares_processed = (sum_of_shares * pow(some_factor, -1, p)) % p
if sum_of_shares_processed == s:
print("Yep, he got my secret message!\n")
print("The shares P(X_i)'s were':")
print(shares)
print("... Oh no. I think now you'd know the secret also... Thanks again though.")
else:
print("Sorry, it looks like that didn't work :(")
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/b01lers/2024/crypto/R_esurre_C_tion_4/server-dist.py | ctfs/b01lers/2024/crypto/R_esurre_C_tion_4/server-dist.py | import random
from Crypto.Util.number import getPrime, isPrime, bytes_to_long, long_to_bytes
"""
Key-scheduling algorithm (KSA)
"""
def KSA(key):
S = [i for i in range(0, 256)]
i = 0
for j in range(0, 256):
i = (i + S[j] + key[j % len(key)]) % 256
S[i] ^= S[j] ## swap values of S[i] and S[j]
S[j] ^= S[i]
S[i] ^= S[j]
return S
"""
Pseudo-random generation algorithm (PRGA)
"""
def PGRA(S):
i = 0
j = 0
while True: ## while GeneratingOutput
i = (1 + i) % 256
j = (S[i] + j) % 256
S[i] ^= S[j] ## swap values of S[i] and S[j]
S[j] ^= S[i]
S[i] ^= S[j]
yield S[(S[i] + S[j]) % 256]
if __name__ == '__main__':
FLAG = 'bctf{REDACTED}'
print("Would you like to pad the plaintext before encrypting it?")
print("(Just hit enter if you do not want to add any padding(s).)")
Padding = input()
input_text = ''
input_text += Padding
input_text += FLAG
plaintext = [ord(char) for char in input_text]
key = long_to_bytes(random.getrandbits(2048)) # 2048 bits = 256 bytes
key = [byte for byte in key]
S = KSA(key)
keystream = PGRA(S)
ciphertext = ''
for char in plaintext:
enc = char ^ next(keystream)
enc = (str(hex(enc)))[2:]
if len(enc) == 1: ## make sure they are all in the form 0x**
enc = '0' + enc
ciphertext += enc
print(ciphertext) | python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/b01lers/2024/crypto/half_big_rsa/half-big-rsa.py | ctfs/b01lers/2024/crypto/half_big_rsa/half-big-rsa.py | import math
from Crypto.Util.number import getPrime, bytes_to_long, long_to_bytes
import os
num_bits = 4096
e = (num_bits - 1) * 2
n = getPrime(num_bits)
with open("flag.txt","rb") as f:
flag = f.read()
m = bytes_to_long(flag)
c = pow(m, e, n)
print(c)
with open("output.txt", "w") as f:
f.write("e = {0}\n".format(e))
f.write("n = {0}\n".format(n))
f.write("c = {0}\n".format(c))
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/b01lers/2024/crypto/Snoopy/snoopy.py | ctfs/b01lers/2024/crypto/Snoopy/snoopy.py | import time
import os
import numpy as np
from Crypto.Cipher import AES
from Crypto.Random.random import randrange
from numba import jit
FLAG = open("flag.txt", "rb").read().strip()
assert FLAG[:5] == b"bctf{" and FLAG[-1:] == b"}"
FLAG = FLAG[5:-1]
assert len(FLAG) <= 16
HI = 3.3
@jit(nopython = True) # serious python computations need something like this..
def sweep(m, turbo = 0.):
res = m.copy()
nx,ny = res.shape
eps = 0.
for i in range(1, nx - 1):
for j in range(1, ny - 1):
d = 0.25 * (m[i, j+1] + m[i, j-1] + m[i+1, j] + m[i-1, j]) - m[i,j]
res[i,j] += d * (1. - turbo)
eps = max(eps, abs(d))
return res, eps
class Snoopy:
def __init__(self, N):
self.N = N
self.die = np.zeros((N + 1, N + 1), dtype = float)
self.on = False
def mapPin(self, k):
N = self.N
if k < N: return 0, k
elif k < 2*N: return k % N, N
elif k < 3*N: return N, (-k) % N
else: return (-k) % N, 0
def setPin(self, k, v):
i,j = self.mapPin(k)
self.die[i,j] = v
def getPin(self, k):
i,j = self.mapPin(k)
return self.die[i,j]
# solely keeping this for backwards compatibility (original tech limitations are long gone)
def firstPin(self, idx):
N4 = self.N >> 2
return ((idx % N4) << 4) + (0 if idx < N4 else 8)
def load(self, idx):
first = self.firstPin(idx % (self.N >> 1))
return sum( [ (1 << k) for k in range(8) if self.getPin(first + k) == HI ] )
def save(self, idx, v):
first = self.firstPin(idx % (self.N >> 1))
for k in range(8): self.setPin(first + k, HI * ((v >> k) & 1))
def swap(self, idx1, idx2):
v1 = self.load(idx1)
v2 = self.load(idx2)
self.save(idx1, v2)
self.save(idx2, v1)
def inc(self, idx):
v = self.load(idx)
self.save(idx, v + 1)
def boot(self):
r = b"SnOoPy@BCtf2024#"
for idx in range(self.N >> 1):
self.save(idx, r[idx % len(r)])
time.sleep(0.1)
self.save(-1, 0)
self.on = True
def placeLoop(self):
if self.on:
print("** Tampering detected **\nShutting down", flush = True)
exit(0)
GAP = 10
while True:
try:
x0,y0 = [int(v) for v in input("top left corner: ").strip().split() ]
x1,y1 = [int(v) for v in input("bottom right corner: ").strip().split() ]
if GAP < x0 < x1 < self.N - GAP and GAP < y0 < y1 < self.N - GAP:
self.loop = ((x0,y0), (x1,y1))
break
except ValueError: pass
def keygen(self):
self.swap(-1, 1)
for k in range(self.N >> 3): self.save(-k, os.urandom(1)[0])
self.swap(-1, 1)
self.inc(-1)
if self.load(-1) == 0:
print("** Ran out of keys **\nShutting down", flush = True)
exit(0)
def encrypt(self):
N = self.N
for i in range(1, N):
for j in range(1, N):
self.die[i, j] = HI * randrange(0, 2**64) / 2**64
self.keygen()
x = bytes( [ self.load(-k) for k in range(N >> 3) ] )
aes = AES.new(x*4, AES.MODE_ECB)
c = aes.encrypt(FLAG)
for k in range(len(c)): self.save(k, c[k])
return self.magic()
def magic(self):
for _ in range(200000):
#self.die, eps = sweep(self.die, 0.)
self.die, eps = sweep(self.die, 0.01) # save some on datacenter costs (US Patent No. 20240412)
if eps < 1e-14: return True
return False
def snoop(self):
((i1, j1), (i2,j2)) = self.loop
# cheapo gear constraints (this is a shoestring op :/)
if min(i2 - i1, j2 - j1) < 10:
print("** Short circuit in detector **", flush = True)
exit(0)
if (i2 - i1) + (j2 - j1) > 40:
print("** Tampering detected **\nShutting down", flush = True)
exit(0)
data = [ self.die[i1, j] for j in range(j1, j2) ]
data += [ self.die[i, j2] for i in range(i1, i2) ]
data += [ self.die[i2, j] for j in range(j2, j1, -1) ]
data += [ self.die[i, j1] for i in range(i2, i1, -1) ]
return data
def menu(self):
print(
"""
Choose:
1) place detector
2) boot
3) generate key
4) encrypt flag
5) snoop
6) exit
""", flush = True)
def run(self):
self.menu()
choice = input("> ").strip()
if choice == "1":
self.placeLoop()
print(f"\nSnoop loop in place at {self.loop} :)", flush = True)
elif choice == "2":
print("Booting system... ", end = "", flush = True)
self.boot()
print("DONE", flush = True)
elif choice == "3":
if not self.on: return
print("\nGenerating key... ", end = "", flush = True)
self.keygen()
print("SUCCESS", flush = True)
elif choice == "4":
if not self.on: return
print("\nEncrypting flag... ", end = "", flush = True)
if self.encrypt(): print("SUCCESS", flush = True)
else: print("FAILURE - try again", flush = True)
elif choice == "5":
if not self.on: return
print("\nCollecting... ", end = "", flush = True)
try:
data = self.snoop()
print("DONE", flush = True)
print(f"Readings: {data}", flush = True)
except AttributeError:
print("FAILURE", flush = True)
elif choice == "6": exit(0)
if __name__ == "__main__":
chal = Snoopy(64)
while True: chal.run()
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/b01lers/2024/crypto/schnore/chal.py | ctfs/b01lers/2024/crypto/schnore/chal.py | #!/usr/bin/python3
import sys
from Crypto.Util import number
from Crypto.Hash import SHA512
with open("flag.txt") as f:
flag = f.read()
# FIPS 186-4 Appendix A.1/A.2 compliant prime order q group and prime order p field
#from Crypto.PublicKey import DSA as FFCrypto
#(p,q,g) = FFCrypto.generate(2048).domain()
p = 32148430219533869432664086521225476372736462680273996089092113172047080583085077464347995262368698415917196323365668601969574610671154445337781821758494432339987784268234681352859122106315479086318464461728521502980081310387167105996276982251134873196176224643518299733023536120537865020373805440309261518826398579473063255138837294134742678213639940734783340740545998610498824621665838546928319540277854869576454258917970187451361767420622980743233300167354760281479159013996441502511973279207690493293107263225937311062981573275941520199567953333720369198426993035900390396753409748657644625989750046213894003084507
q = 25652174680121164880516494520695513229510497175386947962678706338003
g = 23174059265967833044489655691705592548904322689090091191484900111607834369643418104621577292565175857016629416139331387500766371957528415587157736504641585483964952733970570756848175405454138833698893579333073195074203033602295121523371560057410727051683793079669493389242489538716350397240122001054430034016363486006696176634233182788395435344904669454373990351188986655669637138139377076507935928088813456234379677586947957539514196648605649464537827962024445144040395834058714447916981049408310960931998389623396383151616168556706468115596486100257332107454218361019929061651117632864546163172189693989892264385257
def prove():
print("The oracles say that X is g^x and A is g^a. Be that as it may...")
print("Perhaps there exists a way to make their confidence sway!")
# (Sorry, can't choose a :)
A = 30210424620845820052071225945109142323820182565373787589801116895962027171575049058295156742156305996469210267854774935518505743920438652976152675486476209694284460060753584821225066880682226097812673951158980930881565165151455761750621260912545169247447437218263919470449873682069698887953001819921915874928002568841432197395663420509941263729040966054080025218829347912646803956034554112984570671065110024224236097116296364722731368986065647624353094691096824850694884198942548289196057081572758803944199342980170036665636638983619866569688965508039554384758104832379412233201655767221921359451427988699779296943487
h = SHA512.new(truncate="256")
h.update(number.long_to_bytes(g) + number.long_to_bytes(p) + number.long_to_bytes(A))
c = number.bytes_to_long(h.digest()) % p
z = int(input("a + cx = ")) % p
return (A,c,z)
def setup():
print("> I'm so sleepy, I almost forgot; we should share what we ought.")
print("> Just between you and me, can we agree on a verifying key...?")
X = int(input("> X = ")) % p
return X
def verify(A,c,z,X):
h = SHA512.new(truncate="256")
h.update(number.long_to_bytes(g) + number.long_to_bytes(p) + number.long_to_bytes(A))
cp = number.bytes_to_long(h.digest()) % p
if c != cp or pow(g, z, p) != ((A * pow(X, c, p)) % p):
print("> Oh, even my bleary eyes can tell your evidence is fau x !!")
print("> Are you sure that what you say is what you truly know?")
sys.exit()
else:
print("> ", end="")
print(flag)
if __name__ == "__main__":
(A,c,z) = prove()
X = setup()
verify(A,c,z,X)
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/b01lers/2024/crypto/count_the_counter/chal.py | ctfs/b01lers/2024/crypto/count_the_counter/chal.py | #!/bin/python3
from Crypto.Cipher import AES
from Crypto.Util.number import long_to_bytes
from secret import flag
import os
def Encrypt(key, message, nonce):
cipher = AES.new(key, AES.MODE_CTR, nonce=long_to_bytes(nonce))
return cipher.encrypt(message).hex()
def chal():
key = os.urandom(16)
print("Treat or Trick, count my thing. ")
nonce_counter = 1
print(Encrypt(key, flag, nonce_counter))
while True:
nonce_counter += 1
to_enc = input("Give me something to encrypt: ")
print(Encrypt(key, bytes.fromhex(to_enc), nonce_counter))
if __name__ == "__main__":
chal()
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/b01lers/2024/crypto/Propagating_Counter_Block_Chaining/chal.py | ctfs/b01lers/2024/crypto/Propagating_Counter_Block_Chaining/chal.py | from Crypto.Cipher import AES
from Crypto.Util.Padding import pad, unpad
from functools import reduce
from secret import flag
import os
import json
BLOCK_SIZE = 16
key_ctr1 = os.urandom(BLOCK_SIZE)
key_ctr2 = os.urandom(BLOCK_SIZE)
key_cbc = os.urandom(BLOCK_SIZE)
nonce1 = os.urandom(8)
nonce2 = os.urandom(8)
def AES_ECB_enc(key, message):
enc = AES.new(key, AES.MODE_ECB)
return enc.encrypt(message)
def AES_ECB_dec(key, message):
enc = AES.new(key, AES.MODE_ECB)
return enc.decrypt(message)
# Returning a block each time
def get_blocks(message):
for i in range(0, len(message), BLOCK_SIZE):
yield message[i:i+BLOCK_SIZE]
return
# Takes any number of arguements, and return the xor result.
# Similar to pwntools' xor, but trucated to minimum length
def xor(*args):
_xor = lambda x1, x2: x1^x2
return bytes(map(lambda x: reduce(_xor, x, 0), zip(*args)))
def counter(nonce):
count = 0
while count < 2**(16 - len(nonce)):
yield nonce + str(count).encode().rjust(16-len(nonce), b"\x00")
count+=1
return
def encrypt(message):
cipher = b""
iv = os.urandom(BLOCK_SIZE)
prev_block = iv
counter1 = counter(nonce1)
counter2 = counter(nonce2)
for block in get_blocks(pad(message, BLOCK_SIZE)):
enc1 = AES_ECB_enc(key_ctr1, next(counter1))
enc2 = AES_ECB_enc(key_cbc, xor(block, prev_block, enc1))
enc3 = AES_ECB_enc(key_ctr2, next(counter2))
enc4 = xor(enc3, enc2)
prev_block = xor(block, enc4)
cipher += enc4
return iv + cipher
def decrypt(cipher):
message = b""
iv = cipher[:16]
cipher_text = cipher[16:]
prev_block = iv
counter1 = counter(nonce1)
counter2 = counter(nonce2)
for block in get_blocks(cipher_text):
dec1 = AES_ECB_enc(key_ctr2, next(counter2))
dec2 = AES_ECB_dec(key_cbc, xor(block, dec1))
dec3 = AES_ECB_enc(key_ctr1, next(counter1))
message += xor(prev_block, dec2, dec3)
prev_block = xor(prev_block, dec2, block, dec3)
return unpad(message, BLOCK_SIZE)
def main():
certificate = os.urandom(8) + flag + os.urandom(8)
print(f"""
*********************************************************
Certificate as a Service
*********************************************************
Here is a valid certificate: {encrypt(certificate).hex()}
*********************************************************""")
while True:
try:
cert = bytes.fromhex(input("Give me a certificate >> "))
if len(cert) < 32:
print("Your certificate is not long enough")
message = decrypt(cert)
if flag in message:
print("This certificate is valid")
else:
print("This certificate is not valid")
except Exception:
print("Something went wrong")
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/b01lers/2023/pwn/knock_knock/chall.py | ctfs/b01lers/2023/pwn/knock_knock/chall.py | import base64
from subprocess import Popen, PIPE
import struct
import shutil
import uuid
import os
import sys
MAX_CODE_SIZE = 4096 * 4
def main():
if len(sys.argv) == 2:
# use user supplied file
with open(sys.argv[1], 'rb') as f:
data = f.read()
else:
code = input('Enter base 64 encoded machine code: ')
try:
data = base64.b64decode(code)
except:
print('invalid base64 encoded data')
return
if len(data) > MAX_CODE_SIZE:
print('Code is too long')
return
size_bytes = struct.pack('<H', len(data))
disk_uuid = uuid.uuid4()
disk_name = f'/tmp/{disk_uuid}'
shutil.copy('disk_redacted.img', disk_name)
try:
with Popen([
'timeout', '5',
'qemu-system-x86_64',
'-m', '512M',
'-serial', 'stdio',
'-drive', f'file={disk_name},format=raw',
'-display', 'none',
'-monitor', 'none',
'-no-reboot',
], stdout=PIPE, stdin=PIPE) as p:
# For some reason, the first byte is ignored
p.stdin.write(b'\0')
p.stdin.write(size_bytes)
p.stdin.write(data)
p.stdin.flush()
print(p.stdout.read().decode('ascii'))
except:
print('timeout')
os.remove(disk_name)
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/b01lers/2023/crypto/poeticrypto/algo.py | ctfs/b01lers/2023/crypto/poeticrypto/algo.py | #!/usr/bin/env python3
# Use these algorithms
from binascii import unhexlify, hexlify
from Crypto.Cipher import AES
from Crypto.Hash import SHA256
from Crypto.Protocol.KDF import PBKDF2
PUB_SALT = b'Grow grow grow!!'
PRIV_SALT_BITS = 16
KEY_SIZE = 32
from SECRET.keygen import getKey
from SECRET.vals import FLAG, SEED
class TreeOfLife:
def __init__(self, seed, salt_len, key_len):
self.seed = seed
self.salt_len = salt_len
self.key_len = key_len
def burn(self, key):
return AES.new(key, AES.MODE_GCM, nonce=b'00000000').encrypt(bytes(FLAG, 'ascii'))
if __name__ == "__main__":
# Derive the key
tree = TreeOfLife(SEED, PRIV_SALT_BITS, KEY_SIZE)
key = getKey(tree, PUB_SALT)
ct = tree.burn(key)
print('CIPHERTEXT:', hexlify(ct).decode('ascii'))
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/b01lers/2023/crypto/MajesticLop/chal.py | ctfs/b01lers/2023/crypto/MajesticLop/chal.py | import itertools
import os
import datetime
import math
FLAG = open("flag.txt", "rb").read().strip()
cache = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97, 101, 103,
107, 109, 113, 127, 131, 137, 139, 149, 151, 157, 163, 167, 173, 179, 181, 191, 193, 197, 199, 211, 223, 227, 229,
233, 239, 241, 251, 257, 263, 269, 271, 277, 281, 283, 293, 307, 311, 313, 317, 331, 337, 347, 349, 353, 359, 367,
373, 379, 383, 389, 397, 401, 409, 419, 421, 431, 433, 439, 443, 449, 457, 461, 463, 467, 479, 487, 491, 499, 503,
509, 521, 523, 541, 547, 557, 563, 569, 571, 577, 587, 593, 599, 601, 607, 613, 617, 619, 631, 641, 643, 647, 653,
659, 661, 673, 677, 683, 691, 701, 709, 719, 727, 733, 739, 743, 751, 757, 761, 769, 773, 787, 797, 809, 811, 821,
823, 827, 829, 839, 853, 857, 859, 863, 877, 881, 883, 887, 907, 911, 919, 929, 937, 941, 947, 953, 967, 971, 977,
983, 991, 997]
N = 128
def makeStamp(t): return int( "".join( str(t)[:-3].translate({45: ' ', 46: ' ', 58: ' '}).split()[::-1] ) )
def getWeights(stamp): return sorted(cache, key = lambda v: abs(math.sin(math.pi * stamp / v)))
def f(z, key):
A, B, p, q = key
for _ in range(p): z = A * z * (1 - z)
for _ in range(q): z = B * z * (1 - z)
return z
def g(b, key): return int(f(0.5/(N+1)*(b+1), key) * 256)
def keygen(p = None, q = None):
A0 = 3.95
if p == None or q == None:
stamp = makeStamp(t0)
p, q = getWeights(stamp)[:2]
while True:
A = A0 + int.from_bytes(os.urandom(4), "big") * 1e-11
B = A0 + int.from_bytes(os.urandom(4), "big") * 1e-11
key = A, B, p, q
a = sorted( [(g(b, key) << 8) + g(b^0xbc, key) for b in range(N)] )
s = max( [ sum([1 for _ in b]) for _,b in itertools.groupby(a)] )
if s < 2: return A, B, p, q
def enc(m, key):
ctxt = [ (g(c, key) << 8) + g(c^0xbc, key) for c in m ]
return b"".join( [ v.to_bytes(2, "big") for v in ctxt ])
t0 = datetime.datetime.utcnow()
credits = sum( getWeights(makeStamp(t0))[-29:] )
while True:
if credits <= 0:
print("out of credits :/ ")
break
print(
f"""
1) encrypt message [1 credit]
2) encrypt flag [50 credits]
3) buy time [1000 credits]
4) quit
You have {credits} credits.
""", flush = True
)
choice = input("> ")
if choice == "1":
credits -= 1
msghex = input("message in hex: ")
try:
msg = bytes.fromhex(msghex)
except ValueError:
print("invalid hex", flush = True)
continue
key = keygen()
print( enc(msg[:50], key).hex(), flush = True )
elif choice == "2":
credits -= 50
key = keygen()
print( enc(FLAG, key).hex(), flush = True )
elif choice == "3":
if credits < 1000:
print("insufficient credit", flush = True)
continue
credits -= 1000
try:
delta = float( input("Time gain: ") )
if abs(delta) > 5: raise ValueError
t0 += datetime.timedelta(seconds = delta)
except ValueError:
print("invalid input", flush = True)
elif choice == "4": break
print("Goodbye!", flush = True)
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/b01lers/2025/jail/shakespearejail/server.py | ctfs/b01lers/2025/jail/shakespearejail/server.py | #!/usr/local/bin/python3
import io
import random
import sys
from shakespearelang.shakespeare import Shakespeare
print("You're nothing like a summers day.")
print("enter your play > ")
blacklist = [
"Heaven",
"King",
"Lord",
"angel",
"flower",
"happiness",
"joy",
"plum",
"summer's",
"day",
"hero",
"rose",
"kingdom",
"pony",
"animal",
"aunt",
"brother",
"cat",
"chihuahua",
"cousin",
"cow",
"daughter",
"door",
"face",
"father",
"fellow",
"granddaughter",
"grandfather",
"grandmother",
"grandson",
"hair",
"hamster",
"horse",
"lamp",
"lantern",
"mistletoe",
"moon",
"morning",
"mother",
"nephew",
"niece",
"nose",
"purse",
"road",
"roman",
"sister",
"sky",
"son",
"squirrel",
"stone",
"wall",
"thing",
"town",
"tree",
"uncle",
"wind",
"Hell",
"Microsoft",
"bastard",
"beggar",
"blister",
"codpiece",
"coward",
"curse",
"death",
"devil",
"draught",
"famine",
"flirt-gill",
"goat",
"hate",
"hog",
"hound",
"leech",
"lie",
"pig",
"plague",
"starvation",
"toad",
"war",
"wolf"
]
blacklist += ["open",
"listen"]
blacklist += ["am ",
"are ",
"art ",
"be ",
"is "]
solution = ""
for line in sys.stdin:
solution += line.lower()
if line.strip().lower() == "[exeunt]":
break
print("play received")
disallowed = False
for word in blacklist:
if word.lower() in solution:
print(f"You used an illegal word: {word}")
disallowed = True
break
if not solution.isascii():
print("there were non-ascii characters in your solution.")
disallowed = True
if (not disallowed):
old_stdout = sys.stdout
old_stdin = sys.stdin
sys.stdout = io.StringIO()
sys.stdin = io.StringIO()
try:
interpreter = Shakespeare(play=solution, input_style='basic', output_style='basic')
interpreter.run()
payload = sys.stdout.getvalue()
finally:
sys.stdout = old_stdout
sys.stdin = old_stdin
eval(payload)
else:
with open("insults.txt", "r") as file:
insults = file.readlines()
random_insult = random.choice(insults).strip()
print(random_insult) | python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/b01lers/2025/crypto/leetprime/server.py | ctfs/b01lers/2025/crypto/leetprime/server.py | from random import randint, randbytes
from Crypto.Util.number import isPrime
from hashlib import sha256
def proof_of_work():
while True:
prefix = randbytes(4)
print(f"prefix (hex): {prefix.hex()}")
ans = bytes.fromhex(input("ans (hex): ").strip())
if int(sha256(prefix + ans).hexdigest(), 16) & (0xFFFFFF << 232) == 0:
break
proof_of_work()
with open("flag.txt", "r") as f:
flag = f.read()
f = lambda nbits: randint(13, 37).to_bytes(nbits, 'big')
while True:
leet_prime = int.from_bytes(randbytes(1 + 3 * 3 - 7), 'big')
if isPrime(leet_prime, false_positive_prob=133e-7, randfunc=f):
break
for _ in range(1337):
p = int(input("Prime number: ").strip())
if isPrime(p, false_positive_prob=133e-7, randfunc=f):
print(f"The power of leet prime >:D: {pow(leet_prime, p-1**337, p)}")
else:
print(f"Composite number sucks >:(")
if int(input("What is my leet prime: ").strip()) == leet_prime:
print(f"Flag for the leet: {flag}") | python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/b01lers/2025/crypto/Pesky_CBC/pesky_cbc.py | ctfs/b01lers/2025/crypto/Pesky_CBC/pesky_cbc.py | import secrets
from Crypto.Cipher import AES
try:
with open('./flag.txt', 'r') as f:
flag = f.read()
except:
flag = 'bctf{REDACTED}'
key1 = secrets.token_bytes(32)
key2 = secrets.token_bytes(32)
def pesky_decrypt(ciphertext):
assert len(ciphertext) % 16 == 0
iv1 = secrets.token_bytes(16)
iv2 = secrets.token_bytes(16)
c1 = AES.new(key1, AES.MODE_CBC, iv1)
c2 = AES.new(key2, AES.MODE_CBC, iv2)
return c1.decrypt(c2.decrypt(ciphertext))
def main():
cipher = AES.new(key2, AES.MODE_ECB)
secret = secrets.token_bytes(16)
ciphertext = cipher.encrypt(secret)
print('Here is the encrypted secret:')
print(ciphertext.hex())
print()
print('Here are some hints for you ^_^')
for _ in range(8):
random_value = secrets.token_bytes(16)
ciphertext = cipher.encrypt(random_value)
print(random_value.hex())
print(ciphertext.hex())
print()
while True:
print('Options:')
print('1: pesky decrypt')
print('2: guess secret')
choice = input('>> ').strip()
if choice == '1':
ciphertext = bytes.fromhex(input('>> '))
print(pesky_decrypt(ciphertext).hex())
elif choice == '2':
guess = bytes.fromhex(input('>> '))
if secret == guess:
print('Here is your flag :)')
print(flag)
return
else:
print('lmao skill issue')
return
else:
print('Invalid Choice')
return
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/b01lers/2025/crypto/ASSS/ASSS.py | ctfs/b01lers/2025/crypto/ASSS/ASSS.py | from Crypto.Util.number import getPrime, bytes_to_long
def evaluate_poly(poly:list, x:int, s:int):
return s + sum(co*x**(i+1) for i, co in enumerate(poly))
s = bytes_to_long(open("./flag.txt", "rb").read())
a = getPrime(64)
poly = [a*getPrime(64) for _ in range(1, 20)]
share = getPrime(64)
print(f"Here is a ^_^: {a}")
print(f"Here is your share ^_^: ({share}, {evaluate_poly(poly, share, s)})") | python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/b01lers/2022/pwn/veryfastvm/cpu.py | ctfs/b01lers/2022/pwn/veryfastvm/cpu.py | import sys
import os
import random
import struct
X13 = 1024*1024
X14 = 10
X15 = 2000
X16 = 55
class Instruction:
op = None
imm = 0
X11 = None
X12 = None
dsp = None
X08 = None
X10 = 0
X02 = 0
def __init__(self, tstr):
def X06(tt):
if tt.startswith("0x"):
try:
v = int(tt, 16)
except ValueError:
assert False
else:
try:
v = int(tt)
except ValueError:
assert False
assert v>=0
assert v<pow(2,32)
return v
def X17_X08(tt):
try:
v = int(tt)
except ValueError:
assert False
assert v>-1000
assert v<1000
return v
def X07(tt):
assert len(tt) == 2
assert tt[0] == "r"
try:
v = int(tt[1])
except ValueError:
assert False
assert v>=0
assert v<X14
return v
def X17_memory(tt):
try:
v = int(tt)
except ValueError:
assert False
assert v>=0
assert v<X13
return v
assert len(tstr)<100
sstr = tstr.split()
assert len(sstr)>=1
assert len(sstr)<=4
if len(sstr) == 1:
t_op = sstr[0]
assert t_op in ["halt", "time", "magic", "reset"]
self.op = t_op
elif len(sstr) == 2:
t_op, t_1 = sstr
assert t_op in ["jmp", "jmpz"]
self.op = t_op
if self.op == "jmp":
self.X08 = X17_X08(t_1)
elif self.op == "jmpz":
self.X08 = X17_X08(t_1)
else:
assert False
elif len(sstr) == 3:
t_op, t_1, t_2 = sstr
assert t_op in ["mov", "movc", "jmpg", "add", "sub", "mul", "and", "or", "xor"]
self.op = t_op
if self.op == "mov":
self.X11 = X07(t_1)
self.X12 = X07(t_2)
elif self.op in ["add", "sub", "mul", "and", "or", "xor"]:
self.X11 = X07(t_1)
self.X12 = X07(t_2)
elif self.op == "movc":
self.X11 = X07(t_1)
self.imm = X06(t_2)
elif self.op == "jmpg":
self.X08 = X17_X08(t_2)
self.X11 = X07(t_1)
else:
assert False
elif len(sstr) == 4:
t_op, t_1, t_2, t_3 = sstr
assert t_op in ["movfrom", "movto"]
self.op = t_op
if self.op == "movfrom":
self.X11 = X07(t_1)
self.X10 = X17_memory(t_2)
self.dsp = X07(t_3)
elif self.op == "movto":
self.X11 = X07(t_1)
self.X10 = X17_memory(t_2)
self.dsp = X07(t_3)
else:
assert False
else:
assert False
def pprint(self):
tstr = "%s %s %s %s %s %s" % (self.op,
"None" if self.X11==None else "r%d"%self.X11,
"None" if self.X12==None else "r%d"%self.X12,
hex(self.imm), "None" if self.X08==None else self.X08, self.X10)
return tstr
class Cpu:
X05 = 0
instructions = None
X01 = None
memory = None
X02 = 0
X03 = None
X00 = 0
X04 = None
def __init__(self):
self.instructions = []
self.X03 = {}
self.X04 = (random.randint(1,4200000000), random.randint(1,4200000000) , random.randint(1,4200000000), random.randint(1,4200000000))
self.reset()
def reset(self):
self.X05 = 0
self.X01 = [0 for r in range(X14)]
self.memory = [0 for _ in range(X13)]
self.X02 = 0
for k in self.X03.keys():
self.X03[k] = 0
self.X00 += 1
def load_instructions(self, tt):
for line in tt.split("\n"):
if "#" in line:
line = line.split("#")[0]
line = line.strip()
if not line:
continue
self.instructions.append(Instruction(line))
assert len(self.instructions) <= X16
def run(self, debug=0):
ins = self.instructions[0]
for i,v in enumerate(self.X04):
self.memory[i] = v
while (self.X05>=0 and self.X05<len(self.instructions) and self.X00<4 and self.X02<20000):
ins = self.instructions[self.X05]
self.execute(ins)
def execute(self, ins):
self.X02 += 1
if ins.op == "movc":
self.X01[ins.X11] = ins.imm
self.X05 += 1
elif ins.op == "magic":
if self.X00 == 2:
if tuple(self.X01[0:4]) == self.X04:
with open("flag.txt", "rb") as fp:
cc = fp.read()
cc = cc.strip()
cc = cc.ljust(len(self.X01)*4, b"\x00")
for i in range(len(self.X01)):
self.X01[i] = struct.unpack("<I", cc[i*4:(i+1)*4])[0]
self.X05 += 1
elif ins.op == "reset":
self.reset()
elif ins.op == "halt":
self.X05 = len(self.instructions)
elif ins.op == "time":
self.X01[0] = self.X02
self.X05 += 1
elif ins.op == "jmp":
nt = self.X05 + ins.X08
assert nt >=0
assert nt < len(self.instructions)
self.X05 = nt
elif ins.op == "jmpz":
if self.X01[0] == 0:
nt = self.X05 + ins.X08
assert nt >=0
assert nt < len(self.instructions)
self.X05 = nt
else:
self.X05 += 1
elif ins.op == "jmpg":
if self.X01[0] > self.X01[ins.X11]:
nt = self.X05 + ins.X08
assert nt >=0
assert nt < len(self.instructions)
self.X05 = nt
else:
self.X05 += 1
elif ins.op == "mov":
self.X01[ins.X11] = self.X01[ins.X12]
self.X05 += 1
elif ins.op == "sub":
v = self.X01[ins.X11] - self.X01[ins.X12]
self.X01[ins.X11] = (v & 0xffffffff)
self.X05 += 1
elif ins.op == "add":
v = self.X01[ins.X11] + self.X01[ins.X12]
self.X01[ins.X11] = (v & 0xffffffff)
self.X05 += 1
elif ins.op == "mul":
v = self.X01[ins.X11] * self.X01[ins.X12]
self.X01[ins.X11] = (v & 0xffffffff)
self.X05 += 1
elif ins.op == "and":
v = self.X01[ins.X11] & self.X01[ins.X12]
self.X01[ins.X11] = (v & 0xffffffff)
self.X05 += 1
elif ins.op == "or":
v = self.X01[ins.X11] | self.X01[ins.X12]
self.X01[ins.X11] = (v & 0xffffffff)
self.X05 += 1
elif ins.op == "xor":
v = self.X01[ins.X11] ^ self.X01[ins.X12]
self.X01[ins.X11] = (v & 0xffffffff)
self.X05 += 1
elif ins.op == "movfrom":
X09 = ins.X10 + self.X01[ins.dsp]
X09 = X09 % len(self.memory)
if X09 in self.X03:
v = self.X03[X09]
v = (v & 0xffffffff)
self.X01[ins.X11] = v
self.X05 += 1
else:
v = self.memory[X09]
self.X03[X09] = v
self.execute(ins)
elif ins.op == "movto":
X09 = ins.X10 + self.X01[ins.dsp]
X09 = X09 % len(self.memory)
if X09 in self.X03:
del self.X03[X09]
v = (self.X01[ins.X11] & 0xffffffff)
self.memory[X09] = v
self.X05 += 1
else:
assert False
return
def pprint(self, debug=0):
tstr = ""
tstr += "%d> "%self.X05
tstr += "[%d] "%self.X02
tstrl = []
for i,r in enumerate(self.X01):
tstrl.append("r%d=%d"%(i,r))
tstr += ",".join(tstrl)
if debug>1:
tstr += "\nM->"
vv = []
for i,v in enumerate(self.memory):
if v!=0:
vv.append("%d:%d"%(i,v))
tstr += ",".join(vv)
tstr += "\nC->"
tstr += repr(self.X03)
return tstr
def main():
print("Welcome to a very fast VM!")
print("Give me your instructions.")
print("To terminate, send 3 consecutive empty lines.")
instructions = ""
X18 = 0
while True:
line = input()
if not line.strip():
X18 += 1
else:
X18 = 0
instructions += line + "\n"
if X18 >= 3 or len(instructions) > X15:
break
c = Cpu()
print("Parsing...")
c.load_instructions(instructions)
print("Running...")
c.run()
print("Done!")
print("Registers: " + repr(c.X01))
print("Goodbye.")
if __name__ == "__main__":
sys.exit(main()) | python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/b01lers/2022/crypto/Hardcore2/Hardcore.py | ctfs/b01lers/2022/crypto/Hardcore2/Hardcore.py | import numpy as np
from os import urandom
import binascii
import hashlib
from secret import FLAG1, FLAG2
# Helpers
def digest_to_array(digest):
hex_digest = binascii.hexlify(digest)
binary = bin(int(hex_digest, base=16)).lstrip('0b')
binary = np.array(list(binary))
# currently leading 0s are gone, add them back
missing_zeros = np.zeros(256 - len(binary))
binary = np.concatenate((missing_zeros, binary.astype(int)))
return binary.astype(int)
def bitstring_to_bytes(s):
return int(s, 2).to_bytes((len(s) + 7) // 8, byteorder='big')
####################################################################################
def generate_hardcore(secret, r):
return int(np.sum(secret * r) % 2)
def predictor(r, probability = 1):
x_r = (r.copy() != digest_to_array(FLAG))
np.random.seed(x_r)
chance = np.random.rand()
prediction = 0
if chance <= probability:
prediction = generate_hardcore(digest_to_array(FLAG), r)
else:
prediction = 1 - generate_hardcore(digest_to_array(FLAG), r)
return int(prediction)
def parse_input():
bitstring = input()
assert len(bitstring) == 256
assert set(bitstring) <= set(["0", "1"])
bitstring = bitstring_to_bytes(bitstring)
array = digest_to_array(bitstring) % 2
return array
def Level(probability):
hasher = hashlib.sha256()
hasher.update(FLAG)
encrypted_secret = hasher.hexdigest()
problem_statement = \
f"We're looking to find the secret behind this SHA1 hash <{str(encrypted_secret)}>. " \
"Luckily for you, this socket takes a bitstring and predicts the dot product " \
f"of the secret with that bit string (mod 2) with {int(100*probability)}% accuracy and sends you back the answer.\n"
print(problem_statement)
while True:
array = parse_input()
if array is None:
return
print(predictor(array, probability = probability))
def main():
global FLAG
diff = int(input("Select a difficulty (1/2):"))
if diff == 1:
FLAG = FLAG1
Level(1)
if diff == 2:
FLAG = FLAG2
Level(0.9)
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/b01lers/2022/crypto/Hardcore/Hardcore.py | ctfs/b01lers/2022/crypto/Hardcore/Hardcore.py | import numpy as np
from os import urandom
import binascii
import hashlib
from secret import FLAG1, FLAG2
# Helpers
def digest_to_array(digest):
hex_digest = binascii.hexlify(digest)
binary = bin(int(hex_digest, base=16)).lstrip('0b')
binary = np.array(list(binary))
# currently leading 0s are gone, add them back
missing_zeros = np.zeros(256 - len(binary))
binary = np.concatenate((missing_zeros, binary.astype(int)))
return binary.astype(int)
def bitstring_to_bytes(s):
return int(s, 2).to_bytes((len(s) + 7) // 8, byteorder='big')
####################################################################################
def generate_hardcore(secret, r):
return int(np.sum(secret * r) % 2)
def predictor(r, probability = 1):
x_r = (r.copy() != digest_to_array(FLAG))
np.random.seed(x_r)
chance = np.random.rand()
prediction = 0
if chance <= probability:
prediction = generate_hardcore(digest_to_array(FLAG), r)
else:
prediction = 1 - generate_hardcore(digest_to_array(FLAG), r)
return int(prediction)
def parse_input():
bitstring = input()
assert len(bitstring) == 256
assert set(bitstring) <= set(["0", "1"])
bitstring = bitstring_to_bytes(bitstring)
array = digest_to_array(bitstring) % 2
return array
def Level(probability):
hasher = hashlib.sha256()
hasher.update(FLAG)
encrypted_secret = hasher.hexdigest()
problem_statement = \
f"We're looking to find the secret behind this SHA1 hash <{str(encrypted_secret)}>. " \
"Luckily for you, this socket takes a bitstring and predicts the dot product " \
f"of the secret with that bit string (mod 2) with {int(100*probability)}% accuracy and sends you back the answer.\n"
print(problem_statement)
while True:
array = parse_input()
if array is None:
return
print(predictor(array, probability = probability))
def main():
global FLAG
diff = int(input("Select a difficulty (1/2):"))
if diff == 1:
FLAG = FLAG1
Level(1)
if diff == 2:
FLAG = FLAG2
Level(0.9)
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/idekCTF/2021/pwn/VeeAte/server.py | ctfs/idekCTF/2021/pwn/VeeAte/server.py | #!/usr/bin/env python3
# With credit/inspiration to the v8 problem in downUnder CTF 2020
import os
import subprocess
import sys
import tempfile
def p(a):
print(a, flush=True)
MAX_SIZE = 20000
input_size = int(input("Provide size. Must be < 5k:"))
if input_size >= MAX_SIZE:
p(f"Received size of {input_size}, which is too big")
sys.exit(-1)
p(f"Provide script please!!")
script_contents = sys.stdin.read(input_size)
p(script_contents)
# Don't buffer
with tempfile.NamedTemporaryFile(buffering=0) as f:
f.write(script_contents.encode("utf-8"))
p("File written. Running. Timeout is 20s")
res = subprocess.run(["./d8", f.name], timeout=20, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
p("Run Complete")
p(f"Stdout {res.stdout}")
p(f"Stderr {res.stderr}") | python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/idekCTF/2021/rev/Custom_Neural_Network/cnn_flag_checker.py | ctfs/idekCTF/2021/rev/Custom_Neural_Network/cnn_flag_checker.py | import numpy as np
import tensorflow as tf
def Float32Equal(a,b):
return np.abs(a - b) < np.finfo(np.float32).eps
def CheckImage(image, model_filename='flag_model.h5'):
if not Float32Equal(np.max(image), 1.0):
return False
if not Float32Equal(np.min(image), -1.0):
return False
model = tf.keras.models.load_model(model_filename)
input_image = image.copy()
input_image = np.delete(input_image, range(0,61,10), axis=1)
input_image = np.delete(input_image, range(0,61,10), axis=0)
input_image = np.expand_dims(input_image, axis=0)
return Float32Equal(model.predict([input_image])[0,0,0,0], 2916)
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/idekCTF/2021/crypto/Nameless/nameless.py | ctfs/idekCTF/2021/crypto/Nameless/nameless.py | #!/usr/bin/env python3
from Crypto.Util.number import getPrime, bytes_to_long
flag = bytes_to_long(open("flag.txt", "rb").read())
p = getPrime(1024)
q = getPrime(1024)
n = p*q
e = 65537
c = pow(flag, e, n)
print(f"{n = }")
print(f"{p**2 + q**2 = }")
print(f"{c = }")
# n = 17039353907577304435335064263404014554877715060984532599266619880863167873378099082282744647069063737519071263364836126585022715467571812084451441982393173641398961475914685815327955647115633127041896154455593434072255425400800779717723399468604805292082232853055652824142503280033249169812067036520117578584094798348819948005306782099055133323817492597665553443090585282100292603079932759878536941929823231580881942192749039900111873581375554659251791337260557811529597205007196563571790350676229812320194120553090511341491088451472118285832059742983329898372623700182290118257197824687682775782009980169859003817731
# p**2 + q**2 = 34254734236141177160574679812056859631858427160408786991475995766265871545173190051194038767461225382849521482292062983459474860288453334280315736001800236347672807900333594896297515619502911996316514299218938831378736595562870019767614772735193898275208842936903810908125651716713945099823849942766283224215669363078687494444967371294251548767512167452469907361824731739495988324619487099803563636546009036759134670516039262088500254966964852889263176272377467365967151127628965809347292638988052064278479647751273833336918088826074446862207626964731876317800211831559603043730904022957158490478667914769698472788362
# c = 12870370380105677159569686874593314643716517767455659912764832987663831817849402722874771360315463499459803247514426078866675686952348433836656840934671927466173330528381359767745015167610939855705805470288376941237662107279159556248387485524451540986787953598577323572841487131458590546170321983597795128547549803960136942090569419458036728363613060710384550676895546741408072019046530957103700345379626982758919062223712005709765751343132802610106335253368313457365776378662756844353849622352138042802036310704545247436297860319183507369367717753569233726139626694256257605892684852784606001755037052492614845787835
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/idekCTF/2021/crypto/Destroyed_RSA/chall.py | ctfs/idekCTF/2021/crypto/Destroyed_RSA/chall.py | import random
from Crypto.Util.number import bytes_to_long, getPrime, isPrime
from flag import flag
f = flag
def interesting_prime():
#recognize me?
D = 987
while True:
s = random.randint(2**1020,2**1021-1)
check = D * s ** 2 + 1
if check % 4 == 0 and isPrime((check // 4)):
return check // 4
m = bytes_to_long(f)
p = interesting_prime()
q = getPrime(2048)
N = p*q
e = 6551
c = pow(m, e, N)
with open('out.txt', 'w') as w:
w.write(f"n = {N}")
w.write(f"e = {e}")
w.write(f"c = {c}") | python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/idekCTF/2021/crypto/Seed_of_Life/garden.py | ctfs/idekCTF/2021/crypto/Seed_of_Life/garden.py | import random
seed = REDACTED
assert seed in range(10000000)
random.seed(seed)
for i in range(19):
random.seed(random.random())
seedtosave = random.random()
print("share1:")
for add in range(0, 1000):
random.seed(seedtosave+add)
for i in range(0, 100):
print(random.random())
print("share2:")
for add in range(0, 1000):
random.seed(seedtosave-add)
for i in range(0, 1000):
print(random.random())
print("share3:")
random.seed(seedtosave)
for i in range(0, 100):
print(random.random()*100) | python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/idekCTF/2021/crypto/Polyphenol/source.py | ctfs/idekCTF/2021/crypto/Polyphenol/source.py | import random
from secret import flag
assert flag[: 5] == b"idek{"
assert flag[-1:] == b"}"
L = len(flag[5: -1])
print(f"L = {L}")
coeff = list(flag[5: -1])
points = random.sample(range(L), L // 2)
evaluations = []
for p in points:
evaluations += [sum(c * p ** i for i, c in enumerate(coeff))]
print(f"points = {points}")
print(f"evaluations = {evaluations}")
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/idekCTF/2021/crypto/Hashbrown/chall.py | ctfs/idekCTF/2021/crypto/Hashbrown/chall.py | import string
import hashlib
import random
password2hash = b"REDACTED"
hashresult = hashlib.md5(password2hash).digest()
sha1 = hashlib.sha1(hashresult)
sha224 = hashlib.sha224(sha1.digest())
for i in range(0, 10):
sha1 = hashlib.sha1(sha224.digest())
sha224 = hashlib.sha224(sha1.digest())
output = sha224.hexdigest()
print("output: " + output) | python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/idekCTF/2021/web/saas/util.py | ctfs/idekCTF/2021/web/saas/util.py | from PIL import Image
import random
import jwt
import string
import os
from imghdr import tests
import subprocess
priv_key = open('keys/private.pem', 'r').read()
def create_token():
priv_key = open('keys/private.pem', 'r').read()
token = jwt.encode({"username": f"guest_{random.randint(1,10000)}"}, priv_key, algorithm='RS256', headers={'pubkey': 'public.pem'})
return token
def verify_token(token):
try:
headers = jwt.get_unverified_header(token)
pub_key_path = headers['pubkey']
pub_key_path = pub_key_path.replace('..', '') # no traversal!
pub_key_path = os.path.join(os.getcwd(), os.path.join('keys/', pub_key_path))
pub_key = open(pub_key_path, 'rb').read()
if b'BEGIN PUBLIC KEY' not in pub_key:
return False
return jwt.decode(token, pub_key, algorithms=['RS256', 'HS256'])
except:
return False
def rand_string():
return ''.join(random.choice(string.ascii_letters + string.digits) for i in range(32))
def embed_file(embed_file, cover_file, stegfile, password):
cmd = subprocess.Popen(['steghide', 'embed', '-ef', embed_file, '-cf', cover_file, '-sf', stegfile, '-p', password]).wait(timeout=.5)
def cleanup():
for f in os.listdir('uploads/'):
os.remove(os.path.join('uploads/', f))
for f in os.listdir('output/'):
os.remove(os.path.join('output/', f))
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/idekCTF/2021/web/saas/app.py | ctfs/idekCTF/2021/web/saas/app.py | from flask import Flask, request, render_template, make_response, redirect, send_file
import imghdr
from imghdr import tests
import hashlib
from util import *
# https://stackoverflow.com/questions/36870661/imghdr-python-cant-detec-type-of-some-images-image-extension
# there are no bugs here. just patching imghdr
JPEG_MARK = b'\xff\xd8\xff\xdb\x00C\x00\x08\x06\x06' \
b'\x07\x06\x05\x08\x07\x07\x07\t\t\x08\n\x0c\x14\r\x0c\x0b\x0b\x0c\x19\x12\x13\x0f'
def test_jpeg1(h, f):
"""JPEG data in JFIF format"""
if b'JFIF' in h[:23]:
return 'jpeg'
def test_jpeg2(h, f):
"""JPEG with small header"""
if len(h) >= 32 and 67 == h[5] and h[:32] == JPEG_MARK:
return 'jpeg'
def test_jpeg3(h, f):
"""JPEG data in JFIF or Exif format"""
if h[6:10] in (b'JFIF', b'Exif') or h[:2] == b'\xff\xd8':
return 'jpeg'
tests.append(test_jpeg1)
tests.append(test_jpeg2)
tests.append(test_jpeg3)
def verify_jpeg(file_path):
try:
jpeg = Image.open(file_path)
jpeg.verify()
if imghdr.what(file_path) != 'jpeg':
return False
return True
except:
return False
app = Flask(__name__)
app.config['MAX_CONTENT_LENGTH'] = 2 * 1024 * 1024
@app.route('/')
def index():
resp = make_response(render_template('upload.html'))
if not request.cookies.get('session'):
resp.set_cookie('session', create_token())
return resp
@app.route('/upload', methods=['POST'])
def upload():
if not request.cookies.get('session'):
return redirect('/')
session = request.cookies.get('session')
uploaded_file = request.files['file']
password = request.form['password']
content = request.form['content']
upload_name = uploaded_file.filename.replace('../', '') # no traversal!
output_name = os.path.join('output/', os.path.basename(upload_name))
image_data = uploaded_file.stream.read()
image_md5 = hashlib.md5(image_data).hexdigest()
image_path = f'uploads/{image_md5}.jpeg'
content_path = f"uploads/{rand_string()}.txt"
# write temp txt file
with open(content_path, 'w') as f:
f.write(content)
f.close()
# write temp image file
with open(image_path, 'wb') as f:
f.write(image_data)
f.close()
# verify jpeg validity
if not verify_jpeg(image_path):
return 'File is not a valid JPEG!', 400
# verify session before using it
session = verify_token(session)
if not session:
return 'Session token invalid!', 400
# attempt to embed message in image
try:
embed_file(content_path, image_path, output_name, password)
except:
return 'Embedding failed!', 400
# append username to output path to prevent vulns
sanitized_path = f'output/{upload_name}_{session["username"]}'
try:
if not os.path.exists(sanitized_path):
os.rename(output_name, sanitized_path)
except:
pass
try:
return send_file(sanitized_path)
except:
return 'Something went wrong! Check your file name', 400
app.run('0.0.0.0', 1337)
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/idekCTF/2021/web/fancy-notes/app.py | ctfs/idekCTF/2021/web/fancy-notes/app.py | from flask import Flask, redirect, request, session, send_from_directory, render_template
import os
import sqlite3
import subprocess
app = Flask(__name__, static_url_path='/static', static_folder='static', template_folder='templates')
app.secret_key = os.getenv('SECRET', 'secret')
ADMIN_PASS = os.getenv('ADMIN_PASS', 'password')
flag = open('flag.txt', 'r').read()
def init_db():
con = sqlite3.connect('/tmp/database.db')
cur = con.cursor()
cur.execute('CREATE TABLE IF NOT EXISTS users (id INTEGER PRIMARY KEY AUTOINCREMENT, username TEXT NOT NULL UNIQUE, password TEXT NOT NULL)')
cur.execute('INSERT INTO USERS (username, password) VALUES ("admin", ?)', [ADMIN_PASS])
cur.execute('CREATE TABLE IF NOT EXISTS notes (title TEXT NOT NULL, content TEXT NOT NULL, owner TEXT NOT NULL)')
cur.execute('INSERT INTO notes (title, content, owner) VALUES ("flag", ?, 1)', [flag])
con.commit()
con.close()
def try_login(username, password):
con = sqlite3.connect('/tmp/database.db')
cur = con.cursor()
cur.execute('SELECT * FROM users WHERE username = ? AND password = ?', [username, password])
row = cur.fetchone()
if row:
return {'id': row[0], 'username': row[1]}
def try_register(username, password):
con = sqlite3.connect('/tmp/database.db')
cur = con.cursor()
try:
cur.execute('INSERT INTO users (username, password) VALUES (?, ?)', [username, password])
except sqlite3.IntegrityError:
return None
con.commit()
con.close()
return True
def find_note(query, user):
con = sqlite3.connect('/tmp/database.db')
cur = con.cursor()
cur.execute('SELECT title, content FROM notes WHERE owner = ? AND (INSTR(content, ?) OR INSTR(title,?))', [user, query, query])
rows = cur.fetchone()
return rows
def get_notes(user):
con = sqlite3.connect('/tmp/database.db')
cur = con.cursor()
cur.execute('SELECT title, content FROM notes WHERE owner = ?', [user])
rows = cur.fetchall()
return rows
def create_note(title, content, user):
con = sqlite3.connect('/tmp/database.db')
cur = con.cursor()
cur.execute('SELECT title FROM notes where title=? AND owner=?', [title, user])
row = cur.fetchone()
if row:
return False
cur.execute('INSERT INTO notes (title, content, owner) VALUES (?, ?, ?)', [title, content, user])
con.commit()
con.close()
return True
@app.before_first_request
def setup():
try:
os.remove('/tmp/database.db')
except:
pass
init_db()
@app.after_request
def add_headers(response):
response.headers['Cache-Control'] = 'no-store'
return response
@app.route('/')
def index():
if not session:
return redirect('/login')
notes = get_notes(session['id'])
return render_template('index.html', notes=notes, message='select a note to fancify!')
@app.route('/login', methods = ['GET', 'POST'])
def login():
if request.method == 'GET':
return render_template('login.html')
if request.method == 'POST':
password = request.form['password']
username = request.form['username']
user = try_login(username, password)
if user:
session['id'] = user['id']
session['username'] = user['username']
return redirect('/')
else:
return render_template('login.html', message='login failed!')
@app.route('/register', methods=['GET', 'POST'])
def register():
if request.method == 'GET':
return render_template('register.html')
if request.method == 'POST':
username = request.form['username']
password = request.form['password']
if try_register(username, password):
return redirect('/login')
return render_template('register.html', message='registration failed!')
@app.route('/create', methods=['GET', 'POST'])
def create():
if not session:
return redirect('/login')
if session['username'] == 'admin':
return 'nah'
if request.method == 'GET':
return render_template('create.html')
if request.method == 'POST':
title = request.form['title']
content = request.form['content']
if len(title) >= 36 or len(content) >= 256:
return 'pls no'
if create_note(title, content, session['id']):
return render_template('create.html', message='note successfully uploaded!')
return render_template('create.html', message='you already have a note with that title!')
@app.route('/fancy')
def fancify():
if not session:
return redirect('/login')
if 'q' in request.args:
def filter(obj):
return any([len(v) > 1 and k != 'q' for k, v in request.args.items()])
if not filter(request.args):
results = find_note(request.args['q'], session['id'])
if results:
message = 'here is your ๐ป๐ถ๐๐ธ๐ note!'
else:
message = 'no notes found!'
return render_template('fancy.html', note=results, message=message)
return render_template('fancy.html', message='bad format! Your style params should not be so long!')
return render_template('fancy.html')
@app.route('/report', methods=['GET', 'POST'])
def report():
if not session:
return redirect('/')
if request.method == 'GET':
return render_template('report.html')
url = request.form['url']
subprocess.Popen(['node', 'bot.js', url], shell=False)
return render_template('report.html', message='admin visited your url!')
app.run('0.0.0.0', 1337)
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/idekCTF/2021/web/escalator/escalator.py | ctfs/idekCTF/2021/web/escalator/escalator.py | from flask import Flask, render_template, session, request, redirect, flash, make_response, jsonify
import mysql.connector
import secrets
import time
import json
import os
import subprocess
import sys
from datetime import datetime
app = Flask(__name__)
app.secret_key = os.environ['SECRET_KEY']
flag = os.environ['FLAG']
realAdminKey = os.environ['KEY']
config = {
'host': os.environ['DB_HOST'],
'user': os.environ['DB_USER'],
'password': os.environ['DB_PASS'],
'database': os.environ['DB'],
'sql_mode': 'NO_BACKSLASH_ESCAPES'
}
adminKeys=[realAdminKey]
for i in range(30):
try:
conn = mysql.connector.connect(**config)
break
except mysql.connector.errors.DatabaseError:
time.sleep(1)
else: conn = mysql.connector.connect(**config)
cursor = conn.cursor()
try: cursor.execute('CREATE TABLE `tracking` (`id` varchar(600),`time` varchar(64),`place` varchar(64))')
except mysql.connector.errors.ProgrammingError: pass
try: cursor.execute('CREATE TABLE `flag` (`flag` varchar(600))')
except mysql.connector.errors.ProgrammingError: pass
cursor.close()
conn.close()
@app.route('/')
def outofbounds():
cnx = mysql.connector.connect(**config)
cur = cnx.cursor()
id=request.cookies.get('id')
if id:
if("'" in id):
return redirect("https://www.youtube.com/watch?v=dQw4w9WgXcQ")
now = datetime.now()
current_time = now.strftime("%H:%M:%S")
cur.execute(f"INSERT INTO tracking VALUES ('{id}','{current_time}','/')")
else:
id= secrets.token_hex(32)
cur.execute(f"INSERT INTO flag VALUES ('{flag}')")
cnx.commit()
cur.close()
cnx.close()
toSay= request.args.get('toSay')
resp = make_response(render_template('escalator.html',toSay=toSay))
resp.set_cookie('id',id)
return resp
def convertTuple(tup):
# initialize an empty string
str = ''
for item in tup:
str = str + item
return str
@app.route('/trackinfo')
def getInfo():
cnx = mysql.connector.connect(**config)
cur = cnx.cursor()
query = request.args.get('query')
id=request.cookies.get('id')
if("'" in id):
return redirect("https://www.youtube.com/watch?v=dQw4w9WgXcQ")
if(id not in adminKeys):
return render_template('accessdenied.html')
cur.execute(query)
rows = []
for resp in cur:
rows.append(convertTuple(resp))
cur.close()
cnx.close()
return jsonify(rows)
@app.route('/admin', methods=['POST','GET'])
def signOut():
if (not request.args.get('inputtext')):
return render_template('clear.html')
resp = make_response(redirect('/'))
if(request.args.get('inputtext') in adminKeys):
adminKeys.pop(adminKeys.index(request.args.get('inputtext')))
return resp
@app.route('/report', methods=['GET', 'POST'])
def report():
if request.method == 'GET':
return render_template('report.html')
url = request.form.get('url')
if not url:
return render_template('report.html',str='url is required')
if not url.startswith('http://'):
return render_template('report.html',str='invalid url')
id= secrets.token_hex(32)
adminKeys.append(id)
subprocess.Popen(['node', 'bot.js', url,id], shell=False)
flash('Admin is visiting your link!')
return render_template('report.html')
if __name__ == "__main__":
app.run(host='0.0.0.0', port=1337, threaded=True)
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/idekCTF/2021/web/generic-pastebin/app.py | ctfs/idekCTF/2021/web/generic-pastebin/app.py | from flask import Flask, redirect, request, session, send_from_directory, render_template, render_template_string, g, make_response, flash
import os
import sqlite3
import random
import string
import re
import socket
import subprocess
app = Flask(__name__)
app.secret_key = os.getenv('SECRET_KEY', 's3cr3t_k3y')
ADMIN_PASS = os.getenv('ADMIN_PASS', 'adm1n_pa55w0rd')
FLAG = os.getenv('FLAG', 'idek{test_flag}')
def init_db():
con = sqlite3.connect('/tmp/database.db')
cur = con.cursor()
cur.execute('CREATE TABLE IF NOT EXISTS users (id INTEGER PRIMARY KEY AUTOINCREMENT, username TEXT NOT NULL UNIQUE, password TEXT NOT NULL, is_admin INTEGER)')
cur.execute('INSERT INTO USERS (username, password, is_admin) VALUES ("admin", ?, 1)', [ADMIN_PASS])
cur.execute('CREATE TABLE IF NOT EXISTS pastes (id TEXT NOT NULL UNIQUE, title TEXT NOT NULL, content TEXT NOT NULL, owner)')
cur.execute('INSERT INTO pastes (id, title, content, owner) VALUES ("flag", "flag", ?, "admin")', [FLAG])
con.commit()
con.close()
def try_login(username, password):
con = sqlite3.connect('/tmp/database.db')
cur = con.cursor()
cur.execute('SELECT * FROM users WHERE username = ? AND password = ?', [username, password])
row = cur.fetchone()
if row:
return {'id': row[0], 'username': row[1], 'is_admin': row[3]}
def try_register(username, password):
con = sqlite3.connect('/tmp/database.db')
cur = con.cursor()
try:
cur.execute('INSERT INTO users (username, password, is_admin) VALUES (?, ?, 0)', [username, password])
except sqlite3.IntegrityError:
return None
con.commit()
con.close()
return True
def get_all_pastes(username, is_admin=False):
con = sqlite3.connect('/tmp/database.db')
cur = con.cursor()
cur.execute('SELECT id, title FROM pastes WHERE owner = ?', [username])
rows = cur.fetchall()
if is_admin and username != 'admin':
cur.execute('SELECT id, title FROM pastes WHERE owner = "admin"')
admin_rows = cur.fetchall()
rows += admin_rows
return rows
def get_paste(username, paste_id, is_admin=False):
con = sqlite3.connect('/tmp/database.db')
cur = con.cursor()
if is_admin:
cur.execute('SELECT title, content FROM pastes WHERE id = ?', [paste_id])
else:
cur.execute('SELECT title, content FROM pastes WHERE id = ? AND owner = ?', [paste_id, username])
row = cur.fetchone()
if row:
return {'title': row[0], 'content': row[1]}
def create_paste(username, title, content):
paste_id = gen_token()
con = sqlite3.connect('/tmp/database.db')
cur = con.cursor()
cur.execute('INSERT INTO pastes (id, title, content, owner) VALUES (?, ?, ?, ?)', [paste_id, title, content, username])
con.commit()
con.close()
return paste_id
def gen_token():
return ''.join(random.choice(string.ascii_letters + string.digits) for i in range(32))
@app.before_first_request
def setup():
try:
os.remove('/tmp/database.db')
except:
pass
init_db()
@app.before_request
def add_flashes():
if 'error' in request.args.keys():
msg = request.args['error'].lower()
# no event handlers
if all(bad_string in msg for bad_string in ['on', '=']):
return
# none of this shit
if any(bad_string in msg for bad_string in ['script', 'svg', 'object', 'img', '/', ':', '>']):
return
flash(msg)
@app.route('/')
def index():
if not session:
return redirect('/login')
pastes = get_all_pastes(session['username'])
return render_template('index.html', pastes=pastes)
@app.route('/login', methods = ['GET', 'POST'])
def login():
if request.method == 'GET':
return render_template('login.html')
if request.method == 'POST':
password = request.form['password']
username = request.form['username']
user = try_login(username, password)
if user:
session['id'] = user['id']
session['username'] = user['username']
session['is_admin'] = user['is_admin']
return redirect('/')
return redirect('/login?error=login failed')
@app.route('/register', methods=['GET', 'POST'])
def register():
if request.method == 'GET':
return render_template('register.html')
if request.method == 'POST':
username = request.form['username']
password = request.form['password']
if try_register(username, password):
return redirect('/login')
return redirect('/register?error=registration failed')
@app.route('/pastes/<paste_id>')
def show_paste(paste_id):
if not session:
return redirect('/login?error=Please log in')
paste = get_paste(session['username'], paste_id, is_admin=session['is_admin'])
return render_template('view_paste.html', paste=paste)
@app.route('/create', methods=['GET', 'POST'])
def create():
if not session:
return redirect('/login?error=Please log in')
if request.method == 'GET':
return render_template('create.html')
elif request.method == 'POST':
if session['username'] == 'admin':
return 'Admin may not create new pastes'
if not all([field in request.form for field in ['title', 'content']]):
return 'Missing fields!'
title = request.form['title']
content = request.form['content']
if len(title) > 12:
flash('Title must not be longer than 12 characters!')
return redirect('/create')
if len(content) > 256:
flash('Content must not be longer than 256 characters!')
return redirect('/create')
paste_id = create_paste(session['username'], title, content)
return redirect(f'/pastes/{paste_id}')
@app.route('/report', methods=['GET', 'POST'])
def report():
if not session:
return redirect('/login?error=Please log in')
if request.method == 'GET':
return render_template('report.html')
url = request.form.get('url')
if not url:
flash('url is required')
return render_template('report.html')
if not url.startswith('http://'):
flash('invalid url')
return render_template('report.html')
subprocess.Popen(['node', 'bot.js', url], shell=False)
flash('Admin is visiting your link!')
return render_template('report.html')
if __name__ == "__main__":
app.run(host='0.0.0.0', port=1337, threaded=True)
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/idekCTF/2021/web/baby-jinjail/app.py | ctfs/idekCTF/2021/web/baby-jinjail/app.py | from flask import Flask, render_template_string, request
app = Flask(__name__)
blacklist = [
'request',
'config',
'self',
'class',
'flag',
'0',
'1',
'2',
'3',
'4',
'5',
'6',
'7',
'8',
'9',
'"',
'\'',
'.',
'\\',
'`',
'%',
'#',
]
error_page = '''
{% extends "layout.html" %}
{% block body %}
<center>
<section class="section">
<div class="container">
<h1 class="title">Error :(</h1>
<p>Your request was blocked. Please try again!</p>
</div>
</section>
</center>
{% endblock %}
'''
@app.route('/', methods=['GET', 'POST'])
def index():
if request.method == 'POST':
if not request.form['q']:
return render_template_string(error_page)
if len(request.form) > 1:
return render_template_string(error_page)
query = request.form['q'].lower()
if '{' in query and any([bad in query for bad in blacklist]):
return render_template_string(error_page)
page = \
'''
{{% extends "layout.html" %}}
{{% block body %}}
<center>
<section class="section">
<div class="container">
<h1 class="title">You have entered the raffle!</h1>
<ul class=flashes>
<label>Hey {}! We have received your entry! Good luck!</label>
</ul>
</br>
</div>
</section>
</center>
{{% endblock %}}
'''.format(query)
elif request.method == 'GET':
page = \
'''
{% extends "layout.html" %}
{% block body %}
<center>
<section class="section">
<div class="container">
<h1 class="title">Welcome to the idekCTF raffle!</h1>
<p>Enter your name below for a chance to win!</p>
<form action='/' method='POST' align='center'>
<p><input name='q' style='text-align: center;' type='text' placeholder='your name' /></p>
<p><input value='Submit' style='text-align: center;' type='submit' /></p>
</form>
</div>
</section>
</center>
{% endblock %}
'''
return render_template_string(page)
app.run('0.0.0.0', 1337)
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/idekCTF/2021/web/jinjail/app.py | ctfs/idekCTF/2021/web/jinjail/app.py | from flask import Flask, render_template_string, request
app = Flask(__name__)
blacklist = [
'request',
'config',
'self',
'class',
'flag',
'0',
'1',
'2',
'3',
'4',
'5',
'6',
'7',
'8',
'9',
'"',
'\'',
'.',
'\\',
'`',
'%',
'#',
]
error_page = '''
{% extends "layout.html" %}
{% block body %}
<center>
<section class="section">
<div class="container">
<h1 class="title">Error :(</h1>
<p>Your request was blocked. Please try again!</p>
</div>
</section>
</center>
{% endblock %}
'''
@app.route('/', methods=['GET', 'POST'])
def index():
if request.method == 'POST':
if not request.form['q']:
return render_template_string(error_page)
if len(request.form) > 1:
return render_template_string(error_page)
query = request.form['q'].lower()
if '{' in query and any([bad in query for bad in blacklist]):
return render_template_string(error_page)
if len(query) > 256:
return render_template_string(error_page)
page = \
'''
{{% extends "layout.html" %}}
{{% block body %}}
<center>
<section class="section">
<div class="container">
<h1 class="title">You have entered the raffle!</h1>
<ul class=flashes>
<label>Hey {}! We have received your entry! Good luck!</label>
</ul>
</br>
</div>
</section>
</center>
{{% endblock %}}
'''.format(query)
elif request.method == 'GET':
page = \
'''
{% extends "layout.html" %}
{% block body %}
<center>
<section class="section">
<div class="container">
<h1 class="title">Welcome to the idekCTF raffle!</h1>
<p>Enter your name below for a chance to win!</p>
<form action='/' method='POST' align='center'>
<p><input name='q' style='text-align: center;' type='text' placeholder='your name' /></p>
<p><input value='Submit' style='text-align: center;' type='submit' /></p>
</form>
</div>
</section>
</center>
{% endblock %}
'''
return render_template_string(page)
app.run('0.0.0.0', 1337)
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/idekCTF/2023/pwn/coroutine/proxy.py | ctfs/idekCTF/2023/pwn/coroutine/proxy.py | import socket
import sys
import time
import subprocess
proc = subprocess.Popen('./CoroutineCTFChal',stdout=subprocess.PIPE)
line = proc.stdout.readline()
assert line.startswith(b'port number ')
port = int(line[len('port number '):])
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
for _ in range(14):
print('Select Option:')
print('1. Connect')
print('2. Change Receive Buffer')
print('3. Change Send Buffer')
print('4. Send data')
print('5. Receive data')
option = input('> ').strip()
match option:
case '1':
s.connect(('localhost', port))
case '2':
size = int(input('Buffer size> ').strip())
s.setsockopt(socket.SOL_SOCKET, socket.SO_RCVBUF, size)
case '3':
size = int(input('Buffer size> ').strip())
s.setsockopt(socket.SOL_SOCKET, socket.SO_SNDBUF, size)
case '4':
data = input('Data> ').strip()
s.send(data.encode('utf-8')[:512])
case '5':
size = int(input('Size> ').strip())
print(s.recv(size))
case _:
print('Invalid option')
sys.exit(1)
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/idekCTF/2023/crypto/decidophobia/server.py | ctfs/idekCTF/2023/crypto/decidophobia/server.py | #!/usr/bin/env python3
from Crypto.Util.number import *
import random
import signal
class Pool():
def __init__(self):
self.p, self.q, self.r = None, None, None
class PrimeMan():
def __init__(self):
self.p, self.q, self.r = None, None, None
def gen(self, nbits, ticket):
self.p = getPrime(nbits)
self.q = getPrime(nbits)
self.r = getPrime(nbits)
self.n = self.p * self.q * self.r
self.enc = pow(ticket, 0x10001, self.n)
print("You: Integer factoring is hard! No one can steal my ticket now :D.")
def throw_primes(self, pool):
print("Today, you go to the forest to cut down trees as usual. You see a good tree to cut down. The tree is near a pool. But you already worked hard all day. You could not hold your ax and primes very well. The primes slip out of your hands. They go in to the pool.")
pool.p, pool.q, pool.r = self.p, self.q, self.r
self.p, self.q, self.r = None, None, None
def print_backpack(self):
print("")
print(f"n = {self.n}")
print(f"enc = {self.enc}")
class Mercury():
def __init__(self):
self.p, self.q, self.r = None, None, None
def welcome_msg(self):
print("")
print("Mercury: What happened? Why are you crying?")
print("")
print("[1] I lost my primes in the pool. It is the only thing I have, I cannot recover the key without it.")
print("[2] Ignore Mercury")
op = int(input(">>> "))
if op == 2:
print("")
print("No, you cannot ignore me <3.")
def find_primes(self, pool):
print("")
print("Mercury jumps into the pool ... ")
self.p, self.q, self.r = pool.p, pool.q, pool.r
pool.p, pool.q, pool.r = None, None, None
print("He comes up with a good prime, a silver prime and a bronze prime!")
def oblivious(self):
P = getPrime(384)
Q = getPrime(384)
N = P * Q
d = pow(0x10001, -1, (P-1)*(Q-1))
x1 = random.randint(0, N-1)
x2 = random.randint(0, N-1)
x3 = random.randint(0, N-1)
print("Mercury: It's boring to directly give you prime back, I'll give you the prime thrugh oblivious transfer! Here are the parameters: ")
print("")
print(f"N = {N}")
print(f"x1 = {x1}")
print(f"x2 = {x2}")
print(f"x3 = {x3}")
"""
Pick a random r and compute v = r**65537 + x1/x2/x3
If you added x1/x2/x3, then you can retrieve p/q/r by calculating c1/c2/c3 - k % n
"""
v = int(input("Which one is your prime? Gimme your response: "))
k1 = pow(v-x1, d, N)
k2 = pow(v-x2, d, N)
k3 = pow(v-x3, d, N)
c1 = (k1+self.p) % N
c2 = (k2+self.q) % N
c3 = (k3+self.r) % N
print("")
print(f"c1 = {c1}")
print(f"c2 = {c2}")
print(f"c3 = {c3}")
class Story():
def __init__(self):
self.primeman = PrimeMan()
self.pool = Pool()
self.mercury = Mercury()
def prologue(self):
print("Yesterday, you received a ticket to the royal party from PrimeKing. You were afraid that someone would steal the ticket, so you encrpyted the ticket by unbreakable RSA!")
self.ticket = random.randint(0, 1 << 1500)
self.primeman.gen(512, self.ticket)
self.primeman.throw_primes(self.pool)
def menu(self):
print("")
print("[1] Look in your backpack")
print("[2] Cry")
print("[3] Jump into the pool")
print("[4] Go to the party")
print("[5] Exit")
op = int(input(">>> "))
return op
def loop(self, n):
for _ in range(n):
op = self.menu()
if op == 1:
self.primeman.print_backpack()
elif op == 2:
if self.mercury:
self.mercury.welcome_msg()
self.mercury.find_primes(self.pool)
self.mercury.oblivious()
self.mercury = None
else:
print("")
print("Mercury went back to the heaven ... ")
elif op == 3:
print("")
print("Find nothing ...")
elif op == 4:
inp = int(input("Guard: Give me your ticket. "))
if inp == self.ticket:
with open("flag.txt", "r") as f:
print("")
print(f.read())
else:
print("")
print("Go away!")
elif op == 5:
print("")
print("Bye!")
break
if __name__ == '__main__':
signal.alarm(120)
s = Story()
s.prologue()
s.loop(1337)
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/idekCTF/2023/crypto/cleithrophobia/cleithrophobia.py | ctfs/idekCTF/2023/crypto/cleithrophobia/cleithrophobia.py | #!/usr/bin/env python3
#
# Polymero
#
# Imports
from Crypto.Cipher import AES
from Crypto.Util.Padding import pad, unpad
import os
# Local imports
with open('flag.txt', 'rb') as f:
FLAG = f.read()
f.close()
# Header
HDR = r"""|
|
| __ _ ___ ____ ______ __ __ ____ ___ ____ __ __ ___ ____ ____ ____
| / ] | / _] | | | | \ / \| \| | |/ \| \| |/ |
| / /| | / [_ | || | | | D ) | o ) | | | o )| || o |
| / / | |___/ _]| ||_| |_| _ | /| O | _/| _ | O | || || |
| / \_| | [_ | | | | | | | \| | | | | | | O || || _ |
| \ | | || | | | | | | . \ | | | | | | || || | |
| \____|_____|_____|____| |__| |__|__|__|\_|\___/|__| |__|__|\___/|_____|____|__|__|
|
|"""
# Server encryption function
def encrypt(msg, key):
pad_msg = pad(msg, 16)
blocks = [os.urandom(16)] + [pad_msg[i:i+16] for i in range(0,len(pad_msg),16)]
itm = [blocks[0]]
for i in range(len(blocks) - 1):
tmp = AES.new(key, AES.MODE_ECB).encrypt(blocks[i+1])
itm += [bytes(j^k for j,k in zip(tmp, blocks[i]))]
cip = [blocks[0]]
for i in range(len(blocks) - 1):
tmp = AES.new(key, AES.MODE_ECB).decrypt(itm[-(i+1)])
cip += [bytes(j^k for j,k in zip(tmp, itm[-i]))]
return b"".join(cip[::-1])
# Server connection
KEY = os.urandom(32)
print(HDR)
print("| ~ I trapped the flag using AES encryption and decryption layers, so good luck ~ ^w^")
print(f"|\n| flag = {encrypt(FLAG, KEY).hex()}")
# Server loop
while True:
try:
print("|\n| ~ Want to encrypt something?")
msg = bytes.fromhex(input("|\n| > (hex) "))
enc = encrypt(msg, KEY)
print(f"|\n| {enc.hex()}")
except KeyboardInterrupt:
print('\n|\n| ~ Well goodbye then ~\n|')
break
except:
print('|\n| ~ Erhm... Are you okay?\n|')
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/idekCTF/2023/crypto/megalophobia/megalophobia.py | ctfs/idekCTF/2023/crypto/megalophobia/megalophobia.py | #!/usr/bin/env python3
#
# Polymero
#
# Imports
from Crypto.Cipher import AES
from Crypto.Util.number import getPrime, inverse
import os
# Local imports
with open('flag.txt', 'rb') as f:
FLAG = f.read()
f.close()
# Header
HDR = r"""|
|
| ____ ____ ________ ______ _ _____ ___ _______ ____ ____ ___ ______ _____ _
| |_ \ / _|_ __ |.' ___ | / \ |_ _| .' `.|_ __ \_ || _|.' `.|_ _ \|_ _| / \
| | \/ | | |_ \_/ .' \_| / _ \ | | / .-. \ | |__) || |__| | / .-. \ | |_) | | | / _ \
| | |\ /| | | _| _| | ____ / ___ \ | | _| | | | | ___/ | __ | | | | | | __'. | | / ___ \
| _| |_\/_| |_ _| |__/ \ `.___] |_/ / \ \_ _| |__/ \ `-' /_| |_ _| | | |_\ `-' /_| |__) || |_ _/ / \ \_
| |_____||_____|________|`._____.'|____| |____|________|`.___.'|_____| |____||____|`.___.'|_______/_____|____| |____|
|
|"""
# Private RSA key
d = 1
while d == 1:
p, q = [getPrime(512) for _ in '01']
d = inverse(0x10001, (p - 1)*(q - 1))
# Key encoding
num_byt = [i.to_bytes(256, 'big').lstrip(b'\x00') for i in [p, q, d, inverse(q, p)]]
sec_key = b''.join([len(k).to_bytes(2, 'big') + k for k in num_byt])
# OTP key to encrypt private part
otp_key = os.urandom((len(sec_key) - len(FLAG)) // 2) + b"__" + FLAG + b"__" + os.urandom(-((len(FLAG) - len(sec_key)) // 2))
pub_key = (p * q).to_bytes(128,'big')
enc_key = bytes([i^j for i,j in zip(sec_key, otp_key)])
# Server connection
print(HDR)
print("| ~ Here hold my RSA key pair for me, don't worry, I encrypted the private part ::")
print('| ' + pub_key.hex() + '::' + enc_key.hex())
print("|\n| --- several hours later ---")
print('|\n| ~ Hey, could you send me my encrypted private key?')
# Retrieve private key
try:
my_enc_key = bytes.fromhex(input('|\n| > (hex)'))
my_sec_key = bytes([i^j for i,j in zip(my_enc_key, otp_key)])
pop_lst = []
while len(my_sec_key) >= 2:
pop_len = int.from_bytes(my_sec_key[:2], 'big')
if pop_len <= len(my_sec_key[2:]):
pop_lst += [int.from_bytes(my_sec_key[2:2 + pop_len], 'big')]
my_sec_key = my_sec_key[2 + pop_len:]
else:
my_sec_key = b""
assert len(pop_lst) == 4
p, q, d, u = pop_lst
assert p * q == int.from_bytes(pub_key, 'big')
except:
print("|\n| ~ Erhm... That's not my key? I'll go somewhere else for now, bye...\n|")
exit()
# RSA-CRT decryption function
def decrypt(cip, p, q, d, u):
dp = d % (p - 1)
dq = d % (q - 1)
mp = pow(int.from_bytes(cip, 'big'), dp, p)
mq = pow(int.from_bytes(cip, 'big'), dq, q)
t = (mp - mq) % p
h = (t * u) % p
m = (h * q + mq)
return m.to_bytes(128, 'big').lstrip(b'\x00')
# Game
print("| ~ Now, I don't trust my own PRNG. Could you send me some 128-byte nonces encrypted with my RSA public key?")
for _ in range(500):
enc_rng = bytes.fromhex(input('| > '))
nonce = decrypt(enc_rng, p, q, d, u)
if len(nonce) < 128:
print("| ~ Erhm... are you sure this is a random 128-byte nonce? This doesn't seem safe to me... Q_Q")
else:
print("| ~ Thanks, this looks random ^w^") | python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/idekCTF/2023/crypto/primonumerophobia/source.py | ctfs/idekCTF/2023/crypto/primonumerophobia/source.py | #!/usr/bin/env python3
from Crypto.Util.number import *
import random
import os
class LFSR():
def __init__(self, taps):
d = max(taps)
self.taps = [d-t for t in taps]
self.state = [random.randint(0, 1) for _ in range(d)]
def _sum(self, L):
res = 0
for t in L:
res ^= t
return res
def next(self):
s = self.state[0]
self.state = self.state[1:] + [self._sum([self.state[t] for t in self.taps])]
return s
def getPrime(self, nbits):
count = 0
while True:
count += 1
p = int("".join([str(self.next()) for _ in range(nbits)]), 2)
if isPrime(p) and p > 2**(nbits-1):
print(f"[LOG] It takes {count} trials to find a prime.")
return p
if __name__ == '__main__':
lfsr = LFSR([47, 43, 41, 37, 31, 29, 23, 19, 17, 13, 11, 7, 5, 3, 2])
p, q = lfsr.getPrime(512), lfsr.getPrime(512)
with open("flag.txt", "rb") as f:
flag = f.read()
print(f"n = {p*q}")
print(f"enc = {pow(bytes_to_long(flag), 0x10001, p*q)}")
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/idekCTF/2023/crypto/tychophobia/server.py | ctfs/idekCTF/2023/crypto/tychophobia/server.py | #!/usr/bin/env python3
from Crypto.Util.number import *
import random
import os
import signal
class FeisteLCG():
def __init__(self, k, seed):
self.k = k
self.m = 2**(2*k)
self.a = getPrime(k)
self.x = seed
self.b = 0
print(f"a = {self.a}")
print(f"b = {self.b}")
# Generate random permutation by swapping
self.p = list(range(k))
for i in range(k-1):
j = i + random.randint(0, k-i-1)
self.p[i], self.p[j] = self.p[j], self.p[i]
# Start with identity
self.key = list(range(k))
def next(self):
self.x = (self.a * self.x + self.b) % self.m
# Split the state into left and right
left, right = self.x >> self.k, self.x % 2**self.k
# 13-round Alternating Feistel scheme
for _ in range(13):
left, right = right, left ^ self.perm_bits(right, self.key)
left, right = right, left ^ self.perm_bits(right, self.key)
# Update the key
self.key = self.perm(self.key, self.p)
# I'm evil and only give you upper bits :D
return left
def perm(self, L, key):
return [L[key[i]] for i in range(self.k)]
def perm_bits(self, n, key):
bits = list(bin(n)[2:].zfill(self.k))
return int("".join(self.perm(bits, self.key)), 2)
def Challenge():
print("========================")
print("=== Mission Possible ===")
print("========================")
print("")
print("I'll give you 2023 consecutive outputs of the RNG,")
print("you just need to recover the seed. Sounds easy, right?")
print("")
seed = bytes_to_long(os.urandom(16))
rng = FeisteLCG(64, seed)
for _ in range(2023):
print(rng.next())
print("")
inp = int(input("Guess the seed: "))
if inp == seed:
with open("flag.txt", "r") as f:
print(f.read())
else:
print("Nope :<")
if __name__ == '__main__':
signal.alarm(1200)
Challenge()
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/idekCTF/2023/crypto/psychophobia/psychophobia.py | ctfs/idekCTF/2023/crypto/psychophobia/psychophobia.py | #!/usr/bin/env python3
#
# Polymero
#
# Imports
from Crypto.Util.number import inverse
from secrets import randbelow
from hashlib import sha256
# Local imports
with open('flag.txt', 'rb') as f:
FLAG = f.read()
f.close()
# Header
HDR = r"""|
| _ ___
| | | / _ \
| _ _ _ _ ___ _____ _| |_ ___ | |_) )_ __ __
| | || || | | | \ \ / / _ \ / \ / _ \| _ <| |/ \/ /
| | \| |/ | |_| |\ v ( (_) | (| |) | (_) ) |_) ) ( () <
| \_ _/ \___/ > < \___/ \_ _/ \___/| __/ \_)__/\_\
| | | / ^ \ | | | |
| |_| /_/ \_\ |_| |_|
|
|"""
# Curve 25519 :: By^2 = x^3 + Ax^2 + x mod P
# https://en.wikipedia.org/wiki/Curve25519
# Curve Parameters
P = 2**255 - 19
A = 486662
B = 1
# Order of the Curve
O = 57896044618658097711785492504343953926856930875039260848015607506283634007912
# ECC Class
class Point:
def __init__(self, x, y):
self.x = x
self.y = y
if not self.is_on_curve():
raise ValueError("Point NOT on Curve 25519!")
def is_on_curve(self):
if self.x == 0 and self.y == 1:
return True
if ((self.x**3 + A * self.x**2 + self.x) % P) == ((B * self.y**2) % P):
return True
return False
@staticmethod
def lift_x(x):
y_sqr = ((x**3 + A * x**2 + x) * inverse(B, P)) % P
v = pow(2 * y_sqr, (P - 5) // 8, P)
i = (2 * y_sqr * v**2) % P
return Point(x, (y_sqr * v * (1 - i)) % P)
def __repr__(self):
return "Point ({}, {}) on Curve 25519".format(self.x, self.y)
def __eq__(self, other):
return self.x == other.x and self.y == other.y
def __add__(self, other):
if self == self.__class__(0, 1):
return other
if other == self.__class__(0, 1):
return self
if self.x == other.x and self.y != other.y:
return self.__class__(0, 1)
if self.x != other.x:
l = ((other.y - self.y) * inverse(other.x - self.x, P)) % P
else:
l = ((3 * self.x**2 + 2 * A * self.x + 1) * inverse(2 * self.y, P)) % P
x3 = (l**2 - A - self.x - other.x) % P
y3 = (l * (self.x - x3) - self.y) % P
return self.__class__(x3, y3)
def __rmul__(self, k):
out = self.__class__(0, 1)
tmp = self.__class__(self.x, self.y)
while k:
if k & 1:
out += tmp
tmp += tmp
k >>= 1
return out
# Curve25519 Base Point
G = Point.lift_x(9)
# ECDSA Functions
# https://en.wikipedia.org/wiki/Elliptic_Curve_Digital_Signature_Algorithm
def ECDSA_sign(m, priv):
h = int.from_bytes(sha256(m.encode()).digest(), 'big')
k = (4 * randbelow(O)) % O
r = (k * G).x % O
s = (inverse(k, O) * (h + r * priv)) % O
return (r, s)
def ECDSA_verify(m, pub, sig):
r, s = sig
if r > 0 and r < O and s > 0 and s < O:
h = int.from_bytes(sha256(m.encode()).digest(), 'big')
u1 = (h * inverse(s, O)) % O
u2 = (r * inverse(s, O)) % O
if r == (u1 * G + u2 * pub).x % O:
return True
return False
# Server connection
print(HDR)
print("|\n| ~ Are you the psychic I requested? What can I call you?")
name = input("| > ")
msg = f"{name} here, requesting flag for pick-up."
print('|\n| ~ Alright, here is the message I will sign for you :: ')
print(f'| m = \"{msg}\"')
ITER = 500
RATE = 0.72
print(f'|\n| ~ The following {ITER} signatures are all broken, please fix them for me to prove your psychic abilities ~')
print(f'| If you get more than, say, {round(RATE * 100)}% correct, I will believe you ^w^')
# Server loop
success = 0
for k in range(ITER):
try:
d = (2 * randbelow(O) + 1) % O
Q = d * G
while True:
sig = ECDSA_sign(msg, d)
if not ECDSA_verify(msg, Q, sig):
break
print(f"|\n| {k}. Please fix :: {sig}")
fix = [int(i.strip()) for i in input("| > (r,s) ").split(',')]
if (sig[0] == fix[0]) and ECDSA_verify(msg, Q, fix):
success += 1
except KeyboardInterrupt:
print('\n|')
break
except:
continue
print(f"|\n| ~ You managed to fix a total of {success} signatures!")
if success / ITER > RATE:
print(f"|\n| ~ You truly are psychic, here {FLAG}")
else:
print("|\n| ~ Seems like you are a fraud after all...")
print('|\n|') | python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/idekCTF/2023/crypto/formal-security-poop/ecc.py | ctfs/idekCTF/2023/crypto/formal-security-poop/ecc.py | from secrets import randbelow
from hashlib import sha512
class Curve:
def __init__(self, p, a, b) -> None:
self.p = p
self.a = a % p
self.b = b % p
self.O = Point(self, 0, 0)
class Point:
def __init__(self, E: Curve, x: int, y: int) -> None:
self.E = E
self.x = x % E.p
self.y = y % E.p
def __neg__(self) -> 'Point':
return Point(self.E, self.x, -self.y)
def __add__(self, other: 'Point') -> 'Point':
assert self.E == other.E
E = self.E
if other == E.O: return self
if self == E.O: return other
xP, yP = self.x, self.y
xQ, yQ = other.x, other.y
if xP == xQ:
if (yP + yQ) % E.p == 0:
return E.O
m = (3*xP**2 + E.a)*pow(2*yP, -1, E.p) % E.p
else:
m = (yQ - yP)*pow(xQ - xP, -1, E.p) % E.p
xR = m**2 - xP - xQ
yR = m*(xP - xR) - yP
return Point(E, xR, yR)
def __sub__(self, other: 'Point') -> 'Point':
return self + -other
def __mul__(self, k: int) -> 'Point':
P, R = self, self.E.O
if k < 0:
P = -P
k *= -1
while k:
if k % 2:
R += P
P += P
k //= 2
return R
__rmul__ = __mul__
def __eq__(self, o: 'Point') -> bool:
return isinstance(o, Point) \
and self.E == o.E \
and self.x == o.x \
and self.y == o.y
def print(self, msg: str):
print(msg)
print('\tx =', self.x)
print('\ty =', self.y)
@staticmethod
def input(msg: str):
print(msg)
x = int(input('\tx = '))
y = int(input('\ty = '))
return Point(E, x, y)
def H(P: Point) -> int:
z = P.x.to_bytes(32, 'big') + P.y.to_bytes(32, 'big')
return int.from_bytes(sha512(z).digest(), 'big') % p
def gen_key():
a = randbelow(p)
A = a*G
return a, A
# The Sec in Secp256k1 is for Secure
p = 0xfffffffdffffffffffffffffffffffff
E = Curve(p, 0xfffffffdfffffffffffffffffffffffc, 0xe87579c11079f43dd824993c2cee5ed3)
Gx = 0x161ff7528b899b2d0c28607ca52c5b86
Gy = 0xcf5ac8395bafeb13c02da292dded7a83
G = Point(E, Gx, Gy) | python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/idekCTF/2023/crypto/formal-security-poop/main.py | ctfs/idekCTF/2023/crypto/formal-security-poop/main.py | from Crypto.Util.Padding import pad, unpad
from Crypto.Cipher import AES
from ecc import *
class Vault:
def __init__(self) -> None:
self.secrets = {}
def authenticate(self, owner: str) -> None:
# Please see https://en.wikipedia.org/wiki/Proof_of_knowledge#Schnorr_protocol for how to interact
# But we do it over ellipthicc curves, because we already have a group setup :D
P, _ = self.secrets[owner]
print(f"Please prove that you are {owner}:")
T = Point.input("Give me the point T: ")
print('c =', c := randbelow(p))
s = int(input('s = '))
if s*G == T + c*P:
print("Successfully authenticated!")
else:
print("Who are you?? Go away!")
exit()
def sign(self, owner: str):
_, secret = self.secrets[owner]
m = int.from_bytes(sha512(secret).digest(), 'big') % p
k = randbelow(1 << 64) # [Note to self: make the bound dynamic on Y's order]
r = (k*G).x
s = (m + r*y)*pow(k, -1, p) % p
# Verify the signature with (r, _) == (1/s)*(m*G + r*Y)
return r, s
def store(self, secret: bytes, owner: str, P: Point):
if owner not in self.secrets:
self.secrets[owner] = P, secret
return
self.authenticate(owner)
self.secrets[owner] = P, secret
def retrieve(self, owner: str):
_, secret = self.secrets[owner]
self.authenticate(owner)
return secret
def session():
# x, X = gen_key(): your ephemeral keypair
X = Point.input("What is your ephemeral key?")
assert X != E.O
y, Y = gen_key()
B.print("Here is my public key:")
Y.print("Here is my ephemeral key:")
S = (y + H(Y)*b)*(X + H(X)*A) # Shared knowledge
return y, Y, sha512(H(S).to_bytes(32, 'big')).digest()[:16]
if __name__ == '__main__':
with open('flag.txt', 'rb') as f:
flag = f.read()
# a, A = gen_key(): your long term keypair
A = Point.input("What is your public key?")
b, B = gen_key()
y, Y, key = session()
# Communication is encrypted so that third parties can't steal your secrets!
aes = AES.new(key, AES.MODE_ECB)
vault = Vault()
vault.store(flag, 'Bob', B)
while 1:
print("""
[1] Store a secret
[2] Retrieve a secret
[3] Sign a secret
[4] Reinitialize session
""".strip())
opt = int(input('>>> '))
if opt == 1:
owner = input("Who are you? ")
secret = aes.decrypt(bytes.fromhex(input('secret = ')))
vault.store(unpad(secret, 16), owner, A)
print("Secret successfully stored!")
elif opt == 2:
owner = input("Who are you? ")
secret = pad(vault.retrieve(owner), 16)
print("Here is your secret:")
print('secret =', aes.encrypt(secret).hex())
elif opt == 3:
owner = input("Whose secret should I sign? ")
r, s = vault.sign(owner)
print("Here is the signature:")
print('r =', r)
print('s =', s)
elif opt == 4:
y, Y, key = session()
aes = AES.new(key, AES.MODE_ECB)
else:
print("My secrets are safe forever!", flush=True)
exit() | python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/idekCTF/2023/crypto/chronophobia/server.py | ctfs/idekCTF/2023/crypto/chronophobia/server.py | #!/usr/bin/env python3
from Crypto.Util.number import *
import random
import signal
class PoW():
def __init__(self, kbits, L):
self.kbits = kbits
self.L = L
self.banner()
self.gen()
self.loop(1337)
def banner(self):
print("===================================")
print("=== Welcome to idek PoW Service ===")
print("===================================")
print("")
def menu(self):
print("")
print("[1] Broken Oracle")
print("[2] Verify")
print("[3] Exit")
op = int(input(">>> "))
return op
def loop(self, n):
for _ in range(n):
op = self.menu()
if op == 1:
self.broken_oracle()
elif op == 2:
self.verify()
elif op == 3:
print("Bye!")
break
def gen(self):
self.p = getPrime(self.kbits)
self.q = getPrime(self.kbits)
self.n = self.p * self.q
self.phi = (self.p - 1) * (self.q - 1)
t = random.randint(0, self.n-1)
print(f"Here is your random token: {t}")
print(f"The public modulus is: {self.n}")
self.d = random.randint(128, 256)
print(f"Do 2^{self.d} times exponentiation to get the valid ticket t^(2^(2^{self.d})) % n!")
self.r = pow(2, 1 << self.d, self.phi)
self.ans = pow(t, self.r, self.n)
return
def broken_oracle(self):
u = int(input("Tell me the token. "))
ans = pow(u, self.r, self.n)
inp = int(input("What is your calculation? "))
if ans == inp:
print("Your are correct!")
else:
print(f"Nope, the ans is {str(ans)[:self.L]}... ({len(str(ans)[self.L:])} remain digits)")
return
def verify(self):
inp = int(input(f"Give me the ticket. "))
if inp == self.ans:
print("Good :>")
with open("flag.txt", "rb") as f:
print(f.read())
else:
print("Nope :<")
if __name__ == '__main__':
signal.alarm(120)
service = PoW(512, 200)
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/idekCTF/2023/web/proxy-viewer/app/app.py | ctfs/idekCTF/2023/web/proxy-viewer/app/app.py | from flask import Flask, request, render_template
from urllib.request import urlopen
from waitress import serve
from flask_limiter import Limiter
from flask_limiter.util import get_remote_address
import os
app = Flask(
__name__,
static_url_path='/static',
static_folder='./static',
)
PREMIUM_TOKEN = os.urandom(32).hex()
limiter = Limiter(app, key_func=get_remote_address)
@app.after_request
def add_headers(response):
response.cache_control.max_age = 120
return response
@app.route('/')
def index():
return render_template('index.html')
@app.route('/proxy/<path:path>')
@limiter.limit("10/minute")
def proxy(path):
remote_addr = request.headers.get('X-Forwarded-For') or request.remote_addr
is_authorized = request.headers.get('X-Premium-Token') == PREMIUM_TOKEN or remote_addr == "127.0.0.1"
try:
page = urlopen(path, timeout=.5)
except:
return render_template('proxy.html', auth=is_authorized)
if is_authorized:
output = page.read().decode('latin-1')
else:
output = f"<pre>{page.headers.as_string()}</pre>"
return render_template('proxy.html', auth=is_authorized, content=output)
@app.route('/premium')
def premium():
return "we're sorry, but premium membership is not yet available :( please check back soon!"
serve(app, host="0.0.0.0", port=3000, threads=20)
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/idekCTF/2023/web/json_beautifier/app.py | ctfs/idekCTF/2023/web/json_beautifier/app.py | from flask import Flask, send_file
app = Flask(__name__)
@app.after_request
def add_csp_header(response):
response.headers['Content-Security-Policy'] = "script-src 'unsafe-eval' 'self'; object-src 'none';"
return response
@app.route('/')
def index():
return send_file('index.html')
app.run('0.0.0.0', 1337)
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/idekCTF/2023/web/task-manager/taskmanager.py | ctfs/idekCTF/2023/web/task-manager/taskmanager.py | import pydash
class TaskManager:
protected = ["set", "get", "get_all", "__init__", "complete"]
def __init__(self):
self.set("capture the flag", "incomplete")
def set(self, task, status):
if task in self.protected:
return
pydash.set_(self, task, status)
return True
def complete(self, task):
if task in self.protected:
return
pydash.set_(self, task, False)
return True
def get(self, task):
if hasattr(self, task):
return {task: getattr(self, task)}
return {}
def get_all(self):
return self.__dict__ | python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/idekCTF/2023/web/task-manager/app.py | ctfs/idekCTF/2023/web/task-manager/app.py | from flask import Flask, render_template, request, redirect
from taskmanager import TaskManager
import os
app = Flask(__name__)
@app.before_first_request
def init():
if app.env == 'yolo':
app.add_template_global(eval)
@app.route("/<path:path>")
def render_page(path):
if not os.path.exists("templates/" + path):
return "not found", 404
return render_template(path)
@app.route("/api/manage_tasks", methods=["POST"])
def manage_tasks():
task, status = request.json.get('task'), request.json.get('status')
if not task or type(task) != str:
return {"message": "You must provide a task name as a string!"}, 400
if len(task) > 150:
return {"message": "Tasks may not be over 150 characters long!"}, 400
if status and len(status) > 50:
return {"message": "Statuses may not be over 50 characters long!"}, 400
if not status:
tasks.complete(task)
return {"message": "Task marked complete!"}, 200
if type(status) != str:
return {"message": "Your status must be a string!"}, 400
if tasks.set(task, status):
return {"message": "Task updated!"}, 200
return {"message": "Invalid task name!"}, 400
@app.route("/api/get_tasks", methods=["POST"])
def get_tasks():
try:
task = request.json.get('task')
return tasks.get(task)
except:
return tasks.get_all()
@app.route('/')
def index():
return redirect("/home.html")
tasks = TaskManager()
app.run('0.0.0.0', 1337)
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/idekCTF/2023/web/simple-file-server/src/config.py | ctfs/idekCTF/2023/web/simple-file-server/src/config.py | import random
import os
import time
SECRET_OFFSET = 0 # REDACTED
random.seed(round((time.time() + SECRET_OFFSET) * 1000))
os.environ["SECRET_KEY"] = "".join([hex(random.randint(0, 15)) for x in range(32)]).replace("0x", "")
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/idekCTF/2023/web/simple-file-server/src/app.py | ctfs/idekCTF/2023/web/simple-file-server/src/app.py | import logging
import os
import re
import sqlite3
import subprocess
import uuid
import zipfile
from flask import (Flask, flash, redirect, render_template, request, abort,
send_from_directory, session)
from werkzeug.security import check_password_hash, generate_password_hash
app = Flask(__name__)
DATA_DIR = "/tmp/"
# Uploads can only be 2MB in size
app.config['MAX_CONTENT_LENGTH'] = 2 * 1000 * 1000
# Configure logging
LOG_HANDLER = logging.FileHandler(DATA_DIR + 'server.log')
LOG_HANDLER.setFormatter(logging.Formatter(fmt="[{levelname}] [{asctime}] {message}", style='{'))
logger = logging.getLogger("application")
logger.addHandler(LOG_HANDLER)
logger.propagate = False
for handler in logging.root.handlers[:]:
logging.root.removeHandler(handler)
logging.basicConfig(level=logging.WARNING, format='%(asctime)s %(levelname)s %(name)s %(threadName)s : %(message)s')
logging.getLogger().addHandler(logging.StreamHandler())
# Set secret key
app.config["SECRET_KEY"] = os.environ["SECRET_KEY"]
@app.route("/")
def index():
return render_template("index.html")
@app.route("/login", methods=["GET", "POST"])
def login():
session.clear()
if request.method == "GET":
return render_template("login.html")
username = request.form.get("username", "")
password = request.form.get("password", "")
with sqlite3.connect(DATA_DIR + "database.db") as db:
res = db.cursor().execute("SELECT password, admin FROM users WHERE username=?", (username,))
user = res.fetchone()
if not user or not check_password_hash(user[0], password):
flash("Incorrect username/password", "danger")
return render_template("login.html")
session["uid"] = username
session["admin"] = user[1]
return redirect("/upload")
@app.route("/register", methods=["GET", "POST"])
def register():
session.clear()
if request.method == "GET":
return render_template("register.html")
username = request.form.get("username", "")
password = request.form.get("password", "")
if not username or not password or not re.fullmatch("[a-zA-Z0-9_]{1,24}", username):
flash("Invalid username/password", "danger")
return render_template("register.html")
with sqlite3.connect(DATA_DIR + "database.db") as db:
res = db.cursor().execute("SELECT username FROM users WHERE username=?", (username,))
if res.fetchone():
flash("That username is already registered", "danger")
return render_template("register.html")
db.cursor().execute("INSERT INTO users (username, password) VALUES (?, ?)", (username, generate_password_hash(password)))
db.commit()
session["uid"] = username
session["admin"] = False
return redirect("/upload")
@app.route("/upload", methods=["GET", "POST"])
def upload():
if not session.get("uid"):
return redirect("/login")
if request.method == "GET":
return render_template("upload.html")
if "file" not in request.files:
flash("You didn't upload a file!", "danger")
return render_template("upload.html")
file = request.files["file"]
uuidpath = str(uuid.uuid4())
filename = f"{DATA_DIR}uploadraw/{uuidpath}.zip"
file.save(filename)
subprocess.call(["unzip", filename, "-d", f"{DATA_DIR}uploads/{uuidpath}"])
flash(f'Your unique ID is <a href="/uploads/{uuidpath}">{uuidpath}</a>!', "success")
logger.info(f"User {session.get('uid')} uploaded file {uuidpath}")
return redirect("/upload")
@app.route("/uploads/<path:path>")
def uploads(path):
try:
return send_from_directory(DATA_DIR + "uploads", path)
except PermissionError:
abort(404)
@app.route("/flag")
def flag():
if not session.get("admin"):
return "Unauthorized!"
return subprocess.run("./flag", shell=True, stdout=subprocess.PIPE).stdout.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/idekCTF/2023/web/simple-file-server/src/wsgi.py | ctfs/idekCTF/2023/web/simple-file-server/src/wsgi.py | from app import app
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/idekCTF/2023/web/badblocker/challenge/app.py | ctfs/idekCTF/2023/web/badblocker/challenge/app.py | from flask import *
from waitress import serve
from os import environ
PORT = environ.get("port", 1337)
app = Flask(__name__)
app.config["TEMPLATES_AUTO_RELOAD"] = True
@app.route("/")
def index(): return render_template("index.html")
@app.route("/blocked.html")
def blocked(): return render_template("blocked.html")
@app.route("/import-history.html")
def import_history(): return render_template("import-history.html")
@app.route("/<path:url>")
def viewer(url): return render_template("viewer.html")
if __name__ == "__main__":
print(f"Server running on port {PORT}")
serve(app, host="0.0.0.0", port=PORT) | python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/P3rf3ctr00t/2025/web/r00tch4t/main.py | ctfs/P3rf3ctr00t/2025/web/r00tch4t/main.py | from flask import Flask,
, request, redirect, url_for, render_template_string, session
import os
app = Flask(__name__)
app.secret_key = os.urandom(32)
chat_logs = []
CHAT_TEMPLATE = """
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>P3rf3ctr00t CTF โข Global Chat</title>
<style>
@import url('https://fonts.googleapis.com/css2?family=Orbitron:wght@500;700;900&display=swap');
* { margin: 0; padding: 0; box-sizing: border-box; }
body {
font-family: 'Orbitron', 'Courier New', monospace;
background: #000;
color: #0f0;
min-height: 100vh;
background-image:
radial-gradient(circle at 10% 20%, rgba(0, 255, 0, 0.1) 0%, transparent 20%),
radial-gradient(circle at 90% 80%, rgba(0, 255, 0, 0.1) 0%, transparent 20%);
display: flex;
align-items: center;
justify-content: center;
padding: 20px;
}
.container {
background: rgba(0, 5, 0, 0.95);
border: 2px solid #0f0;
border-radius: 8px;
width: 100%;
max-width: 750px;
overflow: hidden;
box-shadow: 0 0 30px rgba(0, 255, 0, 0.5);
animation: glow 3s infinite alternate;
}
@keyframes glow { from { box-shadow: 0 0 20px rgba(0,255,0,0.5); } to { box-shadow: 0 0 40px rgba(0,255,0,0.8); } }
.header {
background: #000;
padding: 20px;
text-align: center;
border-bottom: 2px solid #0f0;
}
.header h1 {
font-size: 36px;
font-weight: 900;
text-shadow: 0 0 10px #0f0;
letter-spacing: 4px;
}
.header .subtitle {
color: #0a0;
font-size: 12px;
letter-spacing: 3px;
margin-top: 8px;
}
.user-badge {
background: #001a00;
display: inline-block;
padding: 6px 14px;
border: 1px solid #0f0;
border-radius: 4px;
margin-top: 10px;
font-size: 14px;
}
.content { padding: 25px; }
#chat-box {
background: #000;
border: 1px dashed #0f0;
height: 420px;
overflow-y: auto;
padding: 15px;
margin-bottom: 20px;
font-family: 'Courier New', monospace;
font-size: 14px;
line-height: 1.6;
}
#chat-box::-webkit-scrollbar-thumb { background: #0f0; }
#chat-box::-webkit-scrollbar-track { background: #001a00; }
.chat-message {
margin-bottom: 12px;
animation: type 0.5s steps(30) forwards;
opacity: 0;
animation-delay: calc(0.05s * var(--i));
}
@keyframes type { from { opacity: 0; } to { opacity: 1; } }
.chat-username { color: #0ff; text-shadow: 0 0 5px #0ff; font-weight: bold; }
.chat-text { color: #0f0; }
.admin-msg {
color: #f00 !important;
text-shadow: 0 0 10px #f00;
font-weight: bold;
animation: blink 1s infinite;
}
@keyframes blink { 50% { opacity: 0.7; } }
input[type="text"], button {
background: #000;
border: 1px solid #0f0;
color: #0f0;
padding: 12px 16px;
font-family: inherit;
font-size: 14px;
}
input[type="text"]:focus, button:hover {
outline: none;
box-shadow: 0 0 15px rgba(0, 255, 0, 0.6);
}
button {
cursor: pointer;
transition: all 0.3s;
}
button:hover { background: #003300; transform: translateY(-2px); }
.logout-btn { background: #330000; border-color: #f00; color: #f00; margin-top: 10px; width: 100%; }
.welcome-container { text-align: center; padding: 40px 20px; }
.welcome-container h2 { font-size: 28px; margin: 20px 0; text-shadow: 0 0 10px #0f0; }
.flag-hint { color: #060; font-size: 11px; margin-top: 30px; opacity: 0.6; }
</style>
</head>
<body>
<div class="container">
<div class="header">
<h1>P3rf3ctr00t CTF</h1>
<p class="subtitle">> r00tCh4t v1.337</p>
{% if username %}
<div class="user-badge">USER: {{ username | e }}</div>
{% endif %}
</div>
<div class="content">
{% if username %}
<div id="chat-box">
{% if chat_content %}
{{ chat_content | safe }}
{% else %}
<div style="text-align:center; color:#060; margin-top:80px;">
<pre style="font-size:18px;">
. _ _ _
/_ _ _/_ _ _ _
(__(__(__(__(__(
</pre>
<p>Waiting for root access...</p>
<p style="margin-top:30px; color:#030;">Hint: The flag is somewhere in the chat... if you're admin ;)</p>
</div>
{% endif %}
</div>
<form method="POST" action="/send_message">
<input type="text" name="message" placeholder="> enter command..." required autofocus>
<button type="submit">EXECUTE</button>
</form>
<form method="GET" action="/logout">
<button type="submit" class="logout-btn">DISCONNECT</button>
</form>
{% else %}
<div class="welcome-container">
<h2>WELCOME HACKER</h2>
<p>Choose your callsign to enter the matrix</p>
<form method="POST" action="/set_username">
<input type="text" name="username" placeholder="callsign" required autofocus maxlength="14">
<button type="submit">BREACH</button>
</form>
<div class="flag-hint">
Tip: root sometimes spills the beans in the chat...<br>
Format: r00t{...}
</div>
</div>
{% endif %}
</div>
</div>
<script>
const chatBox = document.getElementById('chat-box');
if (chatBox) {
chatBox.scrollTop = chatBox.scrollHeight;
document.querySelectorAll('.chat-message').forEach((el, i) => {
el.style.setProperty('--i', i);
});
}
</script>
</body>
</html>
"""
@app.route('/')
def home():
username = session.get('username')
chat_content = render_template_string('<br>'.join(chat_logs)) if chat_logs else ""
return render_template_string(CHAT_TEMPLATE, username=username, chat_content=chat_content)
@app.route('/set_username', methods=['GET', 'POST'])
def set_username():
if request.method == 'POST':
username = request.form.get('username', '').strip()
if len(username) > 14:
return "<h1 style='color:#0f0;background:#000'>ERROR: CALLSIGN TOO LONG</h1>", 400
if '{' in username and '}' in username:
return "<h1 style='color:#0f0;background:#000'>NICE TRY ;)</h1>", 400
session['username'] = username
return redirect(url_for('home'))
return render_template_string(CHAT_TEMPLATE, username=None)
@app.route('/send_message', methods=['POST'])
def send_message():
if 'username' not in session:
return redirect(url_for('set_username'))
message = request.form.get('message', '')
if not message.replace(' ', '').replace('\n', '').isalnum():
return "<h1 style='color:#f00;background:#000'>INVALID CHARACTERS DETECTED</h1>", 400
chat_logs.append(f"{session['username']}: {message}")
return redirect(url_for('home'))
@app.route('/logout')
def logout():
session.pop('username', None)
return redirect(url_for('set_username'))
@app.route('/reset', methods=['GET'])
def reset():
global chat_logs
chat_logs = []
session.pop('username', None)
return "<h1 style='color:#0f0;background:#000'>SYSTEM RESET COMPLETE</h1>"
if __name__ == '__main__':
app.run(host='0.0.0.0', port=5000, debug=False)
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/IrisCTF/2024/misc/Voice_Lock/app.py | ctfs/IrisCTF/2024/misc/Voice_Lock/app.py | from speechbrain.pretrained import SpeakerRecognition, EncoderDecoderASR
from flask import Flask, request, render_template, send_file
from fuzzywuzzy import fuzz
import threading
import hashlib
import random
import time
import os
# setup ###################
sessions = {}
app = Flask(__name__)
app.config['TEMPLATES_AUTO_RELOAD'] = True
asr_model = EncoderDecoderASR.from_hparams(source="speechbrain/asr-crdnn-rnnlm-librispeech", savedir="pretrained_models/asr-crdnn-rnnlm-librispeech")
verification = SpeakerRecognition.from_hparams(source="speechbrain/spkrec-ecapa-voxceleb", savedir="pretrained_models/spkrec-ecapa-voxceleb")
if not os.path.exists("tmp"):
os.mkdir("tmp")
# logic ###################
def matching_words(real_list, voice_recognition_list):
real_sent = " ".join(real_list)
voice_sent = " ".join(voice_recognition_list).replace("'", "")
print(real_sent)
print(voice_sent)
return fuzz.token_set_ratio(real_sent, voice_sent)
def check_pow(pow_answer, pow_prefix):
if len(pow_answer) > 200:
return False
digest = bytearray.fromhex(hashlib.sha256((pow_prefix + pow_answer).encode()).hexdigest())
return digest[0] == 0 and digest[1] == 0 and digest[2] < 10
def generate_token():
return os.urandom(32).hex()
# routes ###################
@app.route('/')
def root():
return render_template('page.html')
@app.route('/secret', methods=['GET'])
def secret():
token = request.args.get('token')
if token not in sessions:
return 'not a valid session'
if sessions[token]['passed'] == 'passed':
return 'irisctf{fake_flag_here}'
return 'no'
@app.route('/get_random_message', methods=['GET'])
def get_random_message():
with open('alicewords.txt', 'r', encoding='utf-8') as f:
words = f.read().split(' ')
start_pos = random.randint(0, len(words) - 22)
word_region = words[start_pos:start_pos+20]
token = generate_token()
proof_of_work = ''.join([random.choice('AMOGUS') for _ in range(16)])
sessions[token] = {
'region': word_region,
'username': request.form.get('user'),
'passed': 'not_attempted',
'pow': proof_of_work
}
return {
'region': word_region,
'token': token,
'pow': proof_of_work
}
@app.route('/submit_voice', methods=['POST'])
def submit_voice():
chk_filename = ''
chk_filename_fix = ''
try:
token = request.form.get('token')
audio_file = request.files.get('audio')
pow_answer = request.form.get('pow_answer')
if token not in sessions:
return '{"error": "not a valid session"}'
if sessions[token]['passed'] != 'not_attempted':
return '{"error": "already attempted, please get a new token"}'
sessions[token]['passed'] = 'checking'
if audio_file.content_length > 100000:
return '{"error": "uploaded file too large"}'
if not check_pow(pow_answer, sessions[token]['pow']):
return '{"error": "pow failed"}'
chk_filename = f'tmp/{token[:10]}.ogg'
with open(chk_filename, 'wb') as f:
f.write(audio_file.stream.read())
# thanks chrome
os.system(f'ffmpeg -i {chk_filename} {chk_filename}_fix.ogg')
chk_filename_fix = f'{chk_filename}_fix.ogg'
transcription = asr_model.transcribe_file(chk_filename_fix).split(' ')
text_match = matching_words(sessions[token]['region'], transcription)
passed_text_check = text_match >= 75
score, decision = verification.verify_files('match_voice.wav', chk_filename_fix)
if decision[0] and passed_text_check:
sessions[token]['passed'] = 'passed'
else:
sessions[token]['passed'] = 'failed'
return f'{{"voice_match": {score[0]}, "text_match": {text_match}, "decision": "{decision[0]}"}}'
except Exception as e:
print(e)
return '{"score": 0, "descision": "False", "match_probability": 0}'
finally:
def remove_files():
# there are some issues when the file is immediately deleted
# the 5 second sleep seems to do the trick
time.sleep(5)
if os.path.exists(chk_filename):
os.remove(chk_filename)
if os.path.exists(chk_filename_fix):
os.remove(chk_filename_fix)
delete_thread = threading.Thread(target=remove_files)
delete_thread.start()
if __name__ == '__main__':
app.run(host="0.0.0.0", port=1337) | python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/IrisCTF/2024/crypto/dhash/chal.py | ctfs/IrisCTF/2024/crypto/dhash/chal.py | from Crypto.Util.number import getPrime, isPrime
e = 65537
N = 1
while (N - 1) % e == 0:
N = getPrime(2048)
def xor(a, b):
return bytes(x^y for x,y in zip(a,b))
class MySeededHash():
def __init__(self, N, e):
self.N = N
self.e = e
self._state = b"\x00" * 256
self.seen = set()
def _hash_block(self, block):
assert len(block) == 256
if block in self.seen:
raise ValueError("This looks too familiar... :o")
self.seen.add(block)
data = int.from_bytes(block, "big")
if data < 2 or data >= N-1:
raise ValueError("Please ensure data is supported by hash function :|")
data = pow(data, self.e, self.N)
if data in self.seen:
raise ValueError("Collisions are cheating!!! >:(")
self.seen.add(data)
return data.to_bytes(256, "big")
def update(self, data):
assert len(data) % 256 == 0
for block in range(0, len(data), 256):
block = data[block:block+256]
self._state = xor(self._state, self._hash_block(block))
return self
def hexdigest(self):
return self._state.hex()
def __repr__(self):
return f"MySeededHash({self.N}, {self.e})"
def main():
hash = MySeededHash(N, e)
print(hash)
print("Give me your string that hashes to 0...")
preimage = bytes.fromhex(input("> "))
if len(preimage) < 256 or len(preimage) % 256 != 0:
raise ValueError("Invalid input!")
zero = hash.update(preimage).hexdigest()
print("hash(input) ==", zero)
if zero == "00" * 256:
with open("flag.txt") as f:
print(f.read())
else:
print("...")
main()
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/IrisCTF/2024/crypto/Beach_Party_Crypto/chal.py | ctfs/IrisCTF/2024/crypto/Beach_Party_Crypto/chal.py | #!/usr/bin/env pypy3
import secrets
import signal
import hashlib
def tropical_pow(x, y, op):
if 1 == y:
return x
exp = bin(y)
value = x
for i in range(3, len(exp)):
value = op(value, value)
if(exp[i:i+1]=='1'):
value = op(value, x)
return value
def pair_add(*a):
return (max(c[0] for c in a), max(c[1] for c in a))
pair_add_semi = lambda a,b,c: pair_add(a, b)
def pair_mul(a, b):
return (max(a[0] + b[0], a[1] + b[1]), max(a[0] + b[1], a[1] + b[0]))
def pair_mul_semi(a, b, c):
return (max(c + a[0] + b[0], c + a[1] + b[1]), max(c + a[0] + b[1], c + a[1] + b[0]))
def semi_factory(c):
def pair_mul_mat(a, b):
zb = list(zip(*b))
return [[pair_add(*[pair_mul_semi(x, y, c) for x, y in zip(row, col)]) for col in zb] for row in a]
return pair_mul_mat
def pair_mul_mat(a, b):
zb = list(zip(*b))
return [[pair_add(*[pair_mul(x, y) for x, y in zip(row, col)]) for col in zb] for row in a]
DIMENSION = 30
LB = -(10**6)
UB = (10**6)
p = secrets.randbelow(-LB + UB) + LB
q = secrets.randbelow(-LB + UB) + LB
c = secrets.randbelow(-LB + UB) + LB
d = secrets.randbelow(-LB + UB) + LB
k = secrets.randbits(128)
l = secrets.randbits(128)
r = secrets.randbits(128)
s = secrets.randbits(128)
X = []
Y = []
for i in range(DIMENSION):
X_ = []
Y_ = []
for j in range(DIMENSION):
X_.append((secrets.randbelow(-LB + UB) + LB, secrets.randbelow(-LB + UB) + LB))
Y_.append((secrets.randbelow(-LB + UB) + LB, secrets.randbelow(-LB + UB) + LB))
X.append(X_)
Y.append(Y_)
print("A's work...")
A1 = tropical_pow(X, k, op=semi_factory(c))
A2 = tropical_pow(Y, l, op=semi_factory(c))
A = pair_mul_mat(A1, A2)
A_pub = [[(e[0]+p,e[1]+p) for e in c] for c in A]
print("B's work...")
B1 = tropical_pow(X, r, op=semi_factory(d))
B2 = tropical_pow(Y, s, op=semi_factory(d))
B = pair_mul_mat(B1, B2)
B_pub = [[(e[0]+q,e[1]+q) for e in c] for c in B]
print("Computing keys")
K_a = pair_mul_mat([[(e[0]+p,e[1]+p) for e in c] for c in A1], pair_mul_mat(B_pub, A2))
K_b = pair_mul_mat([[(e[0]+q,e[1]+q) for e in c] for c in B1], pair_mul_mat(A_pub, B2))
assert all(a == b for c1, c2 in zip(K_a, K_b) for a, b in zip(c1, c2))
print("X=")
print(X)
print("Y=")
print(Y)
print("A_pub =")
print(A_pub)
print("B_pub =")
print(B_pub)
h = hashlib.sha256(repr(K_a).encode()).hexdigest()
signal.alarm(60)
guess = input("What's my hash? ")
if h == guess:
with open("flag") as f:
print(f.read())
else:
print("Sorry.")
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/IrisCTF/2024/crypto/Baby_Charge/chal.py | ctfs/IrisCTF/2024/crypto/Baby_Charge/chal.py | # https://en.wikipedia.org/wiki/Salsa20#ChaCha20_adoption
from Crypto.Util.number import long_to_bytes, bytes_to_long
import secrets
def ROTL(a, b):
return (((a) << (b)) | ((a % 2**32) >> (32 - (b)))) % 2**32
def qr(x, a, b, c, d):
x[a] += x[b]; x[d] ^= x[a]; x[d] = ROTL(x[d],16)
x[c] += x[d]; x[b] ^= x[c]; x[b] = ROTL(x[b],12)
x[a] += x[b]; x[d] ^= x[a]; x[d] = ROTL(x[d], 8)
x[c] += x[d]; x[b] ^= x[c]; x[b] = ROTL(x[b], 7)
ROUNDS = 20
def chacha_block(inp):
x = list(inp)
for i in range(0, ROUNDS, 2):
qr(x, 0, 4, 8, 12)
qr(x, 1, 5, 9, 13)
qr(x, 2, 6, 10, 14)
qr(x, 3, 7, 11, 15)
qr(x, 0, 5, 10, 15)
qr(x, 1, 6, 11, 12)
qr(x, 2, 7, 8, 13)
qr(x, 3, 4, 9, 14)
return [(a+b) % 2**32 for a, b in zip(x, inp)]
def chacha_init(key, nonce, counter):
assert len(key) == 32
assert len(nonce) == 8
state = [0 for _ in range(16)]
state[0] = bytes_to_long(b"expa"[::-1])
state[1] = bytes_to_long(b"nd 3"[::-1])
state[2] = bytes_to_long(b"2-by"[::-1])
state[3] = bytes_to_long(b"te k"[::-1])
key = bytes_to_long(key)
nonce = bytes_to_long(nonce)
for i in range(8):
state[i+4] = key & 0xffffffff
key >>= 32
state[12] = (counter >> 32) & 0xffffffff
state[13] = counter & 0xffffffff
state[14] = (nonce >> 32) & 0xffffffff
state[15] = nonce & 0xffffffff
return state
state = chacha_init(secrets.token_bytes(32), secrets.token_bytes(8), 0)
buffer = b""
def encrypt(data):
global state, buffer
output = []
for b in data:
if len(buffer) == 0:
buffer = b"".join(long_to_bytes(x).rjust(4, b"\x00") for x in state)
state = chacha_block(state)
output.append(b ^ buffer[0])
buffer = buffer[1:]
return bytes(output)
flag = b"fake_flag{FAKE_FLAG}"
if __name__ == "__main__":
print("""This cipher is approved by Disk Jockey B.
1. Encrypt input
2. Encrypt flag
""")
while True:
inp = input("> ")
match inp:
case '1':
print(encrypt(input("? ").encode()).hex())
case '2':
print(encrypt(flag).hex())
case _:
print("Bye!")
exit()
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/IrisCTF/2024/crypto/Integral_Communication/chal.py | ctfs/IrisCTF/2024/crypto/Integral_Communication/chal.py | from json import JSONDecodeError, loads, dumps
from binascii import hexlify, unhexlify
from Crypto.Cipher import AES
from Crypto.Random import get_random_bytes
with open("flag") as f:
flag = f.readline()
key = get_random_bytes(16)
def encrypt(plaintext: bytes) -> (bytes, bytes):
iv = get_random_bytes(16)
aes = AES.new(key, AES.MODE_CBC, iv)
print("IV:", hexlify(iv).decode())
return iv, aes.encrypt(plaintext)
def decrypt(ciphertext: bytes, iv: bytes) -> bytes:
aes = AES.new(key, AES.MODE_CBC, iv)
return aes.decrypt(ciphertext)
def create_command(message: str) -> (str, str):
payload = {"from": "guest", "act": "echo", "msg": message}
payload = dumps(payload).encode()
while len(payload) % 16 != 0:
payload += b'\x00'
iv, payload = encrypt(payload)
return hexlify(iv).decode('utf-8'), hexlify(payload).decode('utf-8')
def run_command(iv: bytes, command: str):
try:
iv = unhexlify(iv)
command = unhexlify(command)
command = decrypt(command, iv)
while command.endswith(b'\x00') and len(command) > 0:
command = command[:-1]
except:
print("Failed to decrypt")
return
try:
command = command.decode()
command = loads(command)
except UnicodeDecodeError:
print(f"Failed to decode UTF-8: {hexlify(command).decode('UTF-8')}")
return
except JSONDecodeError:
print(f"Failed to decode JSON: {command}")
return
match command["act"]:
case "echo":
msg = command['msg']
print(f"You received the following message: {msg}")
case "flag":
if command["from"] == "admin":
print(f"Congratulations! The flag is: {flag}")
else:
print("You don't have permissions to perform this action")
case action:
print(f"Invalid action {action}")
def show_prompt():
print("-" * 75)
print("1. Create command")
print("2. Run command")
print("3. Exit")
print("-" * 75)
try:
sel = input("> ")
sel = int(sel)
match sel:
case 1:
msg = input("Please enter your message: ")
iv, command = create_command(msg)
print(f"IV: {iv}")
print(f"Command: {command}")
case 2:
iv = input("IV: ")
command = input("Command: ")
run_command(iv, command)
case 3:
exit(0)
case _:
print("Invalid selection")
return
except ValueError:
print("Invalid selection")
except:
print("Unknown error")
if __name__ == "__main__":
while True:
show_prompt()
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/IrisCTF/2024/crypto/manykey/chal.py | ctfs/IrisCTF/2024/crypto/manykey/chal.py | from ecdsa import SigningKey
import secrets
sk = SigningKey.generate()
pk = sk.verifying_key
message = secrets.token_bytes(16)
print("Hello,", message.hex())
sig = sk.sign(message)
print(sig.hex())
print("Here's my public key")
print(pk.to_der().hex())
print("What was my private key again? (send me DER-encoded hex bytes)")
der = bytes.fromhex(input(""))
sk2 = SigningKey.from_der(der)
vk2 = sk2.verifying_key
assert sk2.privkey.secret_multiplier * sk2.curve.generator == vk2.pubkey.point
assert vk2.verify(sig, message)
with open("flag") as f:
flag = f.read()
print(flag, sk2.sign(flag.encode()))
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/IrisCTF/2024/crypto/Attack_of_the_Kleins/chal.py | ctfs/IrisCTF/2024/crypto/Attack_of_the_Kleins/chal.py | import secrets
def ksa(key):
buf = []
for i in range(256):
buf.append(i)
j = 0
for i in range(256):
j = (j + buf[i] + key[i % len(key)]) % 256
buf[i], buf[j] = buf[j], buf[i]
return buf
def pgra(buf):
i = 0
j = 0
while True:
i = (i + 1) % 256
j = (buf[i] + j) % 256
buf[i], buf[j] = buf[j], buf[i]
yield buf[(buf[i] + buf[j]) % 256]
def rc4(buf, key, iv):
buf = bytearray(buf, 'latin-1')
sched = ksa(iv + key)
keystream = pgra(sched)
for i in range(len(buf)):
buf[i] ^= next(keystream)
return buf
ctr = 0
def generate_new_iv(old_iv):
global ctr
ctr += 1
new_iv = []
# add to it for extra confusion
for i in range(8):
old_iv[i] = (old_iv[i] + 1) & 0xff
if old_iv[i] == 0:
old_iv[i] = 0
else:
break
for i in range(len(old_iv)):
off = (secrets.randbits(8) - 128) // 2
new_iv.append((old_iv[i] + off) & 0xff)
return bytes(new_iv)
def main():
iv = bytearray(secrets.token_bytes(8))
key = bytearray(secrets.token_bytes(16))
free_encrypts = 1000
print("Welcome to EncryptIt!")
print(f"1. Encrypt message ({free_encrypts} free encrypts remaining)")
print(f"2. Print encrypted flag")
while True:
choice = input("? ")
if choice == "1":
if free_encrypts <= 0:
print("No more free encrypts remaining")
continue
msg = input("Message? ")
new_iv = generate_new_iv(iv)
crypted = rc4(msg, key, new_iv)
print(new_iv.hex() + crypted.hex())
free_encrypts -= 1
elif choice == "2":
msg = "Here is the flag: irisctf{fake_flag}"
new_iv = generate_new_iv(iv)
crypted = rc4(msg, key, iv)
print(crypted.hex())
main()
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/IrisCTF/2024/crypto/Accessible_Sesamum_Indicum/chal.py | ctfs/IrisCTF/2024/crypto/Accessible_Sesamum_Indicum/chal.py | #!/usr/bin/env python3
import random
MAX_DIGITS = 65536
def vault() -> bool:
pin = "".join([random.choice("0123456789abcdef") for _ in range(4)])
digits = ["z", "z", "z", "z"]
counter = 0
print("What is the 4-digit PIN?")
while True:
attempt = list(input("Attempt> "))
for _ in range(len(attempt)):
digits.insert(0, attempt.pop())
digits.pop()
if "".join(digits) == pin:
return True
counter += 1
if counter > MAX_DIGITS:
return False
return False
def main():
print("You're burgling a safehouse one night (as you often do) when you run into a")
print("vault. The vault is protected by a 16-digit pad for a 4-digit PIN. The")
print("safehouse is guarded by an alarm system and if you're not careful, it'll go")
print("off, which is no good for you. After this, there are 15 more vaults.\n")
for n in range(16):
print(f"You've made it to vault #{n+1}.\n")
print("|---|---|---|---|")
print("| 0 | 1 | 2 | 3 |")
print("|---|---|---|---|")
print("|---|---|---|---|")
print("| 4 | 5 | 6 | 7 |")
print("|---|---|---|---|")
print("|---|---|---|---|")
print("| 8 | 9 | a | b |")
print("|---|---|---|---|")
print("|---|---|---|---|")
print("| c | d | e | f |")
print("|---|---|---|---|\n")
if not vault():
print("The alarm goes off and you're forced to flee. Maybe next time!")
return
print("You've defeated this vault.")
print("You unlock the vault and find the flag.\n")
with open("flag.txt", "r") as f:
print(f.read(), end="")
if __name__ == "__main__":
main()
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/IrisCTF/2024/web/LameNote/lamenote/chal.py | ctfs/IrisCTF/2024/web/LameNote/lamenote/chal.py | from flask import Flask, request, g, send_file, redirect, make_response
import secrets
from urllib.parse import urlparse
import re
from functools import wraps
import copy
host = re.compile("^[a-z0-9\.:]+$")
app = Flask(__name__)
NOTES = {}
def check_request(f):
@wraps(f)
def inner(*a, **kw):
secFetchDest = request.headers.get('Sec-Fetch-Dest', None)
if secFetchDest and secFetchDest != 'iframe': return "Invalid request"
return f(*a, **kw)
return inner
@app.after_request
def csp(response):
response.headers["Content-Security-Policy"] = "default-src 'none'; frame-src 'self';";
if "image_url" in g:
url = g.image_url
parsed = urlparse(url)
if host.match(parsed.netloc) and parsed.scheme in ["http", "https"]:
response.headers["Content-Security-Policy"] += "img-src " + parsed.scheme + "://" + parsed.hostname + ";"
response.headers["Cross-Origin-Opener-Policy"] = "same-origin"
response.headers["Cross-Origin-Resource-Policy"] = "same-origin"
response.headers["Cross-Origin-Embedder-Policy"] = "require-corp"
return response
@app.route("/")
def index():
return send_file("index.html")
@app.route("/home")
@check_request
def home():
return """<!DOCTYPE html>
<body>
<form action='/create' method='post'><input type="text" id="title" name="title" placeholder="title"><br>
<input type="textarea" id="text" name="text" placeholder="note text"><br>
<input type="text" id="image" name="image" placeholder="image URL"><br>
<button type="submit">Create</button></form>
<a href='/search'>All Notes</a>
<form action='/search' method='get'><input type="text" id="query" name="query" placeholder="text"> <button type="submit">Search</button></form>
</body>"""
@app.route("/create", methods=["POST"])
@check_request
def create():
if "<" in request.form.get("text", "(empty)") or \
"<" in request.form.get("title", "(empty)") or \
"<" in request.form.get("image", ""):
return "Really?"
user = request.cookies.get("user", None)
if user is None:
user = secrets.token_hex(16)
note = {"id": secrets.token_hex(16), "text": request.form.get("text", "(empty)"), "image": request.form.get("image", None), "title": request.form.get("title", "(empty)"), "owner": user}
NOTES[note["id"]] = note
r = redirect("/note/" + note["id"])
r.set_cookie('user', user, secure=True, httponly=True, samesite='None')
return r
def render_note(note):
data = "<!DOCTYPE html><body><b>" + note["title"] + "</b><br/>" + note["text"]
if note["image"] is not None:
g.image_url = note["image"]
data += "<br/><img width='100%' src='" + note["image"] + "' crossorigin />"
data += "</body>"
return data
@app.route("/note/<nid>")
@check_request
def note(nid):
if nid not in NOTES:
return "?"
return render_note(NOTES[nid])
@app.route("/search")
@check_request
def search():
query = request.args.get("query", "")
user = request.cookies.get("user", None)
results = []
notes_copy = copy.deepcopy(NOTES)
for note in notes_copy.values():
if note["owner"] == user and (query in note["title"] or query in note["text"]):
results.append(note)
if len(results) >= 5:
break
if len(results) == 0:
return "<!DOCTYPE html><body>No notes.</body>"
if len(results) == 1:
return render_note(results[0])
return "<!DOCTYPE html><body>" + "".join("<a href='/note/" + note["id"] + "'>" + note["title"] + "</a> " for note in results) + "</body>"
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/IrisCTF/2024/web/Mokersee/chal.py | ctfs/IrisCTF/2024/web/Mokersee/chal.py | from flask import Flask, request, send_file, render_template
import json
from PIL import Image
from io import BytesIO
import numpy as np
app = Flask(__name__)
MOKERS = {
"flag": {"description": "Free Flag (whatever)", "private": False, "preview": "%5B%7B%22filter%22%3A+%22blur%22%2C+%22args%22%3A+%5B20%5D%7D%5D"},
"moker1": {"description": "Moker: normal", "private": False, "preview": "[]"},
"moker2": {"description": "Moker (very different)", "private": False, "preview": "%5B%7B%22filter%22%3A+%22warp%22%2C+%22args%22%3A+%5B%5B%5B-1%2C+0%2C+768%5D%2C+%5B0%2C+-1%2C+1024%5D%2C+%5B0%2C+0%2C+1%5D%5D%5D%7D%5D"},
"moker3": {"description": "Moker (holy)", "private": False, "preview": "%5B%7B%22filter%22%3A+%22intensity%22%2C+%22args%22%3A+%5B%5B0%2C+1%5D%2C+%5B0%2C+0.6%5D%5D%7D%2C+%7B%22filter%22%3A+%22gamma%22%2C+%22args%22%3A+%5B0.2%5D%7D%5D"},
"moker4": {"description": "Moker... but at what cost?", "private": False, "preview": "%5B%7B%22filter%22%3A+%22rotate%22%2C+%22args%22%3A+%5B77%5D%7D%2C+%7B%22filter%22%3A+%22resize%22%2C+%22args%22%3A+%5B%5B768%2C+1024%5D%5D%7D%5D"},
"moker5": {"description": "[FRESH] Moker", "private": False, "preview": "%5B%7B%22filter%22%3A+%22swirl%22%2C+%22args%22%3A+%5Bnull%2C+3%2C+500%5D%7D%5D"},
"flagmoker": {"description": "Moker with Special Flag (RARE, do not show!)", "private": True, "preview": "[]"},
}
for moker in MOKERS:
MOKERS[moker]["blob"] = Image.open("images/" + moker + ".png")
########### HELPERS
@app.after_request
def csp(r):
# Actually, it's not even an XSS challenge.
r.headers["Content-Security-Policy"] = "default-src 'none'; style-src 'self' https://cdn.jsdelivr.net; img-src 'self'; script-src https://cdn.jsdelivr.net;"
return r
from skimage.filters import gaussian as blur
from skimage.exposure import adjust_gamma as gamma, rescale_intensity as intensity
from skimage.transform import resize, rotate, swirl, warp
FILTERS = {
"blur": blur,
"gamma": gamma,
"intensity": lambda i, a, b: intensity(i, tuple(a), tuple(b)),
"resize": resize,
"rotate": rotate,
"swirl": swirl,
"warp": lambda i, m: warp(i, np.array(m))
}
import time
def doFilterChain(image, chain):
for f in chain:
image = FILTERS[f["filter"]](image, *f["args"])
return image
########### ROUTES
@app.route("/")
def home():
return render_template("index.html", MOKERS=MOKERS)
@app.route("/style.css")
def style():
return send_file("style.css")
@app.route("/view/<moker>", methods=["GET"])
def view(moker):
if moker not in MOKERS:
return "What?"
moker = MOKERS[moker]
image = moker["blob"]
filters = request.args.get("filters", None)
if filters is not None:
filters = json.loads(filters)
image = np.array(image) / 255
image = doFilterChain(image, filters)
image = Image.fromarray((image * 255).astype(np.uint8), 'RGB')
if moker["private"]:
return "Not for public consumption."
io = BytesIO()
image.save(io, "PNG")
io.seek(0)
return send_file(io, mimetype='image/png')
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/IrisCTF/2023/rev/MeaningOfPython1/python1.py | ctfs/IrisCTF/2023/rev/MeaningOfPython1/python1.py | import sys
import zlib
def apple(s, a, b):
arr = list(s)
tmp = arr[a]
arr[a] = arr[b]
arr[b] = tmp
return "".join(arr)
def banana(s, a, b):
arr = list(s)
arr[a] = chr(ord(arr[a]) ^ ord(arr[b]))
return "".join(arr)
def carrot(s, a, b):
arr = bytearray(s)
tmp = arr[a]
arr[a] = arr[b]
arr[b] = tmp
return bytes(arr)
def donut(s, a, b):
arr = bytearray(s)
arr[b] ^= arr[a]
return bytes(arr)
def scramble1(flag):
pos = 36
while True:
if pos == 0:
flag = banana(flag, 25, 41)
pos = 29
elif pos == 1:
flag = apple(flag, 4, 21)
pos = 31
elif pos == 2:
flag = banana(flag, 24, 41)
pos = 41
elif pos == 3:
flag = banana(flag, 16, 24)
pos = 37
elif pos == 4:
flag = banana(flag, 0, 43)
pos = 32
elif pos == 5:
flag = banana(flag, 24, 2)
pos = 16
elif pos == 6:
flag = apple(flag, 18, 29)
pos = 38
elif pos == 7:
flag = banana(flag, 28, 43)
pos = 39
elif pos == 8:
flag = banana(flag, 25, 26)
pos = 12
elif pos == 9:
flag = apple(flag, 4, 43)
pos = 10
elif pos == 10:
flag = apple(flag, 15, 42)
pos = 26
elif pos == 11:
flag = banana(flag, 33, 13)
pos = 14
elif pos == 12:
flag = banana(flag, 43, 2)
pos = 24
elif pos == 13:
flag = apple(flag, 7, 32)
pos = 33
elif pos == 14:
flag = banana(flag, 20, 38)
pos = 27
elif pos == 15:
flag = banana(flag, 16, 29)
pos = 28
elif pos == 16:
flag = apple(flag, 8, 15)
pos = 0
elif pos == 17:
flag = apple(flag, 17, 9)
pos = 21
elif pos == 18:
flag = apple(flag, 37, 32)
pos = 22
elif pos == 19:
flag = banana(flag, 34, 13)
pos = 3
elif pos == 20:
flag = apple(flag, 21, 17)
pos = 7
elif pos == 21:
flag = banana(flag, 8, 38)
pos = 2
elif pos == 22:
flag = apple(flag, 13, 25)
pos = 30
elif pos == 23:
flag = banana(flag, 33, 37)
pos = 17
elif pos == 24:
flag = banana(flag, 15, 22)
pos = 6
elif pos == 25:
flag = apple(flag, 24, 15)
pos = 43
elif pos == 26:
flag = banana(flag, 37, 26)
pos = 11
elif pos == 27:
flag = apple(flag, 9, 0)
pos = 25
elif pos == 28:
flag = banana(flag, 32, 0)
pos = 42
elif pos == 29:
flag = banana(flag, 24, 26)
pos = 47
elif pos == 30:
flag = apple(flag, 1, 2)
pos = 9
elif pos == 31:
flag = banana(flag, 18, 27)
pos = 15
elif pos == 32:
flag = apple(flag, 26, 28)
pos = 49
elif pos == 33:
flag = banana(flag, 24, 16)
pos = 1
elif pos == 34:
flag = banana(flag, 11, 39)
pos = 46
elif pos == 35:
flag = banana(flag, 19, 22)
pos = 50
elif pos == 36:
flag = apple(flag, 28, 27)
pos = 5
elif pos == 37:
flag = apple(flag, 13, 15)
pos = 44
elif pos == 38:
flag = banana(flag, 6, 29)
pos = 23
elif pos == 39:
flag = apple(flag, 15, 37)
pos = 40
elif pos == 40:
flag = apple(flag, 40, 23)
pos = 4
elif pos == 41:
flag = apple(flag, 28, 0)
pos = 18
elif pos == 42:
flag = banana(flag, 41, 19)
pos = 19
elif pos == 43:
flag = apple(flag, 7, 5)
pos = 20
elif pos == 44:
flag = banana(flag, 12, 40)
pos = 35
elif pos == 45:
flag = apple(flag, 19, 30)
pos = 48
elif pos == 46:
flag = apple(flag, 15, 4)
pos = 13
elif pos == 47:
flag = apple(flag, 17, 11)
pos = 45
elif pos == 48:
flag = banana(flag, 8, 28)
pos = 8
elif pos == 49:
flag = banana(flag, 19, 9)
pos = 34
elif pos == 50:
return
def scramble2(flag):
pos = 48
while True:
if pos == 0:
flag = carrot(flag, 13, 25)
pos = 5
elif pos == 1:
flag = donut(flag, 16, 4)
pos = 42
elif pos == 2:
flag = carrot(flag, 22, 4)
pos = 41
elif pos == 3:
flag = donut(flag, 39, 47)
pos = 44
elif pos == 4:
flag = carrot(flag, 29, 41)
pos = 17
elif pos == 5:
flag = donut(flag, 18, 36)
pos = 13
elif pos == 6:
flag = donut(flag, 25, 23)
pos = 31
elif pos == 7:
flag = donut(flag, 37, 49)
pos = 39
elif pos == 8:
flag = donut(flag, 23, 30)
pos = 24
elif pos == 9:
flag = carrot(flag, 32, 11)
pos = 38
elif pos == 10:
flag = donut(flag, 24, 14)
pos = 3
elif pos == 11:
flag = donut(flag, 31, 23)
pos = 26
elif pos == 12:
flag = donut(flag, 25, 9)
pos = 36
elif pos == 13:
flag = carrot(flag, 37, 0)
pos = 37
elif pos == 14:
flag = donut(flag, 30, 35)
pos = 32
elif pos == 15:
flag = carrot(flag, 21, 2)
pos = 27
elif pos == 16:
flag = carrot(flag, 23, 44)
pos = 19
elif pos == 17:
flag = carrot(flag, 1, 51)
pos = 29
elif pos == 18:
flag = carrot(flag, 21, 16)
pos = 35
elif pos == 19:
flag = carrot(flag, 35, 33)
pos = 34
elif pos == 20:
flag = carrot(flag, 18, 1)
pos = 30
elif pos == 21:
flag = carrot(flag, 3, 27)
pos = 45
elif pos == 22:
flag = donut(flag, 2, 13)
pos = 18
elif pos == 23:
flag = donut(flag, 27, 50)
pos = 10
elif pos == 24:
flag = carrot(flag, 27, 45)
pos = 20
elif pos == 25:
flag = carrot(flag, 49, 35)
pos = 6
elif pos == 26:
flag = carrot(flag, 13, 40)
pos = 4
elif pos == 27:
flag = carrot(flag, 47, 50)
pos = 8
elif pos == 28:
flag = donut(flag, 0, 1)
pos = 43
elif pos == 29:
flag = donut(flag, 3, 34)
pos = 49
elif pos == 30:
flag = donut(flag, 50, 7)
pos = 11
elif pos == 31:
flag = donut(flag, 41, 9)
pos = 23
elif pos == 32:
flag = donut(flag, 44, 50)
pos = 16
elif pos == 33:
flag = carrot(flag, 19, 29)
pos = 15
elif pos == 34:
flag = carrot(flag, 34, 47)
pos = 40
elif pos == 35:
flag = carrot(flag, 24, 3)
pos = 47
elif pos == 36:
flag = carrot(flag, 14, 37)
pos = 0
elif pos == 37:
flag = donut(flag, 21, 29)
pos = 25
elif pos == 38:
flag = donut(flag, 29, 1)
pos = 1
elif pos == 39:
flag = carrot(flag, 23, 37)
pos = 33
elif pos == 40:
flag = carrot(flag, 29, 44)
pos = 12
elif pos == 41:
flag = donut(flag, 19, 39)
pos = 50
elif pos == 42:
flag = carrot(flag, 8, 37)
pos = 28
elif pos == 43:
flag = donut(flag, 40, 25)
pos = 21
elif pos == 44:
flag = donut(flag, 46, 14)
pos = 7
elif pos == 45:
flag = donut(flag, 36, 39)
pos = 22
elif pos == 46:
flag = carrot(flag, 44, 6)
pos = 9
elif pos == 47:
flag = carrot(flag, 46, 28)
pos = 14
elif pos == 48:
flag = donut(flag, 16, 50)
pos = 46
elif pos == 49:
flag = carrot(flag, 29, 10)
pos = 2
elif pos == 50:
return
def main():
if len(sys.argv) <= 1:
print("Missing argument")
exit(1)
flag_to_check = sys.argv[1]
flag_length = len(flag_to_check)
if flag_length < 44:
print("Incorrect")
exit(1)
scramble1(flag_to_check)
flag_compressed = zlib.compress(flag_to_check.encode("utf-8"))
flag_compressed_length = len(flag_compressed)
if flag_compressed_length < 52:
print("Incorrect")
exit(1)
scramble2(flag_compressed)
if flag_compressed == b'x\x9c\xcb,\xca,N.I\xab.\xc9\xc8,\x8e7,\x8eOIM3\xcc3,1\xce\xa9\x8c7\x89/\xa8,\xc90\xc8\x8bO\xcc)2L\xcf(\xa9\x05\x00\x83\x0c\x10\xf9':
print("Correct!")
else:
print("Incorrect!")
main() | python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/IrisCTF/2023/crypto/babynotrsa/chal.py | ctfs/IrisCTF/2023/crypto/babynotrsa/chal.py | from Crypto.Util.number import getStrongPrime
# We get 2 1024-bit primes
p = getStrongPrime(1024)
q = getStrongPrime(1024)
# We calculate the modulus
n = p*q
# We generate our encryption key
import secrets
e = secrets.randbelow(n)
# We take our input
flag = b"irisctf{REDACTED_REDACTED_REDACTED}"
assert len(flag) == 35
# and convert it to a number
flag = int.from_bytes(flag, byteorder='big')
# We encrypt our input
encrypted = (flag * e) % n
print(f"n: {n}")
print(f"e: {e}")
print(f"flag: {encrypted}")
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/IrisCTF/2023/crypto/babymixup/chal.py | ctfs/IrisCTF/2023/crypto/babymixup/chal.py | from Crypto.Cipher import AES
import os
key = os.urandom(16)
flag = b"flag{REDACTED}"
assert len(flag) % 16 == 0
iv = os.urandom(16)
cipher = AES.new(iv, AES.MODE_CBC, key)
print("IV1 =", iv.hex())
print("CT1 =", cipher.encrypt(b"Hello, this is a public message. This message contains no flags.").hex())
iv = os.urandom(16)
cipher = AES.new(key, AES.MODE_CBC, iv )
print("IV2 =", iv.hex())
print("CT2 =", cipher.encrypt(flag).hex())
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/IrisCTF/2023/crypto/AES-BAD-256/chal.py | ctfs/IrisCTF/2023/crypto/AES-BAD-256/chal.py | from Crypto.Cipher import AES as AES_BLOCK
import secrets
import random
AES_BLOCK_SIZE = 16
MODE_BLOCK_SIZE = AES_BLOCK_SIZE * 16
KEY = secrets.token_bytes(AES_BLOCK_SIZE)
AES = AES_BLOCK.new(KEY, AES_BLOCK.MODE_ECB)
import random
random.seed(KEY)
PERMUTATION = list(range(AES_BLOCK_SIZE))
random.shuffle(PERMUTATION)
def encrypt(inp):
inp = inp.ljust(MODE_BLOCK_SIZE, b"\x00")
assert len(inp) % MODE_BLOCK_SIZE == 0
data = b""
for block in range(0, len(inp), MODE_BLOCK_SIZE):
for i in range(AES_BLOCK_SIZE):
data += bytes(inp[block+j*AES_BLOCK_SIZE+PERMUTATION[i]] for j in range(MODE_BLOCK_SIZE // AES_BLOCK_SIZE))
return AES.encrypt(data)
def decrypt(inp):
assert len(inp) % MODE_BLOCK_SIZE == 0
inp = AES.decrypt(inp)
data = b""
for block in range(0, len(inp), MODE_BLOCK_SIZE):
for j in range(MODE_BLOCK_SIZE // AES_BLOCK_SIZE):
for i in range(AES_BLOCK_SIZE):
data += bytes([inp[block + PERMUTATION.index(i) * (MODE_BLOCK_SIZE // AES_BLOCK_SIZE) + j]])
return data
import json
def make_echo(inp):
data = json.dumps({"type": "echo", "msg": inp}).encode(errors="ignore")
assert len(data) < 2**32
return len(data).to_bytes(length=2, byteorder="little") + data
def run_command(inp):
inp = decrypt(inp)
length = int.from_bytes(inp[:2], byteorder="little")
if length + 2 >= len(inp):
return "Invalid command"
# Show me what you got
command = inp[2:length+2].decode("ascii", errors="replace")
try:
command = json.loads(command, strict=False)
except Exception as e:
return "Invalid command"
if "type" not in command:
return "No command type"
match command["type"]:
case "echo":
return command.get("msg", "Hello world!")
case "flag":
with open("/flag", "r") as f:
return f.read()
case other:
return f"Unknown command type {command['type']}..."
BANNER = "This is an echo service. This interface is protected by AES-BAD-256 technology."
MENU = """
1. Get an echo command
2. Run a command
3. Exit
"""
def main():
print(BANNER)
while True:
print(MENU)
command = input("> ")
match command:
case "1":
print("Give me some text.\n")
data = input("> ")
print(encrypt(make_echo(data)).hex())
case "2":
print("Give me a command.\n")
data = bytes.fromhex(input("(hex) > "))
print(run_command(data))
case other:
print("Bye!")
exit(0)
if __name__ == "__main__":
main()
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/IrisCTF/2023/crypto/SMarT1/chal.py | ctfs/IrisCTF/2023/crypto/SMarT1/chal.py | from pwn import xor
# I don't know how to make a good substitution box so I'll refer to AES. This way I'm not actually rolling my own crypto
SBOX = [99, 124, 119, 123, 242, 107, 111, 197, 48, 1, 103, 43, 254, 215, 171, 118, 202, 130, 201, 125, 250, 89, 71, 240, 173, 212, 162, 175, 156, 164, 114, 192, 183, 253, 147, 38, 54, 63, 247, 204, 52, 165, 229, 241, 113, 216, 49, 21, 4, 199, 35, 195, 24, 150, 5, 154, 7, 18, 128, 226, 235, 39, 178, 117, 9, 131, 44, 26, 27, 110, 90, 160, 82, 59, 214, 179, 41, 227, 47, 132, 83, 209, 0, 237, 32, 252, 177, 91, 106, 203, 190, 57, 74, 76, 88, 207, 208, 239, 170, 251, 67, 77, 51, 133, 69, 249, 2, 127, 80, 60, 159, 168, 81, 163, 64, 143, 146, 157, 56, 245, 188, 182, 218, 33, 16, 255, 243, 210, 205, 12, 19, 236, 95, 151, 68, 23, 196, 167, 126, 61, 100, 93, 25, 115, 96, 129, 79, 220, 34, 42, 144, 136, 70, 238, 184, 20, 222, 94, 11, 219, 224, 50, 58, 10, 73, 6, 36, 92, 194, 211, 172, 98, 145, 149, 228, 121, 231, 200, 55, 109, 141, 213, 78, 169, 108, 86, 244, 234, 101, 122, 174, 8, 186, 120, 37, 46, 28, 166, 180, 198, 232, 221, 116, 31, 75, 189, 139, 138, 112, 62, 181, 102, 72, 3, 246, 14, 97, 53, 87, 185, 134, 193, 29, 158, 225, 248, 152, 17, 105, 217, 142, 148, 155, 30, 135, 233, 206, 85, 40, 223, 140, 161, 137, 13, 191, 230, 66, 104, 65, 153, 45, 15, 176, 84, 187, 22]
TRANSPOSE = [[3, 1, 4, 5, 6, 7, 0, 2],
[1, 5, 7, 3, 0, 6, 2, 4],
[2, 7, 5, 4, 0, 6, 1, 3],
[2, 0, 1, 6, 4, 3, 5, 7],
[6, 5, 0, 3, 2, 4, 1, 7],
[2, 0, 6, 1, 5, 7, 4, 3],
[1, 6, 2, 5, 0, 7, 4, 3],
[4, 5, 6, 1, 2, 3, 7, 0]]
RR = [4, 2, 0, 6, 9, 3, 5, 7]
def rr(c, n):
n = n % 8
return ((c << (8 - n)) | (c >> n)) & 0xff
import secrets
ROUNDS = 2
MASK = secrets.token_bytes(8)
KEYLEN = 4 + ROUNDS * 4
def encrypt(block, key):
assert len(block) == 8
assert len(key) == KEYLEN
block = bytearray(block)
for r in range(ROUNDS):
block = bytearray(xor(block, key[r*4:(r+2)*4]))
for i in range(8):
block[i] = SBOX[block[i]]
block[i] = rr(block[i], RR[i])
temp = bytearray(8)
for i in range(8):
for j in range(8):
temp[j] |= ((block[i] >> TRANSPOSE[i][j]) & 1) << i
block = temp
block = xor(block, MASK)
return block
def ecb(pt, key):
if len(pt) % 8 != 0:
pt = pt.ljust(len(pt) + (8 - len(pt) % 8), b"\x00")
out = b""
for i in range(0, len(pt), 8):
out += encrypt(pt[i:i+8], key)
return out
key = secrets.token_bytes(KEYLEN)
FLAG = b"irisctf{redacted}"
print(f"MASK: {MASK.hex()}")
print(f"key: {key.hex()}")
import json
pairs = []
for i in range(8):
pt = secrets.token_bytes(8)
pairs.append([pt.hex(), encrypt(pt, key).hex()])
print(f"some test pairs: {json.dumps(pairs)}")
print(f"flag: {ecb(FLAG, key).hex()}")
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/IrisCTF/2023/web/FeelingTagged/tagged.py | ctfs/IrisCTF/2023/web/FeelingTagged/tagged.py | from flask import Flask, request, redirect
from bs4 import BeautifulSoup
import secrets
import base64
app = Flask(__name__)
SAFE_TAGS = ['i', 'b', 'p', 'br']
with open("home.html") as home:
HOME_PAGE = home.read()
@app.route("/")
def home():
return HOME_PAGE
@app.route("/add", methods=['POST'])
def add():
contents = request.form.get('contents', "").encode()
return redirect("/page?contents=" + base64.urlsafe_b64encode(contents).decode())
@app.route("/page")
def page():
contents = base64.urlsafe_b64decode(request.args.get('contents', '')).decode()
tree = BeautifulSoup(contents)
for element in tree.find_all():
if element.name not in SAFE_TAGS or len(element.attrs) > 0:
return "This HTML looks sus."
return f"<!DOCTYPE html><html><body>{str(tree)}</body></html>"
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/IrisCTF/2023/web/mokerview/mokerview.py | ctfs/IrisCTF/2023/web/mokerview/mokerview.py | from flask import Flask, request, redirect, make_response, send_from_directory
from werkzeug.urls import url_decode, url_encode
from functools import wraps
from collections import defaultdict
import hashlib
import requests
import re
import secrets
import base64
app = Flask(__name__)
FLAGMOKER = "REDACTED"
MOKERS = {"moker1": "dQJOyoO", "moker2": "dQJOyoO", "moker3": "dQJOyoO", "moker4": "dQJOyoO", "moker6": "dQJOyoO", "moker7": "dQJOyoO", "moker8": "dQJOyoO", "flagmoker": FLAGMOKER}
MOKER_PATTERN = re.compile("^[A-Za-z0-9]+$")
MOKEROFTHEDAY = "moker3"
STYLE_PATTERN = re.compile("^[A-Za-z0 -9./]+$")
STYLES = ["moker.css", "plain.css"]
########### HELPERS
def imgur(moker):
return f"https://i.imgur.com/{moker}.png"
ADMIN_PASS = "REDACTED"
users = {"@admin": {"password": ADMIN_PASS, "mokers": []}}
sessions = defaultdict(dict)
@app.after_request
def csp(r):
# Moker does not like "Java Script"
r.headers["Content-Security-Policy"] = "script-src 'none'; img-src https://i.imgur.com/"
return r
def session(f):
@wraps(f)
def dec(*a, **k):
session = request.cookies.get("session", None)
if session is None or session not in sessions:
return redirect("/")
session_obj = sessions[session]
return f(session_obj, *a, **k)
return dec
def csrf(f):
@wraps(f)
def dec(*a, **k):
session = request.cookies.get("session", None)
if session is None or session not in sessions:
return redirect("/")
session = sessions[session]
token = request.args.get("token", None)
args = base64.urlsafe_b64decode(request.args.get("args", ""))
if args != b"":
query = request.path.encode() + b"?" + args
else:
query = request.path.encode()
if token is None:
return "CSRF token missing"
if hashlib.sha256(session["key"] + query).digest().hex() != token:
return "Invalid CSRF token"
request.args = url_decode(args)
return f(*a, **k)
return dec
def signer(session):
def sign(url):
raw_url = url.encode()
token = hashlib.sha256(session["key"] + raw_url).digest().hex()
if url.find("?") != -1:
idx = url.index("?")
base = url[:idx]
args = url[idx+1:]
return base + "?" + url_encode({"args": base64.urlsafe_b64encode(args.encode()), "token": token})
else:
return url + "?" + url_encode({"args": '', "token": token})
return sign
def header(session):
sign = signer(session)
return f"<a href='{sign('/logout')}'>Logout</a> <a href='/view'>My Mokers</a> <a href='/add'>Add a Moker</a> <a href='/create'>Create a new Moker</a> <a href='/delete'>Remove Moker</a>\
<form id='add' method='POST' action='{sign('/add?daily=1')}'><input type='submit' value='*Add \"Moker of the Day\"*'/></form>"
########### ROUTES
@app.route("/")
def home():
session = request.cookies.get("session", None)
if session is None or session not in sessions:
return "<!DOCTYPE html><html><body>Welcome to my Moker Collection website. Please <a href=/register>register</a> or <a href=/login>login</a>.</body></html>"
return redirect("/view")
@app.route('/static/<path:path>')
def staticServe(path):
return send_from_directory('static', path)
@app.route("/register", methods=["GET"])
def register_form():
return "<!DOCTYPE html><html><body>Register an Account<br>\
<form method='POST'><input type='text' name='user' value='username'><input type='text' name='password' value='password (stored in plaintext for you)'><input type='submit' value='Submit'></form></body></html>"
@app.route("/register", methods=["POST"])
def register():
user = request.form.get("user", None)
password = request.form.get("password", None)
if user is None or password is None:
return "Need user and password"
if not (MOKER_PATTERN.match(user) and MOKER_PATTERN.match(password)):
return "Invalid username/password"
users[user] = {"password": password, "mokers": []}
return redirect("/login")
@app.route("/login", methods=["GET"])
def login_form():
return "<!DOCTYPE html><html><body>Login<br>\
<form method='POST'><input type='text' name='user' value='Username'><input type='text' name='password' value='password (stored in plaintext for you)'><input type='submit' value='Submit'></form></body></html>"
@app.route("/login", methods=["POST"])
def login():
user = request.form.get("user", "")
password = request.form.get("password", "")
if user not in users:
return "No user"
if users[user]["password"] == password:
response = make_response(redirect("/view"))
sid = request.cookies.get("session", secrets.token_hex(16))
sessions[sid].clear()
response.set_cookie("session", sid, httponly=True)
sessions[sid]["user"] = user
sessions[sid]["key"] = secrets.token_bytes(16)
return response
return "Invalid user/pass"
@app.route("/logout", methods=["GET"])
@csrf
def logout():
sid = request.cookies.get("session") # already exists given by @csrf
del sessions[sid]
r = make_response(redirect("/"))
r.delete_cookie("session")
return r
@app.route("/view", methods=["GET"])
@session
def view(session):
style = request.args.get("style", "/static/plain.css")
if not STYLE_PATTERN.match(style):
return "Bad style link"
mokers = "<br>".join(f"<img src={imgur(moker)} referrerpolicy=no-referrer class=moker></img>" for moker in users[session["user"]]["mokers"])
styles = " ".join(f"<a href=/view?style=/static/{s}>{s}</a>" for s in STYLES)
return f"<!DOCTYPE html><html><head><link rel=stylesheet href={style}></head><body>{header(session)}<br>Use Some Styles: {styles}<br>Your'e Mokers: <br><br>{mokers}</body></html>"
@app.route("/create", methods=["GET"])
@session
def create_form(session):
sign = signer(session)
form = f"<form action='/create' method='POST'><input type='text' name='name' value='Name of Moker'><input type='text' name='path' value='imgur path without extension'><input type='submit' value='Create'></form>"
return "<!DOCTYPE html><html><body>" + header(session) + "Create a moker.<br>" + form + "</body></html>"
@app.route("/create", methods=["POST"])
@session
def create(session):
if len(MOKERS) > 30:
return "We are at max moker capacity. Safety protocols do not allow adding more moker"
name = request.form.get("name", None)
if name is None or name in MOKERS:
return "No name for new moker"
path = request.form.get("path", None)
if path is None or not MOKER_PATTERN.match(path):
return "Invalid moker path"
if requests.get(imgur(path)).status_code != 200:
return "This moker does not appear to be valid"
MOKERS[name] = path
return redirect("/view")
@app.route("/add", methods=["GET"])
@session
def add_form(session):
sign = signer(session)
mokers = " ".join(f"<form action='{sign('/add?moker=' + moker)}' method='POST'><input type='submit' value='{moker}'></form>" for moker in MOKERS)
return "<!DOCTYPE html><html><body>" + header(session) + "Add a moker to your list.<br>" + mokers + "</body></html>"
@app.route("/add", methods=["POST"])
@csrf
@session
def add(session):
moker = request.args.get("moker", None)
if moker is None:
if request.args.get('daily', False):
moker = MOKEROFTHEDAY
if (moker == "flagmoker" and session["user"] != "@admin") or moker not in MOKERS:
return "Invalid moker"
if requests.get(imgur(MOKERS[moker])).status_code != 200:
return "This moker is not avaliable at this time"
if(len(users[session["user"]]["mokers"]) > 30):
# this is too many mokers for one person. you don't need this many
users[session["user"]]["mokers"].clear()
users[session["user"]]["mokers"].append(MOKERS[moker])
return redirect("/view")
@app.route("/delete", methods=["GET"])
@session
def delete_form(session):
sign = signer(session)
mokers = " ".join(f"<form action={sign('/delete?moker=' + moker)} method=POST><img src={imgur(moker)}></img><input type=submit value=Remove></form>" for moker in users[session["user"]]["mokers"])
return "<!DOCTYPE html><html><body>" + header(session) + "Remove a moker from your list.<br>" + mokers + "</body></html>"
@app.route("/delete", methods=["POST"])
@csrf
@session
def delete(session):
moker = request.args.get("moker", None)
if moker is None:
return "No moker to remove"
users[session["user"]]["mokers"].remove(moker)
return redirect("/view")
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/IrisCTF/2023/web/babycsrf/solve_template.py | ctfs/IrisCTF/2023/web/babycsrf/solve_template.py | from flask import Flask, request
import time
app = Flask(__name__)
with open("solve.html") as f:
SOLVE = f.read()
@app.route("/")
def home():
return SOLVE
# You can define functions that return non-static data too, of course
@app.route("/time")
def page():
return f"{time.time()}"
# Run "ngrok http 12345"
# and submit the resulting https:// url to the admin bot
app.run(port=12345)
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/IrisCTF/2023/web/babycsrf/chal.py | ctfs/IrisCTF/2023/web/babycsrf/chal.py | from flask import Flask, request
app = Flask(__name__)
with open("home.html") as home:
HOME_PAGE = home.read()
@app.route("/")
def home():
return HOME_PAGE
@app.route("/api")
def page():
secret = request.cookies.get("secret", "EXAMPLEFLAG")
return f"setMessage('irisctf{{{secret}}}');"
app.run(port=12345)
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/StarCTF/2021/web/oh-my-note/source.py | ctfs/StarCTF/2021/web/oh-my-note/source.py | import string
import random
import time
import datetime
from flask import render_template, redirect, url_for, request, session, Flask
from functools import wraps
from exts import db
from config import Config
from models import User, Note
from forms import CreateNoteForm
app = Flask(__name__)
app.config.from_object(Config)
db.init_app(app)
def login_required(f):
@wraps(f)
def decorated_function(*args, **kws):
if not session.get("username"):
return redirect(url_for('index'))
return f(*args, **kws)
return decorated_function
def get_random_id():
alphabet = list(string.ascii_lowercase + string.digits)
return ''.join([random.choice(alphabet) for _ in range(32)])
@app.route('/')
@app.route('/index')
def index():
results = Note.query.filter_by(prv='False').limit(100).all()
notes = []
for x in results:
note = {}
note['title'] = x.title
note['note_id'] = x.note_id
notes.append(note)
return render_template('index.html', notes=notes)
@app.route('/logout')
@login_required
def logout():
session.pop('username', None)
return redirect(url_for('index'))
@app.route('/create_note', methods=['GET', 'POST'])
def create_note():
try:
form = CreateNoteForm()
if request.method == "POST":
username = form.username.data
title = form.title.data
text = form.body.data
prv = str(form.private.data)
user = User.query.filter_by(username=username).first()
if user:
user_id = user.user_id
else:
timestamp = round(time.time(), 4)
random.seed(timestamp)
user_id = get_random_id()
user = User(username=username, user_id=user_id)
db.session.add(user)
db.session.commit()
session['username'] = username
timestamp = round(time.time(), 4)
post_at = datetime.datetime.fromtimestamp(timestamp, tz=datetime.timezone.utc).strftime('%Y-%m-%d %H:%M UTC')
random.seed(user_id + post_at)
note_id = get_random_id()
note = Note(user_id=user_id, note_id=note_id,
title=title, text=text,
prv=prv, post_at=post_at)
db.session.add(note)
db.session.commit()
return redirect(url_for('index'))
else:
return render_template("create.html", form=form)
except Exception as e:
pass
@app.route('/my_notes')
def my_notes():
if session.get('username'):
username = session['username']
user_id = User.query.filter_by(username=username).first().user_id
else:
user_id = request.args.get('user_id')
if not user_id:
return redirect(url_for('index'))
results = Note.query.filter_by(user_id=user_id).limit(100).all()
notes = []
for x in results:
note = {}
note['title'] = x.title
note['note_id'] = x.note_id
notes.append(note)
return render_template("my_notes.html", notes=notes)
@app.route('/view/<_id>')
def view(_id):
note = Note.query.filter_by(note_id=_id).first()
user_id = note.user_id
username = User.query.filter_by(user_id=user_id).first().username
data = {
'post_at': note.post_at,
'title': note.title,
'text': note.text,
'username': username
}
return render_template('note.html', data=data)
if __name__ == '__main__':
app.run(host='0.0.0.0', port=5000) | python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/StarCTF/2021/web/oh-my-socket/source/webserver/webserver/app.py | ctfs/StarCTF/2021/web/oh-my-socket/source/webserver/webserver/app.py | from flask import Flask, render_template, request
from subprocess import STDOUT, check_output
import os
app = Flask(__name__)
@app.route('/')
def index():
return open(__file__).read()
@app.route('/upload', methods=['GET', 'POST'])
def upload_file():
if request.method == 'GET':
return render_template('index.html')
elif request.method == 'POST':
f = request.files['file']
f.save(os.path.join(f.filename))
try:
output = check_output(['python3', f.filename], stderr=STDOUT, timeout=80)
content = output.decode()
except Exception as e:
content = e.__str__()
os.system(' '.join(['rm', f.filename]))
return content
if __name__ == '__main__':
app.run(port=5000, host='0.0.0.0') | python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/StarCTF/2021/web/oh-my-socket/source/server/server/server.py | ctfs/StarCTF/2021/web/oh-my-socket/source/server/server/server.py | from socket import *
from time import ctime
import time
HOST = '172.21.0.2'
PORT = 21587
BUFSIZ = 1024
ADDR = (HOST, PORT)
tcpSerSock = socket(AF_INET, SOCK_STREAM)
tcpSerSock.bind(ADDR)
tcpSerSock.listen(5)
cnt = 0
while True:
print('waiting for connection...')
tcpCliSock, addr = tcpSerSock.accept()
cnt += 1
print('...connnecting from:', addr)
try:
while True:
data = tcpCliSock.recv(BUFSIZ)
if not data:
break
if data == b'*ctf':
content = open('oh-some-funny-code').read()
tcpCliSock.send((content.encode()))
else:
tcpCliSock.send(('[%s] %s' % (ctime(), data)).encode())
except Exception as e:
pass
if cnt >= 2:
time.sleep(120)
tcpSerSock.close()
exit(0)
tcpSerSock.close() | python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/StarCTF/2021/web/oh-my-socket/source/client/client/client.py | ctfs/StarCTF/2021/web/oh-my-socket/source/client/client/client.py | from socket import *
from requests.exceptions import *
HOST = '172.21.0.2'
PORT = 21587
BUFSIZ =1024
ADDR = (HOST,PORT)
tcpCliSock = socket(AF_INET,SOCK_STREAM)
tcpCliSock.bind(('172.21.0.3',7775))
tcpCliSock.connect(ADDR)
while True:
try:
data1 = tcpCliSock.recv(BUFSIZ)
if not data1:
break
print(data1.decode('utf-8'))
except ConnectionResetError:
tcpCliSock.close()
except Exception:
pass | python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/StarCTF/2021/web/oh-my-socket/source/client/client/app.py | ctfs/StarCTF/2021/web/oh-my-socket/source/client/client/app.py | from flask import Flask, request
app = Flask(__name__)
@app.route('/')
def index():
return open(__file__).read()
@app.route("/file", methods=['GET','POST'])
def file():
file = request.args.get('name')
content = open(file).read()
return content
if __name__ == "__main__":
app.run(port=5000, host='0.0.0.0')
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/StarCTF/2023/misc/Increasing/Increazing_code.py | ctfs/StarCTF/2023/misc/Increasing/Increazing_code.py | from func_timeout import func_set_timeout
import torch
from torch.nn import init
import torch.nn as nn
from copy import deepcopy
import math
model_num=181
@func_set_timeout(60)
def getinput60():
tmps=input()
return tmps
def Net2Init(tmpnet):
for key in tmpnet.state_dict():
if('weight' in key):
init.zeros_(tmpnet.state_dict()[key])
else:
tmpnet.state_dict()[key][...] = 0
return tmpnet
def max_label(t):
labellist = t.tolist()[0]
maxnum = -10000
loc = 0
for j in range(len(labellist)):
if (maxnum < labellist[j]):
loc = j
maxnum = labellist[j]
return loc
class EasyNet(nn.Module):
def __init__(self):
super(EasyNet, self).__init__()
self.norm=nn.Softmax()
self.filter=nn.Linear(1,2)
self.bypass = nn.Linear(2,model_num,bias=False)
def forward(self, x):
x=self.filter(x)
x=self.bypass(x)
x=self.norm(x)
return x
namelist=['filter.weight', 'filter.bias', 'bypass.weight']
weightlist=[]
net=EasyNet()
mydict=net.state_dict()
net=Net2Init(net)
for i in range(len(namelist)):
weightlist.append(mydict[namelist[i]].tolist())
def Increazing_check(tmpnet,changelist):
for i in range(0,model_num-1):
tmpinput = torch.tensor([i * 1.0]).reshape([1, 1])
tmpwl = deepcopy(weightlist)
tmpdict = deepcopy(mydict)
tmpcl=changelist[i]
for j in range(len(tmpcl)):
if(len(tmpcl[j])==3):
a,b,c=tmpcl[j]
tmpwl[a][b]=c
if(len(tmpcl[j])==4):
a,b,c,d=tmpcl[j]
tmpwl[a][b][c]=d
for j in range(len(namelist)):
tmpdict[namelist[j]] = torch.tensor(tmpwl[j])
tmpnet.load_state_dict(tmpdict)
if(max_label(tmpnet(tmpinput))!=i+1):
return False
return True
def Main():
print('Please give me the weights!')
imgstr=getinput60()
weightstr=imgstr.split('|')
if(len(weightstr)!=model_num-1):
print('Wrong model number!')
else:
format_ok=True
changelist=[]
for i in range(len(weightstr)):
tmpstr=weightstr[i]
tmplist=[]
tmpchange=tmpstr.split('#')
for j in range(len(tmpchange)):
tmpweight=tmpchange[j]
tmpnum=tmpweight.split(',')
if(len(tmpnum)==4):
a,b,c,d=int(tmpnum[0]),int(tmpnum[1]),int(tmpnum[2]),float(tmpnum[3])
if(a<0 or a>2 or b<0 or b>model_num or c<0 or c>2 or math.isnan(d)):
format_ok=False
break
tmplist.append((a,b,c,d))
elif(len(tmpnum)==3):
a,b,c=int(tmpnum[0]),int(tmpnum[1]),float(tmpnum[2])
if (a < 0 or a > 2 or b<0 or b>2 or math.isnan(c)):
format_ok = False
break
tmplist.append((a,b,c))
else:
format_ok=False
break
changelist.append(tmplist)
if(format_ok):
if(Increazing_check(net,changelist)):
print('flag{test}')
else:
print('Increazing failure!')
else:
print('Format error!')
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/StarCTF/2023/crypto/gcccd/task.py | ctfs/StarCTF/2023/crypto/gcccd/task.py | #!/usr/bin/env python3
from secret import flag
import socketserver
import hashlib
import signal
import random
import string
import os
p=20973268502876719886012765513713011996343752519737224550553652605696573094756255499211333096502971357908939298357512380813773140436677393056575164230564778609423872301899323721040416852230597466288892977839300189625522429038289083381035647126860128821615664730513694930502000903655609105029016636999073477487851081722316115785141
enc=lambda x:pow(17,x,p)
m=int(flag.encode().hex(),16)
def gcd(a,b,f=enc):
if b:
return gcd(b,a%b,f)
else:
return f(a)
class Task(socketserver.BaseRequestHandler):
def __init__(self, *args, **kargs):
super().__init__(*args, **kargs)
def timeout_handler(self, signum, frame):
self.request.close()
def proof_of_work(self):
random.seed(os.urandom(8))
proof = ''.join([random.choice(string.ascii_letters+string.digits) for _ in range(20)])
_hexdigest = hashlib.sha256(proof.encode()).hexdigest()
self.request.send(f"sha256(XXXX+{proof[4:]}) == {_hexdigest}\n".encode()+b'Give me XXXX: ')
x = self.request.recv(1024).strip(b'\n')
if len(x) != 4 or hashlib.sha256(x+proof[4:].encode()).hexdigest() != _hexdigest:
return False
return True
def handle(self):
signal.alarm(60)
if not self.proof_of_work():
return
while True:
try:
self.request.send(b'type:')
t=int(self.request.recv(1024).strip(b'\n'))
self.request.send(b'a:')
a=int(self.request.recv(1024).strip(b'\n'))
self.request.send(b'b:')
b=int(self.request.recv(1024).strip(b'\n'))
assert a>0 and b>0
if t==1:#enc test
self.request.send(b'%d\n'%gcd(a,b))
elif t==2:#leak try1
self.request.send(b'%d\n'%gcd(a,m))
elif t==3:#leak try2
self.request.send(b'%d\n'%gcd(a,b,f=lambda x:gcd(x,m)))
elif t==4:#leak try3
self.request.send(b'%d\n'%gcd(a,m,f=lambda x:gcd(x,b)))
else:
self.request.close()
break
except BrokenPipeError:
break
except:
self.request.send(b'Bad input!\n')
class ThreadedServer(socketserver.ForkingMixIn, socketserver.TCPServer):
pass
if __name__ == "__main__":
HOST, PORT = '0.0.0.0', 23333
server = ThreadedServer((HOST, PORT), Task)
server.allow_reuse_address = True
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/StarCTF/2023/crypto/ezCrypto/ezCrypto.py | ctfs/StarCTF/2023/crypto/ezCrypto/ezCrypto.py | import random
import string
characters = string.printable[:-6]
digits = string.digits
ascii_letters = string.ascii_letters
def Ran_str(seed : int, origin: str):
random.seed(seed)
random_sequence = random.sample(origin, len(origin))
return ''.join(random_sequence)
rseed = int(input())
assert rseed <= 1000 and rseed >= 0
map_string1 = Ran_str(rseed, characters)
map_string2 = Ran_str(rseed * 2, characters)
map_string3 = Ran_str(rseed * 3, characters)
def util(flag):
return flag[9: -1]
def util1(map_string: str, c):
return map_string.index(c)
def str_xor(s: str, k: str):
return ''.join(chr((ord(a)) ^ (ord(b))) for a, b in zip(s, k))
def mess_sTr(s : str, index : int):
map_str = Ran_str(index, ascii_letters + digits)
new_str = str_xor(s, map_str[index])
if not characters.find(new_str) >= 0:
new_str = "CrashOnYou??" + s
return new_str, util1(map_str, s)
def crypto_phase1(flag):
flag_list1 = util(flag).split('_')
newlist1 = []
newlist2 = []
index = 1
k = 0
for i in flag_list1:
if len(i) % 2 == 1:
i1 = ""
for j in range(len(i)):
p, index = mess_sTr(i[j], index)
i1 += p
p, index = mess_sTr(i[0], index)
i1 += p
i1 += str(k)
k += 1
newlist1.append(i1)
else:
i += str(k)
k += 1
newlist2.append(i)
return newlist1, newlist2
def crypto_phase2(list):
newlist = []
for i in list:
str = ""
for j in i:
str += map_string1[util1(map_string3, j)]
newlist.append(str)
return newlist
def crypto_phase3(list):
newlist = []
for i in list:
str = ""
for j in i:
str += map_string2[util1(map_string3, j)]
newlist.append(str)
return newlist
def crypto_final(list):
str=""
for i in list[::-1]:
str += i
return str
if __name__ == '__main__':
format="sixstars{XXX}"
flag="Nothing normal will contribute to a crash. So when you find nothing, you find A Crashhhhhhhh!!! "
flaglist1, flaglist2 = crypto_phase1(flag)
cipher = crypto_final(crypto_phase3(crypto_phase2(flaglist1) + flaglist1) + crypto_phase2(crypto_phase3(flaglist2)))
print("map_string2: " + map_string2)
print("cipher: " + cipher)
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/StarCTF/2022/crypto/ezRSA/ezRSA.py | ctfs/StarCTF/2022/crypto/ezRSA/ezRSA.py | from Crypto.Util.number import getStrongPrime
from gmpy import next_prime
from random import getrandbits
from flag import flag
p=getStrongPrime(1024)
q=next_prime(p^((1<<900)-1)^getrandbits(300))
n=p*q
e=65537
m=int(flag.encode('hex'),16)
assert m<n
c=pow(m,e,n)
print(hex(n))
#0xe78ab40c343d4985c1de167e80ba2657c7ee8c2e26d88e0026b68fe400224a3bd7e2a7103c3b01ea4d171f5cf68c8f00a64304630e07341cde0bc74ef5c88dcbb9822765df53182e3f57153b5f93ff857d496c6561c3ddbe0ce6ff64ba11d4edfc18a0350c3d0e1f8bd11b3560a111d3a3178ed4a28579c4f1e0dc17cb02c3ac38a66a230ba9a2f741f9168641c8ce28a3a8c33d523553864f014752a04737e555213f253a72f158893f80e631de2f55d1d0b2b654fc7fa4d5b3d95617e8253573967de68f6178f78bb7c4788a3a1e9778cbfc7c7fa8beffe24276b9ad85b11eed01b872b74cdc44959059c67c18b0b7a1d57512319a5e84a9a0735fa536f1b3
print(hex(c))
#0xd7f6c90512bc9494370c3955ff3136bb245a6d1095e43d8636f66f11db525f2063b14b2a4363a96e6eb1bea1e9b2cc62b0cae7659f18f2b8e41fca557281a1e859e8e6b35bd114655b6bf5e454753653309a794fa52ff2e79433ca4bbeb1ab9a78ec49f49ebee2636abd9dd9b80306ae1b87a86c8012211bda88e6e14c58805feb6721a01481d1a7031eb3333375a81858ff3b58d8837c188ffcb982a631e1a7a603b947a6984bd78516c71cfc737aaba479688d56df2c0952deaf496a4eb3f603a46a90efbe9e82a6aef8cfb23e5fcb938c9049b227b7f15c878bd99b61b6c56db7dfff43cd457429d5dcdb5fe314f1cdf317d0c5202bad6a9770076e9b25b1
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/StarCTF/2022/crypto/Patches2/patches2.py | ctfs/StarCTF/2022/crypto/Patches2/patches2.py | from random import choice as c
from random import randint,shuffle
flag=open('flag','r').read()
white_list = ['==','(',')','C0','C1','C2','C3','C4','C5','C6','0','1','and','or']
from Crypto.Util.number import *
def calc(ans,chests,expr):
try:
C0, C1, C2, C3, C4, C5, C6 = chests
r = eval(expr)
except Exception as e:
print("Patches fails to understand your words.\n",e)
exit(0)
return ans(r)
def do_round():
truth=lambda r: not not r
lie=lambda r: not r
chests=[]
for i in range(7):
chests.append(c((True,False)))
print("Seven chests lie here, with mimics or treasure hidden inside.\nBut don't worry. Trusty Patches knows what to do.")
lie_count=c((1,2))
Patches=[truth]*(15-lie_count)+[lie]*lie_count
shuffle(Patches)
for i in range(15):
print("Ask Patches:")
question=input().strip()
for word in question.split(" "):
if word not in white_list:
print("({}) No treasure for dirty hacker!".format(word))
exit(0)
res=str(calc(Patches[i],chests,question))
print('Patches answers: {}!\n'.format(res))
print("Now open the chests:")
return chests == list(map(int, input().strip().split(" ")))
print("The Unbreakable Patches has returned, with more suspicous chests and a far more complicated strategy -- now he can lie twice! Can you still get all the treasure without losing your head?")
for i in range(50):
if not do_round():
print("A chest suddenly comes alive and BITE YOUR HEAD OFF.\n")
exit(0)
else:
print("You take all the treasure safe and sound. Head to the next vault!\n")
print("You've found all the treasure! {}\n".format(flag))
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/StarCTF/2022/crypto/InverseProblem2/problem.py | ctfs/StarCTF/2022/crypto/InverseProblem2/problem.py | import numpy as np
from secret import flag
def getQ(n):
return np.linalg.qr(np.random.random([n,n]))[0]
def pad(x,N=50,k=256):
return np.hstack([x,np.random.random(N-len(x))*k])
n=len(flag)
N=50
A=np.hstack([getQ(N)[:,:n]@np.diag(np.logspace(n,1,n))@getQ(n),getQ(N)[:,n:]@np.diag(np.linspace(N-n,1,N-n))@getQ(N-n)])
x=pad(list(flag))
b=A@x
np.savetxt('A.txt',A)
np.savetxt('b.txt',b) | python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/StarCTF/2022/web/oh-my-lotto-revenge/app/source/gunicorn.conf.py | ctfs/StarCTF/2022/web/oh-my-lotto-revenge/app/source/gunicorn.conf.py | workers = 2
bind = "0.0.0.0:8080" | python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/StarCTF/2022/web/oh-my-lotto-revenge/app/source/app.py | ctfs/StarCTF/2022/web/oh-my-lotto-revenge/app/source/app.py |
from flask import Flask,render_template, request
import secrets
import os
app = Flask(__name__, static_url_path='')
def safe_check(s):
if 'LD' in s or 'HTTP' in s or 'BASH' in s or 'ENV' in s or 'PROXY' in s or 'PS' in s:
return False
return True
@app.route("/", methods=['GET', 'POST'])
def index():
return render_template('index.html')
@app.route("/lotto", methods=['GET', 'POST'])
def lotto():
message = ''
if request.method == 'GET':
return render_template('lotto.html')
elif request.method == 'POST':
lotto_key = request.form.get('lotto_key') or ''
lotto_value = request.form.get('lotto_value') or ''
try:
lotto_key = lotto_key.upper()
except Exception as e:
print(e)
message = 'Lotto Error!'
return render_template('lotto.html', message=message)
if safe_check(lotto_key):
os.environ[lotto_key] = lotto_value
try:
os.system('wget --content-disposition -N lotto')
if os.path.exists("/app/lotto_result.txt"):
lotto_result = open("/app/lotto_result.txt", 'rb').read()
else:
lotto_result = 'result'
if os.path.exists("/app/guess/forecast.txt"):
forecast = open("/app/guess/forecast.txt", 'rb').read()
else:
forecast = 'forecast'
if forecast == lotto_result:
return "You are right!But where is flag?"
else:
message = 'Sorry forecast failed, maybe lucky next time!'
return render_template('lotto.html', message=message)
except Exception as e:
print("lotto error: ", e)
message = 'Lotto Error!'
return render_template('lotto.html', message=message)
else:
message = 'NO NO NO, JUST LOTTO!'
return render_template('lotto.html', message=message)
@app.route("/forecast", methods=['GET', 'POST'])
def forecast():
message = ''
if request.method == 'GET':
return render_template('forecast.html')
elif request.method == 'POST':
if 'file' not in request.files:
message = 'Where is your forecast?'
file = request.files['file']
file.save('/app/guess/forecast.txt')
message = "OK, I get your forecast. Let's Lotto!"
return render_template('forecast.html', message=message)
@app.route("/result", methods=['GET'])
def result():
if os.path.exists("/app/lotto_result.txt"):
lotto_result = open("/app/lotto_result.txt", 'rb').read().decode()
else:
lotto_result = ''
return render_template('result.html', message=lotto_result)
if __name__ == "__main__":
app.run(debug=True,host='0.0.0.0', port=8080)
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/StarCTF/2022/web/oh-my-lotto-revenge/lotto/source/gunicorn.conf.py | ctfs/StarCTF/2022/web/oh-my-lotto-revenge/lotto/source/gunicorn.conf.py | workers = 2
bind = "0.0.0.0:80" | python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/StarCTF/2022/web/oh-my-lotto-revenge/lotto/source/app.py | ctfs/StarCTF/2022/web/oh-my-lotto-revenge/lotto/source/app.py | from flask import Flask, make_response
import secrets
app = Flask(__name__)
@app.route("/")
def index():
lotto = []
for i in range(1, 20):
n = str(secrets.randbelow(40))
lotto.append(n)
r = '\n'.join(lotto)
response = make_response(r)
response.headers['Content-Type'] = 'text/plain'
response.headers['Content-Disposition'] = 'attachment; filename=lotto_result.txt'
return response
if __name__ == "__main__":
app.run(debug=True, host='0.0.0.0', port=80)
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/StarCTF/2022/web/oh-my-lotto/app/source/gunicorn.conf.py | ctfs/StarCTF/2022/web/oh-my-lotto/app/source/gunicorn.conf.py | workers = 2
bind = "0.0.0.0:8080" | python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/StarCTF/2022/web/oh-my-lotto/app/source/app.py | ctfs/StarCTF/2022/web/oh-my-lotto/app/source/app.py |
from flask import Flask,render_template, request
import os
app = Flask(__name__, static_url_path='')
def safe_check(s):
if 'LD' in s or 'HTTP' in s or 'BASH' in s or 'ENV' in s or 'PROXY' in s or 'PS' in s:
return False
return True
@app.route("/", methods=['GET', 'POST'])
def index():
return render_template('index.html')
@app.route("/lotto", methods=['GET', 'POST'])
def lotto():
message = ''
if request.method == 'GET':
return render_template('lotto.html')
elif request.method == 'POST':
flag = os.getenv('flag')
lotto_key = request.form.get('lotto_key') or ''
lotto_value = request.form.get('lotto_value') or ''
try:
lotto_key = lotto_key.upper()
except Exception as e:
print(e)
message = 'Lotto Error!'
return render_template('lotto.html', message=message)
if safe_check(lotto_key):
os.environ[lotto_key] = lotto_value
try:
os.system('wget --content-disposition -N lotto')
if os.path.exists("/app/lotto_result.txt"):
lotto_result = open("/app/lotto_result.txt", 'rb').read()
else:
lotto_result = 'result'
if os.path.exists("/app/guess/forecast.txt"):
forecast = open("/app/guess/forecast.txt", 'rb').read()
else:
forecast = 'forecast'
if forecast == lotto_result:
return flag
else:
message = 'Sorry forecast failed, maybe lucky next time!'
return render_template('lotto.html', message=message)
except Exception as e:
message = 'Lotto Error!'
return render_template('lotto.html', message=message)
else:
message = 'NO NO NO, JUST LOTTO!'
return render_template('lotto.html', message=message)
@app.route("/forecast", methods=['GET', 'POST'])
def forecast():
message = ''
if request.method == 'GET':
return render_template('forecast.html')
elif request.method == 'POST':
if 'file' not in request.files:
message = 'Where is your forecast?'
file = request.files['file']
file.save('/app/guess/forecast.txt')
message = "OK, I get your forecast. Let's Lotto!"
return render_template('forecast.html', message=message)
@app.route("/result", methods=['GET'])
def result():
if os.path.exists("/app/lotto_result.txt"):
lotto_result = open("/app/lotto_result.txt", 'rb').read().decode()
else:
lotto_result = ''
return render_template('result.html', message=lotto_result)
if __name__ == "__main__":
app.run(debug=True,host='0.0.0.0', port=8080)
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/StarCTF/2022/web/oh-my-lotto/lotto/source/gunicorn.conf.py | ctfs/StarCTF/2022/web/oh-my-lotto/lotto/source/gunicorn.conf.py | workers = 2
bind = "0.0.0.0:80" | python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/StarCTF/2022/web/oh-my-lotto/lotto/source/app.py | ctfs/StarCTF/2022/web/oh-my-lotto/lotto/source/app.py | from flask import Flask, make_response
import secrets
app = Flask(__name__)
@app.route("/")
def index():
lotto = []
for i in range(1, 20):
n = str(secrets.randbelow(40))
lotto.append(n)
r = '\n'.join(lotto)
response = make_response(r)
response.headers['Content-Type'] = 'text/plain'
response.headers['Content-Disposition'] = 'attachment; filename=lotto_result.txt'
return response
if __name__ == "__main__":
app.run(debug=True, host='0.0.0.0', port=80)
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/TsukuCTF/2021/web/gyOTAKU/app.py | ctfs/TsukuCTF/2021/web/gyOTAKU/app.py | import io
import os
import random
import string
import requests
import subprocess
from flask import Flask, render_template, request, send_file
app = Flask(__name__)
def sanitize(text):
#RCE is a non-assumed solution. <- This is not a hint.
url = ""
for i in text:
if i in string.digits + string.ascii_lowercase + string.ascii_uppercase + "./_:":
url += i
if (url[0:7]!="http://") and (url[0:8]!="https://"):
url = "https://www.google.com"
return url
@app.route("/")
def gyotaku():
filename = "".join([random.choice(string.digits + string.ascii_lowercase + string.ascii_uppercase) for i in range(15)])
url = request.args.get("url")
if not url:
return "<font size=6>๐gyOTAKU๐</font><br><br>You can get gyotaku: <strong>?url={URL}</strong><br>Sorry, we do not yet support other files in the acquired site."
url = sanitize(url)
html = open(f"{filename}.html", "w")
try:
html.write(requests.get(url, timeout=1).text + "<br><font size=7>gyotakued by gyOTAKU</font>")
except:
html.write("Requests error<br><font size=7>gyotakued by gyOTAKU</font>")
html.close()
cmd = f"chromium-browser --no-sandbox --headless --disable-gpu --screenshot='./gyotaku-{filename}.png' --window-size=1280,1080 '{filename}.html'"
subprocess.run(cmd, shell=True, timeout=1)
os.remove(f"{filename}.html")
png = open(f"gyotaku-{filename}.png", "rb")
screenshot = io.BytesIO(png.read())
png.close()
os.remove(f"gyotaku-{filename}.png")
return send_file(screenshot, mimetype='image/png')
if __name__ == "__main__":
app.run(debug=True, host='0.0.0.0', port=9000) | python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/TsukuCTF/2021/web/digits/program.py | ctfs/TsukuCTF/2021/web/digits/program.py | from typing import Optional
from fastapi import FastAPI
import random
app = FastAPI()
FLAG = "TsukuCTF{}"
@app.get("/")
def main(q: Optional[str] = None):
if q == None:
return {
"msg": "please input param 'q' (0000000000~9999999999). example: /?q=1234567890"
}
if len(q) != 10:
return {"msg": "invalid query"}
if "-" in q or "+" in q:
return {"msg": "invalid query"}
try:
if not type(int(q)) is int:
return {"msg": "invalid query"}
except:
return {"msg": "invalid query"}
you_are_lucky = 0
for _ in range(100):
idx = random.randrange(4)
if q[idx] < "0":
you_are_lucky += 1
if q[idx] > "9":
you_are_lucky += 1
if you_are_lucky > 0:
return {"flag": FLAG}
else:
return {"msg": "Sorry... You're unlucky."}
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/TsukuCTF/2023/crypto/new_cipher_scheme/output.py | ctfs/TsukuCTF/2023/crypto/new_cipher_scheme/output.py | r = 103223593878323616966427038558164830926502672938304332798494105455624811850665520007232855349275322661436610278579342219045141961390918581096853786570821153558254045159535424052709695034827346813080563034864500825268678590931984539859870234179994586959855078548304376995608256368401270715737193311910694875689
n = 90521376653923821958506872761083900256851127935359160710837379527192460953892753506429215845453212892652253605621731883413509776201057002264429057442656548984456115251090306646791059258375402999471135320210755348861434045380328105743420902906907790808856692202001235875364637226136825102255804354305482559609
e = 65537
c = 39668573485152693308506976557973651059962715190609831067529475947235507499262380684639847018675763554013384459402806860854682788726216001229367497152996318350435451964626471390994912819484930957099855090471916842543402636518804720798852670908465424119746453269056516567591615005540824659735238630769424838121
s = 47973982866708538282860872778400091099562248899259778360037347668440286307912908903978215839469425552581036546347166946878631770320447658019243172948791127890920650587484602734465156455346574205060576092006378013418405134156752490431761037178223087071698840062913540185985867322265081768252745826955229941850
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/TsukuCTF/2023/crypto/new_cipher_scheme/problem.py | ctfs/TsukuCTF/2023/crypto/new_cipher_scheme/problem.py | from Crypto.Util.number import *
from flag import flag
def magic2(a):
sum = 0
for i in range(a):
sum += i * 2 + 1
return sum
def magic(p, q, r):
x = p + q
for i in range(3):
x = magic2(x)
return x % r
m = bytes_to_long(flag.encode())
p = getPrime(512)
q = getPrime(512)
r = getPrime(1024)
n = p * q
e = 65537
c = pow(m, e, n)
s = magic(p, q, r)
print("r:", r)
print("n:", n)
print("e:", e)
print("c:", c)
print("s:", s)
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/TsukuCTF/2023/web/EXECpy/crawler/capp.py | ctfs/TsukuCTF/2023/web/EXECpy/crawler/capp.py | import os
import asyncio
from playwright.async_api import async_playwright
from flask import Flask, render_template, request
app = Flask(__name__)
DOMAIN = "nginx"
FLAG = os.environ.get("FLAG", "TsukuCTF23{**********REDACTED**********}")
@app.route("/crawler", methods=["GET"])
def index_get():
return render_template("index_get.html")
async def crawl(url):
async with async_playwright() as p:
browser = await p.chromium.launch()
page = await browser.new_page()
try:
response = await page.goto(url, timeout=5000)
header = await response.header_value("Server")
content = await page.content()
if ("Tsukushi/2.94" in header) and ("๐คช" not in content):
await page.context.add_cookies(
[{"name": "FLAG", "value": FLAG, "domain": DOMAIN, "path": "/"}]
)
if url.startswith(f"http://{DOMAIN}/?code=") or url.startswith(
f"https://{DOMAIN}/?code="
):
await page.goto(url, timeout=5000)
except:
pass
await browser.close()
@app.route("/crawler", methods=["POST"])
def index_post():
asyncio.run(
crawl(
request.form.get("url").replace(
"http://localhost:31416/", f"http://{DOMAIN}/", 1
)
)
)
return render_template("index_post.html")
if __name__ == "__main__":
app.run(debug=True, host="0.0.0.0", port=31417)
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/TsukuCTF/2023/web/EXECpy/app/app.py | ctfs/TsukuCTF/2023/web/EXECpy/app/app.py | from flask import Flask, render_template, request
app = Flask(__name__)
@app.route("/", methods=["GET"])
def index():
code = request.args.get("code")
if not code:
return render_template("index.html")
try:
exec(code)
except:
pass
return render_template("result.html")
if __name__ == "__main__":
app.run(debug=True, host="0.0.0.0", port=31416)
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/TsukuCTF/2023/web/MEMOwow/app/app.py | ctfs/TsukuCTF/2023/web/MEMOwow/app/app.py | import base64
import secrets
import urllib.parse
from flask import Flask, render_template, request, session, redirect, url_for, abort
SECRET_KEY = secrets.token_bytes(32)
app = Flask(__name__)
app.secret_key = SECRET_KEY
@app.route("/", methods=["GET"])
def index():
if not "memo" in session:
session["memo"] = [b"Tsukushi"]
return render_template("index.html")
@app.route("/write", methods=["GET"])
def write_get():
if not "memo" in session:
return redirect(url_for("index"))
return render_template("write_get.html")
@app.route("/read", methods=["GET"])
def read_get():
if not "memo" in session:
return redirect(url_for("index"))
return render_template("read_get.html")
@app.route("/write", methods=["POST"])
def write_post():
if not "memo" in session:
return redirect(url_for("index"))
memo = urllib.parse.unquote_to_bytes(request.get_data()[8:256])
if len(memo) < 8:
return abort(403, "ใใใใใใฎ้ทใใฏ่จๆถใใฆใใ ใใใ๐ป")
try:
session["memo"].append(memo)
if len(session["memo"]) > 5:
session["memo"].pop(0)
session.modified = True
filename = base64.b64encode(memo).decode()
with open(f"./memo/{filename}", "wb+") as f:
f.write(memo)
except:
return abort(403, "ใจใฉใผใ็บ็ใใพใใใ๐ป")
return render_template("write_post.html", id=filename)
@app.route("/read", methods=["POST"])
def read_post():
if not "memo" in session:
return redirect(url_for("index"))
filename = urllib.parse.unquote_to_bytes(request.get_data()[7:]).replace(b"=", b"")
filename = filename + b"=" * (-len(filename) % 4)
if (
(b"." in filename.lower())
or (b"flag" in filename.lower())
or (len(filename) < 8 * 1.33)
):
return abort(403, "ไธๆญฃใชใกใขIDใงใใ๐ป")
try:
filename = base64.b64decode(filename)
if filename not in session["memo"]:
return abort(403, "ใกใขใ่ฆใคใใใพใใใ๐ป")
filename = base64.b64encode(filename).decode()
with open(f"./memo/{filename}", "rb") as f:
memo = f.read()
except:
return abort(403, "ใจใฉใผใ็บ็ใใพใใใ๐ป")
return render_template("read_post.html", id=filename, memo=memo.decode())
if __name__ == "__main__":
app.run(debug=True, host="0.0.0.0", port=31415)
| 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_3/chall.py | ctfs/BlueWater/2024/misc/RSAjail_3/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) > 3) 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 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.