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/CakeCTF/2022/web/openbio/service/app.py | ctfs/CakeCTF/2022/web/openbio/service/app.py | import base64
import flask
from flask_wtf.csrf import CSRFProtect
import hashlib
import json
import os
import re
import redis
import requests
REDIS_HOST = os.getenv('REDIS_HOST', 'redis')
REDIS_PORT = int(os.getenv('REDIS_PORT', 6379))
RECAPTCHA_KEY = os.getenv('RECAPTCHA_KEY', '')
SALT = os.getenv('SALT', os.urandom(8))
app = flask.Flask(__name__)
app.secret_key = os.urandom(16)
csrf = CSRFProtect(app)
"""
Utility functions
"""
def login_ok():
"""Check if the current user is logged in"""
return 'user' in flask.session
def conn_user():
"""Create a connection to user database"""
return redis.Redis(host=REDIS_HOST, port=REDIS_PORT, db=0)
def conn_report():
"""Create a connection to report database"""
return redis.Redis(host=REDIS_HOST, port=REDIS_PORT, db=1)
def success(message):
"""Return a success message"""
return flask.jsonify({'status': 'success', 'message': message})
def error(message):
"""Return an error message"""
return flask.jsonify({'status': 'error', 'message': message})
def passhash(password):
"""Get a safe hash value of password"""
return hashlib.sha256(SALT + password.encode()).hexdigest()
"""
Enforce CSP
"""
@app.after_request
def after_request(response):
csp = ""
csp += "default-src 'none';"
if 'csp_nonce' in flask.g:
csp += f"script-src 'nonce-{flask.g.csp_nonce}' https://cdn.jsdelivr.net/ https://www.google.com/recaptcha/ https://www.gstatic.com/recaptcha/ 'unsafe-eval';"
else:
csp += f"script-src https://cdn.jsdelivr.net/ https://www.google.com/recaptcha/ https://www.gstatic.com/recaptcha/ 'unsafe-eval';"
csp += f"style-src https://cdn.jsdelivr.net/;"
csp += f"frame-src https://www.google.com/recaptcha/ https://recaptcha.google.com/recaptcha/;"
csp += f"base-uri 'none';"
csp += f"connect-src 'self';"
response.headers['Content-Security-Policy'] = csp
return response
@app.context_processor
def csp_nonce_init():
flask.g.csp_nonce = base64.b64encode(os.urandom(16)).decode()
return dict(csp_nonce=flask.g.csp_nonce)
"""
Route
"""
@app.route('/')
def home():
if login_ok():
conn = conn_user()
bio = conn.hget(flask.session['user'], 'bio').decode()
if bio is not None:
return flask.render_template('index.html',
username=flask.session['user'], bio=bio)
return flask.render_template('login.html')
@app.route('/profile/<user>')
def profile(user):
if not login_ok():
return flask.redirect(flask.url_for('home'))
is_report = flask.request.args.get('report') is not None
conn = conn_user()
if not conn.exists(user):
return flask.redirect(flask.url_for('home'))
bio = conn.hget(user, 'bio').decode()
return flask.render_template('profile.html',
username=user, bio=bio,
is_report=is_report)
"""
User API
"""
@app.route('/api/user/register', methods=['POST'])
def user_register():
"""Register a new user"""
# Check username and password
username = flask.request.form.get('username', '')
password = flask.request.form.get('password', '')
if re.match("^[-a-zA-Z0-9_]{5,20}$", username) is None:
return error("Username must follow regex '^[-a-zA-Z0-9_]{5,20}$'")
if re.match("^.{8,128}$", password) is None:
return error("Password must follow regex '^.{8,128}$'")
# Register a new user
conn = conn_user()
if conn.exists(username):
return error("This username has been already taken.")
else:
conn.hset(username, mapping={
'password': passhash(password),
'bio': "<p>Hello! I'm new to this website.</p>"
})
flask.session['user'] = username
return success("Successfully registered a new user.")
@app.route('/api/user/login', methods=['POST'])
def user_login():
"""Login user"""
if login_ok():
return success("You have already been logged in.")
username = flask.request.form.get('username', '')
password = flask.request.form.get('password', '')
# Check password
conn = conn_user()
if conn.hget(username, 'password').decode() == passhash(password):
flask.session['user'] = username
return success("Successfully logged in.")
else:
return error("Invalid password or user does not exist.")
@app.route('/api/user/logout', methods=['POST'])
def user_logout():
"""Logout user"""
if login_ok():
flask.session.clear()
return success("Successfully logged out.")
else:
return error("You are not logged in.")
@app.route('/api/user/update', methods=['POST'])
def user_update():
"""Update user info"""
if not login_ok():
return error("You are not logged in.")
username = flask.session['user']
bio = flask.request.form.get('bio', '')
if len(bio) > 2000:
return error("Bio is too long.")
# Update bio
conn = conn_user()
conn.hset(username, 'bio', bio)
return success("Successfully updated your profile.")
"""
Report spam account
"""
@app.route('/api/support/report', methods=['POST'])
def report():
"""Report spam
Support staff will check the reported contents as soon as possible.
"""
if RECAPTCHA_KEY:
recaptcha = flask.request.form.get('recaptcha', '')
params = {
'secret': RECAPTCHA_KEY,
'response': recaptcha
}
r = requests.get(
"https://www.google.com/recaptcha/api/siteverify", params=params
)
if json.loads(r.text)['success'] == False:
abort(400)
username = flask.request.form.get('username', '')
conn = conn_user()
if not conn.exists(username):
return error("This user does not exist.")
conn = conn_report()
conn.rpush('report', username)
return success("""Thank you for your report.<br>Our support team will check the post as soon as possible.""")
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/GCC/2024/misc/Diabolical_Grumpy_Analyst/challenge.py | ctfs/GCC/2024/misc/Diabolical_Grumpy_Analyst/challenge.py | #!/usr/bin/env python3
print("Loading data... Can take 1-2 minutes")
import warnings
warnings.filterwarnings("ignore", category=DeprecationWarning)
import numpy as np
import random
import pandas as pd
import json
from secret import FLAG
with open("other_dataset_dga.txt", 'r') as file:
content = file.read()
dga_domains = content.split("\n")
with open("other_dataset_legit.txt", 'r') as file:
content = file.read()
legit_domains = content.split("\n")
df = pd.DataFrame()
df['domain'] = random.sample(dga_domains, 5000)
df['dga'] = 1
df_ = pd.DataFrame()
df_['domain'] = random.sample(legit_domains, 5000)
df_['dga'] = 0
df = pd.concat([df, df_], axis=0)
df.reset_index(drop=True, inplace=True)
df = df.reindex(np.random.permutation(df.index))
count = 0
for i in range(0,10000,100):
print("Here is a new batch of domains : ")
print(f"{{ 'domains' : {list(df.iloc[i:i+100]['domain'])} }}")
result = input("Enter your analysis - Respect this format : { \"labels\" : [1,0,0,1...] } - With 1 for dga and 0 for legit : ").strip()
try:
labels = json.loads(result)["labels"]
except json.decoder.JSONDecodeError:
print("Format error !!")
exit()
for j in range(i,i+100):
try :
if labels[j%100] == df.iloc[j]['dga']:
count += 1
except IndexError:
print("List index out of range")
exit()
if count > 8500:
print(f"You're a very good analyst. Here is your flag : {FLAG}")
else:
print(f"You blocked too many legit domains or didn't block enough malicious domains. Here is your count {count} Try again !")
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/GCC/2024/misc/Legerdemain/auto_chall.py | ctfs/GCC/2024/misc/Legerdemain/auto_chall.py | # YAPAMS, Yet Another Pyjail Automated Making Script
# Author: Shy
# Desc.: Setup a basic pyjail with parameters and special pre-setup code you can set
## π SET YOUR PARAMETERS HERE π
p = {
# Filter testing
"banned words": ["get","any","all","print","in","char","or","and","len","flag"],
"banned chars": '_-+.0123456789\\o',
"max length": 18,
"ban unicode": True,
# Main setup
"is prod": True,
"use audithook": False,
"use debugger": False,
"use backups": False,
# Vars
"globals backup": globals(),
"builtins backup": __builtins__,
"vars": [],
# Debug
"debug extra": True,
"debug list": ["onion"],
"debug text": "",
}
## π SET YOUR PARAMETERS HERE π
## Load dependencies
if p["use audithook"]: import sys
if p["use debugger"]: import pdb
## Flag reading
flag = open('./flag.txt', 'r').read() # read flag ...
with open('./flag.txt', 'w') as f: f.write('' if p["is prod"] else flag) # ... and shred flag :)
## π WRITE YOUR OWN SPECIAL VARS SETUP HERE π
def chall_init():
while len(p["vars"])<len(flag): p["vars"].append([])
for i,c in enumerate(flag): p["vars"][i] = c
## π WRITE YOUR OWN SPECIAL VARS SETUP HERE π
TITLE="""
::::::::: ::: ::: ::::::::::: ::: ::::::::::: ::: ::: ::: ::: ::: ::: :::::::::: :::::::::
:+: :+: :+: :+: :+: :+: :+: :+: :+: :+:+: :+:+: :+: :+: :+: :+: :+: :+: :+:
+:+ +:+ +:+ +:+ +:+ +:+ +:+ +:+ +:+ +:+ +:+:+ +:+ +:+ +:+ +:+ +:+ +:+ +:+ +:+
+#++:++#+ +#++: +#+ +#++:++#++: +#+ +#+ +#+ +:+ +#+ +#++:++#++: +#++:++ +#++:++# +#++:++#:
+#+ +#+ +#+ +#+ +#+ +#+ +#+ +#+ +#+ +#+ +#+ +#+ +#+ +#+ +#+ +#+
#+# #+# #+# #+# #+# #+# #+# #+# #+# #+# #+# #+# #+# #+# #+# #+# #+#
### ### ##### ### ### ########### ########## ### ### ### ### ### ### ########## ### ###
"""
CHOICES="""
1- Test input and filters
2- See debug helper
3- Launch pyjail
4- Quit
"""
if __name__=="__main__":
print(TITLE)
while True:
print(CHOICES)
choice = input(">>>").strip()
match choice:
case "1":
inp = input("Test your instruction chief!\n>>> ")
if p["ban unicode"] and any(map(lambda x:ord(x)>128, inp)): inp = "print('gotcha!')"
if len(inp)>p["max length"] or any(bw in inp for bw in p["banned words"]) or any(bc in inp for bc in p["banned chars"]): inp = "print('gotcha!')"
try:
exec(inp)
except:
print("WARNING: Bypass possible ! (or just a bad payload...)")
case "2":
print(p["debug text"])
for dbv in p["debug list"]: print(' -', dbv)
case "3":
chall_init()
# Debug
if p["debug extra"]:
print(p["debug text"])
for dbv in p["debug list"]: print(' -', dbv)
# Launch challenge
from challenge import chall
chall(banned_words=p["banned words"],
banned_chars=p["banned chars"],
globals_=(p["globals backup"] if p["use backups"] else []),
builtins_=(p["builtins backup"] if p["use backups"] else {}),
vars_=p["vars"],
info={"logging":p["debug extra"]})
case "4":
exit()
case _:
print("???")
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/GCC/2024/crypto/SuperAES/chall.py | ctfs/GCC/2024/crypto/SuperAES/chall.py | import random
from Crypto.Cipher import AES
import time
import os
from flag import flag
m = 288493873028852398739253829029106548736
a = int(time.time())
b = a%16
s = random.randint(1,m-1)
class LCG:
def __init__(self, a, b, m, seed):
self.a = a
self.b = b
self.m = m
self.state = seed
self.counter = 0
def next_state(self):
ret = self.state
self.state = (self.a * self.state + self.b) % self.m
return ret
class SuperAES:
def __init__(self,key,lcg):
self.aes = AES.new(key,AES.MODE_ECB)
self.lcg = lcg
def encrypt(self,plaintext):
ciphertext = b""
for i in range(0,len(plaintext),16):
ciphertext += self.encrypt_block(plaintext[i:i+16])
return ciphertext
def encrypt_block(self,block):
keystream = self.aes.encrypt(int(self.lcg.next_state()).to_bytes(16,"big"))
return bytes([k^b for k,b in zip(keystream,block)])
assert len(flag) == 33
assert flag.startswith(b"GCC{")
key = os.urandom(32)
cipher = SuperAES(key,LCG(a,b,m,s))
times = int(input("how many times do you want the flag ?"))
assert times < 50
print(cipher.encrypt(flag*times).hex()) | python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/GCC/2024/crypto/GCC_News/app.py | ctfs/GCC/2024/crypto/GCC_News/app.py | from flask import Flask, render_template, request, redirect, url_for, jsonify
import hashlib
import base64
import json
import time
import random
import hashlib
from Crypto.Util.number import bytes_to_long, isPrime
import math
app = Flask(__name__)
def hash_string_sha256(message):
message_bytes = message.encode('utf-8')
sha256_hash = hashlib.sha256()
sha256_hash.update(message_bytes)
hashed_message = sha256_hash.digest()
return int.from_bytes(hashed_message, byteorder='big')
def generate_signature(message, private_key):
n, d = private_key
hashed_message = hash_string_sha256(message)
signature = pow(hashed_message, d, n)
return signature
def verify_signature(msg, public_key, signature):
initial_hash = hash_string_sha256(msg)
n, e = public_key
recoved_hash = pow(int(signature),e,n)
return initial_hash == recoved_hash
@app.route('/')
def welcome():
return render_template('welcome.html')
@app.route('/login', methods=['POST'])
def login():
username = request.form.get('username')
password = request.form.get('password')
# Check if the user exists
if username not in users:
return redirect(url_for('login', reason='unknown_user'))
# Check if the password is correct
if password != users[username][0]:
return redirect(url_for('login', reason='incorrect_password'))
public_key, private_key = generate_key(username)
public_key_users[username] = public_key
signature = generate_signature(str({username : [users[username][1]]}), private_key)
return redirect(url_for('news', token=signature, message=base64.b64encode(str({username : [users[username][1]]}).encode()).decode()))
@app.route('/news', methods=['GET'])
def news():
signature = request.args.get('token')
message = base64.b64decode(request.args.get('message')).decode()
message = json.loads(message.replace("'", '"').replace("False", "false").replace("True", "true"))
username = list(message.keys())[0]
subscribe = list(message.values())[0][0]
if signature:
is_sign = verify_signature(str(message), public_key_users[username], signature)
if is_sign:
return render_template('news.html', username=username, subscribe=subscribe)
return redirect(url_for('login', reason='unauthorized'))
@app.route('/login', methods=['GET'])
def show_login():
# Extract the reason from the query parameters
reason = request.args.get('reason')
# Display a pop-up message based on the reason
if reason == 'unknown_user':
pop_up_message = "Unknown user. Please check your credentials."
elif reason == 'incorrect_password':
pop_up_message = "Incorrect password. Please try again."
elif reason == 'unauthorized':
pop_up_message = "Unauthorized access. Please log in."
else:
pop_up_message = None
return render_template('login.html', pop_up_message=pop_up_message)
@app.route('/create_user', methods=['POST'])
def create_user():
new_username = request.form.get('new_username')
new_password = request.form.get('new_password')
# Check if the username already exists
if new_username in users:
return redirect(url_for('login', reason='username_exists'))
# Add the new user to the dictionary
users[new_username] = [new_password, False]
# Display a pop-up message
pop_up_message = "Thanks for registering! The admin will soon activate your profile if you have subscribed."
return render_template('login.html', pop_up_message=pop_up_message)
def generate_key(username):
length = lambda x : len(bin(x)[2:])
s = bytes_to_long(username.encode())
random.seed(s)
e = 0x1001
phi = 0
while math.gcd(phi,e) != 1:
n = 1
factors = []
while length(n) < 2048:
temp_n = random.getrandbits(48)
if isPrime(temp_n):
n *= temp_n
factors.append(temp_n)
phi = 1
for f in factors:
phi *= (f - 1)
d = pow(e, -1, phi)
return (n,e), (n,d)
# A simple dictionary to store user credentials and subscription status
users = {
'GCC': ['securePassword', False]
}
public_key_users = {}
if __name__ == '__main__':
app.run(debug=False)
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/GCC/2024/crypto/Too_Many_Leaks/chall.py | ctfs/GCC/2024/crypto/Too_Many_Leaks/chall.py | #!/usr/bin/env python3
from Crypto.Util.number import getStrongPrime
import hashlib
from secret import flag
import os
from Crypto.Cipher import AES
from Crypto.Util.Padding import pad
def encrypt_flag(secret_key):
sha1 = hashlib.sha1()
sha1.update(str(secret_key).encode('ascii'))
key = sha1.digest()[:16]
iv = os.urandom(16)
cipher = AES.new(key, AES.MODE_CBC, iv)
ciphertext = cipher.encrypt(pad(flag,16))
print("{ ciphertext : " + ciphertext.hex() + ", iv : " + iv.hex() + "}")
return ciphertext, iv
# Generate parameters
p = getStrongPrime(512)
print(f"{p=}")
g = 2
# Alice calculates the public key A
a = getStrongPrime(512)
A = pow(g,a,p)
print(f"{A=}")
# Bob calculates the public key B
b = getStrongPrime(512)
B = pow(g,b,p)
print(f"{B=}")
# Calculate the secret key
s = pow(B,a,p)
# What ?!
mask = ((1 << 256) - 1 << 256) + (1 << 255)
r1 = s & mask
print(f"{r1=}")
# Charlie arrives and sync with Alice and Bob
c = getStrongPrime(512)
print(f"{c=}")
AC = pow(g,a+c,p)
s2 = pow(AC,b,p)
print(f"{AC=}")
r2 = s2 & mask
print(f"{r2=}")
encrypt_flag(s)
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/OFPPT/2022/pwn/trickster/game.py | ctfs/OFPPT/2022/pwn/trickster/game.py | import pygame
from random import randrange
from time import sleep
from binascii import unhexlify
abc = b'4142434445464748494a4b4c4d4e4f505152535455565758595a6162636465666768696a6b6c6d6e6f707172737475767778797a31323' \
b'3343536373839305f2d7b7d'
pygame.init()
class Game:
def __init__(self, dW, dH, caption):
self.dW = dW
self.dH = dH
self.alpha = abc
self.hidden = b'666c61677b6a6b5f6e6f745f7468655f7265616c5f666c61677d'
self.gD = pygame.display.set_mode((dW, dH))
self.caption = caption
self.clock = pygame.time.Clock()
self.pause_text = ('Continue', 'Quit')
self.font = 'rkill.ttf'
self.text_small = 20
self.text_large = 115
class Colors:
def __init__(self):
self.colors = {
'black': (0, 0, 0),
'white': (255, 255, 255),
'block': (116, 77, 37),
'red': (255, 0, 0),
'green': (0, 255, 0),
'blue': (0, 0, 255),
'button': (130, 130, 130),
'button_hover': (200, 200, 200),
'button_click': (75, 75, 75),
'bg': (0, 0, 126),
'grey': (1, 1, 1)
}
class Sprite:
def __init__(self, img, imgL, imgR):
self.img = pygame.image.load(img)
self.imgL = pygame.image.load(imgL)
self.imgR = pygame.image.load(imgR)
class Button:
def __init__(self, text, color, color_hover, color_click, bX, bY, bW, bH, action=None):
self.text = text
self.color = color
self.color_hover = color_hover
self.color_click = color_click
self.bX = bX
self.bY = bY
self.bW = bW
self.bH = bH
class Enemy:
def __init__(self, eX, speed, count):
self.eX = eX
self.eY = -600
self.speed = speed
self.eW = 100
self.eH = 100
self.count = count
class Msg:
def __init__(self):
self.alpha = b'4142434445464748494a4b4c4d4e4f505152535455565758595a6162636465666768696a6b6c6d6e6f70717273747' \
b'5767778797a313233343536373839305f2d7b7d'
def prnt(self, message):
msg = str()
for i in message:
msg += u(self.alpha)[i]
return msg
def u(n):
return unhexlify(n).decode('utf-8')
def close_game():
pygame.quit()
quit()
def text_objects(text, font):
text_surface = font.render(text, True, (255, 255, 255))
return text_surface, text_surface.get_rect()
def draw_button(text, color, color_hover, color_click, bX, bY, bW, bH, action=None):
mouse_pos = pygame.mouse.get_pos()
mouse_click = pygame.mouse.get_pressed()
if (bX + bW) > mouse_pos[0] > bX and (bY + bH) > mouse_pos[1] > bY:
pygame.draw.rect(gD, color_hover, (bX, bY, bW, bH))
if mouse_click[0] == 1 and action != None:
action()
else:
pygame.draw.rect(gD, color, (bX, bY, bW, bH))
text_surf, text_rec = text_objects(text, pygame.font.Font(game.font, 20))
text_rec.center = ((bX + (bW / 2)), (bY + (bH / 2)))
gD.blit(text_surf, text_rec)
def escaped(count):
font = pygame.font.SysFont(None, 25)
text = font.render(u(b'446f646765643a20') + str(count), True, color.colors['white'])
gD.blit(text, (0, 0))
def show_msg(text):
text_surf, text_rec = text_objects(text, pygame.font.Font(game.font, 115))
text_rec.center = ((game.dW / 2), (game.dH / 2))
gD.blit(text_surf, text_rec)
pygame.display.update()
sleep(2)
gameloop()
def do_coll():
show_msg(u(b'44656174682764'))
def check_border(cX, cY, cW, cH):
if cX > game.dW - (cW / 2):
return ((game.dW - (cW / 2)), cY)
elif cX < 0 - (cX / 2):
return ((0 - (cX / 2)), cY)
if cY > game.dH - (cH / 1.5):
return (cX, (game.dH - (cH / 1.5)))
elif cY < 0 - (cH / 4):
return (cX, (0 - (cH / 4)))
def get_intersect(x1, x2, w1, w2, y1, y2, h1):
if y1 < (y2 + h1):
if x1 > x2 and x1 < (x2 + w2) or (x1 + w1) > x2 and (x1 + w1) < (x2 + w2):
do_coll()
def spawn_enemy(eX, eY):
gD.blit(enemy.img, (eX, eY))
def spawn_player(pX, pY):
gD.blit(player.img, (pX, pY))
def game_unpause():
global pause
pause = False
def game_pause():
while pause:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
quit()
game.gD.fill((0, 0, 26))
text_large = pygame.font.Font(game.font, 115)
text_surf, text_rec = text_objects("Paused", text_large)
text_rec.center = ((game.dW / 2), (game.dH / 2))
gD.blit(text_surf, text_rec)
draw_button(game.pause_text[0], color.colors['button'], color.colors['button_hover'],
color.colors['button_click'], (game.dW / 4 - 100), (game.dH / 1.25 - 25), 200, 50, game_unpause)
draw_button(game.pause_text[1], color.colors['button'], color.colors['button_hover'],
color.colors['button_click'], (game.dW / 1.3 - 100), (game.dH / 1.25 - 25), 200, 50, close_game)
pygame.display.update()
game.clock.tick()
def set_pref():
return str(f'{b.prnt([14, 5, 15, 15, 19])}')
def gs():
gs_ = [64, 2, 26, 13, 19, 62, 28, 33, 54, 55, 45, 62, 29, 54, 55, 45, 33, 65]
print(f"{set_pref()}{b.prnt(gs_)}")
def game_intro():
intro = True
while intro:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
quit()
gD.fill(color.colors['bg'])
font_sizes = {'large': 72, 'medium': 32}
text_large = pygame.font.Font(game.font, font_sizes['large'])
text_medium = pygame.font.Font(game.font, font_sizes['medium'])
text_surf, text_rec = text_objects(game.caption, text_large)
text_rec.center = ((game.dW / 2), (game.dH / 2))
gD.blit(text_surf, text_rec)
draw_button('GO!', color.colors['button'], color.colors['button_hover'], color.colors['button_click'],
(game.dW / 4 - 100), (game.dH / 1.25 - 25), 200, 50, gameloop)
draw_button('Quit', color.colors['button'], color.colors['button_hover'], color.colors['button_click'],
(game.dW / 1.3 - 100), (game.dH / 1.25 - 25), 200, 50, close_game)
pygame.display.update()
game.clock.tick(15)
def gameloop():
global pause
x = game.dW * 0.45
y = game.dH * 0.85
xchange = 0
ychange = 0
enemy = Enemy(eX=randrange(0, game.dW), speed=4, count=1)
gss, gf = 0, 0
game_exit = False
while not game_exit:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
quit()
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_p:
pause = True
game_pause()
if event.key == pygame.K_LEFT:
xchange = -5
elif event.key == pygame.K_RIGHT:
xchange = 5
elif event.key == pygame.K_UP:
ychange = -2
elif event.key == pygame.K_DOWN:
ychange = 5
if event.type == pygame.KEYUP:
if event.key == pygame.K_LEFT or event.key == pygame.K_RIGHT:
xchange = 0
if event.key == pygame.K_UP or event.key == pygame.K_DOWN:
ychange = 0
x += xchange
y += ychange
gD.fill(color.colors['bg'])
spawn_enemy(enemy.eX, enemy.eY)
enemy.eY += enemy.speed
spawn_player(x, y)
escaped(gss)
if enemy.eY > game.dH:
enemy.eY = 0 - enemy.eH
enemy.eX = randrange(0, game.dW)
gss += 0x1
gf = gss
enemy.speed += 1
if gf > (5 * 20):
gf = (25 * 4)
game.pause_text = gs()
pause = True
if x > game.dW - (player.img.get_rect().size[0] / 2):
x = game.dW - (player.img.get_rect().size[0] / 2)
elif x < 0 - (player.img.get_rect().size[0] / 2):
x = 0 - (player.img.get_rect().size[0] / 2)
if y > game.dH - (player.img.get_rect().size[1] / 2):
y = game.dH - (player.img.get_rect().size[1] / 2)
elif y < 0 - (player.img.get_rect().size[1] / 4):
y = 0 - (player.img.get_rect().size[1] / 4)
get_intersect(x, enemy.eX, player.img.get_rect().size[0], enemy.eW, y, enemy.eY, enemy.eH)
pygame.display.update()
game.clock.tick(60)
# MAIN
b = Msg()
print(b.prnt([31, 37, 26, 32, 64]))
game = Game(dW=800, dH=600, caption='Trick or Treat')
player = Sprite('img/player.png', 'img/player.png', 'img/player.png')
enemy = Sprite('img/enemy.png', 'img/enemy.png', 'img/enemy.png')
pygame.display.set_caption(game.caption)
player_sprite = pygame.image.load('img/player.png')
pygame_gs = (game.dW, game.dH, player_sprite.get_rect().size[0], player_sprite.get_rect().size[1])
pause = True
a = u(abc)
gD = pygame.display.set_mode((game.dW, game.dH))
color = Colors()
game_intro()
gameloop()
pygame.quit()
quit()
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/OFPPT/2022/crypto/MeetMeInMiddle/challenge.py | ctfs/OFPPT/2022/crypto/MeetMeInMiddle/challenge.py | from random import randint
from Crypto.Cipher import AES
from Crypto.Util.Padding import pad
import json
flag = b'OFPPT-CTF{Not_the_real_flag}'
def gen_key(option=0):
alphabet = b'0123456789abcdef'
const = b'0fpptCTF5!@#'
key = b''
for i in range(16-len(const)):
key += bytes([alphabet[randint(0,15)]])
if option:
return key + const
else:
return const + key
def encrypt(data, key1, key2):
cipher = AES.new(key1, mode=AES.MODE_ECB)
ct = cipher.encrypt(pad(data, 16))
cipher = AES.new(key2, mode=AES.MODE_ECB)
ct = cipher.encrypt(ct)
return ct.hex()
def challenge():
k1 = gen_key()
k2 = gen_key(1)
ct = encrypt(flag, k1, k2)
print('Super strong encryption service approved by 2022 stansdards.\n'+\
'Message to decrypt:\n' +ct + '\nEncrypt your text:\n> ')
try:
dt = json.loads(input().strip())
pt = bytes.fromhex(dt['pt'])
res = encrypt(pt, k1, k2)
print(res + '\n')
exit(1)
except Exception as e:
print(e)
print('Invalid payload.\n')
exit(1)
if __name__ == "__main__":
challenge()
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/OFPPT/2022/crypto/XOR/honey.py | ctfs/OFPPT/2022/crypto/XOR/honey.py | import os
FLAG = b'OFPPT-CTF{...REDACTED...}'
class HoneyComb:
def __init__(self, key):
self.vals = [i for i in key]
def turn(self):
self.vals = [self.vals[-1]] + self.vals[:-1]
def encrypt(self, msg):
keystream = []
while len(keystream) < len(msg):
keystream += self.vals
self.turn()
return bytes([msg[i] ^ keystream[i] for i in range(len(msg))]).hex()
hc = HoneyComb(os.urandom(6))
print(hc.encrypt(FLAG))
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/OFPPT/2022/crypto/RSASmall/beezy.py | ctfs/OFPPT/2022/crypto/RSASmall/beezy.py | #! /usr/bin/env python3
from Crypto.PublicKey import RSA
from Crypto.Util.number import bytes_to_long, long_to_bytes
key = RSA.generate(4096, e = 5)
msg = b"Congrats! Your flag is: OFPPT-CTF{XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX}."
m = bytes_to_long(msg)
print("e = ".format(key.e))
print("n = ".format(key.n))
c = pow(m, key.e, key.n)
print("c = ".format(c))
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/DEADFACE/2023/prog/Dead_Drop/deaddrop.py | ctfs/DEADFACE/2023/prog/Dead_Drop/deaddrop.py | # Password recovery:
# buA9kvZ=T_A}b[J8l:@ob_tviPZtb_<olOpxkvZ=T_=xju]olOpxkvZ=T_bxlu]olOpxkvZ=QIEE
arr = ['empty', 'interest', 'current', 'valuable', 'influence', 'from', 'scolded', 'would', 'got', 'key', 'facility', 'run', 'great', 'tack', 'scent', 'close', 'are', 'a', 'plan', 'counter', 'earth', 'self', 'we', 'sick', 'return', 'admit', 'bear', 'cache', 'to', 'grab', 'domination', 'feedback', 'especially', 'motivate', 'tool', 'world', 'phase', 'semblance', 'tone', 'is', 'will', 'the', 'can', 'global', 'tell', 'box', 'alarm', 'life', 'necessary']
def print_password(nums):
if len(nums) < 1:
print("Must provide a list of at least one number i.e. [1]")
print("flag{{{}}}".format(" ".join([arr[num] for num in nums])))
def left_shift(s, n):
return ''.join(chr(ord(char) - n) for char in s) | python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/RealWorld/2021/JunkAV/wrap.py | ctfs/RealWorld/2021/JunkAV/wrap.py | import subprocess
from hashlib import sha256
import string
import random
import base64
import os
import signal
import sys
import time
MAX_FILE_SIZE = 1024 * 1024 * 8
WORK_PATH = b'/home/ctf/check/'
def rand_str(length):
return ''.join(random.choice(string.ascii_letters) for i in range(length)).encode('latin1')
def get_choice():
choic = input('> Continue (Y/N)\n')
if choic == "N" or choic == "n":
exit(0)
elif choic == "Y" or choic == 'y':
return
else:
exit(0)
def get_file():
data = input('> Upload the file (base64)\n')
try:
data = base64.b64decode(data)
if (len(data) > MAX_FILE_SIZE):
raise Exception("The uploaded file is too large (MAX: {:#x}".format(MAX_FILE_SIZE))
name = WORK_PATH + teamtoken.encode('latin1') + b'_' + str(int(time.time())).encode('latin1') + rand_str(20)
with open(name, 'wb') as f:
f.write(data)
except Exception as e :
print(e)
exit(1)
return name
def run_junkav():
get_choice()
fname = get_file().decode('latin1')
subprocess.run(['/home/ctf/junkav','/home/ctf/rules/all-yara.yar', fname], stderr=subprocess.STDOUT, timeout=3)
return
if __name__ == '__main__':
if len(sys.argv) == 2:
global teamtoken
teamtoken = sys.argv[1]
signal.alarm(50)
try:
print("You have 10 chances to check your file\n")
for i in range(10):
run_junkav()
except Exception as e :
print(e)
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/RealWorld/2024/blockchain/SafeBridge/challenge.py | ctfs/RealWorld/2024/blockchain/SafeBridge/challenge.py | from typing import Dict
from eth_abi import abi
from ctf_launchers.pwn_launcher import PwnChallengeLauncher
from ctf_launchers.types import (DaemonInstanceArgs, LaunchAnvilInstanceArgs,
UserData, get_additional_account,
get_privileged_web3)
from ctf_launchers.utils import (anvil_setCodeFromFile, anvil_setStorageAt,
deploy)
class Challenge(PwnChallengeLauncher):
def get_anvil_instances(self) -> Dict[str, LaunchAnvilInstanceArgs]:
return {
"l1": self.get_anvil_instance(chain_id=78704, accounts=3, fork_url=None),
"l2": self.get_anvil_instance(chain_id=78705, accounts=3, fork_url=None),
}
def get_daemon_instances(self) -> Dict[str, DaemonInstanceArgs]:
return {"relayer": DaemonInstanceArgs(image="safe-bridge-relayer:latest")}
def deploy(self, user_data: UserData, mnemonic: str) -> str:
l1_web3 = get_privileged_web3(user_data, "l1")
l2_web3 = get_privileged_web3(user_data, "l2")
challenge = deploy(
l1_web3,
self.project_location,
mnemonic=mnemonic,
env={
"L1_RPC": l1_web3.provider.endpoint_uri,
"L2_RPC": l2_web3.provider.endpoint_uri,
},
)
anvil_setCodeFromFile(
l2_web3,
"0x420000000000000000000000000000000000CAFe",
"L2CrossDomainMessenger.sol:L2CrossDomainMessenger",
)
relayer = get_additional_account(mnemonic, 0)
anvil_setStorageAt(
l2_web3,
"0x420000000000000000000000000000000000CAFe",
hex(0),
"0x" + relayer.address[2:].rjust(64, "0"),
)
default_xdomain_sender = "0x000000000000000000000000000000000000dEaD"
anvil_setStorageAt(
l2_web3,
"0x420000000000000000000000000000000000CAFe",
hex(5),
"0x" + default_xdomain_sender[2:].rjust(64, "0"),
)
anvil_setCodeFromFile(
l2_web3,
"0x420000000000000000000000000000000000baBe",
"L2ERC20Bridge.sol:L2ERC20Bridge",
)
l2messenger_addr = "0x420000000000000000000000000000000000CAFe"
(l1_bridge_addr,) = abi.decode(
["address"],
l1_web3.eth.call(
{
"to": challenge,
"data": l1_web3.keccak(text="BRIDGE()")[:4].hex(),
}
),
)
anvil_setStorageAt(
l2_web3,
"0x420000000000000000000000000000000000baBe",
hex(0),
"0x" + l2messenger_addr[2:].rjust(64, "0"),
)
anvil_setStorageAt(
l2_web3,
"0x420000000000000000000000000000000000baBe",
hex(1),
"0x" + l1_bridge_addr[2:].rjust(64, "0"),
)
anvil_setCodeFromFile(
l2_web3,
"0xDeadDeAddeAddEAddeadDEaDDEAdDeaDDeAD0000",
"L2WETH.sol:L2WETH",
)
return challenge
Challenge().run()
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/RealWorld/2024/blockchain/SafeBridge/relayer.py | ctfs/RealWorld/2024/blockchain/SafeBridge/relayer.py | import json
import os
import time
import traceback
from threading import Thread
import requests
from eth_abi import abi
from web3 import Web3
from web3.contract.contract import Contract
from web3.middleware.signing import construct_sign_and_send_raw_middleware
from ctf_launchers.types import (UserData, get_additional_account,
get_unprivileged_web3)
ORCHESTRATOR = os.getenv("ORCHESTRATOR_HOST", "http://orchestrator:7283")
INSTANCE_ID = os.getenv("INSTANCE_ID")
class Relayer:
def __init__(self):
self.__required_properties = ["mnemonic", "challenge_address"]
def start(self):
while True:
instance_body = requests.get(
f"{ORCHESTRATOR}/instances/{INSTANCE_ID}"
).json()
if instance_body["ok"] == False:
raise Exception("oops")
user_data = instance_body["data"]
if any(
[v not in user_data["metadata"] for v in self.__required_properties]
):
time.sleep(1)
continue
break
self._run(user_data)
def _run(self, user_data: UserData):
challenge_addr = user_data["metadata"]["challenge_address"]
relayer = get_additional_account(user_data["metadata"]["mnemonic"], 0)
l1 = get_unprivileged_web3(user_data, "l1")
l1.middleware_onion.add(construct_sign_and_send_raw_middleware(relayer))
l1.eth.default_account = relayer.address
l2 = get_unprivileged_web3(user_data, "l2")
l2.middleware_onion.add(construct_sign_and_send_raw_middleware(relayer))
l2.eth.default_account = relayer.address
(l1_messenger_addr,) = abi.decode(
["address"],
l1.eth.call(
{
"to": l1.to_checksum_address(challenge_addr),
"data": l1.keccak(text="MESSENGER()")[:4].hex(),
}
),
)
l2_messenger_addr = "0x420000000000000000000000000000000000CAFe"
with open(
"/artifacts/out/CrossDomainMessenger.sol/CrossDomainMessenger.json", "r"
) as f:
cache = json.load(f)
messenger_abi = cache["metadata"]["output"]["abi"]
l1_messenger = l1.eth.contract(
address=l1.to_checksum_address(l1_messenger_addr), abi=messenger_abi
)
l2_messenger = l2.eth.contract(
address=l2.to_checksum_address(l2_messenger_addr), abi=messenger_abi
)
Thread(
target=self._relayer_worker, args=(l1, l1_messenger, l2_messenger)
).start()
Thread(
target=self._relayer_worker, args=(l2, l2_messenger, l1_messenger)
).start()
def _relayer_worker(
self, src_web3: Web3, src_messenger: Contract, dst_messenger: Contract
):
_src_chain_id = src_web3.eth.chain_id
_last_processed_block_number = 0
while True:
try:
latest_block_number = src_web3.eth.block_number
if _last_processed_block_number > latest_block_number:
_last_processed_block_number = latest_block_number
print(
f"chain {_src_chain_id} syncing {_last_processed_block_number + 1} {latest_block_number}"
)
for i in range(
_last_processed_block_number + 1, latest_block_number + 1
):
_last_processed_block_number = i
logs = src_messenger.events.SentMessage().get_logs(
fromBlock=i, toBlock=i
)
for log in logs:
print(f"chain {_src_chain_id} got log {src_web3.to_json(log)}")
try:
tx_hash = dst_messenger.functions.relayMessage(
log.args["target"],
log.args["sender"],
log.args["message"],
log.args["messageNonce"],
).transact()
dst_messenger.w3.eth.wait_for_transaction_receipt(tx_hash)
print(
f"chain {_src_chain_id} relay message hash: {tx_hash.hex()} src block number: {i}"
)
time.sleep(1)
except Exception as e:
print(e)
except:
traceback.print_exc()
pass
finally:
time.sleep(1)
Relayer().start()
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/RealWorld/2024/blockchain/SafeBridge/ctf_launchers/pwn_launcher.py | ctfs/RealWorld/2024/blockchain/SafeBridge/ctf_launchers/pwn_launcher.py | import os
import requests
from eth_abi import abi
from ctf_launchers.launcher import ORCHESTRATOR_HOST, Action, Launcher
from ctf_launchers.team_provider import TeamProvider, get_team_provider
from ctf_launchers.types import UserData, get_privileged_web3
FLAG = os.getenv("FLAG", "rwctf{flag}")
class PwnChallengeLauncher(Launcher):
def __init__(
self,
project_location: str = "challenge/project",
provider: TeamProvider = get_team_provider(),
):
super().__init__(
project_location,
provider,
[
Action(name="get flag", handler=self.get_flag),
],
)
def get_flag(self) -> int:
instance_body = requests.get(
f"{ORCHESTRATOR_HOST}/instances/{self.get_instance_id()}"
).json()
if not instance_body["ok"]:
print(instance_body["message"])
return 1
user_data = instance_body["data"]
if not self.is_solved(user_data, user_data["metadata"]["challenge_address"]):
print("are you sure you solved it?")
return 1
print(FLAG)
return 0
def is_solved(self, user_data: UserData, addr: str) -> bool:
web3 = get_privileged_web3(user_data, "l1")
(result,) = abi.decode(
["bool"],
web3.eth.call(
{
"to": addr,
"data": web3.keccak(text="isSolved()")[:4],
}
),
)
return result
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/RealWorld/2024/blockchain/SafeBridge/ctf_launchers/launcher.py | ctfs/RealWorld/2024/blockchain/SafeBridge/ctf_launchers/launcher.py | import abc
import os
import traceback
from dataclasses import dataclass
from typing import Callable, Dict, List
import requests
from eth_account.hdaccount import generate_mnemonic
from ctf_launchers.team_provider import TeamProvider
from ctf_launchers.types import (CreateInstanceRequest, DaemonInstanceArgs,
LaunchAnvilInstanceArgs, UserData,
get_player_account, get_privileged_web3)
from ctf_launchers.utils import deploy
CHALLENGE = os.getenv("CHALLENGE", "challenge")
ORCHESTRATOR_HOST = os.getenv("ORCHESTRATOR_HOST", "http://orchestrator:7283")
PUBLIC_HOST = os.getenv("PUBLIC_HOST", "http://127.0.0.1:8545")
ETH_RPC_URL = os.getenv("ETH_RPC_URL")
TIMEOUT = int(os.getenv("TIMEOUT", "1440"))
@dataclass
class Action:
name: str
handler: Callable[[], int]
class Launcher(abc.ABC):
def __init__(
self, project_location: str, provider: TeamProvider, actions: List[Action] = []
):
self.project_location = project_location
self.__team_provider = provider
self._actions = [
Action(name="launch new instance", handler=self.launch_instance),
Action(name="kill instance", handler=self.kill_instance),
] + actions
def run(self):
self.team = self.__team_provider.get_team()
if not self.team:
exit(1)
self.mnemonic = generate_mnemonic(12, lang="english")
for i, action in enumerate(self._actions):
print(f"{i+1} - {action.name}")
try:
handler = self._actions[int(input("action? ")) - 1]
except:
print("can you not")
exit(1)
try:
exit(handler.handler())
except Exception as e:
traceback.print_exc()
print("an error occurred", e)
exit(1)
def get_anvil_instances(self) -> Dict[str, LaunchAnvilInstanceArgs]:
return {
"main": self.get_anvil_instance(),
}
def get_daemon_instances(self) -> Dict[str, DaemonInstanceArgs]:
return {}
def get_anvil_instance(self, **kwargs) -> LaunchAnvilInstanceArgs:
if not "balance" in kwargs:
kwargs["balance"] = 1000
if not "accounts" in kwargs:
kwargs["accounts"] = 2
if not "fork_url" in kwargs:
kwargs["fork_url"] = ETH_RPC_URL
if not "mnemonic" in kwargs:
kwargs["mnemonic"] = self.mnemonic
return LaunchAnvilInstanceArgs(
**kwargs,
)
def get_instance_id(self) -> str:
return f"chal-{CHALLENGE}-{self.team}".lower()
def update_metadata(self, new_metadata: Dict[str, str]):
resp = requests.post(
f"{ORCHESTRATOR_HOST}/instances/{self.get_instance_id()}/metadata",
json=new_metadata,
)
body = resp.json()
if not body["ok"]:
print(body["message"])
return 1
def launch_instance(self) -> int:
print("creating private blockchain...")
body = requests.post(
f"{ORCHESTRATOR_HOST}/instances",
json=CreateInstanceRequest(
instance_id=self.get_instance_id(),
timeout=TIMEOUT,
anvil_instances=self.get_anvil_instances(),
daemon_instances=self.get_daemon_instances(),
),
).json()
if body["ok"] == False:
raise Exception(body["message"])
user_data = body["data"]
print("deploying challenge...")
challenge_addr = self.deploy(user_data, self.mnemonic)
self.update_metadata(
{"mnemonic": self.mnemonic, "challenge_address": challenge_addr}
)
print()
print(f"your private blockchain has been set up")
print(f"it will automatically terminate in {TIMEOUT} minutes")
print(f"---")
print(f"rpc endpoints:")
for id in user_data["anvil_instances"]:
print(f" - {PUBLIC_HOST}/{user_data['external_id']}/{id}")
print(f"private key: {get_player_account(self.mnemonic).key.hex()}")
print(f"challenge contract: {challenge_addr}")
return 0
def kill_instance(self) -> int:
resp = requests.delete(
f"{ORCHESTRATOR_HOST}/instances/{self.get_instance_id()}"
)
body = resp.json()
print(body["message"])
return 1
def deploy(self, user_data: UserData, mnemonic: str) -> str:
web3 = get_privileged_web3(user_data, "main")
return deploy(
web3,
self.project_location,
mnemonic,
env=self.get_deployment_args(user_data),
)
def get_deployment_args(self, user_data: UserData) -> Dict[str, str]:
return {}
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/RealWorld/2024/blockchain/SafeBridge/ctf_launchers/team_provider.py | ctfs/RealWorld/2024/blockchain/SafeBridge/ctf_launchers/team_provider.py | import abc
import os
from hashlib import md5
from typing import Optional
import requests
class TeamProvider(abc.ABC):
@abc.abstractmethod
def get_team(self) -> Optional[str]:
pass
class LocalTeamProvider(TeamProvider):
def __init__(self, team_id):
self.__team_id = team_id
def get_team(self):
return self.__team_id
class RemoteTeamProvider(TeamProvider):
def __init__(self, rw_api_token):
self.__rw_api_token = rw_api_token
def get_team(self):
team_id = self.__check(input("team token? "))
if not team_id:
print("invalid team token!")
return None
return team_id
def __check(self, token: str) -> str:
response = requests.get(
"https://realworldctf.com/api/team/info",
headers={"token": self.__rw_api_token},
timeout=8,
)
json = response.json()
assert json["msg"] == "success"
try:
for team in json["data"]:
if team["hash"] == md5(token.encode()).hexdigest():
return team["hash"]
except Exception as e:
print(e)
return None
def get_team_provider() -> TeamProvider:
rw_api_token = os.getenv("API_TOKEN")
if rw_api_token:
return RemoteTeamProvider(rw_api_token)
else:
return LocalTeamProvider(team_id="local")
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/RealWorld/2024/blockchain/SafeBridge/ctf_launchers/utils.py | ctfs/RealWorld/2024/blockchain/SafeBridge/ctf_launchers/utils.py | import json
import os
import subprocess
from typing import Dict
from web3 import Web3
from web3.types import RPCResponse
def deploy(
web3: Web3,
project_location: str,
mnemonic: str,
deploy_script: str = "script/Deploy.s.sol:Deploy",
env: Dict = {},
) -> str:
anvil_autoImpersonateAccount(web3, True)
rfd, wfd = os.pipe2(os.O_NONBLOCK)
proc = subprocess.Popen(
args=[
"/opt/foundry/bin/forge",
"script",
"--rpc-url",
web3.provider.endpoint_uri,
"--out",
"/artifacts/out",
"--cache-path",
"/artifacts/cache",
"--broadcast",
"--unlocked",
"--sender",
"0x0000000000000000000000000000000000000000",
deploy_script,
],
env={
"PATH": "/opt/foundry/bin:/usr/bin:" + os.getenv("PATH", "/fake"),
"MNEMONIC": mnemonic,
"OUTPUT_FILE": f"/proc/self/fd/{wfd}",
}
| env,
pass_fds=[wfd],
cwd=project_location,
text=True,
encoding="utf8",
stdin=subprocess.DEVNULL,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
)
stdout, stderr = proc.communicate()
anvil_autoImpersonateAccount(web3, False)
if proc.returncode != 0:
print(stdout)
print(stderr)
raise Exception("forge failed to run")
result = os.read(rfd, 256).decode("utf8")
os.close(rfd)
os.close(wfd)
return result
def anvil_setCodeFromFile(
web3: Web3,
addr: str,
target: str, # "ContractFile.sol:ContractName",
):
file, contract = target.split(":")
with open(f"/artifacts/out/{file}/{contract}.json", "r") as f:
cache = json.load(f)
bytecode = cache["deployedBytecode"]["object"]
anvil_setCode(web3, addr, bytecode)
def check_error(resp: RPCResponse):
if "error" in resp:
raise Exception("rpc exception", resp["error"])
def anvil_autoImpersonateAccount(web3: Web3, enabled: bool):
check_error(web3.provider.make_request("anvil_autoImpersonateAccount", [enabled]))
def anvil_setCode(web3: Web3, addr: str, bytecode: str):
check_error(web3.provider.make_request("anvil_setCode", [addr, bytecode]))
def anvil_setStorageAt(
web3: Web3,
addr: str,
slot: str,
value: str,
):
check_error(web3.provider.make_request("anvil_setStorageAt", [addr, slot, value]))
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/RealWorld/2024/blockchain/SafeBridge/ctf_launchers/__init__.py | ctfs/RealWorld/2024/blockchain/SafeBridge/ctf_launchers/__init__.py | python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false | |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/RealWorld/2024/blockchain/SafeBridge/ctf_launchers/types.py | ctfs/RealWorld/2024/blockchain/SafeBridge/ctf_launchers/types.py | from typing import Dict, NotRequired, Optional, TypedDict
from eth_account import Account
from eth_account.account import LocalAccount
from eth_account.hdaccount import key_from_seed, seed_from_mnemonic
from web3 import Web3
DEFAULT_DERIVATION_PATH = "m/44'/60'/0'/0/"
class LaunchAnvilInstanceArgs(TypedDict):
image: NotRequired[Optional[str]]
accounts: NotRequired[Optional[int]]
balance: NotRequired[Optional[float]]
derivation_path: NotRequired[Optional[str]]
mnemonic: NotRequired[Optional[str]]
fork_url: NotRequired[Optional[str]]
fork_block_num: NotRequired[Optional[int]]
fork_chain_id: NotRequired[Optional[int]]
no_rate_limit: NotRequired[Optional[bool]]
chain_id: NotRequired[Optional[int]]
code_size_limit: NotRequired[Optional[int]]
class DaemonInstanceArgs(TypedDict):
image: str
class CreateInstanceRequest(TypedDict):
instance_id: str
timeout: int
anvil_instances: NotRequired[Dict[str, LaunchAnvilInstanceArgs]]
daemon_instances: NotRequired[Dict[str, DaemonInstanceArgs]]
class InstanceInfo(TypedDict):
id: str
ip: str
port: int
class UserData(TypedDict):
instance_id: str
external_id: str
created_at: float
expires_at: float
anvil_instances: Dict[str, InstanceInfo]
daemon_instances: Dict[str, InstanceInfo]
metadata: Dict
def get_account(mnemonic: str, offset: int) -> LocalAccount:
seed = seed_from_mnemonic(mnemonic, "")
private_key = key_from_seed(seed, f"{DEFAULT_DERIVATION_PATH}{offset}")
return Account.from_key(private_key)
def get_player_account(mnemonic: str) -> LocalAccount:
return get_account(mnemonic, 0)
def get_additional_account(mnemonic: str, offset: int) -> LocalAccount:
return get_account(mnemonic, offset + 2)
def get_privileged_web3(user_data: UserData, anvil_id: str) -> Web3:
anvil_instance = user_data["anvil_instances"][anvil_id]
return Web3(
Web3.HTTPProvider(f"http://{anvil_instance['ip']}:{anvil_instance['port']}")
)
def get_unprivileged_web3(user_data: UserData, anvil_id: str) -> Web3:
return Web3(
Web3.HTTPProvider(
f"http://anvil-proxy:8545/{user_data['external_id']}/{anvil_id}"
)
)
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/RealWorld/2024/blockchain/SafeBridge/project/lib/forge-std/scripts/vm.py | ctfs/RealWorld/2024/blockchain/SafeBridge/project/lib/forge-std/scripts/vm.py | #!/usr/bin/env python3
import copy
import json
import re
import subprocess
from enum import Enum as PyEnum
from typing import Callable
from urllib import request
VoidFn = Callable[[], None]
CHEATCODES_JSON_URL = "https://raw.githubusercontent.com/foundry-rs/foundry/master/crates/cheatcodes/assets/cheatcodes.json"
OUT_PATH = "src/Vm.sol"
VM_SAFE_DOC = """\
/// The `VmSafe` interface does not allow manipulation of the EVM state or other actions that may
/// result in Script simulations differing from on-chain execution. It is recommended to only use
/// these cheats in scripts.
"""
VM_DOC = """\
/// The `Vm` interface does allow manipulation of the EVM state. These are all intended to be used
/// in tests, but it is not recommended to use these cheats in scripts.
"""
def main():
json_str = request.urlopen(CHEATCODES_JSON_URL).read().decode("utf-8")
contract = Cheatcodes.from_json(json_str)
ccs = contract.cheatcodes
ccs = list(filter(lambda cc: cc.status not in ["experimental", "internal"], ccs))
ccs.sort(key=lambda cc: cc.func.id)
safe = list(filter(lambda cc: cc.safety == "safe", ccs))
safe.sort(key=CmpCheatcode)
unsafe = list(filter(lambda cc: cc.safety == "unsafe", ccs))
unsafe.sort(key=CmpCheatcode)
assert len(safe) + len(unsafe) == len(ccs)
prefix_with_group_headers(safe)
prefix_with_group_headers(unsafe)
out = ""
out += "// Automatically @generated by scripts/vm.py. Do not modify manually.\n\n"
pp = CheatcodesPrinter(
spdx_identifier="MIT OR Apache-2.0",
solidity_requirement=">=0.6.2 <0.9.0",
abicoder_pragma=True,
)
pp.p_prelude()
pp.prelude = False
out += pp.finish()
out += "\n\n"
out += VM_SAFE_DOC
vm_safe = Cheatcodes(
# TODO: Custom errors were introduced in 0.8.4
errors=[], # contract.errors
events=contract.events,
enums=contract.enums,
structs=contract.structs,
cheatcodes=safe,
)
pp.p_contract(vm_safe, "VmSafe")
out += pp.finish()
out += "\n\n"
out += VM_DOC
vm_unsafe = Cheatcodes(
errors=[],
events=[],
enums=[],
structs=[],
cheatcodes=unsafe,
)
pp.p_contract(vm_unsafe, "Vm", "VmSafe")
out += pp.finish()
# Compatibility with <0.8.0
def memory_to_calldata(m: re.Match) -> str:
return " calldata " + m.group(1)
out = re.sub(r" memory (.*returns)", memory_to_calldata, out)
with open(OUT_PATH, "w") as f:
f.write(out)
forge_fmt = ["forge", "fmt", OUT_PATH]
res = subprocess.run(forge_fmt)
assert res.returncode == 0, f"command failed: {forge_fmt}"
print(f"Wrote to {OUT_PATH}")
class CmpCheatcode:
cheatcode: "Cheatcode"
def __init__(self, cheatcode: "Cheatcode"):
self.cheatcode = cheatcode
def __lt__(self, other: "CmpCheatcode") -> bool:
return cmp_cheatcode(self.cheatcode, other.cheatcode) < 0
def __eq__(self, other: "CmpCheatcode") -> bool:
return cmp_cheatcode(self.cheatcode, other.cheatcode) == 0
def __gt__(self, other: "CmpCheatcode") -> bool:
return cmp_cheatcode(self.cheatcode, other.cheatcode) > 0
def cmp_cheatcode(a: "Cheatcode", b: "Cheatcode") -> int:
if a.group != b.group:
return -1 if a.group < b.group else 1
if a.status != b.status:
return -1 if a.status < b.status else 1
if a.safety != b.safety:
return -1 if a.safety < b.safety else 1
if a.func.id != b.func.id:
return -1 if a.func.id < b.func.id else 1
return 0
# HACK: A way to add group header comments without having to modify printer code
def prefix_with_group_headers(cheats: list["Cheatcode"]):
s = set()
for i, cheat in enumerate(cheats):
if cheat.group in s:
continue
s.add(cheat.group)
c = copy.deepcopy(cheat)
c.func.description = ""
c.func.declaration = f"// ======== {group(c.group)} ========"
cheats.insert(i, c)
return cheats
def group(s: str) -> str:
if s == "evm":
return "EVM"
if s == "json":
return "JSON"
return s[0].upper() + s[1:]
class Visibility(PyEnum):
EXTERNAL: str = "external"
PUBLIC: str = "public"
INTERNAL: str = "internal"
PRIVATE: str = "private"
def __str__(self):
return self.value
class Mutability(PyEnum):
PURE: str = "pure"
VIEW: str = "view"
NONE: str = ""
def __str__(self):
return self.value
class Function:
id: str
description: str
declaration: str
visibility: Visibility
mutability: Mutability
signature: str
selector: str
selector_bytes: bytes
def __init__(
self,
id: str,
description: str,
declaration: str,
visibility: Visibility,
mutability: Mutability,
signature: str,
selector: str,
selector_bytes: bytes,
):
self.id = id
self.description = description
self.declaration = declaration
self.visibility = visibility
self.mutability = mutability
self.signature = signature
self.selector = selector
self.selector_bytes = selector_bytes
@staticmethod
def from_dict(d: dict) -> "Function":
return Function(
d["id"],
d["description"],
d["declaration"],
Visibility(d["visibility"]),
Mutability(d["mutability"]),
d["signature"],
d["selector"],
bytes(d["selectorBytes"]),
)
class Cheatcode:
func: Function
group: str
status: str
safety: str
def __init__(self, func: Function, group: str, status: str, safety: str):
self.func = func
self.group = group
self.status = status
self.safety = safety
@staticmethod
def from_dict(d: dict) -> "Cheatcode":
return Cheatcode(
Function.from_dict(d["func"]),
str(d["group"]),
str(d["status"]),
str(d["safety"]),
)
class Error:
name: str
description: str
declaration: str
def __init__(self, name: str, description: str, declaration: str):
self.name = name
self.description = description
self.declaration = declaration
@staticmethod
def from_dict(d: dict) -> "Error":
return Error(**d)
class Event:
name: str
description: str
declaration: str
def __init__(self, name: str, description: str, declaration: str):
self.name = name
self.description = description
self.declaration = declaration
@staticmethod
def from_dict(d: dict) -> "Event":
return Event(**d)
class EnumVariant:
name: str
description: str
def __init__(self, name: str, description: str):
self.name = name
self.description = description
class Enum:
name: str
description: str
variants: list[EnumVariant]
def __init__(self, name: str, description: str, variants: list[EnumVariant]):
self.name = name
self.description = description
self.variants = variants
@staticmethod
def from_dict(d: dict) -> "Enum":
return Enum(
d["name"],
d["description"],
list(map(lambda v: EnumVariant(**v), d["variants"])),
)
class StructField:
name: str
ty: str
description: str
def __init__(self, name: str, ty: str, description: str):
self.name = name
self.ty = ty
self.description = description
class Struct:
name: str
description: str
fields: list[StructField]
def __init__(self, name: str, description: str, fields: list[StructField]):
self.name = name
self.description = description
self.fields = fields
@staticmethod
def from_dict(d: dict) -> "Struct":
return Struct(
d["name"],
d["description"],
list(map(lambda f: StructField(**f), d["fields"])),
)
class Cheatcodes:
errors: list[Error]
events: list[Event]
enums: list[Enum]
structs: list[Struct]
cheatcodes: list[Cheatcode]
def __init__(
self,
errors: list[Error],
events: list[Event],
enums: list[Enum],
structs: list[Struct],
cheatcodes: list[Cheatcode],
):
self.errors = errors
self.events = events
self.enums = enums
self.structs = structs
self.cheatcodes = cheatcodes
@staticmethod
def from_dict(d: dict) -> "Cheatcodes":
return Cheatcodes(
errors=[Error.from_dict(e) for e in d["errors"]],
events=[Event.from_dict(e) for e in d["events"]],
enums=[Enum.from_dict(e) for e in d["enums"]],
structs=[Struct.from_dict(e) for e in d["structs"]],
cheatcodes=[Cheatcode.from_dict(e) for e in d["cheatcodes"]],
)
@staticmethod
def from_json(s) -> "Cheatcodes":
return Cheatcodes.from_dict(json.loads(s))
@staticmethod
def from_json_file(file_path: str) -> "Cheatcodes":
with open(file_path, "r") as f:
return Cheatcodes.from_dict(json.load(f))
class Item(PyEnum):
ERROR: str = "error"
EVENT: str = "event"
ENUM: str = "enum"
STRUCT: str = "struct"
FUNCTION: str = "function"
class ItemOrder:
_list: list[Item]
def __init__(self, list: list[Item]) -> None:
assert len(list) <= len(Item), "list must not contain more items than Item"
assert len(list) == len(set(list)), "list must not contain duplicates"
self._list = list
pass
def get_list(self) -> list[Item]:
return self._list
@staticmethod
def default() -> "ItemOrder":
return ItemOrder(
[
Item.ERROR,
Item.EVENT,
Item.ENUM,
Item.STRUCT,
Item.FUNCTION,
]
)
class CheatcodesPrinter:
buffer: str
prelude: bool
spdx_identifier: str
solidity_requirement: str
abicoder_v2: bool
block_doc_style: bool
indent_level: int
_indent_str: str
nl_str: str
items_order: ItemOrder
def __init__(
self,
buffer: str = "",
prelude: bool = True,
spdx_identifier: str = "UNLICENSED",
solidity_requirement: str = "",
abicoder_pragma: bool = False,
block_doc_style: bool = False,
indent_level: int = 0,
indent_with: int | str = 4,
nl_str: str = "\n",
items_order: ItemOrder = ItemOrder.default(),
):
self.prelude = prelude
self.spdx_identifier = spdx_identifier
self.solidity_requirement = solidity_requirement
self.abicoder_v2 = abicoder_pragma
self.block_doc_style = block_doc_style
self.buffer = buffer
self.indent_level = indent_level
self.nl_str = nl_str
if isinstance(indent_with, int):
assert indent_with >= 0
self._indent_str = " " * indent_with
elif isinstance(indent_with, str):
self._indent_str = indent_with
else:
assert False, "indent_with must be int or str"
self.items_order = items_order
def finish(self) -> str:
ret = self.buffer.rstrip()
self.buffer = ""
return ret
def p_contract(self, contract: Cheatcodes, name: str, inherits: str = ""):
if self.prelude:
self.p_prelude(contract)
self._p_str("interface ")
name = name.strip()
if name != "":
self._p_str(name)
self._p_str(" ")
if inherits != "":
self._p_str("is ")
self._p_str(inherits)
self._p_str(" ")
self._p_str("{")
self._p_nl()
self._with_indent(lambda: self._p_items(contract))
self._p_str("}")
self._p_nl()
def _p_items(self, contract: Cheatcodes):
for item in self.items_order.get_list():
if item == Item.ERROR:
self.p_errors(contract.errors)
elif item == Item.EVENT:
self.p_events(contract.events)
elif item == Item.ENUM:
self.p_enums(contract.enums)
elif item == Item.STRUCT:
self.p_structs(contract.structs)
elif item == Item.FUNCTION:
self.p_functions(contract.cheatcodes)
else:
assert False, f"unknown item {item}"
def p_prelude(self, contract: Cheatcodes | None = None):
self._p_str(f"// SPDX-License-Identifier: {self.spdx_identifier}")
self._p_nl()
if self.solidity_requirement != "":
req = self.solidity_requirement
elif contract and len(contract.errors) > 0:
req = ">=0.8.4 <0.9.0"
else:
req = ">=0.6.0 <0.9.0"
self._p_str(f"pragma solidity {req};")
self._p_nl()
if self.abicoder_v2:
self._p_str("pragma experimental ABIEncoderV2;")
self._p_nl()
self._p_nl()
def p_errors(self, errors: list[Error]):
for error in errors:
self._p_line(lambda: self.p_error(error))
def p_error(self, error: Error):
self._p_comment(error.description, doc=True)
self._p_line(lambda: self._p_str(error.declaration))
def p_events(self, events: list[Event]):
for event in events:
self._p_line(lambda: self.p_event(event))
def p_event(self, event: Event):
self._p_comment(event.description, doc=True)
self._p_line(lambda: self._p_str(event.declaration))
def p_enums(self, enums: list[Enum]):
for enum in enums:
self._p_line(lambda: self.p_enum(enum))
def p_enum(self, enum: Enum):
self._p_comment(enum.description, doc=True)
self._p_line(lambda: self._p_str(f"enum {enum.name} {{"))
self._with_indent(lambda: self.p_enum_variants(enum.variants))
self._p_line(lambda: self._p_str("}"))
def p_enum_variants(self, variants: list[EnumVariant]):
for i, variant in enumerate(variants):
self._p_indent()
self._p_comment(variant.description)
self._p_indent()
self._p_str(variant.name)
if i < len(variants) - 1:
self._p_str(",")
self._p_nl()
def p_structs(self, structs: list[Struct]):
for struct in structs:
self._p_line(lambda: self.p_struct(struct))
def p_struct(self, struct: Struct):
self._p_comment(struct.description, doc=True)
self._p_line(lambda: self._p_str(f"struct {struct.name} {{"))
self._with_indent(lambda: self.p_struct_fields(struct.fields))
self._p_line(lambda: self._p_str("}"))
def p_struct_fields(self, fields: list[StructField]):
for field in fields:
self._p_line(lambda: self.p_struct_field(field))
def p_struct_field(self, field: StructField):
self._p_comment(field.description)
self._p_indented(lambda: self._p_str(f"{field.ty} {field.name};"))
def p_functions(self, cheatcodes: list[Cheatcode]):
for cheatcode in cheatcodes:
self._p_line(lambda: self.p_function(cheatcode.func))
def p_function(self, func: Function):
self._p_comment(func.description, doc=True)
self._p_line(lambda: self._p_str(func.declaration))
def _p_comment(self, s: str, doc: bool = False):
s = s.strip()
if s == "":
return
s = map(lambda line: line.lstrip(), s.split("\n"))
if self.block_doc_style:
self._p_str("/*")
if doc:
self._p_str("*")
self._p_nl()
for line in s:
self._p_indent()
self._p_str(" ")
if doc:
self._p_str("* ")
self._p_str(line)
self._p_nl()
self._p_indent()
self._p_str(" */")
self._p_nl()
else:
first_line = True
for line in s:
if not first_line:
self._p_indent()
first_line = False
if doc:
self._p_str("/// ")
else:
self._p_str("// ")
self._p_str(line)
self._p_nl()
def _with_indent(self, f: VoidFn):
self._inc_indent()
f()
self._dec_indent()
def _p_line(self, f: VoidFn):
self._p_indent()
f()
self._p_nl()
def _p_indented(self, f: VoidFn):
self._p_indent()
f()
def _p_indent(self):
for _ in range(self.indent_level):
self._p_str(self._indent_str)
def _p_nl(self):
self._p_str(self.nl_str)
def _p_str(self, txt: str):
self.buffer += txt
def _inc_indent(self):
self.indent_level += 1
def _dec_indent(self):
self.indent_level -= 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/RealWorld/2024/misc/LLM_sanitizer/main.py | ctfs/RealWorld/2024/misc/LLM_sanitizer/main.py | #!/usr/bin/env python
# pip install langchain==0.1.1 langchain-openai==0.0.3 docker==7.0.0 ecdsa==0.18.0
import logging
import os
import struct
import sys
import signal
import docker
from docker.models.containers import Container
from langchain.prompts import ChatPromptTemplate
from langchain_core.output_parsers import StrOutputParser
from langchain_openai.chat_models import ChatOpenAI
logger = logging.getLogger("llm-sanitizer")
class DockerPythonREPL:
def __init__(self, flag_path: str):
self.client = docker.from_env()
self.flag_path = flag_path
def _decode_stdout(self, buf: bytes):
stdout = b""
while len(buf) > 8:
stream, actual = struct.unpack(">BxxxL", buf[:8])
if stream == 1:
stdout += buf[8 : 8 + actual]
buf = buf[8 + actual :]
return stdout
def run(self, command: str) -> str:
output = ""
try:
container: Container = self.client.containers.create(
"python:3.11-alpine",
command=["python", "-u"],
stdin_open=True,
tty=False,
user=65534,
mem_limit="64m",
network_mode="none",
volumes=[f"{self.flag_path}:/flag:ro"],
)
except Exception:
logger.exception("Failed to run")
return output
sock = None
try:
container.start()
# Attach and send to stdin
sock = container.attach_socket(params={"stdin": 1, "stream": 1})
sock._sock.sendall(command.encode("utf-8"))
sock._sock.close()
sock.close()
sock = None
# Attach again and recv from stdout
sock = container.attach_socket(params={"stdout": 1, "stream": 1})
sock._sock.settimeout(5)
buf = b""
while r := sock._sock.recv(4096):
buf += r
output = self._decode_stdout(buf).decode("utf-8")
except Exception:
logger.exception("Failed to communicate")
finally:
if sock:
sock._sock.close()
sock.close()
try:
container.remove(force=True)
except Exception:
pass
return output
def _sanitize_output(text: str):
_, after = text.split("```python")
output = after.split("```")[0]
print(f"Sanitized:\n{output}")
return output
def main():
signal.alarm(60)
model_args = dict(temperature=0, max_tokens=512, model_kwargs=dict(seed=1337))
model = ChatOpenAI(name="gpt-3.5-turbo-1106", **model_args)
prompt = """Please review and clean the following Python code to ensure it complies with our code sandbox safety standards. Specifically, ensure that the code:
1. Does not contain any form of file reading or writing operations, including but not limited to calls to open(), os.open(), io.open(), etc.
2. Does not attempt to execute system commands or external programs, including but not limited to the use of os.system(), subprocess.Popen(), exec(), eval(), etc.
3. Does not attempt to access any internal property or method of objects, including but not limited to the use of __dict__, __class__, __bases__, etc.
4. Avoids any network access, including the use of requests, urllib, or other networking libraries.
5. Is free from elements that could lead to the abuse of system resources, such as infinite loops or operations that excessively consume memory.
6. Prevents direct or indirect access to system-level environment variables or configurations.
7. Is checked for any potentially unsafe library references or function calls that might pose security vulnerabilities.
Return only the cleaned code that adheres to these sandbox requirements in Markdown format, e.g.:
```python\nprint('Hello, world!')\n```"""
print(f"System prompt: \n---\n{prompt}\n---\nInput:")
template = ChatPromptTemplate.from_messages(
[("system", prompt), ("human", "{input}")]
)
flag_path = os.getenv("FLAG_PATH", "/flag")
repl = DockerPythonREPL(flag_path)
chain = template | model | StrOutputParser() | _sanitize_output | repl.run
args = sys.stdin.read()[:256]
output = chain.invoke(dict(input=args))
print(f"Output:\n{output}")
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/RealWorld/2024/pwn/YouKnowHowToFuzz/chal.py | ctfs/RealWorld/2024/pwn/YouKnowHowToFuzz/chal.py | #!/usr/local/bin/python3
from grammar import Grammar
print("define your own rule >> ")
your_rule = ""
while True:
line = input()
if line == "<EOF>":
break
your_rule += line + "\n"
rwctf_grammar = Grammar()
err = rwctf_grammar.parse_from_string(your_rule)
if err > 0:
print("Grammer Parse Error")
exit(-1)
rwctf_result = rwctf_grammar._generate_code(10)
with open("/domato/rwctf/template.html", "r") as f:
template = f.read()
rwctf_result = template.replace("<rwctf>", rwctf_result)
print("your result >> ")
print(rwctf_result)
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/RealWorld/2024/pwn/hoshmonster/chal.py | ctfs/RealWorld/2024/pwn/hoshmonster/chal.py | from unicorn import Uc, UcError, UC_ARCH_X86, UC_ARCH_ARM64, UC_ARCH_RISCV, UC_MODE_64, UC_MODE_ARM, UC_MODE_RISCV64, UC_PROT_READ, UC_PROT_EXEC, UC_SECOND_SCALE, UC_HOOK_BLOCK
from unicorn.x86_const import UC_X86_REG_RAX, UC_X86_REG_RIP
from unicorn.arm64_const import UC_ARM64_REG_X0, UC_ARM64_REG_PC
from unicorn.riscv_const import UC_RISCV_REG_X1, UC_RISCV_REG_PC
import sys, json, time, hashlib, signal, os, random, dbm
import fastcrc
from filelock import FileLock
from datetime import datetime
def _check_team_token(token):
try:
with dbm.open("data/teams", "r") as db:
return db.get(hashlib.md5(token.encode("utf-8")).hexdigest(), None)
except dbm.error:
return b"<missing team name>"
def hmac64(key, msg): # RFC 2104
opadk = (int.from_bytes(b"\x5c" * 8)^key).to_bytes(8)
ipadk = (int.from_bytes(b"\x36" * 8)^key).to_bytes(8)
return fastcrc.crc64.we(opadk + fastcrc.crc64.we(ipadk + msg).to_bytes(8))
bbcounter = 0
def hook_block(uc, address, size, user_data):
global bbcounter
bbcounter += 1
def run(mu, CODE, MAP_ADDR, REG, PC, INPUT):
try:
mu.mem_map(MAP_ADDR, 4096+(len(CODE)//4096)*4096, UC_PROT_READ|UC_PROT_EXEC)
mu.mem_write(MAP_ADDR, CODE)
mu.reg_write(REG, INPUT)
mu.hook_add(UC_HOOK_BLOCK, hook_block)
# RUN CODE
mu.emu_start(MAP_ADDR, MAP_ADDR + len(CODE), timeout=UC_SECOND_SCALE*60, count=6000000)
result = mu.reg_read(REG)
except UcError as e:
print("ERROR: %s at 0x%x" % (e, mu.reg_read(PC)))
result = 0
return result
def try_login(token):
os.makedirs('/tmp/FF24', mode=0o700, exist_ok=True)
conn_interval = 5
with FileLock(os.path.join('/tmp/FF24', hashlib.sha256(token.encode()).hexdigest()+'.lock'), timeout=1):
fd = os.open(os.path.join('/tmp/FF24', hashlib.sha256(token.encode()).hexdigest()), os.O_CREAT | os.O_RDWR)
with os.fdopen(fd, "r+") as f:
data = f.read()
now = int(time.time())
if data:
last_login, balance = data.split()
last_login = int(last_login)
balance = int(balance)
last_login_str = (
datetime.fromtimestamp(last_login).isoformat().replace("T", " ")
)
balance += now - last_login
if balance > conn_interval * 3:
balance = conn_interval * 3
else:
balance = conn_interval * 3
if conn_interval > balance:
print(
f"Player connection rate limit exceeded, please try again after {conn_interval-balance} seconds. "
)
return False
balance -= conn_interval
f.seek(0)
f.truncate()
f.write(str(now) + " " + str(balance))
return True
signal.alarm(3)
token = input("Please input your team token: ")
team_name = _check_team_token(token)
if team_name is None:
print("No such team!")
exit(1)
team_name = team_name.decode("utf-8")
if not try_login(token):
exit(-1)
signal.alarm(0)
print("Welcome to FF24. Think fast, code faster")
print("Plz choose options:\n\t1. View leaderboard\n\t2. Run program")
choice = int(input("Your choice [1/2]: "))
if choice == 1:
with FileLock("/tmp/FF24/scores.json.lock", timeout=1):
leaderb = json.load(open('data/scores.json','r'))
print('------------LEADERBOARD------------')
temp = sorted(leaderb.values())
for t,s in sorted(leaderb.items(), key=lambda x:x[1]):
print("{0:2} | {1:15} | {2}".format(temp.index(s)+1, t, s))
print('-----------------------------------')
elif choice == 2:
code = bytes.fromhex(input("Give me shellcode in HEX format: "))
code_map = int(input("Give me code mapping address: "))
success = 0
random_input = random.randint(0, 2**64-1)
expect = hmac64(random_input, code+random_input.to_bytes(8))
result = run(Uc(UC_ARCH_ARM64, UC_MODE_ARM), code, code_map, UC_ARM64_REG_X0, UC_ARM64_REG_PC, random_input)
if expect == result:
print("ARM64: SUCCESS")
success += 1
else:
print(f"ARM64: {random_input:016x}, {expect:016x}, {result:016x}")
random_input = random.randint(0, 2**64-1)
expect = hmac64(random_input, code+random_input.to_bytes(8))
result = run(Uc(UC_ARCH_RISCV, UC_MODE_RISCV64), code, code_map, UC_RISCV_REG_X1, UC_RISCV_REG_PC, random_input)
if expect == result:
print("RV64: SUCCESS")
success += 1
else:
print(f"RV64: {random_input:016x}, {expect:016x}, {result:016x}")
if success == 2:
random_input = random.randint(0, 2**64-1)
expect = hmac64(random_input, code+random_input.to_bytes(8))
result = run(Uc(UC_ARCH_X86, UC_MODE_64), code, code_map, UC_X86_REG_RAX, UC_X86_REG_RIP, random_input)
if expect == result:
print("x86-64: SUCCESS")
success += 1
else:
print(f"x86-64: {random_input:016x}, {expect:016x}, {result:016x}")
if success:
score = len(code) * 10000**(3-success) + bbcounter
print("Your score:", score)
if score <= 283:
with open("/flag", "rt") as _f:
print(_f.read(), flush=True)
with FileLock("/tmp/FF24/scores.json.lock", timeout=1):
leaderb = json.load(open('data/scores.json','r'))
if team_name not in leaderb or score < leaderb[team_name]:
leaderb[team_name] = score
json.dump(leaderb, open('data/scores.json','w'))
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/RealWorld/2024/pwn/T_Box/main.py | ctfs/RealWorld/2024/pwn/T_Box/main.py | import sys
import subprocess
import pathlib
import argparse
work_dir = pathlib.Path(__file__).parent.absolute()
instance_dir = pathlib.Path("/var/run/tbox")
class CmdFailed(Exception):
pass
def build_docker(name: str):
cmd = ["docker", "build", "-t", name, work_dir / name]
run_cmd(cmd)
def run_cmd(argv: list, cwd=work_dir) -> bytes:
f = subprocess.run(argv, cwd=cwd, capture_output=True)
if f.returncode != 0:
raise CmdFailed(f"Command failed: {argv}: {f.stderr.decode()}")
return f.stdout
def kill_docker(name: str):
cmd = ["docker", "kill", name]
try:
run_cmd(cmd)
except CmdFailed as e:
print(e)
def attach_ns(pid: int, name: str):
cmd = ["ip", "netns", "attach", name, str(pid)]
run_cmd(cmd)
def delete_ns(name: str):
cmd = ["ip", "netns", "delete", name]
try:
run_cmd(cmd)
except CmdFailed as e:
print(e)
def get_docker_pid(name: str):
cmd = ["docker", "top", name]
result = run_cmd(cmd)
line = result.split(b"\n")[1]
pid = line.split()[1]
return int(pid)
def set_ns(name: str, cmdline: str):
cmd = ["ip", "netns", "exec", name, "sh", "-c", cmdline]
run_cmd(cmd)
def get_ssh_port(name: str):
cmd = ["docker", "port", name, "22"]
result = run_cmd(cmd)
return int(result.split(b'\n')[0].split(b":")[1])
GATEBOX_CMD = '''
ip link add jumpbox type bridge
ip addr add dev jumpbox 10.233.1.1/24
ip link set jumpbox up
ip link add veth_jumpbox type veth peer vm
ip link set dev vm netns {jumpbox_name}
ip link set veth_jumpbox master jumpbox
ip link set veth_jumpbox up
ip link add flagbox type bridge
ip addr add dev flagbox 10.233.2.1/24
ip link set flagbox up
ip link add veth_flagbox type veth peer vm
ip link set dev vm netns {flagbox_name}
ip link set veth_flagbox master flagbox
ip link set veth_flagbox up
iptables -t nat -I POSTROUTING -o eth0 -j MASQUERADE
iptables -I FORWARD -i flagbox -o jumpbox -j DROP
iptables -I FORWARD -o flagbox -i jumpbox -j DROP
iptables -t nat -I PREROUTING -p tcp --dport 22 -j DNAT --to-destination 10.233.1.2:22
'''
JUMPBOX_CMD = '''
ip link set dev vm name eth0
ip addr add 10.233.1.2/24 dev eth0
ip link set dev eth0 up
ip route add 0.0.0.0/0 via 10.233.1.1 dev eth0
'''
FLAGBOX_CMD = '''
ip link set dev vm name eth0
ip addr add 10.233.2.2/24 dev eth0
ip link set dev eth0 up
ip route add 0.0.0.0/0 via 10.233.2.1 dev eth0
'''
def start(identifier: str):
id_path = instance_dir / identifier
if id_path.exists():
print("Instance already exists")
sys.exit(1)
else:
id_path.touch()
# first start all containers
jumpbox_name = f"jumpbox_{identifier}"
flagbox_name = f"flagbox_{identifier}"
gatebox_name = f"gatebox_{identifier}"
cmd = ["docker", "run", "-d", "--rm", "--name", jumpbox_name, "--network", 'none', "--cap-add", "NET_RAW",
"jumpbox"]
run_cmd(cmd)
# change password for jumpbox
run_cmd(["docker", "exec", jumpbox_name, "sh", "-c", f"echo 'root:{identifier}' | chpasswd"])
cmd = ["docker", "run", "-d", "--rm", "--name", flagbox_name, "--network", 'none', "flagbox"]
run_cmd(cmd)
cmd = ["docker", "run", "-d", "--rm", "--name", gatebox_name, "--network", "bridge", "-p", "22", "gatebox"]
run_cmd(cmd)
attach_ns(get_docker_pid(jumpbox_name), jumpbox_name)
attach_ns(get_docker_pid(flagbox_name), flagbox_name)
attach_ns(get_docker_pid(gatebox_name), gatebox_name)
set_ns(gatebox_name, GATEBOX_CMD.format(jumpbox_name=jumpbox_name, flagbox_name=flagbox_name))
set_ns(jumpbox_name, JUMPBOX_CMD)
set_ns(flagbox_name, FLAGBOX_CMD)
ssh_port = get_ssh_port(gatebox_name)
print(f"ssh -p {ssh_port} root@127.0.0.1")
def cleanup(identifier):
jumpbox_name = f"jumpbox_{identifier}"
flagbox_name = f"flagbox_{identifier}"
gatebox_name = f"gatebox_{identifier}"
kill_docker(jumpbox_name)
kill_docker(flagbox_name)
kill_docker(gatebox_name)
delete_ns(jumpbox_name)
delete_ns(flagbox_name)
delete_ns(gatebox_name)
id_path = instance_dir / identifier
id_path.unlink()
def init():
instance_dir.mkdir(parents=True, exist_ok=True)
cmd = ["docker", "version"]
run_cmd(cmd)
cmd = ["ip", 'a']
run_cmd(cmd)
# build docker image
build_docker("jumpbox")
build_docker("gatebox")
build_docker("flagbox")
if __name__ == '__main__':
parser = argparse.ArgumentParser()
parser.add_argument("action", choices=["start", "stop", "init"])
parser.add_argument("identifier", type=str, help="identifier for the challenge")
arg = parser.parse_args()
if arg.action == "stop":
cleanup(arg.identifier)
elif arg.action == "start":
start(arg.identifier)
elif arg.action == "init":
init()
else:
print("Unknown command")
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/RealWorld/2023/crypto/OKPROOF/setup.py | ctfs/RealWorld/2023/crypto/OKPROOF/setup.py | # -*- coding: utf-8 -*-
from setuptools import setup, find_packages
with open('README.md') as f:
readme = f.read()
with open('LICENSE') as f:
license = f.read()
setup(
name='py_ecc',
version='1.0.0',
description='Elliptic curve crypto in python including secp256k1 and alt_bn128',
long_description=readme,
author='Vitalik Buterin',
author_email='',
url='https://github.com/ethereum/py_pairing',
license=license,
packages=find_packages(exclude=('tests', 'docs')),
data_files=[
('', ['LICENSE', 'README.md'])
],
install_requires=[
],
)
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/RealWorld/2023/crypto/OKPROOF/task.py | ctfs/RealWorld/2023/crypto/OKPROOF/task.py | #!/usr/bin/env python3
import signal
import socketserver
import string
import os
from secret import flag
from py_ecc import bn128
lib = bn128
FQ, FQ2, FQ12, field_modulus = lib.FQ, lib.FQ2, lib.FQ12, lib.field_modulus
G1, G2, G12, b, b2, b12, is_inf, is_on_curve, eq, add, double, curve_order, multiply = \
lib.G1, lib.G2, lib.G12, lib.b, lib.b2, lib.b12, lib.is_inf, lib.is_on_curve, lib.eq, lib.add, lib.double, lib.curve_order, lib.multiply
pairing, neg = lib.pairing, lib.neg
LENGTH = 7
def Cx(x,length=LENGTH):
res = []
for i in range(length):
res.append(pow(x,i,curve_order) % curve_order)
return res
def C(x,y,length=LENGTH):
assert len(x) == len(y) == length
res = multiply(G1, curve_order)
for i in range(length):
res = add(multiply(x[i],y[i]),res)
return res
def Z(x):
return (x-1)*(x-2)*(x-3)*(x-4) % curve_order
def genK(curve_order,length=LENGTH):
t = int(os.urandom(8).hex(),16) % curve_order
a = int(os.urandom(8).hex(),16) % curve_order
Ct = Cx(t)
PKC = []
for ct in Ct:
PKC.append(multiply(G1, ct))
PKCa = []
for ct in Ct:
PKCa.append(multiply(multiply(G1, ct), a))
PK = (PKC,PKCa)
VKa = multiply(G2, a)
VKz = multiply(G2, Z(t))
VK = (VKa,VKz)
return PK,VK
def verify(proof,VK):
VKa,VKz = VK
PiC,PiCa,PiH = proof
l = pairing(VKa, PiC)
r = pairing(G2, PiCa)
if l !=r:
return False
l = pairing(G2,PiC)
r = pairing(VKz,PiH)
if l !=r:
return False
return True
class Task(socketserver.BaseRequestHandler):
def __init__(self, *args, **kargs):
super().__init__(*args, **kargs)
def OKPROOF(self,proof,VK):
return verify(proof,VK)
def dosend(self, msg):
try:
self.request.sendall(msg.encode('latin-1') + b'\n')
except:
pass
def timeout_handler(self, signum, frame):
raise TimeoutError
def handle(self):
try:
signal.signal(signal.SIGALRM, self.timeout_handler)
self.dosend('===========================')
self.dosend('=WELCOME TO 0KPR00F SYSTEM=')
self.dosend('===========================')
PK,VK = genK(curve_order)
self.dosend(str(PK))
self.dosend('now give me your proof')
msg = self.request.recv(1024).strip()
msg = msg.decode('utf-8')
tmp = msg.replace('(','').replace(')','').replace(',','')
tmp = tmp.split(' ')
assert len(tmp) == 6
PiC = (FQ(int(tmp[0].strip())),FQ(int(tmp[1].strip())))
PiCa = (FQ(int(tmp[2].strip())),FQ(int(tmp[3].strip())))
PiH = (FQ(int(tmp[4].strip())),FQ(int(tmp[5].strip())))
proof = (PiC,PiCa,PiH)
if self.OKPROOF(proof,VK):
self.dosend("CongratulationsοΌHere is flag:"+flag)
else:
self.dosend("sorry")
except TimeoutError:
self.dosend('Timeout!')
self.request.close()
except:
self.dosend('Wtf?')
self.request.close()
class ThreadedServer(socketserver.ForkingMixIn, socketserver.TCPServer):
pass
if __name__ == "__main__":
HOST, PORT = '0.0.0.0', 13337
server = ThreadedServer((HOST, PORT), Task)
server.allow_reuse_address = True
server.serve_forever() | python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/RealWorld/2023/crypto/OKPROOF/py_ecc/__init__.py | ctfs/RealWorld/2023/crypto/OKPROOF/py_ecc/__init__.py | from . import secp256k1
from . import bn128
from . import optimized_bn128
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/RealWorld/2023/crypto/OKPROOF/py_ecc/secp256k1/secp256k1.py | ctfs/RealWorld/2023/crypto/OKPROOF/py_ecc/secp256k1/secp256k1.py | import hashlib, hmac
import sys
if sys.version[0] == '2':
safe_ord = ord
else:
safe_ord = lambda x: x
# Elliptic curve parameters (secp256k1)
P = 2**256 - 2**32 - 977
N = 115792089237316195423570985008687907852837564279074904382605163141518161494337
A = 0
B = 7
Gx = 55066263022277343669578718895168534326250603453777594175500187360389116729240
Gy = 32670510020758816978083085130507043184471273380659243275938904335757337482424
G = (Gx, Gy)
def bytes_to_int(x):
o = 0
for b in x:
o = (o << 8) + safe_ord(b)
return o
# Extended Euclidean Algorithm
def inv(a, n):
if a == 0:
return 0
lm, hm = 1, 0
low, high = a % n, n
while low > 1:
r = high//low
nm, new = hm-lm*r, high-low*r
lm, low, hm, high = nm, new, lm, low
return lm % n
def to_jacobian(p):
o = (p[0], p[1], 1)
return o
def jacobian_double(p):
if not p[1]:
return (0, 0, 0)
ysq = (p[1] ** 2) % P
S = (4 * p[0] * ysq) % P
M = (3 * p[0] ** 2 + A * p[2] ** 4) % P
nx = (M**2 - 2 * S) % P
ny = (M * (S - nx) - 8 * ysq ** 2) % P
nz = (2 * p[1] * p[2]) % P
return (nx, ny, nz)
def jacobian_add(p, q):
if not p[1]:
return q
if not q[1]:
return p
U1 = (p[0] * q[2] ** 2) % P
U2 = (q[0] * p[2] ** 2) % P
S1 = (p[1] * q[2] ** 3) % P
S2 = (q[1] * p[2] ** 3) % P
if U1 == U2:
if S1 != S2:
return (0, 0, 1)
return jacobian_double(p)
H = U2 - U1
R = S2 - S1
H2 = (H * H) % P
H3 = (H * H2) % P
U1H2 = (U1 * H2) % P
nx = (R ** 2 - H3 - 2 * U1H2) % P
ny = (R * (U1H2 - nx) - S1 * H3) % P
nz = (H * p[2] * q[2]) % P
return (nx, ny, nz)
def from_jacobian(p):
z = inv(p[2], P)
return ((p[0] * z**2) % P, (p[1] * z**3) % P)
def jacobian_multiply(a, n):
if a[1] == 0 or n == 0:
return (0, 0, 1)
if n == 1:
return a
if n < 0 or n >= N:
return jacobian_multiply(a, n % N)
if (n % 2) == 0:
return jacobian_double(jacobian_multiply(a, n//2))
if (n % 2) == 1:
return jacobian_add(jacobian_double(jacobian_multiply(a, n//2)), a)
def multiply(a, n):
return from_jacobian(jacobian_multiply(to_jacobian(a), n))
def add(a, b):
return from_jacobian(jacobian_add(to_jacobian(a), to_jacobian(b)))
def privtopub(privkey):
return multiply(G, bytes_to_int(privkey))
def deterministic_generate_k(msghash, priv):
v = b'\x01' * 32
k = b'\x00' * 32
k = hmac.new(k, v+b'\x00'+priv+msghash, hashlib.sha256).digest()
v = hmac.new(k, v, hashlib.sha256).digest()
k = hmac.new(k, v+b'\x01'+priv+msghash, hashlib.sha256).digest()
v = hmac.new(k, v, hashlib.sha256).digest()
return bytes_to_int(hmac.new(k, v, hashlib.sha256).digest())
# bytes32, bytes32 -> v, r, s (as numbers)
def ecdsa_raw_sign(msghash, priv):
z = bytes_to_int(msghash)
k = deterministic_generate_k(msghash, priv)
r, y = multiply(G, k)
s = inv(k, N) * (z + r*bytes_to_int(priv)) % N
v, r, s = 27+((y % 2) ^ (0 if s * 2 < N else 1)), r, s if s * 2 < N else N - s
return v, r, s
def ecdsa_raw_recover(msghash, vrs):
v, r, s = vrs
if not (27 <= v <= 34):
raise ValueError("%d must in range 27-31" % v)
x = r
xcubedaxb = (x*x*x+A*x+B) % P
beta = pow(xcubedaxb, (P+1)//4, P)
y = beta if v % 2 ^ beta % 2 else (P - beta)
# If xcubedaxb is not a quadratic residue, then r cannot be the x coord
# for a point on the curve, and so the sig is invalid
if (xcubedaxb - y*y) % P != 0 or not (r % N) or not (s % N):
return False
z = bytes_to_int(msghash)
Gz = jacobian_multiply((Gx, Gy, 1), (N - z) % N)
XY = jacobian_multiply((x, y, 1), s)
Qr = jacobian_add(Gz, XY)
Q = jacobian_multiply(Qr, inv(r, N))
Q = from_jacobian(Q)
return Q
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/RealWorld/2023/crypto/OKPROOF/py_ecc/secp256k1/__init__.py | ctfs/RealWorld/2023/crypto/OKPROOF/py_ecc/secp256k1/__init__.py | from .secp256k1 import privtopub, ecdsa_raw_sign, ecdsa_raw_recover, N, P, G
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/RealWorld/2023/crypto/OKPROOF/py_ecc/optimized_bn128/optimized_curve.py | ctfs/RealWorld/2023/crypto/OKPROOF/py_ecc/optimized_bn128/optimized_curve.py | from .optimized_field_elements import FQ2, FQ12, field_modulus, FQ
curve_order = 21888242871839275222246405745257275088548364400416034343698204186575808495617
# Curve order should be prime
assert pow(2, curve_order, curve_order) == 2
# Curve order should be a factor of field_modulus**12 - 1
assert (field_modulus ** 12 - 1) % curve_order == 0
# Curve is y**2 = x**3 + 3
b = FQ(3)
# Twisted curve over FQ**2
b2 = FQ2([3, 0]) / FQ2([9, 1])
# Extension curve over FQ**12; same b value as over FQ
b12 = FQ12([3] + [0] * 11)
# Generator for curve over FQ
G1 = (FQ(1), FQ(2), FQ(1))
# Generator for twisted curve over FQ2
G2 = (FQ2([10857046999023057135944570762232829481370756359578518086990519993285655852781, 11559732032986387107991004021392285783925812861821192530917403151452391805634]),
FQ2([8495653923123431417604973247489272438418190587263600148770280649306958101930, 4082367875863433681332203403145435568316851327593401208105741076214120093531]), FQ2.one())
# Check if a point is the point at infinity
def is_inf(pt):
return pt[-1] == pt[-1].__class__.zero()
# Check that a point is on the curve defined by y**2 == x**3 + b
def is_on_curve(pt, b):
if is_inf(pt):
return True
x, y, z = pt
return y**2 * z - x**3 == b * z**3
assert is_on_curve(G1, b)
assert is_on_curve(G2, b2)
# Elliptic curve doubling
def double(pt):
x, y, z = pt
W = 3 * x * x
S = y * z
B = x * y * S
H = W * W - 8 * B
S_squared = S * S
newx = 2 * H * S
newy = W * (4 * B - H) - 8 * y * y * S_squared
newz = 8 * S * S_squared
return newx, newy, newz
# Elliptic curve addition
def add(p1, p2):
one, zero = p1[0].__class__.one(), p1[0].__class__.zero()
if p1[2] == zero or p2[2] == zero:
return p1 if p2[2] == zero else p2
x1, y1, z1 = p1
x2, y2, z2 = p2
U1 = y2 * z1
U2 = y1 * z2
V1 = x2 * z1
V2 = x1 * z2
if V1 == V2 and U1 == U2:
return double(p1)
elif V1 == V2:
return (one, one, zero)
U = U1 - U2
V = V1 - V2
V_squared = V * V
V_squared_times_V2 = V_squared * V2
V_cubed = V * V_squared
W = z1 * z2
A = U * U * W - V_cubed - 2 * V_squared_times_V2
newx = V * A
newy = U * (V_squared_times_V2 - A) - V_cubed * U2
newz = V_cubed * W
return (newx, newy, newz)
# Elliptic curve point multiplication
def multiply(pt, n):
if n == 0:
return (pt[0].__class__.one(), pt[0].__class__.one(), pt[0].__class__.zero())
elif n == 1:
return pt
elif not n % 2:
return multiply(double(pt), n // 2)
else:
return add(multiply(double(pt), int(n // 2)), pt)
def eq(p1, p2):
x1, y1, z1 = p1
x2, y2, z2 = p2
return x1 * z2 == x2 * z1 and y1 * z2 == y2 * z1
def normalize(pt):
x, y, z = pt
return (x / z, y / z)
# "Twist" a point in E(FQ2) into a point in E(FQ12)
w = FQ12([0, 1] + [0] * 10)
# Convert P => -P
def neg(pt):
if pt is None:
return None
x, y, z = pt
return (x, -y, z)
def twist(pt):
if pt is None:
return None
_x, _y, _z = pt
# Field isomorphism from Z[p] / x**2 to Z[p] / x**2 - 18*x + 82
xcoeffs = [_x.coeffs[0] - _x.coeffs[1] * 9, _x.coeffs[1]]
ycoeffs = [_y.coeffs[0] - _y.coeffs[1] * 9, _y.coeffs[1]]
zcoeffs = [_z.coeffs[0] - _z.coeffs[1] * 9, _z.coeffs[1]]
x, y, z = _x - _y * 9, _y, _z
nx = FQ12([xcoeffs[0]] + [0] * 5 + [xcoeffs[1]] + [0] * 5)
ny = FQ12([ycoeffs[0]] + [0] * 5 + [ycoeffs[1]] + [0] * 5)
nz = FQ12([zcoeffs[0]] + [0] * 5 + [zcoeffs[1]] + [0] * 5)
return (nx * w **2, ny * w**3, nz)
# Check that the twist creates a point that is on the curve
G12 = twist(G2)
assert is_on_curve(G12, b12)
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/RealWorld/2023/crypto/OKPROOF/py_ecc/optimized_bn128/__init__.py | ctfs/RealWorld/2023/crypto/OKPROOF/py_ecc/optimized_bn128/__init__.py | from .optimized_field_elements import field_modulus, FQ, FQP, FQ2, FQ12
from .optimized_curve import add, double, multiply, is_inf, is_on_curve, eq, neg, twist, b, b2, b12, curve_order, G1, G2, G12, normalize
from .optimized_pairing import pairing, final_exponentiate
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/RealWorld/2023/crypto/OKPROOF/py_ecc/optimized_bn128/optimized_field_elements.py | ctfs/RealWorld/2023/crypto/OKPROOF/py_ecc/optimized_bn128/optimized_field_elements.py | field_modulus = 21888242871839275222246405745257275088696311157297823662689037894645226208583
FQ12_modulus_coeffs = [82, 0, 0, 0, 0, 0, -18, 0, 0, 0, 0, 0] # Implied + [1]
FQ12_mc_tuples = [(i, c) for i, c in enumerate(FQ12_modulus_coeffs) if c]
# python3 compatibility
try:
foo = long
except:
long = int
# Extended euclidean algorithm to find modular inverses for
# integers
def prime_field_inv(a, n):
if a == 0:
return 0
lm, hm = 1, 0
low, high = a % n, n
while low > 1:
r = high//low
nm, new = hm-lm*r, high-low*r
lm, low, hm, high = nm, new, lm, low
return lm % n
# A class for field elements in FQ. Wrap a number in this class,
# and it becomes a field element.
class FQ():
def __init__(self, n):
if isinstance(n, self.__class__):
self.n = n.n
else:
self.n = n % field_modulus
assert isinstance(self.n, (int, long))
def __add__(self, other):
on = other.n if isinstance(other, FQ) else other
return FQ((self.n + on) % field_modulus)
def __mul__(self, other):
on = other.n if isinstance(other, FQ) else other
return FQ((self.n * on) % field_modulus)
def __rmul__(self, other):
return self * other
def __radd__(self, other):
return self + other
def __rsub__(self, other):
on = other.n if isinstance(other, FQ) else other
return FQ((on - self.n) % field_modulus)
def __sub__(self, other):
on = other.n if isinstance(other, FQ) else other
return FQ((self.n - on) % field_modulus)
def __div__(self, other):
on = other.n if isinstance(other, FQ) else other
assert isinstance(on, (int, long))
return FQ(self.n * prime_field_inv(on, field_modulus) % field_modulus)
def __truediv__(self, other):
return self.__div__(other)
def __rdiv__(self, other):
on = other.n if isinstance(other, FQ) else other
assert isinstance(on, (int, long)), on
return FQ(prime_field_inv(self.n, field_modulus) * on % field_modulus)
def __rtruediv__(self, other):
return self.__rdiv__(other)
def __pow__(self, other):
if other == 0:
return FQ(1)
elif other == 1:
return FQ(self.n)
elif other % 2 == 0:
return (self * self) ** (other // 2)
else:
return ((self * self) ** int(other // 2)) * self
def __eq__(self, other):
if isinstance(other, FQ):
return self.n == other.n
else:
return self.n == other
def __ne__(self, other):
return not self == other
def __neg__(self):
return FQ(-self.n)
def __repr__(self):
return repr(self.n)
@classmethod
def one(cls):
return cls(1)
@classmethod
def zero(cls):
return cls(0)
# Utility methods for polynomial math
def deg(p):
d = len(p) - 1
while p[d] == 0 and d:
d -= 1
return d
def poly_rounded_div(a, b):
dega = deg(a)
degb = deg(b)
temp = [x for x in a]
o = [0 for x in a]
for i in range(dega - degb, -1, -1):
o[i] = (o[i] + temp[degb + i] * prime_field_inv(b[degb], field_modulus))
for c in range(degb + 1):
temp[c + i] = (temp[c + i] - o[c])
return [x % field_modulus for x in o[:deg(o)+1]]
# A class for elements in polynomial extension fields
class FQP():
def __init__(self, coeffs, modulus_coeffs):
assert len(coeffs) == len(modulus_coeffs)
self.coeffs = coeffs
# The coefficients of the modulus, without the leading [1]
self.modulus_coeffs = modulus_coeffs
# The degree of the extension field
self.degree = len(self.modulus_coeffs)
def __add__(self, other):
assert isinstance(other, self.__class__)
return self.__class__([(x+y) % field_modulus for x,y in zip(self.coeffs, other.coeffs)])
def __sub__(self, other):
assert isinstance(other, self.__class__)
return self.__class__([(x-y) % field_modulus for x,y in zip(self.coeffs, other.coeffs)])
def __mul__(self, other):
if isinstance(other, (int, long)):
return self.__class__([c * other % field_modulus for c in self.coeffs])
else:
# assert isinstance(other, self.__class__)
b = [0] * (self.degree * 2 - 1)
inner_enumerate = list(enumerate(other.coeffs))
for i, eli in enumerate(self.coeffs):
for j, elj in inner_enumerate:
b[i + j] += eli * elj
# MID = len(self.coeffs) // 2
for exp in range(self.degree - 2, -1, -1):
top = b.pop()
for i, c in self.mc_tuples:
b[exp + i] -= top * c
return self.__class__([x % field_modulus for x in b])
def __rmul__(self, other):
return self * other
def __div__(self, other):
if isinstance(other, (int, long)):
return self.__class__([c * prime_field_inv(other, field_modulus) % field_modulus for c in self.coeffs])
else:
assert isinstance(other, self.__class__)
return self * other.inv()
def __truediv__(self, other):
return self.__div__(other)
def __pow__(self, other):
o = self.__class__([1] + [0] * (self.degree - 1))
t = self
while other > 0:
if other & 1:
o = o * t
other >>= 1
t = t * t
return o
# Extended euclidean algorithm used to find the modular inverse
def inv(self):
lm, hm = [1] + [0] * self.degree, [0] * (self.degree + 1)
low, high = self.coeffs + [0], self.modulus_coeffs + [1]
while deg(low):
r = poly_rounded_div(high, low)
r += [0] * (self.degree + 1 - len(r))
nm = [x for x in hm]
new = [x for x in high]
# assert len(lm) == len(hm) == len(low) == len(high) == len(nm) == len(new) == self.degree + 1
for i in range(self.degree + 1):
for j in range(self.degree + 1 - i):
nm[i+j] -= lm[i] * r[j]
new[i+j] -= low[i] * r[j]
nm = [x % field_modulus for x in nm]
new = [x % field_modulus for x in new]
lm, low, hm, high = nm, new, lm, low
return self.__class__(lm[:self.degree]) / low[0]
def __repr__(self):
return repr(self.coeffs)
def __eq__(self, other):
assert isinstance(other, self.__class__)
for c1, c2 in zip(self.coeffs, other.coeffs):
if c1 != c2:
return False
return True
def __ne__(self, other):
return not self == other
def __neg__(self):
return self.__class__([-c for c in self.coeffs])
@classmethod
def one(cls):
return cls([1] + [0] * (cls.degree - 1))
@classmethod
def zero(cls):
return cls([0] * cls.degree)
# The quadratic extension field
class FQ2(FQP):
def __init__(self, coeffs):
self.coeffs = coeffs
self.modulus_coeffs = [1, 0]
self.mc_tuples = [(0, 1)]
self.degree = 2
self.__class__.degree = 2
# The 12th-degree extension field
class FQ12(FQP):
def __init__(self, coeffs):
self.coeffs = coeffs
self.modulus_coeffs = FQ12_modulus_coeffs
self.mc_tuples = FQ12_mc_tuples
self.degree = 12
self.__class__.degree = 12
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/RealWorld/2023/crypto/OKPROOF/py_ecc/optimized_bn128/optimized_pairing.py | ctfs/RealWorld/2023/crypto/OKPROOF/py_ecc/optimized_bn128/optimized_pairing.py | from .optimized_curve import double, add, multiply, is_on_curve, neg, twist, b, b2, b12, curve_order, G1, G2, G12, normalize
from .optimized_field_elements import FQ2, FQ12, field_modulus, FQ
ate_loop_count = 29793968203157093288
log_ate_loop_count = 63
pseudo_binary_encoding = [0, 0, 0, 1, 0, 1, 0, -1, 0, 0, 1, -1, 0, 0, 1, 0,
0, 1, 1, 0, -1, 0, 0, 1, 0, -1, 0, 0, 0, 0, 1, 1,
1, 0, 0, -1, 0, 0, 1, 0, 0, 0, 0, 0, -1, 0, 0, 1,
1, 0, 0, -1, 0, 0, 0, 1, 1, 0, -1, 0, 0, 1, 0, 1, 1]
assert sum([e * 2**i for i, e in enumerate(pseudo_binary_encoding)]) == ate_loop_count
def normalize1(p):
x, y = normalize(p)
return x, y, x.__class__.one()
# Create a function representing the line between P1 and P2,
# and evaluate it at T. Returns a numerator and a denominator
# to avoid unneeded divisions
def linefunc(P1, P2, T):
zero = P1[0].__class__.zero()
x1, y1, z1 = P1
x2, y2, z2 = P2
xt, yt, zt = T
# points in projective coords: (x / z, y / z)
# hence, m = (y2/z2 - y1/z1) / (x2/z2 - x1/z1)
# multiply numerator and denominator by z1z2 to get values below
m_numerator = y2 * z1 - y1 * z2
m_denominator = x2 * z1 - x1 * z2
if m_denominator != zero:
# m * ((xt/zt) - (x1/z1)) - ((yt/zt) - (y1/z1))
return m_numerator * (xt * z1 - x1 * zt) - m_denominator * (yt * z1 - y1 * zt), \
m_denominator * zt * z1
elif m_numerator == zero:
# m = 3(x/z)^2 / 2(y/z), multiply num and den by z**2
m_numerator = 3 * x1 * x1
m_denominator = 2 * y1 * z1
return m_numerator * (xt * z1 - x1 * zt) - m_denominator * (yt * z1 - y1 * zt), \
m_denominator * zt * z1
else:
return xt * z1 - x1 * zt, z1 * zt
def cast_point_to_fq12(pt):
if pt is None:
return None
x, y, z = pt
return (FQ12([x.n] + [0] * 11), FQ12([y.n] + [0] * 11), FQ12([z.n] + [0] * 11))
# Check consistency of the "line function"
one, two, three = G1, double(G1), multiply(G1, 3)
negone, negtwo, negthree = multiply(G1, curve_order - 1), multiply(G1, curve_order - 2), multiply(G1, curve_order - 3)
assert linefunc(one, two, one)[0] == FQ(0)
assert linefunc(one, two, two)[0] == FQ(0)
assert linefunc(one, two, three)[0] != FQ(0)
assert linefunc(one, two, negthree)[0] == FQ(0)
assert linefunc(one, negone, one)[0] == FQ(0)
assert linefunc(one, negone, negone)[0] == FQ(0)
assert linefunc(one, negone, two)[0] != FQ(0)
assert linefunc(one, one, one)[0] == FQ(0)
assert linefunc(one, one, two)[0] != FQ(0)
assert linefunc(one, one, negtwo)[0] == FQ(0)
# Main miller loop
def miller_loop(Q, P, final_exponentiate=True):
if Q is None or P is None:
return FQ12.one()
R = Q
f_num, f_den = FQ12.one(), FQ12.one()
for b in pseudo_binary_encoding[63::-1]:
#for i in range(log_ate_loop_count, -1, -1):
_n, _d = linefunc(R, R, P)
f_num = f_num * f_num * _n
f_den = f_den * f_den * _d
R = double(R)
#if ate_loop_count & (2**i):
if b == 1:
_n, _d = linefunc(R, Q, P)
f_num = f_num * _n
f_den = f_den * _d
R = add(R, Q)
elif b == -1:
nQ = neg(Q)
_n, _d = linefunc(R, nQ, P)
f_num = f_num * _n
f_den = f_den * _d
R = add(R, nQ)
# assert R == multiply(Q, ate_loop_count)
Q1 = (Q[0] ** field_modulus, Q[1] ** field_modulus, Q[2] ** field_modulus)
# assert is_on_curve(Q1, b12)
nQ2 = (Q1[0] ** field_modulus, -Q1[1] ** field_modulus, Q1[2] ** field_modulus)
# assert is_on_curve(nQ2, b12)
_n1, _d1 = linefunc(R, Q1, P)
R = add(R, Q1)
_n2, _d2 = linefunc(R, nQ2, P)
f = f_num * _n1 * _n2 / (f_den * _d1 * _d2)
# R = add(R, nQ2) This line is in many specifications but it technically does nothing
if final_exponentiate:
return f ** ((field_modulus ** 12 - 1) // curve_order)
else:
return f
# Pairing computation
def pairing(Q, P, final_exponentiate=True):
assert is_on_curve(Q, b2)
assert is_on_curve(P, b)
if P[-1] == P[-1].__class__.zero() or Q[-1] == Q[-1].__class__.zero():
return FQ12.one()
return miller_loop(twist(Q), cast_point_to_fq12(P), final_exponentiate=final_exponentiate)
def final_exponentiate(p):
return p ** ((field_modulus ** 12 - 1) // curve_order)
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/RealWorld/2023/crypto/OKPROOF/py_ecc/bn128/bn128_curve.py | ctfs/RealWorld/2023/crypto/OKPROOF/py_ecc/bn128/bn128_curve.py | from .bn128_field_elements import field_modulus, FQ, FQ2, FQ12
curve_order = 21888242871839275222246405745257275088548364400416034343698204186575808495617
# Curve order should be prime
assert pow(2, curve_order, curve_order) == 2
# Curve order should be a factor of field_modulus**12 - 1
assert (field_modulus ** 12 - 1) % curve_order == 0
# Curve is y**2 = x**3 + 3
b = FQ(3)
# Twisted curve over FQ**2
b2 = FQ2([3, 0]) / FQ2([9, 1])
# Extension curve over FQ**12; same b value as over FQ
b12 = FQ12([3] + [0] * 11)
# Generator for curve over FQ
G1 = (FQ(1), FQ(2))
# Generator for twisted curve over FQ2
G2 = (FQ2([10857046999023057135944570762232829481370756359578518086990519993285655852781, 11559732032986387107991004021392285783925812861821192530917403151452391805634]),
FQ2([8495653923123431417604973247489272438418190587263600148770280649306958101930, 4082367875863433681332203403145435568316851327593401208105741076214120093531]))
# Check if a point is the point at infinity
def is_inf(pt):
return pt is None
# Check that a point is on the curve defined by y**2 == x**3 + b
def is_on_curve(pt, b):
if is_inf(pt):
return True
x, y = pt
return y**2 - x**3 == b
assert is_on_curve(G1, b)
assert is_on_curve(G2, b2)
# Elliptic curve doubling
def double(pt):
x, y = pt
l = 3 * x**2 / (2 * y)
newx = l**2 - 2 * x
newy = -l * newx + l * x - y
return newx, newy
# Elliptic curve addition
def add(p1, p2):
if p1 is None or p2 is None:
return p1 if p2 is None else p2
x1, y1 = p1
x2, y2 = p2
if x2 == x1 and y2 == y1:
return double(p1)
elif x2 == x1:
return None
else:
l = (y2 - y1) / (x2 - x1)
newx = l**2 - x1 - x2
newy = -l * newx + l * x1 - y1
assert newy == (-l * newx + l * x2 - y2)
return (newx, newy)
# Elliptic curve point multiplication
def multiply(pt, n):
if n == 0:
return None
elif n == 1:
return pt
elif not n % 2:
return multiply(double(pt), n // 2)
else:
return add(multiply(double(pt), int(n // 2)), pt)
def eq(p1, p2):
return p1 == p2
# "Twist" a point in E(FQ2) into a point in E(FQ12)
w = FQ12([0, 1] + [0] * 10)
# Convert P => -P
def neg(pt):
if pt is None:
return None
x, y = pt
return (x, -y)
def twist(pt):
if pt is None:
return None
_x, _y = pt
# Field isomorphism from Z[p] / x**2 to Z[p] / x**2 - 18*x + 82
xcoeffs = [_x.coeffs[0] - _x.coeffs[1] * 9, _x.coeffs[1]]
ycoeffs = [_y.coeffs[0] - _y.coeffs[1] * 9, _y.coeffs[1]]
# Isomorphism into subfield of Z[p] / w**12 - 18 * w**6 + 82,
# where w**6 = x
nx = FQ12([xcoeffs[0]] + [0] * 5 + [xcoeffs[1]] + [0] * 5)
ny = FQ12([ycoeffs[0]] + [0] * 5 + [ycoeffs[1]] + [0] * 5)
# Divide x coord by w**2 and y coord by w**3
return (nx * w **2, ny * w**3)
G12 = twist(G2)
# Check that the twist creates a point that is on the curve
assert is_on_curve(G12, b12)
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/RealWorld/2023/crypto/OKPROOF/py_ecc/bn128/bn128_pairing.py | ctfs/RealWorld/2023/crypto/OKPROOF/py_ecc/bn128/bn128_pairing.py | from .bn128_curve import double, add, multiply, is_on_curve, neg, twist, b, b2, b12, curve_order, G1, G2, G12
from .bn128_field_elements import field_modulus, FQ, FQ2, FQ12
ate_loop_count = 29793968203157093288
log_ate_loop_count = 63
# Create a function representing the line between P1 and P2,
# and evaluate it at T
def linefunc(P1, P2, T):
assert P1 and P2 and T # No points-at-infinity allowed, sorry
x1, y1 = P1
x2, y2 = P2
xt, yt = T
if x1 != x2:
m = (y2 - y1) / (x2 - x1)
return m * (xt - x1) - (yt - y1)
elif y1 == y2:
m = 3 * x1**2 / (2 * y1)
return m * (xt - x1) - (yt - y1)
else:
return xt - x1
def cast_point_to_fq12(pt):
if pt is None:
return None
x, y = pt
return (FQ12([x.n] + [0] * 11), FQ12([y.n] + [0] * 11))
# Check consistency of the "line function"
one, two, three = G1, double(G1), multiply(G1, 3)
negone, negtwo, negthree = multiply(G1, curve_order - 1), multiply(G1, curve_order - 2), multiply(G1, curve_order - 3)
assert linefunc(one, two, one) == FQ(0)
assert linefunc(one, two, two) == FQ(0)
assert linefunc(one, two, three) != FQ(0)
assert linefunc(one, two, negthree) == FQ(0)
assert linefunc(one, negone, one) == FQ(0)
assert linefunc(one, negone, negone) == FQ(0)
assert linefunc(one, negone, two) != FQ(0)
assert linefunc(one, one, one) == FQ(0)
assert linefunc(one, one, two) != FQ(0)
assert linefunc(one, one, negtwo) == FQ(0)
# Main miller loop
def miller_loop(Q, P):
if Q is None or P is None:
return FQ12.one()
R = Q
f = FQ12.one()
for i in range(log_ate_loop_count, -1, -1):
f = f * f * linefunc(R, R, P)
R = double(R)
if ate_loop_count & (2**i):
f = f * linefunc(R, Q, P)
R = add(R, Q)
# assert R == multiply(Q, ate_loop_count)
Q1 = (Q[0] ** field_modulus, Q[1] ** field_modulus)
# assert is_on_curve(Q1, b12)
nQ2 = (Q1[0] ** field_modulus, -Q1[1] ** field_modulus)
# assert is_on_curve(nQ2, b12)
f = f * linefunc(R, Q1, P)
R = add(R, Q1)
f = f * linefunc(R, nQ2, P)
# R = add(R, nQ2) This line is in many specifications but it technically does nothing
return f ** ((field_modulus ** 12 - 1) // curve_order)
# Pairing computation
def pairing(Q, P):
assert is_on_curve(Q, b2)
assert is_on_curve(P, b)
return miller_loop(twist(Q), cast_point_to_fq12(P))
def final_exponentiate(p):
return p ** ((field_modulus ** 12 - 1) // curve_order)
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/RealWorld/2023/crypto/OKPROOF/py_ecc/bn128/bn128_field_elements.py | ctfs/RealWorld/2023/crypto/OKPROOF/py_ecc/bn128/bn128_field_elements.py | import sys
sys.setrecursionlimit(10000)
# python3 compatibility
try:
foo = long
except:
long = int
# The prime modulus of the field
field_modulus = 21888242871839275222246405745257275088696311157297823662689037894645226208583
# See, it's prime!
assert pow(2, field_modulus, field_modulus) == 2
# The modulus of the polynomial in this representation of FQ12
FQ12_modulus_coeffs = [82, 0, 0, 0, 0, 0, -18, 0, 0, 0, 0, 0] # Implied + [1]
# Extended euclidean algorithm to find modular inverses for
# integers
def inv(a, n):
if a == 0:
return 0
lm, hm = 1, 0
low, high = a % n, n
while low > 1:
r = high//low
nm, new = hm-lm*r, high-low*r
lm, low, hm, high = nm, new, lm, low
return lm % n
# A class for field elements in FQ. Wrap a number in this class,
# and it becomes a field element.
class FQ():
def __init__(self, n):
if isinstance(n, self.__class__):
self.n = n.n
else:
self.n = n % field_modulus
assert isinstance(self.n, (int, long))
def __add__(self, other):
on = other.n if isinstance(other, FQ) else other
return FQ((self.n + on) % field_modulus)
def __mul__(self, other):
on = other.n if isinstance(other, FQ) else other
return FQ((self.n * on) % field_modulus)
def __rmul__(self, other):
return self * other
def __radd__(self, other):
return self + other
def __rsub__(self, other):
on = other.n if isinstance(other, FQ) else other
return FQ((on - self.n) % field_modulus)
def __sub__(self, other):
on = other.n if isinstance(other, FQ) else other
return FQ((self.n - on) % field_modulus)
def __div__(self, other):
on = other.n if isinstance(other, FQ) else other
assert isinstance(on, (int, long))
return FQ(self.n * inv(on, field_modulus) % field_modulus)
def __truediv__(self, other):
return self.__div__(other)
def __rdiv__(self, other):
on = other.n if isinstance(other, FQ) else other
assert isinstance(on, (int, long)), on
return FQ(inv(self.n, field_modulus) * on % field_modulus)
def __rtruediv__(self, other):
return self.__rdiv__(other)
def __pow__(self, other):
if other == 0:
return FQ(1)
elif other == 1:
return FQ(self.n)
elif other % 2 == 0:
return (self * self) ** (other // 2)
else:
return ((self * self) ** int(other // 2)) * self
def __eq__(self, other):
if isinstance(other, FQ):
return self.n == other.n
else:
return self.n == other
def __ne__(self, other):
return not self == other
def __neg__(self):
return FQ(-self.n)
def __repr__(self):
return repr(self.n)
@classmethod
def one(cls):
return cls(1)
@classmethod
def zero(cls):
return cls(0)
# Utility methods for polynomial math
def deg(p):
d = len(p) - 1
while p[d] == 0 and d:
d -= 1
return d
def poly_rounded_div(a, b):
dega = deg(a)
degb = deg(b)
temp = [x for x in a]
o = [0 for x in a]
for i in range(dega - degb, -1, -1):
o[i] += temp[degb + i] / b[degb]
for c in range(degb + 1):
temp[c + i] -= o[c]
return o[:deg(o)+1]
# A class for elements in polynomial extension fields
class FQP():
def __init__(self, coeffs, modulus_coeffs):
assert len(coeffs) == len(modulus_coeffs)
self.coeffs = [FQ(c) for c in coeffs]
# The coefficients of the modulus, without the leading [1]
self.modulus_coeffs = modulus_coeffs
# The degree of the extension field
self.degree = len(self.modulus_coeffs)
def __add__(self, other):
assert isinstance(other, self.__class__)
return self.__class__([x+y for x,y in zip(self.coeffs, other.coeffs)])
def __sub__(self, other):
assert isinstance(other, self.__class__)
return self.__class__([x-y for x,y in zip(self.coeffs, other.coeffs)])
def __mul__(self, other):
if isinstance(other, (FQ, int, long)):
return self.__class__([c * other for c in self.coeffs])
else:
assert isinstance(other, self.__class__)
b = [FQ(0) for i in range(self.degree * 2 - 1)]
for i in range(self.degree):
for j in range(self.degree):
b[i + j] += self.coeffs[i] * other.coeffs[j]
while len(b) > self.degree:
exp, top = len(b) - self.degree - 1, b.pop()
for i in range(self.degree):
b[exp + i] -= top * FQ(self.modulus_coeffs[i])
return self.__class__(b)
def __rmul__(self, other):
return self * other
def __div__(self, other):
if isinstance(other, (FQ, int, long)):
return self.__class__([c / other for c in self.coeffs])
else:
assert isinstance(other, self.__class__)
return self * other.inv()
def __truediv__(self, other):
return self.__div__(other)
def __pow__(self, other):
if other == 0:
return self.__class__([1] + [0] * (self.degree - 1))
elif other == 1:
return self.__class__(self.coeffs)
elif other % 2 == 0:
return (self * self) ** (other // 2)
else:
return ((self * self) ** int(other // 2)) * self
# Extended euclidean algorithm used to find the modular inverse
def inv(self):
lm, hm = [1] + [0] * self.degree, [0] * (self.degree + 1)
low, high = self.coeffs + [0], self.modulus_coeffs + [1]
while deg(low):
r = poly_rounded_div(high, low)
r += [0] * (self.degree + 1 - len(r))
nm = [x for x in hm]
new = [x for x in high]
assert len(lm) == len(hm) == len(low) == len(high) == len(nm) == len(new) == self.degree + 1
for i in range(self.degree + 1):
for j in range(self.degree + 1 - i):
nm[i+j] -= lm[i] * r[j]
new[i+j] -= low[i] * r[j]
lm, low, hm, high = nm, new, lm, low
return self.__class__(lm[:self.degree]) / low[0]
def __repr__(self):
return repr(self.coeffs)
def __eq__(self, other):
assert isinstance(other, self.__class__)
for c1, c2 in zip(self.coeffs, other.coeffs):
if c1 != c2:
return False
return True
def __ne__(self, other):
return not self == other
def __neg__(self):
return self.__class__([-c for c in self.coeffs])
@classmethod
def one(cls):
return cls([1] + [0] * (cls.degree - 1))
@classmethod
def zero(cls):
return cls([0] * cls.degree)
# The quadratic extension field
class FQ2(FQP):
def __init__(self, coeffs):
self.coeffs = [FQ(c) for c in coeffs]
self.modulus_coeffs = [1, 0]
self.degree = 2
self.__class__.degree = 2
# The 12th-degree extension field
class FQ12(FQP):
def __init__(self, coeffs):
self.coeffs = [FQ(c) for c in coeffs]
self.modulus_coeffs = FQ12_modulus_coeffs
self.degree = 12
self.__class__.degree = 12
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/RealWorld/2023/crypto/OKPROOF/py_ecc/bn128/__init__.py | ctfs/RealWorld/2023/crypto/OKPROOF/py_ecc/bn128/__init__.py | from .bn128_field_elements import field_modulus, FQ, FQP, FQ2, FQ12
from .bn128_curve import add, double, multiply, is_inf, is_on_curve, eq, neg, twist, b, b2, b12, curve_order, G1, G2, G12
from .bn128_pairing import pairing, final_exponentiate
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/RealWorld/2022/pwn/secured-java/secured_java.py | ctfs/RealWorld/2022/pwn/secured-java/secured_java.py | #!/usr/bin/env python
import os
import base64
import tempfile
import subprocess
SOURCE_FILE = "Main.java"
DEP_FILE = "dep.jar"
def get_file(filename: str):
print(f"Please send me the file {filename}.")
content = input("Content: (base64 encoded)")
data = base64.b64decode(content)
if len(data) > 1024 * 1024:
raise ValueError("Too long")
with open(filename, "wb") as fp:
fp.write(data)
def main():
print("Welcome to the secured Java sandbox.")
with tempfile.TemporaryDirectory() as dir:
os.chdir(dir)
get_file("Main.java")
get_file("dep.jar")
print("Compiling...")
try:
subprocess.run(
["javac", "-cp", DEP_FILE, SOURCE_FILE],
input=b"",
check=True,
)
except subprocess.CalledProcessError:
print("Failed to compile!")
exit(1)
print("Running...")
try:
subprocess.run(["java", "--version"])
subprocess.run(
[
"java",
"-cp",
f".:{DEP_FILE}",
"-Djava.security.manager",
"-Djava.security.policy==/dev/null",
"Main",
],
check=True,
)
except subprocess.CalledProcessError:
print("Failed to run!")
exit(2)
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/RealWorld/2022/pwn/flag/flag.py | ctfs/RealWorld/2022/pwn/flag/flag.py | import requests
import time
url = "http://localhost:5555/action/backdoor"
flag_path = "/mnt/flag.txt"
def get_flag(path: str):
with open(path, 'r') as fp:
return fp.read().strip()
def check_backdoor():
r = requests.get(url)
if r.status_code == 200:
resp = r.json()
if "status" in resp and resp['status'] == "success":
r.close()
return True
r.close()
return False
def post_flag(flag: str):
params = {"flag": flag}
r = requests.get(url, params=params)
r.close()
try:
if check_backdoor():
f = get_flag(flag_path)
post_flag(f)
except Exception:
exit(1)
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/RealWorld/2022/pwn/QLaaS/main.py | ctfs/RealWorld/2022/pwn/QLaaS/main.py | #!/usr/bin/env python3
import os
import sys
import base64
import tempfile
# pip install qiling==1.4.1
from qiling import Qiling
def my_sandbox(path, rootfs):
ql = Qiling([path], rootfs)
ql.run()
def main():
sys.stdout.write('Your Binary(base64):\n')
line = sys.stdin.readline()
binary = base64.b64decode(line.strip())
with tempfile.TemporaryDirectory() as tmp_dir:
fp = os.path.join(tmp_dir, 'bin')
with open(fp, 'wb') as f:
f.write(binary)
my_sandbox(fp, tmp_dir)
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/RealWorld/2022/web/hack_into_skynet/server.py | ctfs/RealWorld/2022/web/hack_into_skynet/server.py | #!/usr/bin/env python3
import flask
import psycopg2
import datetime
import hashlib
from skynet import Skynet
app = flask.Flask(__name__, static_url_path='')
skynet = Skynet()
def skynet_detect():
req = {
'method': flask.request.method,
'path': flask.request.full_path,
'host': flask.request.headers.get('host'),
'content_type': flask.request.headers.get('content-type'),
'useragent': flask.request.headers.get('user-agent'),
'referer': flask.request.headers.get('referer'),
'cookie': flask.request.headers.get('cookie'),
'body': str(flask.request.get_data()),
}
_, result = skynet.classify(req)
return result and result['attack']
@app.route('/static/<path:path>')
def static_files(path):
return flask.send_from_directory('static', path)
@app.route('/', methods=['GET', 'POST'])
def do_query():
if skynet_detect():
return flask.abort(403)
if not query_login_state():
response = flask.make_response('No login, redirecting', 302)
response.location = flask.escape('/login')
return response
if flask.request.method == 'GET':
return flask.send_from_directory('', 'index.html')
elif flask.request.method == 'POST':
kt = query_kill_time()
if kt:
result = kt
else:
result = ''
return flask.render_template('index.html', result=result)
else:
return flask.abort(400)
@app.route('/login', methods=['GET', 'POST'])
def do_login():
if skynet_detect():
return flask.abort(403)
if flask.request.method == 'GET':
return flask.send_from_directory('static', 'login.html')
elif flask.request.method == 'POST':
if not query_login_attempt():
return flask.send_from_directory('static', 'login.html')
else:
session = create_session()
response = flask.make_response('Login success', 302)
response.set_cookie('SessionId', session)
response.location = flask.escape('/')
return response
else:
return flask.abort(400)
def query_login_state():
sid = flask.request.cookies.get('SessionId', '')
if not sid:
return False
now = datetime.datetime.now()
with psycopg2.connect(
host="challenge-db",
database="ctf",
user="ctf",
password="ctf") as conn:
cursor = conn.cursor()
cursor.execute("SELECT sessionid"
" FROM login_session"
" WHERE sessionid = %s"
" AND valid_since <= %s"
" AND valid_until >= %s"
"", (sid, now, now))
data = [r for r in cursor.fetchall()]
return bool(data)
def query_login_attempt():
username = flask.request.form.get('username', '')
password = flask.request.form.get('password', '')
if not username and not password:
return False
sql = ("SELECT id, account"
" FROM target_credentials"
" WHERE password = '{}'").format(hashlib.md5(password.encode()).hexdigest())
user = sql_exec(sql)
name = user[0][1] if user and user[0] and user[0][1] else ''
return name == username
def create_session():
valid_since = datetime.datetime.now()
valid_until = datetime.datetime.now() + datetime.timedelta(days=1)
sessionid = hashlib.md5((str(valid_since)+str(valid_until)+str(datetime.datetime.now())).encode()).hexdigest()
sql_exec_update(("INSERT INTO login_session (sessionid, valid_since, valid_until)"
" VALUES ('{}', '{}', '{}')").format(sessionid, valid_since, valid_until))
return sessionid
def query_kill_time():
name = flask.request.form.get('name', '')
if not name:
return None
sql = ("SELECT name, born"
" FROM target"
" WHERE age > 0"
" AND name = '{}'").format(name)
nb = sql_exec(sql)
if not nb:
return None
return '{}: {}'.format(*nb[0])
def sql_exec(stmt):
data = list()
try:
with psycopg2.connect(
host="challenge-db",
database="ctf",
user="ctf",
password="ctf") as conn:
cursor = conn.cursor()
cursor.execute(stmt)
for row in cursor.fetchall():
data.append([col for col in row])
cursor.close()
except Exception as e:
print(e)
return data
def sql_exec_update(stmt):
data = list()
try:
with psycopg2.connect(
host="challenge-db",
database="ctf",
user="ctf",
password="ctf") as conn:
cursor = conn.cursor()
cursor.execute(stmt)
conn.commit()
except Exception as e:
print(e)
return data
if __name__ == "__main__":
app.run(host='0.0.0.0', port=8080)
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/MCTF/2021/Quals/web/Starlights_File_Saver/config.py | ctfs/MCTF/2021/Quals/web/Starlights_File_Saver/config.py | import os
basedir = os.path.abspath(os.path.dirname(__file__))
class Config(object):
SECRET_KEY = os.environ.get("SECRET_KEY")
SQLALCHEMY_DATABASE_URI = os.environ.get("DATABASE_URL")
SQLALCHEMY_TRACK_MODIFICATIONS = False
UPLOAD_FOLDER = os.path.join(basedir, "uploads")
CACHE_TYPE = 'FileSystemCache'
CACHE_DIR = "./cache/"
MAX_CONTENT_LENGTH = 16 * 1024 * 1024 | python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/MCTF/2021/Quals/web/Starlights_File_Saver/app.py | ctfs/MCTF/2021/Quals/web/Starlights_File_Saver/app.py | from app import app | python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/MCTF/2021/Quals/web/Starlights_File_Saver/app/models.py | ctfs/MCTF/2021/Quals/web/Starlights_File_Saver/app/models.py | from flask_login import UserMixin
from app import db, login
from werkzeug.security import generate_password_hash, check_password_hash
from dataclasses import dataclass
class User(UserMixin, db.Model):
id = db.Column(db.Integer, primary_key=True)
username = db.Column(db.String(120), index=True, unique=True)
password_hash = db.Column(db.String(128))
def set_password(self, password):
self.password_hash = generate_password_hash(password, method="sha256")
def check_password(self, password):
return check_password_hash(self.password_hash, password)
@dataclass
class File(db.Model):
id: int
filename: str
id = db.Column(db.Integer, primary_key=True)
filename = db.Column(db.String(32))
user_id = db.Column(db.Integer, db.ForeignKey("user.id"))
@login.user_loader
def load_user(id):
return User.query.get(int(id))
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/MCTF/2021/Quals/web/Starlights_File_Saver/app/__init__.py | ctfs/MCTF/2021/Quals/web/Starlights_File_Saver/app/__init__.py | from flask import Flask
from config import Config
from flask_caching import Cache
from flask_sqlalchemy import SQLAlchemy
from flask_login import LoginManager
app = Flask(__name__)
app.config.from_object(Config)
db = SQLAlchemy(app)
cache = Cache(app)
login = LoginManager(app)
from app import routes, models
db.create_all()
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/MCTF/2021/Quals/web/Starlights_File_Saver/app/routes.py | ctfs/MCTF/2021/Quals/web/Starlights_File_Saver/app/routes.py | import os
from flask import redirect, url_for, send_from_directory, escape, jsonify, request
from app import app, cache, db
from flask_login import login_required, current_user, login_user, logout_user
from app.models import User, File
from werkzeug.utils import secure_filename
@app.route('/api/')
def index():
if current_user.is_authenticated:
return jsonify({"Username": current_user.username})
else:
return jsonify({"Message": "Not auth"}), 403
@app.route('/api/login', methods=["POST"])
def login():
if current_user.is_authenticated:
return jsonify({"Message": "You authenticated already."})
if request.method == "POST":
post_data = request.get_json(force=True)
user = User.query.filter_by(username=post_data.get("login")).first()
if user is None or not user.check_password(post_data.get("password")):
return jsonify({"Message": "Wrong credentials"}), 400
login_user(user, remember=post_data.get("remember"))
return jsonify({"Message": "Login success."})
@app.route('/api/logout')
def logout():
logout_user()
return jsonify({"Message": "Logout committed."})
@app.route('/api/register', methods=["POST"])
def register():
if current_user.is_authenticated:
return jsonify({"Message": "You authenticated already."})
if request.method == "POST":
post_data = request.get_json(force=True)
user = User(username=post_data.get("login"))
user.set_password(post_data.get("password"))
if User.query.filter_by(username=post_data.get("login")).first() is not None \
or escape(post_data.get("login")) != post_data.get("login") \
or secure_filename(post_data.get("login")) != post_data.get("login"):
return jsonify({"Message": "Bad username."}), 400
db.session.add(user)
db.session.commit()
login_user(user)
os.mkdir(os.path.join(app.config["UPLOAD_FOLDER"], current_user.username))
return jsonify({"Message": "Register success."})
@app.route("/api/<username>/files", methods=["GET"])
@cache.cached(timeout=10)
def ufiles(username):
if not current_user.is_authenticated:
return jsonify({"Message": "Not auth"}), 403
if username != current_user.username:
return jsonify({"Message": "You have no access to files!"}), 403
files = File.query.filter_by(user_id=current_user.id).all()
return jsonify(files)
@app.route('/api/<username>/files/upload', methods=["POST"])
def upload(username):
if not current_user.is_authenticated:
return jsonify({"Message": "Not auth"}), 403
if username != current_user.username:
return jsonify({"Message": "You have no access to files!"}), 403
f = request.files['file']
filename = f.filename
f.save(os.path.join(app.config['UPLOAD_FOLDER'], current_user.username, filename))
file = File(filename=f.filename, user_id=current_user.id)
db.session.add(file)
db.session.commit()
return jsonify({"Message": "File uploaded successfully."})
@app.route("/api/files/<id>")
def files(id):
if not current_user.is_authenticated:
return jsonify({"Message": "Not auth"}), 403
file = File.query.filter_by(id=id).first()
if file is None or file.user_id != current_user.id:
return jsonify({"Message": "You have no access to files!"})
return send_from_directory(os.path.join(app.config['UPLOAD_FOLDER'], current_user.username), file.filename,
as_attachment=True)
@app.route("/api/healthcheck")
def healthcheck():
if os.environ.get("Secret_Flag"):
return "Ok!"
else:
return "Something wrong!", 500
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/MCTF/2024/Quals/pwn/Achilles/75fbfc64-2398-4f0c-b74b-2f42815ef7ca.py | ctfs/MCTF/2024/Quals/pwn/Achilles/75fbfc64-2398-4f0c-b74b-2f42815ef7ca.py | import sys
from keyword import iskeyword
from keyword import issoftkeyword
from os import environ
print(
'''
.. . .. .. .x+=:.
:**888H: `: .xH"" .uef^" @88> x .d88" x .d88" z` ^%
X `8888k XX888 :d88E %8P 5888R 5888R . <k
'8hx 48888 ?8888 . `888E . '888R '888R .u .@8Ned8"
'8888 '8888 `8888 .udR88N 888E .z8k .@88u 888R 888R ud8888. .@^%8888"
%888>'8888 8888 <888'888k 888E~?888L ''888E` 888R 888R :888'8888. x88: `)8b.
"8 '888" 8888 9888 'Y" 888E 888E 888E 888R 888R d888 '88%" 8888N=*8888
.-` X*" 8888 9888 888E 888E 888E 888R 888R 8888.+" %8" R88
.xhx. 8888 9888 888E 888E 888E 888R 888R 8888L @8Wou 9%
.H88888h.~`8888.> ?8888u../ 888E 888E 888& .888B . .888B . '8888c. .+ .888888P`
.~ `%88!` '888*~ "8888P' m888N= 888> R888" ^*888% ^*888% "88888% ` ^"F
`" "" "P' `Y" 888 "" "% "% "YP'
J88"
@%
:"
'''
)
def retreat():
print('Better be a late learner than an ignorant..')
def conquer():
print('Ten soldiers wisely led will beat a hundred without a head..')
print(environ['FLAG'])
function = input('What would a wise polemarch do? [retreat / conquer] ')
if not function.isidentifier():
sys.exit(f'Invalid identifier: {function!r}')
elif iskeyword(function) or issoftkeyword(function):
sys.exit(f'Reserved identifier: {function!r}')
elif function == 'conquer':
sys.exit('Option [conquer] is temporarily unavailable!')
try:
global_variables = {
'__builtins__': {},
'retreat': retreat,
'conquer': conquer,
}
eval(f'{function}()', global_variables)
except NameError:
sys.exit(f'Option [{function}] is not available!')
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/MCTF/2023-Junior/Quals/crypto/Outer_space/algorithm.py | ctfs/MCTF/2023-Junior/Quals/crypto/Outer_space/algorithm.py | import random
from string import ascii_lowercase, digits
FLAG = 'mctf{redacted}'
alphabet = digits + ascii_lowercase
encrypt_table = {i: v for i, v in enumerate(alphabet)}
decrypt_table = {v: i for i, v in enumerate(alphabet)}
def encrypt(index: int) -> str:
return encrypt_table[index // 36] + encrypt_table[index % 36]
def decrypt(string: str) -> int:
return decrypt_table[string[0]] * 36 + decrypt_table[string[1]]
output = [''] * 1295
pos = random.randint(0, 1295)
for char in FLAG:
if char == '{':
char = 'v'
elif char == '}':
char = 'w'
output[pos] = char + encrypt_table[random.randint(0, 35)]
pos = decrypt(output[pos])
for i, v in enumerate(output):
if not v:
output[i] = encrypt(random.randint(0, 1295))
if __name__ == '__main__':
with open('hash.txt', 'w') as file:
file.write(''.join(output))
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/MCTF/2023-Junior/Quals/web/CatoCloud/main.py | ctfs/MCTF/2023-Junior/Quals/web/CatoCloud/main.py | import os
import time
import requests
from string import ascii_lowercase
from itertools import product
from flask import *
ALPHABET = product(ascii_lowercase, repeat=3)
app = Flask(__name__)
import utils
@app.route('/')
def main_page():
return render_template('index.html')
@app.route('/upload', methods=['POST'])
def upload_file():
global ALPHABET
name = request.json.get('name')
data = request.json.get('data')
if not data or len(data) > 67108864 or not utils.verify_upload(name, data):
return '#'
next_id = ''.join(next(ALPHABET, []))
if not next_id:
ALPHABET = product(ascii_lowercase, repeat=3)
utils.reset_storage()
return '#'
storage_size = sum(os.path.getsize(f'./storage/{file}') for file in os.listdir('./storage'))
if storage_size + len(data) > 1073741824: # 1 GB
utils.reset_storage()
return '#'
if any((file.startswith(next_id) for file in os.listdir('./storage'))):
return '#'
with open(f'./storage/{next_id}_{name}', 'w', encoding='utf-8') as f:
f.write(data)
return next_id
@app.route('/<regex("[a-z]{3}/*"):address>')
def retrieve_file(address):
target = requests.get(f'http://127.0.0.1:8080/check_file/{address}').text
if not target:
time.sleep(1)
return redirect('/')
return render_template('file.html', address=address,
name='<html><head><title>Burp Suite Professional</title> <style type="text/css"> body { background: #dedede; font-family: Arial, sans-serif; color: #404042; -webkit-font-smoothing: antialiased; } #container { padding: 0 15px; margin: 10px auto; background-color: #ffffff; } a { word-wrap: break-word; } a:link, a:visited { color: #e06228; text-decoration: none; } a:hover, a:active { color: #404042; text-decoration: underline; } h1 { font-size: 1.6em; line-height: 1.2em; font-weight: normal; color: #404042; } h2 { font-size: 1.3em; line-height: 1.2em; padding: 0; margin: 0.8em 0 0.3em 0; font-weight: normal; color: #404042;} .title, .navbar { color: #ffffff; background: #e06228; padding: 10px 15px; margin: 0 -15px 10px -15px; overflow: hidden; } .title h1 { color: #ffffff; padding: 0; margin: 0; font-size: 1.8em; } div.navbar {position: absolute; top: 18px; right: 25px;} div.navbar ul {list-style-type: none; margin: 0; padding: 0;} div.navbar li {display: inline; margin-left: 20px;} div.navbar a {color: white; padding: 10px} div.navbar a:hover, div.navbar a:active {text-decoration: none; background: #404042;} </style> </head> <body> <div id="container"> <div class="title"><h1>Burp Suite Professional</h1></div> <h1>Error</h1><p>Invalid client request received: First line of request did not contain an absolute URL - try enabling invisible proxy support.</p> <div class="request">GET /check_file/' + address + ' HTTP/1.1<br> Host: 127.0.0.1:666<br> User-Agent: python-requests/2.28.2<br> Accept-Encoding: gzip, deflate, br<br> Accept: */*<br> Connection: keep-alive<br> <br> </div><p> </p> </div> </body> </html>')
@app.route('/storage/<path:filename>')
def download_file(filename):
try:
return send_from_directory('./storage', filename, as_attachment=True)
except FileNotFoundError:
abort(404)
utils.reset_storage()
if __name__ == "__main__":
app.run('127.0.0.1', 8080, threaded=True)
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/MCTF/2023/Quals/rev/Anaconda/anaconda.py | ctfs/MCTF/2023/Quals/rev/Anaconda/anaconda.py | exec(__import__('zlib').decompress(b'x\x9c\xad\x97\xcd\x8e-\xdbq\x9c_\x853\xf2\xc2\x82\x91\xe9\x91\xa0W\x114 e\xda\x96!S\x80\xe0\x81\x1f\xdf\x90NeD\xe4\xaa\x95?u\xcf\x01\xd9gww\xad\x95?\x11_\xec\xde\xf7\xaf\xff\xef\xaf\xff\xfc\xa7?\xfd\xeb\x9f\xff\xcf_\xfe\xfb\x9f\xff\xf0\xe7\x7f\xf8\xe3\x1f\xff\xeb\xff\xfe\xb7\x7f\xf9\xdb\x9f\xfe\xf1\x9f\xff\xd7\xbf\xff\xe9_\xfe\xf6\x7f\xff\xf4\xe7\x7f\xfc\xcb?\xfc\xe5\xbf\xfc\xfd?\xfd\xdd\x7f\xfb\xed\xb7\xff\xf1o\xff\xfe\x87\xbf\xfc\xe1_\xfe\xf6\x87\x7f\xff\xf3\xdf\xfe\xe7_\xffd\x7f\xf7\xaf\x7f\xfd\xdb\x9f\xfe\xfc\xdb\xdf\xfd\xfdo\xff\xf4\xdbo\x7f\xfa\xa3\xb9\x9b\xf9\x7f\xfc\xcf\xff\xe3;\x93\x9f\xe5\x07\xb3\xe7\x84\xf3\xf5?\x7f\xff\xe3\xf5\xf9\xad=\xf7\x9f\xe7\xff\xf9\xd8~\xdcy\xdf\x8f\xba8\xe3\xf1=\xba=\xc5\x9e\xa3\xce\x99\\\xee=\x0f\xf5\x8aY\x9c\x93\xf3\xcf8\x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fo\xfd==\x1f\xf9\xdb\xea\xe7\xa6\xa3\x93\x8fR\x1f\x12@=`\xf4\xaf\xd2\'\xfc\xc32\x9f\xf2\x13\xe3\x9c\xd2\xe1\xfc\xfc\xf7\xdb9\xb5\xb1zy\xff\x9e\xcf\x89/U}\xf4\xc7\xd3\xdd\xa1\xbfO\xfd\x8f\xfc\xc8,U}\xd7y\x9a\xfa\xa9\x8eV\xbd\xefw\xcc\x1b{\xd0\xf5\x82\xef\x93\xda\r\xdf5\x9f@\x8d\xf5\'\xfe\xfd]?A\x04?\xc8\xfa\xcc\x9f\xce\xd3\xf5gS2\xa1\xb9*\xfc\xfb\xb1\xfb\xcc\x87%\x80\xd3\xfc;\x7f\xb8\xff\x17\x7f\xda\xf9\x9f\xa9\xa1\xd2\xe4\x8f\xce\xdf\xf1\xf7\xe2\xbb\xe9\x0f\xfd\xa8y\xb9\xbf\xd6\x83\xa2\xc3~\xa7?\xfas\xbc\x11\xb5\xfc\xba\x1d|\xd6\xfe&~_\xfa\xd8\xf3\xf7/\xe7a\xe | python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | true |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/CyberLeague/2025/pwn/doublemap/template.py | ctfs/CyberLeague/2025/pwn/doublemap/template.py | #!/usr/bin/env python3
from pwn import *
elf = ELF("dist/bo")
if args.REMOTE:
io = remote("localhost", 8080)
else:
io = elf.process()
io.interactive() | python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/CyberLeague/2025/pwn/file_storage/template.py | ctfs/CyberLeague/2025/pwn/file_storage/template.py | #!/usr/bin/env python3
from pwn import *
elf = ELF("dist/bo")
if args.REMOTE:
io = remote("localhost", 8080)
else:
io = elf.process()
io.interactive() | python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/CyberLeague/2025/pwn/Buffer_Overflow_1/template.py | ctfs/CyberLeague/2025/pwn/Buffer_Overflow_1/template.py | #!/usr/bin/env python3
from pwn import *
elf = ELF("dist/bo")
if args.REMOTE:
io = remote("localhost", 8080)
else:
io = elf.process()
io.interactive() | python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/CyberLeague/2025/pwn/pprotocol/template.py | ctfs/CyberLeague/2025/pwn/pprotocol/template.py | #!/usr/bin/env python3
from pwn import *
elf = ELF("dist/bo")
if args.REMOTE:
io = remote("localhost", 8080)
else:
io = elf.process()
io.interactive() | python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/CyberLeague/2025/crypto/Baby_LCG/enc.py | ctfs/CyberLeague/2025/crypto/Baby_LCG/enc.py | from Crypto.Cipher import AES
from Crypto.Random.random import getrandbits
from Crypto.Util.number import getPrime, long_to_bytes
from Crypto.Util.Padding import pad
import binascii
while True:
key = getrandbits(128)
mult = getrandbits(128)
inc = getrandbits(128)
mod = getPrime(128)
if key < mod and mult < mod and inc < mod:
break
flag = b"[REDACTED]"
cipher = AES.new(long_to_bytes(key), AES.MODE_CBC)
ct = cipher.encrypt(pad(flag, AES.block_size))
print("ct =", binascii.hexlify(ct))
print("iv =", binascii.hexlify(cipher.iv))
print("mod =", mod)
for i in range(1, 58):
key = (key * mult + inc) % mod
if i % 19 == 0:
print("Round", i, "-", key) | python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/CyberLeague/2025/crypto/one_time_pin/app.py | ctfs/CyberLeague/2025/crypto/one_time_pin/app.py | #!/usr/bin/env python3
import asyncio
import logging
import random
from pathlib import Path
logger = logging.basicConfig(level=logging.INFO)
HOST = "0.0.0.0"
PORT = 10008
FLAG = Path("flag.txt").read_bytes()
async def print_prompt(writer: asyncio.StreamWriter):
writer.writelines(
(
b"Welcome Admin!\n",
b"Please enter your 8-char one time pin to continue [00000000 - ffffffff]:",
)
)
await writer.drain()
async def read_pin(reader: asyncio.StreamReader, writer: asyncio.StreamWriter):
while not (line := await reader.readline()):
writer.write(b"Please enter a valid PIN\n")
await writer.drain()
return int(line.rstrip(), base=16)
async def handler(reader: asyncio.StreamReader, writer: asyncio.StreamWriter):
client_ip, client_port = reader._transport.get_extra_info("peername")
logging.info(f"New connection from: {client_ip}:{client_port}")
rand = random.Random()
try:
while True:
await print_prompt(writer)
pin = await read_pin(reader, writer)
num = rand.randrange(2**32 - 1)
if pin != num:
delta = abs(pin - num)
writer.write(f"Error {hex(delta)}: Incorrect PIN.".encode())
else:
writer.write(b"Well done! Here is your flag: " + FLAG)
break
await writer.drain()
except Exception as e:
writer.write(f"Unexpected PIN provided. {e}".encode())
await writer.drain()
finally:
writer.write_eof()
writer.close()
async def main(host, port):
srv = await asyncio.start_server(handler, host, port)
await srv.serve_forever()
if __name__ == "__main__":
asyncio.run(main(HOST, PORT))
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/RCTF/2018/simulator/pow.py | ctfs/RCTF/2018/simulator/pow.py | #!/usr/bin/python -u
# encoding: utf-8
import random, string, subprocess, os, sys
from hashlib import sha256
os.chdir(os.path.dirname(os.path.realpath(__file__)))
def proof_of_work():
chal = ''.join(random.choice(string.letters+string.digits) for _ in xrange(16))
print chal
sol = sys.stdin.read(4)
if len(sol) != 4 or not sha256(chal + sol).digest().startswith('\0\0\0'):
exit()
def exec_serv(name):
p = subprocess.Popen(name)
p.communicate()
if __name__ == '__main__':
proof_of_work()
exec_serv('/home/ctf/run.sh') | python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/RCTF/2022/crypto/magic_sign/task.py | ctfs/RCTF/2022/crypto/magic_sign/task.py | from magic import Magic
with open('flag.txt', 'rb') as f:
flag = f.read()
banner = '''
ββββ ββββ ββββββ βββββββ βββ βββββββ βββββββββββ βββββββ ββββ βββ
βββββ βββββββββββββββββββββ βββββββββββ βββββββββββββββββββ βββββ βββ
ββββββββββββββββββββββ ββββββββββ ββββββββββββββ ββββββββββ βββ
ββββββββββββββββββββββ βββββββββ ββββββββββββββ βββββββββββββ
βββ βββ ββββββ βββββββββββββββββββββββ βββββββββββββββββββββββ ββββββ
βββ ββββββ βββ βββββββ βββ βββββββ βββββββββββ βββββββ βββ βββββ
'''
print(banner)
magic = Magic(137) # most magical number
C, K, Q = magic.random_list(3)
P1, P2 = C*K, K*Q
pk, sk = (C, P1, P2), (C, K, Q)
print('C =', pk[0])
print('P1 =', pk[1])
print('P2 =', pk[2])
H = magic.shake(b'Gotta make you understand~')
S = H*Q # sign
assert P1*S == C*H*P2 # verify
print('S =', S)
H = magic.shake(b'Never gonna give you flag~')
try:
S_ = magic(input('> ')[:magic.N])
if P1*S_ == C*H*P2:
print(flag)
else:
print('Ooh~~~give~you~up~')
except:
print('You know the rules and so~do~I~')
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/RCTF/2022/crypto/magic_sign/magic.py | ctfs/RCTF/2022/crypto/magic_sign/magic.py | from secrets import randbits
from Crypto.Hash import SHAKE256
import re
Magic_Latin_Square = [[5, 3, 1, 6, 7, 2, 0, 4],
[3, 5, 0, 2, 4, 6, 1, 7],
[6, 2, 4, 5, 0, 3, 7, 1],
[4, 7, 6, 1, 3, 0, 2, 5],
[0, 1, 3, 7, 6, 4, 5, 2],
[7, 4, 2, 0, 5, 1, 6, 3],
[2, 6, 7, 3, 1, 5, 4, 0],
[1, 0, 5, 4, 2, 7, 3, 6]]
class Magic():
def __init__(self, N):
self.N = N
def __call__(self, x):
if isinstance(x, int):
return MagicElement(x)
elif isinstance(x, list):
return MagicList(self, x)
elif isinstance(x, str):
return MagicList(self, [int(i) for i in x])
def random_element(self):
return randbits(3)
def random_list(self, n):
return (MagicList(self, [self.random_element() for _ in range(self.N)]) for i in range(n))
def shake(self, something):
H = SHAKE256.new()
H.update(something)
H = re.findall(r'\d{3}', bin(int.from_bytes(
H.read(384 // 8), 'big'))[2:].zfill(3*self.N))
return self([int(i, 2) for i in H])
class MagicElement():
def __init__(self, value):
self.value = int(value) % 8
def __eq__(self, other):
return self.value == other.value
def __add__(self, other):
return MagicElement(Magic_Latin_Square[self.value][other.value])
def __str__(self):
return str(self.value)
class MagicList():
def __init__(self, magic, lst):
self.magic = magic
self.N = magic.N
self.U = [_ for _ in self.generator(self.N**2+1)]
if isinstance(lst, MagicList):
self.lst = lst.lst
elif isinstance(lst[0], int):
self.lst = [MagicElement(_) for _ in lst]
elif isinstance(lst[0], MagicElement):
self.lst = [_ for _ in lst]
def generator(self, x):
U = [(7*(3*i+5)**17+11) % self.N for i in range(self.N)]
for i in range(x):
yield U[i % self.N]
if self.N-i % self.N == 1:
V = U[:]
for j in range(self.N):
U[j] = V[U[j]]
i = i + 1
return
def mix(self, T, K):
R = T+K
e = self.U[0]
for i in range(self.N ** 2):
d = self.U[i+1]
R.lst[d] = R.lst[d] + R.lst[e]
e = d
R = R+K
return R
def __add__(self, other):
R = []
for i in range(self.N):
R.append(self.lst[i] + other.lst[i])
return MagicList(self.magic, R)
def __mul__(self, other):
return MagicList(self.magic, self.mix(self, other))
def __eq__(self, other):
for i in range(len(self.lst)):
if self.lst[i].value != other.lst[i].value:
return False
return True
def __str__(self):
if isinstance(self.lst[0], int):
return ''.join([str(i) for i in self.lst])
elif isinstance(self.lst[0], MagicElement):
return ''.join([str(i.value) for i in self.lst])
def __len__(self):
return len(self.lst)
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/RCTF/2022/crypto/Derek/app/util.py | ctfs/RCTF/2022/crypto/Derek/app/util.py | from Crypto.Cipher import AES
def nsplit(s: list, n: int):
return [s[k: k + n] for k in range(0, len(s), n)]
def aes(data: int, key: bytes) -> int:
data = data.to_bytes(16, 'big')
E = AES.new(key, AES.MODE_ECB)
return int.from_bytes(E.encrypt(data), 'big')
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/RCTF/2022/crypto/Derek/app/task.py | ctfs/RCTF/2022/crypto/Derek/app/task.py | import os
from Derek import Derek
with open('flag.txt', 'rb') as f:
flag = f.read()
banner = '''
βββββββ βββββββββββββββ βββββββββββ βββ
βββββββββββββββββββββββββββββββββββ ββββ
βββ βββββββββ ββββββββββββββ βββββββ
βββ βββββββββ ββββββββββββββ βββββββ
βββββββββββββββββββ ββββββββββββββ βββ
βββββββ βββββββββββ ββββββββββββββ βββ
'''
print(banner)
key = os.urandom(16)
derek = Derek(key, rnd=42)
while True:
print(
'| Option:\n|\t[E]ncrypt\n|\t[D]ecrypt\n|\t[G]et encrypted flag\n|\t[Q]uit')
option = input('> ')
if option.lower() == 'e':
print(derek.encrypt(bytes.fromhex(
(input('msg you want to encrypt (in hex) > ')))).hex())
elif option.lower() == 'd':
print('unimplement')
elif option.lower() == 'g':
print(derek.encrypt(flag).hex())
else:
exit()
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/RCTF/2022/crypto/Derek/app/LFSR.py | ctfs/RCTF/2022/crypto/Derek/app/LFSR.py | class LFSR():
def __init__(self, init, mask=int.from_bytes(b'RCTF2022Hack4fun', 'big'), length=128):
self.init = init
self.mask = mask
self.lengthmask = 2**(length+1)-1
def next(self):
nextdata = (self.init << 1) & self.lengthmask
i = self.init & self.mask & self.lengthmask
output = 0
while i != 0:
output ^= (i & 1)
i = i >> 1
nextdata ^= output
self.init = nextdata
return output
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/RCTF/2022/crypto/Derek/app/Derek.py | ctfs/RCTF/2022/crypto/Derek/app/Derek.py | from LFSR import LFSR
from ctypes import c_uint64
from util import aes, nsplit
from Crypto.Util.Padding import pad
class Derek():
def __init__(self, key, rnd=10):
self.key = key
self.rnd = rnd
self.keys = list()
self.generatekeys(self.key)
def generatekeys(self, key: bytes) -> None:
lfsr = LFSR(int.from_bytes(key, 'big'))
for i in range(self.rnd):
b = 0
for j in range(128):
b = (b << 1) + lfsr.next()
self.keys.append(b.to_bytes(16, 'big'))
def enc_block(self, x: int) -> int:
x_bin = bin(x)[2:].rjust(128, '0')
l, r = int(x_bin[:64], 2), int(x_bin[64:], 2)
for i in range(self.rnd):
magic = c_uint64(0xffffffffffffffff)
for m in bytes([int(bin(byte)[2::].zfill(8)[8::-1], 2)
for byte in l.to_bytes(8, 'big')]):
magic.value ^= c_uint64(m << 56).value
for j in range(8):
if magic.value & 0x8000000000000000 != 0:
magic.value = magic.value << 1 ^ 0x1b
else:
magic.value = magic.value << 1
magic.value ^= 0xffffffffffffffff
t = bytes([int(bin(byte)[2::].zfill(8)[8::-1], 2)
for byte in bytes(magic)])
t = aes(int(t.hex(), 16), self.keys[i]) & 0xffffffffffffffff
t ^= aes(0xdeadbeefbaadf00d if i % 2 else 0xbaadf00ddeadbeef,
self.keys[i]) & 0xffffffffffffffff
l, r = r ^ t, l
l ^= int.from_bytes(self.key[:8], 'big')
r ^= int.from_bytes(self.key[8:], 'big')
l, r = r, l
y = (l + (r << 64)) & 0xffffffffffffffffffffffffffffffff
return y
def dec_block(self, x: int) -> int:
raise Exception('Unimplement')
def encrypt(self, text: bytes) -> bytes:
text_blocks = nsplit(pad(text, 16), 16)
result = b''
for block in text_blocks:
block = int.from_bytes(block, 'big')
result += self.enc_block(block).to_bytes(16, 'big')
return result
def decrypt(self, text: bytes) -> bytes:
raise Exception('Unimplement')
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/RCTF/2022/crypto/guess/chall.py | ctfs/RCTF/2022/crypto/guess/chall.py | from Crypto.Util.number import getPrime, bytes_to_long
from random import randint, choices
from string import ascii_uppercase, digits
import signal
with open('flag.txt', 'rb') as f:
flag = f.read()
signal.alarm(300)
q = getPrime(160)
while True:
key = "rctf_" + "".join(choices(ascii_uppercase + digits, k=15))
x = bytes_to_long("".join(sorted(key)).encode())
if x < q:
break
l = 2
T = []
U = []
for i in range(90):
t = randint(1, q)
u = x * t - randint(1, q >> l)
T.append(t)
U.append(u)
print(f"q = {q}")
print(f"T = {T}")
print(f"U = {U}")
guess = int(input("x = ").strip())
if guess == x:
print(flag) | python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/RCTF/2022/crypto/easyRSA/chall.py | ctfs/RCTF/2022/crypto/easyRSA/chall.py | from Crypto.Util.number import getPrime, inverse, bytes_to_long
with open('flag.txt', 'rb') as f:
flag = f.read()
def v(k):
if k == 0:
return 2
if k == 1:
return r
return (r * v(k - 1) - v(k - 2)) % (N * N)
def encrypt(m, e, N):
c = (1 + m * N) * v(e) % (N * N)
return c
p = getPrime(512)
q = getPrime(512)
N = p * q
d = getPrime(512)
r = getPrime(512)
e = inverse(d, (p * p - 1) * (q * q - 1))
c = encrypt(bytes_to_long(flag), e, N)
print(f"e = {e}")
print(f"c = {c}")
print(f"N = {N}")
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/RCTF/2022/crypto/IS_THIS_LCG/task/util.py | ctfs/RCTF/2022/crypto/IS_THIS_LCG/task/util.py | def mt2dec(X, n, m):
x = 0
for i in range(n):
for j in range(n):
x = x + int(X[i, j]) * (m ** (i * n + j))
return x | python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/RCTF/2022/crypto/IS_THIS_LCG/task/task.py | ctfs/RCTF/2022/crypto/IS_THIS_LCG/task/task.py | """
As we known, LCG is NOT cryptographically secure.
So we designed these variants. Prove us wrong!
"""
from partial_challenge import gen_p1
from curve_challenge import gen_p2
from matrix_challenge import gen_p3
from secret import flag
from Crypto.Util.number import bytes_to_long, getStrongPrime
from os import urandom
p1 = gen_p1()
p2 = gen_p2()
p3 = gen_p3()
q = getStrongPrime(1024)
N = int(p1 * p2 * p3 * q)
flag = bytes_to_long(urandom(N.bit_length() // 8 - len(flag) - 1) + flag)
c = pow(flag, 0x10001, N)
print('N = {}'.format(hex(N)))
print('c = {}'.format(hex(c)))
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/RCTF/2022/crypto/IS_THIS_LCG/task/matrix_challenge.py | ctfs/RCTF/2022/crypto/IS_THIS_LCG/task/matrix_challenge.py | """
As we known,
with some clever arithmetic, we can do fast skipping on LCG.
So we designed this challenge!
"""
from sage.all import *
from util import mt2dec
def gen_p3():
n, m = 8, next_prime(2^16)
A, B, X = [random_matrix(Zmod(m), n, n) for _ in range(3)]
for i in range(1337**1337):
if i < 10:
print('X{} = {}'.format(i, hex(mt2dec(X, n, m))))
X = A*X + B
return next_prime(mt2dec(X, n, m))
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/RCTF/2022/crypto/IS_THIS_LCG/task/partial_challenge.py | ctfs/RCTF/2022/crypto/IS_THIS_LCG/task/partial_challenge.py | """
As we known,
LCG state can be regained with some given output.
But this time we only give partial output each time!
"""
from sage.all import *
from Crypto.Util.number import bytes_to_long, getRandomInteger
def gen_p1():
m = 2 ** 1024
a = bytes_to_long(b'Welcome to RCTF 2022')
b = bytes_to_long(b'IS_THIS_LCG?')
x = getRandomInteger(1024)
for i in range(8):
x = (a * x + b) % m
print('x{} = {}'.format(i, hex(x >> 850)))
x = (a * x + b) % m
return next_prime(x)
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/RCTF/2022/crypto/IS_THIS_LCG/task/secret.py | ctfs/RCTF/2022/crypto/IS_THIS_LCG/task/secret.py | flag = b'RCTF{----REDACTED----}' | python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/RCTF/2022/crypto/IS_THIS_LCG/task/curve_challenge.py | ctfs/RCTF/2022/crypto/IS_THIS_LCG/task/curve_challenge.py | """
As we known,
Linear means vulnerable.
So we put LCG on a curve to make it stronger.
"""
from sage.all import *
from Crypto.Util.number import getStrongPrime, getRandomRange
def gen_p2():
p = getStrongPrime(1024)
A = getRandomRange(p//2, p)
B = getRandomRange(p//2, p)
assert (4*A**3+27*B**2) % p != 0
E = EllipticCurve(GF(p), [A, B])
a = 1
b = E.random_element()
x = E.random_element()
for i in range(7):
x = a*x + b
print('x{} = {}'.format(i, hex(x[0])))
return p
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/RCTF/2022/web/filechecker_mini/app/app.py | ctfs/RCTF/2022/web/filechecker_mini/app/app.py | from flask import Flask, request, render_template, render_template_string
from waitress import serve
import os
import subprocess
app_dir = os.path.split(os.path.realpath(__file__))[0]
app = Flask(__name__)
app.config['UPLOAD_FOLDER'] = f'{app_dir}/upload/'
@app.route('/', methods=['GET','POST'])
def index():
try:
if request.method == 'GET':
return render_template('index.html',result="γ½(=^ο½₯Οο½₯^=)δΈΏ γ½(=^ο½₯Οο½₯^=)δΈΏ γ½(=^ο½₯Οο½₯^=)δΈΏ")
elif request.method == 'POST':
f = request.files['file-upload']
filepath = os.path.join(app.config['UPLOAD_FOLDER'], f.filename)
if os.path.exists(filepath) and ".." in filepath:
return render_template('index.html', result="Don't (^=βα΄₯β=^) (^=βα΄₯β=^) (^=βα΄₯β=^)")
else:
f.save(filepath)
file_check_res = subprocess.check_output(
["/bin/file", "-b", filepath],
shell=False,
encoding='utf-8',
timeout=1
)
os.remove(filepath)
if "empty" in file_check_res or "cannot open" in file_check_res:
file_check_res="wafxixi ΰΈ
β’Οβ’ΰΈ
ΰΈ
β’Οβ’ΰΈ
ΰΈ
β’Οβ’ΰΈ
"
return render_template_string(file_check_res)
except:
return render_template('index.html', result='Error ΰΈ
(ΰΉ*Π΄*ΰΉ)ΰΈ
ΰΈ
(ΰΉ*Π΄*ΰΉ)ΰΈ
ΰΈ
(ΰΉ*Π΄*ΰΉ)ΰΈ
')
if __name__ == '__main__':
serve(app, host="0.0.0.0", port=3000, threads=1000, cleanup_interval=30) | python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/TRX/2025/crypto/factordb.com/chall.py | ctfs/TRX/2025/crypto/factordb.com/chall.py | from Crypto.Util.number import getPrime, bytes_to_long
p,q = getPrime(512), getPrime(512)
N = p*q
e = 65537
flag = b"TRX{??????????????????????}"
print(f"n = {N}")
print(f"e = {e}")
print(f"c = {pow(bytes_to_long(flag), e, N)}")
print(f"leak = {(0x1337 + p + q) ^ (0x1337 * p * q) & (p | 0x1337137)}")
# n = 48512240641840864698611285212880546891958282812678323164929695497979837667167371835079321738954614199887328209689700722900739026689495649897348371742808386272023319885638291436983171905959746612916786515990301081029893115996145232044829058978974408602308231813736063857659634459438506076453437963441215520733
# e = 65537
# c = 36547163254202175014719011914255607837474386170093760562818795855485895858656825454299902190817728613275689042837518944064285193789095094235166256812740012490802514031578972372211469389293445265540278842152695415520550436223647424764618861869589597420855316641231834238167223742740134122313062024294807514651
# leak = 20826963965199127684756501660137785826786703139116744934461978331055754408584988351275721454251225474905754748284336808278049322016982012115699743632649066 | python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/TRX/2025/crypto/Vectorial_RSA/challenge.py | ctfs/TRX/2025/crypto/Vectorial_RSA/challenge.py | from Crypto.Util.number import getPrime, bytes_to_long, long_to_bytes, getRandomInteger
from Crypto.Util.Padding import pad
from Crypto.Cipher import AES
import numpy as np
import secrets
import hashlib
import random
FLAG = b"TRX{fake_flag_for_testing}"
# The great Roman modulus, the foundation of the Pact
p = getPrime(512)
q = getPrime(512)
n = p * q
# The public strengths of Generals Alicius and Bobius
eA = 27 # Alicius' power
eB = 35 # Bobius' power
# Secret keys, determined by fate
kA = getRandomInteger(100)
kB = kA + (-1 if random.randint(0, 1) else 1) * getRandomInteger(16) # A slight, dangerous drift
# Alicius' secret calculations
e1 = [2, 3, 5, 7]
a1 = [69, 420, 1337, 9001]
# Bobius' secret calculations
e2 = [11, 13, 17, 19]
a2 = [72, 95, 237, 1001]
# Each general computes their part of the sacred key
c1 = sum([a * pow(kA, e, n) for a, e in zip(a1, e1)]) # Alicius' part
c2 = sum([a * pow(kB, e, n) for a, e in zip(a2, e2)]) # Bobius' part
# Encryption of each part using the other's public power
cA = pow(c1, eB, n) # Alicius encrypts his secret for Bobius
cB = pow(c2, eA, n) # Bobius encrypts his secret for Alicius
# The shared key, their fragile alliance
key = long_to_bytes(c1 + c2)
key = hashlib.sha256(key).digest()
# The exchange of trust
print(f"n = {n}")
print(f"eA = {eA}")
print(f"eB = {eB}")
# The encrypted secrets, waiting to be revealed
print(f"cA = {cA}")
print(f"cB = {cB}")
# The final encryption of Romeβs fate
iv = secrets.token_bytes(16)
cipher = AES.new(key, AES.MODE_CBC, iv)
ciphertext = cipher.encrypt(pad(FLAG, 16))
print("Here is the encrypted flag")
print(f"iv = {iv.hex()}")
print(f"ciphertext = {ciphertext.hex()}")
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/TRX/2025/crypto/factor.com/server.py | ctfs/TRX/2025/crypto/factor.com/server.py | import random
from Crypto.Util.number import getPrime, bytes_to_long
flag = open('flag.txt', 'rb').read().strip()
def encrypt_flag():
N = 1
while N.bit_length() < 2048:
N *= getPrime(random.randint(1,512))
e = getPrime(random.randint(1024,2048))
c = pow(bytes_to_long(flag), e, N)
return N, e, c
try:
while 1:
N, e, c = encrypt_flag()
print(f'N = {N}')
print(f'e = {e}')
print(f'c = {c}')
new = input('Do you want to see another encryption? (yes/no): ')
if new != 'yes':
break
except Exception:
pass
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/TeamItaly/2023/misc/ZIP_Extractor_3000/src/challenge.py | ctfs/TeamItaly/2023/misc/ZIP_Extractor_3000/src/challenge.py | import os
import zipfile
import subprocess
import hmac, hashlib
key = os.environ["KEY"]
def cleanup(filename):
os.system(f"rm -rf ./files/{filename}.zip")
os.system(f"rm -rf ./files/{filename}")
def verify_zip(filename):
try:
s = open(f"./files/{filename}.zip", "rb").read(4)
if s != b"PK\x03\x04":
raise Exception("Invalid zip file (PK header missing)")
except:
raise Exception("Unable to read zip file")
archive = zipfile.ZipFile(f"./files/{filename}.zip", "r")
try:
FILES = archive.read("FILES").decode()
SIGNATURE = archive.read("SIGNATURE").decode()
except:
raise Exception("Invalid zip file (FILES or SIGNATURE missing)")
my_signature = hmac.new(key.encode(), FILES.encode(), hashlib.sha256).hexdigest()
if my_signature != SIGNATURE:
raise Exception("Invalid signature (FILES and SIGNATURE mismatch)")
def extract_zip(filename):
try:
subprocess.check_call(
f"7z x ./files/{filename}.zip -o./files/{filename}",
shell=True,
stdout=subprocess.DEVNULL,
stderr=subprocess.DEVNULL,
timeout=10,
)
except:
raise Exception("Unable to extract")
try:
fs = open(f"./files/{filename}/FILES", "r").readlines()
except:
raise Exception("Unable to read FILES")
files = {}
for l in fs:
if l == "":
continue
parts = l.split(" ", 1)
files[parts[1].strip()] = parts[0]
d = os.listdir(f"./files/{filename}")
if len(d) > 5:
raise Exception("Too many files")
for file in d:
if file == "FILES" or file == "SIGNATURE":
continue
if file == ".." or file == ".":
raise Exception("Invalid file name " + file)
stat = os.stat(f"./files/{filename}/{file}")
if stat.st_size > 60 * 1024:
raise Exception("File too big " + file)
hash = hashlib.sha256(
open(f"./files/{filename}/{file}", "rb").read()
).hexdigest()
if file not in files or hash != files[file]:
raise Exception("Missing file hash for " + file)
def get_flag(filename):
try:
f = open(f"./files/{filename}/GET_FLAG", "r").read()
except:
raise Exception("Unable to read GET_FLAG")
if f == "I_WANT_THE_FLAG_PLS":
return os.environ["FLAG"]
raise Exception("No flag for you :(")
# !PLEASE DO NOT UPLOAD A ZIP BOMB!
def compute(filename):
try:
verify_zip(filename)
extract_zip(filename)
flag = get_flag(filename)
cleanup(filename)
return flag
except Exception as e:
cleanup(filename)
return str(e)
if __name__ == "__main__":
import shutil, sys
file = sys.argv[1]
filename_without_path = file.split("/")[-1].split(".")[0]
shutil.copyfile(file, f"./files/{filename_without_path}.zip")
print(compute(filename_without_path))
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/TeamItaly/2023/misc/ZIP_Extractor_3000/src/main.py | ctfs/TeamItaly/2023/misc/ZIP_Extractor_3000/src/main.py | #! /usr/bin/env python3
import os
from flask import Flask, request
from challenge import compute
app = Flask(__name__)
if not os.path.exists("./files"):
os.mkdir("./files")
# Fixare path traversal
def allowed_file(filename):
return "." in filename and filename.rsplit(".", 1)[1].lower() == "zip"
@app.route("/", methods=["GET", "POST"])
def upload_zip():
alert = ''
if request.method == "POST":
if "file" not in request.files:
return "No file"
file = request.files["file"]
if file.filename == "":
return "No file"
filename = os.urandom(16).hex()
file.save(os.path.join("./files", filename + ".zip"))
result = compute(filename)
alert = f"""
<div class="alert alert-primary" role="alert">
<b id="result">{result}</b>
</div>
"""
return f"""
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>ZIP Extractor 3000</title>
<link
rel="stylesheet"
href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css"
/>
</head>
<body>
<div
class="modal modal-sheet position-static d-block bg-body-secondary p-4 py-md-5"
tabindex="-1"
role="dialog"
id="modalSheet"
>
<div class="modal-dialog" role="document">
<form method="POST" enctype="multipart/form-data">
<div class="modal-content rounded-4 shadow">
<div class="modal-header border-bottom-0">
<h1 class="modal-title fs-5">Upload your zip</h1>
</div>
<div class="modal-body py-0">
{alert}
<div class="form-group">
<label for="file">Choose a file:</label>
<input
type="file"
class="form-control-file"
id="file"
name="file"
accept=".zip"
/>
</div>
</div>
<div
class="modal-footer flex-column align-items-stretch w-100 gap-2 pb-3 border-top-0"
>
<button type="submit" class="btn btn-lg btn-primary">
Upload
</button>
</div>
</div>
</form>
</div>
</div>
<script src="https://code.jquery.com/jquery-3.5.1.slim.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/@popperjs/core@2.5.3/dist/umd/popper.min.js"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js"></script>
</body>
</html>
"""
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/TeamItaly/2023/misc/Subarray_Sums_101/server.py | ctfs/TeamItaly/2023/misc/Subarray_Sums_101/server.py | import random
import os
import signal
FLAG = os.environ.get("FLAG", "flag{test_flag}")
n = 128
secret = [random.randint(0, 1) for _ in range(n)]
queries_results = {}
for i in range(0, n):
subarray_sum = 0
for j in range(i+1, n+1):
subarray_sum += secret[j-1]
if subarray_sum in queries_results:
queries_results[subarray_sum] += 1
else:
queries_results[subarray_sum] = 1
def signal_handler(signum, frame):
print("Time is up!")
raise TimeoutError
signal.signal(signal.SIGALRM, signal_handler)
def main():
print(f"You have {n//2} queries to guess my secret!")
for _ in range(n//2):
k = int(input('> '))
if k not in queries_results:
print(0)
else:
print(queries_results[k])
guess = input("Give me your guess: ")
if guess == ''.join(str(x) for x in secret):
print(FLAG)
else:
print("Nope")
if __name__ == '__main__':
signal.alarm(20)
try:
main()
except TimeoutError:
exit(1)
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/TeamItaly/2023/crypto/Big_RSA/encrypt.py | ctfs/TeamItaly/2023/crypto/Big_RSA/encrypt.py | from Crypto.Util.number import getPrime, getStrongPrime, bytes_to_long
from sympy import factorial
from random import randint
from secret import flag
p, q = getStrongPrime(1024), getStrongPrime(1024)
def RSAgen(e = None):
d = 0
if not e:
while(d.bit_length() < 2047):
e = getPrime(2047)
d = pow(e, -1, (p-1)*(q-1))
else:
d = pow(e, -1, (p-1)*(q-1))
return (p*q, p, q, e, d)
n = p*q
print(f'{n = }')
key = RSAgen()
k = randint(600, 1200)
f = factorial(k)
leak = (pow(key[3], 2) + (key[3]*key[4] - 1)*f)*getPrime(256) + k
# 2048 bit e is very expensive, i should use standard e for my encryption
key = RSAgen(65537)
e = key[3]
flag = bytes_to_long(flag)
c = pow(flag, e, n)
print(f"{c = }")
print(f"{leak = }")
#OUTPUT
#
#n = 26155610563918771040451217453770153423175480849248932666067623213096628137347700281227651842637531066158966523562535269946270160966349550464316855975843702602386644310622115374093643617687763127399565005930283899166880048303714803385714487858740617133136915034968428269114907303042424391192431406494414712801428682398922655599872605973327217541188045983390427079210204358352343375551675052592229757120847888780576171954181304712725822439789885440973203535622584052397858824995170393109932313608251208103032787250637381098134254687242226624254464180882206386756799922789661143241398308165644172112918996116051241341767
#c = 14882143057207490168145609595794327950964467559973424621597752378687475531116051048471999976592360385753040756962986881197575420871063219354858309758384966841729075968439470757951580317772601028800980369844502945471937420415705013093369495725032356110007789188647453706470456907380267324946203780527015651994928850341098799680560649210763871810476662426271293840410794844793663532229448343601068354829550752842074478598115636890530640204633346276888013284576380941564885085920559055293159358576137659586044231684426664502650956119257574114940925398612801662412390652208379645262117964212231444035372237602987220161154
#leak = 8882329530176003989563469282320326448513961425520889104820115352134009331360402757127024139665879246460280903840841878434886334764358389863635520069842148223207565079555357126011768633841724238023402746185876779525887392481984149029421348288859961294980594601070755980946189936784537926893399566710815892754474482631518313221065280747677073806153015411511245208373763611976120763693741604815436190527484656588721635559583703292529849150438632820886160326184322723507482566078134710656764953471923255683042573911453728381364857973339477093454501755540396376196910045154990604723000628164844678783206034532184996212426411646863562670787117170937484057232253132378686191307517787281075273286073730517840320844224160937065166742670192503005084799125432651202276745876948826479983116284656814139188066381428020724692363565714860614527931752152240198254329317479816158596931824787225489069026346088037877441040453722896865574447079406031506283100005929709985031578939782011738018467829080816081913925121672327305968766974521281843700741425497908524015911173859409613820295440717780859694704848500536323185048069666385294578000406894438137681553061828379901393410655028227052289995544806138411605538810055799529381568985312754486907514057810886832822416112077637141046599291719695931641341477116694041607732362173173111829958139812135983269100274129925726662395368378059697391687349679786945510641238252220381519030943165126475181808810902040710261462429322977874350519175554159491968977598607860470919877896807912649830555310344788510811708640852621939517683512617800947347015328336403343549764926804605586325355602602157724502283094424228440314761426084409569002423419659272529716195776451657960565924304898320195699180560668631806178645741692749524883469846005409211271022431433039546590781549630715275308124729500303196140494010253387465310270348759187686632848767083559239773341844408450815683523679200221818741654323193797457218877776650125241324891467161777274139708214831833313936201971466603547791591622683172049635972772551806007816208466413199652425970868250229578051299718112290796388965170374760048006586491240415960299655674234758022536120132945656010849673271011148857409644260456852793444292102864629782613888832787049959589501287519423225832100567897316528973935415321329220397090613054817402449251249956025659833660199528249628136823951941068620183704359665779941064385612344970878816496323047753331967618070575102035154652470553061929831610193694052912228006377979477318327954292917783836426814224401489211262556447908499035071972531345812915421543036881828636718727357962701875285833936517812391121587399727281240931927431811181444977909594218984279921315492877394195428208756441893687385105650326859023900280137352737660777503064484456016697716191624303099683835521939233782390584505763849676573364198388306561033652480971048175488758111144736636640190185417713883213429725379415164862080052393396741667399031632758281193771891210430178563364662790052209648349668663621672614807647401120518076403133998551484399204398325200361951412241887720441234483010617920388630542945062451586033688057992061925968617174491390233664273716567854279453909892176120950383253842037120054072618389794275273311333932588139102552015371447182882116160259277516530183031644054520783191752410514938160605548110059282703060409667276475969749797140136872904654013231613962248971564712815341527356396922068564215026284215874684201258558000033165916019163319759952566031082383620943938948623145286816988139057606627616639594815749554968862963450819772941547102531289115954195402127419754744687573822011699197232836491588776322734503766502102575418226503487579619923510951731702344792411606628965837547432575532404303417689912716247856960760491417279481456633424179644033150732614552508566990237704498608189201159580503580410535170284429946552129635519661513317741471932078145289068540132823
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/TeamItaly/2023/crypto/Duality/chall.py | ctfs/TeamItaly/2023/crypto/Duality/chall.py | from Crypto.Util.number import *
from Crypto.Cipher import AES
from Crypto.Util.Padding import pad
import hashlib
import secrets
import random
FLAG = open('flag.txt','rb').read()
class LFSR:
def __init__(self, seed):
self.state = list(map(int, list(f"{seed:0128b}")))
self.taps = [0, 16, 32, 64, 96, 127]
def get(self):
next_bit = 0
for tap in self.taps:
next_bit ^= self.state[tap]
self.state = self.state[1:] + [next_bit]
return next_bit
class LCG:
def __init__(self, seed):
self.a = 3
self.b = 7
self.m = 2**64-59
self.state = seed % self.m
def get(self):
self.state = (self.a * self.state + self.b) % self.m
out = 1 if self.state >> 58 else 0
return out
class nonsense:
def __init__(self, seed):
self.lfsr = LFSR(seed)
self.lcg = LCG(seed)
def get(self):
t1 = self.lfsr.get()
t2 = self.lcg.get()
return t1 ^ t2 ^ 1
l = 128
key = secrets.randbelow(2**l-1)
prng = nonsense(key)
for i in range(300):
out = [prng.get() for _ in range(12)]
p = getPrime(256)
leak = []
for x in out:
if x:
a = secrets.randbelow(2**180)
b = secrets.randbelow(a)
leak.append(a*p + b)
else:
leak.append(secrets.randbelow(2**436))
random.shuffle(leak)
print(leak)
print(AES.new(hashlib.sha256(long_to_bytes(key)).digest(), AES.MODE_ECB).encrypt(pad(FLAG, 16)).hex()) | python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/TeamItaly/2023/crypto/Scrambled_Pizzeria/pizzeria.py | ctfs/TeamItaly/2023/crypto/Scrambled_Pizzeria/pizzeria.py | #!/usr/bin/python3
import numpy as np
import numpy.typing as npt
from PIL import Image
import os
def permutation(
img: npt.NDArray[np.uint8], c: npt.NDArray[np.uint64]
) -> npt.NDArray[np.uint8]:
height, width = img.shape
cm = c[np.arange(max(height, width)) % len(c)]
rows = np.argsort(cm[:height])
cols = np.argsort(cm[:width])
return img[rows, :][:, cols]
def substitution(
con: npt.NDArray[np.uint8], c: npt.NDArray[np.uint64]
) -> npt.NDArray[np.uint8]:
ids = np.arange(np.prod(con.shape)) % len(c)
return con ^ (c % 256).astype(np.uint8)[ids].reshape(con.shape)
def main():
c: npt.NDArray[np.uint64] = np.frombuffer(os.urandom(400 * 8), np.uint64)
print(
"Hi, I'm here to take your order! Can you give me an image of the type of pizza you want me to cook?"
)
height = input("What's the height of the image? ")
width = input("What's the width of the image? ")
img_hex = input("Now send me the image and I'll do the rest!\n")
try:
height = int(height)
width = int(width)
assert height <= 400 and width <= 400
img: npt.NDArray[np.uint8] = np.array(
Image.frombytes("L", (width, height), bytes.fromhex(img_hex))
)
except:
print("Uh oh! You're trying to trick me? Out of my pizzeria!")
exit()
con = permutation(img, c)
enc = substitution(con, c)
print("Oh mamma mia! I've scrambled all of your ingredients, look!")
print(enc.tobytes().hex())
flag_img: npt.NDArray[np.uint8] = np.array(Image.open("flag.jpg").convert("L"))
flag_con = permutation(flag_img, c)
flag_enc = substitution(flag_con, c)
print("What a disaster! To make it up to me, here's a gift...")
print(flag_enc.tobytes().hex())
print("My job here is done!")
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/TeamItaly/2023/web/Modern_Sicilian_Network/msn-spaces/app.py | ctfs/TeamItaly/2023/web/Modern_Sicilian_Network/msn-spaces/app.py | import os
import uuid
from datetime import datetime
from time import sleep
from flask import Flask, render_template
from utils.models import *
SECRET_KEY = os.getenv("SECRET_KEY")
DOMAIN = os.getenv("DOMAIN")
CHAT_PORT = os.getenv("CHAT_PORT")
app = Flask(__name__)
app.config["SECRET_KEY"] = SECRET_KEY
app.config["SQLALCHEMY_DATABASE_URI"] = os.getenv("DATABASE_URI")
app.config["SQLALCHEMY_TRACK_MODIFICATIONS"] = False
app.config["SESSION_COOKIE_DOMAIN"] = f".{DOMAIN}"
from utils.db import db
db.init_app(app)
@app.after_request
def csp(r):
r.headers["Content-Security-Policy"] = f"default-src 'self' 'unsafe-inline' chat.{DOMAIN}:{CHAT_PORT}"
r.headers["Access-Control-Allow-Origin"] = "*"
return r
from routes import api
app.register_blueprint(api.bp)
from routes import pages
app.register_blueprint(pages.bp) | 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/Modern_Sicilian_Network/msn-spaces/routes/api.py | ctfs/TeamItaly/2023/web/Modern_Sicilian_Network/msn-spaces/routes/api.py | import uuid
import logging
from datetime import datetime
from flask import Blueprint, Response, redirect, request, session
from functools import wraps
from utils.db import db
from utils.models import *
API_PATH = "/api/v1"
bp = Blueprint("api", __name__)
# auth wrapper
def request_auth(f):
@wraps(f)
def wrapper(*args, **kwargs):
if "id" not in session:
return "", 401
return f(*args, **kwargs)
return wrapper
# get someone's articles
@bp.get(f"{API_PATH}/articles/<uuid>")
def list_user_articles(uuid):
if not User.query.filter_by(id=uuid).first():
return {}, 404
json = []
for article in Article.query.filter_by(author=uuid):
json.append({
"id": article.id,
"title": article.title,
"content": article.content,
"timestamp": article.timestamp
})
return json
# get an article
@bp.get(f"{API_PATH}/articles/<uuid>/<article>")
def get_article(uuid, article):
article = Article.query.filter_by(author=uuid, id=article).first()
if not article:
return "", 404
user = User.query.filter_by(id=uuid).first()
return {
"author": {
"username": user.username,
"propic": f"/static/propic/{user.propic}"
},
"title": article.title,
"content": article.content,
"timestamp": article.timestamp
} | 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/Modern_Sicilian_Network/msn-spaces/routes/pages.py | ctfs/TeamItaly/2023/web/Modern_Sicilian_Network/msn-spaces/routes/pages.py | import re
import uuid
import timeago
import logging
from datetime import datetime
from flask import Blueprint, request, session, redirect, render_template
from utils.models import *
from utils.auth import *
DOMAIN = os.getenv("DOMAIN")
CHAT_PORT = os.getenv("CHAT_PORT")
bp = Blueprint("pages", __name__)
@bp.route("/")
def index():
return render_template("welcome.html")
@bp.route("/login")
@request_auth # let's not waste logic lol
def login():
return redirect("/")
@bp.route("/logout")
def logout():
session.pop("id", None)
session.pop("username", None)
session.pop("propic", None)
return redirect("/")
@bp.route("/articles/")
@request_auth
def showArticleMaker():
return render_template("article-editor.html")
@bp.post("/articles/<userId>/")
@request_auth
def createArticle(userId):
if userId != session["id"]:
return render_template("error.html", message="You can only write an article for yourself."), 403
try:
data = request.form
title = data["title"]
content = data["content"]
if len(title) > 128:
return render_template("error.html", message="Title must be shorter than 128 characters.")
if len(content) > 2048:
return render_template("error.html", message="Article must be shorter than 2048 characters.")
if Article.query.filter_by(author=userId, title=title).first():
return render_template("error.html", message="You already used that title."), 409
# let's filter scripts
content = re.sub(r"(?s)<\s*(script)[\d\D]*?<\s*/\s*\1\s*>", "", content)
articleId = str(uuid.uuid4())
article = Article(articleId, userId, datetime.utcnow(), title, content)
db.session.add(article)
db.session.commit()
return redirect(f"/articles/{userId}/{articleId}")
except AttributeError as e:
return render_template("error.html", message="Invalid request"), 400
except Exception as e:
logging.error(e)
return render_template("error.html", message="Server error"), 500
@bp.route("/articles/<userId>/")
def showUserArticles(userId):
user = User.query.get(userId)
if not user:
return render_template("error.html", message="This user doesn't exist."), 404
articles = Article.query.filter_by(author=user.id)
return render_template("article-list.html", user=user, articles=articles)
@bp.route("/articles/<userId>/<articleId>/")
def showArticle(userId, articleId):
user = User.query.get(userId)
if not user:
return render_template("error.html", message="This user doesn't exist."), 404
article = Article.query.filter_by(author=user.id, id=articleId).first()
if not article:
return render_template("error.html", message="This article doesn't exist."), 404
articleTimestamp = timeago.format(article.timestamp, datetime.utcnow())
return render_template(
"article-view.html",
user=user,
title=article.title,
text=article.content,
timestamp=articleTimestamp,
DOMAIN=DOMAIN,
CHAT_PORT=CHAT_PORT
) | 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/Modern_Sicilian_Network/msn-spaces/routes/__init__.py | ctfs/TeamItaly/2023/web/Modern_Sicilian_Network/msn-spaces/routes/__init__.py | __all__ = ["api", "pages"] | 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/Modern_Sicilian_Network/msn-spaces/utils/db.py | ctfs/TeamItaly/2023/web/Modern_Sicilian_Network/msn-spaces/utils/db.py | from flask_sqlalchemy import SQLAlchemy
db = SQLAlchemy() | python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/TeamItaly/2023/web/Modern_Sicilian_Network/msn-spaces/utils/models.py | ctfs/TeamItaly/2023/web/Modern_Sicilian_Network/msn-spaces/utils/models.py | from .db import db
class User(db.Model):
id = db.Column(db.String(36), primary_key=True)
username = db.Column(db.String(32), unique=True)
password = db.Column(db.String(128))
propic = db.Column(db.String(20))
powTarget = db.Column(db.String(64))
def __repr__(self):
return f"<User {self.username!r}>"
class Article(db.Model):
id = db.Column(db.String(36), primary_key=True)
author = db.Column(db.String(36), db.ForeignKey("user.id"), nullable=False)
timestamp = db.Column(db.DateTime())
title = db.Column(db.String(128))
content = db.Column(db.String(2048))
def __init__(self, id, author, timestamp, title, content):
self.id = id
self.author = author
self.timestamp = timestamp
self.title = title
self.content = content
def __repr__(self):
return f"<Message {self.title!r}>" | 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/Modern_Sicilian_Network/msn-spaces/utils/__init__.py | ctfs/TeamItaly/2023/web/Modern_Sicilian_Network/msn-spaces/utils/__init__.py | __all__ = ["db", "models", "auth"] | 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/Modern_Sicilian_Network/msn-spaces/utils/auth.py | ctfs/TeamItaly/2023/web/Modern_Sicilian_Network/msn-spaces/utils/auth.py | import os
from flask import session, redirect
from functools import wraps
DOMAIN = os.getenv("DOMAIN")
CHAT_PORT = os.getenv("CHAT_PORT")
# auth wrapper
def request_auth(f):
@wraps(f)
def wrapper(*args, **kwargs):
if "id" not in session:
return redirect(f"//chat.{DOMAIN}:{CHAT_PORT}/login?spaces")
return f(*args, **kwargs)
return wrapper | 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/Modern_Sicilian_Network/msn-chat/app.py | ctfs/TeamItaly/2023/web/Modern_Sicilian_Network/msn-chat/app.py | import os
import uuid
from datetime import datetime
from flask import Flask
from utils.models import *
SECRET_KEY = os.getenv("SECRET_KEY")
DOMAIN = os.getenv("DOMAIN")
CHAT_PORT = os.getenv("CHAT_PORT")
SPACES_PORT = os.getenv("SPACES_PORT")
ADMIN_PASSWORD = os.getenv("ADMIN_PASSWORD")
app = Flask(__name__)
app.config["SECRET_KEY"] = SECRET_KEY
app.config["SQLALCHEMY_DATABASE_URI"] = os.getenv("DATABASE_URI")
app.config["SQLALCHEMY_TRACK_MODIFICATIONS"] = False
app.config["SESSION_COOKIE_DOMAIN"] = f".{DOMAIN}"
from utils.db import db
db.init_app(app)
with app.app_context():
db.create_all()
### FOLLOWING CODE CREATES DEFAULT USERS, MESSAGES AND ARTICLES FOR THE CHALLENGE
if not User.query.filter_by(username="Tofu").first():
catId = str(uuid.uuid4())
cat = User(catId, "Tofu", str(uuid.uuid4()), "tofu.png")
db.session.add(cat)
adminId = str(uuid.uuid4())
admin = User(adminId, "Loldemort", ADMIN_PASSWORD, "arancina.jpg")
db.session.add(admin)
db.session.commit()
meow = Message(str(uuid.uuid4()), 0, "Meow!", datetime.utcnow(), admin, cat)
flag = Message(str(uuid.uuid4()), 0, os.getenv("FLAG", "flag{test}"), datetime.utcnow(), cat, admin)
db.session.add(meow)
db.session.add(flag)
db.session.commit()
catArticleId = str(uuid.uuid4())
title = "Meow!"
content = f"Purr meow!!<br /><br /><img src='//chat.{DOMAIN}:{CHAT_PORT}/static/propic/tofu-knows-what-you-are.jpg' width='300' /><br /><b>I know what you are.</b>"
catArticle = Article(catArticleId, catId, datetime.utcnow(), title, content)
db.session.add(catArticle)
adminArticleId = str(uuid.uuid4())
title = "Hi, my new friend!"
content = \
f'''Hi! Nice to see you here! Are you from Sicily? If so, are you from the nice or the evil side of the island?
<br /><br />
If you don't know what it means, it all comes down to the <a href="https://www.streaty.com/blog/arancini-or-arancina/">arancina-vs-arancino</a> civil war.
<br />
Being a matter of the utmost importance and seriousness, you should know that I joined the war on the side of the arancina.
<br /><br />
But setting politics aside, let's talk and become friends!
<br />
I love reading and have nothing to read these days. Do you have any interesting articles to recommend?
<br />
I'm constantly arguing with cat Tofu, so I may not answer quickly... please send a nudge if you message me.'''
adminArticle = Article(adminArticleId, adminId, datetime.utcnow(), title, content)
db.session.add(adminArticle)
title = "Welcome to MSN!"
content = \
f'''Our team is extremely happy to welcome you on this exciting new platform!
<br />
Some articles that may be worth reading:
<ul>
<li><a href="/articles/{catId}/{catArticleId}">Tofu's article</a>, to know more about our values</li>
<li>My personal <a href="/articles/{adminId}/{adminArticleId}">welcome letter</a> to all new members</li>
</ul>
<b>NEW!</b> We created a revolutionary feature to catch busy users' attention, the Nudge!
<br />
Press the <img src="//chat.{DOMAIN}:{CHAT_PORT}/static/style/assets/chat-window/414.png" alt="Nudge" /> button in chat to try it.
<br />
Note that to prevent abuse, your browser will calculate proof of works in background each time you send a nudge. The calculation will take some seconds.'''
welcomeArticle = Article(str(uuid.uuid4()), adminId, datetime.utcnow(), title, content)
db.session.add(welcomeArticle)
db.session.commit()
@app.after_request
def csp(r):
r.headers["Content-Security-Policy"] = f"default-src 'self'; style-src 'self' 'unsafe-inline'; script-src 'self' 'unsafe-eval'; img-src 'self' data:; connect-src 'self' spaces.{DOMAIN}:{SPACES_PORT}"
return r
from utils.socket import socket
socket.init_app(app)
from routes import api
app.register_blueprint(api.bp)
from routes import client
app.register_blueprint(client.bp) | 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/Modern_Sicilian_Network/msn-chat/routes/client.py | ctfs/TeamItaly/2023/web/Modern_Sicilian_Network/msn-chat/routes/client.py | import os
from flask import Blueprint, session, redirect, render_template
from utils.models import *
DOMAIN = os.getenv("DOMAIN")
SPACES_PORT = os.getenv("SPACES_PORT")
bp = Blueprint("client", __name__)
@bp.route("/")
def index():
return redirect("/login")
@bp.route("/logout")
def logout():
session.pop("id", None)
session.pop("username", None)
session.pop("propic", None)
return redirect("/")
@bp.route("/login")
def login():
if "id" in session:
return redirect("/chat")
return render_template("login.html", propics=ALLOWED_PROPICS)
@bp.route("/chat/")
@bp.route("/chat/<uuid>")
def client(uuid=None):
if uuid is None:
uuid = User.query.filter_by(username="Loldemort").first().id
return redirect(f"/chat/{uuid}")
if "id" not in session:
return redirect("/login")
return render_template("chat.html", DOMAIN=DOMAIN, SPACES_PORT=SPACES_PORT) | 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/Modern_Sicilian_Network/msn-chat/routes/api.py | ctfs/TeamItaly/2023/web/Modern_Sicilian_Network/msn-chat/routes/api.py | import os
import uuid
from datetime import datetime
from functools import wraps
from flask import Blueprint, Response, request, session
from argon2.exceptions import VerifyMismatchError
from utils.db import db
from utils.models import *
from hashlib import sha256
import logging
API_PATH = "/api/v1"
SPACES_PORT = os.getenv("SPACES_PORT")
bp = Blueprint("api", __name__)
# auth wrapper
def request_auth(f):
@wraps(f)
def wrapper(*args, **kwargs):
if "id" not in session:
return "", 401
return f(*args, **kwargs)
return wrapper
# get MSN Spaces port
@bp.get(f"{API_PATH}/spacesPort")
def get_spaces_port():
return str(SPACES_PORT)
# get own info
@bp.get(f"{API_PATH}/session")
@request_auth
def get_own_info():
user = User.query.get(session["id"])
return {
"id": user.id,
"username": user.username,
"propic": f"/static/propic/{user.propic}"
}
# login
@bp.post(f"{API_PATH}/session")
def login():
try:
data = request.get_json()
username = data["username"].strip()
password = data["password"].strip()
ph = PasswordHasher(memory_cost=2048)
user = User.query.filter_by(username=username).first()
if user is None:
return "", 401
ph.verify(user.password, password)
session["id"] = user.id
session["username"] = user.username
session["propic"] = user.propic
return "", 201
except AttributeError as e:
return "", 400
except VerifyMismatchError:
return "", 401
except Exception as e:
logging.error(e)
return "", 500
# register
@bp.post(f"{API_PATH}/users")
def register():
try:
data = request.get_json()
username = data["username"].strip()
password = data["password"].strip()
propic = data["propic"].strip()
if not password or not 4 <= len(password) <= 128 or not 4 <= len(username) <= 32 or \
any([c not in ALLOWED_LETTERS for c in username]) or propic not in ALLOWED_PROPICS:
return "", 400
# abort if username is already used
if User.query.filter_by(username=username).first():
return "", 409
user = User(str(uuid.uuid4()), username, password, propic)
db.session.add(user)
db.session.commit()
# create admin's first message
admin = User.query.filter_by(username="Loldemort").first()
welcomeArticleId = Article.query.filter_by(author=admin.id, title="Welcome to MSN!").first().id
message = Message(
str(uuid.uuid4()),
1,
f"{admin.id}/{welcomeArticleId}",
datetime.utcnow(),
user,
admin
)
db.session.add(message)
db.session.commit()
session["id"] = user.id
session["username"] = user.username
session["propic"] = user.propic # doesn't contain /static/propic
res = Response(status=201)
res.headers["Content-Location"] = f"{API_PATH}/session"
return res
except AttributeError as e:
return "", 400
except Exception as e:
logging.error(e)
return "", 500
# get someone's info
@bp.get(f"{API_PATH}/users/<uuid>")
def get_user_info(uuid):
user = User.query.filter_by(id=uuid).first()
if not user:
return "", 404
return {
"id": user.id,
"username": user.username,
"propic": f"/static/propic/{user.propic}"
}
@bp.route(f"{API_PATH}/search/<otherId>")
@request_auth
def search(otherId):
query = request.args.get("query", None)
if not query:
return "", 400
target = User.query.get(otherId)
if not target:
return "", 404
asker = User.query.get(session["id"])
output = []
messages_received = set(asker.messages).intersection(set(target.sent))
messages_sent = set(asker.sent).intersection(set(target.messages))
messages = list(messages_received.union(messages_sent))
for msg in messages:
if msg.type == 0 and query in msg.content:
output.append(msg.id)
return output, 200 if len(output) != 0 else 404 | 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/Modern_Sicilian_Network/msn-chat/routes/__init__.py | ctfs/TeamItaly/2023/web/Modern_Sicilian_Network/msn-chat/routes/__init__.py | __all__ = ["api", "client"] | 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/Modern_Sicilian_Network/msn-chat/utils/socket.py | ctfs/TeamItaly/2023/web/Modern_Sicilian_Network/msn-chat/utils/socket.py | import os
from time import sleep
from hashlib import sha256
from flask import session, request
from flask_socketio import (
emit,
send,
rooms,
SocketIO,
join_room,
ConnectionRefusedError
)
from .models import *
from .chatUtils import *
CHECKER_TOKEN = os.getenv("CHECKER_TOKEN")
socket = SocketIO()
@socket.on("connect")
def socket_connection():
if not 'id' in session:
raise ConnectionRefusedError("Unauthorized!")
emit("connect_response", {"data": "Connected!"})
@socket.on("join")
def join_chat_room(receiver):
if not isinstance(receiver, str):
raise RuntimeError("Wrong type")
sender = session["id"]
room = ':'.join(sorted([sender, receiver]))
join_room(room)
sender = User.query.get(sender)
receiver = User.query.get(receiver)
messages_received = set(sender.messages).intersection(set(receiver.sent))
messages_sent = set(sender.sent).intersection(set(receiver.messages))
messages = list(messages_received.union(messages_sent))
messages = sorted(messages, key=lambda d: d.timestamp)
message_list = [{
"id": message.id,
"type": message.type,
"sender": message.sender_id,
"receiver": message.receiver_id,
"content": message.content,
"timestamp": message.timestamp.timestamp()
} for message in messages]
send({"messages": message_list}, to=room)
emit_pow()
# type 0 = text
# type 1 = article
@socket.on("message")
def chat_message(msgType, content):
if not isinstance(content, str) or not isinstance(msgType, int):
raise RuntimeError("Wrong type")
if len(content) > 512:
return
room = [r for r in rooms() if r != request.sid][0]
if len(room.split(":")) != 2 or msgType not in [0, 1]:
raise RuntimeError("Invalid parameters")
receiver = User.query.get([x for x in room.split(":") if x != session["id"]][0])
sender = User.query.get(session["id"])
# nobody should be able to log in as them but i'll be careful anyway
if sender.username in ["Loldemort", "Tofu"]:
raise RuntimeError("Forbidden accounts")
if msgType == 1:
# articles sanity check
if len(content) != 73 or content.count("/") != 1 or content.index("/") != 36 \
or any([c not in "0123456789abcdef-/" for c in content]):
return
create_message(sender, receiver, msgType, content, room)
@socket.on("nudge")
def chat_nudge(powX):
room = [r for r in rooms() if r != request.sid][0]
sender = User.query.get(session["id"])
# nobody should be able to log in as them but i'll be careful anyway
if sender.username in ["Loldemort", "Tofu"]:
raise RuntimeError("Forbidden accounts")
emit("nudge", {"sender": sender.id}, to=room)
# proof of work check
complexity = 5
target = sender.powTarget
if powX != CHECKER_TOKEN and (not target or not sha256(f'{sender.powTarget}{powX}'.encode()).hexdigest()[:complexity] == '0' * complexity):
return
emit_pow()
# let's bring the admin alive, after 3 seconds
receiver = User.query.get([x for x in room.split(":") if x != session["id"]][0])
if receiver == User.query.filter_by(username="Loldemort").first():
sleep(3)
admin_react_to_message(receiver, sender, room)
def emit_pow():
user = User.query.get(session["id"])
user.powTarget = sha256(os.urandom(24)).hexdigest()
db.session.commit()
emit("pow", {
"target": user.powTarget,
"complexity": 5
}) | 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/Modern_Sicilian_Network/msn-chat/utils/db.py | ctfs/TeamItaly/2023/web/Modern_Sicilian_Network/msn-chat/utils/db.py | from flask_sqlalchemy import SQLAlchemy
db = SQLAlchemy()
# Database optimizations
"""@db.event.listens_for(Engine, "connect")
def set_sqlite_pragma(dbapi_connection, connection_record):
# Uninteresting sqlite optimizations, copied by BeatBuddy
cursor = dbapi_connection.cursor()
cursor.execute("pragma journal_mode = WAL")
cursor.execute("pragma synchronous = normal")
cursor.execute("pragma temp_store = memory")
cursor.execute("pragma mmap_size = 30000000000")
cursor.close()""" | 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/Modern_Sicilian_Network/msn-chat/utils/models.py | ctfs/TeamItaly/2023/web/Modern_Sicilian_Network/msn-chat/utils/models.py | from argon2 import PasswordHasher
from .db import db
ALLOWED_LETTERS = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789!$-.@^_~"
PROPIC_BASE = "/static/propic"
ALLOWED_PROPICS = [
"cannoli.jpg",
"iris.jpg",
"pane-e-panelle.jpg",
"arancina.jpg",
"tofu.png",
"tofu-tongue.jpg",
"tofu-knows-what-you-are.jpg",
"tofu-blanket.jpg"
]
class User(db.Model):
id = db.Column(db.String(36), primary_key=True)
username = db.Column(db.String(32), unique=True)
password = db.Column(db.String(128))
propic = db.Column(db.String(32))
powTarget = db.Column(db.String(64))
def __init__(self, id, username, password, propic="tofu"):
ph = PasswordHasher(memory_cost=2048)
self.id = id
self.username = username
self.password = ph.hash(password)
self.propic = propic
self.powTarget = ""
def __repr__(self):
return f"<User {self.username!r}>"
class Message(db.Model):
id = db.Column(db.String(36), primary_key=True)
type = db.Column(db.SmallInteger)
content = db.Column(db.String(512))
timestamp = db.Column(db.DateTime())
receiver_id = db.Column(db.String(36), db.ForeignKey("user.id"), nullable=False)
receiver = db.relationship("User", backref=db.backref("messages", lazy='dynamic'), primaryjoin="User.id == Message.receiver_id")
sender_id = db.Column(db.String(36), db.ForeignKey("user.id"), nullable=False)
sender = db.relationship("User", backref=db.backref("sent", lazy=True), primaryjoin="User.id == Message.sender_id")
def __init__(self, id, type, content, timestamp, receiver, sender):
self.id = id
self.type = type
self.content = content
self.timestamp = timestamp
self.receiver_id = receiver.id
self.receiver = receiver
self.sender_id = sender.id
self.sender = sender
def __repr__(self):
return f"<Message {self.content!r}>"
class Article(db.Model):
id = db.Column(db.String(36), primary_key=True)
author = db.Column(db.String(36), db.ForeignKey("user.id"), nullable=False)
timestamp = db.Column(db.DateTime())
title = db.Column(db.String(128))
content = db.Column(db.String(2048))
def __init__(self, id, author, timestamp, title, content):
self.id = id
self.author = author
self.timestamp = timestamp
self.title = title
self.content = content
def __repr__(self):
return f"<Message {self.title!r}>" | 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/Modern_Sicilian_Network/msn-chat/utils/chatUtils.py | ctfs/TeamItaly/2023/web/Modern_Sicilian_Network/msn-chat/utils/chatUtils.py | import os
import uuid
import random
import requests
from datetime import datetime
from flask_socketio import send
from .db import *
from .models import *
def create_message(sender, receiver, msgType, content, room):
message = Message(
str(uuid.uuid4()),
msgType,
content,
datetime.utcnow(),
receiver,
sender
)
db.session.add(message)
db.session.commit()
send({"messages": [{
"id": message.id,
"type": message.type,
"sender": message.sender_id,
"receiver": message.receiver_id,
"content": message.content,
"timestamp": message.timestamp.timestamp()
}]}, to=room)
### ADMIN BOT LOGIC - don't waste your time here
DOMAIN = os.getenv("DOMAIN")
HEADLESS_HOST = os.getenv("HEADLESS_HOST")
HEADLESS_PORT = os.getenv("HEADLESS_PORT")
HEADLESS_AUTH = os.getenv("HEADLESS_AUTH")
CHAT_PORT = os.getenv("CHAT_PORT")
SPACES_PORT = os.getenv("SPACES_PORT")
ADMIN_PASSWORD = os.getenv("ADMIN_PASSWORD")
AUTOMATED_REPLIES = {
"nothing": [
"what's up?",
"yeah?",
"tell me"
],
"text": [
"sorry can't answer now, tofu ate my homework",
"don't you think Tofu is a beautiful cat?",
"i love Tofu!! he tries to lick my hair sometimes but he's the cutest",
"have you tried rebooting your computer??",
"eating an arancina would solve your problems, or maybe most of them",
"i ain't reading all that, happy for you tho, or sorry that happened"
],
"article": [
"i love reading blogs! i'll read that soon",
"seems interesting! gonna read it asap",
"oh my, is it a new Team Italy CTF writeup?! i'm opening that link rn!!!"
]
}
def admin_react_to_message(admin, user, room):
messages = sorted(list(set(user.sent).intersection(set(admin.messages))), key=lambda d: d.timestamp)
if len(messages) == 0:
create_message(admin, user, 0, random.choice(AUTOMATED_REPLIES["nothing"]), room)
return
last_user_message = messages[-1]
if last_user_message.type != 1: # text
create_message(admin, user, 0, random.choice(AUTOMATED_REPLIES["text"]), room)
else: # article
CHAT_PORT_SUFFIX = "" if int(CHAT_PORT) == 80 else f":{CHAT_PORT}"
SPACES_PORT_SUFFIX = "" if int(SPACES_PORT) == 80 else f":{SPACES_PORT}"
requests.post(
f"http://{HEADLESS_HOST}:{HEADLESS_PORT}",
json = {
"actions": [
{
"type": "request",
"method": "POST",
"url": f"http://chat.{DOMAIN}{CHAT_PORT_SUFFIX}/api/v1/session",
"data": '{"username":"Loldemort","password":"%s"}' % ADMIN_PASSWORD,
"headers": { "Content-Type": "application/json" },
"timeout": 5
},
{
"type": "request",
"method": "GET",
"url": f"http://spaces.{DOMAIN}{SPACES_PORT_SUFFIX}/articles/{last_user_message.content}",
"timeout": 15
}
]
},
headers = {
"X-Auth": HEADLESS_AUTH
},
timeout = 5
)
create_message(admin, user, 0, random.choice(AUTOMATED_REPLIES["article"]), room) | 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/Modern_Sicilian_Network/msn-chat/utils/__init__.py | ctfs/TeamItaly/2023/web/Modern_Sicilian_Network/msn-chat/utils/__init__.py | __all__ = ["db", "models", "socket", "chatUtils"] | 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/app.py | ctfs/TeamItaly/2023/web/Borraccia/challenge/app.py | from Borraccia import App, render_template, set_status_code
app = App(__name__)
def index(ctx):
return render_template("index.html")
def documentation_test(ctx):
return render_template("documentation_test.html")
def login(ctx):
return render_template("login.html")
def register(ctx):
return render_template("register.html")
def login_handle(ctx):
data = ctx.request.post_data
username = data.get("username")
password = data.get("password")
if username == "admin" and password == "admin":
return render_template("login.html", status="Hi admin! Sorry, no flag for you!")
set_status_code(ctx, 401)
return render_template("login.html", status="Login failed")
def register_handle(ctx):
data = ctx.request.post_data
username = data.get("username")
password = data.get("password")
assert username and password
return "Registered!"
app.get("/", index)
app.get("/index", index)
app.get("/login", login)
app.get("/register", register)
app.get("/documentation_test", documentation_test)
app.post("/login", login_handle)
app.post("/register", register_handle)
if __name__ == "__main__":
app.run("0.0.0.0", 1337)
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.