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/TeamItaly/2023/web/Borraccia/challenge/Borraccia/_types.py
ctfs/TeamItaly/2023/web/Borraccia/challenge/Borraccia/_types.py
import re from rich.logging import RichHandler from rich._null_file import NullFile from rich.traceback import Traceback class ObjDict: def __init__(self, d={}): self.__dict__['_data'] = d # Avoiding Recursion errors on __getitem__ def __getattr__(self, key): if key in self._data: return self._data[key] return None def __contains__(self, key): return key in self._data def __setattr__(self, key, value): self._data[key] = value def __getitem__(self, key): return self._data[key] def __setitem__(self, key, value): self._data[key] = value def __delitem__(self, key): del self._data[key] def __enter__(self, *args): return self def __exit__(self, *args): self.__dict__["_data"].clear() del self.__dict__['_data'] del self def __repr__(self): return f"ObjDict object at <{hex(id(self))}>" def __iter__(self): return iter(self._data) class TruncatedStringHandler(RichHandler): def __init__(self, max_length=256): super().__init__() self.max_length = max_length def emit(self, record) -> None: """Invoked by logging, taken from rich.logging.RichHandler""" """NOTE: THIS IS NOT PART OF THE CHALLENGE. DO NOT WASTE TIME""" record.msg = re.sub(r"\)\d+.", ")", record.msg) message = self.format(record) traceback = None if ( self.rich_tracebacks and record.exc_info and record.exc_info != (None, None, None) ): exc_type, exc_value, exc_traceback = record.exc_info assert exc_type is not None assert exc_value is not None traceback = Traceback.from_exception( exc_type, exc_value, exc_traceback, width=self.tracebacks_width, extra_lines=self.tracebacks_extra_lines, theme=self.tracebacks_theme, word_wrap=self.tracebacks_word_wrap, show_locals=self.tracebacks_show_locals, locals_max_length=self.locals_max_length, locals_max_string=self.locals_max_string, suppress=self.tracebacks_suppress, ) message = record.getMessage() if self.formatter: record.message = record.getMessage() formatter = self.formatter if hasattr(formatter, "usesTime") and formatter.usesTime(): record.asctime = formatter.formatTime(record, formatter.datefmt) message = formatter.formatMessage(record) message_renderable = self.render_message(record, message) if len(message_renderable) > self.max_length: message_renderable = message_renderable[:self.max_length - 3] + "..." log_renderable = self.render( record=record, traceback=traceback, message_renderable=message_renderable ) if isinstance(self.console.file, NullFile): self.handleError(record) else: try: self.console.print(log_renderable) except Exception: self.handleError(record)
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/TeamItaly/2023/web/Borraccia/challenge/Borraccia/const.py
ctfs/TeamItaly/2023/web/Borraccia/challenge/Borraccia/const.py
import os import sys CURRENT_DIR = os.path.dirname(os.path.abspath(sys.modules['__main__'].__name__)) PUBLIC_DIR = os.path.join(CURRENT_DIR, "public") STATIC_DIR = os.path.join(PUBLIC_DIR, "static") ERROR_DIR = os.path.join(os.path.dirname(os.path.abspath(__file__)), "errors")
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/TeamItaly/2023/web/Borraccia/challenge/Borraccia/utils.py
ctfs/TeamItaly/2023/web/Borraccia/challenge/Borraccia/utils.py
import os import re import typing from . import _types from functools import lru_cache from .const import STATIC_DIR, ERROR_DIR @lru_cache def normalize_header(s: str) -> str: return s.lower().replace('-', '_') @lru_cache def normalize_header_value(s: str) -> str: return re.sub(r"[%\"\.\n\'\!:\(\)]", "", s) @lru_cache def serve_file(path: str) -> str: try: with open(path, "r") as f: return f.read() except FileNotFoundError: return '' @lru_cache def serve_static_file(path: str) -> str: try: with open(resolve_path(STATIC_DIR, path), "r") as f: return f.read() except FileNotFoundError: return '' @lru_cache def serve_error(status_code: int) -> str: try: with open(resolve_path(ERROR_DIR, str(status_code).strip()), "r") as f: return f.read() except FileNotFoundError: return '' def extract_params(p) -> typing.Dict: return {key: value[0] if isinstance(value, list) and len(value) == 1 else value \ for key, value in p.items()} @lru_cache def resolve_path(base: str, path: str) -> str: return os.path.join(base, path) if ".." not in path else '' def make_comment(s): return "<!--" + s + "-->" def log(log, s, mode="INFO", ctx=None): { "DEBUG": log.debug, "INFO": log.info, "ERROR": log.error }[mode](s.format(ctx), {"mode": mode}) def build_header(ctx: _types.ObjDict) -> None: # Build the header with status code, headers, etc... ctx.response.header += ctx.request.http_version + " " + str(ctx.response.status_code) + " " + ctx.response.message + "\n" for header in ctx.response.headers: ctx.response.header += f"{header}: {ctx.response.headers[header]}\n" ctx.response.header += f"Content-Length: {len(ctx.response.body)}\n" ctx.response.header += "\n" ctx.response.header = ctx.response.header.replace("\n", "\r\n")
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/TeamItaly/2023/web/Borraccia/challenge/Borraccia/__init__.py
ctfs/TeamItaly/2023/web/Borraccia/challenge/Borraccia/__init__.py
from .server import * from .const import *
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/TeamItaly/2023/web/Borraccia/challenge/Borraccia/server.py
ctfs/TeamItaly/2023/web/Borraccia/challenge/Borraccia/server.py
import os import re import sys import time import typing import socket import logging import traceback import multiprocessing from . import utils from .const import * from jinja2 import Template from rich import print as rich_print from urllib.parse import parse_qs, unquote from ._types import ObjDict, TruncatedStringHandler #========================= # INCREASE THESE VALUE IF # THE CHALLENGE ISN'T WORKING # CORRECTLY MAX_REQ_SIZE = int(os.environ.get("MAX_REQ_SIZE", 16384)) SOCK_TIMEOUT = int(os.environ.get("SOCK_TIMEOUT", 5)) SHORT_SOCK_TIMEOUT = float(os.environ.get("SHORT_SOCK_TIMEOUT", .15)) WORKERS = int(os.environ.get("WORKERS", 4)) # Default value # ======================== VERSION = "1.0" BLOCK_RE = re.compile(r"([\S\s]+(?=\r\n\r\n))") # Matching HTTP header only HEADER_RE = re.compile(r"([a-zA-Z-]{1,40})\:\s*(.{1,128})") # Matching headers (header: value) PATH_TRAVERSAL_RE = re.compile(r"(^(\\|\/))|(\.\.(\/|\\))") # Matching path traversal patterns (/ | ../ | ..\) CONTENT_LENGTH = re.compile(r"Content-Length:\s(\d+)") # Matching content-length header (only positive values) PARSER_RE = re.compile(r"([\S\s]+)(?=(\r\n\r\n(.+))|(\r\n\r\n))") # Matching HTTP header and body METHODS = [ "GET", "POST" ] ERRORS = { 418: "I'm a teapot", 500: "Internal Server Error", 405: "Method Not Allowed", 401: "Unauthorized", 404: "Not found" } SUPPORTED_HTTP_VERSIONS = ["HTTP/1.1"] class App: name: str is_main: bool __nworkers: int server: socket.socket endpoints: typing.Dict running: bool _shared: typing.Dict ratelimit: int def __init__(self, name, ratelimit=float(os.environ.get("RATELIMIT", "inf")), nworkers=WORKERS): self.endpoints = dict() self.name = name self.__nworkers = nworkers self.is_main = self.name == "__main__" self.ratelimit = ratelimit def get(self, endpoint: str, function: typing.Callable) -> None: if endpoint not in self.endpoints: self.endpoints[endpoint] = {"methods": {}} self.endpoints[endpoint]["methods"].update({ "GET": function }) def post(self, endpoint: str, function: typing.Callable) -> None: if endpoint not in self.endpoints: self.endpoints[endpoint] = {"methods": {}} self.endpoints[endpoint]["methods"].update({ "POST": function }) def stop(self) -> None: sys.exit(0) def run(self, address: str="0.0.0.0", port: int=80) -> None: if self.is_main: self.server = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self.server.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) self.server.bind((address, port)) self.server.listen(self.__nworkers * 2) self._shared = multiprocessing.Manager().dict() workers = [multiprocessing.Process(target=handler, args=(self.server, self, )) for _ in range(self.__nworkers)] for w in workers: w.daemon = True w.start() if address == "0.0.0.0": rich_print("[green] * Running on all addresses.[/green]") rich_print(f"[yellow] * Server started at[/yellow] http://localhost:{port}/\n") try: while True: time.sleep(1) except KeyboardInterrupt: rich_print("[yellow]Stopping all processes...[/yellow]") self.stop() def set_logger() -> None: FORMAT = "%(message)s" logging.basicConfig( level="NOTSET", format=FORMAT, datefmt="[%H:%M:%S.%f]", handlers=[TruncatedStringHandler()] ) def set_status_code(ctx: ObjDict, status_code: int) -> None: ctx.response.status_code = status_code ctx.response.message = ERRORS.get(status_code, ERRORS[404]) def recvuntil(sock: socket.socket, buffer_size: int=4096) -> typing.List: received_data = "" post_data = "" match = None sock.settimeout(SOCK_TIMEOUT) while not match: received_data += sock.recv(buffer_size).decode() assert received_data.count("\r") < 1024 match = PARSER_RE.search(received_data[:MAX_REQ_SIZE]) # Receiving until \r\n\r\n found try: sock.settimeout(SHORT_SOCK_TIMEOUT) sock.recv(16, socket.MSG_PEEK) # Receiving without consuming if match: content = match.group(1) if (content_length := CONTENT_LENGTH.search(content)): content_length = int(content_length.group(1)) post_data += sock.recv(content_length).decode() # Receiving POST data return PARSER_RE.search(content + post_data).groups() except TimeoutError: return match.groups() except AttributeError: pass def render_template(template_file: str, **kwargs) -> str: with open(os.path.join(PUBLIC_DIR, "templates", template_file), 'r') as f: buf = f.read() return Template(buf).render(kwargs) def parse_request(request: typing.List, ctx: ObjDict) -> None: ctx.response = ObjDict() ctx.request = ObjDict() ctx.response.status_code = 200 # Default value ctx.response.message = "OK" # Default value ctx.response.headers = { # Static headers. "Server": f"Borraccia/{VERSION}", "Content-Type": "text/html", # Only html content is supported "Content-Security-Policy": "default-src 'none'; require-trusted-types-for 'script'", "Referrer-Policy": "strict-origin-when-cross-origin" } ctx.response.header = "" ctx.response.body = "" start_and_headers = request[0] should_be_a_post_request = bool(request[-2]) post_data = request[-2] post_data = utils.extract_params(parse_qs(post_data) if post_data else {}) rows = start_and_headers.split("\n") first_row = rows[0].split() method = first_row[0] path = first_row[1] params = utils.extract_params(parse_qs(params[1]) if len((params:=path.split("?"))) > 1 else {}) http_version = first_row[2] ctx.request.http_version = http_version ctx.request.params = params ctx.request.path = unquote(path.split("?")[0].lower()) ctx.request.post_data = post_data ctx.request.method = method assert method.isalpha() if method not in METHODS: ctx.response.status_code = 405 # Method not supported elif http_version not in SUPPORTED_HTTP_VERSIONS: ctx.response.status_code = 418 # I'm a teapot elif should_be_a_post_request: if not method == "POST": ctx.response.status_code = 500 # Internal Server Error elif PATH_TRAVERSAL_RE.search(uq:=unquote(path[1:])): ctx.response.status_code = 401 # Unauthorized utils.log(logging, f"Path traversal attempt detected ", "ERROR") for probable_header in filter(None, rows[1:]): # Memorizing headers if (cap:=HEADER_RE.search(probable_header)): header = cap.group(1) value = cap.group(2) h = utils.normalize_header(header) v = utils.normalize_header_value(value) ctx.request[h] = v def request_handler(client: socket.socket, address: typing.Tuple, app: App, curr: str) -> None: with ObjDict() as ctx: data = recvuntil(client) if not data: ctx.response.body = utils.serve_error(500) ctx.response.message = ERRORS[500] client.send((ctx.response.header + ctx.response.body).encode()) parse_request(data, ctx) # Extract path, params, headers, etc... res = function_wrapper(app, ctx) # Check if the path is valid if ctx.response.status_code == 200: ctx.response.status_code = res if ctx.response.status_code != 200: # Something went wrong ctx.response.message = ERRORS.get(ctx.response.status_code, ERRORS[500]) ctx.response.body = utils.serve_error(ctx.response.status_code) else: try: ctx.response.body = app.endpoints[ctx.request.path]["methods"][ctx.request.method](ctx) except Exception as e: # Something went wrong with App() utils.log(logging, ''.join(traceback.format_exception(e)[-2:]), "ERROR") ctx.response.body = utils.serve_error(500) + utils.make_comment(f"{e}") ctx.response.message = ERRORS[500] try: utils.build_header(ctx) # Now the response is ready to be sent utils.log(logging, f"[{curr}]\t{ctx.request.method}\t{ctx.response.status_code}\t{address[0]}", "DEBUG", ctx) assert ctx.response.status_code in ERRORS or ctx.response.status_code == 200 except AssertionError: raise # Something unexpected happened, close conection immediately except Exception as e: ctx.response.status_code = 500 ctx.response.header = "" ctx.response.body = utils.serve_error(ctx.response.status_code) + utils.make_comment(f"{e}") # Something went wrong while building the header. utils.build_header(ctx) client.send((ctx.response.header + ctx.response.body).encode()) def function_wrapper(app: App, ctx: ObjDict) -> bool: return 200 if (endpoint:=app.endpoints.get(ctx.request.path)) and ctx.request.method in endpoint["methods"] else 404 def request_wrapper(client, address, app: App, curr): # This is beautiful! addr = address[0] if addr not in app._shared: app._shared[addr] = (time.time(), 0) app._shared[addr] = (app._shared[addr][0], app._shared[addr][1]+1) if time.time() - app._shared[addr][0] > 1*60: app._shared[addr] = (time.time(), 0) if app._shared[addr][1] < app.ratelimit: request_handler(client, address, app, curr) def handler(sock: socket.socket, app: App) -> None: curr = multiprocessing.current_process().name.split("-")[-1] set_logger() while True: try: client, address = sock.accept() request_wrapper(client, address, app, curr) except Exception as e: utils.log(logging, f"[{curr}] [{address[0]}:{address[1]}] {e}", "ERROR") client.close()
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/Nexus/2024/misc/Escape/chall.py
ctfs/Nexus/2024/misc/Escape/chall.py
#!/usr/bin/python3 import signal from functools import wraps supers3cr3t = 'NexusCTF{REDACTED}' attempt_limit = 3 timeout_seconds = 5 def timeout_handler(signum, frame): print("\nTimeout reached. Exiting...") exit(0) def limit_attempts(func): @wraps(func) def wrapper(*args, **kwargs): for _ in range(attempt_limit): func(*args, **kwargs) print("Exceeded attempt limit. Exiting...") exit(0) return wrapper @limit_attempts def challenge(): signal.signal(signal.SIGALRM, timeout_handler) signal.alarm(timeout_seconds) try: inp = input("Present the Warrior's code to attain the key to victory: ") signal.alarm(0) if len(inp) < 17 and 'supers3cr3t' not in inp: print(eval(inp)) else: print('You are still not worthy. Come back another time') except KeyboardInterrupt: print("\nAbort!!") exit(0) if __name__ == "__main__": print("----------------Welcome to the Dragon's Lair-----------------") challenge()
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/Nexus/2024/crypto/RAS/chall.py
ctfs/Nexus/2024/crypto/RAS/chall.py
from Crypto.Util.number import getPrime, inverse, bytes_to_long, long_to_bytes from string import ascii_letters, digits from random import choice wisdom = "".join(choice(ascii_letters + digits) for _ in range(16)) passion = getPrime(128) ambition = getPrime(128) desire = passion * ambition willpower = 65537 fate = inverse(willpower, (passion - 1) * (ambition - 1)) insight = pow(bytes_to_long(wisdom.encode()), willpower, desire) print(f"{insight = }") print(f"{fate = }") print("Virtue:") virtue = input("> ").strip() if virtue == wisdom: print("Victory!!") with open("/challenge/flag.txt") as f: print(f.read()) else: print("Defeat!")
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/DamCTF/2021/rev/seed/seed.py
ctfs/DamCTF/2021/rev/seed/seed.py
#!/usr/bin/env python3 import sys import time import random import hashlib def seed(): return round(time.time()) def hash(text): return hashlib.sha256(str(text).encode()).hexdigest() def main(): while True: s = seed() random.seed(s, version=2) x = random.random() flag = hash(x) if 'b9ff3ebf' in flag: with open("./flag", "w") as f: f.write(f"dam{{{flag}}}") f.close() break print(f"Incorrect: {x}") print("Good job <3") if __name__ == "__main__": sys.exit(main())
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/DamCTF/2021/crypto/time-ai/chal.py
ctfs/DamCTF/2021/crypto/time-ai/chal.py
#!/usr/bin/env sage from sage.all import * from sage.schemes.elliptic_curves.ell_point import EllipticCurvePoint_number_field from Crypto.Cipher import AES # The description of CrownRNG is too unclear, and the system random number # generator is bound to be more secure anyway. from Crypto.Random import random as crypt_random curve25519_p = 2**255 - 19 F = GF(curve25519_p) curve25519 = EllipticCurve(F, [0, 486662, 0, 1, 0]) assert(curve25519.count_points() == 57896044618658097711785492504343953926856930875039260848015607506283634007912) def sample_R(): # shift is to clear the cofactor return (crypt_random.randrange(2**255) >> 3) <<3 def shared_aes_key(point) -> bytes: return AES.new(int(point.xy()[0]).to_bytes(256 // 8, 'little'), AES.MODE_CTR) def xy_to_curve(x, y): return EllipticCurvePoint_number_field(curve25519, (x, y, 1), check=False) base_p = xy_to_curve(9, 43114425171068552920764898935933967039370386198203806730763910166200978582548) ### execute both parties and print the transcript. ## section 4.I.b # alice a = sample_R() A = a*base_p print(f'A: {A}') # bob b = sample_R() B = b*base_p print(f'B: {B}') # alice Ka = a*B # bob Kb = b*A assert(Ka == Kb) ## section 4.I.c # alice aes = shared_aes_key(Ka) last_digit_idx = crypt_random.randrange(4) start_index = crypt_random.randrange(132, 193) params = f'{last_digit_idx},{start_index:9}'.encode() enc_params = aes.encrypt(params) print(f'enc_params: {enc_params.hex()}') with open("flag", 'r') as f: message = f"Psst! Bob, don't tell anyone, but the flag is {f.read().strip()}.".encode() msg_bits = 8 * len(message) NPSN = 10 * int(Ka.xy()[0]) + [2, 3, 7, 8][last_digit_idx] key_stream = N(sqrt(NPSN), start_index + msg_bits).sign_mantissa_exponent()[1] key_stream &= (2**msg_bits - 1) key_stream = int(key_stream).to_bytes(len(message), 'big') enc_msg = bytes([x ^ y for x, y in zip(message, key_stream)]) print(f'enc_msg: {enc_msg.hex()}')
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/DamCTF/2021/crypto/hav3-i-b33n-pwn3d/common.py
ctfs/DamCTF/2021/crypto/hav3-i-b33n-pwn3d/common.py
#!/usr/bin/env sage from sage.all import * from sage.schemes.elliptic_curves.ell_point import EllipticCurvePoint_number_field from Crypto.Hash import MD5, SHA256 from Crypto.Random import random as crypt_random curve25519_p = 2**255 - 19 F = GF(curve25519_p) R = F['x'] x = R.gen() curve25519 = EllipticCurve(F, [0, 486662, 0, 1, 0]) #assert(curve25519.count_points() == 57896044618658097711785492504343953926856930875039260848015607506283634007912) # cofactor == bad? def sample_R(): return (crypt_random.randrange(2**255) >> 3) <<3 def md5(msg: bytes) -> int: h = MD5.new() h.update(msg) return int.from_bytes(h.digest(), 'little') def sha(msg: bytes) -> bytes: h = SHA256.new() h.update(msg) return h.digest() def xy_to_curve(x, y): return EllipticCurvePoint_number_field(curve25519, (x, y, 1), check=False) base_p = xy_to_curve(9, 43114425171068552920764898935933967039370386198203806730763910166200978582548)
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/DamCTF/2021/crypto/hav3-i-b33n-pwn3d/psi_receiver.py
ctfs/DamCTF/2021/crypto/hav3-i-b33n-pwn3d/psi_receiver.py
#!/usr/bin/env sage from common import * from Crypto.Random import random import json import threading import socket with open("passwords", 'r') as f: passwords = f.read().strip().split('\n') class Server: CHUNK = 64 def __init__(self, host='0.0.0.0', port=31337): print(f"Binding to {host}:{port}") self.s = socket.socket() self.s.bind((host, port)) def listen(self): self.s.listen(5) while True: c, addr = self.s.accept() threading.Thread(target=self.puzzle, args=(c,)).start() def puzzle(self, conn): c = conn def send(msg): c.sendall((msg + '\n').encode()) def recv(): message = b'' while len(message) < 4098: part = c.recv(self.CHUNK) if b'\n' in part: message += part.split(b'\n')[0] break else: message += part return message try: xs = [] ys = [] bs = [] m = xy_to_curve(*json.loads(recv())) for i in range(len(passwords)): b = sample_R() p = b * base_p bs.append(b) key = F(md5(passwords[i].encode())) px, py = p.xy() xs.append((key, px)) ys.append((key, py)) x_poly = R.lagrange_polynomial(xs) y_poly = R.lagrange_polynomial(ys) send(str(x_poly)) send(str(y_poly)) ks = set(json.loads(recv())) if len(ks) > 20: send("Error: password limit exceeded.") return intersection = [] for p, b in zip(passwords, bs): elem = sha(p.encode() + str((b * m)).encode()).hex() if elem in ks: intersection.append(p) if len(intersection) == len(passwords): send("They've all been pwned?! Really?!?! Please hold my flag while I go change them.") with open("flag", "r") as f: send(f.read()) elif len(intersection) != 0: send("Some of my passwords have been leaked! I'll change them when I get around to it...") else: send("It's good to know that none of my passwords are in your pwned database :)") c.shutdown(1) c.close() except Exception as e: pass if __name__ == "__main__": server = Server() server.listen()
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/DamCTF/2021/crypto/hav3-i-b33n-pwn3d/psi_sender.py
ctfs/DamCTF/2021/crypto/hav3-i-b33n-pwn3d/psi_sender.py
#!/usr/bin/env sage from common import * import json import socket import sys IP = "hav3-i-b33n-pwn3d.damctf.xyz" PORT = 30944 CHUNK = 64 def send(c, msg): c.sendall((msg + '\n').encode()) def recv(c): message = b'' while len(message) < 4098: part = c.recv(CHUNK) if b'\n' in part: message += part.split(b'\n')[0] break else: message += part return message.decode() def main(): passwords = sys.argv[1:] a = sample_R() m = a*base_p s = socket.socket() s.connect((IP, PORT)) send(s, str(list(m.xy()))) x_poly = R(recv(s)) y_poly = R(recv(s)) if x_poly.degree() < 1 or y_poly.degree() < 1: exit(1) ks = [] for pas in passwords: key = F(md5(pas.encode())) px = x_poly(key) py = y_poly(key) point = xy_to_curve(px, py) k = sha((pas + str(a * point)).encode()) ks.append(k.hex()) crypt_random.shuffle(ks) send(s, json.dumps(ks)) print(recv(s)) 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/DamCTF/2024/crypto/aedes/aedes.py
ctfs/DamCTF/2024/crypto/aedes/aedes.py
#!/usr/local/bin/python3 from functools import reduce, partial import operator import secrets from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes def xor(*bs): return bytes(reduce(operator.xor, bb) for bb in zip(*bs, strict=True)) def expand_k(k): sched = [] for i in range(7): subkey = F(k, i.to_bytes(16)) sched[i:i] = [subkey, subkey] sched.insert(7, F(k, (7).to_bytes(16))) return sched def F(k, x): f = Cipher(algorithms.AES(k), modes.ECB()).encryptor() return f.update(x) + f.finalize() def enc(k, m): subkeys = expand_k(k) left, right = m[:16], m[16:] for i in range(15): old_right = right right = xor(left, F(subkeys[i], right)) left = old_right return left + right print("Introducing AEDES, the result of taking all of the best parts of AES and DES and shoving them together! It should be a secure block cipher but proofs are hard so I figured I'd enlist the help of random strangers on the internet! If you're able to prove me wrong you might get a little prize :)") key = secrets.token_bytes(16) with open("flag", "rb") as f: flag = f.read(32) assert len(flag) == 32 flag_enc = enc(key, flag) print("Since I'm so confident in the security of AEDES, here's the encrypted flag. Good luck decrypting it without the key :)") print(flag_enc.hex()) for _ in range(5): pt_hex = input("Your encryption query (hex): ") try: pt = bytes.fromhex(pt_hex) assert len(pt) == 32 except (ValueError, AssertionError): print("Make sure your queries are 32 bytes of valid hex please") continue ct = enc(key, pt) print("Result (hex):", ct.hex())
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/DamCTF/2024/crypto/fundamental_revenge/fundamental-revenge.py
ctfs/DamCTF/2024/crypto/fundamental_revenge/fundamental-revenge.py
#!/usr/local/bin/python3 from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes import secrets import sys p = 168344944319507532329116333970287616503 def F(k, x): f = Cipher(algorithms.AES(k), modes.ECB()).encryptor() return f.update(x) + f.finalize() def poly_eval(coeffs, x): res = 0 for c in coeffs: res = (c + x * res) % p return res def to_coeffs(m): coeffs = [1] for i in range(0, len(m), 16): chunk = m[i : i + 16] coeffs.append(int.from_bytes(chunk)) return coeffs def auth(k, s, m): coeffs = to_coeffs(m) poly_k = int.from_bytes(k[16:]) mac_int = (poly_eval(coeffs, poly_k) + s) % p return F(k[:16], mac_int.to_bytes(16)) def ver(k, s, m, t): return secrets.compare_digest(auth(k, s, m), t) def hexinput(msg): try: b = bytes.fromhex(input(msg)) assert len(b) % 16 == 0 and len(b) > 0 return b except (ValueError, AssertionError): print("please enter a valid hex string") return None k = secrets.token_bytes(32) s = secrets.randbelow(p) target = b"gonna ace my crypto final with all this studying" print("Let's try this again, shall we?") print() while (msg1 := hexinput("first message to sign (hex): ")) is None: pass if msg1 == target: print("nice try :)") sys.exit(1) mac = auth(k, s, msg1) print("authentication tag:", mac.hex()) print() print("now sign this:", target.decode()) while (tag := hexinput("enter verification tag (hex): ")) is None: pass if ver(k, s, target, tag): print("oh you did it again...I guess I'm just bad at cryptography :((") with open("flag") as f: print("here's your flag again..", f.read()) else: print("invalid authentication tag")
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/DamCTF/2024/crypto/fundamental/fundamental.py
ctfs/DamCTF/2024/crypto/fundamental/fundamental.py
#!/usr/local/bin/python3 import secrets import sys p = 129887472129814551050345803501316649949 def poly_eval(coeffs, x): res = 0 for c in coeffs: res = (c + x * res) % p return res def pad(m): padlen = 16 - (len(m) % 16) padding = bytes([padlen] * padlen) return m + padding def to_coeffs(m): coeffs = [] for i in range(0, len(m), 16): chunk = m[i:i+16] coeffs.append(int.from_bytes(chunk)) return coeffs def auth(s, k, m): coeffs = to_coeffs(m) mac_int = (poly_eval(coeffs, k) + s) % p return mac_int.to_bytes(16) def ver(s, k, m, t): return secrets.compare_digest(t, auth(s, k, m)) def hexinput(msg): try: return bytes.fromhex(input(msg)) except ValueError: print("please enter a valid hex string") return None k = secrets.randbelow(p) kp = secrets.randbelow(p) s = secrets.randbelow(p) target = b"pleasepleasepleasepleasepleasepl" print("Poly1305 is hard to understand so I decided to try simplifying it myself! Its parameters and stuff were probably just fluff right?") print("Anyways it should be secure but if you can prove me wrong I'll give you a little something special :)") print() print("First I'll let you sign an arbitrary message") while (msg1 := hexinput("message to sign (hex): ")) is None: pass if len(msg1) == 0: print("message must be nonempty") sys.exit(1) elif msg1 == target: print("nice try :)") sys.exit(1) if len(msg1) % 16 != 0: mac = auth(s, kp, pad(msg1)) else: mac = auth(s, k, msg1) print("authentication tag:", mac.hex()) print() print("Now I just *might* give you the flag if you convince me my authenticator is insecure. Give me a valid tag and I'll give you the flag.") while (tag := hexinput("enter verification tag (hex): ")) is None: pass if ver(s, k, target, tag): print("oh you did it...here's your flag I guess") with open("flag") as f: print(f.read()) else: print("invalid authentication tag")
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/BSidesNoida/2021/crypto/Damn_Boi/damn_boi.py
ctfs/BSidesNoida/2021/crypto/Damn_Boi/damn_boi.py
#!/usr/bin/env python3 from Crypto.Util.number import * from random import shuffle from math import lcm, prod from topsecrets import FLAG, FLAG_parts from gmpy2 import next_prime BITS = 512 FLAGINT = bytes_to_long(FLAG.encode()) assert FLAGINT == prod(FLAG_parts) def pm(n): r = 1 a = 2 for i in range(n): r *= a a = next_prime(a) return r def primegen(bits): e = 65537 M = pm(40) while True: a = getPrime(128) b = getPrime(128) p = pow(e, a, M) q = pow(e, b, M) if isPrime(p) and isPrime(q): print(a,b) return int(p), int(q) def keygen(bits, s): p,q = primegen(bits) n = p*q N = n**(s+1) print(f"{p=}") print(f"{q=}") d = lcm(p-1, q-1) x = getRandomRange(2, n-1) j = getRandomRange(2, n-1) while GCD(j, n) != 1: j = getRandomRange(2, n-1) g = pow(n+1, j, N)*x % N pub = (n,g,s) priv = (n,d) return pub, priv def encrypt(m, pub): n, g, s = pub N = n**(s+1) r = getRandomRange(2, n-1) c = pow(g, m, N) * pow(r, n**s, N) % N return c def encryptor(m, pub): n, g, s = pub N = n**(s+1) noise = [getRandomRange(2, N-1) for _ in range(len(FLAG_parts))] shuffle(FLAG_parts) enc = [] for f, r in zip(FLAG_parts, noise): c = encrypt(f*r, pub) enc.append(c) shuffle(noise) return enc, noise if __name__ == '__main__': pub, priv = keygen(BITS, 2) enc, noise = encryptor(FLAGINT, pub) with open('priv.txt', 'w') as out: out.write(f"{priv = }\n\n") with open('out.txt', 'w') as out: out.write(f"{pub = }\n\n") out.write(f"{enc = }\n\n") out.write(f"{noise = }")
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/BSidesNoida/2021/crypto/baby_crypto/babycrypto.py
ctfs/BSidesNoida/2021/crypto/baby_crypto/babycrypto.py
from functools import reduce from operator import mul from secrets import token_bytes from sys import exit from Crypto.Util.number import bytes_to_long, getPrime, long_to_bytes def main(): a = getPrime(512) b = reduce(mul, [getPrime(64) for _ in range(12)]) flag = open("flag.txt", 'rb').read() flag_int = bytes_to_long(flag + token_bytes(20)) if flag_int > b: print("this was not supposed to happen") exit() print("Try decrypting this =>", pow(flag_int, a, b)) print("Hint =>", a) print("Thanks for helping me test this out,") print("Now try to break it") for _ in range(2): inp = int(input(">>> ")) if inp % b in [0, 1, b - 1]: print("No cheating >:(") exit() res = pow(flag_int, inp * a, b) print(res) if res == 1: print(flag) if __name__ == "__main__": try: main() except Exception: print("oopsie")
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/BSidesNoida/2021/crypto/MACAW/MACAW.py
ctfs/BSidesNoida/2021/crypto/MACAW/MACAW.py
#!/usr/bin/env python3 from topsecrets import iv, key, secret_msg, secret_tag, FLAG from Crypto.Cipher import AES iv = bytes.fromhex(iv) menu = """ /===== MENU =====\\ | | | [M] MAC Gen | | [A] AUTH | | | \================/ """ def MAC(data): assert len(data) % 16 == 0, "Invalid Input" assert data != secret_msg, "Not Allowed!!!" cipher = AES.new(key, AES.MODE_CBC, iv) tag = cipher.encrypt(data)[-16:] return tag.hex() def AUTH(tag): if tag == secret_tag: print("[-] Successfully Verified!\n[-] Details:", FLAG) else: print("[-] Verification Flaied !!!") if __name__ == "__main__": print(secret_msg) try: for _ in range(3): print(menu) ch = input("[?] Choice: ").strip().upper() if ch == 'M': data = input("[+] Enter plaintext(hex): ").strip() tag = MAC(bytes.fromhex(data)) print("[-] Generated tag:", tag) print("[-] iv:", iv.hex()) elif ch == 'A': tag = input("[+] Enter your tag to verify: ").strip() AUTH(tag) else: print("[!] Invalid Choice") exit() except Exception as e: print(":( Oops!", e) print("Terminating Session!")
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/BSidesNoida/2021/crypto/Kotf_returns/kotf_returns.py
ctfs/BSidesNoida/2021/crypto/Kotf_returns/kotf_returns.py
from hashlib import sha1 from random import * from sys import exit from os import urandom from Crypto.PublicKey import DSA from Crypto.Util.number import * rot = randint(2, 2**160 - 1) chop = getPrime(159) def message_hash(x): return bytes_to_long(sha1(x).digest()) def nonce(s, padding, i, q): return (pow(message_hash(s), rot, chop) + padding + i)%q def verify(r, s, m): if not (0 < r and r < q and 0 < s and s < q): return False w = pow(s, q - 2, q) u1 = (message_hash(m) * w) % q u2 = (r * w) % q v = ((pow(g, u1, p) * pow(y, u2, p)) % p) % q return v == r def pow_solve(): pow_nonce = urandom(4) print(f"Solve PoW for {pow_nonce.hex()}") inp = bytes.fromhex(input()) if sha1(pow_nonce + inp).hexdigest().endswith('000000'): print("Correct PoW. Continue") return True print("Incorrect PoW. Abort") return False try: if not pow_solve(): exit() L, N = 1024, 160 dsakey = DSA.generate(1024) p = dsakey.p q = dsakey.q h = randint(2, p - 2) # sanity check g = pow(h, (p - 1) // q, p) if g == 1: print("oopsie") exit(1) x = randint(1, q - 1) y = pow(g, x, p) print(f"<p={p}, q={q}, g={g}, y={y}>") pad = randint(1, 2**160) signed = [] for i in range(2): print("what would you like me to sign? in hex, please") m = bytes.fromhex(input()) if m == b'give flag' or m == b'give me all your money': print("haha nice try...") exit() if m in signed: print("i already signed that!") exit() signed.append(m) # nonce generation remains the same k = nonce(m, pad, i, q) if k < 1: exit() r = pow(g, k, p) % q if r == 0: exit() s = (pow(k, q - 2, q) * (message_hash(m) + x * r)) % q if s == 0: exit() # No hash leak for you this time print(f"<r={r}, s={s}>") print("ok im done for now. You visit the flag keeper...") print("for flag, you must bring me signed message for 'give flag'") r1 = int(input()) s1 = int(input()) if verify(r1, s1, b"give flag"): print(open("flag.txt").read()) else: print("Never gonna give you up") except: print("Never gonna let you down")
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/BSidesNoida/2021/crypto/prng/prng.py
ctfs/BSidesNoida/2021/crypto/prng/prng.py
from decimal import Decimal, getcontext from Crypto.Util.number import bytes_to_long, getRandomNBitInteger def is_valid_privkey(n): if n < 0: return False c = n * 4 // 3 d = c.bit_length() a = d >> 1 if d & 1: x = 1 << a y = (x + (n >> a)) >> 1 else: x = (3 << a) >> 2 y = (x + (c >> a)) >> 1 if x != y: x, y = y, (y + n // y) >> 1 while y < x: x, y = y, (y + n // y) >> 1 x = round(x) return all(i**2 != n for i in range(x - 1000, x + 1000)) def gen_secret_key(): while True: sec = getRandomNBitInteger(128) if is_valid_privkey(sec): return sec class PRNG: def __init__(self, key): getcontext().prec = 1000 self.secret_key = key self.state = [int(i) for i in str(Decimal(self.secret_key).sqrt()).split(".")[-1]] def encrypt(self, message): m = [int(i) for i in str(bytes_to_long(message))] s = self.state[:len(m)] self.state = self.state[len(m):] return "".join(hex(i^j)[-1] for i,j in zip(m, s)) if __name__ == "__main__": secret_key = gen_secret_key() rng = PRNG(key=secret_key) print(rng.encrypt(b'My cryptographic message.')) print(rng.encrypt(b"THIS_FLAG_IS_REDACTED_LMAO"))
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/BSidesNoida/2021/crypto/Xoro/xoro.py
ctfs/BSidesNoida/2021/crypto/Xoro/xoro.py
#!/usr/bin/env python3 import os FLAG = open('flag.txt','rb').read() def xor(a, b): return bytes([i^j for i,j in zip(a,b)]) def pad(text, size): return text*(size//len(text)) + text[:size%len(text)] def encrypt(data, key): keystream = pad(key, len(data)) encrypted = xor(keystream, data) return encrypted.hex() if __name__ == "__main__": print("\n===== WELCOME TO OUR ENCRYPTION SERVICE =====\n") try: key = os.urandom(32) pt = input('[plaintext (hex)]> ').strip() ct = encrypt(bytes.fromhex(pt) + FLAG, key) print("[ciphertext (hex)]>", ct) print("See ya ;)") except Exception as e: print(":( Oops!", e) print("Terminating Session!")
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/BSidesNoida/2021/crypto/low_power_crypto/low_power_crypto.py
ctfs/BSidesNoida/2021/crypto/low_power_crypto/low_power_crypto.py
from Crypto.Util.number import getRandomNBitInteger, isPrime # extended gcd def egcd(a, b): old_x, new_x = 1, 0 old_y, new_y = 0, 1 while a != 0: q, a, b = b // a, b % a, a new_x, old_x = old_x, new_x - q * old_x new_y, old_y = old_y, new_y - q * old_y return b, new_x, new_y # multiplicative modular inverse def modinv(a, m): g, x, _ = egcd(a % m, m) if g != 1: return None return x % m # a class to represent a point on elliptic curve class ec_point: def __init__(self, x, y, z=1): self.x = x self.y = y self.z = z def __repr__(self): if self.z == 0: return "<ORIGIN>" return f"<x={self.x}, y={self.y}>" # a class to init an elliptic curve class ec_curve: def __init__(self, p, r, a, b): self.p = p self.r = r self.a = a self.b = b assert isPrime(p) and isPrime(r) def __repr__(self): return f"elliptic curve y^2 = x^3 + {self.a}*x + {self.b} of order {self.r} over GF({self.p})" def is_origin(self, pt): return pt.z == 0 # elliptic curve addition def add(self, pt1, pt2): if self.is_origin(pt1): return pt2 if self.is_origin(pt2): return pt1 if (pt1.y + pt2.y) % self.p == 0 and pt1.x == pt2.x: return self.origin() if pt1.x == pt2.x and pt1.y == pt2.y: temp = (((3 * pt1.x * pt1.x) + self.a) * modinv(2 * pt1.y, self.p)) % self.p else: temp = ((pt2.y - pt1.y) * modinv(pt2.x - pt1.x, self.p)) % self.p x = (temp * temp - pt1.x - pt2.x) % self.p y = (temp * (pt1.x - x) - pt1.y) % self.p return self(x, y) # multiplication using double and add def multiply(self, n, pt): if n == 0: return self.origin() curr_mult = pt res = self.origin() while n > 0: if n & 1: res = self.add(res, curr_mult) curr_mult = self.add(curr_mult, curr_mult) n = n >> 1 return res # init a point on this curve # Usage: # curve = ec_curve(*params) # point = curve_name(x, y[, z]) def __call__(self, x, y, z=1): res = ec_point(x % self.p, y % self.p, z) return res @staticmethod def origin(): return ec_point(0, 1, 0) if __name__ == "__main__": p = 115792089210356248762697446949407573530086143415290314195533631308867097853951 r = 115792089210356248762697446949407573529996955224135760342422259061068512044369 a = 115792089210356248762697446949407573530086143415290314195533631308867097853948 b = 41058363725152142129326129780047268409114441015993725554835256314039467401291 curve = ec_curve(p=p, r=r, a=a, b=b) print(curve) multiplier = getRandomNBitInteger(250) print("Because I am soo confident, I'll even let you make multiple public keys") print("Send points to multiply, or send <0,0> to move on:") try: for _ in range(10): x = int(input(">>> x coord => ")) y = int(input(">>> y coord => ")) if x == 0 and y == 0: break print(curve.multiply(multiplier, curve(x, y))) guess = int(input("multiplier => ")) if guess == multiplier: print(open("flag.txt", "r").read()) else: print("Never gonna give you up") except: print("Never gonna let you down")
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/BSidesNoida/2021/crypto/Macaw_Revenge/macaw_revenge.py
ctfs/BSidesNoida/2021/crypto/Macaw_Revenge/macaw_revenge.py
#!/usr/bin/env python3 from Crypto.Cipher import AES import os with open('flag.txt') as f: FLAG = f.read() menu = """ /===== MENU =====\\ | | | [M] MAC Gen | | [A] AUTH | | | \================/ """ def MAC(data, check=False): assert len(data) % 16 == 0, "Invalid Input" if check: assert data != secret_msg, "Not Allowed!!!" cipher = AES.new(key, AES.MODE_CBC, iv) tag = cipher.encrypt(data)[-16:] return tag.hex() def AUTH(tag): if tag == secret_tag: print("[-] Successfully Verified!\n[-] Details:", FLAG) else: print("[-] Verification Flaied !!!") if __name__ == "__main__": iv = os.urandom(16) key = os.urandom(16) secret_msg = os.urandom(48) secret_tag = MAC(secret_msg) print(f"[+] Forbidden msg: {secret_msg.hex()}") try: for _ in range(3): print(menu) ch = input("[?] Choice: ").strip().upper() if ch == 'M': data = input("[+] Enter plaintext(hex): ").strip() tag = MAC(bytes.fromhex(data), check=True) print("[-] Generated tag:", tag) print("[-] iv:", iv.hex()) elif ch == 'A': tag = input("[+] Enter your tag to verify: ").strip() AUTH(tag) else: print("[!] Invalid Choice") exit() except Exception as e: print(":( Oops!", e) print("Terminating Session!")
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/Securinets/2021/Quals/crypto/Sign_it/app.py
ctfs/Securinets/2021/Quals/crypto/Sign_it/app.py
from Crypto.Util.number import inverse from Crypto.Random import random from fastecdsa.curve import Curve from fastecdsa.point import Point import hashlib import signal class Server(): def __init__(self, curve, G): self.G = G self.order = curve.q self.d = random.randrange(1 , self.order - 1) self.P = (self.d * self.G) def sign(self, msg): z = int( hashlib.sha256(msg.encode()).hexdigest(), 16) k = random.randrange(1, self.order - 1) r = (k * self.G).x % self.order s = (inverse(k, self.order) * (z + r * self.d)) % self.order return (r, s) def verify(self, msg, sig): r, s = sig s %= self.order r %= self.order if s == 0 or r == 0: return False z = int( hashlib.sha256(msg.encode()).hexdigest(), 16) s_inv = inverse(s, self.order) u1 = (z * s_inv) % self.order u2 = (r * s_inv) % self.order W = u1 * self.G + u2 * self.P return W.x == r signal.alarm(360) # S256 curve params p = 0x402969301d0ec23afaf7b6e98c8a6aebb286a58f525ec43b46752bfc466bc435 gx = 0x3aedc2917bdb427d67322a1daf1073df709a1e63ece00b01530511dcb1bae0d4 gy = 0x21cabf9609173616f5f50cb83e6a5673e4ea0facdc00d23572e5269632594f1d a = 0x2ad2f52f18597706566e62f304ae1fa48e4062ee8b7d5627d6f41ed24dd68b97 b = 0x2c173bd8b2197e923097541427dda65c1c41ed5652cba93c86a7d0658070c707 q = 0x402969301d0ec23afaf7b6e98c8a6aeb2f4b05d0bbb538c027395fa703234883 S256 = Curve("S256", p, a, b, q, gx, gy) PROOF = "Give me flag." print("Welcome to the ECDSA testing of our probably secure S256 Curve. First choose your own generator then try to sign this message '{}' to prove us wrong.\n".format(PROOF)) print("Choose your point (x y) : ") try: x = int(input("x : ")) y = int(input("y : ")) G = Point(x, y, curve=S256) S = Server(S256, G) sample = "No flags for you." print("Here's a sample signature: msg = '{}' , signature = {}".format(sample, S.sign(sample))) while True: msg = input("Message : ").strip() r = int(input("r : ")) s = int(input("s : ")) if S.verify(msg, (r, s)): print("Valid signature.") if msg == PROOF: from secret import flag print("Here you go : {}".format(flag)) exit() else: print("Invalid signature.") except Exception as e: print(e) exit()
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/Securinets/2021/Quals/crypto/Shilaformi/app.py
ctfs/Securinets/2021/Quals/crypto/Shilaformi/app.py
import signal from secret import flag from Crypto.Random import random from Crypto.Util.number import getPrime #Odds and evens (hand game) #https://en.wikipedia.org/wiki/Odds_and_evens_(hand_game) def pad(choice, n): return 2*random.randint(1, n//2 - 1) + choice def send(choice, n): choice = pad(choice, n) return pow(2, choice, n ) signal.alarm(360) print ("Let's play odds and evens! If I win you loose 5 times the amount of money you have bet! I choose odd.\n") WALLET = 10 while WALLET > 0: print("Your current wallet is {} $.\n".format(WALLET)) if WALLET > 133337: print("Wow, You've got filthy rich. Here's your flag: {}".format(flag)) exit() n = getPrime(1024)*getPrime(1024) print ("Public Modulus : {}\n".format(n)) bet = int(input("Place your bet : ")) assert bet <= WALLET and bet > 0 choice = random.randint(0, 5) print ("Here's my choice : {}\n".format(send(choice, n))) player = int(input("Shilaaafooooooormi: ")) assert player >= 0 and player < 6 if (choice + player ) & 1: print("You lose.") WALLET -= 5*bet else: print("You win.") WALLET += bet print("You got no money left in your wallet. Make sure to come back later!")
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/Securinets/2021/Quals/crypto/Special/app.py
ctfs/Securinets/2021/Quals/crypto/Special/app.py
from Crypto.Util.number import isPrime, bytes_to_long from secret import flag import random def get(r): while True: a = random.getrandbits(512) p = a**2 + r if isPrime(p) : return p m = bytes_to_long(flag) e = 65537 p, q = get(1337), get(1187) n = p*q c = pow(m, e, n) print ("Modulus : {}".format(n)) print ("Public exponent : {}".format(e)) print ("Ciphertext : {}".format(c)) """ Modulus : 9205101698706979739826801043045342787573860852370120009782047065091267165813818945944938567077767109795693195306758124184300669243481673570359620772491153042678478312809811432352262322016591328649959068333993409371541201650938826630256112619578125044564261211415732174900162604077497313177347706230511508892968172603494805342653386527679619380762253476920434736431368696225307809325876263469267138456334317623292049963916185087736277032965175422891773251267119088153064627668031982940139865703040003065759250189294830016815658342491949959721771171008624698225901660128808998889116825507743256985320474353400908203 Public exponent : 65537 Ciphertext : 7936922632477179427776336441674861485950589109838466370248848810603305227730610589646741819313897162184198914593449584513298801516246072184328924490958302064664202813944180474377318619755541891685799909623945111729243482919086734358170659346187530089396234296268433976153029353575494866263288471212406042845186256151549768916089844077364464961133610687655801313809083988904726871667971720011220619598069236604397523051054337851497256894302257378216064087800301371122182309897203436049352850483968349573626245496903689129366737214112517774597434631637719018819317503710042658242522690613437843118568709251604555104 """
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/Securinets/2021/Quals/crypto/MiTM/app.py
ctfs/Securinets/2021/Quals/crypto/MiTM/app.py
from Crypto.Util.number import long_to_bytes from Crypto.Util.Padding import pad from Crypto.Cipher import AES from secret import flag import hashlib, random, os import signal class DHx(): def __init__(self): self.g = 2 self.p = 0xf18d09115c60ea0e71137b1b35810d0c774f98faae5abcfa98d2e2924715278da4f2738fc5e3d077546373484585288f0637796f52b7584f9158e0f86557b320fe71558251c852e0992eb42028b9117adffa461d25c8ce5b949957abd2a217a011e2986f93e1aadb8c31e8fa787d2710683676f8be5eca76b1badba33f601f45 self.private = random.randint(1, self.p-1) self.secret = None def getPublicKey(self): return pow(self.g, self.private, self.p) def share(self, x : int): assert x > 1 and x < self.p return pow(x, self.private, self.p) def getSharedSecret(self, x : int): assert x > 1 and x < self.p self.secret = pow(x, self.private, self.p) def getFingerprint(self): return hashlib.sha256(long_to_bytes(self.secret)).hexdigest() def checkFingerprint(self, h1 : str, h2 : str ): return h1 == h2 == self.getFingerprint() def encryptFlag(self): iv = os.urandom(16) key = hashlib.sha1(long_to_bytes(self.secret)).digest()[:16] return iv.hex() + AES.new(key, AES.MODE_CBC, iv).encrypt(pad(flag, 16)).hex() signal.alarm(60) Alice = DHx() Bob = DHx() Carol = DHx() A = Alice.getPublicKey() print("Alice sends to Bob: {}".format(A)) A = int(input("Forward to Bob: ")) B = Bob.share(A) print("Bob sends to Carol: {}".format(B)) B = int(input("Forward to Carol: ")) Carol.getSharedSecret(B) B = Bob.getPublicKey() print("Bob sends to Carol: {}".format(B)) B = int(input("Forward to Carol: ")) C = Carol.share(B) print("Carol sends to Alice: {}".format(C)) C = int(input("Forward to Alice: ")) Alice.getSharedSecret(C) C = Carol.getPublicKey() print("Carol sends to Alice: {}".format(C)) C = int(input("Forward to Alice: ")) A = Alice.share(C) print("Alice sends to Bob: {}".format(A)) A = int(input("Forward to Bob: ")) Bob.getSharedSecret(A) print ("Alice says: ") if (Alice.checkFingerprint(Carol.getFingerprint(), Bob.getFingerprint())): print (Alice.encryptFlag()) else: print ("ABORT MISSION! Walls have ears; Be careful what you say as people may be eavesdropping.")
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/Securinets/2021/Quals/crypto/MiTM_Revenge/app.py
ctfs/Securinets/2021/Quals/crypto/MiTM_Revenge/app.py
from Crypto.Util.number import long_to_bytes from Crypto.Util.Padding import pad from Crypto.Cipher import AES from secret import flag import hashlib, random, os import signal class DHx(): def __init__(self): self.g = 2 self.p = 0xf18d09115c60ea0e71137b1b35810d0c774f98faae5abcfa98d2e2924715278da4f2738fc5e3d077546373484585288f0637796f52b7584f9158e0f86557b320fe71558251c852e0992eb42028b9117adffa461d25c8ce5b949957abd2a217a011e2986f93e1aadb8c31e8fa787d2710683676f8be5eca76b1badba33f601f45 self.private = random.randint(1, self.p-1) self.nonce = random.randint(1, self.p-1) self.secret = None def getPublicKey(self): return pow(self.g, self.private, self.p) def share(self, x : int): assert x > 1 and x < self.p return pow(x, self.private, self.p) def getSharedSecret(self, x : int, nonce : int): assert x > 1 and x < self.p self.secret = pow(x, self.private, self.p) ^ nonce def getFingerprint(self): return hashlib.sha256(long_to_bytes(self.secret)).hexdigest() def checkFingerprint(self, h1 : str, h2 : str ): return h1 == h2 == self.getFingerprint() def encryptFlag(self): iv = os.urandom(16) key = hashlib.sha1(long_to_bytes(self.secret)).digest()[:16] return iv.hex() + AES.new(key, AES.MODE_CBC, iv).encrypt(pad(flag, 16)).hex() signal.alarm(120) Alice = DHx() Bob = DHx() Carol = DHx() A = Alice.getPublicKey() print("Alice sends to Bob: {}".format(A)) B = Bob.share(A) print("Bob sends to Carol: {}".format((B, Bob.nonce))) Carol.getSharedSecret(B, Bob.nonce) B = Bob.getPublicKey() print("Bob sends to Carol: {}".format(B)) B = int(input("Forward to Carol: ")) C = Carol.share(B) print("Carol sends to Alice: {}".format((C, Carol.nonce))) data = input("Forward to Alice: ").strip().split() C , Carol.nonce = int(data[0]), int(data[1]) Alice.getSharedSecret(C, Carol.nonce) C = Carol.getPublicKey() print("Carol sends to Alice: {}".format(C)) C = int(input("Forward to Alice: ")) A = Alice.share(C) print("Alice sends to Bob: {}".format(A)) data = input("Forward to Bob: ").strip().split() A , Alice.nonce = int(data[0]), int(data[1]) Bob.getSharedSecret(A, Alice.nonce) print ("Alice says: ") if (Alice.checkFingerprint(Carol.getFingerprint(), Bob.getFingerprint())): print (Alice.encryptFlag()) else: print ("ABORT MISSION! Walls have ears; Be careful what you say as people may be eavesdropping.")
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/Securinets/2021/Quals/web/Mixed/api/config.py
ctfs/Securinets/2021/Quals/web/Mixed/api/config.py
key='None'
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/Securinets/2021/Quals/web/Mixed/api/app.py
ctfs/Securinets/2021/Quals/web/Mixed/api/app.py
from flask import Flask, render_template, request import random import sqlite3 as sql import binascii import json import base64 from Crypto.Cipher import AES import config def my_decrypt(data, passphrase): try: unpad = lambda s : s[:-s[-1]] key = binascii.unhexlify(passphrase) encrypted = json.loads(base64.b64decode(data).decode('ascii')) encrypted_data = base64.b64decode(encrypted['data']) iv = base64.b64decode(encrypted['iv']) cipher = AES.new(key, AES.MODE_CBC, iv) decrypted = cipher.decrypt(encrypted_data) clean = unpad(decrypted).decode('ascii').rstrip() except Exception as e: print("Cannot decrypt datas...") print(e) exit(1) return clean app = Flask(__name__) @app.route('/add_note',methods = ['POST', 'GET']) def add_note(): if request.method == 'GET': try: msg="" username = request.args.get('username') cmt = request.args.get('comment') cook = request.cookies.get('cook') username1=my_decrypt(cook,config.key) if (username!=username1): msg='unauthorized' else: with sql.connect("db/db_notes.sqlite3") as con: cur = con.cursor() id = random.randint(154877,404842) cur.execute("INSERT INTO notes (note_id,username,note) VALUES (?,?,?)",(id,username,cmt) ) con.commit() msg = "Record successfully added / note id -> "+str(id) except: con.rollback() msg = "error in insert operation" finally: return msg con.close() @app.route('/get_note',methods = ['POST', 'GET']) def get_note(): if request.method == 'GET': try: con = sql.connect("db/db_notes.sqlite3") con.row_factory = sql.Row username = request.args.get('username') id = request.args.get('id') cook = request.cookies.get('cook') username1=my_decrypt(cook,config.key) if (username!=username1): msg='unauthorized' else: cur = con.cursor() cur.execute("select note from notes where note_id=?",(id,)) rows = cur.fetchone()[0] msg=rows except: con.rollback() msg = "error " finally: return msg con.close() if __name__ == '__main__': app.run(debug = True)
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/Securinets/2021/Quals/web/Warmup/utils.py
ctfs/Securinets/2021/Quals/web/Warmup/utils.py
import urllib import sys import urlparse import os import time import types import shutil from string import joinfields, split, lower from xml.dom import minidom domimpl = minidom.getDOMImplementation() BUFFER_SIZE = 128 * 1000 class Resource(object): # XXX this class is ugly def __init__(self, fp, file_size): self.__fp = fp self.__file_size = file_size def __len__(self): return self.__file_size def __iter__(self): while 1: data = self.__fp.read(BUFFER_SIZE) if not data: break yield data time.sleep(0.005) self.__fp.close() def read(self, length = 0): if length == 0: length = self.__file_size data = self.__fp.read(length) return data class FilesystemHandler(): def __init__(self, directory, uri, verbose=False): self.setDirectory(directory) self.setBaseURI(uri) self.verbose = verbose def setDirectory(self, path): if not os.path.isdir(path): raise Exception, '%s must be a directory!' % path self.directory = os.path.normpath(path) def setBaseURI(self, uri): if uri: self.baseuri = uri else: self.baseuri = '/' def uri2local(self,uri): path = os.path.normpath(uri) + '/' if path.startswith(self.baseuri): path = path[len(self.baseuri):] filepath = os.path.join(self.directory, path) filepath = os.path.normpath(filepath) return filepath def local2uri(self,filepath): """ map local path to file to self.baseuri """ filepath = os.path.normpath(filepath) if filepath.startswith(self.directory): uri = filepath[len(self.directory):] uri = os.path.normpath(self.baseuri + uri) #print('local2uri: %s -> %s' % (filepath, uri)) return uri def get_children(self, uri, filter=None): """ return the child objects as self.baseuris for the given URI """ fileloc=self.uri2local(uri) filelist=[] if os.path.exists(fileloc): if os.path.isdir(fileloc): try: files=os.listdir(fileloc) except Exception: raise ValueError for file in files: newloc=os.path.join(fileloc,file) filelist.append(self.local2uri(newloc)) return filelist def get_data(self,uri, range = None): """ return the content of an object """ path=self.uri2local(uri) if os.path.exists(path): if os.path.isfile(path): file_size = os.path.getsize(path) if range == None: fp=open(path,"r") return Resource(fp, file_size) else: if range[1] == '': range[1] = file_size else: range[1] = int(range[1]) if range[0] == '': range[0] = file_size - range[1] else: range[0] = int(range[0]) if range[0] > file_size: return 416 if range[1] > file_size: range[1] = file_size fp = open(path, "r") fp.seek(range[0]) return Resource(fp, range[1] - range[0]) elif os.path.isdir(path): # GET for collections is defined as 'return s/th meaningful' :-) from StringIO import StringIO stio = StringIO('Directory at %s' % uri) return Resource(StringIO('Directory at %s' % uri), stio.len) else: pass # also raise an error for collections # don't know what should happen then.. return 404 def put(self, uri, data, content_type=None): """ put the object into the filesystem """ path=self.uri2local(uri) try: fp=open(path, "w+") if isinstance(data, types.GeneratorType): for d in data: fp.write(d) else: if data: fp.write(data) fp.close() status = 201 except: status = 424 return status def mkcol(self,uri): """ create a new collection """ path=self.uri2local(uri) # remove trailing slash if path[-1]=="/": path=path[:-1] # test if file already exists if os.path.exists(path): return 405 # test if parent exists h,t=os.path.split(path) if not os.path.exists(h): return 409 # test, if we are allowed to create it try: os.mkdir(path) return 201 # No space left except IOError: return 507 except: return 403 def parse_propfind(xml_doc): """ Parse an propfind xml file and return a list of props """ doc = minidom.parseString(xml_doc) request_type=None props={} namespaces=[] if doc.getElementsByTagNameNS("DAV:", "allprop"): request_type = "RT_ALLPROP" elif doc.getElementsByTagNameNS("DAV:", "propname"): request_type = "RT_PROPNAME" else: request_type = "RT_PROP" for i in doc.getElementsByTagNameNS("DAV:", "prop"): for e in i.childNodes: if e.nodeType != minidom.Node.ELEMENT_NODE: continue ns = e.namespaceURI ename = e.localName if props.has_key(ns): props[ns].append(ename) else: props[ns]=[ename] namespaces.append(ns) return request_type, props, namespaces class PropfindProcessor: """ parse a propfind xml element and extract props It will set the following instance vars: request_class : ALLPROP | PROPNAME | PROP proplist : list of properties nsmap : map of namespaces The list of properties will contain tuples of the form (element name, ns_prefix, ns_uri) """ def __init__(self, uri, dataclass, depth, body): self.request_type = None self.nsmap = {} self.proplist = {} self.default_ns = None self._depth = str(depth) self._uri = uri.rstrip('/') self._has_body = None # did we parse a body? self._dataclass = dataclass if body: self.request_type, self.proplist, self.namespaces = \ parse_propfind(body) self._has_body = True def create_response(self): """ Create the multistatus response This will be delegated to the specific method depending on which request (allprop, propname, prop) was found. If we get a PROPNAME then we simply return the list with empty values which we get from the interface class If we get an ALLPROP we first get the list of properties and then we do the same as with a PROP method. """ # check if resource exists localpath = self._dataclass.uri2local(self._uri) if not os.path.exists(localpath): raise IOError if self.request_type == 2: # propname df = self.create_propname() elif self.request_type == 3: # prop df = self.create_prop() else: # allprop df = self.create_allprop() return df def get_propnames(self): """ return the property names allowed """ # defined properties ; format is namespace: [list of properties] return { "DAV:" : ('creationdate', #'displayname', #'getcontentlanguage', 'getcontentlength', #'getcontenttype', #'getetag', 'getlastmodified', #'lockdiscovery', 'resourcetype', #'source', #'supportedlock' ) } def get_prop(self, path, ns, propname): """ return the value of a given property uri -- uri of the object to get the property of ns -- namespace of the property pname -- name of the property """ info = os.stat(path) if propname == 'creationdate': response = info[9] elif propname == 'getlastmodified': response = info[8] elif propname == 'getcontentlength': response = '0' if not os.path.isfile(path) else str(info[6]) elif propname == 'resourcetype': response = int(os.path.isfile(path)) return str(response) def create_propname(self): """ create a multistatus response for the prop names """ dc = self._dataclass # create the document generator doc = domimpl.createDocument(None, "multistatus", None) ms = doc.documentElement ms.setAttribute("xmlns:D", "DAV:") ms.tagName = 'D:multistatus' if self._depth == "0": pnames = self.get_propnames() re = self.mk_propname_response(self._uri, pnames, doc) ms.appendChild(re) elif self._depth == "1": pnames = self.get_propnames() re = self.mk_propname_response(self._uri, pnames, doc) ms.appendChild(re) for newuri in dc.get_children(self._uri): pnames = self.get_propnames() re = self.mk_propname_response(newuri, pnames, doc) ms.appendChild(re) else: uri_list = [self._uri] while uri_list: uri = uri_list.pop() pnames = self.get_propnames() re = self.mk_propname_response(uri, pnames, doc) ms.appendChild(re) uri_childs = self._dataclass.get_children(uri) if uri_childs: uri_list.extend(uri_childs) return doc.toxml(encoding="utf-8") def create_allprop(self): """ return a list of all properties """ self.proplist = {} self.namespaces = [] for ns, plist in self.get_propnames().items(): self.proplist[ns] = plist self.namespaces.append(ns) return self.create_prop() def create_prop(self): """ handle a <prop> request This will 1. set up the <multistatus>-Framework 2. read the property values for each URI (which is dependant on the Depth header) This is done by the get_propvalues() method. 3. For each URI call the append_result() method to append the actual <result>-Tag to the result document. We differ between "good" properties, which have been assigned a value by the interface class and "bad" properties, which resulted in an error, either 404 (Not Found) or 403 (Forbidden). """ # create the document generator doc = domimpl.createDocument(None, "multistatus", None) ms = doc.documentElement ms.setAttribute("xmlns:D", "DAV:") ms.tagName = 'D:multistatus' if self._depth == "0": gp, bp = self.get_propvalues(self._uri) res = self.mk_prop_response(self._uri, gp, bp, doc) ms.appendChild(res) elif self._depth == "1": gp, bp = self.get_propvalues(self._uri) res = self.mk_prop_response(self._uri, gp, bp, doc) ms.appendChild(res) for newuri in self._dataclass.get_children(self._uri): gp, bp = self.get_propvalues(newuri) res = self.mk_prop_response(newuri, gp, bp, doc) ms.appendChild(res) elif self._depth == 'infinity': uri_list = [self._uri] while uri_list: uri = uri_list.pop() gp, bp = self.get_propvalues(uri) res = self.mk_prop_response(uri, gp, bp, doc) ms.appendChild(res) uri_childs = self._dataclass.get_children(uri) if uri_childs: uri_list.extend(uri_childs) return doc.toxml(encoding="utf-8") def mk_propname_response(self, uri, propnames, doc): """ make a new <prop> result element for a PROPNAME request This will simply format the propnames list. propnames should have the format {NS1 : [prop1, prop2, ...], NS2: ...} """ re = doc.createElement("D:response") if self._dataclass.baseuri: uri = self._dataclass.baseuri + '/' + '/'.join(uri.split('/')[3:]) # write href information uparts = urlparse.urlparse(uri) fileloc = uparts[2] href = doc.createElement("D:href") huri = doc.createTextNode(uparts[0] + '://' + '/'.join(uparts[1:2]) + urllib.quote(fileloc)) href.appendChild(huri) re.appendChild(href) ps = doc.createElement("D:propstat") nsnum = 0 for ns, plist in propnames.items(): # write prop element pr = doc.createElement("D:prop") nsp = "ns" + str(nsnum) pr.setAttribute("xmlns:" + nsp, ns) nsnum += 1 # write propertynames for p in plist: pe = doc.createElement(nsp + ":" + p) pr.appendChild(pe) ps.appendChild(pr) re.appendChild(ps) return re def mk_prop_response(self, uri, good_props, bad_props, doc): """ make a new <prop> result element We differ between the good props and the bad ones for each generating an extra <propstat>-Node (for each error one, that means). """ re = doc.createElement("D:response") # append namespaces to response nsnum = 0 for nsname in self.namespaces: if nsname != 'DAV:': re.setAttribute("xmlns:ns" + str(nsnum), nsname) nsnum += 1 if self._dataclass.baseuri: uri = urlparse.urljoin(self._dataclass.baseuri, uri) # write href information uparts = urlparse.urlparse(uri) fileloc = uparts[2] href = doc.createElement("D:href") huri = doc.createTextNode(uparts[0] + '://' + '/'.join(uparts[1:2]) + urllib.quote(fileloc)) href.appendChild(huri) re.appendChild(href) # write good properties ps = doc.createElement("D:propstat") if good_props: re.appendChild(ps) gp = doc.createElement("D:prop") for ns in good_props.keys(): if ns != 'DAV:': ns_prefix = "ns" + str(self.namespaces.index(ns)) + ":" else: ns_prefix = 'D:' for p, v in good_props[ns].items(): pe = doc.createElement(ns_prefix + str(p)) if isinstance(v, minidom.Element): pe.appendChild(v) elif isinstance(v, list): for val in v: pe.appendChild(val) else: if p == "resourcetype": if v == 1: ve = doc.createElement("D:collection") pe.appendChild(ve) else: ve = doc.createTextNode(v) pe.appendChild(ve) gp.appendChild(pe) ps.appendChild(gp) s = doc.createElement("D:status") t = doc.createTextNode("HTTP/1.1 200 OK") s.appendChild(t) ps.appendChild(s) re.appendChild(ps) # now write the errors! if len(bad_props.items()): # write a propstat for each error code for ecode in bad_props.keys(): ps = doc.createElement("D:propstat") re.appendChild(ps) bp = doc.createElement("D:prop") ps.appendChild(bp) for ns in bad_props[ecode].keys(): if ns != 'DAV:': ns_prefix = "ns" + str(self.namespaces.index(ns)) + ":" else: ns_prefix = 'D:' for p in bad_props[ecode][ns]: pe = doc.createElement(ns_prefix + str(p)) bp.appendChild(pe) s = doc.createElement("D:status") t = doc.createTextNode("HTTP/1.1 %s" % (ecode)) s.appendChild(t) ps.appendChild(s) re.appendChild(ps) # return the new response element return re def get_propvalues(self, uri): """ create lists of property values for an URI We create two lists for an URI: the properties for which we found a value and the ones for which we only got an error, either because they haven't been found or the user is not allowed to read them. """ good_props = {} bad_props = {} path = self._dataclass.uri2local(uri) ddc = self._dataclass for ns, plist in self.proplist.items(): good_props[ns] = {} for prop in plist: ec = 0 try: r = self.get_prop(path, ns, prop) good_props[ns][prop] = r except UnboundLocalError, error_code: ec = error_code[0] # ignore props with error_code if 0 (invisible) if ec == 0: continue if ec in bad_props: if ns in bad_props[ec]: bad_props[ec][ns].append(prop) else: bad_props[ec][ns] = [prop] else: bad_props[ec] = {ns: [prop]} return good_props, bad_props
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/Securinets/2021/Quals/web/Warmup/app.py
ctfs/Securinets/2021/Quals/web/Warmup/app.py
from itsdangerous import Signer, base64_encode, base64_decode from flask import Flask, request, render_template, make_response, g, Response from flask.views import MethodView import urlparse import shutil import utils import os import mimetypes app = Flask(__name__.split('.')[0]) app.config.from_object(__name__) BUFFER_SIZE = 128000 URI_BEGINNING_PATH = { 'authorization': '/login/', 'weeb': '/weeb/wtf/', } def generate_key(): app.secret_key = os.urandom(24) def generate_cookie_info(origin=None): if not origin: origin = request.headers.get('Origin') useragent = request.headers.get('User-Agent') return '%s %s' % (str(origin), str(useragent)) def verify_cookie(cookey): is_correct = False cookie_value = request.cookies.get(cookey) if cookie_value: s = Signer(app.secret_key) expected_cookie_content = \ generate_cookie_info(base64_decode(cookey)) expected_cookie_content = s.get_signature(expected_cookie_content) if expected_cookie_content == cookie_value: is_correct = True return is_correct def is_authorized(): origin = request.headers.get('Origin') if origin is None: return True return verify_cookie(base64_encode(origin)) @app.before_request def before_request(): headers = {} headers['Access-Control-Max-Age'] = '3600' headers['Access-Control-Allow-Credentials'] = 'true' headers['Access-Control-Allow-Headers'] = \ 'Origin, Accept, Accept-Encoding, Content-Length, ' + \ 'Content-Type, Authorization, Depth, If-Modified-Since, '+ \ 'If-None-Match' headers['Access-Control-Expose-Headers'] = \ 'Content-Type, Last-Modified, WWW-Authenticate' origin = request.headers.get('Origin') headers['Access-Control-Allow-Origin'] = origin specific_header = request.headers.get('Access-Control-Request-Headers') if is_authorized(): status_code = 200 elif request.method == 'OPTIONS' and specific_header: headers['Access-Control-Request-Headers'] = specific_header headers['Access-Control-Allow-Methods'] = ', '.join(['GET', 'PUT', 'PROPFIND', 'DELETE','COPY', 'MOVE', 'OPTIONS']) response = make_response('', 200, headers) return response else: s = Signer(app.secret_key) headers['WWW-Authenticate'] = 'Nayookie login_url=' + \ urlparse.urljoin(request.url_root, URI_BEGINNING_PATH['authorization']) + '?sig=' + \ s.get_signature(origin) + '{&back_url,origin}' response = make_response('', 401, headers) return response g.status = status_code g.headers = headers class weeb(MethodView): methods = ['GET', 'PUT', 'PROPFIND', 'DELETE','COPY', 'MOVE', 'OPTIONS'] def __init__(self): self.baseuri = URI_BEGINNING_PATH['weeb'] def get_body(self): request_data = request.data try: length = int(request.headers.get('Content-length')) except ValueError: length = 0 if not request_data and length: try: request_data = request.form.items()[0][0] except IndexError: request_data = None return request_data def get(self, pathname): status = g.status headers = g.headers status = 501 return make_response('', status, headers) def put(self, pathname): status = g.status headers = g.headers status = 501 return make_response('', status, headers) def propfind(self, pathname): status = g.status headers = g.headers pf = utils.PropfindProcessor( URI_BEGINNING_PATH['weeb'] + pathname, app.fs_handler, request.headers.get('Depth', 'infinity'), self.get_body()) try: response = make_response(pf.create_response() + '\n', status, headers) except IOError, e: response = make_response('Not found', 404, headers) return response def delete(self, pathname): status = g.status headers = g.headers status = 501 return make_response('', status, headers) def copy(self, pathname): status = g.status headers = g.headers status = 501 return make_response('', status, headers) def move(self, pathname): status = g.status headers = g.headers status = 501 return make_response('', status, headers) def options(self, pathname): return make_response('', g.status, g.headers) weeb_view = weeb.as_view('dav') app.add_url_rule( '/weeb/wtf/', defaults={'pathname': ''}, view_func=weeb_view ) app.add_url_rule( URI_BEGINNING_PATH['weeb'] + '<path:pathname>', view_func=weeb_view ) @app.route(URI_BEGINNING_PATH['authorization'], methods=['GET', 'POST']) def authorize(): origin = request.args.get('origin') if request.method == 'POST': response = make_response() if request.form.get('continue') != 'true': generate_key() s = Signer(app.secret_key) if s.get_signature(origin) == request.args.get('sig'): key = base64_encode(str(origin)) back = request.args.get('back_url') info = generate_cookie_info(origin=origin) response.set_cookie(key, value=s.get_signature(info), max_age=None, expires=None, path='/', domain=None, secure=True, httponly=True) else: return 'Something went wrong...' response.status = '301' # response.headers['Location'] = '/' if not back else back else: response = make_response(render_template('authorization_page.html', cookie_list=[ base64_decode(cookey) for cookey in request.cookies.keys() if verify_cookie(cookey) ], origin=request.args.get('origin'), back_url=request.args.get('back_url'))) return response if __name__ == '__main__': app.fs_path = '/app/' app.fs_handler = utils.FilesystemHandler(app.fs_path, URI_BEGINNING_PATH['weeb']) generate_key() app.run(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/Securinets/2023/Quals/crypto/PolyLCG/PolyLCG.py
ctfs/Securinets/2023/Quals/crypto/PolyLCG/PolyLCG.py
from random import randint xcoeff=[2220881165502059873403292638352563283672047788097000474246472547036149880673794935190953317495413822516051735501183996484673938426874803787946897055911986,3780868071235160215367199770952656972709510983146503211692869296836254519620768737356081836837102329626660962468333562050121427935761471039362287802941597,4902413424318450578332022710023815992030030940432088134156375736636296016273860394626141407089100644225364129305706233708267009976783719598126300552264686] ycoeff=[10133630993576627916260025550504106878405253409844193620608338129978685236278362029266353690006955194818074387390350472504283291952199370441443295790407675,3364000239596805500788439152587586988694473612770420810400457954622820421525205173981972752548906690775960238564395459369815397933405749174182967563999094, 5184466564604150683447715719961919989718796968566745874607480183961791804239357212974694797397047787503590843234526492414458478882622032364603797888695699] p=10369539704979520345376943788090457296701518777268113122376443474930073612795297691185597789473973789467303121639140064504782927997022419913721978857764263 class LCG: def __init__(self,p,xcoeffs,ycoeffs): self.p=p self.xcoeffs=xcoeffs self.ycoeffs=ycoeffs self.xstate =randint(1,p-1) self.ystate =randint(1,p-1) for i in range(randint(1,1337)): self.next() def next(self): self.xstate=pow(self.xcoeffs[0]+self.xcoeffs[1]*self.xstate+self.xcoeffs[2]*self.xstate**2,1,self.p) self.ystate=pow(self.ycoeffs[0]+self.ycoeffs[1]*self.ystate+self.ycoeffs[2]*self.ystate**2,1,self.p) def encrypt(self,msg): bin_msg=list(map(int, list(f"{msg:0512b}"))) encrypted=[] for i in bin_msg: self.next() if i==1: encrypted.append(self.xstate) else: encrypted.append(self.ystate) return encrypted flag=b"Securinets{???????????????????????????????????????}" flag=int.from_bytes(flag,"big") lcgCipher=LCG(p,xcoeff,ycoeff) encrypted_flag=lcgCipher.encrypt(flag) print("encrypted_flag=",encrypted_flag)
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/Securinets/2023/Quals/crypto/Farfour_Post_Quantom/Farfour_post_quantom.py
ctfs/Securinets/2023/Quals/crypto/Farfour_Post_Quantom/Farfour_post_quantom.py
from Crypto.Cipher import AES from Crypto.Util.Padding import pad import hashlib from os import urandom from random import SystemRandom from sympy import GF from sympy.polys.matrices import DomainMatrix import json from hashlib import md5 random=SystemRandom() shuffle=random.shuffle randint=random.randint randrange=random.randrange uniform = lambda: randrange(257//2) - 257//2 P=GF(257) secret=open("Secret.txt",'rb').read() assert len(secret)==16 flag=open("flag.txt","rb").read() def encrypt_flag(secret): key = hashlib.sha256(secret).digest()[-16:] iv = urandom(16) cipher = AES.new(key, AES.MODE_CBC, iv) enc_flag=cipher.encrypt(pad(flag,16)) return json.dumps({"encrypted_flag":enc_flag.hex(),"IV":iv.hex()}) def get_hint(vec,mat): res=(Pub_matrix*vec).to_Matrix() res=[int(res[i,0])%257 for i in range(16)] shuffle(res) return json.dumps({"hint":[i for i in res]}) def get_secret(secret,Secret_matrix): secret_vetor=DomainMatrix([[P(int(i))] for i in secret],(16,1),P) public_vector=(Secret_matrix*secret_vetor).to_Matrix() return json.dumps({"secret":[int(public_vector[i,0]) for i in range(16)]}) while True: g=randint(2,257) print(json.dumps({"G":int(g)})) Secret_matrix=[[uniform() for i in range(16)] for j in range(16)] Pub_matrix=DomainMatrix([[P((pow(g,randint(2,256),257))*i) for i in j] for j in Secret_matrix],(16,16),P) Secret_matrix=DomainMatrix(Secret_matrix,(16,16),P) # to make it easier for you <3 while True: try: choice=json.loads(input("Choose an option\n")) if("option" not in choice): print("You need to choose an option") elif choice["option"]=="get_flag": print(encrypt_flag(secret)) elif(choice["option"]=="get_hint") and "vector" in choice: assert len(choice["vector"])==16 vec=[[P(int(i))] for i in choice["vector"]] input_vector=DomainMatrix(vec,(16,1),P) print(get_hint(input_vector,Pub_matrix)) elif choice["option"]=="get_secret": print(get_secret(secret,Secret_matrix)) elif choice["option"]=="reset_connection": g=randint(2,257) print(json.dumps({"G":int(g)})) Secret_matrix=[[uniform() for i in range(16)] for j in range(16)] Pub_matrix=DomainMatrix([[P((pow(g,randint(2,256),257))*i) for i in j] for j in Secret_matrix],(16,16),P) Secret_matrix=DomainMatrix(Secret_matrix,(16,16),P) else: print("Nothing that we have Right now ") except: print("dont try something stupid") exit(1) break
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/Securinets/2023/Quals/crypto/TTsign/TTSign.py
ctfs/Securinets/2023/Quals/crypto/TTsign/TTSign.py
#!/usr/bin/env python3.10 from Crypto.Util.number import long_to_bytes, bytes_to_long, inverse from Crypto.Util import Counter from Crypto.Util.Padding import pad, unpad from Crypto.PublicKey import RSA from Crypto.Cipher import AES import os, sys, hashlib from random import randint import json from APTX import Server,Client rsa = RSA.generate(2048) print(""" /$$$$$$$$ /$$$$$$$$ /$$$$$$ /$$$$$$ /$$$$$$ /$$ /$$ |__ $$__/|__ $$__/ /$$__ $$|_ $$_/ /$$__ $$| $$$ | $$ | $$ | $$ | $$ \\__/ | $$ | $$ \\__/| $$$$| $$ | $$ | $$ | $$$$$$ | $$ | $$ /$$$$| $$ $$ $$ | $$ | $$ \\____ $$ | $$ | $$|_ $$| $$ $$$$ | $$ | $$ /$$ \\ $$ | $$ | $$ \\ $$| $$\\ $$$ | $$ | $$ | $$$$$$/ /$$$$$$| $$$$$$/| $$ \\ $$ |__/ |__/ \\______/ |______/ \\______/ |__/ \\__/ """) class TT_Sign: def __init__(self,client): self.key = os.urandom(16) self.client=client self.iv =os.urandom(16) self.nounce=os.urandom(16) self.msg=self._hash("Integrity is everything") def xor(self,x,y): return bytes([i^j for i,j in zip(x,y)]) def check_sum(self,param): ctr = Counter.new(128, initial_value=bytes_to_long(self.nounce)) enc_param=AES.new(self.key,AES.MODE_CTR,counter=ctr).encrypt(param) h_h=b"\x00"*16 for i in range(0,len(enc_param),16): h_h=bytes(self.xor(h_h,enc_param[i:i+16])) return h_h def _hash(self, data): return hashlib.sha512(data.encode()).hexdigest() def _parse_keys(self, params): lp = bytes_to_long(params[:2]) params = params[2:] p = bytes_to_long(params[:lp]) integrety_check1=params.index(b"U cant fool me")+1 params = params[integrety_check1+13:] lq = bytes_to_long(params[:2]) params = params[2:] q = bytes_to_long(params[:lq]) integrety_check2=params.index(b"Guess this one")+1 params = params[integrety_check2+13:] ld = bytes_to_long(params[:2]) params = params[2:] d = bytes_to_long(params[:ld]) return d, p, q,integrety_check1,integrety_check2 def _get_proof(self, ref): transfer,err=self.client.get_transfer_by_ref(ref) if transfer["sender"]!=self.client.username: return "\nYou can only sign your transaction\n" self.msg=f"ref:{transfer['ref']};from:{transfer['sender']};to:{transfer['receiver']};amount:{str(transfer['amount'])};label:{transfer['label']}" assert len(self.msg) < 256 s, enc_params = self._sign() return f"{s.hex()}|{enc_params.hex()}" def prepare_param(self,pad1=randint(24,42),pad2=randint(24,42)): d_bytes = long_to_bytes(rsa.d) p_bytes = long_to_bytes(rsa.p q_bytes = long_to_bytes(rsa.q) params = long_to_bytes(len(p_bytes), 2) + p_bytes+b"\x00"*pad1+b'U cant fool me' params += long_to_bytes(len(q_bytes), 2) + q_bytes+b"\x00"*pad2+b"Guess this one" params += long_to_bytes(len(d_bytes), 2) + d_bytes return params def _sign(self): h = int(self._hash(self.msg), 16) s = pow(h, rsa.d, rsa.n) self.nounce=os.urandom(16) params=self.prepare_param() params_padded=pad(params,16)+self.check_sum(pad(params,16)) enc_params = self.iv + AES.new(self.key, AES.MODE_CBC, self.iv).encrypt(params_padded) return long_to_bytes(s), enc_params def _create_transfer(self): receiver = str(input("Receiver: ")) amount = int(input("Amount: ")) label = str(input("Label: ")) ref ,err= self.client.set_transfer(receiver, amount, label) if len(err)==0: print(f"Here is your reference: {ref},sign it to finilize transaction here is your signature {self._get_proof(ref)}\n\n") else: print(err) def _sign_transfer(self): ref=str(input("ref")) proof = str(input("Proof: ")) s, enc_params = proof.split('|') s = int(s, 16) enc_params = bytes.fromhex(enc_params) if self._verify(self.msg, s,ref, enc_params): self.client.update_transfer(ref) else: print("Failed to sign the transaction !") def _verify(self, msg, s,ref, enc_params): transfer,err=self.client.get_transfer_by_ref(ref) if len(err)!=0: print("Transaction doesnt exist !") return False msg=f"ref:{transfer['ref']};from:{transfer['sender']};to:{transfer['receiver']};amount:{transfer['amount']};label:{transfer['label']}" h = int(self._hash(msg), 16) params = AES.new(self.key, AES.MODE_CBC, enc_params[:16]).decrypt(enc_params[16:]) sum=params[-16:] params=params[:-16] d, p, q,pad1,pad2 = self._parse_keys(params) if p!=rsa.p or q!=rsa.q and d!=rsa.d: print("Dont try to touch my precious parameters") return False padded_params=self.prepare_param(pad1,pad2) new_sum=self.check_sum(pad(padded_params,16)) if new_sum!=sum: print(f"Somedata go corrupted durring transfer {new_sum}") return False e = inverse(d, (p-1)*(q-1)) n = p*q m = pow(s, e, n) if m == h: return True else: print(f"\n[-] Invalid transfer : {long_to_bytes(m).hex()}\n\n") return False def main(): server = Server() print(f"~ Welcome to TT_Sign ~") print("\nPlease login.") username = str(input("Username: ")) password = str(input("Password: ")) if server.login(username, password): client=Client(username,password) tt_sign = TT_Sign(client) while True: print("1- Create Transfer\n2- Sign Transfer\n3- show info \n4- list Transfers\n") choice = str(input("> ")) if choice == '1': tt_sign._create_transfer() elif choice == '2': tt_sign._sign_transfer() elif choice == '3': tt_sign.client.show_info() elif choice =="4": tt_sign.client.list_transfers() elif choice =="5": tt_sign.client.list_clients() else: print("\n[-] Invalid Choice!\n\n") else: sys.exit() if __name__ == '__main__': main()
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/Securinets/2023/Quals/crypto/TTSign2/TTSign.py
ctfs/Securinets/2023/Quals/crypto/TTSign2/TTSign.py
#!/usr/bin/env python3.10 from Crypto.Util.number import long_to_bytes, bytes_to_long, inverse from Crypto.Util import Counter from Crypto.Util.Padding import pad, unpad from Crypto.PublicKey import RSA from Crypto.Cipher import AES import os, sys, hashlib from random import randint import json from APTX import Server,Client rsa = RSA.generate(2048) print(""" /$$$$$$$$ /$$$$$$$$ /$$$$$$ /$$$$$$ /$$$$$$ /$$ /$$ |__ $$__/|__ $$__/ /$$__ $$|_ $$_/ /$$__ $$| $$$ | $$ | $$ | $$ | $$ \\__/ | $$ | $$ \\__/| $$$$| $$ | $$ | $$ | $$$$$$ | $$ | $$ /$$$$| $$ $$ $$ | $$ | $$ \\____ $$ | $$ | $$|_ $$| $$ $$$$ | $$ | $$ /$$ \\ $$ | $$ | $$ \\ $$| $$\\ $$$ | $$ | $$ | $$$$$$/ /$$$$$$| $$$$$$/| $$ \\ $$ |__/ |__/ \\______/ |______/ \\______/ |__/ \\__/ """) class TT_Sign: def __init__(self,client): self.key = os.urandom(16) self.client=client self.iv =os.urandom(16) self.nounce=os.urandom(16) self.msg=self._hash("Integrity is everything") def xor(self,x,y): return bytes([i^j for i,j in zip(x,y)]) def check_sum(self,param): ctr = Counter.new(128, initial_value=bytes_to_long(self.nounce)) enc_param=AES.new(self.key,AES.MODE_CTR,counter=ctr).encrypt(param) h_h=b"\x00"*16 for i in range(0,len(enc_param),16): h_h=bytes(self.xor(h_h,enc_param[i:i+16])) return h_h def _hash(self, data): return hashlib.sha512(data.encode()).hexdigest() def _parse_keys(self, params): lp = bytes_to_long(params[:2]) params = params[2:] p = bytes_to_long(params[:lp]) params=params[lp:] integrety_check1=params.index(b"U cant fool me")+1 params = params[integrety_check1+13:] lq = bytes_to_long(params[:2]) params = params[2:] q = bytes_to_long(params[:lq]) params=params[lq:] integrety_check2=params.index(b"Guess this one")+1 params = params[integrety_check2+13:] ld = bytes_to_long(params[:2]) params = params[2:] d = bytes_to_long(params[:ld]) return d, p, q,integrety_check1-1,integrety_check2-1 def _get_proof(self, ref): transfer,err=self.client.get_transfer_by_ref(ref) if transfer["sender"]!=self.client.username: return "\nYou can only sign your transaction\n" self.msg=f"ref:{transfer['ref']};from:{transfer['sender']};to:{transfer['receiver']};amount:{str(transfer['amount'])};label:{transfer['label']}" assert len(self.msg) < 256 s, enc_params = self._sign() return f"{s.hex()}|{enc_params.hex()}" def prepare_param(self,pad1=randint(24,42),pad2=randint(24,42)): d_bytes = long_to_bytes(rsa.d) p_bytes = long_to_bytes(rsa.p) q_bytes = long_to_bytes(rsa.q) params = long_to_bytes(len(p_bytes), 2) + p_bytes+b"\x00"*pad1+b'U cant fool me' params += long_to_bytes(len(q_bytes), 2) + q_bytes+b"\x00"*pad2+b"Guess this one" params += long_to_bytes(len(d_bytes), 2) + d_bytes return params def _sign(self): h = int(self._hash(self.msg), 16) s = pow(h, rsa.d, rsa.n) self.nounce=os.urandom(16) params=self.prepare_param() params_padded=pad(params,16)+self.check_sum(pad(params,16)) enc_params = self.iv + AES.new(self.key, AES.MODE_CBC, self.iv).encrypt(params_padded) return long_to_bytes(s), enc_params def _create_transfer(self): receiver = str(input("Receiver: ")) amount = int(input("Amount: ")) label = str(input("Label: ")) ref ,err= self.client.set_transfer(receiver, amount, label) if len(err)==0: print(f"Here is your reference: {ref},sign it to finilize transaction here is your signature {self._get_proof(ref)}\n\n") else: print(err) def _sign_transfer(self): ref=str(input("ref: ")) proof = str(input("Proof: ")) s, enc_params = proof.split('|') s = int(s, 16) enc_params = bytes.fromhex(enc_params) if self._verify(self.msg, s,ref, enc_params): self.client.update_transfer(ref) else: print("Failed to sign the transaction !") def _verify(self, msg, s,ref, enc_params): transfer,err=self.client.get_transfer_by_ref(ref) if len(err)!=0: print("Transaction doesnt exist !") return False msg=f"ref:{transfer['ref']};from:{transfer['sender']};to:{transfer['receiver']};amount:{str(transfer['amount'])};label:{transfer['label']}" h = int(self._hash(msg), 16) params = AES.new(self.key, AES.MODE_CBC, enc_params[:16]).decrypt(enc_params[16:]) sum=params[-16:] params=params[:-16] d, p, q,pad1,pad2 = self._parse_keys(params) if p!=rsa.p or q!=rsa.q and d!=rsa.d: print("Dont try to touch my precious parameters") return False padded_params=self.prepare_param(pad1,pad2) new_sum=self.check_sum(pad(padded_params,16)) if new_sum!=sum: print(f"Somedata go corrupted durring transfer {new_sum}") return False e = inverse(d, (p-1)*(q-1)) n = p*q m = pow(s, e, n) if m == h: return True else: print(f"\n[-] Invalid transfer : {long_to_bytes(m).hex()}\n\n") return False def main(): server = Server() print(f"~ Welcome to TT_Sign ~") print("\nPlease login.") username = str(input("Username: ")) password = str(input("Password: ")) if server.login(username, password): client=Client(username,password) tt_sign = TT_Sign(client) while True: print("1- Create Transfer\n2- Sign Transfer\n3- show info \n4- list Transfers\n") choice = str(input("> ")) if choice == '1': tt_sign._create_transfer() elif choice == '2': tt_sign._sign_transfer() elif choice == '3': tt_sign.client.show_info() elif choice =="4": tt_sign.client.list_transfers() elif choice =="5": tt_sign.client.list_clients() else: print("\n[-] Invalid Choice!\n\n") else: sys.exit() if __name__ == '__main__': main()
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/Securinets/2023/Quals/crypto/DigestiveV2/DigestiveV2.py
ctfs/Securinets/2023/Quals/crypto/DigestiveV2/DigestiveV2.py
from fastecdsa.curve import P192 from fastecdsa.point import Point from secrets import randbelow,flag,banner,menu from Crypto.Util.number import bytes_to_long,inverse from string import ascii_uppercase import json #P192 Order O=6277101735386680763835789423176059013767194773182842284081 d=randbelow(O) G=Point(0x188da80eb03090f67cbf20eb43a18800f4ff0afd82ff1012, 0x07192b95ffc8da78631011ed6b24cdd573f977a11e794811,curve=P192) P=d*G def pub_hash(m): return (bytes_to_long(m.encode())%O)>>60 def ecdsa_sign(m): h = pub_hash(m) k = randbelow(O) r = (k * G).x % O s = (inverse(k, O) * (h + r * d)) % O return json.dumps({"r":r,"s":s}) def verify(msg,r,s): h=pub_hash(msg) if r > 0 and r < O and s > 0 and s < O: u1=(h*inverse(s,O))%O u2=(r*inverse(s,O))%O V=u1*G+u2*P if r==V.x: return True return False print(banner) print(menu) normal_user=["JAKC","YASSINE"] for i in range(2): try: choice=json.loads(input()) if "option" not in choice or "name" not in choice: print("Give me a option and a message next time") continue if choice["option"]=="sign": name=choice["name"] if any(i not in ascii_uppercase for i in name) or len(name)!=40: print("give me a strong and long name next time") normal_user.append(name) payload=json.dumps({"username":name,"admin":"false"}) print(ecdsa_sign(payload)) if choice["option"]=="verify_admin": if "r" not in choice or 's' not in choice : print("Remember to return with the admin signature next time") continue if choice["name"] in normal_user: print("Dont Try to cheat your way through!") continue payload=json.dumps({"username":choice["name"],"admin":"truee"}) if verify(payload,choice['r'],choice['s']): print("Welcome back admin",flag) else: print("You seemed to send something wrong try again") continue except: pass
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/Securinets/2023/Quals/web/Giancardi_Bank/accountant/job.py
ctfs/Securinets/2023/Quals/web/Giancardi_Bank/accountant/job.py
#!/usr/bin/env python3 import datetime import os import requests import signal from yaml import * signal.alarm(20) def verify_records(s): return "[+] I'm done, let me go home\n"+s pw = os.environ["ACCOUNTANT_PASSWORD"] auth_data = {"username": "MisterX", "password": pw} print("[+] Let me get into my office") sess = requests.Session() resp = sess.post( "http://bank:3000/login", data={"username": "MisterX", "password": pw}, headers={"Content-Type": "application/x-www-form-urlencoded"}, allow_redirects=False, ) sess.cookies.set("session_id", resp.cookies.get("session_id")) print("[+] Verifying old records, I am shocking with dust, Damn there are rats too !") resp = sess.get("http://bank:3000/transactions/report/info/all") print(resp.text) if len(resp.text)!=0: print("[-] I am not happy, I am not going to work today") reports = resp.text.split("|") for report in reports: try: report_id = report.split(":")[0] user_id = report.split(":")[1] print("[+] Interesting record here, ") res=sess.get( "http://bank:3000/transactions/report/gen/" + report_id + "?user_id=" + user_id ) if res.status_code == 200: loaded_yaml = load(res.text, Loader=Loader) print(verify_records(loaded_yaml)) except: print("[-] ~#! !!!! Oo $h/t the rats are eating the old records") resp = sess.get("http://bank:3000/users") print("[+] Got new reports for today hope not, let me do my work you shorty!") for user in resp.json(): try: resp = sess.get( "http://bank:3000/transactions/report/gen/1?user_id=" + str(user["ID"]) ) except: print("[+] a bit more ...") print(f"[{datetime.datetime.now()}] Accountant will be back soon.")
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/Securinets/2023/Quals/web/mark4archive/backend/analyze.py
ctfs/Securinets/2023/Quals/web/mark4archive/backend/analyze.py
import fnmatch import hashlib import hmac import pickle import random import os import re import shutil import zipfile from flask import Blueprint, request import requests from template import DUMMY_CodeQL_BODY, DUMMY_CodeQL_HEADER, BODY_CONTENT, SNIPPET from config.config import SECRET TMP_SECRET=SECRET if os.path.exists("config/config.py"): os.remove("config/config.py") analyze_bp = Blueprint('analyze', __name__) def func_format(dict): return DUMMY_CodeQL_BODY.format(**dict) def UnzipAndSave(url, repo_name, username, dir): response = requests.get(url) if response.status_code == 200: zip_hash = hashlib.sha256( str(response.content).encode('utf-8')).hexdigest() if not os.path.exists(dir): os.makedirs(dir) os.makedirs(f"{dir}/{zip_hash}") filename = f'{dir}/file_{repo_name}_{username}_{zip_hash}.zip' with open(filename, 'wb') as f: f.write(response.content) print('Zip file downloaded and saved to ' + filename) with zipfile.ZipFile(f'{filename}', 'r') as zip_ref: zip_ref.extractall(f"{dir}/{zip_hash}") os.remove(filename) return f"{dir}/{zip_hash}" else: print('Failed to download zip file') return None def shuffle_string(input_str): char_list = list(input_str) random.shuffle(char_list) shuffled_str = ''.join(char_list) return shuffled_str def check_input(data): username_regex = re.compile( r'^[a-zA-Z0-9](?:[a-zA-Z0-9]|-(?=[a-zA-Z0-9])){0,37}[a-zA-Z0-9]$') repo_regex = re.compile( r'^[a-zA-Z0-9](?:[a-zA-Z0-9]|-(?=[a-zA-Z0-9])){0,98}[a-zA-Z0-9]$') token_regex = re.compile(r'^[A-Z0-9]{29}$') branch_regex = re.compile(r'^[\w.-]{1,255}$') msg = 'valid' try: username = data['username'] repo_name = data['repo_name'] token = data['token'] branch = data['branch'] if not branch_regex.match(branch): msg = "invalid branch name", 400 if not token_regex.match(token): msg = "invalid token", 400 if not repo_regex.match(repo_name): msg = "invalid repo name", 400 if not username_regex.match(username): msg = "invalid username", 400 except: return "invalid data", 400 return msg, username, repo_name, token, branch def generateSig(data_bytes, key_bytes): signature = hmac.new(key_bytes, data_bytes, digestmod='sha256').hexdigest() return signature def create_signed_mark(path, data): try: with open(f"{path}/mark4archive", "xb") as f: pickled = pickle.dumps(data) f.write(pickled) signature = bytes(generateSig( pickled, TMP_SECRET), "utf-8") f.write(signature) return signature except Exception as e: print("error occured: ", e) @analyze_bp.route('/analyze', methods=['POST']) def analyze(): # Open your private repo, download the repo as a ZIP, from your browser go to DOWNDLOAD section and copy the link of the downloaded zip # example: https: // codeload.github.com/anas-cherni/thisisprivate/zip/refs/heads/main?token = ABMJT7F6YNPNCKMMBBIWO4DEHP6KG #token: ABMJT7F6YNPNCKMMBBIWO4DEHP6KG #repo_name: thisisprivate #username: anas-cherni #branch: main data = request.form isValid, username, repo_name, token, branch = check_input(data) if isValid != "valid": return isValid repo_url = f"https://api.github.com/repos/{username}/{repo_name}" repo_response = requests.get(repo_url) repo_data = repo_response.json() try: if not repo_data["private"]: return "Our policies don't allow us to analyze a public repo! please provide the one that you own", 400 except: print("This is either a private or doesn't exist") valid_url = f"https://codeload.github.com/{username}/{repo_name}/zip/refs/heads/{branch}?token={token}" # unzip and save in internal folder to check the content dir = UnzipAndSave(valid_url, repo_name, username, "/tmp") if not dir: return "failed to download the zip", 400 # check for a reserved file name, if it exists return an error for file in os.listdir(f"{dir}/{repo_name}-{branch}"): if fnmatch.fnmatch(file, "mark4archive"): return "mark4archive is reserved to our service, please choose another name for your file", 400 try: with open(f"{dir}/{repo_name}-{branch}/{file}", "rb") as f: first_two_bytes = f.read(2) if first_two_bytes == b'\x80\x04': return "This Beta version of the app can't handle this kind of files!", 400 except Exception as e: print("error: ", e) aux = dict(BODY_CONTENT[0]) aux["Snippet"] = aux["Snippet"].format(**{"Snippet":SNIPPET[list(SNIPPET.keys())[0]]}) result = DUMMY_CodeQL_HEADER.format(**{ "repo":repo_name, "branch":branch, "Id": "0", "File":"dummy", "Line":"12", }) + func_format(aux) # Delete the previously created folders internally shutil.rmtree(dir) # All checks done, relase to a public path user_access = UnzipAndSave( valid_url, repo_name, username, "public") sig = create_signed_mark(f"{user_access}/{repo_name}-{branch}", result) return "token: " +user_access.split("/")[1]
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/Securinets/2023/Quals/web/mark4archive/backend/report.py
ctfs/Securinets/2023/Quals/web/mark4archive/backend/report.py
import hmac import pickle from flask import Blueprint, Response, render_template, request import requests import re import os import random import string from analyze import TMP_SECRET SECRET=TMP_SECRET report_bp = Blueprint('report', __name__) def check_input(data): msg = "success" hash_re = re.compile( r'^[0-9a-fA-F]{64}$') try: hash = data['hash'] if not hash_re.match(hash): msg = "invalid input" except: return "invalid data" return msg def get_repo_path(random_hash): base_path = "public" hash_folder = os.path.join(base_path, random_hash) items = os.listdir(hash_folder) repo_name = next((item for item in items if os.path.isdir(os.path.join(hash_folder, item))), None) if repo_name: repo_folder = os.path.join(hash_folder, repo_name) return repo_folder else: return None def generateSig(data_bytes, key_bytes): print("data when generating 1st sig", data_bytes) signature = hmac.new(key_bytes, data_bytes, digestmod='sha256').hexdigest() return signature def verify_and_unpickle(path): try: with open(f"{path}/mark4archive", "rb") as f: pickled = f.read() message_bytes = pickled[:-64] received_signature = pickled[-64:] print("received_signature ", received_signature) computed_signature = hmac.new( SECRET, message_bytes, digestmod="sha256").hexdigest() print("computed_signature ",computed_signature) if hmac.compare_digest(bytes(computed_signature, "utf-8"), received_signature): obj = pickle.loads(message_bytes) return obj else: return "Signature is invalid" except Exception as e: print("error in verify and unpickle: ", e) return None def write_to_random_file(input_string): file_name = ''.join(random.choices(string.ascii_lowercase + string.digits, k=10)) file_path = os.path.join('/tmp', file_name) print("tmp path ", file_path ) try: with open(file_path, 'w') as file: file.write(input_string) return file_path except Exception as e: print(f"Error occurred while writing to file: {e}") @report_bp.route('/makereport', methods=['GET','POST']) def MakeReport(): if request.method == "POST": data = request.form if not data["hash"]: return "No hash provided" check = check_input(data) if check == "invalid input" or check == "invalid data": return "invalid hash", 400 hash = data["hash"] path = get_repo_path(hash) print("path ", path) if path: res = verify_and_unpickle(path) random_path = write_to_random_file(res) url = "http://backend:5000/api/pdf?p="+random_path req = requests.get(url) return Response(req.content, mimetype='application/pdf', headers={ 'Content-Disposition': 'attachment; filename=report.pdf' }) return "error" elif request.method == "GET": return render_template("report.html"), 200
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/Securinets/2023/Quals/web/mark4archive/backend/api.py
ctfs/Securinets/2023/Quals/web/mark4archive/backend/api.py
from flask import Blueprint, request, Response from reportlab.lib import colors from reportlab.lib.pagesizes import letter, landscape from reportlab.platypus import SimpleDocTemplate, Paragraph, Spacer from reportlab.lib.styles import getSampleStyleSheet, ParagraphStyle from io import BytesIO api_bp = Blueprint('api', __name__) def generate_pdf_from_file(file_path, output_path): with open(file_path, 'r') as file: content = file.read() doc = SimpleDocTemplate(output_path, pagesize=landscape(letter)) styles = getSampleStyleSheet() title_style = styles['Title'] title_style.alignment = 1 title_style.fontSize = 20 title_style.leading = 24 code_style = ParagraphStyle('Code', parent=styles['Code']) code_style.fontSize = 8 code_style.fontName = 'Courier' elements = [] elements.append(Paragraph("Dummy CodeQL Analysis Report", title_style)) elements.append(Spacer(1, 24)) elements.append(Paragraph(content, code_style)) doc.build(elements) @api_bp.route('/api/pdf', methods=['GET']) def generate_pdf(): if not request.method == "GET": return "invalid method" path = request.args.get("p") pdf_buffer = BytesIO() generate_pdf_from_file(path, pdf_buffer) pdf_buffer.seek(0) return Response(pdf_buffer, mimetype='application/pdf', headers={ 'Content-Disposition': 'attachment; filename=report.pdf' })
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/Securinets/2023/Quals/web/mark4archive/backend/template.py
ctfs/Securinets/2023/Quals/web/mark4archive/backend/template.py
DUMMY_CodeQL_BODY= """{Id}. {Title} File: {File} Line: {Line} Code Snippet: ```{Snippet}``` """ DUMMY_CodeQL_HEADER = """Dummy CodeQL Analysis Report ====================== Repository: {repo} Branch: {branch} Language: "python" Results: """ SNIPPET = { "Python":"""python num = input("Enter a number: ") os.system("factorial_calc " + num)""", "NodeJS": """const readline = require('readline'); const { exec } = require('child_process'); const rl = readline.createInterface({ input: process.stdin, output: process.stdout }); rl.question("Enter a number: ", (num) => { exec("node factorial_calc.js " + num, (error, stdout, stderr) => { if (error) { console.error(`Error: ${error.message}`); } else { console.log(stdout); } rl.close(); }); }); """, "Java": """import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; public class Main { public static void main(String[] args) throws IOException { BufferedReader reader = new BufferedReader(new InputStreamReader(System.in)); System.out.print("Enter a number: "); String num = reader.readLine(); """, "CPP":"""#include <iostream> #include <cstdlib> using namespace std; int main() { string num; cout << "Enter a number: "; getline(cin, num);""", } BODY_CONTENT = [{ "Id":"1", "Title": "Potential Command Injection (Critical)", "File": "dummy", "Line": "15", "Snippet": "{Snippet}", }, { "title": "Potential SSTI (high)", }, ]
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/Securinets/2023/Quals/web/mark4archive/backend/app.py
ctfs/Securinets/2023/Quals/web/mark4archive/backend/app.py
import json import time import os from flask import Flask, render_template from analyze import analyze_bp from report import report_bp from api import api_bp from flask_sock import Sock app = Flask(__name__) app.register_blueprint(analyze_bp) app.register_blueprint(report_bp) app.register_blueprint(api_bp) sock = Sock(app) @app.route("/", methods=["GET"]) def home(): return render_template("index.html") @app.route("/instructions", methods=["GET"]) def instruction(): return render_template("instruction.html") @sock.route('/echo') def echo(sock): total_size = 100 progress = 0 while progress < total_size: time.sleep(0.1) progress += 10 sock.send(json.dumps({'progress': progress})) return "complete!" if __name__ == '__main__': app.run(host='0.0.0.0', port=5000)
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/Securinets/2023/Quals/web/mark4archive/backend/config/config.py
ctfs/Securinets/2023/Quals/web/mark4archive/backend/config/config.py
SECRET = bytes("secret", "utf-8")
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/Securinets/2023/Quals/web/0_CSP/app.py
ctfs/Securinets/2023/Quals/web/0_CSP/app.py
import os import re from flask import Flask, request, jsonify, escape import random import string import requests app = Flask(__name__) url = os.environ.get("URL_BOT") user_tokens = {} headers = { 'Access-Control-Allow-Origin': '*', 'Access-Control-Allow-Methods': 'POST, GET, OPTIONS', 'Access-Control-Allow-Headers': ' *', 'Access-Control-Max-Age': '3600', } def use_regex(input_text): pattern = re.compile(r"https://escape.nzeros.me/", re.IGNORECASE) return pattern.match(input_text) def generate_token(): return ''.join(random.choices(string.ascii_letters + string.digits, k=12)) @app.route('/reporturl', methods=['POST', 'OPTIONS']) def report(): if request.method == "OPTIONS": return '', 200, headers if request.method == "POST": link = request.form['link'] if not use_regex(link): return "wrong url format", 200, headers obj = {'url': link} # send to bot x = requests.post(url, json=obj) if (x.content == b'OK'): return "success!", 200, headers return "failed to visit", 200, headers @app.route('/GetToken', methods=['GET', 'OPTIONS']) def get_token(): if request.method == "OPTIONS": return '', 200, headers try: new_header: dict[str, str | bytes] = dict(headers) userid = request.args.get("userid") if not userid: return jsonify({'error': 'Missing userid'}), 400, headers if userid in user_tokens: token = user_tokens[userid] else: token = generate_token() user_tokens[userid] = token new_header["Auth-Token-" + userid] = token return jsonify({'token': token, 'user': str(escape(userid))[:110]}), 200, new_header except Exception as e: return jsonify({'error': f'Something went wrong {e}'}), 500, headers @app.route('/securinets', methods=['GET', 'OPTIONS']) def securinets(): if request.method == "OPTIONS": return "", 200, headers token = None for key, value in request.headers.items(): if 'Auth-Token-' in key: token_name = key[len('Auth-Token-'):] token = request.headers.get('Auth-Token-'+token_name) if not token: return jsonify({'error': 'Missing Auth-Token header', }), 401, headers if token in user_tokens.values(): return jsonify({'message': f'Welcome to Securinets. {token_name}'}), 200, headers else: return jsonify({'error': 'Invalid token or user not found'}), 403, headers 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/Securinets/2025/Quals/misc/Easy_Jail/give.py
ctfs/Securinets/2025/Quals/misc/Easy_Jail/give.py
import random import string seed = random.randint(0, 2**20) shift_rng = random.Random(seed) class ProtectedFlag: def __init__(self, value): self._value = value def __str__(self): return "variable protected, sryy" def __repr__(self): return "variable protected, sryy" def __getitem__(self, index): try: return self._value[index] except Exception: return "variable protected, sryy" # Example flag flag = ProtectedFlag("flag{dummy_flag}") def shift_mapping(mapping): # well guess how it was done >_< def make_initial_mapping(): letters = list(string.ascii_lowercase) shuffled = letters[:] random.shuffle(shuffled) return dict(zip(letters, shuffled)) def main(): valid_chars = set(string.ascii_lowercase + "[]()~><*+") mapping = make_initial_mapping() print("Welcome to the shifting jail! Enter text using only a-z, []()~><*+") try: while True: user_in = input("> ").strip() if len(user_in) > 150: raise ValueError(f"Input exceeds 150 characters") if not all(c in valid_chars for c in user_in): print("Invalid input. Only [a-z] and []()~><*+ are allowed.") continue encoded = "".join(mapping[c] if c in mapping else c for c in user_in) mapping = shift_mapping(mapping) try: result = eval(encoded, {"__builtins__": None}, {"flag": flag}) print(result) except Exception: print(encoded) except KeyboardInterrupt: print("\nGoodbye!") 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/Securinets/2025/Quals/crypto/Fl1pper_Zer0/chall.py
ctfs/Securinets/2025/Quals/crypto/Fl1pper_Zer0/chall.py
from Crypto.Util.number import long_to_bytes, bytes_to_long, inverse from Crypto.Cipher import AES from Crypto.Util.Padding import pad from fastecdsa.curve import P256 as EC from fastecdsa.point import Point import os, random, hashlib, json from secret import FLAG class SignService: def __init__(self): self.G = Point(EC.gx, EC.gy, curve=EC) self.order = EC.q self.p = EC.p self.a = EC.a self.b = EC.b self.privkey = random.randrange(1, self.order - 1) self.pubkey = (self.privkey * self.G) self.key = os.urandom(16) self.iv = os.urandom(16) def generate_key(self): self.privkey = random.randrange(1, self.order - 1) self.pubkey = (self.privkey * self.G) def ecdsa_sign(self, message, privkey): z = int(hashlib.sha256(message).hexdigest(), 16) k = random.randrange(1, self.order - 1) r = (k*self.G).x % self.order s = (inverse(k, self.order) * (z + r*privkey)) % self.order return (r, s) def ecdsa_verify(self, message, r, s, pubkey): r %= self.order s %= self.order if s == 0 or r == 0: return False z = int(hashlib.sha256(message).hexdigest(), 16) s_inv = inverse(s, self.order) u1 = (z*s_inv) % self.order u2 = (r*s_inv) % self.order W = u1*self.G + u2*pubkey return W.x == r def aes_encrypt(self, plaintext): cipher = AES.new(self.key, AES.MODE_GCM, nonce=self.iv) ct, tag = cipher.encrypt_and_digest(plaintext) return tag + ct def aes_decrypt(self, ciphertext): tag, ct = ciphertext[:16], ciphertext[16:] cipher = AES.new(self.key, AES.MODE_GCM, nonce=self.iv) plaintext = cipher.decrypt_and_verify(ct, tag) return plaintext def get_flag(self): key = hashlib.sha256(long_to_bytes(self.privkey)).digest()[:16] cipher = AES.new(key, AES.MODE_ECB) encrypted_flag = cipher.encrypt(pad(FLAG.encode(), 16)) return encrypted_flag if __name__ == '__main__': print("Welcome to Fl1pper Zer0 – Signing Service!\n") S = SignService() signkey = S.aes_encrypt(long_to_bytes(S.privkey)) print(f"Here is your encrypted signing key, use it to sign a message : {json.dumps({'pubkey': {'x': hex(S.pubkey.x), 'y': hex(S.pubkey.y)}, 'signkey': signkey.hex()})}") while True: print("\nOptions:\n \ 1) sign <message> <signkey> : Sign a message\n \ 2) verify <message> <signature> <pubkey> : Verify the signed message\n \ 3) generate_key : Generate a new signing key\n \ 4) get_flag : Get the flag\n \ 5) quit : Quit\n") try: inp = json.loads(input('> ')) if 'option' not in inp: print(json.dumps({'error': 'You must send an option'})) elif inp['option'] == 'sign': msg = bytes.fromhex(inp['msg']) signkey = bytes.fromhex(inp['signkey']) sk = bytes_to_long(S.aes_decrypt(signkey)) r, s = S.ecdsa_sign(msg, sk) print(json.dumps({'r': hex(r), 's': hex(s)})) elif inp['option'] == 'verify': msg = bytes.fromhex(inp['msg']) r = int(inp['r'], 16) s = int(inp['s'], 16) px = int(inp['px'], 16) py = int(inp['py'], 16) pub = Point(px, py, curve=EC) verified = S.ecdsa_verify(msg, r, s, pub) if verified: print(json.dumps({'result': 'Success'})) else: print(json.dumps({'result': 'Invalid signature'})) elif inp['option'] == 'generate_key': S.generate_key() signkey = S.aes_encrypt(long_to_bytes(S.privkey)) print("Here is your *NEW* encrypted signing key :") print(json.dumps({'pubkey': {'x': hex(S.pubkey.x), 'y': hex(S.pubkey.y)}, 'signkey': signkey.hex()})) elif inp['option'] == 'get_flag': encrypted_flag = S.get_flag() print(json.dumps({'flag': encrypted_flag.hex()})) elif inp['option'] == 'quit': print("Adios :)") break else: print(json.dumps({'error': 'Invalid option'})) except Exception: print(json.dumps({'error': 'Oops! Something went wrong'})) break
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/Securinets/2025/Quals/crypto/XTaSy/chall.py
ctfs/Securinets/2025/Quals/crypto/XTaSy/chall.py
from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes import os, json from secret import FLAG class AES_XTS: def __init__(self): self.key = os.urandom(64) self.tweak = os.urandom(16) def encrypt(self, plaintext): encryptor = Cipher(algorithms.AES(self.key), modes.XTS(self.tweak)).encryptor() return encryptor.update(plaintext.encode('latin-1')) def decrypt(self, ciphertext): decryptor = Cipher(algorithms.AES(self.key), modes.XTS(self.tweak)).decryptor() return decryptor.update(ciphertext) def get_token(username, password): json_data = { "username": username, "password": password, "admin": 0 } str_data = json.dumps(json_data, ensure_ascii=False) token = cipher.encrypt(str_data) return token def check_admin(token): try: str_data = cipher.decrypt(token) json_data = json.loads(str_data) return json_data['admin'] except: print(json.dumps({'error': f'Invalid JSON token "{str_data.hex()}"'})) return None if __name__ == '__main__': print("Welcome to the XTaSy vault! You need to become a VIP (admin) to get a taste.") cipher = AES_XTS() while True: print("\nOptions:\n \ 1) get_token <username> <password> : Generate an access token\n \ 2) check_admin <token> : Check admin access\n \ 3) quit : Quit\n") try: inp = json.loads(input('> ')) except: print(json.dumps({'error': 'Invalid JSON input'})) continue if 'option' not in inp: print(json.dumps({'error': 'You must send an option'})) elif inp['option'] == 'get_token': try: username = bytes.fromhex(inp['username']).decode('latin-1') password = bytes.fromhex(inp['password']).decode('latin-1') token = get_token(username, password) print(json.dumps({'token': token.hex()})) except: print(json.dumps({'error': 'Invalid username or/and password'})) elif inp['option'] == 'check_admin': try: token = bytes.fromhex(inp['token']) assert len(token) >= 16 except: print(json.dumps({'error': 'Invalid token'})) continue is_admin = check_admin(token) if is_admin is None: continue elif is_admin: print(json.dumps({'result': f'Access granted! Enjoy the taste of the flag {FLAG}'})) else: print(json.dumps({'result': 'Access denied!'})) elif inp['option'] == 'quit': print('Adios :)') break else: print(json.dumps({'error': 'Invalid option'}))
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/Securinets/2025/Quals/crypto/Exclusive/chall.py
ctfs/Securinets/2025/Quals/crypto/Exclusive/chall.py
from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes import os, signal from secret import FLAG signal.alarm(30) class AES_XTS: def __init__(self): self.key = os.urandom(64) self.tweak = os.urandom(16) def encrypt(self, plaintext): encryptor = Cipher(algorithms.AES(self.key), modes.XTS(self.tweak)).encryptor() return encryptor.update(plaintext) def decrypt(self, ciphertext): decryptor = Cipher(algorithms.AES(self.key), modes.XTS(self.tweak)).decryptor() return decryptor.update(ciphertext) if __name__ == '__main__': print("Welcome! Exclusive contents awaits, but you'll have to figure it out yourself.") cipher = AES_XTS() blocks = [FLAG[i:i+16] for i in range(0, len(FLAG), 16)] try: print(f"Select a block number to generate a clue (1-{len(blocks)})") ind = int(input('> ')) clue = cipher.encrypt(os.urandom(16) + blocks[ind-1]) print(f"Your clue : {clue.hex()}") while True: print("Submit the clue (in hex)") your_clue = bytes.fromhex(input('> ')) decrypted = cipher.decrypt(your_clue) decrypted_blocks = [decrypted[i:i+16] for i in range(0, len(decrypted), 16)] exclusive_content = decrypted_blocks[0] print(f"Exclusive content : {exclusive_content.hex()}") except: print('Oops! Something went wrong')
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/Securinets/2022/Quals/crypto/aes-2/aes-2.py
ctfs/Securinets/2022/Quals/crypto/aes-2/aes-2.py
from Crypto.Cipher import AES from Crypto.Util.Padding import pad import os, sys, hashlib, random FLAG = b"Securinets{REDACTED}" key, iv1, iv2 = [os.urandom(16) for _ in range(3)] def xor(a, b): return bytes(i ^ j for i, j in zip(a, b)) def get_token(msg, iv1, iv2): if len(msg) % 16 != 0: msg = pad(msg, 16) aes = AES.new(key, AES.MODE_ECB) blocks = [msg[i:i+16] for i in range(0, len(msg), 16)] enc = b"" tmp1 = iv1 tmp2 = iv2 for block in blocks: tmp = aes.encrypt(xor(block, tmp1)) _tmp = aes.encrypt(xor(tmp, tmp2)) enc += _tmp tmp1 = _tmp tmp2 = tmp return enc def proof(msg): res = b"\x00"*16 for i in range(0, len(msg), 16): res = xor(res, msg[i:i+16]) return hashlib.sha256(res).digest() if __name__ == "__main__": alice_username = os.urandom(32) alice_token = get_token(alice_username, iv1, iv2) print(f"Alice's creds : {alice_username.hex()} -> {alice_token.hex()}\n") while True: try: username = bytes.fromhex(input("Username : ")) token = get_token(username, iv1, iv2) print(f"Your creds : {username.hex()} -> {token.hex()}") if proof(token) == proof(alice_token): if token == alice_token: print(f"You are not Alice!") sys.exit() else: print(f"Hey Alice! Here is your flag {FLAG}") sys.exit() else: print("Try again!\n") except Exception as e: print(e) print("Invalid input.\n")
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/Securinets/2022/Quals/crypto/escrime/escrime.py
ctfs/Securinets/2022/Quals/crypto/escrime/escrime.py
from Crypto.Util.number import getStrongPrime, getPrime, isPrime, bytes_to_long FLAG = b"Securinets{REDACTED}" def genPrime(prime): while True: a = getPrime(256) p = 2*prime*a + 1 if isPrime(p): break while True: b = getPrime(256) q = 2*prime*b + 1 if isPrime(q): break return p, q prime = getStrongPrime(512) p1, q1 = genPrime(prime) p2, q2 = genPrime(prime) assert p1 != p2 != q1 != q2 n1 = p1*q1 n2 = p2*q2 e = 65537 m1 = bytes_to_long(FLAG[:len(FLAG)//2]) m2 = bytes_to_long(FLAG[len(FLAG)//2:]) c1 = pow(m1, e, n1) c2 = pow(m2, e, n2) print(f"n1 = {n1}") print(f"n2 = {n2}") print(f"e = {e}") print(f"c1 = {c1}") print(f"c2 = {c2}")
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/Securinets/2022/Quals/web/NarutoKeeper/app/form.py
ctfs/Securinets/2022/Quals/web/NarutoKeeper/app/form.py
from flask_wtf import Form, RecaptchaField from wtforms import StringField, validators,PasswordField,SubmitField class ReportForm(Form): url = StringField('Url To Visit', [validators.DataRequired(), validators.Length(max=255)],render_kw={"placeholder": "http://URL/"}) recaptcha = RecaptchaField() class LoginForm(Form): user_name = StringField('userName', validators=[validators.DataRequired()]) password = PasswordField('password', validators=[validators.DataRequired()]) submit = SubmitField('Sign In') class RegisterForm(Form): user_name = StringField('userName', validators=[validators.DataRequired()]) password = PasswordField('password', validators=[validators.DataRequired()]) submit = SubmitField('Sign Up')
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/Securinets/2022/Quals/web/NarutoKeeper/app/app.py
ctfs/Securinets/2022/Quals/web/NarutoKeeper/app/app.py
from flask import Flask,request,render_template,session,redirect from form import ReportForm,LoginForm,RegisterForm import os,pymysql,time import requests,secrets,random,string from flask_wtf.csrf import CSRFProtect app= Flask(__name__) app.config["SECRET_KEY"]=os.urandom(15).hex() app.config['RECAPTCHA_USE_SSL']= False DOMAIN=os.getenv("DOMAIN") app.config['RECAPTCHA_PUBLIC_KEY']= os.getenv("PUBLIC_KEY") app.config['RECAPTCHA_PRIVATE_KEY']=os.getenv("PRIVATE_KEY") app.config['RECAPTCHA_OPTIONS'] = {'theme':'white'} app.config['SESSION_COOKIE_SAMESITE']="None" app.config['SESSION_COOKIE_SECURE']= True csrf = CSRFProtect() csrf.init_app(app) def random_string(S): ran = ''.join(random.choices(string.ascii_uppercase + string.digits, k = S)) return ran def get_db(): mydb = pymysql.connect( host="db", user="securinets", password=os.getenv("mysql_pass"), database="l33k" ) return mydb.cursor(),mydb def create_paste(paste, username): paste_id = random_string(64) cursor,mydb=get_db() cursor.execute( 'INSERT INTO pastes (id, paste, username) VALUES (%s, %s, %s);', (paste_id, paste, username) ) mydb.commit() return paste_id def get_pastes(username): cursor,mydb=get_db() cursor.execute( 'SELECT id FROM pastes WHERE username = %s', username ) result=cursor.fetchall() mydb.commit() return [paste_id[0] for paste_id in result] def get_paste(paste_id): cursor,mydb=get_db() cursor.execute( 'SELECT paste FROM pastes WHERE id = %s', paste_id ) results=cursor.fetchone() mydb.commit() if len(results) < 1: return 'Paste not found!' return results[0] @app.route("/",methods=["GET"]) def index(): return render_template("index.html") @app.route("/register",methods=["GET","POST"]) def register(): if request.method == "POST": if "username" in session : return redirect("/home") if request.values.get("username") and len(request.values.get("username"))<50 and request.values.get("password"): cursor,mydb = get_db() query = "SELECT * FROM users WHERE username=%s" cursor.execute(query, request.values.get("username")) result = cursor.fetchone() if result is not None: return render_template("register.html",error="Username already exists") try: mydb.commit() cursor.close() cursor,mydb=get_db() query="INSERT INTO users(id,username,password) VALUES(null,%s,%s)" values=(request.values.get("username"),request.values.get("password")) cursor.execute(query,values) mydb.commit() session["username"]=request.values.get("username") cursor.close() return redirect("/home") except Exception: return render_template("register.html",error="Error happened while registering") else: return redirect("/login",302) else: if "username" in session: return redirect("/home") else: return render_template("register.html",error="") @app.route("/home",methods=["GET"]) def home(): if "username" in session : print(get_pastes(session['username'])) return render_template("home.html",username=session["username"],pastes=get_pastes(session['username'])) else: return redirect("/login") @app.route("/login",methods=["GET","POST"]) def login(): if request.method=="GET": if "username" in session: return redirect("/home") else: return render_template("login.html",error="") else: username=request.values.get("username") password=request.values.get("password") if username is None or password is None: return render_template("login.html",error="") else: cursor,mydb = get_db() query = "SELECT * FROM users WHERE username=%s AND password=%s" cursor.execute(query, (username, password)) result = cursor.fetchone() if result is not None: session["username"]=result[1] mydb.commit() cursor.close() return redirect("/home") else: return render_template("login.html",error="Username or password is incorrect") @app.route("/logout",methods=["GET"]) def logout(): session.clear() return redirect("/") @app.route('/source',methods=['GET']) def source(): return render_template("source.html") @app.route('/create_paste', methods=['POST','GET']) def create(): if request.method=="GET": if 'username' not in session: return redirect('/login') return render_template("create_paste.html") else: if 'username' not in session: return redirect('/login') if len(request.values.get('paste'))<1000: paste_id = create_paste( request.values.get('paste'), session['username'] ) return redirect('/view?id='+paste_id) return redirect('/home') @app.route('/view', methods=['GET']) def view(): paste_id = request.args.get('id') if paste_id=="MaximumReached" : return render_template("view.jinja2",paste="Maximum iterations is reached! your last paste is: "+request.args.get("paste")) if paste_id=="Found": return render_template("view.jinja2",paste="Found your search!. your last paste is: "+request.args.get("paste")) return render_template( 'view.jinja2', paste=get_paste(paste_id) ) @app.route('/search') def search(): if 'username' not in session: return redirect('/login') if 'query' not in request.args: return redirect('/home') query = str(request.args.get('query')) results = get_pastes(session['username']) res_content=[{"id":id,"val":get_paste(id)} for id in results] if ":" in query: toGo=get_paste(query.split(":")[1]) sear=query.split(":")[0] else: toGo=res_content[0]["val"] sear=query i=0 for paste in res_content: i=i+1 if i>5: return redirect("/view?id=MaximumReached&paste="+toGo.strip()) if sear in paste["val"]: return redirect("/view?id=Found&paste="+toGo.strip()) return render_template("search.html",error='No results found.',result="") # No vulns here just the bot implementation @app.route("/report",methods=["POST","GET"]) def report(): form= ReportForm() if request.method=="POST": r=requests.get("http://bot?url="+request.form.get("url")) if "successfully" in r.text: return render_template("report.html",form=form,msg="Admin visited your website successfully") else: return render_template("report.html",form=form,msg="An unknown error has occured") else: return render_template("report.html",msg="",form=form) if __name__=="__main__": app.run(host="0.0.0.0",debug=False,port=443,ssl_context='adhoc')
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/BxMCTF/2023/pwn/Banking_Issues/main.py
ctfs/BxMCTF/2023/pwn/Banking_Issues/main.py
#!/usr/local/bin/python import os balances = [10, 20, 50, 16, 29, 52, 100000] PERMS_ADMIN = { "MAX_INDEX": len(balances) - 1 } PERMS_AGENT = { "MAX_INDEX": len(balances) - 2 } def main(): perms = PERMS_AGENT wallet = 0 idx = int(input("Which account would you like to withdraw from? ")) if idx > perms["MAX_INDEX"]: print("Unauthorized") return wallet += balances[idx] balances[idx] = 0 print(f"You now have ${wallet} in your wallet.\n") if wallet >= 100000: print("Thanks for storing a lot of $$ at our bank.") print("You qualify for free wealth management services.") print(f"To access this service, please email {os.getenv('FLAG')}@bxmctf.bank.\n") print("Thank you for banking with BxMCTF Bank.") 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/BxMCTF/2023/pwn/The_Revenge_of_Checkpass_1/main.py
ctfs/BxMCTF/2023/pwn/The_Revenge_of_Checkpass_1/main.py
#!/usr/local/bin/python # -*- coding: utf-8 -*- def main(): password = "the password can contain non-ascii charactérs :)" inp = input("Enter a Python list: ") lis = eval(inp, {'__builtins__': None}, None) if type(lis) != list: print("That's not a list") return for i in lis: if not isinstance(i, int): print("The list can only contain integers") return if lis == [ord(e) for e in password]: print("You are now authorized!") with open("flag.txt", "r") as flag: print(flag.read()) else: print("Incorrect password!") 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/BxMCTF/2023/rev/MCV5U/Rev3.py
ctfs/BxMCTF/2023/rev/MCV5U/Rev3.py
import math import hashlib import sys SIZE = int(3e5) VERIFY_KEY = "46e1b8845b40bc9d977b8932580ae44c" def getSequence(A, B, n, m): ans = [0] * (n + m - 1) for x in range(n): for y in range(m): ans[x + y] += A[x] * B[y] return ans A = [0] * SIZE B = [0] * SIZE document1 = open("Document 1.txt", "r") nums1 = document1.readlines() idx = 0 for num in nums1: A[idx] = int(num.strip()) idx += 1 document2 = open("Document 2.txt", "r") nums2 = document2.readlines() idx = 0 for num in nums2: B[idx] = int(num.strip()) idx += 1 sequence = getSequence(A, B, SIZE, SIZE) val = 0 for num in sequence: val = (val + num) val = str(val) val_md5 = hashlib.md5(val.encode()).hexdigest() if val_md5 != VERIFY_KEY: print("Wrong solution.") sys.exit(1) key = str(hashlib.sha256(val.encode()).digest()) flag = "ctf{" + "".join(list([x for x in key if x.isalpha() or x.isnumeric()])) + "}" print(flag)
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/BxMCTF/2023/web/Username_Decorator/src/app.py
ctfs/BxMCTF/2023/web/Username_Decorator/src/app.py
from flask import Flask, render_template_string, request import re app = Flask(__name__) app.config['FLAG_LOCATION'] = 'os.getenv("FLAG")' def validate_username(username): return bool(re.fullmatch("[a-zA-Z0-9._\[\]\(\)\-=,]{2,}", username)) @app.route('/', methods=['GET', 'POST']) def index(): prefix = '' username = '' suffix = '' if request.method == 'POST': prefix = (request.form['prefix'] or '')[:2] username = request.form['username'] or '' suffix = (request.form['suffix'] or '')[:2] if not validate_username(username): username = 'Invalid Username' template = '<!DOCTYPE html><html><body>\ <form action="" method="post">\ Prefix: <input name="prefix"> <br>\ Username: <input name="username"> <br>\ Suffix: <input name="suffix"> <br> \ <input type="submit" value="Preview!">\ </form><h2>%s %s %s</h2></body></html>' % (prefix, username, suffix) return render_template_string(template) @app.route('/flag') def get_flag(): return 'Nein' import os return eval(app.config['FLAG_LOCATION'])
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/BxMCTF/2023/web/Username_Decorator/src/wsgi.py
ctfs/BxMCTF/2023/web/Username_Decorator/src/wsgi.py
from app import app
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/BxMCTF/2023/web/Repository_Security/manage.py
ctfs/BxMCTF/2023/web/Repository_Security/manage.py
import json import os from functools import wraps import click from flask import Flask, jsonify, render_template from flask_simplelogin import Message, SimpleLogin, login_required from werkzeug.security import check_password_hash, generate_password_hash # [ -- Utils -- ] def validate_login(user): db_users = json.load(open("users.json")) if not db_users.get(user["username"]): return False stored_password = db_users[user["username"]]["password"] if check_password_hash(stored_password, user["password"]): return True return False def create_user(**data): """Creates user with encrypted password""" if "username" not in data or "password" not in data: raise ValueError("username and password are required.") # Hash the user password data["password"] = generate_password_hash( data.pop("password"), method="pbkdf2:sha256" ) # Here you insert the `data` in your users database # for this simple example we are recording in a json file db_users = json.load(open("users.json")) # add the new created user to json db_users[data["username"]] = data # commit changes to database json.dump(db_users, open("users.json", "w")) return data # [--- Flask Factories ---] def create_app(): app = Flask(__name__) app.config.from_object("settings") return app def configure_extensions(app): messages = { "login_success": "Welcome!", "is_logged_in": Message("already logged in", "success"), "logout": None, } SimpleLogin(app, login_checker=validate_login, messages=messages) if not os.path.exists("users.json"): with open("users.json", "a") as json_file: # This just touch create a new dbfile json.dump({"username": "", "password": ""}, json_file) def configure_views(app): @app.route("/") def index(): return render_template("index.html") @app.route("/secret") @login_required() def secret(): return render_template("secret.html") @app.route("/api", methods=["POST"]) @login_required(basic=True) def api(): return jsonify(data="You are logged in with basic auth") @app.route("/complex") @login_required(username=["admin"]) def complexview(): return render_template("secret.html") # [--- Command line functions ---] def with_app(f): """Calls function passing app as first argument""" @wraps(f) def decorator(*args, **kwargs): app = create_app() configure_extensions(app) configure_views(app) return f(app=app, *args, **kwargs) return decorator @click.group() def main(): """Flask Simple Login Example App""" @main.command() @click.option("--username", required=True, prompt=True) @click.option( "--password", required=True, prompt=True, hide_input=True, confirmation_prompt=True ) @with_app def adduser(app, username, password): """Add new user with admin access""" with app.app_context(): create_user(username=username, password=password) click.echo("user created!") @main.command() @click.option("--reloader/--no-reloader", default=None) @click.option("--debug/--no-debug", default=None) @click.option("--host", default=None) @click.option("--port", default=None) @with_app def runserver(app=None, reloader=None, debug=None, host=None, port=None): """Run the Flask development server i.e. app.run()""" debug = debug or app.config.get("DEBUG", False) reloader = reloader or app.config.get("RELOADER", False) host = host or app.config.get("HOST", "127.0.0.1") port = port or app.config.get("PORT", 5000) app.run(use_reloader=reloader, debug=debug, host=host, port=port) # [--- Entry point ---] if __name__ == "__main__": # python manage.py to see help main()
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/BxMCTF/2023/web/Repository_Security/settings.py
ctfs/BxMCTF/2023/web/Repository_Security/settings.py
import os SECRET_KEY = "secret-here" SIMPLELOGIN_BLUEPRINT = os.getenv("SIMPLELOGIN_BLUEPRINT") SIMPLELOGIN_LOGIN_URL = os.getenv("SIMPLELOGIN_LOGIN_URL") SIMPLELOGIN_LOGOUT_URL = os.getenv("SIMPLELOGIN_LOGOUT_URL") SIMPLELOGIN_HOME_URL = os.getenv("SIMPLELOGIN_HOME_URL")
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/BxMCTF/2023/web/Repository_Security/app.py
ctfs/BxMCTF/2023/web/Repository_Security/app.py
from flask import Flask, jsonify, render_template from flask.views import MethodView from flask_simplelogin import SimpleLogin, get_username, login_required my_users = { "chuck": {"password": "norris", "roles": ["admin"]}, "lee": {"password": "douglas", "roles": []}, "mary": {"password": "jane", "roles": []}, "steven": {"password": "wilson", "roles": ["admin"]}, } def check_my_users(user): """Check if user exists and its credentials. Take a look at encrypt_app.py and encrypt_cli.py to see how to encrypt passwords """ user_data = my_users.get(user["username"]) if not user_data: return False # <--- invalid credentials elif user_data.get("password") == user["password"]: return True # <--- user is logged in! return False # <--- invalid credentials app = Flask(__name__) app.config.from_object("settings") simple_login = SimpleLogin(app, login_checker=check_my_users) @app.route("/") def index(): return render_template("index.html") @app.route("/secret") @login_required(username=["chuck", "mary"]) def secret(): return render_template("secret.html") @app.route("/api", methods=["POST"]) @login_required(basic=True) def api(): return jsonify(data="You are logged in with basic auth") def be_admin(username): """Validator to check if user has admin role""" user_data = my_users.get(username) if not user_data or "admin" not in user_data.get("roles", []): return "User does not have admin role" def have_approval(username): """Validator: all users approved, return None""" return @app.route("/complex") @login_required(must=[be_admin, have_approval]) def complexview(): return render_template("secret.html") class ProtectedView(MethodView): decorators = [login_required] def get(self): return "You are logged in as <b>{0}</b>".format(get_username()) app.add_url_rule("/protected", view_func=ProtectedView.as_view("protected")) if __name__ == "__main__": app.run(host="0.0.0.0", port=5050, use_reloader=True, debug=True)
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/BxMCTF/2023/web/Repository_Security/wsgi.py
ctfs/BxMCTF/2023/web/Repository_Security/wsgi.py
from app import app
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/BxMCTF/2023/web/Repository_Security/flask_simplelogin/__init__.py
ctfs/BxMCTF/2023/web/Repository_Security/flask_simplelogin/__init__.py
import logging import os from functools import wraps from uuid import uuid4 from urllib.parse import urlparse, urljoin from warnings import warn from flask import ( abort, Blueprint, current_app, flash, redirect, render_template, request, session, url_for, ) from flask_wtf import FlaskForm from wtforms import PasswordField, StringField from wtforms.validators import DataRequired logger = logging.getLogger(__name__) class Message: def __init__(self, text, category="primary"): self.text = text self.category = category @classmethod def from_current_app(cls, label): """Helper to get messages from Flask's current_app""" return current_app.extensions["simplelogin"].messages.get(label) def __str__(self): return self.text def format(self, *args, **kwargs): return self.text.format(*args, **kwargs) class LoginForm(FlaskForm): "Default login form" username = StringField( "name", validators=[DataRequired()], render_kw={"autocapitalize": "none"} ) password = PasswordField("password", validators=[DataRequired()]) def default_login_checker(user): """user must be a dictionary here default is checking username/password if login is ok returns True else False :param user: dict {'username':'', 'password': ''} """ username = user.get("username") password = user.get("password") the_username = os.environ.get( "SIMPLELOGIN_USERNAME", current_app.config.get("SIMPLELOGIN_USERNAME", "admin") ) the_password = os.environ.get( "SIMPLELOGIN_PASSWORD", current_app.config.get("SIMPLELOGIN_PASSWORD", "secret") ) if username == the_username and password == the_password: return True return False def is_logged_in(username=None): """Checks if user is logged in if `username` is passed check if specified user is logged in username can be a list""" if username: if not isinstance(username, (list, tuple)): username = [username] return "simple_logged_in" in session and get_username() in username return "simple_logged_in" in session def get_username(): """Get current logged in username""" return session.get("simple_username") def login_required(function=None, username=None, basic=False, must=None): """Decorate views to require login @login_required @login_required() @login_required(username='admin') @login_required(username=['admin', 'jon']) @login_required(basic=True) @login_required(must=[function, another_function]) """ if function and not callable(function): raise ValueError( "Decorator receives only named arguments, " 'try login_required(username="foo")' ) def check(validators): """Return in the first validation error, else return None""" if validators is None: return if not isinstance(validators, (list, tuple)): validators = [validators] for validator in validators: error = validator(get_username()) if error is not None: return Message.from_current_app("auth_error").format(error), 403 def dispatch(fun, *args, **kwargs): if basic and request.is_json: return dispatch_basic_auth(fun, *args, **kwargs) if is_logged_in(username=username): return check(must) or fun(*args, **kwargs) elif is_logged_in(): return Message.from_current_app("access_denied"), 403 else: SimpleLogin.flash("login_required") return redirect(url_for("simplelogin.login", next=request.path)) def dispatch_basic_auth(fun, *args, **kwargs): simplelogin = current_app.extensions["simplelogin"] auth_response = simplelogin.basic_auth() if auth_response is True: return check(must) or fun(*args, **kwargs) else: return auth_response if function: @wraps(function) def simple_decorator(*args, **kwargs): """This is for when decorator is @login_required""" return dispatch(function, *args, **kwargs) return simple_decorator def decorator(f): """This is for when decorator is @login_required(...)""" @wraps(f) def wrap(*args, **kwargs): return dispatch(f, *args, **kwargs) return wrap return decorator class SimpleLogin: """Simple Flask Login""" messages = { "login_success": Message("login success!", "success"), "login_failure": Message("invalid credentials", "danger"), "is_logged_in": Message("already logged in"), "logout": Message("Logged out!"), "login_required": Message("You need to login first", "warning"), "access_denied": Message("Access Denied"), "auth_error": Message("Authentication Error: {0}"), } @staticmethod def flash(label, *args, **kwargs): msg = Message.from_current_app(label) if not msg: return if args or kwargs: flash(msg.format(*args, **kwargs), msg.category) else: flash(msg.text, msg.category) def __init__(self, app=None, login_checker=None, login_form=None, messages=None): self.config = { "blueprint": "simplelogin", "login_url": "/login/", "logout_url": "/logout/", "home_url": "/", } self.app = None self._login_checker = login_checker or default_login_checker self._login_form = login_form or LoginForm if app is not None: self.init_app( app=app, login_checker=login_checker, login_form=login_form, messages=messages, ) def login_checker(self, f): """To set login_checker as decorator: @simple.login_checher def foo(user): ... """ self._login_checker = f return f def init_app(self, app, login_checker=None, login_form=None, messages=None): if login_checker: self._login_checker = login_checker if login_form: self._login_form = login_form if messages and isinstance(messages, dict): cleaned = {k: v for k, v in messages.items() if k in self.messages.keys()} for key in cleaned.keys(): if isinstance(cleaned[key], str): cleaned[key] = Message(cleaned[key]) self.messages.update(cleaned) self._register(app) self._load_config() self._set_default_secret() self._register_views() self._register_extras() def _register(self, app): if not hasattr(app, "extensions"): app.extensions = {} if "simplelogin" in app.extensions: raise RuntimeError("Flask extension already initialized") app.extensions["simplelogin"] = self self.app = app def _load_config(self): config = self.app.config.get_namespace( namespace="SIMPLELOGIN_", lowercase=True, trim_namespace=True ) # backwards compatibility old_config = self.app.config.get_namespace( namespace="SIMPLE_LOGIN_", lowercase=True, trim_namespace=True ) config.update(old_config) if old_config: msg = ( "Settings defined as SIMPLE_LOGIN_ will be deprecated. " "Please, use SIMPLELOGIN_ instead." ) warn(msg, FutureWarning) self.config.update(old_config) self.config.update(dict((key, value) for key, value in config.items() if value)) def _set_default_secret(self): if self.app.config.get("SECRET_KEY") is None: secret_key = str(uuid4()) logger.warning( ( "Using random SECRET_KEY: {0}, " 'please set it on your app.config["SECRET_KEY"]' ).format(secret_key) ) self.app.config["SECRET_KEY"] = secret_key def _register_views(self): self.blueprint = Blueprint( self.config["blueprint"], __name__, template_folder="templates" ) self.blueprint.add_url_rule( self.config["login_url"], endpoint="login", view_func=self.login, methods=["GET", "POST"], ) self.blueprint.add_url_rule( self.config["logout_url"], endpoint="logout", view_func=self.logout, methods=["GET"], ) self.app.register_blueprint(self.blueprint) def _register_extras(self): self.app.add_template_global(is_logged_in) self.app.add_template_global(get_username) def basic_auth(self, response=None): """Support basic_auth via /login or login_required(basic=True)""" auth = request.authorization if auth and self._login_checker( {"username": auth.username, "password": auth.password} ): session["simple_logged_in"] = True session["simple_basic_auth"] = True session["simple_username"] = auth.username return response or True else: headers = {"WWW-Authenticate": 'Basic realm="Login Required"'} return "Invalid credentials", 401, headers def login(self): destiny = request.args.get( "next", default=request.form.get("next", default=self.config.get("home_url", "/")), ) host_url = urlparse(request.host_url) redirect_url = urlparse(urljoin(request.host_url, destiny)) if ( not host_url.netloc == redirect_url.netloc and redirect_url.netloc not in self.app.config.get("ALLOWED_HOSTS", []) ): return abort(400, "Invalid next url, can only redirect to the same host") if is_logged_in(): self.flash("is_logged_in") return redirect(destiny) if request.is_json: # recommended to use `login_required(basic=True)` instead this return self.basic_auth(destiny=redirect(destiny)) form = self._login_form() ret_code = 200 if form.validate_on_submit(): if self._login_checker(form.data): self.flash("login_success") session["simple_logged_in"] = True session["simple_username"] = form.data.get("username") return redirect(destiny) else: self.flash("login_failure") ret_code = 401 # <-- invalid credentials RFC7235 return render_template("login.html", form=form, next=destiny), ret_code def logout(self): session.clear() self.flash("logout") return redirect(self.config.get("home_url", "/"))
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/Nowruz/2025/misc/ecal/jail.py
ctfs/Nowruz/2025/misc/ecal/jail.py
#!/usr/bin/env python import importlib blacklist = [ "os", "posix", "subprocess", "shutil", "pickle", "marshal", "csv", "pdb", "tty", "pty" ] def secure_importer(name, globals=None, locals=None, fromlist=(), level=0): if name in blacklist: raise ImportError("module '%s' is restricted." % name) return importlib.__import__(name, globals, locals, fromlist, level) def isnumber(v): assert type(v) in [int, float], "Only numbers are valid" return True # ensure you don't use blacklist __builtins__.__dict__['__import__'] = secure_importer def main(): while True: num1 = input("Enter number1: ") num2 = input("Enter number2: ") operator = input("Enter operator: ") if operator not in ["*", "+", "/", "-"]: print("Invalid operator") exit() code = f"({num1}) {operator} ({num2})" result = eval(code, {'__builtins__':{},'globals': {}}, {'__builtins__':{}}) isnumber(result) print(f"{code} = {result}") try: main() except Exception as exp: print(f"[-] Error: {exp}")
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/Nowruz/2025/pwn/gogogo/run.py
ctfs/Nowruz/2025/pwn/gogogo/run.py
#!/usr/bin/env python3 import tempfile import pathlib import os os.chdir(pathlib.Path(__file__).parent.resolve()) with tempfile.NamedTemporaryFile() as tmp: print('Send the file: (ended with "\\n-- EOF --\\n"):') s = input() while(s != '-- EOF --'): tmp.write((s+'\n').encode()) s = input() tmp.flush() os.system('timeout 3 ./chall ' + tmp.name + ' 2>&1')
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/Nowruz/2025/crypto/seal_the_deal/server.py
ctfs/Nowruz/2025/crypto/seal_the_deal/server.py
from math import gcd from Crypto.Util.number import getPrime, inverse from random import randint import secrets import time with open("flag.txt") as f: flag = f.readline() class Paillier: def __init__(self, bits): self.bits = bits self.pub, self.priv = self.keygen() def lcm(self, a, b): return a * b // gcd(a, b) def keygen(self): while True: p = getPrime(self.bits) q = getPrime(self.bits) if p != q: break n = p * q Lambda = self.lcm(p - 1, q - 1) g = n + 1 mu = inverse(Lambda, n) return ((n, g), (Lambda, mu)) def encrypt(self, m): (n, g) = self.pub n_sq = n * n while True: r = randint(1, n - 1) if gcd(r, n) == 1: break c = (pow(g, m, n_sq) * pow(r, n, n_sq)) % n_sq return c def decrypt(self, c): (n, g) = self.pub (Lambda, mu) = self.priv n_sq = n * n x = pow(c, Lambda, n_sq) m = (((x - 1) // n) * mu) % n return m def get_keys(self): return self.pub, self.priv if __name__ == "__main__": print("Welcome to the Secure Gate Challenge!") paillier = Paillier(256) pub, priv = paillier.get_keys() print('(n,g)=', pub) nums = [secrets.randbits(16) for _ in range(4)] res = (nums[0] + nums[1]) + (nums[2] - nums[3]) ciphers = [paillier.encrypt(i) for i in nums] print('c1 =', ciphers[0]) print('c2 =', ciphers[1]) print('c3 =', ciphers[2]) print('c4 =', ciphers[3]) try: start_time = time.time() pass_code = int(input("Can you open the gate? If so, insert the passcode fast: ")) if time.time() - start_time > 60: print("Too slow! Time's up!") exit() pass_decode = paillier.decrypt(pass_code) if res == pass_decode: print(f"Wow! You opened it, The flag is: {flag}") else: print("Nope, Maybe next time :(") except Exception as e: print("Invalid input or error occurred:", str(e)) exit()
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/Nowruz/2025/crypto/superguesser_v2/chal.py
ctfs/Nowruz/2025/crypto/superguesser_v2/chal.py
#!/usr/local/bin/python import os import random from Crypto.Cipher import AES from Crypto.Util.Padding import pad MAX_ATTEMPTS = 10 def encrypt_flag(flag, iv): key = random.getrandbits(128).to_bytes(16, 'big') cipher = AES.new(key, AES.MODE_CBC, iv*2) encrypted = cipher.encrypt(pad(flag.encode(), AES.block_size)) return encrypted def main(): secureSeed = os.urandom(8) random.seed(secureSeed) hints = [random.getrandbits(32) for _ in range(624)] encrypted_flag = encrypt_flag(open('./flag.txt').read(), secureSeed) print("\n✨ Welcome to the **Guess the Number Challenge v2**! ✨") print("🕵️‍♂️ Your mission: Decode the encrypted flag by uncovering critical hints.") print("📊 We've precomputed 624 random numbers using a secure PRNG.") print(f"❗ But there's a catch: You can only access {MAX_ATTEMPTS} of them.") print("🔑 Choose your indices wisely to uncover the key!") print("\n📜 Instructions:") print("1️⃣ You have 624 unique random numbers that are critical for decrypting the flag.") print("2️⃣ Enter an index (0-623) to reveal a hint.") print(f"3️⃣ You only have {MAX_ATTEMPTS} attempts, so choose wisely!") print("4️⃣ Use your understanding of randomness to crack the secure seed.") print(f"\n🔒 Here is your encrypted flag: \n{encrypted_flag.hex()}") print(f"\nGood luck! You have {MAX_ATTEMPTS} attempts to guess the correct index.\n") for attempt in range(1, MAX_ATTEMPTS + 1): print(f"Attempt {attempt}/{MAX_ATTEMPTS}") try: index = int(input("Enter an index (0-624): ").strip()) if 0 <= index < 624: print(f"Hint at index {index}: {hints[index]}\n") else: print("❌ Invalid index! Please enter a number between 0 and 624.\n") except ValueError: print("❌ Invalid input! Please enter a valid integer.\n") print("✨ Your attempts are over! Good luck solving the challenge!\n") print("🔍 Remember, the flag is encrypted. Use your hints wisely. Goodbye!") if __name__ == "__main__": main()
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/Nowruz/2025/crypto/Robin_s_Mystery/Robin_Mystery.py
ctfs/Nowruz/2025/crypto/Robin_s_Mystery/Robin_Mystery.py
import random from Crypto.PublicKey import RSA from Crypto.Util.number import * def nextPrime(prim): if isPrime(prim): return prim else: return nextPrime(prim+1) p = getPrime(512) q = nextPrime(p+1) while p%4 != 3 or q%4 !=3: p = getPrime(512) q = nextPrime(p+1) n = p*q m = bytes_to_long( open('flag.txt','rb').read() ) c = pow(m, e, n) rsa = RSA.construct((n, e)) print(rsa.exportKey().decode()) print(f"cipher: { long_to_bytes(c) }")
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/Nowruz/2025/crypto/EZ_RSA/EZ_RSA.py
ctfs/Nowruz/2025/crypto/EZ_RSA/EZ_RSA.py
from Crypto.Util.number import getPrime import os flag = os.getenv("FLAG", "FMCTF{F4K3_FL49}") m = int(flag.encode().hex(), 16) p = getPrime(512) q = getPrime(512) n = p*q e = 65537 c = pow(m, e, n) hint = p+q print(f"{hint = }") print(f"{n = }") print(f"{c = }") # hint = 17469292153344571442220879753705314094982989674618803961044325274734902918518047825543639089360378046111761829828690097867206972174713085299385569035446604 # n = 72178676992512160441554160179592383158203955928083976740488546189244761660478121450369459709272987174826935459768807973546852656122370605905453926547673003297830819475396600384101353650933279529161854454268770358323854195264696322371766082303954604264551309576730976571309522883511488619775495703381232031179 # c = 58920849369961001974878540043377399205173235403895163231084588694712964281923344842680972991777380071418111292770515352012869237864259800540355713208626735820573601770413846338478651482053989341163751620131823006414875347921150338651475973491744075397194132475674270761198474531891598902225518350430719735601
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/Nowruz/2025/crypto/EZ_XOR/EZ_XOR.py
ctfs/Nowruz/2025/crypto/EZ_XOR/EZ_XOR.py
from pwn import * FLAG = os.environ.get("FLAG", "FMCTF{F4K3_FL49}").encode() key = os.urandom(7) encryptedFlag = xor(FLAG, key).hex() print(f"encryptedFlag = {encryptedFlag}") # encryptedFlag = a850d725cb56b0de4fcb40de72a4df56a72ec06cafa75ecb41f51c95
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/Nowruz/2025/crypto/superguesser/chal.py
ctfs/Nowruz/2025/crypto/superguesser/chal.py
#!/usr/local/bin/python import random import time from Crypto.Cipher import AES from Crypto.Util.Padding import pad MAX_ATTEMPTS = 1000 def encrypt_flag(flag): key = random.getrandbits(128).to_bytes(16, 'big') iv = random.getrandbits(128).to_bytes(16, 'big') cipher = AES.new(key, AES.MODE_CBC, iv) encrypted = cipher.encrypt(pad(flag.encode(), AES.block_size)) return encrypted def main(): random.seed(time.time()) encrypted_flag = encrypt_flag(open('./flag.txt').read()) print("\n✨ Welcome to the **Guess the Number Challenge v1**! ✨") print("🕵️‍♂️ Can you uncover the secret behind the encrypted flag?") print("📜 Use your intelligence, strategy, and the hints provided to succeed!") print("Your task: Use your wits and strategy to uncover hints to decrypt the flag.") print(f"\nHere is your encrypted flag: \n{encrypted_flag.hex()}") print("\nBut don't worry, I'm generous. I've precomputed 1000 random hints for you!") print(f"You have {MAX_ATTEMPTS} attempts to guess the right index.\n") hints = [random.getrandbits(32) for _ in range(1000)] for attempt in range(1, MAX_ATTEMPTS + 1): print(f"Attempt {attempt}/{MAX_ATTEMPTS}") try: index = int(input("Enter an index (0-999): ").strip()) if 0 <= index < 1000: print(f"🔑 Hint at index {index}: {hints[index]}") else: print("❌ Invalid index! Please enter a number between 0 and 999.\n") except ValueError: print("❌ Invalid input! Please enter a valid integer.\n") print("\n✨ Your attempts are over! But don't give up just yet.") print("✨ Your attempts are over! Good luck solving the challenge!\n") print("🔍 Don't forget: The key to solving the challenge lies in these random hints. Goodbye!") if __name__ == "__main__": main()
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/WeCTF/2021/Gallery/main.py
ctfs/WeCTF/2021/Gallery/main.py
import os import time import uuid from flask import Flask, request, make_response, render_template, redirect from google.cloud import storage from peewee import * db = SqliteDatabase("core.db") class User(Model): # mapping from user token to their background pic url id = AutoField() token = CharField() url = TextField() class Meta: database = db @db.connection_context() def initialize(): db.create_tables([User]) User.create(token=os.environ["ADMIN_TOKEN"], url=os.environ["FLAG_URL"]) initialize() app = Flask(__name__) os.environ["GOOGLE_APPLICATION_CREDENTIALS"] = "auth.json" # set up Google Cloud credentials CLOUD_STORAGE_BUCKET = "gallery-wectf21" # Google Cloud Storage bucket name DEFAULT_PIC = "/static/default.gif" CSP = "script-src 'nonce-%s'; connect-src 'self'; base-uri 'self'; object-src 'none'; frame-ancestors 'none'; " def uuid4() -> str: return str(uuid.uuid4()) @app.route('/') @db.connection_context() def index(): token = request.cookies.get("token") # get token from cookies if not token: token = uuid4() # user has no token, generate one for them nonce = uuid4() # generate a random nonce user_obj = User.select().where(User.token == token) resp = make_response(render_template("index.html", background=user_obj[-1].url if len(user_obj) > 0 else DEFAULT_PIC, nonce=nonce)) # render the template with background & CSP nonce resp.set_cookie("token", token) # set cookie to the token resp.headers['Content-Security-Policy'] = CSP % nonce # wanna be safe resp.headers['X-Frame-Options'] = 'DENY' # ensure no one is putting our site in iframe return resp def is_bad_content_type(content_type): return content_type and "html" in content_type # uploading a html picture? seriously? @app.route('/upload', methods=['POST']) @db.connection_context() def upload(): token = request.cookies.get("token") if not token: return redirect("/") # no token, go to home page uploaded_file = request.files.get('file') # the file uploaded by user if not uploaded_file: return 'No file uploaded.', 400 # dumbass user uploads nothing if is_bad_content_type(uploaded_file.content_type): return "Don't hack me :(", 400 # hacker uploading html gcs = storage.Client() # do some Google Cloud Storage bs copied from their docs bucket = gcs.get_bucket(CLOUD_STORAGE_BUCKET) blob = bucket.blob(uuid4() + uuid4()) # use uuid + uuid as file name blob.upload_from_string(uploaded_file.read(), content_type=uploaded_file.content_type) # upload it # get the signed url expiring in 1000min url = blob.generate_signed_url(expiration=int(time.time()) + 600000)\ .replace("https://storage.googleapis.com/gallery-wectf21/", "https://gallery-img-cdn.ctf.so/") User.create(token=token, url=url) return redirect("/") # go back home if __name__ == '__main__': app.run(host='127.0.0.1', port=8083, debug=True)
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/WeCTF/2021/CSP1/app.py
ctfs/WeCTF/2021/CSP1/app.py
import urllib.parse import uuid from flask import Flask, render_template, request, redirect, make_response from bs4 import BeautifulSoup as bs from peewee import * app = Flask(__name__) db = SqliteDatabase("core.db") class Post(Model): id = AutoField() token = CharField() content = TextField() class Meta: database = db @db.connection_context() def initialize(): db.create_tables([Post]) initialize() @app.route('/') def index(): return render_template("index.html") @app.route('/write', methods=["POST"]) def write(): content = request.form["content"] token = str(uuid.uuid4()) Post.create(token=token, content=content) return redirect("/display/" + token) def filter_url(urls): domain_list = [] for url in urls: domain = urllib.parse.urlparse(url).scheme + "://" + urllib.parse.urlparse(url).netloc if domain: domain_list.append(domain) return " ".join(domain_list) @app.route('/display/<token>') def display(token): user_obj = Post.select().where(Post.token == token) content = user_obj[-1].content if len(user_obj) > 0 else "Not Found" img_urls = [x['src'] for x in bs(content).find_all("img")] tmpl = render_template("display.html", content=content) resp = make_response(tmpl) resp.headers["Content-Security-Policy"] = "default-src 'none'; connect-src 'self'; img-src " \ f"'self' {filter_url(img_urls)}; script-src 'none'; " \ "style-src 'self'; base-uri 'self'; form-action 'self' " return resp 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/WeCTF/2021/Cache/manage.py
ctfs/WeCTF/2021/Cache/manage.py
#!/usr/bin/env python """Django's command-line utility for administrative tasks.""" import os import sys def main(): """Run administrative tasks.""" os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'cache.settings') try: from django.core.management import execute_from_command_line except ImportError as exc: raise ImportError( "Couldn't import Django. Are you sure it's installed and " "available on your PYTHONPATH environment variable? Did you " "forget to activate a virtual environment?" ) from exc execute_from_command_line(sys.argv) 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/WeCTF/2021/Cache/cache/asgi.py
ctfs/WeCTF/2021/Cache/cache/asgi.py
""" ASGI config for cache project. It exposes the ASGI callable as a module-level variable named ``application``. For more information on this file, see https://docs.djangoproject.com/en/3.2/howto/deployment/asgi/ """ import os from django.core.asgi import get_asgi_application os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'cache.settings') application = get_asgi_application()
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/WeCTF/2021/Cache/cache/settings.py
ctfs/WeCTF/2021/Cache/cache/settings.py
from pathlib import Path BASE_DIR = Path(__file__).resolve().parent.parent SECRET_KEY = 'django-insecure-p*sk-&$*0qb^j3@_b07a38kzus7d^&)-elk6rmoh1&__6yv^bf' DEBUG = True ALLOWED_HOSTS = ["*"] INSTALLED_APPS = [] MIDDLEWARE = [ 'cache.cache_middleware.SimpleMiddleware', ] ROOT_URLCONF = 'cache.urls' TEMPLATES = [] WSGI_APPLICATION = 'cache.wsgi.application' DATABASES = {} LANGUAGE_CODE = 'en-us' TIME_ZONE = 'UTC' USE_I18N = True USE_L10N = True USE_TZ = True STATIC_URL = '/static/' DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/WeCTF/2021/Cache/cache/__init__.py
ctfs/WeCTF/2021/Cache/cache/__init__.py
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/WeCTF/2021/Cache/cache/cache_middleware.py
ctfs/WeCTF/2021/Cache/cache/cache_middleware.py
import urllib.parse from django.http import HttpResponse, HttpRequest import time CACHE = {} # PATH => (Response, EXPIRE) class SimpleMiddleware: def __init__(self, get_response): self.get_response = get_response def __call__(self, request: HttpRequest): path = urllib.parse.urlparse(request.path).path if path in CACHE and CACHE[path][1] > time.time(): return CACHE[path][0] is_static = path.endswith(".css") or path.endswith(".js") or path.endswith(".html") response = self.get_response(request) if is_static: CACHE[path] = (response, time.time() + 10) return response
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/WeCTF/2021/Cache/cache/wsgi.py
ctfs/WeCTF/2021/Cache/cache/wsgi.py
""" WSGI config for cache 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/3.2/howto/deployment/wsgi/ """ import os from django.core.wsgi import get_wsgi_application os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'cache.settings') 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/WeCTF/2021/Cache/cache/urls.py
ctfs/WeCTF/2021/Cache/cache/urls.py
import os from django.urls import re_path from django.http import HttpResponse, HttpRequest FLAG = os.getenv("FLAG") ADMIN_TOKEN = os.getenv("ADMIN_TOKEN") def flag(request: HttpRequest): token = request.COOKIES.get("token") print(token, ADMIN_TOKEN) if not token or token != ADMIN_TOKEN: return HttpResponse("Only admin can view this!") return HttpResponse(FLAG) def index(request: HttpRequest): return HttpResponse("Not thing here, check out /flag.") urlpatterns = [ re_path('index', index), re_path('flag', flag) ]
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/WeCTF/2021/Phish/main.py
ctfs/WeCTF/2021/Phish/main.py
import os from flask import Flask, render_template, request from peewee import * app = Flask(__name__) db = SqliteDatabase("core.db") class User(Model): id = AutoField() password = CharField() username = CharField(unique=True) class Meta: database = db @db.connection_context() def initialize(): try: db.create_tables([User]) User.create(username="shou", password=os.getenv("FLAG")) except: pass initialize() @app.route("/") def index(): return render_template("index.html") @app.route("/add", methods=["POST"]) def add(): username = request.form["username"] password = request.form["password"] sql = f"INSERT INTO `user`(password, username) VALUES ('{password}', '{username}')" try: db.execute_sql(sql) except Exception as e: return f"Err: {sql} <br>" + str(e) return "Your password is leaked :)<br>" + \ """<blockquote class="imgur-embed-pub" lang="en" data-id="WY6z44D" ><a href="//imgur.com/WY6z44D">Please take care of your privacy</a></blockquote><script async src="//s.imgur.com/min/embed.js" charset="utf-8"></script> """ 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/WeCTF/2022/StatusPage/main.py
ctfs/WeCTF/2022/StatusPage/main.py
import os import time import uuid from datetime import datetime from flask import Flask, render_template, jsonify, request import psutil from influxdb import InfluxDBClient from multiprocessing import Process DB_NAME = "network" def network_stats(): return psutil.net_io_counters()._asdict() def get_conn(): return InfluxDBClient(host='localhost', port=8086) def push_stats(): client = get_conn() while True: json_body = [] for k, v in network_stats().items(): json_body.append({ "measurement": k, "tags": {}, "time": datetime.utcnow(), "fields": {"value": v} }) client.write_points(json_body, database=DB_NAME) time.sleep(3) def initialize(): client = get_conn() client.drop_database(DB_NAME) client.create_database(DB_NAME) def rand(): return "a" + str(uuid.uuid4()).replace("-", "")[:9] flag_db = rand() client.create_database(flag_db) client.write_points([{ "measurement": rand(), "tags": {}, "time": datetime.utcnow(), "fields": {"flag": os.getenv("flag")} }], database=flag_db) Process(target=push_stats, ).start() measurements = ["bytes_sent", "bytes_recv"] def get_measurement(minutes): results = [] client = get_conn() for db in measurements: result = client.query( f'SELECT MEAN("value") AS dp FROM "{db}" WHERE time > now() - {minutes}m GROUP BY time(1m)', database=DB_NAME ) if type(result) == list: return results if (db, None) in result.keys(): for item in result[(db, None)]: idx = measurements.index(db) if len(results) <= idx: results.append({"x": [], "y": [], "type": "scatter", "name": db}) results[idx]["x"].append(item["time"] if item["time"] else 0) results[idx]["y"].append(item["dp"] if item["dp"] else 0) return results app = Flask(__name__) @app.route("/q") def query(): minutes = request.args.get("minutes") return jsonify(get_measurement(minutes if minutes else 10)) @app.route("/") def index(): return render_template("index.html") initialize() app.run(port=80, 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/USC/2024/crypto/Its_Not_Called_Data_Loss_Prevention/handout.py
ctfs/USC/2024/crypto/Its_Not_Called_Data_Loss_Prevention/handout.py
from Crypto.Util.number import * p = 72582273207584409523836416205503873456840672244861668902068962428022358668644213717033410220094858213785909158082084409697781833525734642650576180002727864094178853739590888445753712196268567738582111704293273201721006648707008913242412196989487167851968618303659742648153352883917176492356546118351747721810800909873736282570227177961197335450387989276806079489 g = 3 FLAG = b"REDACTED" a = pow(g, bytes_to_long(FLAG), p) print(a) """ 24393771488717960431147269064624631828310604373526026598603386491263061338072489803153972728250242949112187407825532440328751180404635401465476512488685185622725060580628770654048867200033806585934697471249921972700552978079752695585970921337459580789152970187925768085334409084092041192304935279345047595337816976845617649400223935358270007572542969925561362228 """
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/USC/2024/crypto/unpopcorn/encoder.py
ctfs/USC/2024/crypto/unpopcorn/encoder.py
m = 57983 p = int(open("p.txt").read().strip()) def pop(s): return map(lambda x: ord(x)^42, s) def butter(s): return map(lambda x: x*p%m, s) def churn(s): l = list(map(lambda x: (x << 3), s)) return " ".join(map(lambda x: "{:x}".format(x).upper(), l[16:] + l[:16])) flag = open("flag.txt").read().strip() message = open("message.txt", "w") message.write(churn(butter(pop(flag)))) message.close()
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/ICHSA/2021/crypto/Crime_Cloud/source.py
ctfs/ICHSA/2021/crypto/Crime_Cloud/source.py
import base64 import os import zlib def rand(n): return os.urandom(n) def xor(a,b): return bytes(x^y for x,y in zip(a,b)) def enc_otp(pt): return xor(pt, rand(len(pt))) def process(req): pt = zlib.compress(b"ICHSA_CTF{fake_flag_to_annoy_you_pay_us_ten_thousand_BTC}" + rand(32) + req) return enc_otp(pt) def main(): print("Wellcome!\nInput an empty line to exit.") while True: req = input("\nYour input: ") if len(req) == 0: print("Bye!") break req_bytes = req.encode() if len(req_bytes) > 128: print(f'Bad input length {len(req_bytes)} > 128') continue print(base64.b64encode(process(req_bytes)).decode()) if __name__ == "__main__": try: main() except: print("Some error occured")
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/ICHSA/2021/crypto/Poodle2/poodle2.py
ctfs/ICHSA/2021/crypto/Poodle2/poodle2.py
from binascii import hexlify, unhexlify from Crypto.Cipher import AES from Crypto.Random import get_random_bytes from Crypto.Util.Padding import pad, unpad import sys, traceback def encrypt(msg, key): iv = get_random_bytes(AES.block_size) cipher = AES.new(key, AES.MODE_CBC, iv) return iv + cipher.encrypt(pad(msg, AES.block_size)) def decrypt(msg, key): iv = msg[:AES.block_size] cipher = AES.new(key, AES.MODE_CBC, iv) dec_msg = cipher.decrypt(msg[AES.block_size:]) return unpad(dec_msg, AES.block_size) welcome_text = """hi there! it's the oracle again :) ok ok, I promise to give you your poodle this time - not encrypted just send me the word: givemetheflag encrypted with my secret key that only I know >:) (add padding if needed of course... I know you can do it) """ tell_me = "\nWhat do you want to send me? ('nothing' to exit)\n>> " def main(): # load, encrypt and print the flag with open("flag.txt") as f: flag = f.read().strip().encode() with open("key.txt") as f: key = f.read().strip().encode() print(welcome_text) while(True): try: # get input and respond msg = input(tell_me) if msg == "nothing": print("bye bye") break # decrpyt the given message enc_msg = unhexlify(msg) dec_msg = decrypt(enc_msg, key) if b"givemetheflag" in dec_msg: print(f"nice work! {flag}") else: print("mmm... very interesting... thank you!") except ValueError: print("invalid padding >:(") except: traceback.print_exc(file=sys.stdout) sys.exit(1) if __name__ == "__main__": main()
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/ICHSA/2021/crypto/Baby_Homework/best_crypto_service.py
ctfs/ICHSA/2021/crypto/Baby_Homework/best_crypto_service.py
#!/usr/local/bin/python2 from Crypto.Cipher.AES import AESCipher import os, random, binascii from sys import argv import string import sys def padding(data): pad_size = 16 - (len(data) % 16) data = data + "".join([random.choice(string.printable) for _ in range(pad_size)]) return data def encrypt(data): return AESCipher(os.environ.get('KEY')).encrypt(padding(data)) def main(): print "Hello! What do you want to encrypt today?" sys.stdout.flush() user_input = raw_input() print binascii.hexlify(encrypt(user_input + os.environ.get('FLAG'))) sys.exit() if __name__ == '__main__': main()
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/ICHSA/2021/crypto/Poodle1/poodle1.py
ctfs/ICHSA/2021/crypto/Poodle1/poodle1.py
from binascii import hexlify, unhexlify from Crypto.Cipher import AES from Crypto.Random import get_random_bytes from Crypto.Util.Padding import pad, unpad import sys, traceback def encrypt(msg, key): iv = get_random_bytes(AES.block_size) cipher = AES.new(key, AES.MODE_CBC, iv) return iv + cipher.encrypt(pad(msg, AES.block_size)) def decrypt(msg, key): iv = msg[:AES.block_size] cipher = AES.new(key, AES.MODE_CBC, iv) dec_msg = cipher.decrypt(msg[AES.block_size:]) return unpad(dec_msg, AES.block_size) welcome_text = """hi there! I am the oracle :D searching for a poodle, huh? what about that cute and encrypted poodle? {} BTW, if you want to tell me something don't forget to encrypt it (with my secret key, of course ;)) """ tell_me = "\nWhat do you want to tell me? ('nothing' to exit)\n>> " def main(): # load, encrypt and print the flag with open("flag.txt") as f: flag = f.read().strip().encode() with open("key.txt") as f: key = f.read().strip().encode() enc_flag = hexlify(encrypt(flag, key)).decode() print(welcome_text.format(enc_flag)) while(True): try: # get input and respond msg = input(tell_me) if msg == "nothing": print("bye bye") break # decrpyt the given message enc_msg = unhexlify(msg) dec_msg = decrypt(enc_msg, key) print("mmm... very interesting... thank you!") except ValueError: print("invalid padding >:(") except: traceback.print_exc(file=sys.stdout) sys.exit(1) if __name__ == "__main__": main()
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/Tasteless/2021/crypto/crybaby/crybaby.py
ctfs/Tasteless/2021/crypto/crybaby/crybaby.py
#!/usr/bin/env python3 import os import sys # pip install cryptography from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes from cryptography.hazmat.primitives.ciphers.aead import AESGCM key = os.urandom(16) def from_user(msg): decryptor = Cipher(algorithms.AES(key), modes.CTR(nonce)).encryptor() return decryptor.update(msg) + decryptor.finalize() def to_user(msg): encryptor = Cipher(algorithms.AES(key), modes.CTR(nonce)).encryptor() return (encryptor.update(msg) + encryptor.finalize()) # administrators must sign all their messages def from_admin(msg): return AESGCM(key).decrypt(nonce, msg, associated_data=None) def to_admin(msg): return AESGCM(key).encrypt(nonce, msg, associated_data=None) print("cry baby cry") admin = False while True: nonce, msg = map(bytes.fromhex, sys.stdin.readline().split()) if not admin: cmd = from_user(msg) if cmd == b'adminplz': admin = True print(to_user(b'Login successful!').hex()) else: print(to_user(b'Unknown command!').hex()) else: cmd = from_admin(msg) if cmd == b'flagplz': with open('flag', 'rb') as f: print(to_admin(f.read()).hex()) else: print(to_admin(b'Unknown command!').hex())
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/Tasteless/2020/papple/adjust_image.py
ctfs/Tasteless/2020/papple/adjust_image.py
import os import mmap DEFAULT_FLAG = 'tstlss{XXXXXXXXXXXXXXXXXXXXXXXXXXXXX}' DEFAULT_IP = '133.133.133.133' ip = os.getenv('IP') flag = os.getenv('FLAG') if ip is None: print("Please specify an ip via the IP environment variable.") exit(-1) if len(ip) > len(DEFAULT_IP): print("Please specify an ip with less characters") exit(-1) if flag is not None and len(flag) > len(DEFAULT_FLAG): print("Please specify a flag with less characters") exit(-1) with open('/images/root.dsk', 'rw+b') as f: mapped_file = mmap.mmap(f.fileno(), 0) mapped_file.seek(mapped_file.find(DEFAULT_IP)) mapped_file.write(ip.ljust(len(DEFAULT_IP), '\x00')) if flag is not None: mapped_file.seek(mapped_file.find(DEFAULT_FLAG)) mapped_file.write(flag.ljust(len(DEFAULT_FLAG), '\x00'))
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/Tasteless/2020/movcode/chall.py
ctfs/Tasteless/2020/movcode/chall.py
#!/usr/bin/env python3 import re import sys import subprocess from time import sleep from shutil import rmtree from tempfile import TemporaryDirectory COMPILE_CMD = ['gcc', '-c', 'movcode.s'] LINK_CMD = ['ld', '-melf_x86_64', '-z', 'noexecstack', 'movcode.o'] RUN_CMD = ['setarch', 'x86_64', '-R', './a.out'] TEMPLATE = ''' .intel_syntax noprefix .text .globl _start _start: xor rcx, rcx mov rdx, 0x1000 mov rsp, 0x7ffffffff000 u_no_env: push rax dec rdx cmp rdx, 0x00 jnz u_no_env mov rsp, 0x7ffffffff000 {} mov rax, 1 syscall mov rdi, 0x42 mov rax, 0x3c syscall ''' class TastelessException(Exception): pass def print(string): for c in string: sys.stdout.write(c) sys.stdout.flush() sleep(.1) sys.stdout.write("\n") def create_assembly_file(dir): filter = re.compile(r'^mov\s[\w\[\],\s]*;?$') print("SHOW ME WHAT YOU GOT: \n") movcode = [] for line in sys.stdin: if (line == '\n'): break movcode += [line] for l in movcode: if filter.match(l) is None: raise TastelessException("THIS AINT NO MOVCODE!!!") with open('{}/movcode.s'.format(dir.name), 'w') as f: f.write( TEMPLATE.format( ''.join(movcode)) ) def compile_and_link(dir): if subprocess.run(COMPILE_CMD, cwd=dir.name).returncode: raise TastelessException("NO COMPILE.") if subprocess.run(LINK_CMD, cwd=dir.name).returncode: raise TastelessException("NO LINK.") def check_output(dir, output): movret = subprocess.run(RUN_CMD, cwd=dir.name, stdout=subprocess.PIPE, timeout=1, env={}) if movret.returncode != 0x42: raise TastelessException("Hmmm.... NOPE!") if movret.stdout != output: raise TastelessException("NOPE!") def give_flag(): print("GG. WE GIVE U FLAG: ") with open('flag.txt', 'r') as f: flag = f.read() print(flag) def main(): dir = TemporaryDirectory() try: create_assembly_file(dir) compile_and_link(dir) print("RUN ONCE ...") check_output(dir, b'TASTE') print("GOT RIGHT RESPONSE!\n") print("RUN TWICE ...") check_output(dir, b'LESS!') print("THAT WAS NICE!\n") give_flag() except TastelessException as e: print(e.args[0]) except Exception as e: print("WHAT AR U DOING?!?") 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/LedgerDonjon/2021/rev/braincool/client.py
ctfs/LedgerDonjon/2021/rev/braincool/client.py
import requests CHALLENGE_URL = "http://braincool.donjon-ctf.io:3200/apdu" def get_public_key(): req = requests.post(CHALLENGE_URL, data=bytes.fromhex("e005000000")) response = req.content if response[-2:] != b"\x90\x00": return None return response[:-2] public_key = get_public_key() assert public_key == bytes.fromhex("0494e92dd2a82e93d90c13322819db091a869c30c03c5a47d7b1f38683ba9bfdf33f44582dbd19e55e319ce5b2929fba6da9705c84df8c209441bcb713cf99c6d5d6e94445bc808e6821b73f3fa7d55b8a")
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/LedgerDonjon/2021/rev/puzzle/client.py
ctfs/LedgerDonjon/2021/rev/puzzle/client.py
import numpy as np import requests from binascii import hexlify url = "http://puzzle.donjon-ctf.io:7000" def send(dat): data = hexlify(bytes(dat, 'utf8')).decode() cmd = {'cmd' : 'send', 'data': data } x = requests.post(url, json = cmd) return x.json() if __name__ == "__main__": print(send("0\n1\n")["message"])
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/LedgerDonjon/2021/crypto/stellar-radiation-1/challenge/server.py
ctfs/LedgerDonjon/2021/crypto/stellar-radiation-1/challenge/server.py
#!/usr/bin/env python import os from aiohttp import web from stellar_sdk import ( Keypair, Account, TransactionBuilder, Asset, Network, TransactionEnvelope, ) from stellar_sdk.exceptions import BadSignatureError app = web.Application() routes = web.RouteTableDef() STELLAR_SECRET = os.environ.get("STELLAR_SECRET") FLAG = os.environ.get("FLAG") if STELLAR_SECRET is None or FLAG is None: raise EnvironmentError("Secrets are not set") # Disabled for now # @routes.post("/prepareorder") async def prepare_order(request: web.Request): data = await request.post() if "address" not in data: return web.Response(status=500, body="Missing destination address") keypair = Keypair.from_secret(STELLAR_SECRET) account = Account(account=keypair.public_key, sequence=1) transaction = ( TransactionBuilder( source_account=account, network_passphrase=Network.PUBLIC_NETWORK_PASSPHRASE, base_fee=100, ) .append_payment_op( data["address"], Asset("PIZZA", keypair.public_key), "1" ) .build() ) transaction.sign(keypair) return web.Response(body=transaction.to_xdr()) @routes.post("/submit") async def submit_transaction(request: web.Request): data = await request.post() if "tx" not in data: return web.Response(status=500, body="Missing tx") envelope = TransactionEnvelope.from_xdr( data["tx"], Network.PUBLIC_NETWORK_PASSPHRASE ) if len(envelope.signatures) != 1: return web.Response(status=500, body="Invalid envelope") keypair = Keypair.from_secret(STELLAR_SECRET) try: keypair.verify(envelope.hash(), envelope.signatures[0].signature) except BadSignatureError: return web.Response(status=500, body="Invalid signature") # server = Server(horizon_url="https://horizon.stellar.org") # response = server.submit_transaction(envelope) # return response["flag"] return web.Response(body=FLAG) @routes.get("/publickey") async def public_key(_: web.Request): keypair = Keypair.from_secret(STELLAR_SECRET) return web.Response(body=keypair.public_key) @routes.get("/") async def index(request): return web.FileResponse("./index.html") if __name__ == "__main__": app.add_routes(routes) web.run_app(app, port=25519)
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/LedgerDonjon/2021/crypto/magic-otp/app-otp/demo.py
ctfs/LedgerDonjon/2021/crypto/magic-otp/app-otp/demo.py
#!/usr/bin/env python3 """ Demo script that shows a setup of an OTP server with 2 OTP clients. The seed of the OTP server is known by the administrator. """ import base64 import bip32utils import mnemonic import os import struct import sys import time from cryptography.hazmat.backends import default_backend from cryptography.hazmat.primitives.asymmetric import ec from cryptography.hazmat.primitives import hashes, serialization from enum import IntEnum from speculos.client import ApduException, SpeculosClient SERVER_SEED = "lake essence common federal aisle amazing spend danger suspect barely verb try" CLIENT1_SEED = "wire solve theme picnic matter aunt light volcano time bright produce verify" CLIENT2_SEED = "entire dove rug stage garbage three elevator pair peace scrub convince monitor" class Cmd(IntEnum): GET_PUBKEY = 0x00 REGISTER_DEVICE = 0x01 GET_REGISTERED_DEVICE_PUBKEY = 0x02 ENCRYPT_OTP = 0x03 DECRYPT_OTP = 0x04 def get_private_key_(mnemonic_words, path): mobj = mnemonic.Mnemonic("english") seed = mobj.to_seed(mnemonic_words) bip32_child_key_obj = bip32utils.BIP32Key.fromEntropy(seed) for n in path: bip32_child_key_obj = bip32_child_key_obj.ChildKey(n) infos = { 'mnemonic_words': mnemonic_words, 'addr': bip32_child_key_obj.Address(), 'publickey': bip32_child_key_obj.PublicKey().hex(), 'privatekey': bip32_child_key_obj.WalletImportFormat(), } return bip32_child_key_obj.PrivateKey() def get_private_key(seed): H = bip32utils.BIP32_HARDEN path = [ H | 13, H | 37, H | 0, 0, 0 ] private_bytes = get_private_key_(seed, path) private_value = int.from_bytes(private_bytes, "big") private_key = ec.derive_private_key(private_value, ec.SECP256K1(), default_backend()) return private_key def get_pubkey(peer): data = peer.apdu_exchange(0, Cmd.GET_PUBKEY, b"") return data def get_encrypted_otp(server, n): epoch = int(time.time() / 30) payload = n.to_bytes(4, "little") payload += struct.pack('>q', epoch) data = server.apdu_exchange(0, Cmd.ENCRYPT_OTP, payload) return data def register_device(server, client): private_key = get_private_key(SERVER_SEED) pubkey = get_pubkey(client) pubkey = pubkey.rjust(65, b"\x00") assert len(pubkey) == 65 signature = private_key.sign(pubkey, ec.ECDSA(hashes.SHA256())) assert len(signature) <= 73 print(f"[*] registering client with pubkey {pubkey.hex()}") payload = pubkey + signature.ljust(73, b"\x00") + len(signature).to_bytes(4, "little") data = server.apdu_exchange(0, Cmd.REGISTER_DEVICE, payload) def decrypt_otp(server, client, data): pubkey = get_pubkey(server) assert len(data) == 32 payload = pubkey.rjust(65, b"\x00") + data return client.apdu_exchange(0, Cmd.DECRYPT_OTP, payload) if __name__ == "__main__": # run the OTP server with SpeculosClient("bin/app-server.elf", ["--seed", SERVER_SEED]) as server: # run 2 OTP clients with SpeculosClient("bin/app-client.elf", ["--seed", CLIENT1_SEED, "--api-port", "7000", "--apdu-port", "7001"], api_url="http://127.0.0.1:7000") as client1: with SpeculosClient("bin/app-client.elf", ["--seed", CLIENT2_SEED, "--api-port", "7002", "--apdu-port", "7003"], api_url="http://127.0.0.1:7002") as client2: # register the client devices on the server register_device(server, client1) register_device(server, client2) for i, client in enumerate([client1, client2]): # ask the server for an OTP for the client i encrypted_otp = get_encrypted_otp(server, i) print(f"[*] encrypted OTP: {encrypted_otp.hex()}") # decrypt it otp = decrypt_otp(server, client, encrypted_otp) otp = otp.replace(b"\x00", b'').decode("ascii") print(f"[*] OTP: {otp}")
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/LedgerDonjon/2021/crypto/magic-otp/challenge/app.py
ctfs/LedgerDonjon/2021/crypto/magic-otp/challenge/app.py
#!/usr/bin/env python3 import base64 import hashlib import hmac import json import os import struct import sys import time from flask import Flask, jsonify, request, send_from_directory, stream_with_context, Response from flask_limiter import Limiter from flask_limiter.util import get_remote_address import device app = Flask(__name__, static_url_path="/assets/", static_folder="data/assets/") limiter = Limiter(app, key_func=get_remote_address) def time_now(): return time.time() def get_otp_secret(): otp_secret = os.environ.get("OTP_SECRET") if not otp_secret: print("OTP_SECRET environment variable is unset", file=sys.stderr) sys.exit(1) return base64.b64decode(otp_secret) def check_otp(otp): otp_secret = get_otp_secret() # a new OTP is generated every 30 seconds epoch = int(time_now() / 30) # OTPs are valid during 1 minute for epoch_offset in range(0, 2): value = struct.pack('>q', epoch - epoch_offset) hmac_hash = hmac.new(otp_secret, value, hashlib.sha256).digest() offset = hmac_hash[-1] & 0x0F truncated_hash = hmac_hash[offset:offset + 4] truncated_hash = struct.unpack('>L', truncated_hash)[0] truncated_hash &= 0x7FFFFFFF if otp == f"{truncated_hash:010d}": return True return False def device_response(callback, **kwargs): """ Stream the response since the communication with the device is not instant. It prevents concurrent HTTP requests from being blocked. """ def generate_device_response(callback, **kwargs): # force headers to be sent yield b"" # generate reponse yield json.dumps(callback(**kwargs)).encode() return Response(stream_with_context(generate_device_response(callback, **kwargs)), content_type="application/json") @limiter.limit("10/minute") @app.route("/api/get_flag", methods=["POST"]) def get_flag(): content = request.get_json(force=True, silent=True) if content is None or "otp" not in content: return jsonify({"error": "missing otp"}) if not check_otp(content["otp"]): return jsonify({"error": "invalid otp"}) flag = os.environ.get("FLAG", "CTF{FLAG environment variable is unset}") return jsonify({"message": f"Congratulation! Here's the flag: {flag}."}) @app.route("/api/get_encrypted_otp", methods=["POST"]) def get_encrypted_otp(): content = request.get_json(force=True, silent=True) if content is None or "deviceid" not in content: return jsonify({"error": "missing device id"}) def callback(request, deviceid): epoch = int(time_now() / 30) try: encrypted_otp = device.get_encrypted_otp(request, epoch, deviceid) except device.DeviceError as e: return {"error": f"failed to generate encrypted otp: {e}"} return {"encrypted_otp": encrypted_otp} return device_response(callback, request=request, deviceid=content["deviceid"]) @app.route("/api/get_server_pubkey", methods=["GET"]) def get_server_pubkey(): def callback(request): pubkey = device.get_server_pubkey(request) return {"pubkey": pubkey.hex()} return device_response(callback, request=request) @app.route("/api/list_registered_devices", methods=["GET"]) def list_registered_devices(): def callback(request): pubkeys = device.list_registered_devices(request) return {"pubkeys": [pubkey.hex() for pubkey in pubkeys]} return device_response(callback, request=request) @app.route("/", methods=['GET']) def index(): return send_from_directory("data/assets/", "index.html") if __name__ == "__main__": tls_cert = os.path.join(os.path.dirname(__file__), "data/https.pem") app.run(host="0.0.0.0", port=9000, threaded=True, use_reloader=False, ssl_context=(tls_cert, tls_cert))
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/LedgerDonjon/2021/crypto/fine--fine-/challenge/client.py
ctfs/LedgerDonjon/2021/crypto/fine--fine-/challenge/client.py
import numpy as np import requests from binascii import hexlify url = 'http://fine-fine.donjon-ctf.io:6000' def send_getpubkey(data): cmd = {'cmd' : 'getpubkey', 'data': data } x = requests.post(url, json = cmd) if x.headers["content-type"] == "application/octet-stream": trace = np.frombuffer(x.content, dtype=np.uint16) return trace else: return x.json() if __name__ == "__main__": print(send_getpubkey("aa"*64)) r = send_getpubkey("6b17d1f2e12c4247f8bce6e563a440f277037d812deb33a0f4a13945d898c2964fe342e2fe1a7f9b8ee7eb4a7c0f9e162bce33576b315ececbb6406837bf51f5") # this is secp256r1's basepoint
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/LedgerDonjon/2021/crypto/stellar-radiation-2/challenge/server.py
ctfs/LedgerDonjon/2021/crypto/stellar-radiation-2/challenge/server.py
#!/usr/bin/env python import os import string from aiohttp import web from stellar_sdk import ( Keypair, Account, TransactionBuilder, Asset, Network, TransactionEnvelope, ) from stellar_sdk.exceptions import BadSignatureError app = web.Application() routes = web.RouteTableDef() STELLAR_SECRET = os.environ.get("STELLAR_SECRET") FLAG = os.environ.get("FLAG") if STELLAR_SECRET is None or FLAG is None: raise EnvironmentError("Secrets are not set") # Disabled for now # @routes.post("/prepareorder") async def prepare_order(request: web.Request): data = await request.post() if "address" not in data: return web.Response(status=500, body="Missing destination address") keypair = Keypair.from_secret(STELLAR_SECRET) account = Account(account=keypair.public_key, sequence=1) transaction = ( TransactionBuilder( source_account=account, network_passphrase=Network.PUBLIC_NETWORK_PASSPHRASE, base_fee=100, ) .append_payment_op( data["address"], Asset("PIZZA", keypair.public_key), "1" ) .build() ) transaction.sign(keypair) return web.Response(body=transaction.to_xdr()) @routes.post("/submit") async def submit_transaction(request: web.Request): data = await request.post() if "tx" not in data: return web.Response(status=500, body="Missing tx") envelope = TransactionEnvelope.from_xdr( data["tx"], Network.PUBLIC_NETWORK_PASSPHRASE ) if len(envelope.signatures) != 1: return web.Response(status=500, body="Invalid envelope") keypair = Keypair.from_secret(STELLAR_SECRET) try: keypair.verify(envelope.hash(), envelope.signatures[0].signature) except BadSignatureError: return web.Response(status=500, body="Invalid signature") # server = Server(horizon_url="https://horizon.stellar.org") # response = server.submit_transaction(envelope) # return response["flag"] return web.Response(body=FLAG) MAX_PROOF_SIZE = 32 MAX_TRIES = 30 @routes.post("/publickey") async def public_key(request: web.Request): data = await request.post() public_keys = set() # Detect Stellar radiations for _ in range(MAX_TRIES): public_keys.add(Keypair.from_secret(STELLAR_SECRET).public_key) if len(public_keys) > 1: return web.Response(status=500) sk = Keypair.from_secret(STELLAR_SECRET).signing_key if "proof" in data: # Sign a short "proof" message so that client can verify public key is valid, # in case previous check was not enough. # Proof must be short, printable messages. proof = data["proof"] if len(proof) > MAX_PROOF_SIZE or not all(c in string.printable for c in proof): return web.Response(status=500, body="Invalid proof requested") signed_message = sk.sign(proof.encode()) return web.json_response( { "public_key": public_keys.pop(), "signature": signed_message.signature.hex(), } ) else: return web.json_response({"public_key": public_keys.pop()}) @routes.get("/") async def index(request): return web.FileResponse("./index.html") if __name__ == "__main__": app.add_routes(routes) web.run_app(app, port=25520)
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/LedgerDonjon/2021/crypto/virtual-public-network/placeholder/app.py
ctfs/LedgerDonjon/2021/crypto/virtual-public-network/placeholder/app.py
#!/usr/bin/env python3 from flask import Flask import os app = Flask(__name__) #insert your challenge here, only accessible through the vpn ! @app.route("/", methods=['GET']) def index(): return "Hello World, the flag is %s" % os.environ.get("FLAG") if __name__ == "__main__": app.run(host="0.0.0.0", port=8000)
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false
sajjadium/ctf-archives
https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/LedgerDonjon/2020/ghostbuster/ghostbuster/network/ssh-isolation.py
ctfs/LedgerDonjon/2020/ghostbuster/ghostbuster/network/ssh-isolation.py
#!/usr/bin/python3 -EIs """ Give a different UID to each SSH connection. Not meant to be secure, just prevent different users from messing with each other (there is nothing to see here.) """ import logging import os import re import shutil import sys MIN_UID = 3000 MAX_UID = 3100 WORKDIR = "/tmp/ghostbuster" def drop_privileges(uid, gid): os.setgroups([]) os.setgid(gid) os.setuid(uid) os.umask(0o77) def remove_user(uid): logger.info(f"removing user {uid}") shutil.rmtree(f"{WORKDIR}/{uid}/") os.remove(f"{WORKDIR}/{uid}.user") def create_user(uid, gid, ssh_connection): logger.info(f"adding user {uid}") # raises an FileExistsError if the file already exists with open(f"{WORKDIR}/{uid}.user", "x") as fp: fp.write(ssh_connection) tmpdir = f"{WORKDIR}/{uid}" os.makedirs(tmpdir, 0o700, True) os.chown(tmpdir, uid, gid) def reuse_connection(connected, ssh_connection): for dirname in os.listdir(WORKDIR): if not re.match("^[0-9]+\.user$", dirname): continue uid = int(os.path.splitext(dirname)[0]) # remove disconnected users if uid not in connected: remove_user(uid) continue with open(f"{WORKDIR}/{uid}.user") as fp: connection = fp.read() if connection == ssh_connection: logger.info(f"reusing connection {ssh_connection} for uid {uid}") return uid return -1 def pick_user(connected, ssh_connection): """Pick an available user""" uids = set(range(MIN_UID, MAX_UID)) - set(connected) if not uids: logger.error("no uid available") sys.exit(1) uid = sorted(uids)[0] try: create_user(uid, uid, ssh_connection) except FileExistsError: connected.append(uid) return pick_user(connected, ssh_connection) return uid def connected_uids(): """Return a list of connected users.""" # walk /proc/ to retrieve running processes uids = set([]) for pid in os.listdir("/proc/"): if not re.match("^[0-9]+$", pid): continue try: uid = os.stat(f"/proc/{pid}").st_uid except FileNotFoundError: continue if uid in range(MIN_UID, MAX_UID): uids.add(uid) return list(uids) def new_connection(ssh_connection): connected = connected_uids() logger.info(f"connected users: {connected}") uid = reuse_connection(connected, ssh_connection) if uid == -1: uid = pick_user(connected, ssh_connection) drop_privileges(uid, gid=uid) tmpdir = f"{WORKDIR}/{uid}" os.chdir(tmpdir) os.putenv("HOME", "/home/ghostbuster") os.putenv("USER", "ghostbuster") try: os.symlink("/home/ghostbuster/challenge.sh", os.path.join(tmpdir, "challenge.sh")) except FileExistsError: pass if "SSH_ORIGINAL_COMMAND" in os.environ: args = [ "bash", "-c", os.environ["SSH_ORIGINAL_COMMAND"] ] else: args = [ "bash" ] logger.info(f"executing {args}") os.execv("/bin/bash", args) if __name__ == '__main__': logging.basicConfig(level=logging.WARNING) logger = logging.getLogger("ssh-isolation") if not os.path.exists(WORKDIR): os.mkdir(WORKDIR, 0o711) if "SSH_CONNECTION" not in os.environ: logger.critical("environment variable SSH_CONNECTION is not set") sys.exit(1) new_connection(os.environ["SSH_CONNECTION"])
python
MIT
129a3a9fe604443211fa4d493a49630c30689df7
2026-01-05T01:34:13.869332Z
false