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/Crypto/2022/soda/soda_server.py | ctfs/Crypto/2022/soda/soda_server.py | #!/usr/bin/env python3
from Crypto.Util.number import *
import sys
from secret import p, q, flag
def soda(g, p, q, m):
n, phi = p * q, (p - 1) * (q - 1)
if isPrime(m) and m.bit_length() <= 128:
e = m
else:
e = 2 * (pow(g, m**2, n) % 2**152) ^ 1
if GCD(e, phi) == 1:
d = inverse(e, phi)
return pow(g, d, n)
def die(*args):
pr(*args)
quit()
def pr(*args):
s = " ".join(map(str, args))
sys.stdout.write(s + "\n")
sys.stdout.flush()
def sc():
return sys.stdin.readline().strip()
def main():
border = "|"
pr(border*72)
pr(border, "Hi all cryptographers! Welcome to SODA crypto oracle, we do SODAing!", border)
pr(border, "You mission is find a way to SODA a given message, I think its easy.", border)
border = "|"
n = p * q
phi = (p - 1) * (q - 1)
g = 31337
CRY = "Long Live Crypto :))"
m = bytes_to_long(CRY.encode('utf-8'))
while True:
pr("| Options: \n|\t[G]et the parameters \n|\t[T]ry the soda \n|\t[V]erify the signature \n|\t[Q]uit")
ans = sc().lower()
if ans == 'g':
pr(border, f'n = {n}')
pr(border, f'g = {g}')
elif ans == 't':
pr(border, "please send your integer to get soda: ")
s = sc()
try:
s = int(s)
except:
die(border, "Something went wrong! Your input is not valid!! Bye!!!")
h = soda(g, p, q, s)
if h != None:
if s == m:
die(border, 'Are you kidding me? We will never SODA it!! Bye!!!')
else:
pr(border, f"soda(g, p, q, m) = {soda(g, p, q, s)}")
else:
pr(border, 'Something went wrong! See source code!!')
elif ans == "v":
pr(border, "please send the soda to verify: ")
sd = sc()
try:
sd = int(sd)
except:
die(border, "Your input is not valid! Bye!!")
_e = 2 * (pow(g, m**2, n) % 2**152) ^ 1
if pow(sd, _e, n) == g:
die(border, "Congrats! your got the flag: " + flag)
else:
pr(border, "[ERR]: Your answer is NOT correct!!!")
elif ans == 'q':
die(border, "Quitting ...")
else:
die(border, "Bye bye ...")
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/Crypto/2022/versace/versace.py | ctfs/Crypto/2022/versace/versace.py | #!/usr/bin/env python3
# In the name of Allah
from Crypto.Util.number import *
from flag import flag
def keygen(n):
e = 65537
x, y = [getRandomRange(2, n - 2) for _ in '01']
fi = pow(5, x, n)
th = pow(13, y, n)
return (n, e, fi, th)
def encrypt(m, pubkey):
n, e, fi, th = pubkey
k, u, v = [getRandomRange(2, n - 2) for _ in '012']
c_1 = pow(k, e, n)
c_2 = pow(5, u, n)
c_3 = pow(13, v, n)
c_4 = pow(fi, u, n) * pow(th, v, n) * pow(k + 1, e, n) * m % n
return c_1, c_2, c_3, c_4
n = 141886649864474336567180245736091175577519141092893110664440298696325928109107819365023509727482657156444454196974621121317731892910779276975799862237645015028934626195549529415068518701179353407407170273107294065819774663163018151369555922179926003735413019069305586784817562889650637936781439564028325920769
pubkey = keygen(n)
msg = bytes_to_long(flag.encode('utf-8'))
enc = encrypt(msg, pubkey)
print(f'pubkey = {pubkey}')
print(f'enc = {enc}') | python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/Crypto/2022/polyRSA/polyRSA.py | ctfs/Crypto/2022/polyRSA/polyRSA.py | #!/usr/bin/env python3
from Crypto.Util.number import *
from flag import flag
def keygen(nbit = 64):
while True:
k = getRandomNBitInteger(nbit)
p = k**6 + 7*k**4 - 40*k**3 + 12*k**2 - 114*k + 31377
q = k**5 - 8*k**4 + 19*k**3 - 313*k**2 - 14*k + 14011
if isPrime(p) and isPrime(q):
return p, q
def encrypt(msg, n, e = 31337):
m = bytes_to_long(msg)
return pow(m, e, n)
p, q = keygen()
n = p * q
enc = encrypt(flag, n)
print(f'n = {n}')
print(f'enc = {enc}') | python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/LINE/2021/pwn/atelier/client.py | ctfs/LINE/2021/pwn/atelier/client.py | #!/usr/bin/env python3
import sys
import json
import asyncio
import importlib
# from sqlalchemy import *
class AtelierException:
def __init__(self, e):
self.message = repr(e)
class MaterialRequest:
pass
class MaterialRequestReply:
pass
class RecipeCreateRequest:
def __init__(self, materials):
self.materials = materials
class RecipeCreateReply:
pass
def object_to_dict(c):
res = {}
res["__class__"] = str(c.__class__.__name__)
res["__module__"] = str(c.__module__)
res.update(c.__dict__)
return res
def dict_to_object(d):
if "__class__" in d:
class_name = d.pop("__class__")
module_name = d.pop("__module__")
module = importlib.import_module(module_name)
class_ = getattr(module, class_name)
inst = class_.__new__(class_)
inst.__dict__.update(d)
else:
inst = d
return inst
async def rpc_client(message):
message = json.dumps(message, default=object_to_dict)
reader, writer = await asyncio.open_connection(sys.argv[1], int(sys.argv[2]))
writer.write(message.encode())
data = await reader.read(2000)
writer.close()
res = json.loads(data, object_hook=dict_to_object)
if isinstance(res, AtelierException):
print("Exception: " + res.message)
exit(1)
return res
print("""
,✿ ✿ ✿
/ | -|- ,-✿ | ✿ ,-✿ ,-✿
✿'`✿' /--| | |-' | | |-' | ✿'`✿'
,' `-' `' `-' `' ' `-' '
Author: twitter.com/vsnrain
Hi and welcome to my Atelier!
I am making a handy database to store my alchemy recipes.
I have not finished adding all of the recipes yet, but you can try crafting some of them if you want.
""")
loop = asyncio.get_event_loop()
req = MaterialRequest()
res = loop.run_until_complete(rpc_client(req))
print("\nMaterial 1:")
for i, m in enumerate(res.material1):
print(f"{i}: {m}")
input1 = int(input("Choose material 1: "))
material1 = res.material1[input1]
print("\nMaterial 2:")
for i, m in enumerate(res.material2):
print(f"{i}: {m}")
input2 = int(input("Choose material 2: "))
material2 = res.material2[input2]
req = RecipeCreateRequest(f"{material1},{material2}")
res = loop.run_until_complete(rpc_client(req))
print("\nResult :\n" + res.result)
loop.close()
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/LINE/2021/crypto/babycrypto1/babycrypto1.py | ctfs/LINE/2021/crypto/babycrypto1/babycrypto1.py | #!/usr/bin/env python
from base64 import b64decode
from base64 import b64encode
import socket
import multiprocessing
from Crypto.Cipher import AES
from Crypto.Random import get_random_bytes
from Crypto.Util.Padding import pad, unpad
import hashlib
import sys
class AESCipher:
def __init__(self, key):
self.key = key
def encrypt(self, data):
iv = get_random_bytes(AES.block_size)
self.cipher = AES.new(self.key, AES.MODE_CBC, iv)
return b64encode(iv + self.cipher.encrypt(pad(data,
AES.block_size)))
def encrypt_iv(self, data, iv):
self.cipher = AES.new(self.key, AES.MODE_CBC, iv)
return b64encode(iv + self.cipher.encrypt(pad(data,
AES.block_size)))
def decrypt(self, data):
raw = b64decode(data)
self.cipher = AES.new(self.key, AES.MODE_CBC, raw[:AES.block_size])
return unpad(self.cipher.decrypt(raw[AES.block_size:]), AES.block_size)
flag = open("flag", "rb").read().strip()
COMMAND = [b'test',b'show']
def run_server(client, aes_key, token):
client.send(b'test Command: ' + AESCipher(aes_key).encrypt(token+COMMAND[0]) + b'\n')
client.send(b'**Cipher oracle**\n')
client.send(b'IV...: ')
iv = b64decode(client.recv(1024).decode().strip())
client.send(b'Message...: ')
msg = b64decode(client.recv(1024).decode().strip())
client.send(b'Ciphertext:' + AESCipher(aes_key).encrypt_iv(msg,iv) + b'\n\n')
while(True):
client.send(b'Enter your command: ')
tt = client.recv(1024).strip()
tt2 = AESCipher(aes_key).decrypt(tt)
client.send(tt2 + b'\n')
if tt2 == token+COMMAND[1]:
client.send(b'The flag is: ' + flag)
client.close()
break
if __name__ == '__main__':
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
server.bind(('0.0.0.0', 16001))
server.listen(1)
while True:
client, address = server.accept()
aes_key = get_random_bytes(AES.block_size)
token = b64encode(get_random_bytes(AES.block_size*10))[:AES.block_size*10]
process = multiprocessing.Process(target=run_server, args=(client, aes_key, token))
process.daemon = True
process.start() | python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/LINE/2021/crypto/babycrypto2/babycrypto2.py | ctfs/LINE/2021/crypto/babycrypto2/babycrypto2.py | #!/usr/bin/env python
from base64 import b64decode
from base64 import b64encode
import socket
import multiprocessing
from Crypto.Cipher import AES
from Crypto.Random import get_random_bytes
from Crypto.Util.Padding import pad, unpad
import hashlib
import sys
class AESCipher:
def __init__(self, key):
self.key = key
def encrypt(self, data):
iv = get_random_bytes(AES.block_size)
self.cipher = AES.new(self.key, AES.MODE_CBC, iv)
return b64encode(iv + self.cipher.encrypt(pad(data,
AES.block_size)))
def encrypt_iv(self, data, iv):
self.cipher = AES.new(self.key, AES.MODE_CBC, iv)
return b64encode(iv + self.cipher.encrypt(pad(data,
AES.block_size)))
def decrypt(self, data):
raw = b64decode(data)
self.cipher = AES.new(self.key, AES.MODE_CBC, raw[:AES.block_size])
return unpad(self.cipher.decrypt(raw[AES.block_size:]), AES.block_size)
flag = open("flag", "rb").read().strip()
AES_KEY = get_random_bytes(AES.block_size)
TOKEN = b64encode(get_random_bytes(AES.block_size*10-1))
COMMAND = [b'test',b'show']
PREFIX = b'Command: '
def run_server(client):
client.send(b'test Command: ' + AESCipher(AES_KEY).encrypt(PREFIX+COMMAND[0]+TOKEN) + b'\n')
while(True):
client.send(b'Enter your command: ')
tt = client.recv(1024).strip()
tt2 = AESCipher(AES_KEY).decrypt(tt)
client.send(tt2 + b'\n')
if tt2 == PREFIX+COMMAND[1]+TOKEN:
client.send(b'The flag is: ' + flag)
client.close()
break
if __name__ == '__main__':
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
server.bind(('0.0.0.0', 16002))
server.listen(1)
while True:
client, address = server.accept()
process = multiprocessing.Process(target=run_server, args=(client, ))
process.daemon = True
process.start() | python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/LINE/2021/web/YourNote/web/src/models.py | ctfs/LINE/2021/web/YourNote/web/src/models.py | from flask_login import UserMixin
from werkzeug.security import generate_password_hash, check_password_hash
from sqlalchemy import Column, Integer, String, ForeignKey
from sqlalchemy_utils import UUIDType
from sqlalchemy.orm import relationship, backref
from flask_marshmallow import Marshmallow
import uuid
from database import db
class User(UserMixin, db.Model):
__tablename__ = 'user'
id = Column(Integer, primary_key=True)
username = Column(String(50), unique=True)
password_hash = Column(String(120))
@property
def password(self):
raise AttributeError('password is not a readable attribute')
@password.setter
def password(self, password):
self.password_hash = generate_password_hash(password)
def verify_password(self, password):
return check_password_hash(self.password_hash, password)
def __repr__(self):
return '<User %r>' % self.username
class Note(db.Model):
__tablename__ = 'note'
id = Column(UUIDType(binary=False), primary_key=True, default=uuid.uuid4)
title = Column(String(50))
content = Column(String(100))
owner_id = Column(Integer, ForeignKey('user.id'))
owner = relationship(
User,
backref=backref(
'user',
uselist=True,
cascade='delete,all'
)
)
ma = Marshmallow()
class NoteSchema(ma.SQLAlchemyAutoSchema):
class Meta:
model = Note | python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/LINE/2021/web/YourNote/web/src/database.py | ctfs/LINE/2021/web/YourNote/web/src/database.py | from flask_sqlalchemy import SQLAlchemy
from retrying import retry
db = SQLAlchemy()
@retry(wait_fixed=2000, stop_max_attempt_number=10)
def init_db(app):
db.init_app(app)
with app.app_context():
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/LINE/2021/web/YourNote/web/src/config.py | ctfs/LINE/2021/web/YourNote/web/src/config.py | import os
class BaseConfig(object):
DEBUG = False
TESTING = False
SQLALCHEMY_TRACK_MODIFICATIONS = False
SESSION_TYPE = 'filesystem'
class DevConfig(BaseConfig):
DEBUG = True
TESTING = True
SQLALCHEMY_DATABASE_URI = 'sqlite:///dev.sqlite3'
SECRET_KEY = 'dev_secret'
ADMIN_PASSWORD = 'password'
FLAG = 'LINECTF{example}'
APP_HOST = 'localhost:5000'
BASE_URL = f"http://{APP_HOST}"
CRAWLER_URL = 'http://localhost:3000'
POW_COMPLEXITY = 1
class ProdConfig(BaseConfig):
SQLALCHEMY_DATABASE_URI = f"mysql://{os.getenv('MYSQL_USER')}:{os.getenv('MYSQL_PASSWORD')}@yournote-db/{os.getenv('MYSQL_DATABASE')}"
SECRET_KEY = os.getenv('SECRET_KEY')
ADMIN_PASSWORD = os.getenv('ADMIN_PASSWORD')
FLAG = os.getenv('FLAG')
APP_HOST = os.getenv('APP_HOST')
BASE_URL = f"http://{APP_HOST}"
CRAWLER_URL = os.getenv('CRAWLER_URL')
POW_COMPLEXITY = os.getenv('POW_COMPLEXITY')
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/LINE/2021/web/YourNote/web/src/app.py | ctfs/LINE/2021/web/YourNote/web/src/app.py | from flask import Flask, flash, redirect, url_for, render_template, request, jsonify, send_file, Response, session
from flask_login import LoginManager, login_required, login_user, logout_user, current_user
from flask_wtf.csrf import CSRFProtect
from flask_sqlalchemy import SQLAlchemy
from flask_session import Session
from sqlalchemy.orm.exc import NoResultFound
from sqlalchemy.exc import IntegrityError, DataError
from sqlalchemy import or_
import json
import os
import secrets
import requests
from database import init_db, db
from models import User, Note, NoteSchema
app = Flask(__name__)
if os.getenv('APP_ENV') == 'PROD':
app.config.from_object('config.ProdConfig')
else:
app.config.from_object('config.DevConfig')
init_db(app)
login_manager = LoginManager()
login_manager.init_app(app)
csrf = CSRFProtect(app)
Session(app)
@login_manager.user_loader
def load_user(user_id):
return User.query.get(int(user_id))
@login_manager.unauthorized_handler
def unauthorized():
return redirect(url_for('login', redirect=request.full_path))
@app.before_first_request
def insert_initial_data():
try:
admin = User(
username='admin',
password=app.config.get('ADMIN_PASSWORD')
)
db.session.add(admin)
db.session.commit()
except IntegrityError:
db.session.rollback()
return
admin_note = Note(
title='Hello world',
content=('Lorem ipsum dolor sit amet, consectetur '
'adipiscing elit, sed do eiusmod tempor incididunt...'),
owner=admin
)
db.session.add(admin_note)
admin_note = Note(
title='flag',
content=app.config.get('FLAG'),
owner=admin
)
db.session.add(admin_note)
db.session.commit()
@app.route('/')
@login_required
def index():
notes = Note.query.filter_by(owner=current_user).all()
return render_template('index.html', notes=notes)
@app.route('/search')
@login_required
def search():
q = request.args.get('q')
download = request.args.get('download') is not None
if q:
notes = Note.query.filter_by(owner=current_user).filter(or_(Note.title.like(f'%{q}%'), Note.content.like(f'%{q}%'))).all()
if notes and download:
return Response(json.dumps(NoteSchema(many=True).dump(notes)), headers={'Content-disposition': 'attachment;filename=result.json'})
else:
return redirect(url_for('index'))
return render_template('index.html', notes=notes, is_search=True)
@app.route('/register', methods=['GET', 'POST'])
def register():
if request.method == 'POST':
username = request.form.get('username')
password = request.form.get('password')
if username and password:
user = User.query.filter_by(username=username).first()
if user:
flash('Username already exists.')
return redirect(url_for('register'))
user = User(
username=username,
password=password
)
db.session.add(user)
db.session.commit()
return redirect(url_for('login'))
flash('Registeration failed')
return redirect(url_for('register'))
elif request.method == 'GET':
return render_template('register.html')
@app.route('/login', methods=['GET', 'POST'])
def login():
url = request.args.get('redirect')
if url:
url = app.config.get('BASE_URL') + url
if current_user.is_authenticated:
return redirect(url)
if request.method == 'POST':
username = request.form.get('username')
password = request.form.get('password')
if username and password:
user = User.query.filter_by(username=username).first()
if user and user.verify_password(password):
login_user(user)
if url:
return redirect(url)
return redirect(url_for('index'))
flash('Login failed')
return redirect(url_for('login'))
elif request.method == 'GET':
return render_template('login.html')
@app.route('/logout')
@login_required
def logout():
logout_user()
return redirect(url_for('index'))
@app.route('/note', methods=['GET', 'POST'])
@login_required
def create_note():
if request.method == 'POST':
title = request.form.get('title')
content = request.form.get('content')
try:
if title and content:
note = Note(
title=title,
content=content,
owner=current_user
)
db.session.add(note)
db.session.commit()
return redirect(url_for('note', note_id=note.id))
except DataError:
flash('Note creation failed')
return redirect(url_for('create_note'))
elif request.method == 'GET':
return render_template('create_note.html')
@app.route('/note/<note_id>')
@login_required
def note(note_id):
try:
note = Note.query.filter_by(owner=current_user, id=note_id).one()
except NoResultFound:
flash('Note not found')
return render_template('note.html')
return render_template('note.html', note=note)
@app.route('/report', methods=['GET', 'POST'])
@login_required
def report():
if request.method == 'POST':
url = request.form.get('url')
proof = request.form.get('proof')
if url and proof:
res = requests.get(
app.config.get('CRAWLER_URL'),
params={
'url': url,
'proof': proof,
'prefix': session.pop('pow_prefix')
}
)
prefix = secrets.token_hex(16)
session['pow_prefix'] = prefix
return render_template('report.html', pow_prefix=prefix, pow_complexity=app.config.get('POW_COMPLEXITY'), msg=res.json()['msg'])
else:
return redirect('report')
elif request.method == 'GET':
prefix = secrets.token_hex(16)
session['pow_prefix'] = prefix
return render_template('report.html', pow_prefix=prefix, pow_complexity=app.config.get('POW_COMPLEXITY'))
if __name__ == '__main__':
app.run('0.0.0.0') | python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/LINE/2021/web/diveinternal/private/app/datamodel.py | ctfs/LINE/2021/web/diveinternal/private/app/datamodel.py | import os
from datetime import date, datetime, timedelta
from sqlalchemy import create_engine, ForeignKeyConstraint
from sqlalchemy.orm import sessionmaker
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy import Column, String, Integer, Date, Table, Boolean, ForeignKey, DateTime, BLOB, Text, JSON, Float
from sqlalchemy.orm import relationship, backref
Base = declarative_base()
class Database:
SQLITE = 'sqlite'
DB_ENGINE = {
SQLITE: 'sqlite:///{DB}'
}
# Main DB Connection Ref Obj
dbEngine = None
sdbType = SQLITE
if sdbType in DB_ENGINE.keys():
engineUrl = DB_ENGINE[sdbType].format(DB=os.environ['DBFILE'])
dbEngine = create_engine(engineUrl,connect_args={'check_same_thread': False})
session = sessionmaker(bind=dbEngine,expire_on_commit=False)
else:
print("DBType is not found in DB_ENGINE")
class Subscriber(Base):
__tablename__ = 'Subscriber'
id = Column(Integer, primary_key=True)
email = Column(String)
date = Column(String)
def __init__(self, email, date):
self.email = email
self.date = date
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/LINE/2021/web/diveinternal/private/app/coinapi.py | ctfs/LINE/2021/web/diveinternal/private/app/coinapi.py | import json,os,sys, random
import requests, urllib.parse,subprocess,time
from requests.auth import HTTPBasicAuth
from requests_toolbelt.utils import dump
from datetime import datetime, timedelta
import logging
logger = logging.getLogger('KillCoinapi')
headers = {'content-encoding': 'gzip','content-type':'application/json'}
"""
Coin Dataset.
coinData = [
{"symbol" : "BTCUSDT", "price" : btcusdt},
{"symbol" : "XRPUSDT", "price" : xrpusdt},
{"symbol" : "ADAUSDT", "price" : adausdt},
{"symbol" : "LINKUSDT", "price" : linkusdt}
]
"""
def getCoinInfo():
try:
url = '' #-----> Find your favorite api provider.
resp = requests.get(url,headers=headers)
if resp.status_code >= 200:
if resp.status_code < 300:
try:
json_data = json.loads(resp.text)
return(json_data)
except:
logger.debug('Request of KillCoinapi')
else:
logger.error(resp.text)
except Exception as e:
logger.error('coinapi Error : {c}, Message, {m}, Error on line {l}'.format(c = type(e).__name__, m = str(e), l = sys.exc_info()[-1].tb_lineno))
pass
getCoinInfo() | python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/LINE/2021/web/diveinternal/private/app/main.py | ctfs/LINE/2021/web/diveinternal/private/app/main.py | import schedule, signal, queue, threading, time,sys, os, datetime, multiprocessing, requests, telegram, jsonify, threading, requests, re, hashlib, hmac, random, base64
from threading import Thread
import flask
from flask import Flask, request, render_template, json
from flask_bootstrap import Bootstrap
from flask_cors import CORS
import logging
import logging.config
from dotenv import load_dotenv
from datamodel import Database, Base, Subscriber
from coinapi import getCoinInfo
from rollback import RunRollbackDB, RunbackupDB
load_dotenv()
logging.config.fileConfig('./logging.conf', defaults={'logfilename1': './logs/KillCoinapi.log'})
logger = logging.getLogger('KillCoinapi')
privateKey = b'let\'sbitcorinparty'
status = {
'success' : {'message':'success'},
'false' : {'message':'false'},
'error' : {'message': 'error'},
'key' : {'message': 'Key error'},
'sign' : {'message': 'Not Allowed'},
'email' : {'message': 'Email invalid'},
'admin' : {'message': 'Do you wanna admin cherry? You need to cool down bro! Your head is too heavy. Go outside. Your weight is '}
}
class Activity():
def __init__(self):
self.engine = Database.dbEngine
Base.metadata.create_all(self.engine, Base.metadata.tables.values(), checkfirst=True)
self.session = Database.session()
self.dbHash = hashlib.md5(open(os.environ['DBFILE'],'rb').read()).hexdigest()
self.integrityKey = hashlib.sha512((self.dbHash).encode('ascii')).hexdigest()
self.subscriberObjs = self.session.query(Subscriber).all()
self.backupedHash = ''
def DbBackupRunner(self):
self.dbHash = hashlib.md5(open(os.environ['DBFILE'],'rb').read()).hexdigest()
self.backupedHash = RunbackupDB(self.backupedHash, self.dbHash)
def Commit(self):
try:
self.session.commit()
except Exception as e :
err = 'Error On {f} : {c}, Message, {m}, Error on line {l}'.format(f = sys._getframe().f_code.co_name ,c = type(e).__name__, m = str(e), l = sys.exc_info()[-1].tb_lineno)
RunRollbackDB(self.dbHash)
self.UpdateKey()
self.Commit()
def UpdateKey(self):
file = open(os.environ['DBFILE'],'rb').read()
self.dbHash = hashlib.md5(file).hexdigest()
self.integrityKey = hashlib.sha512((self.dbHash).encode('ascii')).hexdigest()
def IntegrityCheckWorker(self):
key = self.integrityKey
dbHash = hashlib.md5(open(os.environ['DBFILE'],'rb').read()).hexdigest()
self.IntegrityCheck(key, dbHash)
def IntegrityCheck(self,key, dbHash):
if self.integrityKey == key:
pass
else:
return json.dumps(status['key'])
if self.dbHash != dbHash:
flag = RunRollbackDB(dbHash)
logger.debug('DB File changed!!'+dbHash)
file = open(os.environ['DBFILE'],'rb').read()
self.dbHash = hashlib.md5(file).hexdigest()
self.integrityKey = hashlib.sha512((self.dbHash).encode('ascii')).hexdigest()
return flag
return "DB is safe!"
def AddSubscriber(self, email):
sub_time = time.strftime("%Y-%m-%d %H:%M:%S")
subscriberObj = Subscriber(email, sub_time)
self.session.add(subscriberObj)
self.Commit()
return json.dumps(status['success'])
def ScheduleWorker(self):
while True:
schedule.run_pending()
time.sleep(1)
def run(self):
threading.Thread(target=self.ScheduleWorker).start()
schedule.every(int(os.environ['CHKTIME'])).seconds.do(self.IntegrityCheckWorker)
# schedule.every(5).minutes.do(self.DbBackupRunner)
schedule.every(2).seconds.do(self.UpdateKey)
schedule.every(2).seconds.do(self.DbBackupRunner)
app = Flask(__name__)
Bootstrap(app)
cors = CORS(app, resources={r"/*": {"origins": "*"}})
activity = Activity()
activity.run()
def valid_download(src):
if( src != None ):
return True
else:
return False
def WriteFile(url):
local_filename = url.split('/')[-1]
with requests.get(url, stream=True) as r:
r.raise_for_status()
with open('backup/'+local_filename, 'wb') as f:
for chunk in r.iter_content(chunk_size=8192):
f.write(chunk)
def LanguageNomarize(request):
if request.headers.get('Lang') is None:
return "en"
else:
regex = '^[!@#$\\/.].*/.*' # Easy~~
language = request.headers.get('Lang')
language = re.sub(r'%00|%0d|%0a|[!@#$^]|\.\./', '', language)
if re.search(regex,language):
return request.headers.get('Lang')
try:
data = requests.get(request.host_url+language, headers=request.headers)
if data.status_code == 200:
return data.text
else:
return request.headers.get('Lang')
except:
return request.headers.get('Lang')
def list_routes():
return ['%s' % rule for rule in app.url_map.iter_rules()]
def SignCheck(request):
sigining = hmac.new( privateKey , request.query_string, hashlib.sha512 )
if sigining.hexdigest() != request.headers.get('Sign'):
return False
else:
return True
@app.route('/', methods=['GET'])
def index():
# information call
information = list_routes()
information.append(request.host_url)
return str(information)
@app.route('/en', methods=['GET'])
def en():
return 'en'
@app.route('/jp', methods=['GET'])
def jp():
return 'jp'
@app.route('/coin', methods=['GET'])
def coin():
try:
response = app.response_class()
language = LanguageNomarize(request)
response.headers["Lang"] = language
data = getCoinInfo()
response.data = json.dumps(data)
return response
except Exception as e :
err = 'Error On {f} : {c}, Message, {m}, Error on line {l}'.format(f = sys._getframe().f_code.co_name ,c = type(e).__name__, m = str(e), l = sys.exc_info()[-1].tb_lineno)
logger.error(err)
@app.route('/download', methods=['GET','POST'])
def download():
try:
if request.headers.get('Sign') == None:
return json.dumps(status['sign'])
else:
if SignCheck(request):
pass
else:
return json.dumps(status['sign'])
if request.method == 'GET':
src = request.args.get('src')
if valid_download(src):
pass
else:
return json.dumps(status.get('false'))
elif request.method == 'POST':
if valid_download(request.form['src']):
pass
else:
return json.dumps(status.get('false'))
WriteFile(src)
return json.dumps(status.get('success'))
except Exception as e :
err = 'Error On {f} : {c}, Message, {m}, Error on line {l}'.format(f = sys._getframe().f_code.co_name ,c = type(e).__name__, m = str(e), l = sys.exc_info()[-1].tb_lineno)
logger.error(err)
return json.dumps(status.get('false')), 404
@app.route('/addsub', methods=['GET'])
def addsub():
try:
regex = '^[a-z0-9]+[\._]?[a-z0-9]+[@]\w+[.]\w{2,3}$'
email = request.args.get('email')
if (email is None) or (len(email)>100):
return json.dumps(status['email'])
if re.search(regex,email):
return activity.AddSubscriber(email)
else:
return json.dumps(status['email'])
except Exception as e :
err = 'Error On {f} : {c}, Message, {m}, Error on line {l}'.format(f = sys._getframe().f_code.co_name ,c = type(e).__name__, m = str(e), l = sys.exc_info()[-1].tb_lineno)
logger.error(err)
@app.route('/integrityStatus', methods=['GET'])
def integritycheck():
data = {'db':'database/master.db','dbhash':activity.dbHash}
data = json.dumps(data)
return data
@app.route('/rollback', methods=['GET'])
def rollback():
try:
if request.headers.get('Sign') == None:
return json.dumps(status['sign'])
else:
if SignCheck(request):
pass
else:
return json.dumps(status['sign'])
if request.headers.get('Key') == None:
return json.dumps(status['key'])
result = activity.IntegrityCheck(request.headers.get('Key'),request.args.get('dbhash'))
return result
except Exception as e :
err = 'Error On {f} : {c}, Message, {m}, Error on line {l}'.format(f = sys._getframe().f_code.co_name ,c = type(e).__name__, m = str(e), l = sys.exc_info()[-1].tb_lineno)
logger.error(err)
return json.dumps(status['error']), 404
@app.before_request
def before_request():
if str(request.url_rule) not in list_routes():
return json.dumps(status['error']), 404
if request.headers.get('Sign') != None:
if len(request.headers)>8:
result = status['admin']
result['message'] = result['message']+str(len(request.headers))
return json.dumps(result), 404
@app.after_request
def after_request(response):
response.headers.add("Access-Control-Allow-Origin", "*")
response.headers.add("Access-Control-Allow-Headers", "Content-Type,Authorization")
response.headers.add("Access-Control-Allow-Methods", "GET,PUT,POST,DELETE,OPTIONS")
return response
@app.errorhandler(404)
def page_not_found(e):
return json.dumps(status['error']), 404
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/LINE/2021/web/diveinternal/private/app/rollback.py | ctfs/LINE/2021/web/diveinternal/private/app/rollback.py | import subprocess,time,os, sys
import logging
from dotenv import load_dotenv
load_dotenv()
logger = logging.getLogger('KillCoinapi')
subprocess.SW_HIDE = 1
def RunRollbackDB(dbhash):
try:
if os.environ['ENV'] == 'LOCAL':
return
if dbhash is None:
return "dbhash is None"
dbhash = ''.join(e for e in dbhash if e.isalnum())
if os.path.isfile('backup/'+dbhash):
with open('FLAG', 'r') as f:
flag = f.read()
return flag
else:
return "Where is file?"
except Exception as e :
logger.error('Error On {f} : {c}, Message, {m}, Error on line {l}'.format(f = sys._getframe().f_code.co_name ,c = type(e).__name__, m = str(e), l = sys.exc_info()[-1].tb_lineno))
return "exception!!"
pass
def RunbackupDB(remove, dbhash):
try:
if os.environ['ENV'] == 'LOCAL':
return
subprocess.Popen(r'rm backup/*' , shell=True).wait()
subprocess.Popen(r'cp ' + os.environ['DBFILE'] + ' backup/' + dbhash, shell=True).wait() # for low memory.
return dbhash
except Exception as e :
logger.error('Error On {f} : {c}, Message, {m}, Error on line {l}'.format(f = sys._getframe().f_code.co_name ,c = type(e).__name__, m = str(e), l = sys.exc_info()[-1].tb_lineno))
pass
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/LINE/2021/web/babyweb/gen.py | ctfs/LINE/2021/web/babyweb/gen.py | from uuid import uuid4
USERNAME_HEADER = f"x-user-{uuid4()}"
PASSWORD_HEADER = f"x-pass-{uuid4()}"
USERNAME_ADMIN = "admin"
PASSWORD_ADMIN = f"{uuid4()}"
with open("docker-compose_tmp.yml") as f:
dcyml = f.read()
dcyml = dcyml.replace("USERNAME_HEADER_DUMMY", USERNAME_HEADER)
dcyml = dcyml.replace("PASSWORD_HEADER_DUMMY", PASSWORD_HEADER)
dcyml = dcyml.replace("USERNAME_ADMIN_DUMMY", USERNAME_ADMIN)
dcyml = dcyml.replace("PASSWORD_ADMIN_DUMMY", PASSWORD_ADMIN)
with open("docker-compose.yml", "w") as f:
f.write(dcyml)
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/LINE/2021/web/babyweb/public/src/utils.py | ctfs/LINE/2021/web/babyweb/public/src/utils.py | import hyper
from uuid import uuid4
from config import cfg
def create_connection():
hyper.tls.cert_loc="./cert.pem"
return hyper.HTTPConnection(cfg["INTERNAL"]["HOST"], secure=True)
def get_uuid():
return str(uuid4()) | python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/LINE/2021/web/babyweb/public/src/internal.py | ctfs/LINE/2021/web/babyweb/public/src/internal.py | import functools
import requests
from flask import (
Blueprint, flash, g, redirect, render_template, request, session, url_for, jsonify
)
from utils import *
from config import cfg
internal_bp = Blueprint('internal', __name__, url_prefix='/internal')
@internal_bp.route("/auth", methods=["POST"])
def auth():
data = request.get_json()
conn = create_connection()
headers = {
cfg["HEADER"]["USERNAME"]: data["username"],
cfg["HEADER"]["PASSWORD"]: data["password"]
}
conn.request("GET", "/auth", headers=headers)
resp = conn.get_response()
return resp.read()
@internal_bp.route("/health", methods=["POST"])
def health():
try:
data = request.get_json()
if "type" in data.keys():
if data["type"] == "1.1":
requests.get("https://" + cfg["INTERNAL"]["HOST"] + "/health", verify=False)
headers = {
cfg["HEADER"]["USERNAME"]: cfg["ADMIN"]["USERNAME"],
cfg["HEADER"]["PASSWORD"]: cfg["ADMIN"]["PASSWORD"]
}
requests.get("https://" + cfg["INTERNAL"]["HOST"] + "/auth", headers=headers, verify=False)
r = requests.post("https://" + cfg["INTERNAL"]["HOST"] + "/", data=data["data"].encode('latin-1'), verify=False)
return r.text
elif data["type"] == "2":
conn = create_connection()
conn.request("GET", "/health")
resp = conn.get_response()
headers = {
cfg["HEADER"]["USERNAME"]: cfg["ADMIN"]["USERNAME"],
cfg["HEADER"]["PASSWORD"]: cfg["ADMIN"]["PASSWORD"]
}
conn.request("GET", "/auth", headers=headers)
resp = conn.get_response()
conn._new_stream()
conn._send_cb(data["data"].encode('latin-1'))
conn._sock.fill()
return conn._sock.buffer.tobytes()
else:
return "done."
else:
return "done."
except:
return "error occurs"
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/LINE/2021/web/babyweb/public/src/config.py | ctfs/LINE/2021/web/babyweb/public/src/config.py | from os import getenv
cfg = {
"HEADER": {
"USERNAME": getenv("USERNAME_HEADER"),
"PASSWORD": getenv("PASSWORD_HEADER")
},
"ADMIN": {
"USERNAME": getenv("USERNAME_ADMIN"),
"PASSWORD": getenv("PASSWORD_ADMIN")
},
"INTERNAL": {
"HOST": getenv("INTERNAL_HOST")
}
} | python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/LINE/2021/web/babyweb/public/src/app.py | ctfs/LINE/2021/web/babyweb/public/src/app.py | from functools import wraps
from flask import Flask, render_template, g, jsonify, request, session, redirect, url_for, abort
from hyper import HTTPConnection
import sqlite3
from internal import internal_bp
from utils import get_uuid
DATABASE = 'database/sql.db'
app = Flask(__name__)
app.register_blueprint(internal_bp)
app.secret_key = get_uuid()
@app.errorhandler(404)
def page_not_found(e):
return render_template("404.html"), 404
@app.errorhandler(500)
def internal_error(e):
return render_template("500.html"), 500
def session_required(f):
@wraps(f)
def decorated_function(*args, **kwargs):
if "uid" not in session:
return redirect('/')
return f(*args, **kwargs)
return decorated_function
def get_db():
db = getattr(g, '_database', None)
if db is None:
db = g._database = sqlite3.connect(DATABASE)
return db
def init_db():
with app.app_context():
db = get_db()
with app.open_resource('schema.sql', mode='r') as f:
db.cursor().executescript(f.read())
db.commit()
def get_notelist():
query = "SELECT * FROM note WHERE uid = ? LIMIT 10"
cur = get_db().execute(query, [session["uid"]])
rv = cur.fetchall()
return rv
def get_note(uuid):
query = "SELECT * FROM note WHERE id = ?"
cur = get_db().execute(query, [uuid])
rv = cur.fetchone()
return rv
def save_note(title, content):
query = "INSERT INTO note VALUES (?,?,?,?)"
_id = get_uuid()
db = get_db()
db.cursor().execute(query, (session["uid"], _id, title, content))
db.commit()
return _id
@app.teardown_appcontext
def close_connection(exception):
db = getattr(g, '_database', None)
if db is not None:
db.close()
@app.route("/", methods=["GET"])
def main():
if "uid" not in session:
session["uid"] = get_uuid()
return render_template("index.html")
@app.route("/note", methods=["GET", "POST"])
@session_required
def note():
if request.method == "GET":
rv = get_notelist()
return render_template("note.html", notes=rv)
else:
title = request.form.get("title")
content = request.form.get("content")
if type(title) == str and type(content) == str:
_id = save_note(title, content)
return redirect(f"/note/{_id}")
else:
return redirect("/note")
@app.route("/note/<uuid>", methods=["GET"])
@session_required
def get_note_with_uuid(uuid):
rv = get_note(uuid)
if rv == None:
abort(404)
return render_template("view_note.html", note=rv)
if __name__ == "__main__":
init_db()
app.run("0.0.0.0", port=12000, debug=False) | python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/LINE/2023/pwn/catgle/catgle/models.py | ctfs/LINE/2023/pwn/catgle/catgle/models.py | from sqlalchemy import Column, Boolean, Integer, String, Text, DateTime, ForeignKey, Table
from sqlalchemy.orm import relationship, backref
from database import Base
question_voter = Table(
'question_voter',
Base.metadata,
Column('user_id', Integer, ForeignKey('users.id'), primary_key=True),
Column('question_id', Integer, ForeignKey('question.id'), primary_key=True)
)
answer_voter = Table(
'answer_voter',
Base.metadata,
Column('user_id', Integer, ForeignKey('users.id'), primary_key=True),
Column('answer_id', Integer, ForeignKey('answer.id'), primary_key=True)
)
### for <jump to fastapi>
class Question(Base):
__tablename__ = "question"
id = Column(Integer, primary_key=True)
subject = Column(String(64), nullable=False)
content = Column(Text, nullable=False)
create_date = Column(DateTime, nullable=False)
modify_date = Column(DateTime, nullable=True)
user_id = Column(Integer, ForeignKey('users.id'), nullable=True)
user = relationship('User', backref='question_users')
voters = relationship('User', secondary=question_voter, backref='voted_questions')
is_markdown = Column(Boolean, nullable=True)
class Answer(Base):
__tablename__ = "answer"
id = Column(Integer, primary_key=True)
content = Column(Text, nullable=False)
create_date = Column(DateTime, nullable=False)
modify_date = Column(DateTime, nullable=True)
question_id = Column(Integer, ForeignKey("question.id"))
question = relationship("Question", backref=backref("answers", cascade="all,delete"))
user_id = Column(Integer, ForeignKey('users.id'), nullable=True)
user = relationship('User', backref='answer_users')
voters = relationship('User', secondary=answer_voter, backref='voted_answers')
is_markdown = Column(Boolean, nullable=True)
### for catgle ###
class User(Base):
__tablename__ = "users"
id = Column(Integer, primary_key=True)
username = Column(String(16), unique=True, nullable=False)
password = Column(Text, nullable=False)
uploaded_model = Column(Boolean, nullable=False)
registered_ip = Column(String(16), unique=True, nullable=False)
last_activity = Column(DateTime, nullable=True)
participated = Column(Integer, nullable=True)
ranking = Column(Integer, nullable=True)
register_date = Column(DateTime, nullable=True)
class Chall(Base):
__tablename__ = 'chall'
id = Column(Integer, primary_key=True)
source = Column(Text, nullable=False)
file_name = Column(Text, nullable=False)
file_size = Column(Integer, nullable=False)
user_id = Column(Integer, ForeignKey('users.id'))
user = relationship('User', backref='challs')
category = Column(String(16), nullable=False)
submission_date = Column(DateTime, nullable=True)
failed = Column(Boolean, nullable=True)
reason = Column(String(64), nullable=True) # reason for fail
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/LINE/2023/pwn/catgle/catgle/main.py | ctfs/LINE/2023/pwn/catgle/catgle/main.py | from fastapi import FastAPI, Request
from starlette.middleware.cors import CORSMiddleware
from starlette_validation_uploadfile import ValidateUploadFileMiddleware
from domain.question import question_router
from domain.answer import answer_router
from domain.user import user_router
from domain.chall import chall_router
from starlette.responses import FileResponse
from starlette.staticfiles import StaticFiles
from fastapi.templating import Jinja2Templates
import models
from database import engine
app = FastAPI()
origins = [
"*",
]
app.add_middleware(
CORSMiddleware,
allow_origins=origins,
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
app.add_middleware(
ValidateUploadFileMiddleware,
app_path="/",
max_size=1024 * 1024 * 101, #100Mbyte
file_type=["*"]
)
app.include_router(question_router.router)
app.include_router(answer_router.router)
app.include_router(user_router.router)
app.include_router(chall_router.router)
app.mount("", StaticFiles(directory="frontend/", html=True), name="frontend")
# to support Browser Routing of routify in frontend
templates = Jinja2Templates(directory="frontend/")
@app.exception_handler(404)
async def custom_404_handler(request: Request, _):
return templates.TemplateResponse("index.html", {"request": request})
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/LINE/2023/pwn/catgle/catgle/database.py | ctfs/LINE/2023/pwn/catgle/catgle/database.py | from sqlalchemy import create_engine, MetaData
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker
import os
SQLALCHEMY_DATABASE_URL = "mysql+mysqldb://{username}:{password}@{host}:{port}/catgle".format(
username=os.environ['MYSQL_USER'],
password=os.environ['MYSQL_PASSWORD'],
host=os.environ['MYSQL_HOST'],
port=os.environ['MYSQL_PORT'])
engine = create_engine(
SQLALCHEMY_DATABASE_URL, connect_args={'connect_timeout': 20}
)
SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)
Base = declarative_base()
naming_convention = {
'ix': 'ix_%(column_0_label)s',
'uq': 'uq_%(table_name)s_%(column_0_name)s',
'ck': 'ck_%(table_name)s_%(column_0_name)s',
'fk': 'fk_%(table_name)s_%(column_0_name)s_%(referred_table_name)s',
'pk': 'pk_%(table_name)s'
}
Base.metadata = MetaData(naming_convention=naming_convention)
def get_db():
db = SessionLocal()
try:
yield db
finally:
db.close()
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/LINE/2023/pwn/catgle/catgle/config.py | ctfs/LINE/2023/pwn/catgle/catgle/config.py | from pydantic import BaseSettings
class Settings(BaseSettings):
ACCESS_TOKEN_EXPIRATION_MIN: int
# REFRESH_TOKEN_EXPIRATION_MIN: int
# JWT_PUBLIC_KEY: str
JWT_PRIVATE_KEY: str
ALGORITHM: str
class Config:
env_file = ".env"
def get_envs():
return Settings() | python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/LINE/2023/pwn/catgle/catgle/domain/chall/chall_schema.py | ctfs/LINE/2023/pwn/catgle/catgle/domain/chall/chall_schema.py | from pydantic import BaseModel, validator
class UploadedModel(BaseModel):
source: str
file_name: str
file_size: int | python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/LINE/2023/pwn/catgle/catgle/domain/chall/chall_router.py | ctfs/LINE/2023/pwn/catgle/catgle/domain/chall/chall_router.py | import os
from datetime import datetime
from fastapi import APIRouter, Depends, HTTPException, UploadFile
from sqlalchemy.orm import Session
from starlette import status
from database import get_db
from domain.answer import answer_schema, answer_crud
from domain.question import question_crud
from domain.chall import chall_crud, chall_schema
from domain.user import user_crud
from domain.user.user_router import get_current_user
from models import User
import tensorflow as tf
import torch
UPLOAD_DIR = "uploads/"
try:
os.mkdir(UPLOAD_DIR)
except:
pass
router = APIRouter(
prefix="/api/chall"
)
@router.post('/upload/{category}', status_code=status.HTTP_204_NO_CONTENT)
def handle_upload(category: str,
file: UploadFile,
user: User = Depends(get_current_user),
db:Session = Depends(get_db)):
if not ('classification' == category.lower() or \
'gan' == category.lower()):
raise HTTPException(status_code=status.HTTP_406_NOT_ACCEPTABLE,
detail='Only submissions for classifcation and gan are allowed')
if user.last_activity is not None and \
(datetime.now() - user.last_activity).seconds <= 3:
raise HTTPException(status_code=status.HTTP_429_TOO_MANY_REQUESTS,
detail="sending too many requests. wait 3 seconds and retry")
# delete existing submission
chall_crud.delete_chall_by_category(db=db, user=user, category=category)
file_signature = file.file.read(4)
file.file.seek(0)
saved_name = os.urandom(16).hex()
if file_signature == '\x89HDF':
saved_name += '.h5'
failed = False
failed_reason = ''
with open(UPLOAD_DIR + saved_name, "wb") as f:
file_data = file.file.read()
file_size = len(file_data)
f.write(file_data)
if saved_name[-3:] == '.h5':
try:
model = tf.keras.models.load_model(UPLOAD_DIR+saved_name)
model_shape = model.input_shape[-3:]
if model_shape != (299, 299, 3):
failed = True
failed_reason = f'Input shape must be (299, 299, 3). You provided {model_shape}'
except:
failed = True
failed_reason = f'Failed to load model. https://www.tensorflow.org/tutorials/keras/save_and_load#hdf5_format'
else:
try:
model = torch.load(UPLOAD_DIR+saved_name)
# it seems there is no method to get shape of an input layer, so just skipping check.
except Exception as e:
failed = True
failed_reason = f'Failed to load model. https://pytorch.org/tutorials/beginner/saving_loading_models.html#save-load-entire-model'
# process failed torch model and raise
try:
os.remove(UPLOAD_DIR + saved_name) # I will not actually run inferences.
except:
pass
# validation done. save chal in DB
chall_crud.create_chall(db=db,
source=os.urandom(4).hex(), # source acts like a "key" in FilePond
user=user,
file_name=file.filename,
file_size=file_size,
category=category,
failed=failed,
failed_reason=failed_reason)
user_crud.add_participation(db=db,
user=user,
category=category)
@router.delete('/cancel/{category}', status_code=status.HTTP_204_NO_CONTENT)
def handle_delete(category: str,
user: User = Depends(get_current_user),
db: Session = Depends(get_db)):
if user.last_activity is not None and \
(datetime.now() - user.last_activity).seconds <= 3:
raise HTTPException(status_code=status.HTTP_429_TOO_MANY_REQUESTS,
detail="sending too many requests. wait 3 seconds and retry")
chall_crud.delete_chall_by_category(db=db, user=user, category=category)
user_crud.delete_participation(db=db, user=user, category=category)
@router.get('/progress/{category}')
def get_progress(category: str,
db: Session = Depends(get_db),
user: User = Depends(get_current_user)):
chall = chall_crud.get_chall_by_category(db=db, user=user, category=category)
if not chall:
raise HTTPException(status_code=status.HTTP_428_PRECONDITION_REQUIRED,
detail="Model not submitted yet.")
if chall.failed:
raise HTTPException(status_code=status.HTTP_417_EXPECTATION_FAILED,
detail=chall.reason)
return {
'detail': "Model submitted successfully and validated. Actual evaluation will be done after LINE CTF 2023 ends."
}
@router.get('/get/{category}', response_model=chall_schema.UploadedModel)
def get_uploaded(category: str,
db: Session = Depends(get_db),
user: User = Depends(get_current_user)):
if user.last_activity is not None and \
(datetime.now() - user.last_activity).seconds <= 3:
raise HTTPException(status_code=status.HTTP_429_TOO_MANY_REQUESTS,
detail="sending too many requests. wait 3 seconds and retry")
chall = chall_crud.get_chall_by_category(db=db, user=user, category=category)
if not chall:
raise HTTPException(status_code=status.HTTP_428_PRECONDITION_REQUIRED,
detail="Model not submitted yet")
return {
'source': chall.source,
'file_name': chall.file_name,
'file_size': chall.file_size
}
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/LINE/2023/pwn/catgle/catgle/domain/chall/chall_crud.py | ctfs/LINE/2023/pwn/catgle/catgle/domain/chall/chall_crud.py | from datetime import datetime
from sqlalchemy.orm import Session
from domain.answer.answer_schema import AnswerCreate, AnswerUpdate
from models import User, Chall
def create_chall(db: Session,
source: str,
user: User,
category: str,
file_name: str,
file_size: int,
failed: bool,
failed_reason: str):
new_chall = Chall(user_id=user.id,
user=user,
category=category,
source=source,
file_name=file_name,
file_size=file_size,
submission_date=datetime.now(),
failed=failed,
reason=failed_reason)
db.add(new_chall)
db.commit()
def get_chall_by_category(db: Session,
user: User,
category: str):
return db.query(Chall).filter(
(Chall.category == category) &
(Chall.id == User.id)
).first()
def delete_chall_by_category(db: Session,
user: User,
category: str):
chall = db.query(Chall).filter(
(Chall.category == category) &
(Chall.id == User.id)
).first()
if chall:
db.delete(chall)
db.commit() | python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/LINE/2023/pwn/catgle/catgle/domain/user/user_schema.py | ctfs/LINE/2023/pwn/catgle/catgle/domain/user/user_schema.py | from pydantic import BaseModel, validator
import datetime
class UserCreate(BaseModel):
username: str
password: str
password_confirm: str
@validator('username', 'password', 'password_confirm')
def not_empty(cls, v):
if not v or not v.strip():
raise ValueError("Empty values are not allowed")
return v
@validator('password_confirm')
def pw_match(cls, v, values):
if 'password' in values and v != values['password']:
raise ValueError("Passwords don't match")
return v
class Token(BaseModel):
access_token: str
token_type: str
username: str
user_idx: int
class User(BaseModel):
id: int
username: str
participated: int = None
ranking: int = None
register_date: datetime.datetime | None = None
class Config:
orm_mode = True | python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/LINE/2023/pwn/catgle/catgle/domain/user/user_crud.py | ctfs/LINE/2023/pwn/catgle/catgle/domain/user/user_crud.py | import hashlib
from datetime import datetime
from sqlalchemy.orm import Session
from domain.user.user_schema import UserCreate
from models import User, Chall
def create_user(db: Session, user_create: UserCreate, ip_addr: str):
"""
username = Column(String, unique=True, nullable=False)
password = Column(String, nullable=False)
uploaded_model = Column(Boolean, nullable=False)
registered_ip = Column(String, unique=True, nullable=False)
"""
db_user = User(username=user_create.username,
password=hashlib.sha3_512(bytes(user_create.password, 'utf-8')).hexdigest(),
uploaded_model=False,
registered_ip=ip_addr,
last_activity=datetime.now(),
participated=0,
ranking=0,
register_date=datetime.now()
)
db.add(db_user)
db.commit()
def get_user(db:Session, user_create: UserCreate):
return db.query(User).filter(
(User.username == user_create.username)
).first()
def get_user_by_name(db: Session, username: str):
return db.query(User).filter(
(User.username == username)
).first()
def get_user_by_id(db: Session, userid: int):
return db.query(User).filter(
(User.id == userid)
).first()
def get_user_by_ip(db: Session, ip_addr: str):
return db.query(User).filter(
(User.registered_ip == ip_addr)
).first()
def hash_password(passwd: str):
return hashlib.sha3_512(bytes(passwd, 'utf-8')).hexdigest()
def add_participation(db: Session, user: User, category: str):
new_value = user.participated
new_value = new_value | 1 if category == 'classification' else new_value
new_value = new_value | 2 if category == 'gan' else new_value
user.participated = new_value
db.add(user)
db.commit()
def delete_participation(db: Session, user: User, category: str):
new_value = user.participated
new_value = new_value & ~1 if category == 'classification' else new_value
new_value = new_value & ~2 if category == 'gan' else new_value
user.participated = new_value
db.add(user)
db.commit() | python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/LINE/2023/pwn/catgle/catgle/domain/user/user_router.py | ctfs/LINE/2023/pwn/catgle/catgle/domain/user/user_router.py | from datetime import timedelta, datetime
import os
import hashlib
from fastapi import APIRouter, Depends, Request, HTTPException
from fastapi.security import OAuth2PasswordRequestForm, OAuth2PasswordBearer
from jose import jwt, JWTError
from sqlalchemy.orm import Session
from starlette import status
from database import get_db
from domain.user import user_crud, user_schema
from config import get_envs
env = get_envs() # envs have settings for JWT
oauth2_scheme = OAuth2PasswordBearer(tokenUrl='/api/user/login')
router = APIRouter(
prefix="/api/user",
)
def get_current_user(token: str = Depends(oauth2_scheme),
db: Session = Depends(get_db)):
credentials_exception = HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail="Could not validate credentials",
headers={"WWW-Authenticate": "Bearer"},
)
try:
payload = jwt.decode(token, env.JWT_PRIVATE_KEY, algorithms=[env.ALGORITHM])
username: str = payload.get('sub')
if username is None:
raise credentials_exception
except JWTError as e:
raise credentials_exception
else:
user = user_crud.get_user_by_name(db, username=username)
if user is None:
raise credentials_exception
return user
@router.get('/check_ip', status_code=status.HTTP_204_NO_CONTENT)
def check_ip(request: Request,
db:Session = Depends(get_db)):
user = user_crud.get_user_by_ip(db, ip_addr=request.client.host)
if user:
raise HTTPException(status_code=status.HTTP_409_CONFLICT,
detail=f"Only one account per IP address is allowed [ {user.username} ]")
@router.get('/check_login', status_code=status.HTTP_204_NO_CONTENT)
def check_login(request: Request,
user:user_schema.User = Depends(get_current_user)):
# if get_current_user succeeds(logged in and access token valid):
# HTTP 204
# else (if access token invalid):
# get_current_user raises HTTP_401_UNAUTHORIZED
pass
@router.post("/register", status_code=status.HTTP_204_NO_CONTENT)
def user_create(request: Request,
_user_create: user_schema.UserCreate,
db: Session = Depends(get_db)):
user = user_crud.get_user_by_ip(db, ip_addr=request.client.host)
if user:
# allow one account per ip
raise HTTPException(status_code=status.HTTP_409_CONFLICT,
detail=f"User [{user.username}, {user.registered_ip}] already exists!!")
user = user_crud.get_user_by_name(db, username=_user_create.username)
if user:
raise HTTPException(status_code=status.HTTP_409_CONFLICT,
detail=f"User [{user.username}] already exists!!")
user_crud.create_user(db=db,
user_create=_user_create,
ip_addr=request.client.host)
@router.post("/login", response_model=user_schema.Token)
def login(form_data: OAuth2PasswordRequestForm = Depends(),
db: Session = Depends(get_db)):
user = user_crud.get_user_by_name(db, form_data.username)
if not user or \
(user.password != user_crud.hash_password(form_data.password)):
raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail="Incorrect username or password",
headers={"WWW-Authenticate": "Bearer"},
)
data = {
"sub": user.username,
"exp": datetime.utcnow() + timedelta(minutes=env.ACCESS_TOKEN_EXPIRATION_MIN)
}
access_token = jwt.encode(data, env.JWT_PRIVATE_KEY, algorithm=env.ALGORITHM)
return {
"access_token": access_token,
"token_type": "bearer",
"username": user.username,
"user_idx": user.id
}
@router.get('/userinfo/{user_id}', response_model=user_schema.User)
def userinfo(user_id: int,
request: Request,
db: Session = Depends(get_db)):
# only serve "public" user informations
user = user_crud.get_user_by_id(db, userid=user_id)
if user:
return {
'id': user.id,
'username': user.username,
'participated': user.participated,
'ranking': user.ranking,
'register_date': user.register_date,
}
else:
return {
'id': user_id,
'username': 'N/A',
'participated': 0,
'ranking': 0,
'register_date': datetime.fromtimestamp(0)
} | python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/LINE/2023/pwn/catgle/catgle/domain/answer/answer_router.py | ctfs/LINE/2023/pwn/catgle/catgle/domain/answer/answer_router.py | from datetime import datetime
from fastapi import APIRouter, Depends, HTTPException
from sqlalchemy.orm import Session
from starlette import status
from database import get_db
from domain.answer import answer_schema, answer_crud
from domain.question import question_crud
from domain.user.user_router import get_current_user
from models import User
router = APIRouter(
prefix="/api/answer"
)
@router.post("/create/{question_id}", status_code=status.HTTP_204_NO_CONTENT)
def answer_create(question_id: int,
_answer_create:answer_schema.AnswerCreate,
db:Session = Depends(get_db),
current_user: User = Depends(get_current_user)):
if current_user.last_activity is not None and \
(datetime.now() - current_user.last_activity).seconds <= 3:
raise HTTPException(status_code=status.HTTP_429_TOO_MANY_REQUESTS,
detail="sending too many requests. wait 3 seconds and retry")
current_user.last_activity = datetime.now()
question = question_crud.get_question(db, question_id=question_id)
if not question:
raise HTTPException(status_code=404, detail="Question not found")
answer_crud.create_answer(db, question=question,
answer_create=_answer_create,
user=current_user)
@router.get('/detail/{answer_id}', response_model=answer_schema.Answer)
def answer_data(answer_id: int, db: Session = Depends(get_db)):
answer = answer_crud.get_answer(db, answer_id=answer_id)
return answer
@router.put('/update', status_code=status.HTTP_204_NO_CONTENT)
def answer_update(_answer_update: answer_schema.AnswerUpdate,
db: Session = Depends(get_db),
current_user: User = Depends(get_current_user)):
if current_user.last_activity is not None and \
(datetime.now() - current_user.last_activity).seconds <= 3:
raise HTTPException(status_code=status.HTTP_429_TOO_MANY_REQUESTS,
detail="sending too many requests. wait 3 seconds and retry")
current_user.last_activity = datetime.now()
db_answer = answer_crud.get_answer(db, answer_id=_answer_update.answer_id)
if not db_answer or \
current_user.id != db_answer.user.id:
raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST,
detail='invalid comment id')
answer_crud.update_answer(db=db,
db_answer=db_answer,
answer_update=_answer_update)
@router.delete('/delete', status_code=status.HTTP_204_NO_CONTENT)
def answer_delete(_answer_delete: answer_schema.AnswerDelete,
db: Session = Depends(get_db),
current_user: User = Depends(get_current_user)):
if current_user.last_activity is not None and \
(datetime.now() - current_user.last_activity).seconds <= 3:
raise HTTPException(status_code=status.HTTP_429_TOO_MANY_REQUESTS,
detail="sending too many requests. wait 3 seconds and retry")
current_user.last_activity = datetime.now()
db_answer = answer_crud.get_answer(db, answer_id=_answer_delete.answer_id)
if not db_answer or\
current_user.id != db_answer.user.id:
raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST,
detail='invalid comment id')
answer_crud.delete_answer(db=db, db_answer=db_answer)
@router.post('/upvote', status_code=status.HTTP_204_NO_CONTENT)
def answer_vote(_answer_vote: answer_schema.AnswerVote,
db: Session = Depends(get_db),
current_user: User = Depends(get_current_user)):
if current_user.last_activity is not None and \
(datetime.now() - current_user.last_activity).seconds <= 3:
raise HTTPException(status_code=status.HTTP_429_TOO_MANY_REQUESTS,
detail="sending too many requests. wait 3 seconds and retry")
current_user.last_activity = datetime.now()
db_answer = answer_crud.get_answer(db, answer_id=_answer_vote.answer_id)
if not db_answer:
raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST,
detail='Invalid answer id')
answer_crud.vote_answer(db, db_answer=db_answer, db_user=current_user) | python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/LINE/2023/pwn/catgle/catgle/domain/answer/answer_schema.py | ctfs/LINE/2023/pwn/catgle/catgle/domain/answer/answer_schema.py | import datetime
from pydantic import BaseModel, validator
from domain.user.user_schema import User
class Answer(BaseModel):
id: int
content: str
create_date: datetime.datetime
user: User | None
question_id: int
modify_date: datetime.datetime | None = None
voters: list[User] = []
is_markdown: bool = False
class Config:
orm_mode = True
class AnswerCreate(BaseModel):
content: str
is_markdown: bool
@validator('content')
def not_empty(cls, v):
if not v or not v.strip():
raise ValueError('Empty values are not allowed')
return v
class AnswerUpdate(AnswerCreate):
answer_id: int
is_markdown: bool
class AnswerDelete(BaseModel):
answer_id: int
class AnswerVote(BaseModel):
answer_id: int | python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/LINE/2023/pwn/catgle/catgle/domain/answer/answer_crud.py | ctfs/LINE/2023/pwn/catgle/catgle/domain/answer/answer_crud.py | from datetime import datetime
from sqlalchemy.orm import Session
from domain.answer.answer_schema import AnswerCreate, AnswerUpdate
from models import Question, Answer, User
def create_answer(db: Session,
question: Question,
answer_create: AnswerCreate,
user: User):
db_answer = Answer(question=question,
content=answer_create.content,
is_markdown=answer_create.is_markdown,
create_date=datetime.now(),
user=user)
db.add(db_answer)
db.commit()
def get_answer(db: Session, answer_id: int):
return db.query(Answer).get(answer_id)
def update_answer(db: Session,
db_answer: Answer,
answer_update: AnswerUpdate):
db_answer.content = answer_update.content
db_answer.modify_date = datetime.now()
db.add(db_answer)
db.commit()
def delete_answer(db: Session,
db_answer: Answer):
db.delete(db_answer)
db.commit()
def vote_answer(db: Session,
db_answer: Answer,
db_user: User):
if db_user in db_answer.voters:
db_answer.voters.remove(db_user)
else:
db_answer.voters.append(db_user)
db.commit() | python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/LINE/2023/pwn/catgle/catgle/domain/question/question_crud.py | ctfs/LINE/2023/pwn/catgle/catgle/domain/question/question_crud.py | from datetime import datetime
from domain.question.question_schema import QuestionCreate, QuestionUpdate
from models import Question, Answer, User
from sqlalchemy.orm import Session
def get_question_list(db: Session, skip: int = 0, limit: int = 10, keyword: str = ''):
question_list = db.query(Question)
if keyword:
print(keyword)
search = "%{}%".format(keyword)
sub_query = db.query(Answer.question_id, Answer.content, User.username)\
.outerjoin(User, Answer.user_id == User.id).subquery()
question_list = question_list.outerjoin(User)\
.outerjoin(sub_query, sub_query.c.question_id == Question.id)\
.filter(Question.subject.ilike(search) |
Question.content.ilike(search) |
User.username.ilike(search) |
sub_query.c.content.ilike(search) |
sub_query.c.username.ilike(search)
)
total = question_list.distinct().count()
question_list = question_list.order_by(Question.create_date.desc())\
.offset(skip).limit(limit).distinct().all()
return total, question_list
def get_question(db: Session, question_id: int):
question = db.query(Question).get(question_id)
return question
def create_question(db: Session,
question_create:QuestionCreate,
user: User):
db_question = Question(subject=question_create.subject,
content=question_create.content,
is_markdown=question_create.is_markdown,
create_date=datetime.now(),
user=user)
db.add(db_question)
db.commit()
def update_question(db: Session,
db_question: Question,
question_update: QuestionUpdate):
db_question.subject = question_update.subject
db_question.content = question_update.content
db_question.modify_date = datetime.now()
db_question.is_markdown = question_update.is_markdown
db.add(db_question)
db.commit()
def delete_question(db: Session,
db_question: Question):
db.delete(db_question)
db.commit()
def vote_question(db: Session,
db_question: Question, db_user: User):
if db_user in db_question.voters:
db_question.voters.remove(db_user)
else:
db_question.voters.append(db_user)
db.commit() | python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/LINE/2023/pwn/catgle/catgle/domain/question/question_schema.py | ctfs/LINE/2023/pwn/catgle/catgle/domain/question/question_schema.py | import datetime
from pydantic import BaseModel, validator
from domain.answer.answer_schema import Answer
from domain.user.user_schema import User
class Question(BaseModel):
id: int
subject: str
content: str
create_date: datetime.datetime
answers: list[Answer] = []
user: User | None
modify_date: datetime.datetime | None = None
voters: list[User] = []
is_markdown: bool = False
class Config:
orm_mode = True
class QuestionCreate(BaseModel):
subject: str
content: str
is_markdown: bool
@validator('subject', 'content')
def not_empty(cls, v):
if not v or not v.strip():
raise ValueError('Empty values are not allowed')
return v
class QuestionList(BaseModel):
total: int = 0
question_list: list[Question] = []
class QuestionUpdate(QuestionCreate):
question_id: int
class QuestionDelete(BaseModel):
question_id: int
class QuestionVote(BaseModel):
question_id: int | python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/LINE/2023/pwn/catgle/catgle/domain/question/question_router.py | ctfs/LINE/2023/pwn/catgle/catgle/domain/question/question_router.py | from datetime import datetime
from fastapi import APIRouter, Depends, HTTPException
from sqlalchemy.orm import Session
from starlette import status
from database import get_db
from domain.question import question_schema, question_crud
from domain.user.user_router import get_current_user
from models import User
router = APIRouter(
prefix="/api/question",
)
@router.get("/list", response_model=question_schema.QuestionList)
def question_list(db: Session = Depends(get_db),
page: int = 0, size: int = 10, keyword: str = ''):
total, _question_list = question_crud.get_question_list(db,
skip=page*size,
limit=size,
keyword=keyword)
return {
'total': total,
'question_list': _question_list
}
@router.get("/detail/{question_id}", response_model=question_schema.Question)
def question_detail(question_id: int, db: Session = Depends(get_db)):
question = question_crud.get_question(db, question_id=question_id)
return question
@router.post("/create", status_code=status.HTTP_204_NO_CONTENT)
def question_create(_question_create:question_schema.QuestionCreate,
db: Session = Depends(get_db),
current_user: User = Depends(get_current_user)):
if current_user.last_activity is not None and \
(datetime.now() - current_user.last_activity).seconds <= 3:
raise HTTPException(status_code=status.HTTP_429_TOO_MANY_REQUESTS,
detail="sending too many requests. wait 3 seconds and retry")
current_user.last_activity = datetime.now()
question_crud.create_question(db=db,
question_create=_question_create,
user=current_user)
@router.put('/update', status_code=status.HTTP_204_NO_CONTENT)
def question_update(_question_update: question_schema.QuestionUpdate,
db: Session = Depends(get_db),
current_user: User = Depends(get_current_user)):
if current_user.last_activity is not None and \
(datetime.now() - current_user.last_activity).seconds <= 3:
raise HTTPException(status_code=status.HTTP_429_TOO_MANY_REQUESTS,
detail="sending too many requests. wait 3 seconds and retry")
current_user.last_activity = datetime.now()
db_question = question_crud.get_question(db, question_id=_question_update.question_id)
if not db_question or current_user.id != db_question.user.id:
raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST,
detail="Invalid id")
question_crud.update_question(db=db,
db_question=db_question,
question_update=_question_update)
@router.delete('/delete', status_code=status.HTTP_204_NO_CONTENT)
def question_delete(_question_delete: question_schema.QuestionDelete,
db: Session = Depends(get_db),
current_user: User = Depends(get_current_user)):
if current_user.last_activity is not None and \
(datetime.now() - current_user.last_activity).seconds <= 3:
raise HTTPException(status_code=status.HTTP_429_TOO_MANY_REQUESTS,
detail="sending too many requests. wait 3 seconds and retry")
current_user.last_activity = datetime.now()
db_question = question_crud.get_question(db, question_id=_question_delete.question_id)
if not db_question or current_user.id != db_question.user.id:
raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST,
detail='Invalid id')
question_crud.delete_question(db=db, db_question=db_question)
@router.post('/upvote', status_code=status.HTTP_204_NO_CONTENT)
def question_vote(_question_vote: question_schema.QuestionVote,
db: Session = Depends(get_db),
current_user: User = Depends(get_current_user)):
if current_user.last_activity is not None and \
(datetime.now() - current_user.last_activity).seconds <= 3:
raise HTTPException(status_code=status.HTTP_429_TOO_MANY_REQUESTS,
detail="sending too many requests. wait 3 seconds and retry")
current_user.last_activity = datetime.now()
db_question = question_crud.get_question(db, question_id=_question_vote.question_id)
if not db_question:
raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST,
detail='Invalid question id')
question_crud.vote_question(db, db_question=db_question, db_user=current_user) | python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/LINE/2023/pwn/simple-blogger/agent/admin_janitor.py | ctfs/LINE/2023/pwn/simple-blogger/agent/admin_janitor.py | from pwn import *
import struct, os, binascii
HOST = 'server'
ADMIN_USER = os.getenv('ADMIN_USER')
ADMIN_PASS = os.getenv('ADMIN_PASS')
PORT = 13443
TIMEOUT = 3
def auth():
payload = b'\x01\x02'
payload += b'\x41'*16
cred = '{0}:{1}'.format(ADMIN_USER, ADMIN_PASS)
cred_len = len(cred)
payload += struct.pack('>H', cred_len)
payload += cred.encode('utf-8')
print(payload)
return payload
def extract_sess(auth_res):
sess = auth_res[4:]
return sess
def clear_db(sess):
payload = b'\x01\x01'
payload += sess
payload += b'\x00\x04'
payload += b'PING'
return payload
def connect(payload):
r = remote(HOST, PORT)
r.send(payload)
data = r.recvrepeat(TIMEOUT)
r.close()
return data
res = connect(auth())
extracted_sess = extract_sess(res)
clear_res = connect(clear_db(extracted_sess))
print(binascii.hexlify(clear_res), end="") | python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/LINE/2023/crypto/malcheeeeese/client.py | ctfs/LINE/2023/crypto/malcheeeeese/client.py | #!/usr/bin/env python3
# crypto + misc challenge
# How to generate the authentication token
# Given as secret; key for AES, sign_key_pair for EdDSA ( sign_key, verify_key ), token, password
# key for AES, token, password were pre-shared to server.
# 1. Generate Signature for token over Ed25519 ( RFC8032 )
# 2. Encrypt password, token and signature with AES-256-CTR-Enc( base64enc(password || token || signature), key for AES, iv for AES )
# 3. Generate authentication token ; base64enc( iv for AES) || AES-256-CTR-Enc( base64enc(password || token || signature), key for AES, iv for AES )
# - password : 12 bytes, random bit-string
# - token : 15 bytes, random bit-string
# - signature : 64 bytes, Ed25519 signature ( RFC8032 )
# - key for AES : 32 bytes, random bit-string
# - iv for AES : 8 bytes, random bit-string
# - payload = base64enc(password || token || signature) : 124 bytes
# - authentication_token ( encrypted_payload ) = base64enc(iv) || AES-256-CTR-Enc ( payload ) : 136 bytes
import sys, os
sys.path.append(os.path.join(os.path.dirname(__file__), './secret/'))
from client_secret import SIGN_KEY_PAIR_HEX
from common_secret import AES_KEY_HEX, TOKEN_HEX, PASSWORD_HEX
import base64
from Crypto.PublicKey import ECC
from Crypto.Signature import eddsa
from Crypto.Cipher import AES
AES_IV_HEX = "04ab09f1b64fbf70"
aes_iv = bytes.fromhex(AES_IV_HEX)
# load secrets
aes_key = bytes.fromhex(AES_KEY_HEX)
password = bytes.fromhex(PASSWORD_HEX)
token = bytes.fromhex(TOKEN_HEX)
sign_key_pair = ECC.import_key(bytes.fromhex(SIGN_KEY_PAIR_HEX).decode('ascii'))
# 1. Generate Signature for token over Ed25519 ( RFC8032 )
signer = eddsa.new(key=sign_key_pair, mode='rfc8032')
signature = signer.sign(token)
# 2. Encrypt password, token and signature with AES-256-CTR-Enc( base64enc(password || token || signature), key for AES, iv for AES )
payload = base64.b64encode(password+token+signature)
cipher = AES.new(key=aes_key, mode=AES.MODE_CTR, nonce=aes_iv)
# 3. Generate authentication token ; base64enc( iv for AES) || AES-256-CTR-Enc( base64enc(password || token || signature), key for AES, iv for AES )
encrypted_pwd_token_sig = cipher.encrypt(payload)
encrypted_payload = base64.b64encode(aes_iv) + encrypted_pwd_token_sig
# user used PREVIOUS_AUTHN_TOKEN_HEX as authentication token
# print("PREVIOUS_AUTHN_TOKEN_HEX", encrypted_payload.hex())
print("PREVIOUS_ENCRYPTED_PWD_HEX", encrypted_pwd_token_sig[:16].hex()) | python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/LINE/2023/crypto/malcheeeeese/challenge_server.py | ctfs/LINE/2023/crypto/malcheeeeese/challenge_server.py | from server import decrypt, generate_new_auth_token
import socket, signal, json, threading
from socketserver import BaseRequestHandler, TCPServer, ForkingMixIn
address = ('0.0.0.0', 11223)
class ChallengeHandler(BaseRequestHandler):
def challenge(self, req, verifier, verify_counter):
authtoken = req.recv(1024).decode().strip()
ret = decrypt(authtoken, verifier, verify_counter)
req.sendall(json.dumps(ret).encode('utf-8')+b'\n')
def handle(self):
signal.alarm(1500)
req = self.request
req.settimeout(60)
new_auth_token, verifier = generate_new_auth_token()
req.sendall(b"Leaked Token:"+new_auth_token.hex().encode('utf-8')+b"\n")
verify_counter = 0
while True:
try:
self.challenge(req, verifier, verify_counter)
except socket.timeout as e:
req.sendall(b"Timeout. Bye.\n")
break
except socket.error:
break
except Exception as e:
print(e)
break
finally:
if verify_counter < 2:
verify_counter+=1
class ChallengeServer(ForkingMixIn, TCPServer):
request_queue_size = 100
# For address reassignment on reboot
def server_bind(self):
self.socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
self.socket.bind(self.server_address)
if __name__ == "__main__":
TCPServer.allow_reuse_address = True
server = ChallengeServer(address, ChallengeHandler)
server.serve_forever()
with server:
server_thread = threading.Thread(target=server.serve_forever)
server_thread.setDaemon(True)
server_thread.start()
while True:
pass
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/LINE/2023/crypto/malcheeeeese/server.py | ctfs/LINE/2023/crypto/malcheeeeese/server.py | #!/usr/bin/env python3
# crypto + misc challenge
# See generate_new_auth_token() in this file and client.py for details on the authentication token.
import sys, os
sys.path.append(os.path.join(os.path.dirname(__file__), './secret/'))
from server_secret import FLAG
from common_secret import AES_KEY_HEX, TOKEN_HEX, PASSWORD_HEX
import base64
from Crypto.PublicKey import ECC
from Crypto.Signature import eddsa
from Crypto.Cipher import AES
from Crypto.Random import get_random_bytes
ENCRYPTED_PAYLOAD_SIZE = 136
PREVIOUS_ENCRYPTED_PWD = "72e124ff792af7bc2c077a0260ba3c4a"
AES_IV_HEX = "04ab09f1b64fbf70"
previous_aes_iv = bytes.fromhex(AES_IV_HEX)
# load secrets
aes_key = bytes.fromhex(AES_KEY_HEX)
previous_password = bytes.fromhex(PASSWORD_HEX)
# for authentication
previous_iv_b64 = base64.b64encode(previous_aes_iv)
replay_attack_filter_for_iv = [previous_iv_b64]
replay_attack_filter_for_sig = []
acceptable_token = [] # cf. previous token ( TOKEN_HEX ) was removed
acceptable_password = [b"cheeeeese"] # cf. previous password ( PASSWORD_HEX ) was removed
# Generate new token per request
# Output:
# - new authentication token
# - verifier for EdDSA
def generate_new_auth_token():
# re-generate token+signature part
# Generate authentication token ; base64enc( iv for AES ) || AES-256-CTR-Enc( base64enc(password || token || signature), key for AES, iv for AES )
# Not changed : key for AES, iv for AES, password(PASSWORD_HEX)
# Change : token, signature
token = get_random_bytes(15)
# 1. Generate Signature for token over Ed25519 ( RFC8032 )
sign_key_pair = ECC.generate(curve='Ed25519')
signer = eddsa.new(key=sign_key_pair, mode='rfc8032')
signature = signer.sign(token)
# 2. Encrypt password, token and signature with AES-256-CTR-Enc( base64enc(password || token || signature), key for AES, iv for AES )
payload = base64.b64encode(previous_password+token+signature)
cipher = AES.new(key=aes_key, mode=AES.MODE_CTR, nonce=previous_aes_iv)
# 3. Generate authentication token ; base64enc( iv for AES) || AES-256-CTR-Enc( base64enc(password || token || signature), key for AES, iv for AES )
encrypted_payload = base64.b64encode(previous_aes_iv) + cipher.encrypt(payload)
# add token and signature to filter
acceptable_token.append(token)
replay_attack_filter_for_sig.append(base64.b64encode(token+signature)[20:])
# prepare verifier for EdDSA
verifier = eddsa.new(key=sign_key_pair.public_key(), mode='rfc8032')
return encrypted_payload, verifier
# Input : b64password : base64 encoded password
# Output:
# - Is password verification successful? ( True / False )
# - raw passowrd length
# - Error Code ( 0, 1, 2 )
# - Error Message
def verify_password(b64password):
try:
password = base64.b64decode(b64password)
except:
return False, -1, 1, "Base64 decoding error"
if password in acceptable_password:
return True, len(password), 0, "Your password is correct!"
return False, len(password), 2, "Your password is incorrect."
# Input : b64token_signature : base64 encoded token+signature, verifier, verify_counter
# Output:
# - Is signature verification successful? ( True / False )
# - Error Code ( 0, 1, 2, 3, 4 )
# - Error Message
def verify_signature(b64token_signature, verifier, verify_counter):
b64token = b64token_signature[:20]
b64signature = b64token_signature[20:]
if verify_counter > 1:
return False, 1, "Err1-Verification limit Error"
if b64signature in replay_attack_filter_for_sig:
return False, 2, "Err2-Deactived Token"
try:
token = base64.b64decode(b64token)
signature = base64.b64decode(b64signature)
except:
return False, 3, "Err3-Base64 decoding error"
try:
verifier.verify(token, signature)
if token in acceptable_token:
return True, 0, "verification is successful"
except ValueError:
pass
return False, 4, "Err4-verification is failed"
def decrypt(hex_ciphertext, verifier, verify_counter):
flag = ""
# Length check
ciphertext = bytes.fromhex(hex_ciphertext)
if len(ciphertext)!=ENCRYPTED_PAYLOAD_SIZE:
ret = {
"is_iv_verified" : False,
"is_pwd_verified" : False,
"pwd_len" : -1,
"pwd_error_number" : -1,
"pwd_error_reason": "",
"is_sig_verified" : False,
"sig_error_number" : -1,
"sig_verification_reason": "authentication token size MUST be 136 bytes",
"flag" : ""
}
return ret
iv_b64 = ciphertext[:12]
ciphertext = ciphertext[12:]
# iv reuse detection
if iv_b64 in replay_attack_filter_for_iv:
ret = {
"is_iv_verified" : False,
"is_pwd_verified" : False,
"pwd_len" : -1,
"pwd_error_number" : -1,
"pwd_error_reason": "",
"is_sig_verified" : False,
"sig_error_number" : -1,
"sig_verification_reason": "iv reuse detected",
"flag" : ""
}
return ret
cipher = AES.new(aes_key, AES.MODE_CTR, nonce=base64.b64decode(iv_b64))
pt_b64 = cipher.decrypt(ciphertext)
# password authentication
is_pwd_verified, pwd_len, pwd_error_number, pwd_error_reason = verify_password(pt_b64[:16])
# authentication using EdDSA
is_sig_verified, sig_error_number, sig_error_reason = verify_signature(pt_b64[16:], verifier, verify_counter)
if True==is_pwd_verified and True==is_sig_verified:
flag = FLAG
ret = {
"is_iv_verified" : True,
"is_pwd_verified" : is_pwd_verified,
"pwd_len" : pwd_len,
"pwd_error_number" : pwd_error_number,
"pwd_error_reason": pwd_error_reason,
"is_sig_verified" : is_sig_verified,
"sig_error_number" : sig_error_number,
"sig_error_reason": sig_error_reason,
"flag" : flag
}
return ret
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/LINE/2023/web/flag-masker/web/app.py | ctfs/LINE/2023/web/flag-masker/web/app.py | from flask import Flask, Response, session, render_template, abort, request, redirect
from captcha.image import ImageCaptcha
from core.database import Database
from core.report import Report
from core.config import Config
from string import digits
from base64 import b64encode
from random import choice
from uuid import uuid4
app = Flask(__name__)
db = Database()
report = Report()
image = ImageCaptcha(width=300, height=70)
def check_owner(uid):
return session.get("uid", False) == uid
def check_params(data):
if not data.get("memo") or not data.get("secret"):
return None
if len(data.get("memo")) > 100:
return None
if not isinstance(data.get("secret"), bool):
return None
return {"memo": data.get("memo"), "secret": data.get("secret")}
def check_url(data):
if not data.get("url") and not data.get("captcha"):
return None
return {"url": data.get("url"), "captcha": data.get("captcha")}
def log(text):
print(text, flush=True)
@app.after_request
def after_request(response):
response.headers["Referrer-Policy"] = "no-referrer"
return response
@app.route("/", methods=["GET"])
def main():
if not session.get("uid", False):
session["uid"] = uuid4().__str__()
return redirect(f"{session['uid']}")
else:
return redirect(f"{session['uid']}")
@app.route("/<string:uid>", methods=["GET"])
def memo_view(uid):
try:
owner = check_owner(uid)
memo = db.loads(
{
"uid": uid,
}
)
if not memo and not owner:
return abort(403)
return render_template("index.html", memo=memo, owner=owner)
except:
abort(404)
@app.route("/<string:uid>", methods=["POST"])
def memo_handle(uid):
try:
params = check_params(request.get_json())
params = request.get_json()
if not params:
abort(400)
if not check_owner(uid):
abort(403)
db.write({"uid": uid, "memo": params["memo"], "secret": params["secret"]})
return ""
except:
abort(404)
@app.route("/<string:uid>/alert", methods=["GET"])
def memo_alert(uid):
log(f"Memo {uid} contains flag!")
return ""
@app.route("/config", methods=["GET"])
def config():
return Response('{"regex": "LINECTF\\\{(.+)\\\}"}', mimetype="application/json")
@app.route("/report", methods=["GET"])
def report_view():
session["captcha"] = "".join(choice(digits) for _ in range(8))
captcha = b64encode(image.generate(session["captcha"]).getvalue()).decode()
return render_template("report.html", captcha=captcha)
@app.route("/report", methods=["POST"])
def report_handle():
try:
params = check_url(request.get_json())
if not params:
abort(400)
if session["captcha"] != params["captcha"]:
session.pop("captcha")
abort(400)
report.submit({"url": params["url"]})
session.pop("captcha")
return ""
except:
abort(400)
app.secret_key = Config.secret
app.run(host="0.0.0.0", port=8000, debug=False)
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/LINE/2023/web/flag-masker/web/core/report.py | ctfs/LINE/2023/web/flag-masker/web/core/report.py | from redis import Redis
class Report:
def __init__(self):
try:
self.conn = Redis(host="redis", port=6379)
except Exception as error:
print(error, flush=True)
def submit(self, data: object):
try:
self.conn.lpush("query", data["url"])
except Exception as error:
print(error, flush=True) | python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/LINE/2023/web/flag-masker/web/core/database.py | ctfs/LINE/2023/web/flag-masker/web/core/database.py | from sqlite3 import connect
from core.config import Config
class Database:
def __init__(self):
try:
self.conn = connect("./memo.db", check_same_thread=False)
cursor = self.conn.cursor()
with open("init.sql", "r") as fp:
cursor.executescript(fp.read())
self.conn.commit()
except Exception as error:
print(error, flush=True)
finally:
cursor.close()
def write(self, data: object):
try:
cursor = self.conn.cursor()
cursor.execute(
Config.quries["write"],
{
"uid": data["uid"],
"memo": data["memo"],
"secret": data["secret"]
},
)
self.conn.commit()
except Exception as error:
print(error)
finally:
cursor.close()
def loads(self, data: object):
try:
cursor = self.conn.cursor()
cursor.execute(
Config.quries["loads"],
{
"uid": data["uid"],
},
)
return cursor.fetchall()
except Exception as error:
print(error)
finally:
cursor.close() | python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/LINE/2023/web/flag-masker/web/core/config.py | ctfs/LINE/2023/web/flag-masker/web/core/config.py | from os import getenv
class Config:
secret = getenv("secret")
quries = {
"write": "insert into memo (uid, memo, secret) values (:uid, :memo, :secret)",
"loads": "select memo, secret from memo where uid = :uid",
}
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/LINE/2023/web/imagexif/backend/src/app.py | ctfs/LINE/2023/web/imagexif/backend/src/app.py |
import os, queue, secrets, uuid
from random import seed, randrange
from flask import Flask, request, redirect, url_for, session, render_template, jsonify, Response
from flask_executor import Executor
from flask_jwt_extended import JWTManager
from werkzeug.utils import secure_filename
from werkzeug.exceptions import HTTPException
import exifread, exiftool
from exiftool.exceptions import *
import base64, re, ast
from common.config import load_config, Config
from common.error import APIError, FileNotAllowed
conf = load_config()
work_queue = queue.Queue()
app = Flask(__name__)
executor = Executor(app)
app.config.from_object(Config)
app.jinja_env.add_extension("jinja2.ext.loopcontrols")
app.config['EXECUTOR_TYPE'] = 'thread'
app.config['EXECUTOR_MAX_WORKERS'] = 5
ALLOWED_EXTENSIONS = set(['png', 'jpg', 'jpeg', 'gif'])
IMAGE_EXTENSIONS = set(['png', 'jpg', 'jpeg', 'gif'])
@app.before_request
def before_request():
userAgent = request.headers
def allowed_file(filename):
return '.' in filename and \
filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS
@app.errorhandler(Exception)
def handle_error(e):
code = 500
if isinstance(e, HTTPException):
code = e.code
return jsonify(error=str(e)), code
@app.route('/')
def index():
return render_template(
'index.html.j2')
@app.route('/upload', methods=["GET","POST"])
def upload():
try:
if request.method == 'GET':
return render_template(
'upload.html.j2')
elif request.method == 'POST':
if 'file' not in request.files:
return 'there is no file in form!'
file = request.files['file']
if file and allowed_file(file.filename):
_file = file.read()
tmpFileName = str(uuid.uuid4())
with open("tmp/"+tmpFileName,'wb') as f:
f.write(_file)
f.close()
tags = exifread.process_file(file)
_encfile = base64.b64encode(_file)
try:
thumbnail = base64.b64encode(tags.get('JPEGThumbnail'))
except:
thumbnail = b'None'
with exiftool.ExifToolHelper() as et:
metadata = et.get_metadata(["tmp/"+tmpFileName])[0]
else:
raise FileNotAllowed(file.filename.rsplit('.',1)[1])
os.remove("tmp/"+tmpFileName)
return render_template(
'uploaded.html.j2', tags=metadata, image=_encfile.decode() , thumbnail=thumbnail.decode()), 200
except FileNotAllowed as e:
return jsonify({
"error": APIError("FileNotAllowed Error Occur", str(e)).__dict__,
}), 400
except ExifToolJSONInvalidError as e:
os.remove("tmp/"+tmpFileName)
data = e.stdout
reg = re.findall('\[(.*?)\]',data, re.S )[0]
metadata = ast.literal_eval(reg)
if 0 != len(metadata):
return render_template(
'uploaded.html.j2', tags=metadata, image=_encfile.decode() , thumbnail=thumbnail.decode()), 200
else:
return jsonify({
"error": APIError("ExifToolJSONInvalidError Error Occur", str(e)).__dict__,
}), 400
except ExifToolException as e:
os.remove("tmp/"+tmpFileName)
return jsonify({
"error": APIError("ExifToolException Error Occur", str(e)).__dict__,
}), 400
except IndexError as e:
return jsonify({
"error": APIError("File extension could not found.", str(e)).__dict__,
}), 400
except Exception as e:
os.remove("tmp/"+tmpFileName)
return jsonify({
"error": APIError("Unknown Error Occur", str(e)).__dict__,
}), 400
if __name__ == '__main__':
app.run(host='0.0.0.0')
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/LINE/2023/web/imagexif/backend/src/common/error.py | ctfs/LINE/2023/web/imagexif/backend/src/common/error.py | class APIError(Exception):
"""Base class for other exceptions"""
def __init__(self, description, reason: str):
self.description = description
self.reason = reason
class FileNotAllowed(Exception):
def __init__(self, _file_extension,message="File Not Allowed"):
self.message = message
self._file_extension = _file_extension
super().__init__(self.message)
def __str__(self):
return f'{self._file_extension} {self.message}'
class MalFileNotAllowed(Exception):
def __init__(self,message="This File is danger... Not Allowed"):
self.message = message
super().__init__(self.message)
def __str__(self):
return f'{self.message}' | python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/LINE/2023/web/imagexif/backend/src/common/config.py | ctfs/LINE/2023/web/imagexif/backend/src/common/config.py | import os
import random
import yaml
current_dir = os.path.join(os.path.dirname(__file__), "../../conf/")
class Config(object):
"""set app config in here"""
SECRET_KEY = os.urandom(12).hex()
JSON_AS_ASCII = False
def merge_dicts(dict1, dict2) -> dict:
"""
Recursively merges dict2 into dict1
:param dict1:
:param dict2:
:return:
"""
if not isinstance(dict1, dict) or not isinstance(dict2, dict):
return dict2
for k in dict2:
dict1[k] = merge_dicts(dict1[k], dict2[k]) if k in dict1 else dict2[k]
return dict1
def load_env() -> str:
env = os.environ.get("FLASK_ENV")
if env is None:
return "development"
return os.environ.get("FLASK_ENV")
def load_config() -> dict:
"""
load conf based on environment
:return:
"""
try:
with open(current_dir + "config.yaml", "r", encoding="utf-8") as conf_main:
conf = (yaml.safe_load(conf_main))
env = "dev"
if os.environ.get("SCRIPT_ENV") == "production":
env = "prod"
elif os.environ.get("SCRIPT_ENV") == "staging":
env = "staging"
with open(current_dir + "config_%s.yaml" % env, "r", encoding="utf-8") as conf_f:
conf = merge_dicts(conf, yaml.safe_load(conf_f))
return conf
except FileNotFoundError:
return {}
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/LINE/2022/crypto/forward-or/present.py | ctfs/LINE/2022/crypto/forward-or/present.py | '''
Python3 PRESENT implementation
original code (implementation for python2) is here:
http://www.lightweightcrypto.org/downloads/implementations/pypresent.py
'''
'''
key = bytes.fromhex("00000000000000000000")
plain = bytes.fromhex("0000000000000000")
cipher = Present(key)
encrypted = cipher.encrypt(plain)
print(encrypted.hex())
>> '5579c1387b228445'
decrypted = cipher.decrypt(encrypted)
decrypted.hex()
>> '0000000000000000'
'''
class Present:
def __init__(self,key,rounds=32):
"""Create a PRESENT cipher object
key: the key as a 128-bit or 80-bit rawstring
rounds: the number of rounds as an integer, 32 by default
"""
self.rounds = rounds
if len(key) * 8 == 80:
self.roundkeys = generateRoundkeys80(byte2number(key),self.rounds)
elif len(key) * 8 == 128:
self.roundkeys = generateRoundkeys128(byte2number(key),self.rounds)
else:
raise (ValueError, "Key must be a 128-bit or 80-bit rawstring")
def encrypt(self,block):
"""Encrypt 1 block (8 bytes)
Input: plaintext block as raw string
Output: ciphertext block as raw string
"""
state = byte2number(block)
for i in range(self.rounds-1):
state = addRoundKey(state,self.roundkeys[i])
state = sBoxLayer(state)
state = pLayer(state)
cipher = addRoundKey(state,self.roundkeys[-1])
return number2byte_N(cipher,8)
def decrypt(self,block):
"""Decrypt 1 block (8 bytes)
Input: ciphertext block as raw string
Output: plaintext block as raw string
"""
state = byte2number(block)
for i in range(self.rounds-1):
state = addRoundKey(state,self.roundkeys[-i-1])
state = pLayer_dec(state)
state = sBoxLayer_dec(state)
decipher = addRoundKey(state,self.roundkeys[0])
return number2byte_N(decipher,8)
def get_block_size(self):
return 8
# 0 1 2 3 4 5 6 7 8 9 a b c d e f
Sbox= [0xc,0x5,0x6,0xb,0x9,0x0,0xa,0xd,0x3,0xe,0xf,0x8,0x4,0x7,0x1,0x2]
Sbox_inv = [Sbox.index(x) for x in range(16)]
PBox = [0,16,32,48,1,17,33,49,2,18,34,50,3,19,35,51,
4,20,36,52,5,21,37,53,6,22,38,54,7,23,39,55,
8,24,40,56,9,25,41,57,10,26,42,58,11,27,43,59,
12,28,44,60,13,29,45,61,14,30,46,62,15,31,47,63]
PBox_inv = [PBox.index(x) for x in range(64)]
def generateRoundkeys80(key,rounds):
"""Generate the roundkeys for a 80-bit key
Input:
key: the key as a 80-bit integer
rounds: the number of rounds as an integer
Output: list of 64-bit roundkeys as integers"""
roundkeys = []
for i in range(1,rounds+1): # (K1 ... K32)
# rawkey: used in comments to show what happens at bitlevel
# rawKey[0:64]
roundkeys.append(key >>16)
#1. Shift
#rawKey[19:len(rawKey)]+rawKey[0:19]
key = ((key & (2**19-1)) << 61) + (key >> 19)
#2. SBox
#rawKey[76:80] = S(rawKey[76:80])
key = (Sbox[key >> 76] << 76)+(key & (2**76-1))
#3. Salt
#rawKey[15:20] ^ i
key ^= i << 15
return roundkeys
def generateRoundkeys128(key,rounds):
"""Generate the roundkeys for a 128-bit key
Input:
key: the key as a 128-bit integer
rounds: the number of rounds as an integer
Output: list of 64-bit roundkeys as integers"""
roundkeys = []
for i in range(1,rounds+1): # (K1 ... K32)
# rawkey: used in comments to show what happens at bitlevel
roundkeys.append(key >>64)
#1. Shift
key = ((key & (2**67-1)) << 61) + (key >> 67)
#2. SBox
key = (Sbox[key >> 124] << 124)+(Sbox[(key >> 120) & 0xF] << 120)+(key & (2**120-1))
#3. Salt
#rawKey[62:67] ^ i
key ^= i << 62
return roundkeys
def addRoundKey(state,roundkey):
return state ^ roundkey
def sBoxLayer(state):
"""SBox function for encryption
Input: 64-bit integer
Output: 64-bit integer"""
output = 0
for i in range(16):
output += Sbox[( state >> (i*4)) & 0xF] << (i*4)
return output
def sBoxLayer_dec(state):
"""Inverse SBox function for decryption
Input: 64-bit integer
Output: 64-bit integer"""
output = 0
for i in range(16):
output += Sbox_inv[( state >> (i*4)) & 0xF] << (i*4)
return output
def pLayer(state):
"""Permutation layer for encryption
Input: 64-bit integer
Output: 64-bit integer"""
output = 0
for i in range(64):
output += ((state >> i) & 0x01) << PBox[i]
return output
def pLayer_dec(state):
"""Permutation layer for decryption
Input: 64-bit integer
Output: 64-bit integer"""
output = 0
for i in range(64):
output += ((state >> i) & 0x01) << PBox_inv[i]
return output
def byte2number(i):
""" Convert a string to a number
Input: byte (big-endian)
Output: long or integer
"""
return int.from_bytes(i, 'big')
def number2byte_N(i, N):
"""Convert a number to a string of fixed size
i: long or integer
N: length of byte
Output: string (big-endian)
"""
return i.to_bytes(N, byteorder='big')
def _test():
import doctest
doctest.testmod()
if __name__ == "__main__":
_test() | python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/LINE/2022/crypto/forward-or/main.py | ctfs/LINE/2022/crypto/forward-or/main.py | from present import Present
from Crypto.Util.strxor import strxor
import os, re
class CTRMode():
def __init__(self, key, nonce=None):
self.key = key # 20bytes
self.cipher = DoubleRoundReducedPresent(key)
if None==nonce:
nonce = os.urandom(self.cipher.block_size//2)
self.nonce = nonce # 4bytes
def XorStream(self, data):
output = b""
counter = 0
for i in range(0, len(data), self.cipher.block_size):
keystream = self.cipher.encrypt(self.nonce+counter.to_bytes(self.cipher.block_size//2, 'big'))
if b""==keystream:
exit(1)
if len(data)<i+self.cipher.block_size:
block = data[i:len(data)]
block = data[i:i+self.cipher.block_size]
block = strxor(keystream[:len(block)], block)
output+=block
counter+=1
return output
def encrypt(self, plaintext):
return self.XorStream(plaintext)
def decrypt(self, ciphertext):
return self.XorStream(ciphertext)
class DoubleRoundReducedPresent():
def __init__(self, key):
self.block_size = 8
self.key_length = 160 # bits
self.round = 16
self.cipher0 = Present(key[0:10], self.round)
self.cipher1 = Present(key[10:20], self.round)
def encrypt(self, plaintext):
if len(plaintext)>self.block_size:
print("Error: Plaintext must be less than %d bytes per block" % self.block_size)
return b""
return self.cipher1.encrypt(self.cipher0.encrypt(plaintext))
def decrypt(self, ciphertext):
if len(ciphertext)>self.block_size:
print("Error: Ciphertext must be less than %d bytes per block" % self.block_size)
return b""
return self.cipher0.decrypt(self.cipher1.decrypt(ciphertext))
if __name__ == "__main__":
import sys, os
sys.path.append(os.path.join(os.path.dirname(__file__), './secret/'))
from keyfile import key
from flag import flag
# load key
if not re.fullmatch(r'[0-3]+', key):
exit(1)
key = key.encode('ascii')
# load flag
flag = flag.encode('ascii') # LINECTF{...}
plain = flag
cipher = CTRMode(key)
ciphertext = cipher.encrypt(plain)
nonce = cipher.nonce
print(ciphertext.hex())
print(nonce.hex())
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/LINE/2022/crypto/ss_puzzle/ss_puzzle.py | ctfs/LINE/2022/crypto/ss_puzzle/ss_puzzle.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# 64 bytes
FLAG = b'LINECTF{...}'
def xor(a:bytes, b:bytes) -> bytes:
return bytes(i^j for i, j in zip(a, b))
S = [None]*4
R = [None]*4
Share = [None]*5
S[0] = FLAG[0:8]
S[1] = FLAG[8:16]
S[2] = FLAG[16:24]
S[3] = FLAG[24:32]
# Ideally, R should be random stream. (Not hint)
R[0] = FLAG[32:40]
R[1] = FLAG[40:48]
R[2] = FLAG[48:56]
R[3] = FLAG[56:64]
Share[0] = R[0] + xor(R[1], S[3]) + xor(R[2], S[2]) + xor(R[3],S[1])
Share[1] = xor(R[0], S[0]) + R[1] + xor(R[2], S[3]) + xor(R[3],S[2])
Share[2] = xor(R[0], S[1]) + xor(R[1], S[0]) + R[2] + xor(R[3],S[3])
Share[3] = xor(R[0], S[2]) + xor(R[1], S[1]) + xor(R[2], S[0]) + R[3]
Share[4] = xor(R[0], S[3]) + xor(R[1], S[2]) + xor(R[2], S[1]) + xor(R[3],S[0])
# This share is partially broken.
Share[1] = Share[1][0:8] + b'\x00'*8 + Share[1][16:24] + Share[1][24:32]
with open('./Share1', 'wb') as f:
f.write(Share[1])
f.close()
with open('./Share4', 'wb') as f:
f.write(Share[4])
f.close()
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/LINE/2022/web/memo-drive/memo-drive/index.py | ctfs/LINE/2022/web/memo-drive/memo-drive/index.py | import os
import hashlib
import shutil
import datetime
import uvicorn
import logging
from urllib.parse import unquote
from starlette.applications import Starlette
from starlette.responses import HTMLResponse
from starlette.routing import Route, Mount
from starlette.templating import Jinja2Templates
from starlette.staticfiles import StaticFiles
logger = logging.getLogger()
logger.setLevel(logging.DEBUG)
templates = Jinja2Templates(directory='./')
templates.env.autoescape = False
def index(request):
context = {}
memoList = []
try:
clientId = getClientID(request.client.host)
path = './memo/' + clientId
if os.path.exists(path):
memoList = os.listdir(path)
context['request'] = request
context['ip'] = request.client.host
context['clientId'] = clientId
context['memoList'] = memoList
context['count'] = len(memoList)
except:
pass
return templates.TemplateResponse('/view/index.html', context)
def save(request):
context = {}
memoList = []
try:
context['request'] = request
context['ip'] = request.client.host
contents = request.query_params['contents']
path = './memo/' + getClientID(request.client.host) + '/'
if os.path.exists(path) == False:
os.makedirs(path, exist_ok=True)
memoList = os.listdir(path)
idx = len(memoList)
if idx >= 3:
return HTMLResponse('Memo Full')
elif len(contents) > 100:
return HTMLResponse('Contents Size Error (MAX:100)')
filename = str(idx) + '_' + datetime.datetime.now().strftime('%Y%m%d%H%M%S')
f = open(path + filename, 'w')
f.write(contents)
f.close()
except:
pass
return HTMLResponse('Save Complete')
def reset(request):
context = {}
try:
context['request'] = request
clientId = getClientID(request.client.host)
path = './memo/' + clientId
if os.path.exists(path) == False:
return HTMLResponse('Memo Null')
shutil.rmtree(path)
except:
pass
return HTMLResponse('Reset Complete')
def view(request):
context = {}
try:
context['request'] = request
clientId = getClientID(request.client.host)
if '&' in request.url.query or '.' in request.url.query or '.' in unquote(request.query_params[clientId]):
raise
filename = request.query_params[clientId]
path = './memo/' + "".join(request.query_params.keys()) + '/' + filename
f = open(path, 'r')
contents = f.readlines()
f.close()
context['filename'] = filename
context['contents'] = contents
except:
pass
return templates.TemplateResponse('/view/view.html', context)
def getClientID(ip):
key = ip + '_' + os.getenv('SALT')
return hashlib.md5(key.encode('utf-8')).hexdigest()
routes = [
Route('/', endpoint=index),
Route('/view', endpoint=view),
Route('/reset', endpoint=reset),
Route('/save', endpoint=save),
Mount('/static', StaticFiles(directory='./static'), name='static')
]
app = Starlette(debug=False, routes=routes)
if __name__ == "__main__":
logging.info("Starting Starlette Server")
uvicorn.run(app, host="0.0.0.0", port=11000) | python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/LINE/2022/web/title_todo/dist/src/app/models.py | ctfs/LINE/2022/web/title_todo/dist/src/app/models.py | from flask_login import UserMixin
from werkzeug.security import generate_password_hash, check_password_hash
from sqlalchemy import Column, Integer, String, Boolean,ForeignKey, UniqueConstraint, Text, DateTime
from sqlalchemy_utils import UUIDType
from sqlalchemy.orm import relationship, backref
from sqlalchemy.sql.functions import current_timestamp
import uuid
from database import db
class User(UserMixin, db.Model):
__tablename__ = 'user'
id = Column(Integer, primary_key=True)
username = Column(String(50), unique=True)
password_hash = Column(String(120))
is_admin = Column(Boolean, default=False)
@property
def password(self):
raise AttributeError('password is not a readable attribute')
@password.setter
def password(self, password):
self.password_hash = generate_password_hash(password)
def verify_password(self, password):
return check_password_hash(self.password_hash, password)
def __repr__(self):
return '<User %r>' % self.username
class Image(db.Model):
__tablename__ = 'image'
id = Column(UUIDType(binary=False), primary_key=True, default=uuid.uuid4)
title = Column(Text)
url = Column(Text)
owner_id = Column(Integer, ForeignKey('user.id'))
created_at = Column(DateTime, nullable=False, server_default=current_timestamp())
owner = relationship(
User,
backref=backref(
'image_owner',
uselist=True,
cascade='delete,all'
)
)
class Share(db.Model):
__tablename__ = 'share'
__table_args__ = (UniqueConstraint('image_id', 'shared_user_id'),)
id = Column(Integer, primary_key=True)
image_id = Column(UUIDType(binary=False), ForeignKey('image.id'))
shared_user_id = Column(Integer, ForeignKey('user.id'))
image = relationship(
Image,
backref=backref(
'image',
uselist=True,
cascade='delete,all'
)
)
shared_user = relationship(
User,
backref=backref(
'shared_user',
uselist=True,
cascade='delete,all'
)
) | python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/LINE/2022/web/title_todo/dist/src/app/database.py | ctfs/LINE/2022/web/title_todo/dist/src/app/database.py | from flask_sqlalchemy import SQLAlchemy
db = SQLAlchemy()
def init_db(app):
db.init_app(app)
with app.app_context():
db.create_all()
return db | python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/LINE/2022/web/title_todo/dist/src/app/config.py | ctfs/LINE/2022/web/title_todo/dist/src/app/config.py | import os
import secrets
class Config(object):
SECRET_KEY = secrets.token_bytes()
FLAG = os.getenv('FLAG')
APP_HOST = os.getenv('APP_HOST')
BASE_URL = f"http://{APP_HOST}/"
SQLALCHEMY_DATABASE_URI = 'sqlite:///db.sqlite3'
UPLOAD_FOLDER = './static/image'
REDIS_HOST = os.getenv('REDIS_HOST')
REDIS_PORT = 6379
REDIS_PASSWORD = os.getenv('REDIS_PASSWORD')
ADMIN_PASSWORD = os.getenv('ADMIN_PASSWORD') | python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/LINE/2022/web/title_todo/dist/src/app/app.py | ctfs/LINE/2022/web/title_todo/dist/src/app/app.py | import os
import re
from uuid import uuid4
from flask import Flask, json, request, redirect, url_for, flash, render_template, jsonify
from flask_login import LoginManager, login_manager, login_required, login_user, current_user, logout_user
from redis import Redis
from sqlalchemy.exc import IntegrityError
from database import init_db
from models import User, Image, Share
app = Flask(__name__)
app.config.from_object('config.Config')
db = init_db(app)
redis = Redis(host=app.config.get('REDIS_HOST'), port=app.config.get('REDIS_PORT'), db=0, password=app.config.get('REDIS_PASSWORD'))
redis.set('queued_count', 0)
redis.set('proceeded_count', 0)
login_manager = LoginManager()
login_manager.init_app(app)
@login_manager.user_loader
def load_user(user_id):
return User.query.get(int(user_id))
@login_manager.unauthorized_handler
def unauthorized():
return redirect(url_for('login'))
@app.before_first_request
def init_admin():
admin = User.query.filter_by(username='admin').first()
if not admin:
admin = User(
username='admin',
password=app.config.get('ADMIN_PASSWORD'),
is_admin=True
)
db.session.add(admin)
db.session.commit()
@app.route('/')
@login_required
def index():
images = Image.query.filter_by(owner=current_user).all()
return render_template('index.html', images=images)
@app.after_request
def add_header(response):
response.headers['Content-Security-Policy'] = "default-src 'self'; script-src 'self'; style-src 'self'; img-src 'self' blob:"
return response
@app.route('/register', methods=['GET', 'POST'])
def register():
if request.method == 'POST':
username = request.form.get('username')
password = request.form.get('password')
if username and password:
user = User.query.filter_by(username=username).first()
if user:
flash('Username already exists.')
return redirect(url_for('register'))
user = User(
username=username,
password=password
)
db.session.add(user)
db.session.commit()
return redirect(url_for('login'))
flash('Registeration failed')
return redirect(url_for('register'))
elif request.method == 'GET':
if current_user.is_authenticated:
return redirect(url_for('index'))
return render_template('register.html')
@app.route('/login', methods=['GET', 'POST'])
def login():
if request.method == 'POST':
username = request.form.get('username')
password = request.form.get('password')
if username and password:
user = User.query.filter_by(username=username).first()
if user and user.verify_password(password):
login_user(user)
return redirect(url_for('index'))
flash('Login failed')
return redirect(url_for('login'))
elif request.method == 'GET':
if current_user.is_authenticated:
return redirect(url_for('index'))
return render_template('login.html')
@app.route('/logout')
@login_required
def logout():
logout_user()
return redirect(url_for('index'))
@app.route('/image/upload', methods=['POST'])
@login_required
def upload_image():
img_file = request.files['img_file']
if img_file:
ext = os.path.splitext(img_file.filename)[1]
if ext in ['.jpg', '.png']:
filename = uuid4().hex + ext
img_path = os.path.join(app.config.get('UPLOAD_FOLDER'), filename)
img_file.save(img_path)
return jsonify({'img_url': f'/static/image/{filename}'}), 200
return jsonify({}), 400
@app.route('/image', methods=['GET', 'POST'])
@login_required
def create_image():
if request.method == 'POST':
title = request.form.get('title')
img_url = request.form.get('img_url')
if title and img_url:
if not img_url.startswith('/static/image/'):
flash('Image creation failed')
return redirect(url_for('create_image'))
image = Image(title=title, url=img_url, owner=current_user)
db.session.add(image)
db.session.commit()
res = redirect(url_for('index'))
res.headers['X-ImageId'] = image.id
return res
return redirect(url_for('create_image'))
elif request.method == 'GET':
return render_template('create_image.html')
@app.route('/image/<image_id>')
@login_required
def image(image_id):
try:
image = Image.query.filter_by(owner=current_user, id=image_id).first()
if image: # if my image
return render_template('image.html', image=image)
share = Share.query.filter_by(shared_user=current_user, image_id=image_id).first()
if share: # if shared image
image = Image.query.filter_by(id=image_id).one()
return render_template('image.html', image=image, shared=True)
except Exception as e:
print(e)
return ('', 404)
return ('', 404)
PATTERN_IMG_ID = re.compile(r'^image/([0-9a-f-]{36})')
@app.route('/share', methods=['POST'])
@login_required
def share():
share_target = User.query.filter_by(username='admin').first() # Now users can share image only with admin
try:
path = request.json['path']
img_id = PATTERN_IMG_ID.match(path).groups()[0]
image = Image.query.filter_by(owner=current_user, id=img_id).first()
if image:
share = Share(image=image, shared_user=share_target)
db.session.add(share)
db.session.commit()
# send_notification_mail(share_target, app.config.get("BASE_URL")+path) # implement before official release
print(f'[*] share {path}')
redis.rpush('query', path)
redis.incr('queued_count')
return jsonify({'result': 'ok'}), 200
except IntegrityError as e:
print(e)
return jsonify({'error': 'Already shared'}), 400
except Exception as e:
print(e)
return jsonify({'error': 'Internal Server Error'}), 400
return jsonify({}), 404
if __name__ == '__main__':
app.run('0.0.0.0') | python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/LINE/2022/web/me7ball/backend/src/app.py | ctfs/LINE/2022/web/me7ball/backend/src/app.py |
import os, queue, secrets
from random import seed, randrange
import logging.config
from flask import Flask, request, redirect, url_for, session, render_template, jsonify, Response
from flask_executor import Executor
from flask_jwt_extended import JWTManager
from werkzeug.utils import secure_filename
from werkzeug.exceptions import HTTPException
from common.config import load_config, Config
from common.logger import set_logger
from common.error import APIError, FileNotAllowed, NullParam
from me7_ba11.meatball import MeatBall
conf = load_config()
work_queue = queue.Queue()
os.makedirs(os.path.dirname(os.path.join(os.path.dirname(__file__), "../", conf["common"]["log"]["app_log_file"])), exist_ok=True)
logging.config.dictConfig(conf["logging"])
app = Flask(__name__)
executor = Executor(app)
app.config.from_object(Config)
app.jinja_env.add_extension("jinja2.ext.loopcontrols")
app.config['EXECUTOR_TYPE'] = 'thread'
app.config['EXECUTOR_MAX_WORKERS'] = 5
ALLOWED_EXTENSIONS = set(['txt', 'pdf', 'png', 'jpg', 'jpeg', 'gif'])
IMAGE_EXTENSIONS = set(['png', 'jpg', 'jpeg', 'gif'])
secret = secrets.token_bytes(2048)
backup_count = conf["common"]["log"]["backupCount"]
local_config = {
"keyForEncryption" : secret,
}
mb = MeatBall("./meat.ball",local_config, )
@app.before_request
def before_request():
userAgent = request.headers
def allowed_file(filename):
return '.' in filename and \
filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS
@app.errorhandler(Exception)
def handle_error(e):
code = 500
if isinstance(e, HTTPException):
code = e.code
return jsonify(error=str(e)), code
@app.route('/')
def index():
return render_template(
'index.html.j2')
@app.route('/append', methods=["GET","POST"])
def append():
try:
if request.method == 'GET':
return render_template(
'append.html.j2')
elif request.method == 'POST':
param = request.form.to_dict()
if param.items().__len__() != 0:
result = mb.append(param=param)
return jsonify(
result
), 200
else:
raise NullParam
except Exception as e:
return jsonify({
"error": APIError("Error Occur", str(e)).__dict__
}), 400
@app.route('/update', methods=["GET","POST"])
def update():
try:
if request.method == 'GET':
return render_template(
'update.html.j2')
elif request.method == 'POST':
param = request.form.to_dict()
if param.items().__len__() != 0:
return jsonify(
mb.update(param=param)
), 200
else:
raise NullParam
except Exception as e:
return jsonify({
"error": APIError("Error Occur", str(e)).__dict__
}), 400
@app.route('/get', methods=["GET"])
def get():
param = request.args.to_dict()
try:
if param.get('key') == None:
return render_template(
'get.html.j2')
return jsonify(
mb.get(param)
), 200
except Exception as e:
return jsonify({
"error": APIError("Error Occur", str(e)).__dict__
}), 400
@app.route('/env', methods=["GET"])
def env():
try:
return jsonify(
mb.get_env()
), 200
except Exception as e:
return jsonify({
"error": APIError("Error Occur", str(e)).__dict__
}), 400
@app.route('/upload', methods=["GET","POST"])
def upload():
try:
key = request.form.get('key')
if request.method == 'GET':
return render_template(
'upload.html.j2')
elif request.method == 'POST':
if 'file' not in request.files:
return 'there is no file in form!'
file = request.files['file']
if file and allowed_file(file.filename):
_file = file.read()
else:
raise FileNotAllowed(file.filename.rsplit('.',1)[1])
param = request.form.to_dict()
if param.items().__len__() != 0:
if key:
result = mb.update(param=param, _file=_file)
else:
result = mb.append(param=param, _file=_file)
return result
else:
raise NullParam
return jsonify(
result
), 200
except Exception as e:
return jsonify({
"error": APIError("Error Occur", str(e)).__dict__
}), 400
@app.route('/delete', methods=["POST"])
def delete():
try:
param = request.form.to_dict()
if param.items().__len__() != 0:
return jsonify({
"result": mb.delete(param)
}), 200
else:
raise NullParam
except Exception as e:
return jsonify({
"error": APIError("Error Occur", str(e)).__dict__
}), 400
if __name__ == '__main__':
app.run(host='0.0.0.0')
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/LINE/2022/web/me7ball/backend/src/common/error.py | ctfs/LINE/2022/web/me7ball/backend/src/common/error.py | class APIError(Exception):
"""Base class for other exceptions"""
def __init__(self, description, reason: str):
self.description = description
self.reason = reason
class FileNotAllowed(Exception):
def __init__(self, _file_extension,message="File Not Allowed"):
self.message = message
self._file_extension = _file_extension
super().__init__(self.message)
def __str__(self):
return f'{self._file_extension} {self.message}'
class NullParam(Exception):
def __init__(self,message="Parameter is null"):
self.message = message
super().__init__(self.message)
def __str__(self):
return f'{self.message}' | python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/LINE/2022/web/me7ball/backend/src/common/logger.py | ctfs/LINE/2022/web/me7ball/backend/src/common/logger.py | import os
import sys
from logging import getLogger, Formatter, StreamHandler, WARN, INFO, DEBUG
from logging.handlers import TimedRotatingFileHandler
def get_common_logger(name: str, log_level: str = "DEBUG", log_file_path: str = None, std_out: bool = True, backup_count: int = 180):
"""
:param name:
:param log_level:
:param log_file_path:
:param std_out:
:param backup_count:
:return:
"""
logger = getLogger(name)
if log_level == "WARN":
log_level = WARN
elif log_level == "INFO":
log_level = INFO
else:
log_level = DEBUG
formatter = Formatter("%(asctime)s %(levelname)s %(module)s %(lineno)s :%(message)s")
if log_file_path is not None:
os.makedirs(os.path.dirname(log_file_path), exist_ok=True)
handler = TimedRotatingFileHandler(filename=log_file_path, when="midnight", backupCount=backup_count, encoding="utf-8", delay=True)
handler.setLevel(log_level)
handler.setFormatter(formatter)
logger.addHandler(handler)
if std_out:
handler = StreamHandler(sys.stdout)
handler.setLevel(log_level)
handler.setFormatter(formatter)
logger.addHandler(handler)
logger.setLevel(log_level)
logger.propagate = False
return logger
def set_logger(name: str, log_conf: dict, backup_count: int = 180):
"""
set the logger for different usage
:param name:
:param log_conf:
:param backup_count:
:return:
"""
return get_common_logger(name, log_level=log_conf["level"],
log_file_path=os.path.dirname(__file__) + "/../.." + log_conf["log_file_path"],
std_out=log_conf["std_out"], backup_count=backup_count)
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/LINE/2022/web/me7ball/backend/src/common/config.py | ctfs/LINE/2022/web/me7ball/backend/src/common/config.py | import os
import random
import yaml
current_dir = os.path.join(os.path.dirname(__file__), "../../conf/")
class Config(object):
"""set app config in here"""
SECRET_KEY = os.urandom(12).hex()
JSON_AS_ASCII = False
def merge_dicts(dict1, dict2) -> dict:
"""
Recursively merges dict2 into dict1
:param dict1:
:param dict2:
:return:
"""
if not isinstance(dict1, dict) or not isinstance(dict2, dict):
return dict2
for k in dict2:
dict1[k] = merge_dicts(dict1[k], dict2[k]) if k in dict1 else dict2[k]
return dict1
def load_env() -> str:
env = os.environ.get("FLASK_ENV")
if env is None:
return "development"
return os.environ.get("FLASK_ENV")
def load_config() -> dict:
"""
load conf based on environment
:return:
"""
try:
with open(current_dir + "config.yaml", "r", encoding="utf-8") as conf_main:
conf = (yaml.safe_load(conf_main))
env = "dev"
if os.environ.get("SCRIPT_ENV") == "production":
env = "prod"
elif os.environ.get("SCRIPT_ENV") == "staging":
env = "staging"
with open(current_dir + "config_%s.yaml" % env, "r", encoding="utf-8") as conf_f:
conf = merge_dicts(conf, yaml.safe_load(conf_f))
return conf
except FileNotFoundError:
return {}
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/LINE/2022/web/hariboteSecureNote/dist/src/app/models.py | ctfs/LINE/2022/web/hariboteSecureNote/dist/src/app/models.py | import uuid
import werkzeug.security
from flask_login import UserMixin
from sqlalchemy import Column, Integer, String, Boolean, DateTime, ForeignKey, UniqueConstraint
from sqlalchemy.orm import relationship, backref
from sqlalchemy.sql.functions import current_timestamp
from sqlalchemy_utils import UUIDType
from database import db
class User(UserMixin, db.Model):
__tablename__ = 'user'
id = Column(Integer, primary_key=True)
user_id = Column(String(50), unique=True)
display_name = Column(String(16))
password_hash = Column(String(120))
is_admin = Column(Boolean, default=False)
@property
def password(self):
raise AttributeError('password is not a readable attribute')
@password.setter
def password(self, password: str):
self.password_hash = werkzeug.security.generate_password_hash(password)
def verify_password(self, password: str) -> bool:
return werkzeug.security.check_password_hash(self.password_hash, password)
def __repr__(self) -> str:
return f'<User {self.user_id}>'
class Note(db.Model):
__tablename__ = 'note'
id = Column(UUIDType(binary=False), primary_key=True, default=uuid.uuid4)
title = Column(String(64))
content = Column(String(400))
author_id = Column(Integer, ForeignKey('user.id'))
created_at = Column(DateTime, nullable=False, server_default=current_timestamp())
author = relationship(
User,
backref=backref(
'note_author',
uselist=True,
cascade='delete,all'
)
)
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/LINE/2022/web/hariboteSecureNote/dist/src/app/database.py | ctfs/LINE/2022/web/hariboteSecureNote/dist/src/app/database.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/LINE/2022/web/hariboteSecureNote/dist/src/app/config.py | ctfs/LINE/2022/web/hariboteSecureNote/dist/src/app/config.py | import os
import secrets
class Config(object):
APP_NAME = "Haribote Secure Note"
BASE_URL = os.getenv('BASE_URL', 'http://nginx/')
SECRET_KEY = secrets.token_bytes()
RATELIMIT_HEADERS_ENABLED = True
FLAG = os.getenv('FLAG', 'linectf{dummy}')
REDIS_HOST = os.getenv('REDIS_HOST', '127.0.0.1')
REDIS_PORT = os.getenv('REDIS_PORT', '6379')
REDIS_PASSWORD = os.getenv('REDIS_PASSWORD', '')
SQLALCHEMY_DATABASE_URI = 'sqlite:///db.sqlite3'
SQLALCHEMY_TRACK_MODIFICATIONS = False
ADMIN_USER_ID = os.getenv('ADMIN_USER_ID', 'admin')
ADMIN_USERNAME = os.getenv('ADMIN_USERNAME', 'admin')
ADMIN_PASSWORD = os.getenv('ADMIN_PASSWORD', 'P@ssw0rd')
NOTE_TITLE_MAX_LENGTH = 64
NOTE_CONTENT_MAX_LENGTH = 128
USER_DISPLAY_NAME_MAX_LENGTH = 16
SHARE_ID_LENGTH = 64
USER_ID_PATTERN = '^[a-zA-Z0-9-_]{1,50}$'
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/LINE/2022/web/hariboteSecureNote/dist/src/app/app.py | ctfs/LINE/2022/web/hariboteSecureNote/dist/src/app/app.py | import http
import re
import secrets
import string
from base64 import b64encode
from urllib.parse import urljoin
from flask import Flask, render_template, request, redirect, url_for, flash, make_response, jsonify
from flask_limiter import Limiter
from flask_limiter.util import get_remote_address
from flask_login import login_required, logout_user, login_user, current_user, LoginManager
from redis.client import Redis
from database import db
from models import User, Note
app = Flask(__name__)
app.config.from_object('config.Config')
db.init_app(app)
with app.app_context():
db.create_all()
redis = Redis(host=app.config.get('REDIS_HOST'),
port=app.config.get('REDIS_PORT'),
db=0,
password=app.config.get('REDIS_PASSWORD'))
login_manager = LoginManager()
login_manager.init_app(app)
limiter = Limiter(app,
key_func=get_remote_address,
storage_uri=f'redis://{app.config.get("REDIS_HOST")}:{app.config.get("REDIS_PORT")}')
@login_manager.user_loader
def load_user(user_id):
return User.query.get(int(user_id))
@login_manager.unauthorized_handler
def unauthorized():
return redirect(url_for('login'))
@app.errorhandler(429)
def ratelimit_handler(e):
return make_response(
jsonify(
error=str(e),
method=request.method,
path=request.path,
remote_addr=get_remote_address()
), 429)
@app.before_first_request
def init_admin():
if not User.query.filter_by(user_id=app.config.get('ADMIN_USERNAME')).first():
admin = User(
user_id=app.config.get('ADMIN_USER_ID'),
display_name=app.config.get('ADMIN_USERNAME'),
password=app.config.get('ADMIN_PASSWORD'),
is_admin=True
)
db.session.add(admin)
db.session.commit()
@app.route('/', methods=['GET'])
@login_required
def index():
notes = Note.query.filter_by(author=current_user).all()
ctx = {
'csp_nonce': b64encode(secrets.token_bytes(20)).decode(),
'notes': [
{
'id': str(n.id),
'title': n.title,
'content': n.content,
'createdAt': n.created_at.isoformat()
} for n in notes
]
}
return render_template('index.j2', **ctx)
@app.route('/register', methods=['GET', 'POST'])
def register():
match request.method:
case 'GET':
if current_user.is_authenticated:
return redirect(url_for('login'))
return render_template('register.j2')
case 'POST':
req_user_id = request.form.get('user_id')
req_display_name = request.form.get('display_name')
req_password = request.form.get('password')
if not req_user_id or not req_display_name or not req_password:
flash('there is blank field', category='danger')
return redirect(url_for('register'))
if not re.match(app.config.get('USER_ID_PATTERN'), req_user_id):
flash('invalid user id', category='danger')
return redirect(url_for('register'))
if len(req_display_name) > app.config.get('USER_DISPLAY_NAME_MAX_LENGTH'):
flash('invalid display name', category='danger')
return redirect(url_for('register'))
try:
if User.query.filter_by(user_id=req_user_id).first():
flash('specified user id already exists', category='danger')
return redirect(url_for('register'))
new_user = User(
user_id=req_user_id,
display_name=req_display_name,
password=req_password
)
db.session.add(new_user)
db.session.commit()
return redirect(url_for('login'))
except Exception:
flash('registration failed', category='danger')
return redirect(url_for('register'))
@app.route('/login', methods=['GET', 'POST'])
def login():
match request.method:
case 'GET':
if current_user.is_authenticated:
return redirect(url_for('index'))
return render_template('login.j2')
case 'POST':
req_user_id = request.form.get('user_id')
req_password = request.form.get('password')
if req_user_id and req_password:
user = User.query.filter_by(user_id=req_user_id).first()
if user and user.verify_password(req_password):
login_user(user)
return redirect(url_for('index'))
flash('Login failed', category='danger')
return redirect(url_for('login'))
@app.route('/profile', methods=['GET', 'POST'])
@login_required
def profile():
match request.method:
case 'GET':
return render_template('profile.j2')
case 'POST':
req_display_name = request.form.get('display_name')
if not req_display_name:
flash('there is blank field', category='danger')
return redirect(url_for('profile'))
if len(req_display_name) > app.config.get('USER_DISPLAY_NAME_MAX_LENGTH'):
flash('invalid display name', category='danger')
return redirect(url_for('profile'))
try:
updating_user = User.query.get(current_user.id)
updating_user.display_name = req_display_name
db.session.commit()
flash("update your profile successfully", category='success')
return redirect(url_for('profile'))
except Exception as e:
flash('update failed' + str(e), category='danger')
return redirect(url_for('profile'))
@app.route('/logout')
@login_required
def logout():
logout_user()
return redirect(url_for('index'))
@app.route('/note', methods=['POST'])
def note():
req_title = request.form.get('title')
req_content = request.form.get('content')
if not req_title or not req_content:
flash('title or content is blank', category='danger')
return redirect(url_for('index'))
if len(req_title) > app.config.get('NOTE_TITLE_MAX_LENGTH'):
flash(f'too long title (max length: {app.config.get("NOTE_TITLE_MAX_LENGTH")})', category='danger')
return redirect(url_for('index'))
if len(req_content) > app.config.get('NOTE_CONTENT_MAX_LENGTH'):
flash(f'too long content (max length: {app.config.get("NOTE_CONTENT_MAX_LENGTH")})', category='danger')
return redirect(url_for('index'))
new_note = Note(
title=req_title,
content=req_content,
author=current_user
)
db.session.add(new_note)
db.session.commit()
flash('added new note successfully', category='success')
return redirect(url_for('index'))
@app.route('/plzcheckit', methods=['GET'])
@limiter.limit("1 per 15 seconds")
@login_required
def share():
try:
share_key = ''.join([secrets.choice(string.ascii_letters + string.digits) for _ in range(app.config.get('SHARE_ID_LENGTH'))])
redis.rpush('query', urljoin(app.config.get('BASE_URL'), f'/shared/{share_key}'))
redis.setnx(share_key, current_user.id)
flash(f'admin will check your notes shortly, please wait! (waiting={redis.llen("query")}, shareKey={share_key[:16]}...)', category='success')
return redirect(url_for('index'))
except Exception as e:
flash(str(e), category='danger')
return redirect(url_for('index'))
@app.route('/shared/<share_key>')
@login_required
def published_note(share_key):
if not current_user.is_admin:
return 'you are not admin', http.HTTPStatus.UNAUTHORIZED
author_id = redis.get(share_key)
if not author_id:
return 'specified key is not found', http.HTTPStatus.NOT_FOUND
author = User.query.get(int(author_id))
notes = Note.query.filter_by(author_id=int(author_id)).all()
ctx = {
'shared_user_id': author.user_id,
'shared_user_name': author.display_name,
'csp_nonce': b64encode(secrets.token_bytes(20)).decode(),
'notes': [
{
'id': str(n.id),
'title': n.title,
'content': n.content,
'createdAt': n.created_at.isoformat()
} for n in notes
]
}
return render_template('index.j2', **ctx)
if __name__ == '__main__':
app.run(debug=True)
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/Akasec/2024/misc/pyJail/chall.py | ctfs/Akasec/2024/misc/pyJail/chall.py | import sys
from string import printable
print('''
#################################################################
# #
# Welcome to pyJail! #
# #
# You have been jailed for using too many characters. #
# #
# You are only allowed to use 16 characters of printable #
# ascii. #
# #
# If you manage to break free, you will get the flag. #
# #
#################################################################\n''')
code = input('> ')
sys.stdin = None
len = sum(1 for char in code if char in printable)
if len >= 17:
print('Too long!')
exit()
eval(code) | python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/Akasec/2024/crypto/DODOLOUF/chall.py | ctfs/Akasec/2024/crypto/DODOLOUF/chall.py | from os import urandom
from random import getrandbits
from Crypto.Cipher import AES
from Crypto.Util.number import long_to_bytes
from Crypto.Util.Padding import pad
import pickle
import time
def generate_number(bits):
return getrandbits(bits)
class myencryption():
def __init__(self):
self.key_counter = 0
self.encryptions_count = 0
self.still_single = True
self.keys = []
self.username = ""
self.iv = urandom(16)
def generate_key(self):
key = getrandbits(128)
return long_to_bytes(key)
def get_recognizer(self):
self.recognizer = {"id": int(time.time()) * 0xff, "username": self.username, "is_admin": False, "key": self.keys[self.key_counter].hex()}
def encrypt(self):
key = self.generate_key()
self.keys.append(key)
self.encryptions_count += 1
self.get_recognizer()
cipher = AES.new(key, AES.MODE_CBC, iv=self.iv)
return cipher.encrypt(pad(pickle.dumps(self.recognizer), 16))
def decrypt(self, data):
key = self.keys[self.key_counter]
cipher = AES.new(key, AES.MODE_CBC, iv=self.iv)
return pickle.loads(cipher.decrypt(data))
header = "=========================================================================================="
def logs(cipher):
print("Welcome to your inbox !")
print("---> You have 1 message <---")
print(f"---> You have encrypted a text {cipher.encryptions_count} times.")
print(f"---> Unfortunatly you are still single." if cipher.still_single else "You are in a relationship.")
print(f"---> The current key that was used to encrypt is {cipher.keys[cipher.key_counter].hex()}.")
print("Thank you for using our service !")
def main():
cipher = myencryption()
cipher.username = input("What can I call you ? ")
print("IV used during this session: ", cipher.iv.hex())
print(header)
while True:
token = cipher.encrypt()
print("Your new token is : ", token.hex())
print("Menu:\n1. Logs\n2. Get Flag\n3. Exit")
choice = int(input("Enter your choice: "))
if choice == 1:
session_id = bytes.fromhex(input("Would you kindly input your session id: "))
cipher.iv = session_id[:16]
decrypted_token = cipher.decrypt(session_id[16:])
if decrypted_token['is_admin'] == True:
logs(cipher)
else:
print("My apologies, but this is reserved for the admins only.")
elif choice == 2:
print("In order to get the flag, you must prove that you are the admin.")
your_bet = input("What is the key that I'm going to use next ?")
if your_bet == cipher.generate_key().hex():
print("Congratulation ! Here is the flag: AKASEC{nn_hh}")
else:
print("I am sorry, but you are not the admin.")
exit()
elif choice == 3:
exit()
else:
print("Invalid choice. Please try again.")
cipher.key_counter += 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/Akasec/2024/crypto/Twin/chall.py | ctfs/Akasec/2024/crypto/Twin/chall.py | from Crypto.Util.number import getPrime, bytes_to_long
from SECRET import FLAG
e = 5
p = getPrime(256)
q = getPrime(256)
n = p * q
m1 = bytes_to_long(FLAG)
m2 = m1 >> 8
if __name__ == "__main__":
c1, c2 = pow(m1, e, n), pow(m2, e, n)
print("n = {}\nc1 = {}\nc2 = {}".format(n, c1, c2)) | python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/Akasec/2024/crypto/Power_Over_All/chall.py | ctfs/Akasec/2024/crypto/Power_Over_All/chall.py | from Crypto.Util.number import getPrime, bytes_to_long
from random import randint
from SECRET import FLAG
def key_gen():
ps = []
n = randint(2,2**6)
for _ in range(n):
p = getPrime(256)
ps.append(p)
return ps
def encrypt(m, ps):
ps.sort()
for p in ps:
e = 1<<1
m = pow(m, e, p)
return m
if __name__ == "__main__":
ps = key_gen()
c = encrypt(bytes_to_long(FLAG), ps)
print('ps = {}\nc = {}'.format(ps, c)) | python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/Akasec/2024/crypto/Lost/chall.py | ctfs/Akasec/2024/crypto/Lost/chall.py | from random import getrandbits
from Crypto.Util.number import getPrime, bytes_to_long
from SECRET import FLAG
e = 2
p = getPrime(256)
q = getPrime(256)
n = p * q
m = bytes_to_long(FLAG)
cor_m = m - getrandbits(160)
if __name__ == "__main__":
c = pow(m, e, n)
print("n = {}\nc = {}\ncor_m = {}".format(n, c, cor_m))
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/Akasec/2024/crypto/GCL/chall.py | ctfs/Akasec/2024/crypto/GCL/chall.py | from random import getrandbits
from Crypto.Util.number import getPrime
from SECRET import FLAG
BITS = 128
m = getPrime(BITS)
s = getrandbits(BITS - 1)
a = getrandbits(BITS - 1)
b = getrandbits(BITS - 1)
def lcg(s, c):
return c*(a*s + b) % m
if __name__ == "__main__":
c = []
r = s
for i in FLAG:
r = lcg(r, ord(i))
c.append(r)
print("m = {}\nc = {}".format(m, c))
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/SpaceHeroes/2024/crypto/CRYPTIC/encrypt.py | ctfs/SpaceHeroes/2024/crypto/CRYPTIC/encrypt.py | from Crypto.Cipher import AES
import binascii, os
key = b"3153153153153153"
iv = os.urandom(16)
plaintext = open('message.txt', 'rb').read().strip()
cipher = AES.new(key, AES.MODE_CBC, iv)
encrypted_flag = open('message.enc', 'wb')
encrypted_flag.write(binascii.hexlify(cipher.encrypt(plaintext)))
encrypted_flag.close()
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/SpaceHeroes/2024/crypto/Comms_Array/comms_array.py | ctfs/SpaceHeroes/2024/crypto/Comms_Array/comms_array.py | #!/use/bin/env python3
import os, sys, zlib, fcntl
flag = os.getenvb(b'FLAG', b'UNSET')
size = sys.stdin.buffer.read(1)
size = size[0] if size else 0
flags = fcntl.fcntl(sys.stdin, fcntl.F_GETFL)
fcntl.fcntl(sys.stdin, fcntl.F_SETFL, flags | os.O_NONBLOCK)
max_sz = 255 - len(flag)
buf = sys.stdin.buffer.read(min(size, max_sz))
buf = buf if buf else b''
buf = buf.ljust(max_sz, b'\x00') + flag
calc_crc = zlib.crc32(buf[:size])
if calc_crc == 0:
print("yup")
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/SpaceHeroes/2023/pwn/OneByte/shell/pyshell.py | ctfs/SpaceHeroes/2023/pwn/OneByte/shell/pyshell.py | import os
import tempfile
print("One Small Byte For Pwn, One Giant Leap For Flag")
print("Leap >>>")
leap = int(input())
print("Byte >>>")
new_byte = int(input())
with open("chal.bin", "rb") as f:
contents = f.read()
contents = contents[:leap] + bytes([new_byte]) + contents[leap+1:]
with tempfile.NamedTemporaryFile(delete=False) as temp_file:
temp_file.write(contents)
os.system("chmod +x %s" %temp_file.name)
os.system(temp_file.name)
os.remove(temp_file.name) | python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/SpaceHeroes/2023/crypto/CryptographicSpaceRover/nasa_crypto.py | ctfs/SpaceHeroes/2023/crypto/CryptographicSpaceRover/nasa_crypto.py | import psutil
import datetime
import os
import signal
import subprocess
import uuid
import setproctitle
#python3 -m pip install setproctitle
def get_dashes(perc):
dashes = "|" * int((float(perc) / 10 * 4))
empty_dashes = " " * (40 - len(dashes))
return dashes, empty_dashes
def print_top(guess, uuid):
cat_check = 0
if(guess == True):
setproctitle.setproctitle(str(uuid))
setproctitle.setthreadtitle(str(uuid))
print(f"top - {str(datetime.timedelta(seconds=psutil.boot_time()))}")
percs = psutil.cpu_percent(interval=0, percpu=True)
for cpu_num, perc in enumerate(percs):
dashes, empty_dashes = get_dashes(perc)
line = " CPU%-2s [%s%s] %5s%%" % (cpu_num, dashes, empty_dashes, perc)
print(line)
virtual_memory = psutil.virtual_memory()
print(f"MiB Swap :\t{virtual_memory.total / 1024 / 1024:.2f} total\t{virtual_memory.free / 1024 / 1024:.2f} free\t{virtual_memory.used / 1024 / 1024:.2f} used\t{virtual_memory.active / 1024 / 1024:.2f} active")
swap_memory = psutil.swap_memory()
print(f"MiB Swap :\t{swap_memory.total / 1024 / 1024:.2f} total\t{swap_memory.free / 1024 / 1024:.2f} free\t{swap_memory.used / 1024 / 1024:.2f} used")
listOfProcessNames = []
for proc in psutil.process_iter():
pInfoDict = proc.as_dict(attrs=['pid', 'username', 'cpu_percent', 'memory_percent', 'status', 'name']) # Get process detail as dictionary
listOfProcessNames.append(pInfoDict) # Add to list
print(f'{"PID":>6}{"USER":>10}{"%CPU":>6}{"%MEM":>6}{"STATUS":>15}{"NAME":>45}')
for elem in listOfProcessNames:
print(f'{elem["pid"]:>6}{elem["username"]:>10}{elem["cpu_percent"]:>6}{elem["memory_percent"]:>6.2f}{elem["status"]:>15}{elem["name"]:>45}')
if (guess == True):
setproctitle.setproctitle("python3")
setproctitle.setthreadtitle("python3")
def logo(uuid):
ascii_art = """
____________________________________________________
/ \\
| _____________________________________________ |
| | | |
| | Welcome to the NASA Lunar Rover. | |
| | | |
| | Session UUID: | |
| | {0} | |
| | | |
| | This program should help us track CPU | |
| | usage but it seems to spawn extra | |
| | processes when we give it certain | |
| | characters. | |
| | | |
| | Can you help us narrow down what | |
| | characters to avoid at each index? | |
| | | |
| | Enter your characters below. | |
| | Thanks, The Space Heroes | |
| |_____________________________________________| |
| |
\_____________________________________________________/
\_______________________________________/
""".format(uuid)
print(ascii_art)
def main():
session_uuid = uuid.uuid4()
flag = open('flag.txt', 'r').readline().strip('\n').lower()
logo(session_uuid)
print("Please enter characters:: ")
user_guess = input().lower().strip("\n")
for i in range(0, len(flag)):
if i+1 > len(user_guess):
print_top(guess=None, uuid=session_uuid)
exit(-1)
elif (user_guess[i] != flag[i]):
print_top(guess=False, uuid=session_uuid)
else:
print_top(guess=True,uuid=session_uuid)
if user_guess == flag:
print(f"Thanks; we'll avoid these characters: {flag}")
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/SpaceHeroes/2023/crypto/Ive-got-the-same-combination-on-my-luggage/luggage_combination.py | ctfs/SpaceHeroes/2023/crypto/Ive-got-the-same-combination-on-my-luggage/luggage_combination.py | from pwn import *
plaintext = b'****************************************'
key1 = b'****************************************'
key2 = b'****************************************'
def shield_combination(p, k1, k2):
A = xor(p, k1, k2)
B = xor(p, k1)
C = xor(p, k2)
return A + B + C
print(shield_combination(plaintext, key1, key2).hex())
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/SpaceHeroes/2023/crypto/DSAlien/DSAlien.py | ctfs/SpaceHeroes/2023/crypto/DSAlien/DSAlien.py | #!/usr/bin/python3
import sys
import random, time
from Crypto.PublicKey import DSA
from Crypto.Hash import SHA256
from Crypto.Util.number import inverse
MASTER_KEY = DSA.generate(1024)
USER_KEY = None
CHALL = None
LAST_SIGNED_MSG = None
def get_opts():
opt = 0
while opt < 1 or opt > 4:
print("1) Generate DSA Key")
print("2) Set DSA Key")
print("3) Sign Message")
print("4) Send Message")
print("Enter an option: ", end="")
opt = int(input())
print("\n")
return opt
def gen_user_key():
global USER_KEY
USER_KEY = DSA.generate(1024)
print("---YOUR KEY PARAMETERS---")
print(f"y = {USER_KEY.y}")
print(f"g = {USER_KEY.g}")
print(f"p = {USER_KEY.p}")
print(f"q = {USER_KEY.q}")
print(f"x = {USER_KEY.x}\n\n")
def set_user_key():
global USER_KEY
print("---ENTER KEY PARAMETERS---")
print("y = ", end="")
y = int(input())
print("g = ", end="")
g = int(input())
print("p = ", end="")
p = int(input())
print("q = ", end="")
q = int(input())
print("x = ", end="")
x = int(input())
print("\n")
try:
USER_KEY = DSA.construct((y,g,p,q,x))
except:
print("---INVALID DSA KEY---\n\n")
def hash_msg(msg):
msg_bytes = bytes(msg, "ascii")
h = SHA256.new(msg_bytes).digest()
return int.from_bytes(h, "big")
def sign(msg, key, sender):
global LAST_SIGNED_MSG
h = hash_msg(msg)
k = 0
if sender == "YOU":
while k < 2 or k >= key.q:
try:
print("---ENTER A MAX K FROM 3 TO Q---")
max = int(input())
assert(max > 2 and max <= key.q)
print("\n")
k = random.randrange(0, max)
except:
k = 0
print("---MAX K MUST BE FROM 3 TO Q---\n")
else:
k = random.randrange(2, key.q)
kinv = inverse(k, key.q)
r = pow(key.g, k, key.p) % key.q
s = kinv * (h + r * key.x) % key.q
if sender == "YOU":
print("---K GENERATED FOR SIGNATURE---")
print(f"{k}\n")
print("---YOUR SIGNED MESSAGE---")
print(f"MSG: {msg}")
print(f"R: {r}")
print(f"S: {s}\n\n")
LAST_SIGNED_MSG = (msg,r,s)
return (r, s)
def verify(msg, r, s, key):
h = hash_msg(msg)
w = inverse(s, key.q)
u1 = (h * w) % key.q
u2 = (r * w) % key.q
u1 = pow(key.g, u1, key.p)
u2 = pow(key.y, u2, key.p)
v = (u1 * u2) % key.p % key.q
if r == v:
return True
else:
return False
def send_message(msg, r, s, key, sender):
global MASTER_KEY
print(f"########################### MESSAGE FROM {sender} ###########################")
print(f"MSG: {msg}")
print(f"R: {r}")
print(f"S: {s}")
print("########################################################################\n\n")
if sender == "YOU":
recv_message(msg, r, s)
def recv_message(msg, r, s):
global USER_KEY, MASTER_KEY
for i in range(3):
print("\r",end="")
print("."*(i+1),end="")
sys.stdout.flush()
time.sleep(.75)
print("\n\n")
if verify(msg, r, s, MASTER_KEY):
if msg == "COMMAND: TAKE CONTROL":
msg = "Oh... that's quite clever of you..."
r, s = sign(msg, MASTER_KEY, "ALI")
send_message(msg, r, s, MASTER_KEY, "ALI")
print("---WELCOME KEYMASTER---")
flag_file = open("flag.txt", "r")
flag = flag_file.read()
print(f"{flag}\n\n")
sys.exit()
else:
print("---INVALID COMMAND---\n\n")
elif verify(msg, r, s, USER_KEY):
if msg == "COMMAND: TAKE CONTROL":
msg = "HAH! Nice try, foolish human."
r, s = sign(msg, MASTER_KEY, "ALI")
send_message(msg, r, s, MASTER_KEY, "ALI")
else:
msg = "I find your conversation boring and disinteresting, simple human."
r, s = sign(msg, MASTER_KEY, "ALI")
send_message(msg, r, s, MASTER_KEY, "ALI")
return
msg = "Human, I cannot even verify that message was from you."
r, s = sign(msg, MASTER_KEY, "ALI")
send_message(msg, r, s, MASTER_KEY, "ALI")
# ASCII art from https://www.asciiart.eu/space/aliens
print(" _____")
print(" ,-\" \"-.")
print(" / o o \\")
print(" / \ / \\")
print(" / )-\"-( \\")
print(" / ( 6 6 ) \\")
print(" / \ \" / \\")
print(" / )=( \\")
print(" / o .--\"-\"--. o \\")
print(" / I / - - \ I \\")
print(" .--( (_}y/\ /\y{_) )--.")
print("( \".___l\/__\_____/__\/l___,\" )")
print(" \ /")
print(" \"-._ o O o O o O o _,-\"")
print(" `--Y--.___________.--Y--'")
print(" |==.___________.==|")
print(" `==.___________.=='\n")
print("Greetings Earthling, let us engage in telecommunication between our ships.")
print("To ensure validity, here are my parameters for verification with DSA.\n")
print(f"y = {MASTER_KEY.y}")
print(f"g = {MASTER_KEY.g}")
print(f"p = {MASTER_KEY.p}")
print(f"q = {MASTER_KEY.q}\n")
print("I have built a system for us to communicate over. Do not fret your little mind over it, it is quite simple\nto use, it even allows you to generate your own K.")
print("I ask that you do not send any commands to my ship, it is not like it would believe YOU were its owner.\n\n")
for request in range(700):
match get_opts():
case 1:
gen_user_key()
case 2:
set_user_key()
case 3:
if type(USER_KEY) != DSA.DsaKey:
print("---ERROR: KEY IS NOT SET---\n\n")
else:
print("---ENTER YOUR MESSAGE---")
msg = input()
print("\n")
sign(msg, USER_KEY, "YOU")
case 4:
if type(USER_KEY) != DSA.DsaKey:
print("---ERROR: KEY IS NOT SET---\n\n")
elif LAST_SIGNED_MSG == None:
print("---ERROR: NO MESSAGES HAVE BEEN SIGNED---\n\n")
else:
send_message(LAST_SIGNED_MSG[0], LAST_SIGNED_MSG[1], LAST_SIGNED_MSG[2], USER_KEY, "YOU")
msg = "You have thoroughly bored me human, see you never."
r,s = sign_message(msg, MASTER_KEY, "ALI")
send_message(msg, r, s, MASTER_KEY, "ALI")
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/SpaceHeroes/2022/rev/CapeKennedy/moon.py | ctfs/SpaceHeroes/2022/rev/CapeKennedy/moon.py | import sys
def main():
if len(sys.argv) != 2:
print("Invalid args")
return
password = sys.argv[1]
builder = 0
for c in password:
builder += ord(c)
if builder == 713 and len(password) == 8 and (ord(password[2]) == ord(password[5])):
if (ord(password[3]) == ord(password[4])) and ((ord(password[6])) == ord(password[7])):
print("correct")
else:
print("incorrect")
else:
print("incorrect")
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/FooBarCTF/2021/crypto/Lost-N/enc.py | ctfs/FooBarCTF/2021/crypto/Lost-N/enc.py | from Crypto.Util.number import getPrime, bytes_to_long, inverse
p = getPrime(512)
q = getPrime(512)
n = p * q
e = 65537
plain = open('plaintext.txt','r').read().lower()
ct = []
f = open('encrypted','w')
for i in plain:
ct.append(pow(ord(i),e,n))
f.write('ct = ' + str(ct) + '\n')
#f.write('n = ' + str(n) + '\n') | python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/FooBarCTF/2021/crypto/Back-to-the-future/server.py | ctfs/FooBarCTF/2021/crypto/Back-to-the-future/server.py | #!/usr/bin/env python3
import arrow
import json
import random
import sys
keys = {
"a": 15498798452335698516189763255,
"b": 4
}
with open('flag') as f:
flag = f.read()
with open('/dev/urandom', 'rb') as f:
rand = f.read(8)
rand_int = int(rand.hex(), 16)
random.seed(rand_int)
offset = random.randint(-1623476442, 1623476442)
while True:
sys.stdout.write('''Server's open.. for now
Would you like to get ->
1. current time
2. access to sanctum sanctorum
3. goodbye
:''')
sys.stdout.flush()
response = input('')
if response == '1':
time = int(arrow.utcnow().timestamp()) - offset
enc_time = pow(time, keys['b'], keys['a'])
sys.stdout.write(
'This NTP server has been taken over by time-travellers!!!\n')
sys.stdout.write('Time mixed with sweet RSA!\n')
sys.stdout.write(str(enc_time))
sys.stdout.write('\n')
sys.stdout.flush()
elif response == '2':
time = int(arrow.utcnow().timestamp()) - offset
random.seed(time)
guessing_int = random.randint(0, 99999999999)
sys.stdout.write('''Only Dr.Strange with time-stone can access this area! To prove your worth guess the passcode by looking into the future!\n''')
sys.stdout.flush()
response = input('=> ')
if response == str(guessing_int):
sys.stdout.write('''Wow, guess you are a wizard, Harry XD\n''')
sys.stdout.write(flag)
sys.stdout.write('\n')
break
else:
sys.stdout.write('''Imposter!''')
sys.stdout.write('\n')
break
else:
print('Farewell traveller...')
break
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/FooBarCTF/2025/rev/Bitmap_Mystery/compressed.py | ctfs/FooBarCTF/2025/rev/Bitmap_Mystery/compressed.py | import struct
def compress_bmp(input_file, output_file):
with open(input_file, "rb") as f:
header = f.read(54) # BMP header (first 54 bytes)
pixel_data = f.read()
compressed_data = bytearray()
prev_byte = None
count = 0
for byte in pixel_data:
transformed_byte = byte ^ 0xAA # XOR with 0xAA for obfuscation
if transformed_byte == prev_byte and count < 255:
count += 1
else:
if prev_byte is not None:
compressed_data.append(prev_byte)
compressed_data.append(count)
prev_byte = transformed_byte
count = 1
# Append the last byte
if prev_byte is not None:
compressed_data.append(prev_byte)
compressed_data.append(count)
with open(output_file, "wb") as f:
f.write(header) # Write BMP header
f.write(compressed_data) # Write compressed pixel data
print(f"Compression complete. Original size: {len(pixel_data)} bytes, Compressed size: {len(compressed_data)} bytes")
if __name__ == "__main__":
compress_bmp("flag.bmp", "compressed_data")
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/FooBarCTF/2022/crypto/TrailingBits/chall.py | ctfs/FooBarCTF/2022/crypto/TrailingBits/chall.py |
from Crypto.Util.number import getPrime, bytes_to_long, GCD
from random import randint
flag = bytes_to_long(b"#REDACTED")
p = getPrime(1024)
q = getPrime(1024)
N= p*q
e = 0x10001
x = 20525505347673424633540552541653983694845618896895730522108032420068957585904662258035635517965886817710455542800215902662848701181206871835128952191014493697284969437314225749429743933083828160659364661388058087193251081260335982254080118777967019114025487327203682649658969427745709426290533798413074002576442578240125282339739757429305467392467056855474421076815986701014649799010560681947651299817835748393824150668018627770878313651343270246832490595870418506765783183714239947943610319258616554427446129948999323762841507343205007649094350172991183628556644081749900113654945488511477133416252720845890086594005
c = pow(flag, e , N)
enc_pq = []
bin_p = bin(p)[2:]
bin_q = bin(q)[2:]
for i in range(512):
while True:
r = randint(1, N)
if GCD(r, N) == 1:
bin_r = bin(r)[2:]
p_bit = (pow(x, int(bin_r + bin_p[i], 2), N) * r ** 2) % N
enc_pq.append(p_bit)
break
for i in range(512):
while True:
r = randint(1, N)
if GCD(r, N) == 1:
bin_r = bin(r)[2:]
q_bit = (pow(x, int(bin_r + bin_q[512+i], 2), N) * r ** 2) % N
enc_pq.append(q_bit)
break
f = open("Output.txt", "w")
f.write(f"{N = }\n")
f.write(f"{e = }\n")
f.write(f"{c = }\n")
f.write(f"{x = }\n")
f.write(f"{enc_pq = }\n")
f.close() | python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/FooBarCTF/2022/crypto/new-intern/server.py | ctfs/FooBarCTF/2022/crypto/new-intern/server.py | #!/usr/bin/env python3
from Crypto.Util.number import *
from random import getrandbits
flag = b'***********************REDACTED***********************'
FLAG = bytes_to_long(flag)
p = getStrongPrime(512)
q = getStrongPrime(512)
N = p * q
e = 17
menu = """
[1].CURR STATE
[2].ENCRYPT FLAG
[3].EXIT
"""
class PRNG(object):
def __init__(self, seed1,seed2):
self.seed1 = seed1
self.seed2 = seed2
@staticmethod
def rotl(x, k):
return ((x << k) & 0xffffffffffffffff) | (x >> 64 - k)
def next(self):
s0 = self.seed1
s1 = self.seed2
result = (s0 + s1) & 0xffffffffffffffff
s1 ^= s0
self.seed1 = self.rotl(s0, 55) ^ s1 ^ ((s1 << 14) & 0xffffffffffffffff)
self.seed2 = self.rotl(s1, 36)
return result
def main():
a = getrandbits(64)
b = getrandbits(64)
g = PRNG(a,b)
print("N : {}".format(N))
print("e : {}".format(e))
while True:
print(menu)
choice = input("$ ").rstrip().lstrip()
if not choice in ["1","2","3"]:
print("HIGH AF")
exit()
if choice == "1":
print("state for you: {}".format(g.next()))
elif choice == "2":
X = g.next()
ct = pow(FLAG + X, e, N)
print("ENC(flag+next_num): {}".format(ct))
elif choice == "3":
exit()
if __name__ == "__main__":
main()
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/FooBarCTF/2022/crypto/RandomFandom/enc.py | ctfs/FooBarCTF/2022/crypto/RandomFandom/enc.py | #!/usr/bin/env python3
import random
import math
secret = #REDACTED
flag = #REDACTED
def keygen(n):
privKey = [0]*n
privKey[0] = #REDACTED
for i in range(1, n):
total = sum(privKey)
privKey[i] = random.randint(total*2 ,total*3)
privKey = tuple(privKey)
total = sum(privKey)
modulo = random.randint(total*2 ,total*3)
while True:
multiplier = random.randint(modulo//4, modulo-1)
if math.gcd(multiplier, modulo):
break
pubKey = [multiplier*privKey[i]%modulo for i in range(n)]
return pubKey
def encryption(enc_state):
global pubKey
pubKey = keygen(n=32)
enc_array = []
for i in state_one:
result = 0
j= bin(i)[2:].zfill(32)
for k,b in zip(j, pubKey):
result+=(int(k)*b)
enc_array.append(result)
return(tuple(enc_array))
random.seed(secret)
state = random.getstate()
enc_flag = 0
state_one = state[1]
random_number = random.randint(1, 2**8)
shuffled_flag = (''.join(random.sample(flag,len(flag))))
for i in shuffled_flag:
enc_flag=(enc_flag*(random_number**ord(i)))+ord(i)
enc_state_one = encryption(state_one)
enc_state = tuple([state[0], enc_state_one, state[2]])
print(enc_flag)
print(enc_state)
print(pubKey)
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/FooBarCTF/2022/crypto/BG/chall.py | ctfs/FooBarCTF/2022/crypto/BG/chall.py | #!/usr/bin/env python3
from Crypto.Util.number import *
import math
flag = b'***************REDACTED******************'
def keygen(bits):
while True:
p,q = getPrime(bits),getPrime(bits)
if (p % 4 == 3) and (q % 4 == 3 ) and (p != q):
n = p * q
break
return n
def keygen2():
X = [2]
x = 2
for i in range(len((C))):
x = 2 * x + 1
X.append(x)
return X
def encrypt1(m,h,n):
while len(m)%h!=0:
m = '0'+ m
l = len(m) // h
r = 89657896589
x=pow(r,2,n)
C = ''
for i in range(l):
x = pow(x,2,n)
p_i = (bin(x)[2:])[-h:]
c_i = int(p_i,2)^int(m[i*h:(i+1)*h],2)
cx = bin(c_i)[2:].zfill(h)
C+=cx
return C
def encrypt2(C, M):
S = 0
for x, m in zip(C, M):
S += int(x) * m
return S
n = keygen(512)
h = int(math.log(int(math.log(n,2)),2))
m = ''.join(bin(ord(i))[2:].zfill(8) for i in str(flag))
C = encrypt1(m,h,n)
X = keygen2()
S = encrypt2(C,X)
print("n = {}".format(n))
print("S = {}".format(S))
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/FooBarCTF/2022/crypto/babyRSA/enc.py | ctfs/FooBarCTF/2022/crypto/babyRSA/enc.py | from Crypto.Util.number import *
flag = b"GLUG{**********REDACTED***************}"
p,q = getPrime(1024),getPrime(1024)
N = p * p * q
e = 0x10001
phi = p * (p-1) * (q-1)
d = inverse(e, phi)
m = bytes_to_long(flag)
c = pow(m, e, N)
x = (p * q) % 2**1337
print("N = {}".format(N))
print("e = {}".format(e))
print("c = {}".format(c))
print("x = {}".format(x))
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/FooBarCTF/2022/web/FileClub/app.py | ctfs/FooBarCTF/2022/web/FileClub/app.py | #!/usr/bin/python3
from asyncio import subprocess
from flask import Flask, Response, redirect, request, render_template
from werkzeug.exceptions import RequestEntityTooLarge
from string import ascii_lowercase, digits
from random import choice
import os, tarfile, wave
from PIL import Image
import yaml
import zipfile
app = Flask(__name__)
UPLOAD_FOLDER = "./uploads/"
EXTRACT_FOLDER = "./extracted/"
charset = digits + ascii_lowercase
random_string = lambda: "".join(choice(charset) for _ in range(10))
def valid_png(file):
try:
img = Image.open(file)
if(img.format == 'PNG'):
pass
return True
except:
return False
def valid_wave(file):
try :
with wave.open(file):
pass
return True
except:
return False
def valid_pdf(file):
return_code = os.system(f"pdfinfo {file} >/dev/null 2>&1")
return return_code == 0
def valid_zip(file):
try :
with zipfile.ZipFile(file):
return True
except:
return False
def valid_tar(file):
try :
with tarfile.open(file):
pass
return True
except:
return False
def check(file):
if valid_tar(file) and valid_wave(file) and valid_pdf(file) and not valid_png(file):
try:
with tarfile.open(file) as tar:
tar.extractall(EXTRACT_FOLDER)
except Exception as e:
print(e)
return False
print("Files extracted")
try:
with open('{}test.yaml'.format(EXTRACT_FOLDER),'r') as stream:
output = yaml.load(stream,Loader=yaml.FullLoader)
except Exception as e:
print(e)
os.system(f'rm -rf {EXTRACT_FOLDER}/*')
return False
os.system(f'rm -rf {EXTRACT_FOLDER}/*')
isvalid = True
else:
isvalid = False
os.system(f"rm {file}")
return isvalid
@app.route("/", methods=["GET"])
def root():
return render_template("index.html")
@app.route('/upload', methods=['GET', 'POST'])
def upload_file():
if request.method == "POST":
f = request.files.get('upload-file')
if not f:
return render_template("nofile.html"), 400
file_location = os.path.join(UPLOAD_FOLDER, random_string())
f.save(file_location)
if check(file_location):
return render_template("success.html")
else:
return render_template("fail.html")
else:
return redirect("/")
@app.errorhandler(404)
def not_found(e):
return render_template('404.html'), 404 | python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/VULNCON/2021/crypto/baby_crypto_1/baby_crypto_1.py | ctfs/VULNCON/2021/crypto/baby_crypto_1/baby_crypto_1.py | from Crypto.PublicKey import RSA
from labmath import nextprime
from Crypto.Util.number import bytes_to_long
flag = bytes_to_long(b"REDACTED")
key = RSA.generate(2048)
p, q = key.p, key.q
n1 = p * q
n2 = nextprime(p + 0x1337) * nextprime(q + 0x69420)
e = 0x10001
print(n1)
print(n2)
# for alice
c1 = pow(flag, e, n1)
print(c1)
# for bob
c2 = pow(flag, e, n2)
print(c2)
"""
22243767031601205606016724543394930965574710684607939977002923653467515703910708073153303837197514453047530981163061414432553406922379064426711180712199214148695524074852292709843679483946765826870486767413648398940133262658583561865532248340848798197069347180941760889923311080443408332311280000720444030202313987744329723440602348873266088225457793745023406168229198052883533457979075930671593721756049119623439980058663481487875407803740428753364349578448179538422057210061297317455298747898736294488215527556155413660495462710790183196097603497852931743336515415984055572082317119324317677742645961245335632851491
22243767031601205606016724543394930965574710684607939977002923653467515703910708073153303837197514453047530981163061414432553406922379064426711180712199214148695524074852292709843679483946765826870486767413648398940133262658583561865532248340848798197069347180941760889923311080443408332311280000720444088631755201518863682427020328661800944870199966918281743538003953548886667168717595850683487724572933861527424312817284865432246601050829245671332285117732021604161087765520706258045960134431616629369489298042899004980834927326168764114693314977815338647689995504140027507603785895207956532803125995629781105125051
21015887075421597796881082947987101126069551861907298153305115458195043650321017152078923571591176106457664970164210111446945546910454719331155256239779901883809540555018856905735566026769497037893656895619950331023776596397084788049341711529298269351942650618644778314295214814482899243754667427202019028761299527182084519600480383057195877660162355968191754720194183870387237310465727792481211316959702803683072186328458267125586299697285649619652001364385177367764033046337354326442405138998227801884286911634858441035727869447332895575415317302333865925984575835983462914397463753678529746998277861755912512542253
18033234810107245295695114288774462048246048944427175259056227859740672397821846313589796303990554738083820877989535464331501271594079843486103405062004322473117600744907503540878867935169489970847351064017904893197458137188082397861749636500835816496558787142262141012162812477082366819283819468962564030638030928952176361809500503798659677504678332595023403916483873209678034982645507279773866148541604275432492431487352311749602260256947218870522211767983081790530171144505947660791630104016196546975050608195933787622438390086522065812781475998593315648139280245968689513117433828903087114386318416667811613662962
"""
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/VULNCON/2021/crypto/baby_crypto_2/baby_crypto_2.py | ctfs/VULNCON/2021/crypto/baby_crypto_2/baby_crypto_2.py | from hashlib import sha1
from os import urandom
from Crypto.Util.number import bytes_to_long, getPrime
from collections import namedtuple
from textwrap import dedent
DIFFICULTY = 20
PubKey = namedtuple("PubKey", "p q g")
privkey = bytes_to_long(b"REDACTED")
class LCG:
def __init__(self, m: int, a: int, b: int) -> None:
self.m = m
self.a = a
self.b = b
self.s = bytes_to_long(urandom(DIFFICULTY)) | 1
while self.a >= self.m:
self.a = bytes_to_long(urandom(DIFFICULTY)) | 1
while self.b >= self.m:
self.b = bytes_to_long(urandom(DIFFICULTY)) | 1
def seed(self) -> None:
self.s = bytes_to_long(urandom(DIFFICULTY)) | 1
def getRandom(self) -> int:
self.s = (self.a * self.s + self.b) % self.m
return self.s
def help(self) -> None:
print(
dedent(f"""
LCG HELP ->
This generates random numebrs like so -
{self.getRandom()}
{self.getRandom()}
{self.getRandom()}
{self.getRandom()}
See, completely random :)
"""))
self.seed()
def sign(pubkey: PubKey, x: int, h: int, k: int):
p, q, g = pubkey
r = pow(g, k, p) % q
s = (pow(k, -1, q) * (h + x * r)) % q
return r, s
def printSignatures(lcg: LCG, pub: PubKey, priv: int) -> None:
msgs = [b"Hello", b"there"]
hashes = [bytes_to_long(sha1(m).digest()) for m in msgs]
nonces = [lcg.getRandom() for _ in hashes]
signs = [sign(pub, priv, h, k) for h, k in zip(hashes, nonces)]
print("\n".join(f"sign_{i} = {sign}" for i, sign in enumerate(signs)))
m = getPrime(DIFFICULTY * 8)
a = bytes_to_long(urandom(DIFFICULTY)) | 1
b = bytes_to_long(urandom(DIFFICULTY)) | 1
pubkey = PubKey(
7723227163652206196072315877851665970492409383498621787915763836703165497532056144920977718337221463593649391334584803149362349291402576071382757173855489,
1419435951773960878522380192164715964887544050251,
3177589275498063000838438765591095514446952503023627047492796256311729225229378235819032575431223841654220960177156277529073194075117755794549781574237012
)
# sanity check
if privkey > pubkey.q:
print("WTF. Contact admin")
exit()
lcg = LCG(m, a, b)
lcg.help()
print("BTW, I made some spicy signatures with that LCG ->")
printSignatures(lcg, pubkey, privkey)
print("Please use them carefully")
"""
LCG HELP ->
This generates random numebrs like so -
571950745479432267005464851096356774896792314093
442389987284185335289253341364665422032816391623
674689295937843496428836795727103849648022363056
534115548763794721117336167251846846861246743872
See, completely random :)
BTW, I made some spicy signatures with that LCG ->
sign_0 = (1068578444686700850472665790275239904755324934637, 773641167123158554564050069711067502164705010631)
sign_1 = (1261138445303763427942699370178218831470626347614, 466653063468278381121557045661962018351821473529)
Please use them carefully
"""
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/VULNCON/2021/crypto/BitSafe/output.py | ctfs/VULNCON/2021/crypto/BitSafe/output.py | pub = [413764712158568989289685738971911506209701839654762492215204673201608947054527907036545764344989577366897032382017470420253743928452619177164360397739570777853675702170092177189794976123870224754119486580284122284965448573737835275179404351921068621051686322622930047747851825019447703719175949194732695464446522494146364841213164720933897211433090338126, 130471476666210486625717184747699757727535651556218298642195427988651396564790270764447270901811696345427187850250735829297949684726542314864174632272838834989991616693456437020712740663300824419076730310892863258561178308683777171501180529420844968181082770148270642499441227001187883431173809845935813919370798631357736196975665093680975502674584717671, 430823756139282511960792588917749979349695446028232847205656787394002717644269434703841071909689258394145281273763971078607679486145957574463468401631328444837961569643759369692785936478653087557761839216014291466779384179738408256487702021479318377817957495840612629552345462909248961631640885818701119581681435880204737231127781678270127970552146854510, 284944805828895641620497811145148451285749342781267620984188815469173551459225191846980161059622315530688701228711895931289079848913546173010756069959249887753352854474301861540861146469676533174668381087545087613815605476311666250493447658969936846267981786786799618495236376470005306434333736302300616043687664126307762547959222819850646849627304920245, 284872708767662682186946588263225278468505175727367782335118451444768498133247384381726288150734055957689865367606710383598212708927961453212342556207858017643383092880154247792879325902181065716756259996377861034481608317566083752356096955879949814181064801512521597039535016544423791870427053303769467828374347108508356683523110131101167305853567968328, 129141122442770720727229185150645054701010720231575454701229807683211686307817094150008557383068923906141298900395027040798085916722251696283364860311516276408308577947846980773940075342428407215144730022001413293776933576647202857791133085957346755136450295316409959110073519989086489961200649313549266995204277183179033457147670843896897841228730936616, 353707086298384093658634180583273739866666972497284089795445807018966938965367986352896857340751146572811558730050202176688945587530919183971656684374766363191744316362361743685127409225747197151739388497166156425853203849993201205919690885949117786562047009423476997323463545446027688664096237949085511189456642010192290018836515126005521924784580036612, 94309209243195425510986018792922068198716363745953552911109344122284769240154987629553929485314521979162394712766901168476229027466075330761236110510939487489858075975940489075016317171689599998435975907340301796033552383491943480833817293368990761519178184217859005578384378179147951276219857561588043987624656420427998054750740450262334677066072432076, 247971077522388606493305419342885688305540984298509802769265588117099069971768710327993093074692605407191980912270484820129978693282166865762586083826061542833563111359256569942825659523927377708227743524106730339602800544382423665425609535403158329380413522647603061635159328453620603506684281906594561569823709527523925307085306917562694598006542520758, 522160366500770737451489296760111217241345870612890640811413704663128251672219781084329624884533449292076081744132289963560876869737564955337255329652238283988550703174375300303478549100360303772300206987453470684437899991418509242325254265940878131428824792810332439947582839432174707598993537712043605889147191338349413359481737531641257603896844362, 707563675450197557555238451748669686524814898390295784282476092507615876488984602235639217478679137761816202348417556578099867884681197725243232235303101028260821506102905631333826334576639887874974654081454495198036462139878871681485901468124937273984383668816745653401947116328685677481875187352492505184241405504821798541993262207290870910359873440880, 488168922287802103598266163817380864965805677439229687874282411911051161840628796830365380644864152118625878587864150353984585914982297833542295647975692317241758699421138725883336229861847556293563552996041323926984113678945640139585959244910263107585382551920411639623469468480612136075929993691825754125168994629936482891146797674745669968207547444430, 557297720783409873526732888983977346929838709189796171864118713163812080337142414685991445262091962948200647349719552860080234164330905793718046268370961625430925071478329320353326869148837612082555457377028131900745532894658160561606221844116003042130896135532355059483836570922346993446120687898104213697493090690188196298170719214162762090100074311016, 110562959244612826916780860328716759757486320915567756548607604336284584008507933476503722403828222095093305227213043739500761050239375586399994305893301214702311161688400708325624130160298621951984637290911601628257924218356378411390588966413683284373032951862923273520742412883727400057984890079625479553037480972394294740448828274790680223402088234654, 669973548955775220830368978911192110723238385933992674388409113288027018578256331510175405650105026167365543208402368872300346955252827816967251679862547083415528815178809185841984657677896917131609684935442697280341667709470729038561869454102939496498999764714437107392759085270529951231960748005970572989583430099187587585530980204732139895298723422313, 397073447830978233106519204997903336891027101892863235441454534670860152657576644105141359985448020270014640008803520976688382228152559831001562888974557386158242234243183465715986544695161035213373265101341916825279644737378239105460685219567424689406936942679412302183281141288662037110732878671122204248288054362963723635051615341186396095540931034184, 185737048468983251073720179768471764141884997035718616651546833123975506602228462602145845853643940055567763558648944897676568622348203276017241042677213224814463877216532670575037570040264666704097587712658676672199349956856840261379838653853633400403849191367742323301217855278735672845645508257326926470221405964388473189214936730831312490445668013380, 208005723590822048599578614402321388351250046400096243943643400858144991961322600462623110449415074683489126163063873189639152048198294598665355875332809157024891056160946040574403865586810086271484862658667562652604739727221758625691745112323222655443121882134231643737898178717151751087855351610503047585115015117784040496918100654383583200102334194338, 694914700188800687856411257207713252186258912946557712949884515664876340849205200210144338363277603688366739064165089984674928952531086988876522219028052804165443232001485361902615693458396636998664963315698981937833184431187337444467535802704553233226375010035016088550833293212292777950782320832282285245769698432085432713759302998208804286445845578038, 193401588982569430835477029077965170070252412697433520106856312460212825409476752554755589052343701579824242603825214824529889599487792090826481928999943745516382624765121656914224768193231635217244284488742825022623658653935914677609026177829463322682247060892282243180713820580436020490653466839205389048011890393976867829094815160340173131052064857613, 194164690254574022514296090185243865805341870249480177196613500021153602767147344359728838180068662203559547162856445608871809398952322905070447000378383091525648360048732945474442149382927853096329118967665324000348718981306861112068412936792851514796786759097233251797504725314186719441694523870899009061021313600779876161802651662952322246898618963266, 376302739527328412968941633448781414069665326176728627655442927354331714304526928959267797421696818253425271311083889886074816175980916477200129921067928785740568622831445511807515006134073446486537369031143074925808784020967348408478098962184105036345338347166890758943538385756456055211829983038575735231374080348694385779422684682171732174868252924927, 230569356951830468872719835165887730347625912062702004411740978759215272850734594745038343014942325476396896980797940698408962930585373260987404493636214408962818639909253578558699150086543152459778238289143015353616466380424640662219745042786118174715523449967989535724807504080344060269769050773837242562203196544008174034276720407393928807074332824812, 428516771787039208447849750813028211096277989778451862045234973136495509903891703737677539858486117724690857779534614789286174348715085316298535479877009524606720544226967343089744451759931482214066726875600142975740627497239988577615687698786840639963959579275690354009081366109170355953001273765649266597434606227710032489744141078392888895725745751540, 43866548930391137204642896260042098647336983459430907117460562035916007536297900587897116898727366498729734509985314186686893144159664510518223378779187087520596609866585692487472882973267760481004416343135692236742847373353622529255419612000859153339821181343899193047200438796183590750006433336931048006293194371167277474904088451227485989698768103803, 319459754038092095512197012417992915117889330822690909429956322362255944752957338078868925540246463328459887749061933142584163492414224885578529219000719888156833206073623066920875634340336294901770071073797979061106819869381183004650830840596012741831125029210750748907082375059560086406542101102500400972461562414883000119329494070652252760438096108036, 598340996804248902269515646376417007599494880087845658425687767757150356479062062682309866449146246398420615617170306804173811824119718862337193636789682698438374627610254149930547436125147556324596872425298405618729863284041527819186001446392866463658215977852799999323050717604213404941356349713856545315051257788300239589810829396377661376572576046584, 411508526541324022108366663363742298776543426628995702134019600919674876177659735111195734872428918860543796868190993225072413979551673171673062625702310579533992550987757895941763871863652575384048086684589560930390964173457538999653386568589843318611928243564516360485549681272274606559941874251288349236607810873027659306743754680843808983697100264570, 546347497428823060868158284723053080712049299836096539390115338667384166947381208790174003638702965943293561990771120506404936309327596613571372998687828989014532797275914700748443077865432718971814307836019736332994069036631527058501749298022472568403196271136172787638070995406523180064810129126408835132723673717704677083037841957093427738747716953486, 351929088398900848620401335064421413585168041319162527049787839828553336116089442630933896917942447430029851408350369999206915232664346991278143029039834893432112506473359422352328289227819268044108950534463427180176336656610155354702104363141163717101766937947204968212690218197724265022135288349503250950398036620971649809068428686426190661988412000521, 276470792412300510119850883283751543760465125375264368413650076810771963266197349808007015653975824646836068894351146253150568922254197638069648308645026334166028661682418391134837474644026600619611869787149693567850843329873636766565234846316083646872579785742454294423270459855919784139944801076958091421236063578679808888623137993003199169774512183393, 96156322450756117134398357931892191791957243138909097936308782172449789008531460149245388634875624087342241232448451949556429106549528699968040787620728267687620932089985227883914644166845950019066385669053989464934779970786663285746933049142451746846097800362010334447803046580035295931760921116874285409543742131757588001194903567256768025669222866728, 665654730419649995997283764102399889840615859256974395259504870759809326143222701499876912427404447006033309414167998506214831399245718594962278007338264576673138994022205301620528708301085849507217128924667119541816496769929233516872699509904852179144794791864768691540029966907851689747045349332645288567067502671373887657046617994534613934892973499501, 53450305269850495732286003268816222653257051795756241903069718000539492165911701179518041507876866026839233132601858172004585023324621894229597750550563116570658880467789640881328154727614796241815716720426372262609059034216736193394916838780319423691936525571280485778557217591682159613825682144658185494311322691454756442358375792720238236522703025441, 436624065452384732553554970343462192308204287363636084582355885531152623107106105025165850878123997600354064731414928211378724133884123236646766291955753114296369520668765222318171373727621995572310822859388473785708142318557476205216572398509137129974467159346150907603010150664621492727610860396731778171649948308226327189654442868392611841119006955807, 112443675400730631445005388221982846122465064102934491334798682063383714335513298852727719918280115058549393426879906364335167257597541165343451366752873070034194728467958005072942106061815234529929560731964126638311348766913246642503630809761341377001469424533779767615956423889899497445158854205237746724540127718950173151571840703870836381929524284549, 270969162414816401551074593989175846255121316155928581591357871857089150953928785397876343389030528435039260316796540526148142202604066537067020598622001842226288046792356200814456191958666304395547742717112888117964983869280852718349781855180708786953184046685600531686804702550082577352181208742423774793845638361370940332031716830071687413294759892380, 325340968743155775843155258517552859596008788946263197369313046106084672032136590926721340656916862552656689917792721335522236895175612782354061641692275773418645614860542215145855659027261545081534122242766063268051354322253895224418371612083428617391068687157249275647570853296172807068906513874975086604584512494927423027515263859573292781344132248878, 645861631321677010326846714344668857401661254330060159274251450216827179854908609492812288387940842891253480692056255117015092111547865476747274033118388461483021728669058345841867822025370047043779063479503157589481022790359146160137865157644091746693657449152658096551309699294494582554921777595564692767155117171943236292994840220728615880152789303617, 148667033803185923476183397359728932318264923052428134305559611317030581108447062450351997704499909789579589461008931509044546206075434037905771617660943784898103778671803819538254631744365168292318976102724725686091138706058308114872475320018014614114549350871435443336779873272512680543554159812542681159848153538354437689992452623297795718248213353774, 716695872607258655605496432898641685466973735690288633086682002164409286829135118090079305565617029274993062431279625741936212947211081596642008961669901881806692881862113500278845674847076674917546003925420087993826018364269032986595625528127343899821690419437826836458504100726953324249497258219407254014667529589169558921008229737012046930301897352764, 374851555526248528803810050295641073248311236839467001877430733786638309389583309741264093473296323760123824458952700804910245961876378158064591790532962003808744875831299089497429150827079813432004377970749403440569573172081809267058146307089080893404526769779073495654519269989090728246381836839070838723836177463481648288756132647157659889574627906594, 549989115009690227756524390404453206621989200583862464483354985867335113416031685627619820730049790229140556039190863708958397313565096186563229355802783863993832190820971891814081527444362881486527806389051281702036258461736075006898714117066821053103680865777804916729469092799296359689806130906556162010139947868340014480287755702012473894427051354670, 121071032279709719141773809211096160816975026970832271715835617966275974058539790657235915017651260648686541585641929114235124477280525246697467741107957344264083531284513301984829285890912212202966129110720477943905521062787935143770948284922428704672009837968487844047642334392366829980918295084322292430650307306732442608612052375340910492968252852474, 394338308618227936350090188994344629637829388719826266639957309499810377467971577362792981457164014775417788703898852958465071206981391213364860932816874950389385028252542238165361047915608020703172016936531486945703865874673821007484401018653248306123601423083985576617774667084867740614269231362279880061527362198052212512808736378973463861883317502555, 601254507951122722266214690865628819685326188577455833181227660271566531880130167509898628837664331742153413295316542119968902544745889312645200167277719083278378210688407801681054094025910332160520350564112681824529678661605536246724527121853448282229554971624271601433865533485395235389254077919898849123284099493689870686408418237360454371283216372594, 652326454418808477249248621109776109023326561288210726057760493520197628670731701469562899196085156547654002771788709036095856101380991734401054380694080518284803697500164612960595656278838738277948896255731248594275077454882127412735158405423372033282334852693092812392387547307977854523518418512980637752498958782137837900717093008490327653941857202602, 641155490514384078348130584937902720472195867811424075201283013821318075465849226265907808363989108996961296707231020353625671430449645216744189431428031487701848144732192075561908967680018141181281826695297731196773345101474288386637548996365196037885636965726760931896320163770177968427315365748543513442182060052139860221403238841889567253867222665401, 673692163830916102290626929616894335226910716304571242556547042767861641133498947715112489530904793847099997496932652839591170290712316761646897267856079471367675315336014241594591188538933751141030892859917202016648936585028548525880860449491647118922946352785284570648616888138999460107629293857965460165798055672789713181342228752384423926923756748577, 544981910977482438877484790569665684712111875526532834404113256732602417899008724902376524328359598841473772714120297171645250431184695633755706209014164498254250448926398244069455122641508267106933430090589489262783019072598702442003276918440671937914222877612153547041725439097143397368584651038663690929895296957512178365250352676997805397357829334241, 601547797662745632183004735244563966902140415599551215838685810702196163154404746231894379726038119591836887691665404678201137221045093559843219633298334878385502152755842681764977745308304729774841834074999937072014569037268645480614814496096494503331313282681082998475972975913246481488862966875500625711768254683619511245600359107207274865408831959309, 90534520698511085239285803388426539510969812086177557391159985320383480091851518154473824462404205965228653946804874728360776770364471095348273332881513481858359279173179733917127952027546701802967748677193494696567095247641714811572568473714107218579414002829449930454550724540702146176908119235393604156513539490738409542934637600805844188187649189408, 352496058904562125210600188633723245757365853736421639076557262097010503563197412137638133887371473919150491135367842135151279915539363590943045127340936146800547612873557953652212422808748501374462816379607028846069436810908877752054074554987693624868758201192739627453614076358385705188703995109059406523649217857261928645074785032272314557939149780169, 134863723810591714472082057459732537726035309520430045723521339012120875163098717730084246833776432753039218648050804491571640735330912953816036373344066733895893739872534194715535967032635668800684750857667823683568049724186140629476462661068205569918105850506018108556477005880196131197563710194296583905830571683361271689686702724635899806343589756226, 266117969537609977697322742145564940542393598921968066533608197899381363304220763555393236191066040931569205904163058113634918851781472619329050887690079728153454004082227379923119334028971882602078350567684702067518235386218955923812106797717214013819863365476376425290072281855613819093610575154151167530018619554387770029366113544083728743331206275091, 334750340992123799732117132403790867303094550708754944812804087481647676905804063930130490424001631372773493164014594948189568870009563105951248179951414388194470697451360992874266157614883985450629488115031082201385917103471749938241458515222911989351789116694307972741223780450636054694426517306376252251773524379396236143035033716935212505174856276453, 264840700777643948946854577569359261401294428946524883967166137037179903684501040802186274223917802560150105635027010975321130316995828527281486518513408355589082855315631430721552574322424137457212377667576757153999864137500804181797635814270584234533154644242325198855796920101951097380699688989197656342486517596680572405928891310357064256743000200599, 358579726234479614418082881957001406025848420477104121554536903569067663112342173460241210937727279942734122579682441647088055783405690187717169714458698282938108040989968802234758206399946158132661419913502978204057696653246181928780823988167964751665927763609607951484711230520043810548507744362474508094458027042977039600310743726554251462388376872744, 576224340396249382532487750566785659078086584605005806604369050149554049502463733637045387940919358997794936761300972170334990952382192746930700765884376535570795996481285812958887544683532818601789556036552229105040079931970187099560026251995300357987533367174864394616267868072929704575145984670722374917473968115161882812115469766176879265461272965713, 410396378229520694442348214197179232447030155275408885841695597065802197736010397462694196297620931111160870662777973780168016568706378782707009861506299504437900725155337115548746108464928402439898616007461004301820656671884754115833645112304235641411471733758865864232795925891668761749360568580445537720117405347289446620378884114306862342918727539161, 514030666320442417457103884509938881539919858232033478028241029281661383490458020720222557758759431254156773835354715332260632638473206400534738208779778571143434903720124210362848198488329252526384535647586278120675224050640744782702908182099857443903755544522176274455197877010164835860700850693180982808004139348271970980833194879169729677053030494756, 491035680463003138301887771065501910305031767005514757812719560752833905725146598129349937098088999004916550153985741318131613105294032556145274755034259068934869801742062967333532467957914484473467103403705351529620971329172927874699792273486681433651313947240382119950343641977750847136422023404114836246788422134987832199465581626307563632697221995328, 506747628218287514232625157819015885350711839675148572684432576966019476609575067319900041434944364649935103641239280325742014935426248315103784101006388404800988445935766203183048600464013530080262763764227908855582831461887790215358211436654821441794317095125192698203446559405833163287469890337640619405144895851500851923476916964667047734584587079278, 163362786780137255097265147228902273852966841183139750875818837583013342580016170241555545628430489848837041439292947363579065777780442451103889147494290093909775628611981584829408906844032680258150977951251769265513904360174472237399379855300267410940692678057545866931484584851436314996217890879640216886310260643060298189869303238494432577522466171750, 433223846401751475097044539186653996530633625464372954928631923261438705124241996611974391980079754798241825174545594161546068467162394991822017862508947214631899540209387251576573515059948011194602523121126504878265131092241862151791079160464786651712105163632459953082416870390370484975447549702365794783940026078551114146690396782301935114638674237191, 386119416713200648384021939056054691848053310656353891342391366879272918519188104318850956725996743935737320853415226296804741152991496309131226292871877343688724773712963542883348833590494699334790583363050010720397284886482584755080425957809944445504413893859733202631211222686895134131314982005277144898066114519773347946525825153451279427313330805740, 671043133582368769847946952856628796239488405078216638402639546521292428250927902851253620769023612340952774567494615867185481707863567521627306310261735919134371328852678488882613548456390798324899476546593685729129328563131170302484527179936611671909092123774021466968063378765876765983061945296743584968983086114732471615086059539281294354076284163867, 97271285348597278269890752750117111722655962700267111520127020954866047661598910114794789540624739304603890359769600848293746503981601428246180801827854605386599534665828097317424764950264993146463934964241786815132560415396664590627653197642853338597811859484534683995797832156556219205636857641620230682344420723903248478440719512016011166627457191961, 195348022195887037551414176907773580663142564352068076523083637814883528809186175666835604421911546888644979913313148252284199991604801591483978091149146480009700670834062670899061913230612242593151205479378421427409530742088288308261522308003151496004525683806122418297837575151127968847738737772616782331038745765738665048802253796958366766453658308898, 381364836604675366965025994851771571480762027394002308742036739413888664421760085888527848091939576591995901710315745070858666886234038692459074617056660843390987534327835043292812719747295875958069783689609875876365611187501557850234950197555566972777959778142305181767025843873898484770989690743015445320420052890363252696417959320542540153285007889541, 179741868365128270268691272148171859323422460131129671360782976232835961048893932422175993031132407532073017342070722796644985143497301617418581604789983236771914265407002081760611731619681858988523442212000937759785726048591838156445146061574137713127242497684307853009912506818301346440866934602266163983303990033629009615356779177126789286548945886645, 638882431773248662122953578825157314790550442209147606322715263560762038610814964278847581873169361183807606352112446219152804824676814297455174317145835495993534522323433126436733893492730773888285589012637386294519622465265440512584834148096528803461176391067037870432813499011757638665064488867721798387635805043568486005448902005389467303881601151494, 345249340107975910323201021160011018776448833602822831580775498586470927695276741225405405832044676919542423867299231972051213279370807898605386467495068127576255517346159164420586206457062450810213383670405751337397544167158375930569537758951270666466164678092160454784146237282315544963444233738352225071201983615255939909300704097663693836183932911574, 640869258383507879513157114547637789711747175336277525920145201432834400711639194325604127254725305772916898772685387836181966575264442243036376809022416006429910965062265717872342054661412821549399160675189232905306257541433126788699679054692411856338465128139398275625955584264312621261820480373820509339015232691633967750267199565774173755384433844879, 733784740944079960908723345936237488238465732150060996944495457767940837101006832410680039479852502991348192067686138621577096340126715766728249134127093226372011978549552891132407371832391139253028044681455258013924167414025343964706998148377454288183144002052053209570529036177483127019368293000986067231297660907352501781341716647443951707091934946024, 196835687793204397787665321035242803376145722103076505162597231952916219314907705730688902829733494351304644645553406016874697264708949646832561367929559662834224022287649489292231745779644902292331748450448550245045718698196008381300628837155342104667263070357858286509436532387138780592906889838861013281919220074887786706426259995686830130520374257901, 33254150719689498440224533980613603484689423053575085183327110910583152985686280100951944537990299524087984095241316044822895859725702235147970201665491876952901900873017821796523030930281073798788262259988296954737955838822564206263060417085310470459039640657003028116969578131917977510370096742037230988523844725004234537272680897768797481658668250457, 359014672517530836217786017834426031308528084640556434325060798127645575079188040386137416220149675940716836587993999217640994708428688312514807338323193973738669040402936053614614899578956630417093787080990305126840588559881393461365771624577499132906750629652299622900537577841385354839678241617454600796051942652714014710680537620692310913680701130073, 467339513428663959041900829510499420670190261878513177502797150697761342130093282683436714872568602848133034256100054460409606514892587047107079667018965449838330640232451975019838775786554835515814776113530538003541956265236395210237413913394948233176845360964968211413180894963280914957606535278250006535912996956687784058049331256436103437598642854272, 318125654821608087807909665385816302952416051470264370512802291495603989767849452160797369216023539204152777561831393459098237129419357193806605188995247812708500827552862906658189603716347075550922840042996639780852578025623254747553273175334285424246850987356339462955986318870782942032644513334585852347261344751026377802861151315773535738716774717375, 218956493151855455511207494173649275701683075604085159132940055503473535336095493683045975766539646882418665807335428983794380988982886520529869035119761015880550704503787866927860028845106223016637883161567866670583137059692486444833265584160320652565966295496180324542912370964039292633539349194214112785356694941084351694015965869140270171843746274241, 526678073893157725456143918504438569007398305209959919861490621740527083753446766447711153373938223457325817740640891189470330142070065597710868576472368563471670155687968362723311326883354744749346519256722381954009709696407838543447257288134996402088355827211550276034358326596634686676615575798258357218832742223540505830460396142881752974607433417943, 293158200118114792649884657018998345968177161370218467916626383700413007032599844628073055550494496265659533697322201947663050922497352540965393435456307605710737052228948332421454018850027537440055859310027798641638470207327675080726705118957748590005963732426351798786479155136832277745131782722378810512106287509395664855648224024968792542693799279400, 739886062003143471399772489568576069670420925917659719462084858357699705355412664899480619541104583804255028900061251833175311520519497653110198044053544383671512562459314194644274917824132112636901883225913976580372067054990729969840627800755033469994673857030326969754905580662486372585819172728070740592595234723065906599421844741748877268713510837961, 225870320951045144287654813356667831617189898531943638131025151617501255606504087390468297427417827096017409220334944471923095182908129314459799617354809743084550407350776389933678946270112481414793928089618810650956151515732490784172931042473389255701567575864840890462971817901531439280869622141670147573699351579751109371964256161028580752753400244072, 27018788427173928446034531070950600594607503433412693613634697371884268059094129460794673086425418729470644653371048206094994152383473448089156553817368189679793487212181920596569495126387202046015441192304884442055061259617231632188719708101476947955612722360497684020368796797645742893259604400394391459916203084627063337142090433036530029743941427436, 567755139852561873774336197423687426064582212677195198786283321178139587722938764663025529351059435988341934962320961395894211540454215577346268130403281183416736371870313624295197488953201836140098567892478309782405984912766544179804174150618761709004711941357865449499010649113223589327790846486271561360578017442593044808638104271006350036612102010110, 702947191641421206271650353688013476758453311829353390102010726677205339203535809733012235363687507814743988777397863205018620734734302872725674870204613538971162501483044891708020093542179436971203797517709914266292327013911403783764420327135971998279893934583998978039808239957853919689896887284480817579522493023842276628672831387050461041709188166274, 513276693473895609211643205634272685746303961486645344931324900558845327571600493382304768610339115209351536650298512687934445283953384796819198751594203654889685202984298556363961422852363836907711962560463903907607703907181913192617961430681237648543308240356226683266630353211808109641558266649459264085451888175943676099692349788852693888903460525477, 663760621913796442104328233999344211518952190111971327897499915336695711091641821665697013979871261456632837275739301206225743243734435612611630209578892548330934085579521708110366214426844007172742025151686847946682349400667860504592499698523005224686050652863240086952186598092209583969012076240691047794524625245544102379507086704865530297755534979630, 203704495521529300684255027614480829034459546477788009301885076337719800844133285343570329707876118698223604998546113325275122361952283419098753366561461360818226353853284800510131688856314575313459293008246649048112801580986361102463654147074452494572727301385094198338295616941817510651533219955145112671512893982566159139049301152030070146160482378948, 670410335849226620979337453194619133962795815466324781903866875848857327616733180445981974280939624967362667628508087309024479876679513801480530757852885986389011581469892434852175185545409810159283583978733958723956651374552436066759974524226871618142179408120664328770192634115853040477409960884542579648114979622203554616242114311675160437264765941108, 16895648203764207731 | python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | true |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/VULNCON/2021/crypto/BitSafe/chal.py | ctfs/VULNCON/2021/crypto/BitSafe/chal.py | from Crypto.Util.number import getRandomRange, long_to_bytes, bytes_to_long, inverse, GCD
class BitSafe:
def __init__(self, msg):
self.mbits = bin(bytes_to_long(msg))[2:]
self.tbits = len(self.mbits)
def keygen(self):
self.pub = []
self.priv = [ getRandomRange(2, 1 << 10) ]
s = self.priv[0]
for i in range(1, self.tbits):
self.priv.append( getRandomRange(s+1, s << 5) )
s += self.priv[i]
self.q = getRandomRange(s+1, s << 5)
while True:
self.r = getRandomRange(2, self.q)
if GCD(self.r, self.q) == 1:
break
self.pub = [ self.r * w_i % self.q for w_i in self.priv ]
def encrypt(self):
cipher = 0
for i, bit in enumerate(self.mbits):
cipher += int(bit) * self.pub[i]
return hex(cipher)[2:]
def decrypt(self, cipher):
rp = inverse(self.r, self.q)
cp = int(cipher, 16) * rp % self.q
mbits = ''
for w_i in reversed(self.priv):
if cp - w_i >= 0:
mbits = '1' + mbits
cp -= w_i
else:
mbits = '0' + mbits
msg = long_to_bytes(int(mbits, 2))
return msg
if __name__ == '__main__':
FLAG = open('flag.txt', 'rb').read().strip()
safe = BitSafe(FLAG)
safe.keygen()
cipher = safe.encrypt()
assert safe.decrypt(cipher) == FLAG, "Something's Wrong !!!"
with open('output.py', 'w') as f:
f.write('pub = %s\n' % str(safe.pub))
f.write('cipher = 0x%s' % str(cipher))
print("Your Secret is Safe with us !!!")
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/VULNCON/2021/crypto/mfine/chal.py | ctfs/VULNCON/2021/crypto/mfine/chal.py | import random
def encrypt(plaintext):
ciphertext = ''
for letter in plaintext:
i = ALPHA.index(letter)
c = (a*i + b) % m
ciphertext += ALPHA[c]
return ciphertext
ALPHA = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ{}_ #"
m = len(ALPHA)
a = random.randrange(1, m)
b = random.randrange(1, m)
message = open("message.txt").read().replace('\n', '')
cipher = encrypt(message)
with open("cipher.txt", 'w') as f:
for i in range(0,len(cipher),64):
f.write( cipher[i:i+64]+'\n' )
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/CrateCTF/2024/rev/Extraterrestriell_Kommunikation/alien.py | ctfs/CrateCTF/2024/rev/Extraterrestriell_Kommunikation/alien.py | from PIL import Image
from math import lcm
morse_code_dict = {
'a': '.-', 'b': '-...', 'c': '-.-.', 'd': '-..', 'e': '.', 'f': '..-.',
'g': '--.', 'h': '....', 'i': '..', 'j': '.---', 'k': '-.-', 'l': '.-..',
'm': '--', 'n': '-.', 'o': '---', 'p': '.--.', 'q': '--.-', 'r': '.-.',
's': '...', 't': '-', 'u': '..-', 'v': '...-', 'w': '.--', 'x': '-..-',
'y': '-.--', 'z': '--..',
'0': '-----', '1': '.----', '2': '..---', '3': '...--', '4': '....-',
'5': '.....', '6': '-....', '7': '--...', '8': '---..', '9': '----.', '{': '---...', '}': '...---'
}
def convertTuple(tup):
st = ''.join(map(str, tup))
return st
ascii_to_coord = {}
for letter in morse_code_dict:
ascii_to_coord[letter] = morse_code_dict[letter].count('-'), morse_code_dict[letter].count('.')
coord_to_ascii = {}
for a in ascii_to_coord:
coord_to_ascii[convertTuple(ascii_to_coord[a])] = []
for b in ascii_to_coord:
if ascii_to_coord[a] == ascii_to_coord[b]:
if b not in coord_to_ascii:
coord_to_ascii[convertTuple(ascii_to_coord[a])].append(b)
#print(a,b)
flag = ""
with open("flag.txt", "r") as f:
flag = f.readlines()[0]
dummyPaint = [[0, 0, 0, 0, 0] for i in range(6)]
for ch in flag:
dummyPaint[ascii_to_coord[ch][0]][ascii_to_coord[ch][1]] += 1
removedZeroes = sum(list(map(lambda i: list(filter(lambda j: j > 0, i)), dummyPaint)), [])
minRows = lcm(*removedZeroes)
pixels = 5 * minRows
image = Image.new('RGB', (pixels, pixels))
for index, ch in enumerate(flag):
r = int(((coord_to_ascii[convertTuple(ascii_to_coord[ch])].index(ch)) / len(coord_to_ascii[convertTuple(ascii_to_coord[ch])]) *256) + 1)
rgb = (r, 0, int((index/len(flag)*256) + 1))
tot = 0
isMany = False
strokeSize = minRows / dummyPaint[ascii_to_coord[ch][0]][ascii_to_coord[ch][1]]
if dummyPaint[ascii_to_coord[ch][0]][ascii_to_coord[ch][1]] > 1:
isMany = True
for asc in coord_to_ascii[convertTuple(ascii_to_coord[ch])]:
tot += flag[0:index].count(asc)
for i in range(0, minRows):
for j in range(0, minRows):
if isMany and not (i+1 > (strokeSize * tot) and i < (strokeSize * (tot + 1))):
continue
x = (minRows * (ascii_to_coord[ch][0])) + i
y = (minRows * (ascii_to_coord[ch][1])) + j
image.putpixel((x,y), rgb)
image.save('flag.png')
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/CrateCTF/2024/crypto/Skyltsmedjan/skyltsmedjan.py | ctfs/CrateCTF/2024/crypto/Skyltsmedjan/skyltsmedjan.py | from sympy import nextprime, randprime
from secrets import randbits, randbelow
from os import getenv
from sys import stdin
def get_flag(n: int, e: int, userid: int) -> None:
print("Var god skriv in ett meddelande som säger att du får hämta flaggan\n> ", end="")
msg = stdin.buffer.readline()[:-1]
m = int.from_bytes(msg, "little")
sgn = int(input("Var god ange en passande skylttext till meddelandet > "))
msg2 = pow(sgn, e, n)
if m != msg2:
print("Jättedålig skylttext >:(")
return
if msg.decode("utf-8") == f"Kund nr. {userid} får hämta flaggan":
print(getenv("FLAG") or "ingen flagga!?!?!?!?!?!?!?!?")
else:
print("Det verkar visst som att du inte får hämta någon flagga <:(")
def sign_message(n: int, d: int) -> None:
print("Ange ett meddelande du vill ha en alldeles utmärkt skylttext till\n> ", end="")
msg = stdin.buffer.readline()[:-1]
if b"flag" in msg:
print("Ingen skylttext till det där inte >:(")
return
m = int.from_bytes(msg, "little")
if m > n:
print("Så där breda skyltar har vi tyvärr inte här!")
return
sgn = pow(m, d, n)
print(sgn)
def main():
print("Art by Marcin Glinski")
print(" _.gd8888888bp._")
print(" .g88888888888888888p.")
print(" .d8888P"" ""Y8888b.")
print(" \"Y8P\" \"Y8P'")
print(" `. ,'")
print(" \\ .-. /")
print(" \\ (___) /")
print(" .------------------._______________________:__________j")
print("/ | | |`-.,_")
print("\\###################|######################|###########|,-'`")
print(" `------------------' : ___ l")
print(" / ( ) \\")
print(" fsc / `-' \\")
print(" ,' `.")
print(" .d8b. .d8b.")
print(" \"Y8888p.. ,.d8888P\"")
print(" \"Y88888888888888888P\"")
print(" \"\"YY8888888PP\"\"\n")
print("Hämtar blåsbälg...")
p = randprime(1 << 1024, 1 << 2048)
print("Värmer upp ässja...")
q = randprime(1 << 1024, 1 << 2048)
n = p * q
e = 65537
d = pow(e, -1, (p - 1) * (q - 1))
userid = randbelow(1000000)
print(f"Välkommen, kund nr. {userid}!\n{n = }\n{e = }")
while True:
match input(f"Hämta [f]lagga eller [s]kylt? ")[0]:
case "f":
get_flag(n, e, userid)
case "s":
sign_message(n, d)
if __name__ == "__main__":
raise SystemExit(main())
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/CrateCTF/2025/misc/Echo_Service/echo_service.py | ctfs/CrateCTF/2025/misc/Echo_Service/echo_service.py | #!/usr/local/bin/python3
from os import chdir, system, remove
from shutil import rmtree, unpack_archive
from hashlib import sha256
chdir("/tmp")
ok = {}
if __name__ == "__main__":
while True:
rmtree("files", True)
try: remove("archive.tar.gz")
except: pass
match input("[v]alidate or [e]cho? "):
case "v":
rawtar = b""
while (line := input()) != "":
rawtar += bytes.fromhex(line)
with open("archive.tar.gz", "wb") as f:
f.write(rawtar)
unpack_archive("archive.tar.gz", "files", filter="fully_trusted")
with open("files/message", "rb") as f:
if all(c in "abcdefghijklmnopqrstuvwxyzåäö 0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZÅÄÖ.,".encode() for c in f.readline().strip()):
ok[sha256(rawtar).hexdigest()] = ()
else:
print("🧌")
case "e":
rawtar = b""
while (line := input()) != "":
rawtar += bytes.fromhex(line)
hash = sha256(rawtar).hexdigest()
if hash not in ok:
print("👺")
continue
with open("archive.tar.gz", "wb") as f:
f.write(rawtar)
unpack_archive("archive.tar.gz", "files")
with open("files/message", "rb") as f:
system(b"echo " + f.readline().strip())
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/CrateCTF/2025/pwn/Sandbox/chall.py | ctfs/CrateCTF/2025/pwn/Sandbox/chall.py | #!/usr/local/bin/python
# pip install capstone==5.0.6 pyelftools==0.32
from capstone import *
from capstone.x86 import *
from elftools.elf.elffile import ELFFile
import fcntl, io, os, sys, tempfile
md = Cs(CS_ARCH_X86, CS_MODE_64)
md.detail = True
checked = set()
def check(offset: int):
if offset in checked:
return
checked.add(offset)
pprev = None
prev = None
for inst in md.disasm(code[offset:], seg.header.p_vaddr + offset):
# print(inst)
assert inst.id != X86_INS_INT, "Interrupt instruction is not allowed"
assert inst.id != X86_INS_SYSENTER, "Sysenter instruction not allowed. Use syscall."
if inst.id == X86_INS_SYSCALL:
assert prev is not None, "Must have instruction immediately before syscall"
assert prev.id == X86_INS_MOV, "Instruction before syscall must be mov"
_, wr = prev.regs_access()
assert wr == [X86_REG_EAX], "Instruction before syscall must set eax"
assert prev.op_count(X86_OP_IMM) == 1, "Instruction before must set eax to immediate"
syscall_nr = prev.op_find(X86_OP_IMM, 1).value.imm
assert syscall_nr in [0, 1, 9, 11, 0x3c], "Only read, write, mmap, exit syscalls are allowed"
if syscall_nr == 9: # mmap
assert pprev is not None, "Two instructions must precede mmap syscall"
assert pprev.id == X86_INS_MOV, "Two mov instructions must precede mmap syscall"
_, wr = pprev.regs_access()
assert wr == [X86_REG_EDX], "Instruction before instruction before syscall must set edx"
assert pprev.op_count(X86_OP_IMM) == 1, "Instruction before must set eax to immediate"
prot = pprev.op_find(X86_OP_IMM, 1).value.imm
assert prot & ~0b11 == 0, "mmap may only be called with PROT_READ and PROT_WRITE"
if inst.group(X86_GRP_JUMP) or inst.group(X86_GRP_CALL):
for i in range(1, inst.op_count(X86_OP_IMM) + 1):
op = inst.op_find(X86_OP_IMM, i)
check(op.value.imm - seg.header.p_vaddr)
assert inst.op_count(X86_OP_MEM) == 0, "Not allowed to jump to/call memory location"
for i in range(1, inst.op_count(X86_OP_REG) + 1):
reg = inst.op_find(X86_OP_REG, i).value.reg
assert prev is not None, "Must have an instruction immediately before register jump/call"
assert prev.id == X86_INS_MOV, "Instruction before register jump/call must be mov"
_, [wr] = prev.regs_access()
assert reg == wr, "mov before register jump/call must set the same register"
assert prev.op_count(X86_OP_IMM) == 1, "mov before register jump/call must use immediate value"
check(prev.op_find(X86_OP_IMM, 1).value.imm - seg.header.p_vaddr)
assert inst.op_count(X86_OP_INVALID) == 0, "Not allowed to jump to/call invalid"
pprev = prev
prev = inst
print("Give me a hex encoded 64 bit executable ELF file (end with an empty line):")
hexdata = ""
while (line := input()) != "":
hexdata += line
data = bytes.fromhex(hexdata)
print(data)
elf = ELFFile(io.BytesIO(data))
assert elf.header.e_ident.EI_CLASS == "ELFCLASS64", "Only 64-bit elf files are allowed"
found_executable = False
for seg in elf.iter_segments():
if seg.header.p_flags & 0b1 == 0: # not exec
continue
assert not found_executable, "Only one segment may be executable"
found_executable = True
assert seg.header.p_flags & 0b10 == 0, "Executable segment may not be writable"
code = data[seg.header.p_offset:][:seg.header.p_filesz]
# print(seg.header)
# print(code[elf.header.e_entry - seg.header.p_vaddr:][:10].hex())
if seg.header.p_vaddr <= elf.header.e_entry < seg.header.p_vaddr + seg.header.p_memsz:
check(elf.header.e_entry - seg.header.p_vaddr)
else:
check(0)
print("This program seems safe, let's run it!", flush=True)
with tempfile.NamedTemporaryFile(delete_on_close=False) as f:
f.write(data)
os.fchmod(f.fileno(), 0o500)
f.close()
os.execve(f.name, ["your", "program"], {})
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/CrateCTF/2025/rev/Eventually_a_Flag/printflag.py | ctfs/CrateCTF/2025/rev/Eventually_a_Flag/printflag.py | import string, time
alphabet = string.ascii_lowercase + string.ascii_uppercase + string.digits + "!#$%&()*+,-./:;<=>?@[]^_{|}~åäö "
ciphertext = "cq rbäl{%$0eYXm&5bV( Z&j@|2VoT2fVzö5)äXMömlfpmhhtawc]eiwvl2ö26a4Vm$3bP6@Rm5#r)ToR2p!XlZ.B8@);äfkldq=<}{[:#RkY4h55m8!r(,E{g:#z)-yRRäAs#nH?rbi|$|"
# TODO: Too much recursion?
def fibonacci(n: int) -> int:
return n if n < 2 else fibonacci(n - 2) + fibonacci(n - 1)
for i, c in enumerate(ciphertext):
print(alphabet[(alphabet.index(c) + fibonacci(i)) % len(alphabet)], end="", flush=True)
time.sleep(0.03)
print()
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/CrateCTF/2025/crypto/Julius_Caesar/julius_caesar.py | ctfs/CrateCTF/2025/crypto/Julius_Caesar/julius_caesar.py | import string, random, sys
alphabet = string.ascii_lowercase + "åäö "
def substitute(s: str, sub: str) -> str:
assert set(sub) == set(alphabet) and len(sub) == len(alphabet)
return "".join(alphabet[sub.index(c)] if c in alphabet else c for c in s.lower())
CHUNK_SIZE = 32
def substitute_better(s: str, init_sub: str) -> str:
res = ""
sub = init_sub
for i in range(0, len(s), CHUNK_SIZE):
pt = s[i:i+CHUNK_SIZE]
nextsub = "".join(random.sample(alphabet, len(alphabet))) if len(s) > i + CHUNK_SIZE else ""
res += substitute(pt + nextsub, sub)
sub = nextsub
return res
if __name__ == "__main__":
with open(0, "r") as f:
large_english_text = f.read()
large_english_text = list(large_english_text)
flag = sys.argv[1]
large_english_text.insert(len(large_english_text) // 2, flag)
plaintext = "".join(large_english_text)
init_sub = random.sample(alphabet, len(alphabet))
print(substitute_better(plaintext, init_sub))
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/CrateCTF/2025/crypto/collision/kollision.py | ctfs/CrateCTF/2025/crypto/collision/kollision.py | #!/usr/local/bin/python3
from collections.abc import Iterable
from Crypto.Cipher import AES
from Crypto.Util.Padding import pad
from itertools import batched
from sys import stdin
from os import system
def xor(a: Iterable[int], b: Iterable[int]) -> bytes:
return bytes(x ^ y for x, y in zip(a, b))
def hash(b: bytes) -> bytes:
j = bytes([16] * 16)
k = bytes([17] * 16)
for chunk in batched(pad(b, 16), 16):
j, k = k, xor(AES.new(j, AES.MODE_ECB).encrypt(bytes(chunk)), k)
return k
texts = {}
if __name__ == "__main__":
while True:
match input("[v]alidate or [e]cho? "):
case "v":
print(end="> ", flush=True)
text = stdin.buffer.readline().rstrip()
texts[hash(text)] = all(c in "abcdefghijklmnopqrstuvwxyzåäö 0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZÅÄÖ.,/".encode() for c in text)
case "e":
print(end="> ", flush=True)
text = stdin.buffer.readline().rstrip()
if hash(text) in texts and texts[hash(text)] == True:
system(b"echo " + text)
else:
print("👺")
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/CrateCTF/2025/crypto/Fiats_and_Shamirs_Sign_Forge/fiats_och_shamirs_skyltsmedja.py | ctfs/CrateCTF/2025/crypto/Fiats_and_Shamirs_Sign_Forge/fiats_och_shamirs_skyltsmedja.py | #!/usr/bin/env python3
from sympy import randprime
from secrets import randbelow
from hashlib import sha512
from itertools import batched
from os import getenv
from sys import stdin
from tqdm import tqdm
import readline # python can't read more than 4095 bytes on a line without this!?!?!?!!?
bits = 1024
# P = randprime(1 << (bits - 1), 1 << bits)
P = 142183057539221114772334320155357900971672839527033419933632930422598689244699118628790550686385782087839264608691124166282411111453892566790501991185690337007365084640514843134915886806685595932682449190226519709045107875062749184557628698954376693978319256727395538290496585148574130635824813936971351780687
# G = randbelow(P)
G = 115773473808249193389699647223738486415484530297622716921274546881781790662447225064269223145484400140584983064539536225792083546317579179348492488582505669728734929584059156983199640635484135491292806628496468871748306724500896820885050766131662643822318998434410907162883100710397133922104461934169171994660
def get_flag(y: int, userid: int) -> None:
print("Var god skriv in ett meddelande som säger att du får hämta flaggan\n> ", end="", flush=True)
msg = stdin.buffer.readline()[:-1]
print("Var god ange en passande skylttext till meddelandet\n> ", end="", flush=True)
sgn = input()
sgn = (
int("".join(x), 16) for x in
batched(sgn, bits // 4)
)
y1, *sgn = sgn
if y != y1:
return print("Vem har ens gjort den här?")
h = sha512(msg)
h.update(P.to_bytes(bits // 8) + G.to_bytes(bits // 8) + y.to_bytes(bits // 8))
valid = True
for c, ans in tqdm(batched(sgn, 2), total=128):
h.update(c.to_bytes(bits // 8))
if f"{int(h.hexdigest(), 16):b}".count("1") % 2:
if pow(G, ans, P) != c:
valid = False
break
else:
if pow(G, ans, P) != c * y % P:
valid = False
break
h.update(ans.to_bytes(bits // 8))
if not valid:
return print("Jättedålig skylttext >:(")
if msg.decode("utf-8") == f"Kund nr. {userid} får hämta flaggan":
print(getenv("FLAG") or "ingen flagga!?!?!?!?!?!?!?!?")
else:
print("Det verkar visst som att du inte får hämta någon flagga <:(")
def sign_message(y: int, x: int) -> None:
print("Ange ett meddelande du vill ha en alldeles utmärkt skylttext till\n> ", end="", flush=True)
msg = stdin.buffer.readline()[:-1]
if b"flag" in msg:
print("Ingen skylttext till det där inte >:(")
return
sgn = []
h = sha512(msg)
h.update(P.to_bytes(bits // 8) + G.to_bytes(bits // 8) + y.to_bytes(bits // 8))
sgn.append(y)
for _ in tqdm(range(128)):
r = randbelow(P)
c = pow(G, r, P)
h.update(c.to_bytes(bits // 8))
sgn.append(c)
ans = r if f"{int(h.hexdigest(), 16):b}".count("1") % 2 else (x + r) % (P - 1)
h.update(ans.to_bytes(bits // 8))
sgn.append(ans)
print("".join(f"{n:0{bits // 4}x}" for n in sgn))
def main():
x = randbelow(P)
y = pow(G, x, P)
userid = randbelow(1000000)
print(f"Välkommen, kund nr. {userid}!\n{P = }\n{G = }\n{y = }")
while True:
match input("Hämta [f]lagga eller [s]kylt? ")[0]:
case "f":
get_flag(y, userid)
case "s":
sign_message(y, x)
if __name__ == "__main__":
raise SystemExit(main())
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/involuntaryCTF/2025/rev/Basic_python/basicPython.py | ctfs/involuntaryCTF/2025/rev/Basic_python/basicPython.py | def getFLag():
file=open("flag.txt","rt")
fileContents=file.read().strip()
return fileContents
def main():
a=getFLag()
b=[]
for i in range(len(a)):
if(i%2==0):
b.append(ord(a[i])+i)
else:
b.append(ord(a[i])-i)
for i in range(len(b)//2):
temp=b[-i]
b[-i]=b[i]
b[i]=temp
print(b)
main()
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/UrchinSecAware/2024/code/Heart/app.py | ctfs/UrchinSecAware/2024/code/Heart/app.py | from flask import Flask, request, render_template_string
app = Flask(__name__)
@app.route('/name/<input_name>', methods=['GET'])
def say_name(input_name):
if request.method == 'GET':
if input_name is not None:
return render_template_string(f"Hello {input_name}")
if __name__ == '__main__':
app.run(host='127.0.0.1', port=5555) | python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/UrchinSecAware/2024/crypto/Tr3ppl3_Stuffs/script.py | ctfs/UrchinSecAware/2024/crypto/Tr3ppl3_Stuffs/script.py | #!/usr/bin/env python3
from Crypto.Util.number import getPrime, bytes_to_long
with open('flag.txt', 'rb') as f:
flag = f.read()
p = getPrime(1024)
q = getPrime(1024)
r = getPrime(1024)
n1 = p * q
n2 = p * r
n3 = q * r
moduli = [n1, n2, n3]
e = 65537
c = bytes_to_long(flag)
for n in moduli:
c = pow(c, e, n)
print("Encrypted message:", c)
with open('public-key.txt', 'w') as f:
f.write(f'n1: {n1}\n')
f.write(f'n2: {n2}\n')
f.write(f'n3: {n3}\n')
f.write(f'e: {e}\n')
f.write(f'c: {c}\n')
| 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.