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/BSidesTLV/2022/crypto/SEV/lib/session.py | ctfs/BSidesTLV/2022/crypto/SEV/lib/session.py | import enum
import hashlib
import hmac
from typing import NamedTuple
def KMAC(key, size, prefix, content):
return hashlib.shake_256(key + size.to_bytes(4, byteorder='little') + prefix + content).digest(size)
class RoleLabel(enum.Enum):
I2R = b'I2R'
R2I = b'R2I'
class Role(enum.Enum):
Initiator = (RoleLabel.R2I, RoleLabel.I2R)
Responder = (RoleLabel.I2R, RoleLabel.R2I)
class Context(enum.Enum):
KEYS = b'\x00'
ENC = b'\x01'
INT = b'\x02'
class Counter:
def __init__(self, init : int = 0) -> None:
assert init >= 0
self.val = init
def __call__(self) -> bytes:
ret = self.val.to_bytes(4, 'big')
self.val += 1
return ret
class RoleContext(NamedTuple):
ENC: bytes
INT: bytes
CTR: Counter
def role_ctx_derive(mk: bytes, label: RoleLabel, ctr = 0):
keys = KMAC(mk, 64, Context.KEYS.value, label.value + b" Session Keys")
return RoleContext(keys[:32], keys[32:], Counter(ctr))
def session_context(share : bytes, role: Role):
mk = hashlib.sha384(share).digest()
rx_label, tx_label = role.value
return SessionContext(role_ctx_derive(mk, rx_label), role_ctx_derive(mk, tx_label))
class SessionContext:
def __init__(self, rx_ctx : RoleContext, tx_ctx : RoleContext):
self.tx_ctx = tx_ctx
self.rx_ctx = rx_ctx
def tx_encrypt(self, msg : bytes):
txc = self.tx_ctx.CTR()
ct = bytes(x^y for x,y in zip(msg, KMAC(self.tx_ctx.ENC, len(msg), Context.ENC.value, txc)))
tag = KMAC(self.tx_ctx.INT, 32, Context.INT.value, txc + ct)
return ct, tag
def rx_decrypt(self, ct : bytes, tag : bytes):
rxc = self.rx_ctx.CTR()
calc_tag = KMAC(self.rx_ctx.INT, 32, Context.INT.value, rxc + ct)
if not hmac.compare_digest(tag, calc_tag):
raise RuntimeError("Bad tag")
return bytes(x^y for x,y in zip(ct, KMAC(self.rx_ctx.ENC, len(ct), Context.ENC.value, rxc)))
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/BSidesTLV/2022/crypto/SEV/lib/io.py | ctfs/BSidesTLV/2022/crypto/SEV/lib/io.py | from typing import Protocol, runtime_checkable
from .data import JoinData, SplitData
@runtime_checkable
class IOBase(Protocol):
def writeLine(self, line : bytes) -> None: ...
def readLine(self) -> bytes: ...
class IO:
def __init__(self, base : IOBase) -> None:
self.base = base
def readLine(self):
return self.base.readLine()
def writeLine(self, line : bytes):
self.base.writeLine(line)
def readData(self):
return SplitData(self.readLine())
def writeData(self, *data : bytes):
self.writeLine(JoinData(*data)) | python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/BSidesTLV/2022/crypto/SEV/lib/data.py | ctfs/BSidesTLV/2022/crypto/SEV/lib/data.py | from base64 import b64encode, b64decode
def JoinData(*data : bytes):
return b'|'.join(b64encode(d) for d in data)
def SplitData(data : bytes):
return tuple(b64decode(x) for x in data.split(b'|'))
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/BSidesTLV/2022/crypto/HighExpectations/challenge.py | ctfs/BSidesTLV/2022/crypto/HighExpectations/challenge.py | import secrets
import flag
START_NUM_OF_PEOPLE = 60
PERFECT_SHOW = 2000
MAX_NUM_GAMES = 3000
RIGHT_GUESS = 60
WRONG_GUESS = 1
NUM_OF_SUITS = 4
NUM_OF_VALUES = 13
WELCOME_TEXT = """
You are a mentalist and now it's your show!
It's your chance to make the impossible possible!
Currently there are {} people in the show.
Your goal is to have {} people in it!
You can do it!
Magic is real!!
"""
SESSION_TEXT = """
There are {} people in the show
You pick a volunteer
You ask her to think on a card
"""
THINK_OF_A_SUIT_TEXT = """
You ask her to think on the suit of the card
You read her mind and choose:
1) Spades
2) Hearts
3) Clubs
4) Diamond
"""
THINK_OF_A_VALUE_TEXT = """
You ask her to think on the value of the card
Value between 1 and 13 when:
1 is Ace
2-10 are 2-10 :)
11 is Jack
12 is Queen
13 is King
You read her mind and choose:
"""
RIGHT_GUESS_TEXT = """
Bravo! You did the impossible!
The applause you get attracts {} more people to the show!
"""
WRONG_GUESS_TEXT = """
Wrong answer :|
You probably read someone else's mind by mistake...
Someone left the show :(
"""
WIN_TEXT = "You Won! Here is your flag:"
LOSE_TEXT = """No one left in the show :(
Maybe you should practice more before...
"""
def red(text):
return "\033[91m" + text + "\033[0m"
def green(text):
return "\033[92m" + text + "\033[0m"
def purple(text):
return "\033[95m" + text + "\033[0m"
# return a number between 1 and the given range
def rand_range(rng):
return rng - (secrets.randbits(4) % rng)
def get_int(rng):
while True:
num_str = input(">> ")
if not num_str.isdigit():
print("Not a number, try again :/")
continue
num = int(num_str)
if num <= 0 or num > rng:
print(f"Not in range, choose between 1 and {rng}")
continue
break
return num
def run_game():
people = START_NUM_OF_PEOPLE
print(WELCOME_TEXT.format(people, PERFECT_SHOW))
for i in range(MAX_NUM_GAMES):
if people <= 0:
print(red(LOSE_TEXT))
break
if people >= PERFECT_SHOW:
print(green(WIN_TEXT))
print(flag.FLAG)
break
print(SESSION_TEXT.format(purple(str(people))))
print(THINK_OF_A_SUIT_TEXT)
rand_suit = rand_range(NUM_OF_SUITS)
suit = get_int(NUM_OF_SUITS)
print(THINK_OF_A_VALUE_TEXT)
rand_value = rand_range(NUM_OF_VALUES)
value = get_int(NUM_OF_VALUES)
if suit == rand_suit and value == rand_value:
print(green(RIGHT_GUESS_TEXT.format(RIGHT_GUESS)))
people += RIGHT_GUESS
else:
print(red(WRONG_GUESS_TEXT))
people -= WRONG_GUESS
else:
print("Sorry... the crowd is bored")
if __name__ == "__main__":
run_game()
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/BSidesTLV/2022/crypto/MediumExpectations/challenge.py | ctfs/BSidesTLV/2022/crypto/MediumExpectations/challenge.py | import random
import hashlib
import flag
START_NUM_OF_PEOPLE = 60
PERFECT_SHOW = 2000
MAX_NUM_GAMES = 3000
RIGHT_GUESS = 60
WRONG_GUESS = 1
NUM_OF_SUITS = 4
NUM_OF_VALUES = 13
WELCOME_TEXT = """
You are a mentalist and now it's your show!
It's your chance to make the impossible possible!
Currently there are {} people in the show.
Your goal is to have {} people in it!
You can do it!
Magic is real!!
"""
SESSION_TEXT = """
There are {} people in the show
You pick a volunteer
You ask her to think on a card
"""
THINK_OF_A_SUIT_TEXT = """
You ask her to think on the suit of the card
You read her mind and choose:
1) Spades
2) Hearts
3) Clubs
4) Diamond
"""
THINK_OF_A_VALUE_TEXT = """
You ask her to think on the value of the card
Value between 1 and 13 when:
1 is Ace
2-10 are 2-10 :)
11 is Jack
12 is Queen
13 is King
You read her mind and choose:
"""
RIGHT_GUESS_TEXT = """
Bravo! You did the impossible!
The applause you get attracts {} more people to the show!
"""
WRONG_GUESS_TEXT = """
Wrong answer :|
You probably read someone else's mind by mistake...
Someone left the show :(
"""
WIN_TEXT = "You Won! Here is your flag:"
LOSE_TEXT = """No one left in the show :(
Maybe you should practice more before...
"""
def red(text):
return "\033[91m" + text + "\033[0m"
def green(text):
return "\033[92m" + text + "\033[0m"
def purple(text):
return "\033[95m" + text + "\033[0m"
# return a number between 1 and the given range
def rand_range(rng):
return rng - random.randrange(rng)
def get_int(rng):
while True:
num_str = input(">> ")
if not num_str.isdigit():
print("Not a number, try again :/")
continue
num = int(num_str)
if num <= 0 or num > rng:
print(f"Not in range, choose between 1 and {rng}")
continue
break
return num
def run_game():
random.seed(int(hashlib.md5(b"magic_is_real").hexdigest(), 16))
people = START_NUM_OF_PEOPLE
print(WELCOME_TEXT.format(people, PERFECT_SHOW))
for i in range(MAX_NUM_GAMES):
if people <= 0:
print(red(LOSE_TEXT))
break
if people >= PERFECT_SHOW:
print(green(WIN_TEXT))
print(flag.FLAG)
break
print(SESSION_TEXT.format(purple(str(people))))
print(THINK_OF_A_SUIT_TEXT)
rand_suit = rand_range(NUM_OF_SUITS)
suit = get_int(NUM_OF_SUITS)
print(THINK_OF_A_VALUE_TEXT)
rand_value = rand_range(NUM_OF_VALUES)
value = get_int(NUM_OF_VALUES)
if suit == rand_suit and value == rand_value:
print(green(RIGHT_GUESS_TEXT.format(RIGHT_GUESS)))
people += RIGHT_GUESS
else:
print(red(WRONG_GUESS_TEXT))
people -= WRONG_GUESS
else:
print("Sorry... the crowd is bored")
if __name__ == "__main__":
run_game()
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/BSidesTLV/2022/web/RollTheImpossible/challenge.py | ctfs/BSidesTLV/2022/web/RollTheImpossible/challenge.py | from flask import session
import flag
import random
CTX_FIELDS = ["question", "num"]
NUM_DIGITS = 10
FISH_IN_SEA = 3500000000000 # thanks wikipedia
QUESTIONS_LIST = {"roll a negative number": lambda num: int(num) < 0,
"roll a number that is divisable by 10": lambda num: int(num) % 10 == 0,
"roll a number that contains only ones": lambda num: all(x == "1" for x in num),
"roll the number of fish in the sea": lambda num: int(num) == random.randrange(FISH_IN_SEA),
"misdirection": lambda num: True}
def is_context_exist():
return all(key in session for key in CTX_FIELDS)
def init():
question = random.choice(list(QUESTIONS_LIST.keys())[:-1])
# init context, must contain all the fields in CTX_FIELDS
session["question"] = question
session["num"] = ""
def step():
if not is_context_exist():
return {"num": "", "new_digit": "", "flag": "invalid session data"}
# load data from the session
question = session["question"]
num = session["num"]
_flag = ""
new_digit = ""
if len(num) < NUM_DIGITS:
# roll a new digit and update the number
new_digit = str(random.randrange(9)+1)
num += new_digit
if len(num) == NUM_DIGITS:
if QUESTIONS_LIST[question](num):
_flag = flag.FLAG
else:
_flag = "wrong :("
# store the changed data to the session
session["num"] = num
return {"num": num,
"new_digit": new_digit,
"flag": _flag}
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/BSidesTLV/2022/web/RollTheImpossible/flask_server.py | ctfs/BSidesTLV/2022/web/RollTheImpossible/flask_server.py | import os
import challenge
from flask import Flask, session, render_template
app = Flask(__name__)
app.secret_key = os.getenv("SECRET_KEY", os.urandom(32))
@app.route("/")
def init():
challenge.init()
return render_template("index.html")
@app.route("/step", methods=["POST"])
def step():
return challenge.step()
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/BSidesTLV/2022/web/RollTheImpossible/flag.py | ctfs/BSidesTLV/2022/web/RollTheImpossible/flag.py | FLAG = "BSidesTLV2022{1_wi11_n3ver_submi7_a_dummy_fl4g_ag4in}"
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/BSidesTLV/2022/web/Smuggler/python-microservice/server.py | ctfs/BSidesTLV/2022/web/Smuggler/python-microservice/server.py | import os
from flask import Flask, request
from werkzeug.serving import WSGIRequestHandler
app = Flask(__name__)
@app.route('/')
def run_cmd():
if 'cmd' in request.args:
os.system(request.args['cmd'])
return 'OK'
@app.route('/', methods=['POST'])
def echo_request():
return request.get_data()
if __name__ == '__main__':
WSGIRequestHandler.protocol_version = "HTTP/1.1"
app.run(host='0.0.0.0', port=80, threaded=True, debug=False)
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/LakeCTF/2024/Quals/rev/Nerfed/r.py | ctfs/LakeCTF/2024/Quals/rev/Nerfed/r.py | class R:
def __init__(s)->None:
s.__r=[0 for _ in range(11)]
def s(s,r,v):
s.__r[r]=v
def g(s,r):
return s.__r[r]
def gh(s):
return s.__r
# Created by pyminifier (https://github.com/liftoff/pyminifier)
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/LakeCTF/2024/Quals/rev/Nerfed/f.py | ctfs/LakeCTF/2024/Quals/rev/Nerfed/f.py | class F:
def __init__(s)->None:
s.__flag=0
def x(s,bit):
s.__flag= s.__flag^(1<<bit)
def s(s,bit,value=1):
if value!=s.gf(bit):
s.x(bit)
def c(s,bit):
s.__flag=s.__flag&~(1<<bit)
def gf(s,bit):
return 1 if s.__flag&(1<<bit)else 0
def gh(s):
return hash(s.__flag)
def gn(s):
return s.__flag
# Created by pyminifier (https://github.com/liftoff/pyminifier)
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/LakeCTF/2024/Quals/rev/Nerfed/main.py | ctfs/LakeCTF/2024/Quals/rev/Nerfed/main.py | #!/usr/bin/env python3
import random
import PIL.Image
import numpy as np
from PIL import Image
import pickle
import secrets
from m import M
from r import R
from t import T
from f import F
def fin():
fl.c(0)
exit("congrats, you can get flag")
def fl_s():
fl.s(1,tb.c_c[rs.g(0),rs.g(1)])
fl.s(13,tb.r_c[rs.g(0),rs.g(1)])
fl.s(14,tb.f_c[rs.g(0),rs.g(1)])
def com(instr):
if fl.gf(2):
return
cur_h=hash((tuple(rs.gh()),fl.gh(),tuple(me.gh().tolist())))
if cur_h==tb.c_h[rs.g(0),rs.g(1)]:
me.s()
try:
instr=instr[rs.g(1)+1:]
except IndexError:
fl.s(2)
rs.s(10,69)
rs.s(tb.r_s[rs.g(0)][0],tb.r_s[rs.g(0)][1])
rs.s(0,1+rs.g(0))
rs.s(1,0)
else:
fl.s(2)
return instr
def fl_c():
cur_num=fl.gn()
if cur_num!=tb.f_h[rs.g(0),rs.g(1)]:
fl.s(2)
def r_c():
cur_h=rs.gh()
if cur_h!=tb.r_h[rs.g(0),rs.g(1)].tolist():
fl.s(2)
def e_c():
if rs.g(10):
fl.s(2)
def start():
if rs.g(0)+rs.g(1)!=0:
fl.s(2)
else:
fl.s(0)
fl.s(1)
def rt():
fl.c(3)
fl.x(4)
fl.c(5)
fl.c(6)
fl.c(7)
fl.c(8)
fl.c(9)
fl.c(10)
fl.c(11)
fl.c(12)
fl.c(13)
fl.c(14)
fl.c(15)
rs.s(6,0)
rs.s(7,0)
rs.s(8,0)
rs.s(9,0)
rs.s(10,0)
def g_t():
try:
if rs.g(rs.g(3))<rs.g(rs.g(4)):
fl.s(12)
except IndexError:
fl.s(2)
def l_i(ins):
rs.s(5,ord(ins))
fl.s(3)
fl.x(5)
def c_i():
fl.s(1)
fl.x(6)
def incr(ins):
rs.s(ord(ins)-9,1+rs.g(ord(ins)-9))
fl.x(7)
def ma(src,dst):
rs.s(dst,rs.g(src))
fl.x(11)
def andd(ins):
try:
rs.s(rs.g(5),rs.g(rs.g(4))&rs.g(ord(ins)-0x20))
except IndexError:
fl.s(2)
def xor(ins):
try:
rs.s(ord(ins)-0x28,rs.g(rs.g(3))^rs.g(rs.g(4)))
except IndexError:
fl.s(2)
def f_t_r(ins):
rs.s(ord(ins)-0x30,fl.gn())
fl.x(10)
def ad(ins):
try:
rs.s(ord(ins)-0x38,rs.g(rs.g(3))+rs.g(rs.g(4)))
except IndexError:
fl.s(2)
fl.x(8)
def l_m(ins):
me.m(tb.masks[ord(ins)-0x01],37*rs.g(2)+rs.g(1))
fl.x(15)
inss=input("What's up ('til newline ofc)? ")
if __name__=="__main__":
fl=F()
me=M()
tb=T()
rs=R()
while True:
if fl.gf(2):
exit()
if rs.g(0)==11:
fin()
fl_s()
try:
ins=inss[rs.g(1)]
except IndexError:
fl.s(2)
if ins=="\x00" and not fl.gf(2):
start()
elif fl.gf(3)and fl.gf(0)and not fl.gf(2):
rs.s(rs.g(5),ord(ins))
fl.c(3)
elif fl.gf(0)and not fl.gf(2):
match ins:
case "\x1d":
ma(7,10)
case "\x01":
rt()
case "\x17":
ma(4,5)
case "\x1a":
ma(8,5)
case "\x02":
g_t()
case "\x15":
ma(3,4)
case "\x16":
ma(4,2)
case ins if ord(ins)<11:
l_i(ins)
case "\x19":
ma(6,4)
case "\x18":
ma(5,7)
case ins if ord(ins)<0x13:
incr(ins)
case "\x13":
ma(0,8)
case "\x1b":
ma(8,10)
case "\x1c":
ma(7,2)
case "\x14":
ma(0,4)
case "\x1e":
ma(9,3)
case "\x1f":
ma(10,8)
case ins if ord(ins)<0x2a:
andd(ins)
case ins if ord(ins)<0x32:
xor(ins)
case ins if ord(ins)<0x3a:
f_t_r(ins)
case ins if ord(ins)<0x42:
ad(ins)
case ins if ord(ins)<253:
l_m(ins)
case "\xff":
c_i()
case _:
fl.s(2)
else:
exit("3735928559")
e_c()
if fl.gf(13):
r_c()
if fl.gf(14):
fl_c()
e_c()
if fl.gf(1):
inss=com(inss)
else:
rs.s(1,1+rs.g(1))
e_c()
# Created by pyminifier (https://github.com/liftoff/pyminifier)
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/LakeCTF/2024/Quals/rev/Nerfed/m.py | ctfs/LakeCTF/2024/Quals/rev/Nerfed/m.py | #!/usr/bin/env python3
import numpy as np
class M:
def __init__(s)->None:
s.__m=np.load("flag.npz")["flag"]
def gh(s):
x_m=np.zeros(s.__m.shape[1],dtype=np.int8)
for i in range(s.__m.shape[0]):
x_m=x_m^s.__m[i]
x_m.flags.writeable=False
return x_m
def s(s):
mask=s.gh()*np.ones(s.__m.shape,dtype=np.int8)
s.__m=s.__m^mask
def m(s,mask,offset):
s.__m=s.__m^ np.roll(mask,offset,axis=1)
def w(s):
return s.__m
# Created by pyminifier (https://github.com/liftoff/pyminifier)
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/LakeCTF/2024/Quals/rev/Nerfed/t.py | ctfs/LakeCTF/2024/Quals/rev/Nerfed/t.py | #!/usr/bin/env python3
import numpy as np
class T:
npz=np.load("tz.npz")
c_c=npz["compute_check"]
c_c.flags.writeable=False
c_h=npz["compute_hash"]
c_h.flags.writeable=False
f_c=npz["flag_check"]
f_c.flags.writeable=False
f_h=npz["flag_hash"]
f_h.flags.writeable=False
r_c=npz["reg_check"]
r_c.flags.writeable=False
r_h=npz["reg_hash"]
r_h.flags.writeable=False
masks=npz["masks"]
masks.flags.writeable=False
r_s=npz["reg_scrable"]
r_s.flags.writeable=False
# Created by pyminifier (https://github.com/liftoff/pyminifier)
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/LakeCTF/2024/Quals/rev/silent_lake/chal.py | ctfs/LakeCTF/2024/Quals/rev/silent_lake/chal.py | #!/usr/bin/env python3
import subprocess
import tempfile
import os
def pns(s: str) -> None:
print(s)
pns("Give me the correct source code.")
source = ""
for line in iter(input, "EOF"):
source += line + "\n"
with tempfile.TemporaryDirectory() as tmpdirname:
with open(os.path.join(tmpdirname, "main.c"), "w") as f:
f.write(source)
subprocess.run(["/codeql/codeql",
"database",
"create",
"--language=c",
"--command=clang -nostdinc -O0 -o " + os.path.join(tmpdirname, "main") + " " + os.path.join(tmpdirname, "main.c"),
os.path.join(tmpdirname, "db")],
stdout = subprocess.DEVNULL,
stderr = subprocess.DEVNULL
)
result = subprocess.run(["/codeql/codeql",
"query",
"run",
"vscode-codeql-starter/codeql-custom-queries-cpp/example.ql",
"-d",
os.path.join(tmpdirname, "db")],
capture_output = True, text=True)
print(result.stdout)
if "correct" in result.stdout:
try:
with open("/flag.txt", "r") as f:
print(f.read())
except:
print("EPFL{local_fake_flag}")
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/LakeCTF/2024/Quals/crypto/wild_signatures/server.py | ctfs/LakeCTF/2024/Quals/crypto/wild_signatures/server.py | #!/usr/bin/env python3
import os
from Crypto.PublicKey import ECC
from Crypto.Signature import eddsa
flag = os.environ.get("FLAG", "EPFL{test_flag}")
msgs = [
b"I, gallileo, command you to give me the flag",
b"Really, give me the flag",
b"can I haz flagg",
b"flag plz"
]
leos_key = ECC.generate(curve='ed25519')
sigs = [ leos_key.public_key().export_key(format='raw') + eddsa.new(leos_key, 'rfc8032').sign(msg) for msg in msgs]
def parse_and_vfy_sig(sig: bytes, msg: bytes):
pk_bytes = sig[:32]
sig_bytes = sig[32:]
pk = eddsa.import_public_key(encoded=pk_bytes)
if pk.pointQ.x == 0:
print("you think you are funny")
raise ValueError("funny user")
eddsa.new(pk, 'rfc8032').verify(msg, sig_bytes)
if __name__ == "__main__":
try:
print("if you really are leo, give me public keys that can verify these signatures")
for msg, sig in zip(msgs, sigs):
print(sig[64:].hex())
user_msg = bytes.fromhex(input())
# first 64 bytes encode the public key
if len(user_msg) > 64 or len(user_msg) == 0:
print("you're talking too much, or too little")
exit()
to_verif = user_msg + sig[len(user_msg):]
parse_and_vfy_sig(to_verif, msg)
print("it's valid")
except ValueError as e:
print(e)
exit()
print(flag)
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/LakeCTF/2024/Quals/crypto/cert/cert.py | ctfs/LakeCTF/2024/Quals/crypto/cert/cert.py | from binascii import hexlify, unhexlify
from Crypto.Util.number import bytes_to_long, long_to_bytes
from precomputed import message, signature, N, e
from flag import flag
if __name__ == "__main__":
print(message + hexlify(long_to_bytes(signature)).decode())
cert = input(" > ")
try:
s = bytes_to_long(unhexlify(cert))
assert(s < N)
if pow(s,e,N)==bytes_to_long("admin".encode()):
print(flag)
else:
print("Not admin")
except:
print("Not admin")
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/LakeCTF/2024/Quals/crypto/cert/precomputed.py | ctfs/LakeCTF/2024/Quals/crypto/cert/precomputed.py | from Crypto.Util.number import bytes_to_long
message = "Sign \"admin\" for flag. Cheers, "
m = 147375778215096992303698953296971440676323238260974337233541805023476001824
N = 128134160623834514804190012838497659744559662971015449992742073261127899204627514400519744946918210411041809618188694716954631963628028483173612071660003564406245581339496966919577443709945261868529023522932989623577005570770318555545829416559256628409790858255069196868638535981579544864087110789571665244161
e = 65537
signature = 20661001899082038314677406680643845704517079727331364133442054045393583514677972720637608461085964711216045721340073161354294542882374724777349428076118583374204393298507730977308343378120231535513191849991112740159641542630971203726024554641972313611321807388512576263009358133517944367899713953992857054626
assert(m == bytes_to_long(message.encode()))
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/LakeCTF/2024/Quals/crypto/hsb_2.2/challenge.py | ctfs/LakeCTF/2024/Quals/crypto/hsb_2.2/challenge.py | # Thanks to _MH_ for the code
from Crypto.PublicKey import RSA
from inspect import signature
from secrets import choice
import os
RSA_LEN = 256
TYPE_USER = b"\x01"
TYPE_INTERNAL = b"\x02"
SECRET = os.getenv("flag", "EPFL{not_the_flag}").encode()
def b2i(b: bytes) -> int:
return int.from_bytes(b, "big")
def i2b(i: int) -> bytes:
return i.to_bytes((i.bit_length() + 7) // 8, "big")
def get_random_bytes(l: int):
alph = list(range(1, 256))
return b"".join([bytes([choice(alph)]) for _ in range(l)])
def pad(p: bytes) -> bytes:
return get_random_bytes(RSA_LEN - len(p) - 2) + b"\x00" + p
def unpad(p: bytes) -> bytes:
pad_end = 1
while pad_end < len(p) and p[pad_end] != 0:
pad_end += 1
return p[pad_end + 1 :]
class HSM:
def __init__(self):
self.vendor = "Cybersecurity Competence Center"
self.model = "Perfection v2.2"
self.rsa = None
self.running = False
def info(self):
print(f"Vendor: {self.vendor}\nModel: {self.model}")
def stop(self):
if not self.running:
print("HSM is already stopped.")
return
self.running = False
def gen_key(self):
bits = RSA_LEN * 8
self.rsa = RSA.generate(bits)
print(f"Generated new RSA-{bits} keys")
# def sign(self, m: int):
# m_pad = int.from_bytes(pad(i2b(m)), "big")
# sig = pow(m_pad, self.rsa.d, self.rsa.n)
# print(f"Signature: {sig}")
def verify(self, sig: int, m: int):
recovered = b2i(
unpad(pow(sig, self.rsa.e, self.rsa.n).to_bytes(RSA_LEN, "big"))
)
if recovered == m:
print("Valid signature.")
else:
print("Invalid signature.")
def _enc(self, m: bytes):
c = pow(int.from_bytes(pad(m), "big"), self.rsa.e, self.rsa.n)
print(f"Ciphertext: {c}")
def enc(self, m: int):
self._enc(TYPE_USER + i2b(m))
def dec(self, c: int):
m = unpad(pow(c, self.rsa.d, self.rsa.n).to_bytes(RSA_LEN, "big"))
t, m = m[:1], b2i(m[1:])
if t == TYPE_USER:
print(f"Plaintext: {m}")
else:
print("Cannot decrypt internal secrets")
def export_secret(self):
self._enc(TYPE_INTERNAL + SECRET)
def run(self):
self.running = True
options = [
self.info,
self.stop,
self.gen_key,
# self.sign,
self.verify,
self.enc,
self.dec,
self.export_secret,
]
while self.running:
print("Available operations:")
for i, opt in enumerate(options):
print(f"\t[{i}] {opt.__name__}")
print()
try:
opt = int(input("Enter selected option: "))
print()
if opt > 2 and not self.rsa:
print("No RSA key available. Use gen_key() first.")
else:
fn = options[opt]
args = []
for i in range(len(signature(fn).parameters)):
try:
args.append(int(input(f"input {i}: ")))
except ValueError as e:
print("Invalid input format, must be integer")
raise e
fn(*args)
except (ValueError, IndexError):
print("Invalid option")
pass
print()
if __name__ == "__main__":
HSM().run()
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/LakeCTF/2024/Quals/crypto/circuits/challenge.py | ctfs/LakeCTF/2024/Quals/crypto/circuits/challenge.py | from Crypto.Random import random
import os
B = 12
def and_gate(a, b):
return a & b
def or_gate(a, b):
return a | b
def xor_gate(a, b):
return a ^ b
def not_gate(a, x):
return ~a & 1
def rand_circuit(size: int, input_size: int, output_size):
circ_gates = [or_gate, not_gate, xor_gate, and_gate]
assert size > 0 and input_size > 0 and output_size > 0
assert output_size + size <= input_size and (input_size - output_size) % size == 0
dec = (input_size - output_size) // size
gates = []
for iteration in range(1, size + 1):
gate_level = []
c_size = input_size - dec * iteration
for i in range(c_size):
gate_level.append(
(random.choice(circ_gates),
(i,
random.randint(0, c_size + dec - 1))))
gates.append(gate_level)
return gates
def eval_circuit(gates, inp):
assert len(gates) >= 1
for level in gates:
new_inp = []
for gate, (i1, i2) in level:
new_inp.append(gate(inp[i1], inp[i2]))
inp = new_inp
return inp
def i2b(i):
return list(map(int, bin(i)[2:].zfill(B)))
def b2i(b):
return int(''.join(map(str, b)), 2)
SIZE = int(input("What circuit size are you interested in ?"))
assert 3 <= SIZE <= B - 1
correct = 0
b = random.getrandbits(1)
p = rand_circuit(SIZE, B, B - SIZE)
keys = set()
while correct < 32:
input_func = random.getrandbits(B)
choice = int(input(f"[1] check bit\n[2] test input\n"))
if choice == 1:
assert int(input("bit: ")) == b
b = random.getrandbits(1)
p = rand_circuit(SIZE, B, B - SIZE)
keys = set()
correct += 1
else:
i = int(input(f"input: "))
if i in keys or len(keys) > 7 or not 0 <= i <= 2 ** B:
print("uh uh no cheating")
exit()
keys.add(i)
if b == 0:
res = random.getrandbits(B - SIZE)
else:
res = b2i(eval_circuit(p, i2b(i)))
print(f"res = {res}")
print("well done !!")
print(os.getenv("flag",b"EPFL{fake_flag}"))
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/LakeCTF/2023/Quals/pwn/trustMEE/exploit_template.py | ctfs/LakeCTF/2023/Quals/pwn/trustMEE/exploit_template.py | from pwn import *
import hashlib
import re
import base64
def upload(r, bytes, outfile_path):
r.sendline(f"touch {outfile_path}.b64".encode())
b64_data = base64.b64encode(bytes)
for i in range(0, len(b64_data), 256):
chunk = b64_data[i:i + 256]
r.sendline(f'echo -n {chunk.decode()} >> {outfile_path}.b64'.encode())
r.sendline(f'base64 -d {outfile_path}.b64 > {outfile_path}')
def pow_solver(prefix, difficulty):
zeros = '0' * difficulty
def is_valid(digest):
bits = ''.join(bin(i)[2:].zfill(8) for i in digest)
return bits[:difficulty] == zeros
i = 0
while True:
i += 1
s = prefix + str(i)
if is_valid(hashlib.sha256(s.encode()).digest()):
return str(i)
import sys
print(sys.argv)
if len(sys.argv) < 3:
host = "127.0.0.1"
port = "9002"
else:
host = sys.argv[1]
port = int(sys.argv[2])
r = remote(host, port)
recv_data = r.recvuntil(b">").decode()
prefix = re.findall(r'\[\*\] prefix: ([0-9A-Za-z]+)\n', recv_data)[0]
difficulty = int(re.findall(r'\[\*\] difficulty: ([0-9]+)\n', recv_data)[0])
print("difficulty;", difficulty)
print("prefix:", prefix)
answer = pow_solver(prefix, difficulty)
print("answer:", answer)
r.sendline(answer.encode())
r.recvuntil(b"execution environment")
# TODO
r.interactive()
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/LakeCTF/2023/Quals/crypto/KeySharer/chal.py | ctfs/LakeCTF/2023/Quals/crypto/KeySharer/chal.py | #!/usr/bin/env -S python3 -u
import os
from Crypto.Util.number import isPrime, bytes_to_long
from Crypto.Random.random import randrange
class Point:
def __init__(self,x,y,curve, isInfinity = False):
self.x = x % curve.p
self.y = y % curve.p
self.curve = curve
self.isInfinity = isInfinity
def __add__(self,other):
return self.curve.add(self,other)
def __mul__(self,other):
return self.curve.multiply(self,other)
def __rmul__(self,other):
return self.curve.multiply(self,other)
def __str__(self):
return f"({self.x},{self.y})"
def __eq__(self, other):
return self.x == other.x and self.y == other.y and self.curve == other.curve
class Curve:
def __init__(self,a,b,p):
if (4*pow(a,3,p)+27*pow(b,2,p)) %p == 0:
print("Error : 4a^3+27b^2 = 0")
quit()
if p < 1 or not isPrime(p):
print("p needs to be prime ")
quit()
self.a = a%p
self.b = b%p
self.p = p
def multiply(self, P:Point, k:int) -> Point:
Q = P
R = Point(0,0,self,isInfinity=True)
while k > 0 :
if (k & 1) == 1:
R = self.add(R,Q)
Q = self.add(Q,Q)
k >>= 1
return R
def find_y(self,x):
# p is 3 mod 4 in NIST-192-P so easy to find y
x = x % self.p
y_squared = (pow(x, 3, self.p) + self.a * x + self.b) % self.p
assert pow(y_squared, (self.p - 1) // 2, self.p) == 1, "The x coordinate is not on the curve"
y = pow(y_squared, (self.p + 1) // 4, self.p)
assert pow(y,2,self.p) == (pow(x, 3, self.p) + self.a * x + self.b) % self.p
return y
def add(self,P: Point, Q : Point) -> Point:
if P.isInfinity:
return Q
elif Q.isInfinity:
return P
elif P.x == Q.x and P.y == (-Q.y) % self.p:
return Point(0,0,self,isInfinity=True)
if P.x == Q.x and P.y == Q.y:
param = ((3*pow(P.x,2,self.p)+self.a) * pow(2*P.y,-1,self.p))
else:
param = ((Q.y - P.y) * pow(Q.x-P.x,-1,self.p))
Sx = (pow(param,2,self.p)-P.x-Q.x)%self.p
Sy = (param * ((P.x-Sx)%self.p) - P.y) % self.p
return Point(Sx,Sy,self)
p = 0xfffffffffffffffffffffffffffffffeffffffffffffffff
a = 0xfffffffffffffffffffffffffffffffefffffffffffffffc
b = 0x64210519e59c80e70fa7e9ab72243049feb8deecc146b9b1
curve = Curve(a,b,p)
flag = os.getenv("flag","EPFL{fake_flag}")
flag = bytes_to_long(flag.encode())
G = Point(flag,curve.find_y(flag),curve)
PK = randrange(1,p)
pub = PK * G
print(f"""Welcome to KeySharer™ using that good old NIST 192-P
=============================================
Alice wants to share her public key with you so that you both can have multiple shared secret keys !
Alice's public key is {pub}
Now send over yours !
""")
for i in range(4):
your_pub_key_x = int(input(f"Gimme your pub key's x : \n"))
your_pub_key_y = int(input(f"Gimme your pub key's y : \n"))
your_pub_key = Point(your_pub_key_x,your_pub_key_y,curve)
shared_key = your_pub_key * PK
print(f"The shared key is\n {shared_key}")
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/LakeCTF/2023/Quals/crypto/Vigenere_CBC/vigenere.py | ctfs/LakeCTF/2023/Quals/crypto/Vigenere_CBC/vigenere.py | import secrets
SHIFT = 65
MOD = 26
BLOCKLENGTH = 20
def add(block1,block2):
assert(len(block1)<= len(block2))
assert(len(block2)<= BLOCKLENGTH)
b1upper = block1.upper()
b2upper = block2.upper()
b1 = [ ord(b1upper[i])-SHIFT for i in range(len(block1))]
b2 = [ ord(b2upper[i])-SHIFT for i in range(len(block1))]
s = [ (b1[i] + b2[i]) % MOD for i in range(len(block1))]
slist = [ chr(s[i]+SHIFT) for i in range(len(block1))]
sum = ''.join(slist)
return(sum)
def sub(block1,block2):
assert(len(block1)<= len(block2))
assert(len(block2)<= BLOCKLENGTH)
b1upper = block1.upper()
b2upper = block2.upper()
b1 = [ ord(b1upper[i])-SHIFT for i in range(len(block1))]
b2 = [ ord(b2upper[i])-SHIFT for i in range(len(block1))]
s = [ (b1[i] - b2[i]) % MOD for i in range(len(block1))]
slist = [ chr(s[i]+SHIFT) for i in range(len(block1))]
sum = ''.join(slist)
return(sum)
def get_blocks(s):
blocks = []
i = 0
while(i + BLOCKLENGTH<len(s)):
blocks.append(s[i:i+BLOCKLENGTH])
i = i + BLOCKLENGTH
blocks.append(s[i:len(s)])
return(blocks)
def random_block():
l = []
for _ in range (BLOCKLENGTH):
l.append(chr(secrets.randbelow(MOD)+SHIFT))
b= ''.join(l)
return(b)
def vigenere_enc(block,key):
return(add(block,key))
def vigenere_dec(block,key):
return(sub(block,key))
def keygen():
return(random_block())
def get_iv():
return(random_block())
def vigenere_cbc_enc(message, key):
blocks = get_blocks(message)
ctxt = get_iv()
for b in blocks:
to_enc = add(b,ctxt[len(ctxt)-BLOCKLENGTH:len(ctxt)])
ctxt = ctxt + vigenere_enc(to_enc,key)
return(ctxt)
def vigenere_cbc_dec(ctxt, key):
blocks = get_blocks(ctxt)
ptxt = ""
for i in range(1,len(blocks)):
sum = vigenere_dec(blocks[i],key)
ptxt = ptxt + sub(sum,ctxt[(i-1)*BLOCKLENGTH:(i)*BLOCKLENGTH])
return(ptxt)
def read_flag():
f = open("flag.txt","r")
flag = f.read()
f.close()
return(flag)
if __name__ == "__main__":
KEY = keygen()
FLAGTEXT = read_flag()
CTXT = vigenere_cbc_enc(FLAGTEXT,KEY)
PTXT = vigenere_cbc_dec(CTXT,KEY)
assert(PTXT == FLAGTEXT)
print(CTXT)
#Output: AFCNUUOCGIFIDTRSBHAXVHZDRIEZMKTRPSSXIBXCFVVNGRSCZJLZFXBEMYSLUTKWGVVGBJJQDUOXPWOFWUDHYJSMUYMCXLXIWEBGYAGSTYMLPCJEOBPBOYKLRDOJMHQACLHPAENFBLPABTHFPXSQVAFADEZRXYOXQTKUFKMSHTIEWYAVGWWKKQHHBKTMRRAGCDNJOUGBYPOYQQNGLQCITTFCDCDOTDKAXFDBVTLOTXRKFDNAJCRLFJMLQZJSVWQBFPGRAEKAQFUYGXFJAWFHICQODDTLGSOASIWSCPUUHNLAXMNHZOVUJTEIEEJHWPNTZZKXYSMNZOYOVIMUUNXJFHHOVGPDURSONLLUDFAGYGWZNKYXAGUEEEGNMNKTVFYZDIQZPJKXGYUQWFPWYEYFWZKUYUTXSECJWQSTDDVVLIYXEYCZHYEXFOBVQWNHUFHHZBAKHOHQJAKXACNODTQJTGC
#Flag has length 70 and is uppercase english without punctuation nor spaces. Please wrap it in EPFL{...} for submission
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/LakeCTF/2023/Quals/crypto/Choices/choices.py | ctfs/LakeCTF/2023/Quals/crypto/Choices/choices.py | import random, string
flag = ''.join(random.SystemRandom().sample(string.ascii_letters, 32))
print(f"EPFL{{{flag}}}")
open("output.txt", "w").write(''.join(random.choices(flag, k=10000)))
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/LakeCTF/2023/Quals/web/Cyber_Library/serve.py | ctfs/LakeCTF/2023/Quals/web/Cyber_Library/serve.py | from web import create_app
if __name__ == '__main__':
app = create_app()
app.run(host='0.0.0.0', port=8080, debug=False) | python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/LakeCTF/2023/Quals/web/Cyber_Library/web/user.py | ctfs/LakeCTF/2023/Quals/web/Cyber_Library/web/user.py | from flask_login import UserMixin
class User(UserMixin):
def __init__(self, id):
self.id = id
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/LakeCTF/2023/Quals/web/Cyber_Library/web/main.py | ctfs/LakeCTF/2023/Quals/web/Cyber_Library/web/main.py | from flask import Blueprint, abort, current_app
from flask import flash, render_template, redirect, url_for, request
from flask_cors import cross_origin
from flask_login import login_user, current_user
import os
import time
import validators
from . import admin_token, sock, limiter, q, User
from .bot import visit
ORIGINS = ["http://chall.polygl0ts.ch:9010", "http://web:8080"]
main = Blueprint('main', __name__)
@main.route('/')
def index():
return render_template('index.html')
@main.route('/collection')
def collection():
return render_template('collection.html')
@main.route('/viewer')
def viewer():
return render_template('viewer.html', is_admin=current_user.is_authenticated)
@main.route('/submit', methods=['POST'])
@limiter.limit("2/2 minute")
def submit():
url = request.form['url']
if validators.url(url):
try:
q.enqueue(visit, url, admin_token)
flash("Thank you, a librarian will index your document shortly.", "success")
except Exception as e:
print(e)
flash("Error submitting document", "danger")
else:
flash("Invalid URL", "danger")
return redirect(url_for('main.index'))
@main.route('/admin/login', methods=['GET'])
def login():
if request.args.get('token') == admin_token:
login_user(User('admin'))
flash("You are now logged in.", "success")
return redirect(url_for('main.index'))
else:
abort(403)
@sock.route('/ws', bp=main)
@limiter.limit("2/2 minute")
@cross_origin(origins=ORIGINS)
def ws_handler(ws):
while True:
try:
ws.send(current_app.counter)
time.sleep(5)
except:
break
try:
ws.close()
except:
pass
@sock.route('/admin/ws', bp=main)
@cross_origin(origins=ORIGINS)
def admin_ws_handler(ws):
# Authenticate socket with Flask-Login
# https://flask-socketio.readthedocs.io/en/latest/implementation_notes.html#using-flask-login-with-flask-socketio
if current_user.is_authenticated:
print('authenticated')
while True:
command = ws.receive()
if command == 'increment':
current_app.counter += 1
ws.send('updated')
elif command == 'flag':
ws.send(os.getenv('FLAG') or 'flag{flag_not_set}')
else:
break
else:
ws.send('Not Authenticated')
ws.close()
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/LakeCTF/2023/Quals/web/Cyber_Library/web/__init__.py | ctfs/LakeCTF/2023/Quals/web/Cyber_Library/web/__init__.py | from flask import Flask, render_template
from flask_cors import CORS
from flask_limiter import Limiter
from flask_limiter.util import get_remote_address
from flask_login import LoginManager, UserMixin
from flask_sock import Sock
from redis import Redis
from rq import Queue
from werkzeug.exceptions import HTTPException
import secrets
import os
limiter = Limiter(key_func=get_remote_address)
q = Queue(connection=Redis.from_url('redis://redis:6379'))
admin_token = os.getenv('ADMIN_TOKEN') or secrets.token_hex()
sock = Sock()
class User(UserMixin):
def __init__(self, id):
self.id = id
def handle_error(e):
code = 500
if isinstance(e, HTTPException):
code = e.code
return render_template('error.html', e=e), code
def create_app():
app = Flask(__name__)
CORS(app)
app.config['SECRET_KEY'] = os.getenv('SECRET_KEY') or secrets.token_hex()
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///db.sqlite'
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
app.config["TEMPLATES_AUTO_RELOAD"] = True
app.register_error_handler(Exception, handle_error)
limiter.init_app(app)
login_manager = LoginManager()
login_manager.init_app(app)
@login_manager.user_loader
def load_user(user_id):
if user_id == 'admin':
return User('admin')
@app.after_request
def add_header(response):
response.headers["Content-Security-Policy"] = "default-src 'none'; script-src 'self'; frame-src *; style-src 'self'; font-src 'self' https://*.epfl.ch; img-src * data:; connect-src 'self'"
response.headers["X-Frame-Options"] = "DENY"
return response
from .main import main as main_blueprint
app.register_blueprint(main_blueprint)
sock.init_app(app)
app.counter = 1337
return app
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/LakeCTF/2023/Quals/web/Cyber_Library/web/bot.py | ctfs/LakeCTF/2023/Quals/web/Cyber_Library/web/bot.py | from playwright.sync_api import sync_playwright
from time import sleep
import sys
def visit(url, admin_token):
print("Visiting", url, file=sys.stderr)
with sync_playwright() as p:
# Launch a headless browser with custom Firefox preferences
browser = p.firefox.launch(
headless=True,
# Make sure we don't get hacked this time
firefox_user_prefs={
# Prevent potential IP leaks by disabling WebRTC.
"media.peerconnection.enabled": False,
# Set a common User-Agent to avoid being identified as a bot or Playwright browser.
# Note: This can also be set via the context, but it's shown here as a demonstration.
"general.useragent.override": "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:91.0) SecureBrowser/9001.0 FortressEdition/42.0 SafeFox/1337.0",
# Block all 3rd party cookies and trackers.
"network.cookie.cookieBehavior": 4,
# Enforce content security policies.
"security.csp.enable": True,
# Increase privacy by disabling DOM storage.
"dom.storage.enabled": False,
# Disable unnecessary plugins to prevent fingerprinting.
"plugin.scan.plid.all": False,
# Disable images for faster loading if not needed. (Note: This can also be achieved using Playwright's routing)
"permissions.default.image": 2,
# Prevent the browser from sending the referrer in the HTTP headers.
"network.http.sendRefererHeader": 0
}
)
page = browser.new_page()
page.set_default_timeout(3000)
# Visit the desired URLs
page.goto(f'http://web:8080/admin/login?token={admin_token}')
page.goto('about:blank')
page.goto(f'http://web:8080/viewer#{url}')
sleep(4)
browser.close()
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/LakeCTF/2025/Quals/pwn/stackception_2/chall.py | ctfs/LakeCTF/2025/Quals/pwn/stackception_2/chall.py | #!/usr/bin/env -S python3 -u
import os
import subprocess as sp
from textwrap import dedent
def main():
msg = dedent(
"""
Enter assembly code
Note: replace spaces with underscores, newlines with '|', e.g.,
main:
push 5
call main
becomes 'main:|push_5|call_main'
"""
).strip()
print(msg)
asm_code = input()
input_path = "/tmp/input.asm"
with open(input_path, "w") as f:
f.write(asm_code.replace("_", " ").replace("|", "\n"))
output_path = "/tmp/out.bin"
p = sp.Popen(
# Adjust path if running locally
["/app/stackception-asm", input_path, output_path],
stdin=sp.DEVNULL,
stdout=sp.DEVNULL,
stderr=sp.PIPE,
)
p.wait(timeout=5)
if p.returncode != 0:
print("Assembly failed:")
_, stderr = p.communicate()
print(stderr.decode())
exit(1)
# Adjust path if running locally
os.execv("/app/stackception", ["/app/stackception", output_path])
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/LakeCTF/2025/Quals/pwn/stackception_1/chall.py | ctfs/LakeCTF/2025/Quals/pwn/stackception_1/chall.py | #!/usr/bin/env -S python3 -u
import os
import subprocess as sp
from textwrap import dedent
def main():
msg = dedent(
"""
Enter assembly code
Note: replace spaces with underscores, newlines with '|', e.g.,
main:
push 5
call main
becomes 'main:|push_5|call_main'
"""
).strip()
print(msg)
asm_code = input()
input_path = "/tmp/input.asm"
with open(input_path, "w") as f:
f.write(asm_code.replace("_", " ").replace("|", "\n"))
output_path = "/tmp/out.bin"
p = sp.Popen(
# Adjust path if running locally
["/app/stackception-asm", input_path, output_path],
stdin=sp.DEVNULL,
stdout=sp.DEVNULL,
stderr=sp.PIPE,
)
p.wait(timeout=5)
if p.returncode != 0:
print("Assembly failed:")
_, stderr = p.communicate()
print(stderr.decode())
exit(1)
# Adjust path if running locally
os.execve(
"/app/stackception",
["/app/stackception", output_path],
{
"GLIBC_TUNABLES": "glibc.cpu.hwcaps=-ACPI,-ADX,AES,AESKLE,-AMD_IBPB,"
+ "-AMD_IBRS,-AMD_SSBD,-AMD_STIBP,-AMD_VIRT_SSBD,-AMX_BF16,"
+ "-AMX_COMPLEX,-AMX_FP16,-AMX_INT8,-AMX_TILE,-APIC,-APX_F,"
+ "-ARCH_CAPABILITIES,-AVX,-AVX10,-AVX10_XMM,-AVX10_YMM,-AVX10_ZMM,"
+ "-AVX2,-AVX512BW,-AVX512CD,-AVX512DQ,-AVX512ER,-AVX512F,-AVX512PF,"
+ "-AVX512VL,-AVX512_4FMAPS,-AVX512_4VNNIW,-AVX512_BF16,-AVX512_BITALG,"
+ "-AVX512_FP16,-AVX512_IFMA,-AVX512_VBMI,-AVX512_VBMI2,-AVX512_VNNI,"
+ "-AVX512_VP2INTERSECT,-AVX512_VPOPCNTDQ,-AVX_IFMA,-AVX_NE_CONVERT,"
+ "-AVX_VNNI,-AVX_VNNI_INT8,-BMI1,-BMI2,-CLDEMOTE,-CLFLUSHOPT,-CLFSH,"
+ "-CLWB,CMOV,CMPCCXADD,CMPXCHG16B,-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3,-SSE4A,"
+ "-SSE4_1,-SSE4_2,-SSSE3,-STIBP,-SVM,-SYSCALL_SYSRET,-TBM,-TM,-TM2,"
+ "-TRACE,-TSC,-TSC_ADJUST,-TSC_DEADLINE,-TSXLDTRK,-UINTR,-UMIP,"
+ "-VAES,-VME,-VMX,-VPCLMULQDQ,-WAITPKG,-WBNOINVD,-WIDE_KL,-X2APIC,"
+ "-XFD,-XGETBV_ECX_1,-XOP,XSAVE,XSAVEC,-XSAVEOPT,-XSAVES,"
+ "-XTPRUPDCTRL:glibc.cpu.hwcaps_mask=all"
},
)
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/LakeCTF/2025/Quals/crypto/Guess_Flag/Guessflag.py | ctfs/LakeCTF/2025/Quals/crypto/Guess_Flag/Guessflag.py | #!/usr/bin/env -S python3 -u
flag = "00000000000000000000000000000000"
print("Don't even think to guess the flag by brute force, it is 32 digits long!")
user_input = input()
if not user_input.isdigit():
print("Flag only contains digits!")
exit()
index = 0
for char in user_input:
if char != flag[index]:
print("Wrong flag!")
exit()
index += 1
print("Correct flag!")
print("flag is : EPFL{" +user_input + "}") | python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/LakeCTF/2025/Quals/crypto/The_Phantom_Menace/chall.py | ctfs/LakeCTF/2025/Quals/crypto/The_Phantom_Menace/chall.py | import numpy as np
import json
try:
from flag import flag
except:
flag = "redacted_this_is_just_so_that_it_works_and_you_can_test_locally."
m_b = np.array([int(c) for char in flag for c in format(ord(char), '08b')])
# Parameters
q = 3329
n = 512
k = 4
f = np.array([1] + [0]*(n-1) + [1])
assert len(m_b)==n
# ---------- Helper functions ----------
def _small_noise(n, weight=2):
coeffs = np.zeros(n, dtype=int)
idx = np.random.choice(n, size=weight, replace=False)
signs = np.random.choice([-1, 1], size=weight)
coeffs[idx] = signs
return coeffs
def _vec_poly_mul(v0, v1):
def _poly_mul(a, b):
res = np.convolve(a, b)
for i in range(n, len(res)):
res[i - n] = (res[i - n] - res[i]) % q
return res[:n] % q
return sum((_poly_mul(a, b) for a, b in zip(v0, v1))) % q
def encrypt(A, t, m_b, r, e_1, e_2):
A_T = list(map(list, zip(*A)))
u = np.array([(mat + err) % q for mat, err in
zip([_vec_poly_mul(row, r) for row in A_T], e_1)
])
tr = _vec_poly_mul(t, r)
m = (m_b * ((q + 1)//2)) % q
v = (tr + e_2 + m) % q
return u, v
# ---------- Key generation ----------
A = np.array([np.array([np.random.randint(0, q, n) for _ in range(k)]) for _ in range(k)])
s = np.array([_small_noise(n, n*2//3) for _ in range(k)])
e = np.array([_small_noise(n) for _ in range(k)])
t = np.array([(_vec_poly_mul(row, s) + err) % q for row, err in zip(A, e)])
# ---------- Encryption -------------
r = [_small_noise(n) for _ in range(k)]
e_1 = [_small_noise(n) for _ in range(k)]
e_2 = _small_noise(n)
u, v = encrypt(A, t, m_b, r, e_1, e_2)
# ---------- Saving key ---------------
keys = {
"s":s.tolist(),
"u":u.tolist(),
"v":v.tolist()
}
with open("keys.json", "w") as f:
f.write(json.dumps(keys))
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/LakeCTF/2025/Quals/crypto/Attack_of_the_Clones/chall.py | ctfs/LakeCTF/2025/Quals/crypto/Attack_of_the_Clones/chall.py | import numpy as np
import json
try:
from flag import flag
except:
flag = "redacted_this_is_just_so_that_it_works_and_you_can_test_locally."
m_b = np.array([int(c) for char in flag for c in format(ord(char), '08b')])
# Parameters
q = 3329
n = 512
k = 4
f = np.array([1] + [0]*(n-1) + [1])
assert len(m_b)==n
# ---------- Helper functions ----------
def _small_noise(n, weight=2):
coeffs = np.zeros(n, dtype=int)
idx = np.random.choice(n, size=weight, replace=False)
signs = np.random.choice([-1, 1], size=weight)
coeffs[idx] = signs
return coeffs
def _vec_poly_mul(v0, v1):
def _poly_mul(a, b):
res = np.convolve(a, b)
for i in range(n, len(res)):
res[i - n] = (res[i - n] - res[i]) % q
return res[:n] % q
return sum((_poly_mul(a, b) for a, b in zip(v0, v1))) % q
def encrypt(A, t, m_b, r, e_1, e_2):
u = np.array([(mat + err) % q for mat, err in
zip([_vec_poly_mul(row, r) for row in A.T], e_1)
])
tr = _vec_poly_mul(t, r)
m = (m_b * ((q + 1)//2)) % q
v = (tr + e_2 + m) % q
return u, v
# ---------- Key generation ----------
A_1 = np.array([np.array([np.random.randint(0, q, n) for _ in range(k)]) for _ in range(k)])
A_2 = np.array([np.array([np.random.randint(0, q, n) for _ in range(k)]) for _ in range(k)])
s_1 = np.array([_small_noise(n, n*2//3) for _ in range(k)])
s_2 = np.array([_small_noise(n, n*2//3) for _ in range(k)])
e = np.array([_small_noise(n) for _ in range(k)])
t_1 = np.array([(_vec_poly_mul(row, s_1) + err) % q for row, err in zip(A_1, e)])
t_2 = np.array([(_vec_poly_mul(row, s_2) + err) % q for row, err in zip(A_2, e)])
# ---------- Encryption ----------
r = [_small_noise(n) for _ in range(k)]
e_1 = [_small_noise(n) for _ in range(k)]
e_2 = _small_noise(n)
u_1, v_1 = encrypt(A_1, t_1, m_b, r, e_1, e_2)
u_2, v_2 = encrypt(A_2, t_2, m_b, r, e_1, e_2)
# ---------- Giving keys to user ---------------
keys = {
"A_1" : A_1.tolist(),
"t_1" : t_1.tolist(),
"A_2" : A_2.tolist(),
"t_2" : t_2.tolist(),
"u_1" : u_1.tolist(),
"u_2" : u_2.tolist(),
"v_1" : v_1.tolist(),
"v_2" : v_2.tolist()
}
with open("keys.json", "w") as f:
f.write(json.dumps(keys))
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/LakeCTF/2025/Quals/crypto/Quantum_vernam/chall.py | ctfs/LakeCTF/2025/Quals/crypto/Quantum_vernam/chall.py | #!/usr/bin/env -S python3 -u
import os
import numpy as np
from math import sqrt
# no need quantum libraries here, only linear algebra.
from scipy.stats import unitary_group
def string_to_bits(s):
bits = []
for byte in s:
for i in range(8):
bits.append((byte >> (7 - i)) & 1)
return bits
def bit_to_qubit(bit):
if bit == 0:
return np.array([1,0]) # |0>
else:
return np.array([0, 1]) # |1>
def encryption(key, message,gate1,gate2,x):
key_bits = string_to_bits(key)
message_bits = string_to_bits(message)
cipher = []
encryption_matrix = np.array([])
PauliX = np.array([(0,1), (1,0)])
PauliZ = np.array([(1,0), (0,-1)])
for k, m in zip(key_bits, message_bits):
qubit = bit_to_qubit(m)
qubit = gate1 @ qubit
if k == 1:
qubit = x @ qubit
qubit = gate2 @ qubit
cipher.append(qubit)
return cipher
def measurement(cipher):
measured_bits = []
for qubit in cipher:
prob_0 = qubit[0]*qubit[0].conjugate()
if np.random.rand() < prob_0:
measured_bits.append(0)
else:
measured_bits.append(1)
return measured_bits
def bits_to_string(bits):
bytes_list = []
for i in range(0, len(bits), 8):
byte = 0
for j in range(8):
byte = (byte << 1) | bits[i + j]
bytes_list.append(byte)
return bytes(bytes_list)
####################################################################################
FLAG = b"EPFL{FAKEFLAAAAAAAG}}"
n = len(FLAG)
key = os.urandom(n)
x = unitary_group.rvs(2)
print("Welcome to the Quantum Vernam Cipher Encryption! Key and flag have same length, try to break perfect secrecy if you can.")
print("\n")
print('The qubits will be encrypted with the matrix x = ',x)
print("\n")
print("You can apply any gate you want to the qubits before and after measurement as a 2X2 matrix, choose your favorite one :)")
print("\n")
print("Also pls remember that in python, j is the imaginary unit, not i.")
print('\n')
print('Enter coefficients for the first matrix that will be applied BEFORE encryption:')
print('Enter first matrix element:')
a1 = complex(input())
print('Enter second matrix element:')
b1 = complex(input())
print('Enter third matrix element:')
c1 = complex(input())
print('Enter fourth matrix element:')
d1 = complex(input())
gate1 = np.array([(a1,b1),(c1,d1)])
print('\n')
print('Enter coefficients for the second matrix that will be applied AFTER encryption:')
print('Enter first matrix element:')
a2 = complex(input())
print('Enter second matrix element:')
b2 = complex(input())
print('Enter third matrix element:')
c2 = complex(input())
print('Enter fourth matrix element:')
d2 = complex(input())
gate2 = np.array([(a2,b2),(c2,d2)])
# vérifie que les matrices sont unitaires
def is_unitary(matrix):
identity = np.eye(matrix.shape[0])
return np.allclose(matrix.conj().T @ matrix, identity)
assert is_unitary(gate1), "Gate 1 is not unitary!"
assert is_unitary(gate2), "Gate 2 is not unitary!"
cipher = encryption(key, FLAG,gate1,gate2,x)
measurement_result = measurement(cipher)
print("measurement:", measurement_result)
print(bits_to_string(measurement_result))
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/LakeCTF/2025/Quals/crypto/Ez_Part/chall.py | ctfs/LakeCTF/2025/Quals/crypto/Ez_Part/chall.py | #!/usr/bin/env python3
import string
from flask import Flask, request, jsonify
import hashlib
import random
import os
from Crypto.Util.number import getPrime, isPrime, bytes_to_long
from default_vals import masks
app = Flask(__name__)
BITS = 1535
def gen_p(BITS):
while True:
q = getPrime(BITS - 150)
p = q << 150 + 1
if isPrime(p):
return p
try:
from default_vals import masks,p,flag
except:
# format is (hex_str, int)
# Each mask selects 80 random bits from a cluster of ~200 bits
masks: list[tuple[str,int]] = []
# Prime is different on the server but both generated by
# p = gen_p(BITS)
p = 1732375678348793163110979624583189918791211347874570063077747228871780679837312679884703658887914365969404158603484185079982598145035362799209646932685520475588628009679552144657804894178808188015838257707147507885403108840475984682027682697255610433385306893786350792445042471333672111078427931663022180180037950193762885807473428197371729778595450783535441462358215336078627581208438522699070134974814274127945312368169334436503982185460769011058116257367719937
flag = "EPFL{fakeflag}"
a = 3
users_db = {}
def hash_value(value):
return hashlib.sha256(str(value).encode()).hexdigest()
def verify(x, b, hashes):
s = ""
# Verify discrete log
computed_b = pow(a, x, p)
if computed_b != b:
s += f"Wrong b: {b}\n"
# Verify mask hashes
for idx in range(len(masks)):
hex_val, shift = masks[idx]
mask = int(hex_val, 16) << shift
masked_value = x & mask
computed_hash = hash_value(masked_value)
if computed_hash != hashes[idx]:
s += f"Wrong mask : {idx},{hashes[idx]}\n"
if s == "":
return True, "Valid password"
else:
return False, s
def register_user(username, x):
b = pow(a, x, p)
mask_hashes = []
for (hex_val, shift) in masks:
mask = int(hex_val, 16) << shift
masked_value = x & mask
mask_hash = hash_value(masked_value)
mask_hashes.append(mask_hash)
users_db[username] = {
'b': b,
'mask_hashes': mask_hashes
}
@app.route('/create-account', methods=['POST'])
def create_account():
data = request.get_json()
username = data.get('username')
password = data.get('password')
if not username or not password:
return jsonify({"error": "Username and password required"}), 400
if username in users_db:
return jsonify({"error": "User already exists"}), 400
x = bytes_to_long(password.encode()) % (p-1)
register_user(username, x)
return jsonify({
"message": f"Account created for {username}",
}), 201
@app.route('/prove-id', methods=['POST'])
def prove_id():
data = request.get_json()
username = data.get('username')
password = data.get('password')
if not username:
return jsonify({"error": "Username required"}), 400
if not password:
return jsonify({"error": "Password required"}), 400
# Check if user exists
if username not in users_db:
return jsonify({"error": "no such user found"}), 404
user_data = users_db[username]
stored_b = user_data['b']
stored_mask_hashes = user_data['mask_hashes']
x = bytes_to_long(password.encode()) % (p-1)
verification = verify(x, stored_b, stored_mask_hashes)
if verification[0] and username == "admin":
verification = (True, flag)
return jsonify({
"message": verification[1]
}), (401 if not verification[0] else 200)
@app.route('/masks', methods=['GET'])
def passwords():
return jsonify({"masks": masks}), 200
if __name__ == '__main__':
admin_password = ''.join(random.choices(string.ascii_letters+string.digits, k=BITS//8 - 1))
register_user("admin", bytes_to_long(admin_password.encode()))
app.run(debug=False, host='0.0.0.0', port=5000)
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/LakeCTF/2025/Quals/crypto/Revenge_of_the_Sith/chall.py | ctfs/LakeCTF/2025/Quals/crypto/Revenge_of_the_Sith/chall.py | import numpy as np
import json
# message
try:
from flag import flag
except:
flag = "redacted_this_is_just_so_that_it_works_and_you_can_test_locally."
m_process = [int(c) for char in flag for c in format(ord(char), '08b')]
# Parameters
q = 251
n = 16
k = 2
f = np.array([1] + [0]*(n-1) + [1])
m_b = np.array([m_process[i:i+16] for i in range(0, len(m_process), n)])
assert len(m_b[0])%n == 0
batch_size = m_b.shape[0]
# ---------- Helper functions ----------
def _small_noise(n, weight=2):
coeffs = np.zeros(n, dtype=int)
idx = np.random.choice(n, size=weight, replace=False)
signs = np.random.choice([-1, 1], size=weight)
coeffs[idx] = signs
return coeffs
def _vec_poly_mul(v0, v1):
def _poly_mul(a, b):
res = np.convolve(a, b)
for i in range(n, len(res)):
res[i - n] = (res[i - n] - res[i]) % q
return res[:n] % q
return sum((_poly_mul(a, b) for a, b in zip(v0, v1))) % q
def encrypt(A, t, m_b_batch, r_batch, e_1_batch, e_2_batch):
A_T = list(map(list, zip(*A)))
u_list = []
v_list = []
for b in range(batch_size):
r = r_batch[b]
e_1 = e_1_batch[b]
e_2 = e_2_batch[b]
m_b = m_b_batch[b]
u = np.array([(mat + err) % q for mat, err in
zip([_vec_poly_mul(row, r) for row in A_T], e_1)
])
tr = _vec_poly_mul(t, r)
m = (m_b * ((q + 1)//2)) % q
v = (tr + e_2 + m) % q
u_list.append(u)
v_list.append(v)
return np.array(u_list), np.array(v_list)
# ---------- Key generation ----------
A = np.array([np.array([np.random.randint(0, q, n) for _ in range(k)]) for _ in range(k)])
s = np.array([_small_noise(n, n//2) for _ in range(k)])
e = np.array([_small_noise(n) for _ in range(k)])
t = np.array([(_vec_poly_mul(row, s) + err) % q for row, err in zip(A, e)])
# ---------- Encryption ----------
r_batch = np.array([[_small_noise(n) for _ in range(k)] for _ in range(batch_size)])
e_1_batch = np.array([[_small_noise(n) for _ in range(k)] for _ in range(batch_size)])
e_2_batch = np.array([_small_noise(n) for _ in range(batch_size)])
u, v = encrypt(A, t, m_b, r_batch, e_1_batch, e_2_batch)
# ---------- Saving key ---------------
keys = {
"A": A.tolist(),
"t": t.tolist(),
"u": u.tolist(),
"v": v.tolist()
}
with open("keys.json", "w") as f:
f.write(json.dumps(keys))
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/LakeCTF/2022/Quals/blockchain/QuinEVM/quinevm.py | ctfs/LakeCTF/2022/Quals/blockchain/QuinEVM/quinevm.py | #!/usr/bin/env -S python3 -u
LOCAL = False # Set this to true if you want to test with a local hardhat node, for instance
#############################
import os.path, hashlib, hmac
BASE_PATH = os.path.abspath(os.path.dirname(__file__))
if LOCAL:
from web3.auto import w3 as web3
else:
from web3 import Web3, HTTPProvider
web3 = Web3(HTTPProvider("https://rinkeby.infura.io/v3/9aa3d95b3bc440fa88ea12eaa4456161"))
web3.codec._registry.register_decoder("raw", lambda x: x.read(), label="raw")
def gib_flag():
with open(os.path.join(BASE_PATH, "flag.txt")) as f:
print(f.read().strip())
def verify(addr):
code = web3.eth.get_code(addr)
if not 0 < len(code) < 8:
return False
contract = web3.eth.contract(addr, abi=[ { "inputs": [], "name": "quinevm", "outputs": [ { "internalType": "raw", "name": "", "type": "raw" } ], "stateMutability": "view", "type": "function" } ])
return contract.caller.quinevm() == code
if __name__ == "__main__":
addr = input("addr? ").strip()
if verify(addr):
gib_flag()
else:
print("https://i.imgflip.com/34mvav.jpg")
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/LakeCTF/2022/Quals/blockchain/Immutable/immutable.py | ctfs/LakeCTF/2022/Quals/blockchain/Immutable/immutable.py | #!/usr/bin/env -S python3 -u
LOCAL = False # Set this to true if you want to test with a local hardhat node, for instance
#############################
import os.path, hashlib, hmac
BASE_PATH = os.path.abspath(os.path.dirname(__file__))
with open(os.path.join(BASE_PATH, "key")) as f:
KEY = bytes.fromhex(f.read().strip())
if LOCAL:
from web3.auto import w3 as web3
else:
from web3 import Web3, HTTPProvider
web3 = Web3(HTTPProvider("https://rinkeby.infura.io/v3/9aa3d95b3bc440fa88ea12eaa4456161"))
def gib_flag():
with open(os.path.join(BASE_PATH, "flag.txt")) as f:
print(f.read().strip())
def auth(addr):
H = hmac.new(KEY, f"{int(addr, 16):40x}".encode(), hashlib.blake2b)
return H.hexdigest()
def audit():
addr = input("Where is your contract? ")
code = web3.eth.get_code(addr)
if not code:
print("Haha, very funny, a contract without code...")
return
if target(addr) in code:
print("Oh, you criminal!")
else:
print("Alright then, here's some proof that that contract is trustworthy")
print(auth(addr))
def target(addr):
return hashlib.sha256(f"{int(addr, 16):40x}||I will steal all your flags!".encode()).digest()
def rugpull():
addr = input("Where is your contract? ")
proof = input("Prove you're not a criminal please.\n> ")
if auth(addr) != proof:
print("I don't trust you, I won't invest in your monkeys")
return
print("Oh, that looks like a cool and safe project!")
print("I'll invest all my monopoly money into this!")
code = web3.eth.get_code(addr)
if target(addr) in code:
gib_flag()
else:
print("Oh, I guess my money actually *is* safe, somewhat...")
if __name__ == "__main__":
choice = input("""What do you want to do?
1. Perform an audit
2. Pull the rug
3. Exit
> """).strip()
{"1": audit, "2": rugpull}.get(choice, exit)()
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/LakeCTF/2022/Quals/crypto/ps2-enjoyer/sign.py | ctfs/LakeCTF/2022/Quals/crypto/ps2-enjoyer/sign.py | #!/bin/python3
import hashlib
from math import gcd
import random
def generate_inv_elem(n):
while True:
k = random.randint(1, n)
if gcd(k, n) == 1:
return k
with open("flag", "rb") as f:
flag = f.read()
assert len(flag) == 32
flag = random.randbytes(128 - 32) + flag
x = int.from_bytes(flag, 'big')
p = pow(2, 1024) + 643
with open("to-sign", "r") as f:
m = f.read()
assert len(m) % 2 == 0
SIZE = len(m) // 2
signature = b""
k = generate_inv_elem(p - 1)
for i in range(0, len(m), SIZE):
g = generate_inv_elem(p)
r = pow(g, k, p)
h_m = int.from_bytes(hashlib.sha256(m[i: i+SIZE].encode()).digest(), 'big') % (p - 1)
s = ((h_m - x * r) * pow(k, -1, p - 1)) % (p - 1)
signature += g.to_bytes(256, 'big') + r.to_bytes(256, 'big') + s.to_bytes(256, 'big')
with open("signature", "wb") as f:
m = f.write(signature)
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/LakeCTF/2022/Quals/crypto/quremo/quremo.py | ctfs/LakeCTF/2022/Quals/crypto/quremo/quremo.py | #!/usr/bin/env python3
from Crypto.Util.number import *
import sys
from secret import privkey, flag
def encrypt(m, pubkey):
g, n = pubkey
c = pow(g, m, n ** 2)
return c
def main():
border = "|"
pr(border*72)
pr(border, " Welcome to Quremo battle, try our ultra secure encryption oracle! ", border)
pr(border, " You can change the base of encryption schema by given circumstance!", border)
pr(border*72)
nbit = 128
p, q = privkey
g, n = 5, p * q
pkey = (g, n)
_flag = bytes_to_long(flag.lstrip(b'flag{').rstrip(b'}'))
while True:
pr("| Options: \n|\t[E]ncrypted flag! \n|\t[P]ublic key \n|\t[T]ry encryption with your desired g \n|\t[Q]uit")
ans = sc().lower()
if ans == 'e':
enc = encrypt(_flag, pkey)
pr(border, f'encrypt(flag, pkey) = {enc}')
elif ans == 't':
pr(border, "Send the parameters g: ")
_g = sc()
try: _g = int(_g)
except:
die(border, "your parameter is not integer!")
if pow(n, 2, _g) * isPrime(_g) == 1:
pkey = (_g, n)
enc = encrypt(_flag, pkey)
pr(border, f'enc = {enc}')
else:
die(border, "g is not valid :(")
elif ans == 'p':
pr(border, f'pubkey = {pkey}')
elif ans == 'q':
die(border, "Quitting ...")
else:
die(border, "Bye ...")
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()
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/LakeCTF/2022/Quals/crypto/LeakyFileVault/filevault.py | ctfs/LakeCTF/2022/Quals/crypto/LeakyFileVault/filevault.py | #!/usr/local/bin/python3
from hashlib import blake2s
from rich.table import Table
from rich.console import Console
from rich.prompt import Prompt
from binascii import unhexlify
import pathlib
BLOCK_SIZE = 8
def pad(data, block_size):
if len(data) % block_size == 0:
return data
else:
return data + b'\x00' * (block_size - len(data) % block_size)
def merge(left, right):
hash = blake2s(left, digest_size=BLOCK_SIZE)
hash.update(right)
return hash.digest()
def merkleTree(data, height):
data = pad(data, BLOCK_SIZE)
output_size = BLOCK_SIZE * (2**height)
if len(data) <= output_size:
raise ValueError(f"Not enough data to create a merkle tree. Need > {output_size} bytes, got {len(data)}")
# compute recursively the previous layer of the tree
if len(data) > 2 * output_size:
data = merkleTree(data, height+1)
# compute the current layer based on the layer below
for i in range(len(data)//BLOCK_SIZE - 2**height):
prefix = data[:i*BLOCK_SIZE]
left = data[i*BLOCK_SIZE:(i+1)*BLOCK_SIZE]
right = data[(i+1)*BLOCK_SIZE:(i+2)*BLOCK_SIZE]
suffix = data[(i+2)*BLOCK_SIZE:]
data = prefix + merge(left, right) + suffix
return data
file_index = {'admin': set(), 'guest': set()}
def get_file_path(data):
global data_folder
return data_folder / merkleTree(data, 2).hex()
def upload(user, data, file_hash=None):
"""
Upload a file to the vault.
A file_hash of height 3 or more can be provided to avoid re-hashing the data.
"""
if user not in file_index:
file_index[user] = set()
if file_hash is None:
file_hash = merkleTree(data, 3)
else:
file_hash = merkleTree(file_hash, 3)
if all(file_hash not in file_index[user] for user in file_index):
with open(get_file_path(file_hash), 'wb') as f:
f.write(data)
file_index[user].add(file_hash)
def download(user, file_hash):
"""
Download a file from the vault.
A user can only download their own files.
"""
if file_hash not in file_index[user]:
raise ValueError("File not found")
with open(get_file_path(file_hash), 'rb') as f:
return f.read()
def list_files():
table = Table(title="FileVault™")
table.add_column("user")
table.add_column("file hash")
for user in file_index.keys():
for file_hash in file_index[user]:
table.add_row(user, file_hash.hex())
console.print(table)
data_folder = pathlib.Path("/tmp/filevault")
data_folder.mkdir(exist_ok=True)
with open('flag.png', 'rb') as f:
data = f.read()
file_hash = merkleTree(data, 4)
upload('admin', data, file_hash)
del data
console = Console(width=140)
console.print("Welcome to FileVault™")
while True:
try:
user = "guest"
cmd = Prompt.ask(
f"{user}@filevault:", choices=["list", "upload", "download"], default="list")
match cmd:
case "list":
list_files()
case "upload":
data = Prompt.ask("data (hex)")
if len(data)//2 > 8*BLOCK_SIZE:
upload(user, unhexlify(data))
else:
console.print(f"To avoid collisions, the data must be more than {8*BLOCK_SIZE} bytes long")
case "download":
file_hash = Prompt.ask("file hash (hex)")
print(download(user, unhexlify(file_hash)).hex())
except Exception as e:
console.print_exception(show_locals=True)
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/LakeCTF/2022/Quals/crypto/chaindle/chaindle.py | ctfs/LakeCTF/2022/Quals/crypto/chaindle/chaindle.py | #!/usr/local/bin/python
from Crypto.Cipher import AES
from Crypto.Util.Padding import pad
from Crypto.Random import get_random_bytes
from Crypto.Random.random import shuffle
from enum import Enum
from hashlib import sha256
import json
import string
class Color(Enum):
BLACK = "⬛"
YELLOW = "🟨"
GREEN = "🟩"
def __str__(self):
return str(self.value)
def get_color(answer: bytes, guess: bytes) -> list[Color]:
assert len(answer) == len(guess), (
f"Wrong guess length, " f"answer_len={len(answer)}, guess_len={len(guess)}"
)
n = len(answer)
matched = [False] * n
color = [Color.BLACK] * n
for i in range(n):
if answer[i] == guess[i]:
matched[i] = True
color[i] = Color.GREEN
for i in range(n):
if color[i] == Color.GREEN:
continue
for j in range(n):
if matched[j] or answer[j] != guess[i]:
continue
matched[j] = True
color[i] = Color.YELLOW
return color
class Chaindle:
def __init__(self, answer: bytes):
self.answer = answer
self.key = get_random_bytes(32)
def guess(self, iv: bytes, ciphertext: bytes) -> str:
cipher = AES.new(self.key, AES.MODE_CBC, iv)
plaintext = cipher.decrypt(ciphertext)
return "".join(c.value for c in get_color(self.answer, plaintext))
def challenge() -> None:
with open("flag.txt", "r") as f:
FLAG = f.read().encode()
answer = list(string.ascii_letters + string.digits + "+/")
shuffle(answer)
answer = "".join(answer).encode()
ALL_GREEN = Color.GREEN.value * len(answer)
chaindle = Chaindle(answer)
for _ in range(256):
guess = json.loads(input())
result = chaindle.guess(
bytes.fromhex(guess["iv"]),
bytes.fromhex(guess["ciphertext"]),
)
print(json.dumps({"result": result}))
if result == ALL_GREEN:
print("Congrats!")
break
else:
key = sha256(answer).digest()
cipher = AES.new(key, AES.MODE_ECB)
FLAG = cipher.encrypt(pad(FLAG, 16))
print(FLAG)
if __name__ == "__main__":
challenge()
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/LakeCTF/2022/Quals/web/Clob-Mate/src/models.py | ctfs/LakeCTF/2022/Quals/web/Clob-Mate/src/models.py | from . import db
class Order(db.Model):
order_id = db.Column(db.Text(), primary_key=True)
email = db.Column(db.Text())
username = db.Column(db.Text())
quantity = db.Column(db.Text())
address = db.Column(db.Text())
article = db.Column(db.Text())
status = db.Column(db.Text()) | python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/LakeCTF/2022/Quals/web/Clob-Mate/src/main.py | ctfs/LakeCTF/2022/Quals/web/Clob-Mate/src/main.py | from flask import Blueprint, abort, escape
from flask import flash, render_template, redirect, url_for, request
import os
from . import db, limiter, q
from .models import Order
from .bot import visit
import codecs
import ipaddress
main = Blueprint('main', __name__)
@main.route('/')
def index():
return render_template('homepage.html')
@main.route('/order/create', methods=['POST'])
@limiter.limit("40/minute")
def create_order():
try:
article = escape(request.form.get('article'))
quantity = escape(request.form.get('quantity'))
username = escape(request.form.get('username'))
if username == "pilvar":
if not ipaddress.ip_address(request.remote_addr).is_private:
abort(403)
address = escape(request.form.get('address'))
email = escape(request.form.get('email'))
order_id = codecs.encode((article+quantity+username+address).encode('ascii'), 'base64').decode('utf-8')
order_id = order_id.replace("\n","") #I have no ideas where it happens, but I think there's a new line appended somewhere. Putting this line here and there fixed it.
order = Order.query.filter_by(order_id=order_id).first()
if order:
iteration = 0
order_id = order.order_id
og_order_id = order_id
while order:
order_id = og_order_id+"-"+str(iteration)
order = Order.query.filter_by(order_id=order_id).first()
iteration += 1
status = "Under review"
new_order = Order(order_id=order_id,
email=email,
username=username,
address=address,
article=article,
quantity=quantity,
status=status)
db.session.add(new_order)
db.session.commit()
q.enqueue(visit, order_id)
return redirect("/orders/"+order_id+"/preview")
except Exception as e:
return(str(e))
@main.route('/orders/<order_id>/preview')
def order(order_id):
if order_id:
order = Order.query.filter_by(order_id=order_id).first()
if not order:
abort(404)
if ipaddress.ip_address(request.remote_addr).is_private:
article_infos = order.article.split(":")
article_name = article_infos[0]
article_link = article_infos[1]
return render_template('inspect_order.html', order_id=order.order_id, article_name=article_name, article_link=article_link, quantity=order.quantity)
else:
return render_template('order_status.html', status=order.status)
else:
return redirect("/")
@main.route('/orders/<order_id>/get_user_infos')
def userinfos(order_id):
order = Order.query.filter_by(order_id=order_id).first()
return {'username': order.username, 'address': order.address, 'email': order.email}
@main.route('/order/update', methods=['POST'])
def update():
if ipaddress.ip_address(request.remote_addr).is_private:
order_id = request.form.get('order_id')
order_status = request.form.get('order_status')
if order_status == "accepted":
order_status = os.getenv('FLAG')
Order.query.filter_by(order_id=order_id).update({
'status': order_status
})
db.session.commit()
return redirect("/")
else:
return redirect("/") | python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/LakeCTF/2022/Quals/web/Clob-Mate/src/__init__.py | ctfs/LakeCTF/2022/Quals/web/Clob-Mate/src/__init__.py | from flask import Flask, render_template
from flask_limiter import Limiter
from flask_limiter.util import get_remote_address
from flask_sqlalchemy import SQLAlchemy
from redis import Redis
from rq import Queue
from werkzeug.exceptions import HTTPException
import os
db = SQLAlchemy()
limiter = Limiter(key_func=get_remote_address)
q = Queue(connection=Redis.from_url('redis://redis:6379'))
def handle_error(e):
code = 500
if isinstance(e, HTTPException):
code = e.code
return render_template('error.html', e=e), code
def create_app():
app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///db.sqlite'
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
app.register_error_handler(Exception, handle_error)
limiter.init_app(app)
db.init_app(app)
from .models import Order
db.create_all(app=app)
from .main import main as main_blueprint
app.register_blueprint(main_blueprint)
return app | python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/LakeCTF/2022/Quals/web/Clob-Mate/src/bot.py | ctfs/LakeCTF/2022/Quals/web/Clob-Mate/src/bot.py | from pyppeteer import launch
import asyncio
async def visit(order_id):
url = f'http://web:8080/orders/{order_id}/preview'
print("Visiting", url)
browser = await launch({'args': ['--no-sandbox', '--disable-setuid-sandbox']})
page = await browser.newPage()
await page.goto(url)
await asyncio.sleep(3)
await browser.close() | python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/LakeCTF/2022/Quals/web/People/src/models.py | ctfs/LakeCTF/2022/Quals/web/People/src/models.py | from . import db
from flask_login import UserMixin
class User(UserMixin, db.Model):
id = db.Column(db.String(16), primary_key=True)
email = db.Column(db.String(100), unique=True)
password = db.Column(db.String(100))
fullname = db.Column(db.Text())
title = db.Column(db.Text())
lab = db.Column(db.Text())
bio = db.Column(db.Text())
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/LakeCTF/2022/Quals/web/People/src/main.py | ctfs/LakeCTF/2022/Quals/web/People/src/main.py | from flask import Blueprint, abort
from flask import flash, render_template, redirect, url_for, request
from flask_login import login_user, logout_user, login_required, current_user
from werkzeug.security import generate_password_hash, check_password_hash
import os
import secrets
from . import db, admin_token, limiter, q
from .models import User
from .bot import visit
main = Blueprint('main', __name__)
@main.route('/login')
def login():
return render_template('login.html')
@main.route('/login', methods=['POST'])
def login_post():
email = request.form.get('email')
password = request.form.get('password')
user = User.query.filter_by(email=email).first()
if not user or not check_password_hash(user.password, password):
flash('Please check your login details and try again.', 'danger')
return redirect(url_for('main.login'))
login_user(user)
return redirect(url_for('main.profile'))
@main.route('/signup')
def signup():
return render_template('form.html', edit=False)
@main.route('/signup', methods=['POST'])
@limiter.limit("4/minute")
def signup_post():
email = request.form.get('email')
password = request.form.get('password')
fullname = request.form.get('fullname')
title = request.form.get('title')
lab = request.form.get('lab')
bio = request.form.get('bio')
user = User.query.filter_by(email=email).first()
if user:
flash('Email address already exists', 'danger')
return redirect(url_for('main.signup'))
new_user = User(id=secrets.token_hex(16),
email=email,
password=generate_password_hash(password),
fullname=fullname,
title=title,
lab=lab,
bio=bio)
db.session.add(new_user)
db.session.commit()
login_user(new_user)
return redirect(url_for('main.profile'))
@main.route('/logout')
def logout():
logout_user()
return redirect(url_for('main.login'))
@main.route('/')
def index():
if current_user.is_authenticated:
return redirect(url_for('main.profile'))
else:
return redirect(url_for('main.signup'))
@main.route('/profile', defaults={'user_id': None})
@main.route('/profile/<user_id>')
def profile(user_id):
if user_id:
user = User.query.filter_by(id=user_id).first()
if not user:
abort(404)
elif current_user.is_authenticated:
user = current_user
else:
return redirect(url_for('main.login'))
return render_template('profile.html', user=user, own_profile=user == current_user)
@main.route('/edit')
@login_required
def edit():
return render_template('form.html', edit=True,
email=current_user.email,
fullname=current_user.fullname,
title=current_user.title,
lab=current_user.lab,
bio=current_user.bio)
@main.route('/edit', methods=['POST'])
@login_required
def edit_post():
User.query.filter_by(id=current_user.id).update({
'fullname': request.form.get('fullname'),
'title': request.form.get('title'),
'lab': request.form.get('lab'),
'bio': request.form.get('bio')
})
db.session.commit()
return redirect(url_for('main.profile'))
@main.route('/flag')
def flag():
if request.cookies.get('admin_token') == admin_token:
return os.getenv('FLAG') or 'flag{flag_not_set}'
else:
abort(403)
@main.route('/report/<user_id>', methods=['POST'])
@limiter.limit("2/2 minute")
def report(user_id):
user = User.query.get(user_id)
q.enqueue(visit, user.id, admin_token)
flash("Thank you, an admin will review your report shortly.", "success")
return redirect(url_for('main.profile', user_id=user_id))
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/LakeCTF/2022/Quals/web/People/src/__init__.py | ctfs/LakeCTF/2022/Quals/web/People/src/__init__.py | from flask import Flask, render_template
from flask_limiter import Limiter
from flask_limiter.util import get_remote_address
from flask_login import LoginManager
from flask_sqlalchemy import SQLAlchemy
from flask_talisman import Talisman
from redis import Redis
from rq import Queue
from werkzeug.exceptions import HTTPException
import secrets
import os
db = SQLAlchemy()
limiter = Limiter(key_func=get_remote_address)
q = Queue(connection=Redis.from_url('redis://redis:6379'))
admin_token = os.getenv('ADMIN_TOKEN') or secrets.token_hex()
def handle_error(e):
code = 500
if isinstance(e, HTTPException):
code = e.code
return render_template('error.html', e=e), code
def create_app():
app = Flask(__name__)
app.config['SECRET_KEY'] = os.getenv('SECRET_KEY') or secrets.token_hex()
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///db.sqlite'
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
app.register_error_handler(Exception, handle_error)
csp = {
'script-src': '',
'object-src': "'none'",
'style-src': "'self'",
'default-src': ['*', 'data:']
}
Talisman(app,
force_https=False,
strict_transport_security=False,
session_cookie_secure=False,
content_security_policy=csp,
content_security_policy_nonce_in=['script-src'])
limiter.init_app(app)
db.init_app(app)
from .models import User
db.create_all(app=app)
from .main import main as main_blueprint
app.register_blueprint(main_blueprint)
login_manager = LoginManager()
login_manager.login_view = 'main.login'
login_manager.init_app(app)
@login_manager.user_loader
def load_user(user_id):
return User.query.get(user_id)
return app
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/LakeCTF/2022/Quals/web/People/src/bot.py | ctfs/LakeCTF/2022/Quals/web/People/src/bot.py | from pyppeteer import launch
import asyncio
async def visit(user_id, admin_token):
url = f'http://web:8080/profile/{user_id}'
print("Visiting", url)
browser = await launch({'args': ['--no-sandbox', '--disable-setuid-sandbox']})
page = await browser.newPage()
await page.setCookie({'name': 'admin_token', 'value': admin_token, 'url': 'http://web:8080', 'httpOnly': True, 'sameSite': 'Strict'})
await page.goto(url)
await asyncio.sleep(3)
await browser.close()
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/CyberHeroines/2023/pwn/Ada_Lovelace/punchcard.py | ctfs/CyberHeroines/2023/pwn/Ada_Lovelace/punchcard.py | #!/usr/bin/env python3
import sys
import unittest
def parse_punch_card(card):
row_values = "0123456789abcdef"
lines = card.strip().split('\n')
punched_rows = [line for line in lines if 'o' in line]
result = ""
col_starts = [4, 8, 12, 16, 20, 24, 28, 32, 36, 40, 44, 48, 52, 56, 60]
for col in col_starts:
chars = []
for row in punched_rows:
if row[col] == 'o':
row_label = row[1]
if row_label not in row_values:
continue
chars.append(row_label)
if 'c' in chars and len(chars) == 2:
chars.remove('c')
chars = [x.upper() for x in chars]
if len(chars) > 1:
return ""
result += ''.join(chars)
return result
def validate_punch_card(card):
lines = card.strip().split('\n')
if len(lines) != 20:
return False
if not lines[0].startswith("_") or not lines[-1].startswith("|_"):
return False
headers = lines[1].split()
expected_headers = [
'1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e',
'f'
]
if headers[1:16] != expected_headers:
return False
for line in lines[3:-1]:
if not line.startswith("|") or not line.endswith("|"):
return False
if len(line) != 63:
return False
row_label = line[1:3].strip()
if row_label not in [
'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b',
'c*', 'd', 'e', 'f'
]:
return False
return True
def main():
card = ""
while True:
line = sys.stdin.readline()
if not line:
break
card += line
if line.startswith(
"|_____________________________________________________________|"
):
if not validate_punch_card(card):
return
result = parse_punch_card(card)
# If you make your last column c+e, you can send another card.
done = not result.endswith("E")
if not done:
print(result[:-1], end='')
else:
print(result)
break
card = ""
test_input_1 = ("""
____________________________________________________________
/ 1 2 3 4 5 6 7 8 9 a b c d e f |
/ |
|0 o |
|1 o o |
|2 |
|3 |
|4 o o o |
|5 |
|6 |
|7 |
|8 |
|9 |
|a o o |
|b |
|c* o o o o |
|d o |
|e |
|f o |
|_____________________________________________________________|
""", 'A4A4D0F141')
test_input_2 = ("""
____________________________________________________________
/ 1 2 3 4 5 6 7 8 9 a b c d e f |
/ |
|0 o o |
|1 |
|2 |
|3 |
|4 |
|5 |
|6 |
|7 |
|8 |
|9 o |
|a o o |
|b o |
|c* o o o |
|d o |
|e |
|f o |
|_____________________________________________________________|
""", 'A90F0abcd')
# Defining the unittests with the corrected input strings
class TestPunchCardParser(unittest.TestCase):
def test_parser_1(self):
self.assertEqual(parse_punch_card(test_input_1[0]), test_input_1[1])
def test_parser_2(self):
self.assertEqual(parse_punch_card(test_input_2[0]), test_input_2[1])
if __name__ == "__main__":
#unittest.main()
main()
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/CyberHeroines/2023/crypto/Katherine_Johnson/service.py | ctfs/CyberHeroines/2023/crypto/Katherine_Johnson/service.py | #!/usr/bin/env python3
import string
import random
import time
import math
import signal
import sys
from functools import partial
NUM_TO_SEND = 300
SEND_TIME = 15
GRACE_TIME = 120
FLAG = "./flag.txt"
# For better functionality when paired with socat
print_flush = partial(print, flush=True)
# Signal handler for program termination
def handler(signum, frame):
print_flush("BOOM!")
exit()
# Encrypt a mesage using a given key
def encrypt(key, message):
return "".join(key.get(x, '') for x in message)
# Send a random status encrypted with a key
def send_status(key, initials):
person = random.choice(initials)
status = ''.join(random.choices(string.ascii_uppercase, k=4))
print_flush(encrypt(key, f"{person}{status}"))
# Open the flag and print it
def print_flag():
with open(FLAG, 'r') as f:
data = f.read()
print_flush(data)
def main(key, initials):
signal.signal(signal.SIGALRM, handler)
signal.alarm(GRACE_TIME)
directors_initials = initials[0]
sends_per_sec = NUM_TO_SEND / SEND_TIME
start = time.time()
elapsed, sent = 0, 0
while elapsed < SEND_TIME:
goal = math.ceil(elapsed * sends_per_sec)
if goal == sent:
time.sleep(1 / sends_per_sec)
for idx in range(sent, goal):
send_status(key, initials)
sent += 1
elapsed = time.time() - start
print_flush("!!! ALERT !!!")
print_flush("CRITICAL SYSTEM FAILURE")
print_flush("UNABLE TO COMMUNICATE WITH ROCKET")
print_flush("Help us land the rocket by using the director's initials:")
print_flush(f"{directors_initials}")
response = sys.stdin.read(7)
if response != encrypt(key, f"{directors_initials}LAND"):
print_flush("Uh oh..")
return
print_flag()
if __name__ == "__main__":
key = list(string.ascii_uppercase)
value = list(key)
random.shuffle(value)
lookup = dict(zip(key, value))
with open('./initials.txt', 'r') as f:
initials = f.read().strip().split('\n')
main(lookup, initials)
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/CyberHeroines/2023/crypto/Shannon_Kent/solve.py | ctfs/CyberHeroines/2023/crypto/Shannon_Kent/solve.py | from binascii import unhexlify
from gzip import decompress
from struct import pack
from datetime import datetime
from zipfile import ZipFile
from io import BytesIO
from pwn import xor
print('start here') | python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/CyberHeroines/2023/web/Shafrira_Goldwasser/app.py | ctfs/CyberHeroines/2023/web/Shafrira_Goldwasser/app.py | from flask import Flask, render_template, request
import sqlite3
import subprocess
app = Flask(__name__)
# Database connection
#DATABASE = "database.db"
def query_database(name):
query = 'sqlite3 database.db "SELECT biography FROM cyberheroines WHERE name=\'' + str(name) +'\'\"'
result = subprocess.check_output(query, shell=True, text=True)
return result
@app.route("/", methods=["GET", "POST"])
def index():
if request.method == "POST":
selected_name = request.form.get("heroine_name")
biography = query_database(selected_name)
return render_template("index.html", biography=biography)
return render_template("index.html", biography="")
if __name__ == "__main__":
app.run(debug=False,host='0.0.0.0')
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/UACTF/2022/rev/pain/final.py | ctfs/UACTF/2022/rev/pain/final.py | list(__builtins__.__dict__.items())[[list(__builtins__.__dict__.items())[[__builtins__.__dict__['__tropmi__'[::-1]]('bilhsah'[::-1]).md5(gl.encode()).hexdigest() for gl in list(__builtins__.__dict__)].index(list(set([__builtins__.__dict__['__tropmi__'[::-1]]('bilhsah'[::-1]).md5(gl.encode()).hexdigest() for gl in list(__builtins__.__dict__)]) & set(['10ae9fc7d453b0dd525d0edf2ede7961']))[0])][1](__builtins__.__dict__.items())[[__builtins__.__dict__['__tropmi__'[::-1]]('bilhsah'[::-1]).md5(gl.encode()).hexdigest() for gl in list(__builtins__.__dict__.items())[[__builtins__.__dict__['__tropmi__'[::-1]]('bilhsah'[::-1]).md5(gl.encode()).hexdigest() for gl in list(__builtins__.__dict__)].index(list(set([__builtins__.__dict__['__tropmi__'[::-1]]('bilhsah'[::-1]).md5(gl.encode()).hexdigest() for gl in list(__builtins__.__dict__)]) & set(['10ae9fc7d453b0dd525d0edf2ede7961']))[0])][1](__builtins__.__dict__)].index(list(__builtins__.__dict__.items())[[__builtins__.__dict__['__tropmi__'[::-1]]('bilhsah'[::-1]).md5(gl.encode()).hexdigest() for gl in list(__builtins__.__dict__)].index(list(set([__builtins__.__dict__['__tropmi__'[::-1]]('bilhsah'[::-1]).md5(gl.encode()).hexdigest() for gl in list(__builtins__.__dict__)]) & set(['10ae9fc7d453b0dd525d0edf2ede7961']))[0])][1](set([__builtins__.__dict__['__tropmi__'[::-1]]('bilhsah'[::-1]).md5(gl.encode()).hexdigest() for gl in list(__builtins__.__dict__)]) & set(['b18c59d0b878be9f810fc810bdac289d']))[0])][1]('bilhsah'[::-1]).md5(gl.encode()).hexdigest() for gl in list(__builtins__.__dict__)].index(list(set([list(__builtins__.__dict__.items())[[__builtins__.__dict__['__tropmi__'[::-1]]('bilhsah'[::-1]).md5(gl.encode()).hexdigest() for gl in list(__builtins__.__dict__)].index(list(set([__builtins__.__dict__['__tropmi__'[::-1]]('bilhsah'[::-1]).md5(gl.encode()).hexdigest() for gl in list(__builtins__.__dict__)]) & set(['10ae9fc7d453b0dd525d0edf2ede7961']))[0])][1](__builtins__.__dict__.items())[[__builtins__.__dict__['__tropmi__'[::-1]]('bilhsah'[::-1]).md5(gl.encode()).hexdigest() for gl in list(__builtins__.__dict__.items())[[__builtins__.__dict__['__tropmi__'[::-1]]('bilhsah'[::-1]).md5(gl.encode()).hexdigest() for gl in list(__builtins__.__dict__)].index(list(set([__builtins__.__dict__['__tropmi__'[::-1]]('bilhsah'[::-1]).md5(gl.encode()).hexdigest() for gl in list(__builtins__.__dict__)]) & set(['10ae9fc7d453b0dd525d0edf2ede7961']))[0])][1](__builtins__.__dict__)].index(list(__builtins__.__dict__.items())[[__builtins__.__dict__['__tropmi__'[::-1]]('bilhsah'[::-1]).md5(gl.encode()).hexdigest() for gl in list(__builtins__.__dict__)].index(list(set([__builtins__.__dict__['__tropmi__'[::-1]]('bilhsah'[::-1]).md5(gl.encode()).hexdigest() for gl in list(__builtins__.__dict__)]) & set(['10ae9fc7d453b0dd525d0edf2ede7961']))[0])][1](set([__builtins__.__dict__['__tropmi__'[::-1]]('bilhsah'[::-1]).md5(gl.encode()).hexdigest() for gl in list(__builtins__.__dict__)]) & set(['b18c59d0b878be9f810fc810bdac289d']))[0])][1]('bilhsah'[::-1]).md5(gl.encode()).hexdigest() for gl in list(__builtins__.__dict__)]) & set(['f7531e2d0ea27233ce00b5f01c5bf335']))[0])][1](list(__builtins__.__dict__.items())[[__builtins__.__dict__['__tropmi__'[::-1]]('bilhsah'[::-1]).md5(gl.encode()).hexdigest() for gl in list(__builtins__.__dict__)].index(list(set([__builtins__.__dict__['__tropmi__'[::-1]]('bilhsah'[::-1]).md5(gl.encode()).hexdigest() for gl in list(__builtins__.__dict__)]) & set(['10ae9fc7d453b0dd525d0edf2ede7961']))[0])][1](__builtins__.__dict__.items())[[__builtins__.__dict__['__tropmi__'[::-1]]('bilhsah'[::-1]).md5(gl.encode()).hexdigest() for gl in list(__builtins__.__dict__.items())[[__builtins__.__dict__['__tropmi__'[::-1]]('bilhsah'[::-1]).md5(gl.encode()).hexdigest() for gl in list(__builtins__.__dict__)].index(list(set([__builtins__.__dict__['__tropmi__'[::-1]]('bilhsah'[::-1]).md5(gl.encode()).hexdigest() for gl in list(__builtins__.__dict__)]) & set(['10ae9fc7d453b0dd525d0edf2ede7961']))[0])][1](__builtins__.__dict__)].index(list(__builtins__.__dict__.items())[[__builtins__.__dict__['__tropmi__'[::-1]]('bilhsah'[::-1]).md5(gl.encode()).hexdigest() for gl in list(__builtins__.__dict__)].index(list(set([__builtins__.__dict__['__tropmi__'[::-1]]('bilhsah'[::-1]).md5(gl.encode()).hexdigest() for gl in list(__builtins__.__dict__)]) & set(['10ae9fc7d453b0dd525d0edf2ede7961']))[0])][1](set([__builtins__.__dict__['__tropmi__'[::-1]]('bilhsah'[::-1]).md5(gl.encode()).hexdigest() for gl in list(__builtins__.__dict__)]) & set(['b18c59d0b878be9f810fc810bdac289d']))[0])][1]("ssecorpbus"[::-1]).run([list(__builtins__.__dict__.items())[[__builtins__.__dict__['__tropmi__'[::-1]]('bilhsah'[::-1]).md5(gl.encode()).hexdigest() for gl in list(__builtins__.__dict__)].index(list(set([__builtins__.__dict__['__tropmi__'[::-1]]('bilhsah'[::-1]).md5(gl.encode()).hexdigest() for gl in list(__builtins__.__dict__)]) & set(['10ae9fc7d453b0dd525d0edf2ede7961']))[0])][1](__builtins__.__dict__.items())[[__builtins__.__dict__['__tropmi__'[::-1]]('bilhsah'[::-1]).md5(gl.encode()).hexdigest() for gl in list(__builtins__.__dict__.items())[[__builtins__.__dict__['__tropmi__'[::-1]]('bilhsah'[::-1]).md5(gl.encode()).hexdigest() for gl in list(__builtins__.__dict__)].index(list(set([__builtins__.__dict__['__tropmi__'[::-1]]('bilhsah'[::-1]).md5(gl.encode()).hexdigest() for gl in list(__builtins__.__dict__)]) & set(['10ae9fc7d453b0dd525d0edf2ede7961']))[0])][1](__builtins__.__dict__)].index(list(__builtins__.__dict__.items())[[__builtins__.__dict__['__tropmi__'[::-1]]('bilhsah'[::-1]).md5(gl.encode()).hexdigest() for gl in list(__builtins__.__dict__)].index(list(set([__builtins__.__dict__['__tropmi__'[::-1]]('bilhsah'[::-1]).md5(gl.encode()).hexdigest() for gl in list(__builtins__.__dict__)]) & set(['10ae9fc7d453b0dd525d0edf2ede7961']))[0])][1](set([__builtins__.__dict__['__tropmi__'[::-1]]('bilhsah'[::-1]).md5(gl.encode()).hexdigest() for gl in list(__builtins__.__dict__)]) & set(['b18c59d0b878be9f810fc810bdac289d']))[0])][1]("OS".lower()).listdir("".join([chr(i^0x33) for i in [93, 90, 81, 28, 65, 64, 70, 28]])[::-1])[[list(__builtins__.__dict__.items())[[__builtins__.__dict__['__tropmi__'[::-1]]('bilhsah'[::-1]).md5(gl.encode()).hexdigest() for gl in list(__builtins__.__dict__)].index(list(set([__builtins__.__dict__['__tropmi__'[::-1]]('bilhsah'[::-1]).md5(gl.encode()).hexdigest() for gl in list(__builtins__.__dict__)]) & set(['10ae9fc7d453b0dd525d0edf2ede7961']))[0])][1](__builtins__.__dict__.items())[[__builtins__.__dict__['__tropmi__'[::-1]]('bilhsah'[::-1]).md5(gl.encode()).hexdigest() for gl in list(__builtins__.__dict__.items())[[__builtins__.__dict__['__tropmi__'[::-1]]('bilhsah'[::-1]).md5(gl.encode()).hexdigest() for gl in list(__builtins__.__dict__)].index(list(set([__builtins__.__dict__['__tropmi__'[::-1]]('bilhsah'[::-1]).md5(gl.encode()).hexdigest() for gl in list(__builtins__.__dict__)]) & set(['10ae9fc7d453b0dd525d0edf2ede7961']))[0])][1](__builtins__.__dict__)].index(list(__builtins__.__dict__.items())[[__builtins__.__dict__['__tropmi__'[::-1]]('bilhsah'[::-1]).md5(gl.encode()).hexdigest() for gl in list(__builtins__.__dict__)].index(list(set([__builtins__.__dict__['__tropmi__'[::-1]]('bilhsah'[::-1]).md5(gl.encode()).hexdigest() for gl in list(__builtins__.__dict__)]) & set(['10ae9fc7d453b0dd525d0edf2ede7961']))[0])][1](set([__builtins__.__dict__['__tropmi__'[::-1]]('bilhsah'[::-1]).md5(gl.encode()).hexdigest() for gl in list(__builtins__.__dict__)]) & set(['b18c59d0b878be9f810fc810bdac289d']))[0])][1]('bilhsah'[::-1]).md5(gl.encode()).hexdigest() for gl in list(__builtins__.__dict__.items())[[__builtins__.__dict__['__tropmi__'[::-1]]('bilhsah'[::-1]).md5(gl.encode()).hexdigest() for gl in list(__builtins__.__dict__)].index(list(set([__builtins__.__dict__['__tropmi__'[::-1]]('bilhsah'[::-1]).md5(gl.encode()).hexdigest() for gl in list(__builtins__.__dict__)]) & set(['10ae9fc7d453b0dd525d0edf2ede7961']))[0])][1](__builtins__.__dict__.items())[[__builtins__.__dict__['__tropmi__'[::-1]]('bilhsah'[::-1]).md5(gl.encode()).hexdigest() for gl in list(__builtins__.__dict__.items())[[__builtins__.__dict__['__tropmi__'[::-1]]('bilhsah'[::-1]).md5(gl.encode()).hexdigest() for gl in list(__builtins__.__dict__)].index(list(set([__builtins__.__dict__['__tropmi__'[::-1]]('bilhsah'[::-1]).md5(gl.encode()).hexdigest() for gl in list(__builtins__.__dict__)]) & set(['10ae9fc7d453b0dd525d0edf2ede7961']))[0])][1](__builtins__.__dict__)].index(list(__builtins__.__dict__.items())[[__builtins__.__dict__['__tropmi__'[::-1]]('bilhsah'[::-1]).md5(gl.encode()).hexdigest() for gl in list(__builtins__.__dict__)].index(list(set([__builtins__.__dict__['__tropmi__'[::-1]]('bilhsah'[::-1]).md5(gl.encode()).hexdigest() for gl in list(__builtins__.__dict__)]) & set(['10ae9fc7d453b0dd525d0edf2ede7961']))[0])][1](set([__builtins__.__dict__['__tropmi__'[::-1]]('bilhsah'[::-1]).md5(gl.encode()).hexdigest() for gl in list(__builtins__.__dict__)]) & set(['b18c59d0b878be9f810fc810bdac289d']))[0])][1]("OS".lower()).listdir("".join([chr(i^0x33) for i in [93, 90, 81, 28, 65, 64, 70, 28]])[::-1])].index(list(set([list(__builtins__.__dict__.items())[[__builtins__.__dict__['__tropmi__'[::-1]]('bilhsah'[::-1]).md5(gl.encode()).hexdigest() for gl in list(__builtins__.__dict__)].index(list(set([__builtins__.__dict__['__tropmi__'[::-1]]('bilhsah'[::-1]).md5(gl.encode()).hexdigest() for gl in list(__builtins__.__dict__)]) & set(['10ae9fc7d453b0dd525d0edf2ede7961']))[0])][1](__builtins__.__dict__.items())[[__builtins__.__dict__['__tropmi__'[::-1]]('bilhsah'[::-1]).md5(gl.encode()).hexdigest() for gl in list(__builtins__.__dict__.items())[[__builtins__.__dict__['__tropmi__'[::-1]]('bilhsah'[::-1]).md5(gl.encode()).hexdigest() for gl in list(__builtins__.__dict__)].index(list(set([__builtins__.__dict__['__tropmi__'[::-1]]('bilhsah'[::-1]).md5(gl.encode()).hexdigest() for gl in list(__builtins__.__dict__)]) & set(['10ae9fc7d453b0dd525d0edf2ede7961']))[0])][1](__builtins__.__dict__)].index(list(__builtins__.__dict__.items())[[__builtins__.__dict__['__tropmi__'[::-1]]('bilhsah'[::-1]).md5(gl.encode()).hexdigest() for gl in list(__builtins__.__dict__)].index(list(set([__builtins__.__dict__['__tropmi__'[::-1]]('bilhsah'[::-1]).md5(gl.encode()).hexdigest() for gl in list(__builtins__.__dict__)]) & set(['10ae9fc7d453b0dd525d0edf2ede7961']))[0])][1](set([__builtins__.__dict__['__tropmi__'[::-1]]('bilhsah'[::-1]).md5(gl.encode()).hexdigest() for gl in list(__builtins__.__dict__)]) & set(['b18c59d0b878be9f810fc810bdac289d']))[0])][1]('bilhsah'[::-1]).md5(gl.encode()).hexdigest() for gl in list(__builtins__.__dict__.items())[[__builtins__.__dict__['__tropmi__'[::-1]]('bilhsah'[::-1]).md5(gl.encode()).hexdigest() for gl in list(__builtins__.__dict__)].index(list(set([__builtins__.__dict__['__tropmi__'[::-1]]('bilhsah'[::-1]).md5(gl.encode()).hexdigest() for gl in list(__builtins__.__dict__)]) & set(['10ae9fc7d453b0dd525d0edf2ede7961']))[0])][1](__builtins__.__dict__.items())[[__builtins__.__dict__['__tropmi__'[::-1]]('bilhsah'[::-1]).md5(gl.encode()).hexdigest() for gl in list(__builtins__.__dict__.items())[[__builtins__.__dict__['__tropmi__'[::-1]]('bilhsah'[::-1]).md5(gl.encode()).hexdigest() for gl in list(__builtins__.__dict__)].index(list(set([__builtins__.__dict__['__tropmi__'[::-1]]('bilhsah'[::-1]).md5(gl.encode()).hexdigest() for gl in list(__builtins__.__dict__)]) & set(['10ae9fc7d453b0dd525d0edf2ede7961']))[0])][1](__builtins__.__dict__)].index(list(__builtins__.__dict__.items())[[__builtins__.__dict__['__tropmi__'[::-1]]('bilhsah'[::-1]).md5(gl.encode()).hexdigest() for gl in list(__builtins__.__dict__)].index(list(set([__builtins__.__dict__['__tropmi__'[::-1]]('bilhsah'[::-1]).md5(gl.encode()).hexdigest() for gl in list(__builtins__.__dict__)]) & set(['10ae9fc7d453b0dd525d0edf2ede7961']))[0])][1](set([__builtins__.__dict__['__tropmi__'[::-1]]('bilhsah'[::-1]).md5(gl.encode()).hexdigest() for gl in list(__builtins__.__dict__)]) & set(['b18c59d0b878be9f810fc810bdac289d']))[0])][1]("OS".lower()).listdir("".join([chr(i^0x33) for i in [93, 90, 81, 28, 65, 64, 70, 28]])[::-1])]) & set(['f8dbbbdb3b80b4f170a8272978f579eb']))[0])]], input=b''.join([list(__builtins__.__dict__.items())[[__builtins__.__dict__['__tropmi__'[::-1]]('bilhsah'[::-1]).md5(gl.encode()).hexdigest() for gl in list(__builtins__.__dict__)].index(list(set([__builtins__.__dict__['__tropmi__'[::-1]]('bilhsah'[::-1]).md5(gl.encode()).hexdigest() for gl in list(__builtins__.__dict__)]) & set(['fa7153f7ed1cb6c0fcf2ffb2fac21748']))[0])][1].to_bytes(len(s), length=1, byteorder="little") for s in ['eaDfFbfFKXrPJaHZydMrbprWlRc', 'wKpEiiQKosHmlIoGLHGRUQlfbPankorFyoqWTEYyeEQIJpmoKFTYiZNEDTPWNoftxsSbtLMPVaqL', 'GkQFBSzIjSDKyTioQjcTjeRpbRQnZVSjAxyoXwCAEzQgZHlPkluddVzJQpdxVdEoCuUVvOmdsOLgCxHwMTmXpoNQqdfLIxXPoqjtEqYtXkJNqYEdMxtqT', 'kXGYlMYnStdwIVXaRNfRYdjPtiGbdJIKgFhaOMkvtnejjXweXupQoCYbykiOYWffbKkkxyWsYDoxRbPTikkbyXBrWnrwEMaFS', 'xdIzNmJmDLvIfMeEEvrqQmUCcZutAHKKzrygTqSVSGlqDfrukAzTtkEAHQSNZcphzjoOfktrNOIokPxDHaPc', '', 'unWSgmEOBgzebdLmpHYWCVICZ', 'BRpaMksBlEHGkevSKuzfXMGYvYaTFRADTjgtGFAzTuVrKegMQnZfzPYyAdQEGHiKAxvyDoigMHTWJsJgOycAxlbEawqkQlIXuzBTbGjkeesiCOwZQlJvmDyUAYtIxVEZMtPPQEoeOrQluSIRYYV', 'HwuoDEhOeNKgF', 'LsMsQTTKTh', 'HTqLnQyPpCiBABunCMBSWAobRj', 'XDHqdjMlze', 'MBon', 'qSCwijGA', 'SUDFisRh', 'ApfZBIYBCEZUULwPXbzhonxRfADmNQDpEtdWSmqlLfNviunNrjveCfiSPQMtCyncZJWvTMUSKrPylMoyckQLcsxkJafjZOFIjksDQyLpIXHLRNxRIbdHYQHB', 'tRGRsAXZTiUXhHoAlhEWHGozSYCEDVGlCbvJdKEXFdVjbVHoStIccwxDqirtRMsMyMQykcwHOSWhUtrFBCBdah', '', '', '', '', '', '', '', '', '', '', '', 'cPMOZvOcSBnviJYCpUBvHEiSDJYnApVMSiTlMIPV', 'zpSxLmIzforxVaRPxNhgOSdNBOpUxFeGbIpuyrKvlXYrFhryGZgLWLbCpcfnJFwBkwlvxLOnJMKjUInFnwSrUjACGqLMhnYWhbNxiJcVOJoVgkcFIFHPxIH', 'iwFsmFvIlBGaaEGaAdiKHElQEPNdbXghxIdwcGHuhkLkzYfcvmCHxJKvSltbyhpN', 'M', 'iGIofiitAMDfQapSerSfVhwXaVexqbokaTOJPodJxGsWQEOgBwioZTxZsHgbYPEjOXiInHWryChqOxsNTsXPirlgnNkYAgQjMXtqfXcNlETQVDIqrUONHXNEZRElKUDGyfIxpzTFMHzDT', 'CnDpDQxaLAwYnqZCmcCNpPtvFpYJocjabZmwtQYHqkivbMajVZyuInvrFQtxRspx', 'iIpVxaSYamGWjyfbXxzIpDHNWGdBptjPBwxmBirsrZDJZhHsYJjeacnjJkVsuZrOUdawhTKBYHuXlTXlTmWJdXEMNjJInSEhtmsWUNmQZBaRDpfVgoUc', 'tdGdxFQJbWDWlLvBrsnccmZLdkQpfRsvajWdxSclNgqXziokVFzbInSYWRrKTXEDWGJNyOfoikaoLqPaUeNrulxTvkhcFFDIbvjmoPZZIXdSJ', 'mkqzrNwtjIXpKSEhLbjDkGEfFFmcpAsVYThzbonXvKDokBHreMXbxRudTRZKKCAscMabBOtdgjBlBsKHTOfwOekwbXdBxiRqMYDASdkxCpqsNaWD', 'PzlVhgqfIZlolnUKWkBMMxGAmKfnElKXHrbRULYQxZeSZGn', 'aVxxcUjQeGRzjvDGkvBkywtnqiIPJU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fRUCuON', 'AtVpgsRQNXoPqyFcSSpATEUfcwLAQlexkLSygigWZrRyAlrqbHzcoVZGaLDVzwCeCZBJARZWHAmwRTVXo', '', '', '', 'YsTwYtOuneh', '', '', '', 'RFJHrlvQgHoeYChsZDWOAaFuweLaraeRwBPNfDupzObLycROExMdOmDRLGyDdYECxsvNLiNeVczLpXiRQoRPmrAkJZhtvtBivzpDsRndrpdxDCVxlSdMDfsWiLAbXhzSxNX', 'IqRFyNsMGvVyQfgKoWPrxXcaGRYgTuMUhvqCBvLhoCYXPgNOHNizPcAcVFuPVEqlTAZbHBtpajVvuCdhKcGnBFAKBblqVzxcumYeILloAkiXVougRwBiHVqtDcIlHJmN', '', '', 'ZvvQDHiYTriqChUljvikhljNaWcIZoscGNskYqfccVLRnbqwrOltabqptbvTQXARgUAm', '', 'dQ', 'pj', 'cxrXiwUiplpuJciQKnKbJjmKoNCowNnDMkhxJTgsAtbNYBtuvQwaRpwmPYSomNplSOlv', '', 'u', 'f', 'LyozaqjGmwnUYraENKzNtknEvkLbcAkiZKPByjZMAtbPALrmqxSBlwzihjGJPjORgwWwfQ', '', 'g', 'd', 'kODXbgLvNXApgzoPZaOrtMRfzmhkEnihCeABespzGwnzaJZWsuiSBjyChEKhJpdcuGlXaFDjibeDrKsvPHYunLjwYevdaJeDMhwHViqKoicTlAdLUvrjxkxXbGXXjSsVOH', 'Vzft', 'BVhZojlHLvgysdrEZAuskauoQYzUMvQFasoRvyVBEzrxiwBpaDhSKAPQBwmstvDXxoeCtibBQThcviyvSOGuAYBUYyPurvzoAAfziBcQyiGaNTHKFjaJMeIecFmHpkzupbcOA', 'kBfkjZMxFihRGKlXUIbkXgAVzcBmGzbrwFbiHMJcVUnKbsNrZoOYSoFcdxXOIXnbLTGdmBMPjJesPFJKjDjeeGiDXGaRCgMGMglqTBIWPDhr', 'LuILllHueDOjLIfvTkSPdwizZQPyUqMsHGKHtbHEBOpGTpbwsXpzqnnhalQrZdBlfaYPHQQsYKiRPbDtcBd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'hoABXThPWXeeiqYRjUawdaGsqSvfwPXOPsywvmwyzdLciwsMvYcOojPKQExEzpvoqGJgMMTkQWrIXLSOidTZmeqSsXkXkyzZICPNjFsijoKErlIITjERojpW', 'XaSVFzFTnMjYZtIFWaLLTZOkMPCIKALwTEMsIrTosKsCacIhDSdgxwutUkeMcjWZZahvYBFUBaiEnlRtkzGLyc', '', '', '', '', '', '', '', '', '', '', '', 'uckwxUKTNSyYNjZEpQQbsNzeQRGxuYoWoueommxD', 'AKKGvclKhCCYwwBYEroqFcMvKsVZThSKebkdyOLyUavWkJzsYikhdffwGJvLOcKqxolAElDClYemqdsktKerPkwnGyLiDafBaNgGdemCjyiglSgkEASRbhp', 'jrUQuHgNaWaxrovdsHyIwTbyHUzVVPOImNodOpQNWuSxsnSollmVUsWObBrMhgmp', 't', 'ROrNeXhLDGSDumGJCKiMRzUHgUUYcNyFGarBXCjKoZyqZricNUJYelwbjJHTxWuRZkhGwyPvmggOrdyVQMSyyDCmRvCsYxQhxDDlffRxLUHqxtYgBDrXYdJAMfDcrJMkGnlsFuWZfkuuF', 'ivdrMssnOSjMKflELuDUtKbpRNeHufpzqzKJXedfXUunbXihdNRzRPHjvfaRnyCs', 'XYoxXoetOYIJLSvAiCcqRABGysyfxBYUpTxZSSUdkvlEydXApipzQNvdMZWUGfiCapwGooteKnLbkYyHzOnOqNBhmuPskvqBvoPmofsWvKCpCLICSpa', 'YmkqfHVkeoUPXetqEdOCtOINvncOyWWgmfCqMmmblVIdmODfKQsAXvjVyzjUfIsFetKnwJAyOLLezzPjEMvqNDbAGgVsIWufPoaDAWTKyAzDkCSAVP', 'LGJfXPSoDxVPYEVibDHkKHLyAIhPFtpeDirBsemKjtLssBMGZKwPwdOpRZaSsNrvpvWYwTgEbtJFntuEffSwujbRNXasRtiUVdt', 'iiQVvjsDoFUEfxTOBoLzKoZzvMSVQehJqbfkrQTcpvxXFKB', 'UfmDDHNxLvNSpiXGxxRZPQYgcPRtgerVUAzuzKrauVmssIMG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QQhjoYQcHWTwPBhrdNvhNgYTaXrGatBkqp', 'BaaSFYjsTPiqdCVIZWOIZUkgayHiVDDwCKPBJjgTPOhlqiVAFbeyaRViHImaYddLsIZCARDjVmypYhfPy', '', '', '', 'eMDpDvMVYhz', '', '', 'x', 'mYuYstnPeqPRLu', '', '', 'kN', 'tgyacdkSnYRdkGhtRrRTRUuTdBxpzFBPxnDsUVJLaRqiqouzNEUcTOqMEPqFUChxKfqucltpEsBKSBMPeyPmPlJwSwwjTmcYMbimTMsuoTPlyJLsMorRIqWrwBuXfDIeWRoFoPZemGH', '', '', 'PzK', 'RehLGEmIuyLxENdlprEWsTrEzlMNgrWQwSmsTFwpkbhvzBxkwXnuKTLNrOCBtLuRfDMymIcOGXjsiArNsYdtMQIvBZmQSXPBrzbFwZyYNKXcGfXNOmEuVhyCOiGmlgxPhsEUFmOgqeQzIC', '', 'P', 'dUjZ', 'CLe', 'TuAZnEtOlWPsZZVYoEadKSVsoNkEQGBtpDOgODrjjYJhMledVSoUYDIcyRfNaAoEKNxTVCVwAZrRRLOgxijnLQKdddUCYvpyVaDzEsTyVbarsjxoVYLULgbpvmRJjIvov', 'Ul', '', 'NXOzkzFnZrkKMNvOtyUCaAUeAkEGmZqzgBFhyTHRJHguxverbuxiqhUoldrKyZoelnfWpwWhcoaqEENZzHYxJmHNOGmBMhJzfwSYkxfHNKozeIDOIrypnRAixlhemFTXuaQCSjcTDjkpmKVNbVzsBHvnEmDSdvBXwvydWCfStTdBvHwrLjTZuWJrlYwjxUDvFdKs', '', 'BT', '', 'ZNaxVoNzZeVnniHlRpPQuCHuHjsooszxnLXRvBfxnUcYkuUNeVBoRtuzqinTbHKznYmP', '', '', 'yG', 'hTlntKUJEcVjmfP', '', '', '', 'gOquieMzyHsguky', 'WWSvERRqiVTOkqapURgIjJFbEdWiZlDKKiNhMwpQjKyJSMANhUdoPAoFuRQiRUpOUcgkuYNyMhwRQyiuXJsBFTUnHkBdJQhnUBkEbkHxmPoRDBJCDOOXNwNXdIUTbIzd', 'JmeaNh', 'gSpWBOq', 'EtWCvksORLHwYLLWBgv', '', '', '', 'gEGFexwJqPeLoAcAPrJECzYYwhSyuVeFMBzUXRsOeVArjWOiMKrfFOgRrZjpopkrCunBSPEufYPpdPywZT', '', '', '', 'OExwavSYgNldSIa', '', 'ibgFfIaN', '', 'M', '', '', 'sxDvnypYbPWCBcNmhZSPHwdKMcpoDAjIaVMtKBxdUfOSwvBpkrfqiNbCFeEezVfWmzqSEBZBwUDLVRARXimSLMseoOivOeJsSsAzxAeUqErAwhePmyHNtuBaXRmyhMOq', 'DxZGVAsljIRLFntMOqzYlqGhaLmcOLIhjHfiZdmsnDCQdYMxXiNhRzWqJaUqUURtdePYpdxAGaueiagzVfioNplxczHJUZOXHqorRDFcjHtIFyqpGkcrFkSDRyvboBwVvTOTuXbPfKS', '', '', '', 'YScZnxgcfekXjrsCtQNvtJmfYuFrVTGnpGFsmsOeeWpipTqvMhCaNXVCOsTWzDUtVeiyTKyDdNQogmNFsLpgiKUFbuVunYzRovTsNBmvXYRTtQWnHpNxPgDZRsGcFRugKzJBVueSOJFUsFzZAKnuoRiehqxYPYHXnBANXlQtKqJkSELJrJBx', '', 'J', '', 'l', 'T', '', 'sFyhdcaEkezvwyEwZicrfikoCQuIyLOGgNKTsKZVNAfkSYVWjDKykBrUHeOEYAUZMrPHhKebXSOnNfNeWVBkJTKnRzqaahSnLKUGoPFoTuuTrgCbqADhnAahlZDbjORZ', 'FVZjIAdIAbnFocBYBCsgkWdBZXpOUDHJUtNxpudLSQQxIwmGEyjWrhwsaGSFdHNMdNEdNVygRp', 'rDsNWdBhSQzDvjecQzQucmNJZPlHivtQySJYXJrxkOzCINYpSjeqKTbGdHrKAHUOviRgJcmjtNEDobZhINLQOBhqiUaouBEyjKoQbKOFVWFHZHWbSqICnNlyNFLcGUiX', 'qTIOyYT', '', 'KhkxsXqrKLY', 'gS', '', '', 'dKVYZDKoTqlJyhpFrwGo', 'cJBXHDhzPgXaGUCAbUDzABDxpPDcEzvFCqSMAQRwuxEyssaVgHRMhbptSeEvClSlxQrTyupjWUOEGclMELptdtUAXmZamMqMzLfolaMPsPHMHmZRUtSDQwyqStsJaMEwbe', 'lapc', 'jgvtOKEla', '', 'Lpz', 'nct', '', 'IGBvDyRKdVzCVEyluAfqrTDnaVgsweyzEAnEHynAjhfZJLsXVLrYQeqiInEtEXflcXavtMBvgcmFvFOxKaQdNZjfKcuIkDtOifTTjyiHiHNeusITKucWmoePChjEXojS', 'eOW', 'cpD', '', 'NJeuDvmlpEfRuowpZGKHTkRxDSfCpzbhhmSyxboBIbihuxghRifnOycaBzDCLeZbAAGK', 'cm', 'hfPV', 'bi', 'uKJweVQoUeEbUmVraphNQFiCwvKbcskKNdWKtbylYISzhkYxbSffxGRXXutEpOTvUaKuwqhiLGVinGBHvGmWkJoyFbajSrNQlnKZoocfidprDCJNEdnlzynDVIMAPKyQPIlLnPcuWTs', 'io', '', 'gkFpbEpaRE', 'ohgNriPwaoWlLIeqOlBFVUuuTROlJRsiORikUlTvgeXLbCYLBVbsapZJPRTAHRunxmukYTAsnfXAUDPTCqbJOBAOwiSNhxxROHOfAyFNLqpWWZYipcvEXTLswgdfnwPWPCdFgtyQnQbOmB', 'LI', 'kaiRL', 'ADsYrWnOhxO', 'vKFSFlpOGLe', 'lXw', '', 'kgNSwMgW', 'auRjfKcdQDgzWePOiOrajBhyJoMKyXfHxYzLOyHfnvhKMtdEIuHRSLkLrcqzeYhRDdYoZeypoXoxRyyVxqunlkBWEqrHGzbnWhiwCRsnEKKquyhxPTQutUmwsqRJWvxZyqSzPWpfPzd', 'LxF', '', 'v', 'YvhQUIFCWtKeKtDkOXCWRBrkLcmgvARbJDkaWrYDWEcxotKyUrwEantPGxDVTZnvkUejmrRaQhMgBKUdPhomeeZpwXrnverxNHUdavzWWsnlgwKPzTHJlVApGYbzzyinVdHQfOUEHpitbi', 'Zxf', 'pFTuAAQ', 'wRodNwFKThQV', '', 'CIGp', 'PPnd', '', 'X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usM', '', '', 'BmZCGYYDJL', 'JHyfkflQFBSweHAJRaVGPcQXETborRBQNcHZZuIMuwBYRkFIAUEcShCMtvaDzHWpObdytUQRHILLKDaWXeXhhrHBuYZHOZaXjjQZOKTWJQAxRLHzvhywqskXtTdMckXlcybuQAaVRnhFWW', '', 'Z', 'JTGSSrybSlhFfZ', 'EEhrxonpGTV', 'f', '', 'AiRbDhEq', 'pcYdZQLbvHdRXuAzqQpvQAObKgYprkUUeQlEjOdZWrlVvQHIlrHrUuQzypklyWjUHUHzqHilpACcNOwjdMhzzgENGfDAmhDxLvXybtNSYpxmPDYKlncMFcJAsAChXLNiceM', 'GNFOkUNBxrHAumDVvBdaFcjKJjQHnIQufSMvytCckkytLzAwgBoqlDLSkVxCeBKDRprIVEVOqUrNWfpTmgNuMxJPsvKgRntgYgHovbJqltiOECAvhRxWUFNHiNFZjhERA', 'jtGENco', '', 'lVMvpSRkIjhSLPyrDQtMtbGxFZJReqsOwKcscprsYSVuDspEnJkbStWmWBSPpWKWHCmsFINLWqaikdoCrZpCQhCczSYJeFEpwsjEmWUtZacbKrbwxiuebyvqsvJlJFyRbiXpLVtPPcUmoqTPismSUehIqycLzVRFEIqMeOnGplwBmNtnVkmBNLQxprpBAEtlxXtx', '', 'Ozl', 'Hc', 'mMyhtraFmhHkxERpKFMmGiiBtbYmrOjoNNBlcTmqkPBfTEIyEpQsADhkS', '', 'Z', '', 'HdHFlXDRmauPXiYeWzwbfrBflUAlwHbcnOaKfzYfqIuqYZuHhpAJNDYT', 'w', '', 'MKLMAsPUCZjDLzsVSAdgDHUbdbCvHhGffloXCTBYnIyvTTVIoZlOaIWyYUTYHqsYdwcTeiOtWXDvLmzseOXipopcIlwEbPmTXqcqNnABKHHTwYrIfwSKfJQfxTNXzkzr', 'cIsHWqVuCZF', '', '', 'WpAUGgCdawSdIufv', 'wSAghdjBotQUoncLYNIRuSlnrRxuGfmRFjIjpzJLNVKrinwSbUsjfkcocfNaNwaFmGWwXltYiIGXPspgUGfDEuBtggPBrHbpgAtHRktDtRnfSiVxLSrefrEpAKgqZNFNXIa', 'tmogryTNcxkfKhfxQnNZKbizpyECQMAeAqEUqyoFwYMRwogVfNfapaRaATLDJprmMtJOmgibREQwBausESnWcABoEABaTwLkGDkXaVKKTVVVIshexgEMFApaCFxvbHzo', 'pPzIOlMe', '', 'OHHHEjCkUWtJAgADFdkrQmEoIHwYfBynbiMMoGgByIGuiUytyNGkbHiZSXimOZsXADJF', '', 'YF', 'g', 'HTSqQZpokJQHIRDfriqMQpDTVdwkrLcUzHMQvxdRSBbXADicDfzVDgRVZpElAJlcJJdprs', '', 'E', 'F', 'SWBqxYoayOdUigorroFGBurQPLyVbTGEIWoDHfjwdwdTIOVympnayDQqDvZjYByaacQleMvvSNotNGqxWsZrSetsLGPvaJpAGYnhTilSCkorxNSzDLyDIfIOPVBTKkcNmEkJytRSJabncLwzdX', 'huDx', 'sVmdRtUuYgBFipXCjlyXeXCuRLGChDSHUmwJKwpDtnlkOuYGamsZPgcPEQbmdnuoUAwdqOREWyvlKuhfhOmaSyAYNzEVbdqLVNMSnBMgmOqyWTwtnETeNGLlFDVIcHNNly', 'ymdqvKlhEfCVMIPYDatWkbXshiwHKFUFLBCtTGHhXlffAgZbCOgCQteIsuPrSfDAqbKNLMchzkDDHZIbKnJAYjrOqAkoDwzdhQDEmpVAGnQgYKoXzbu', 'bnJR', 'gDgdRaIcEBvcZKeAzWMFNRuPziGtXgIQbvgmGIxVcWGnkTDbuEzdaenWTzNzWACxOjPqLzwLOnIwOiIMhSznUXRJgggJJSKePRquwzfogdKtgsIRXUZbyDmqVanfvZxCXLIQzag', 'BDcgROwtBbFLEmnyELZSrjWdrHXSFTHDYCSWkVbKvSKImjNTdWPEepKphGwoVQdiBHFriDvFbvAVGQHpckcLYHfmOAsvvnzYBYozFlVrxmQvVEgjtOu', 'khqDGzooGatxHZkkCtWKZIwcoJVCHZlpjNetiOXHJAtfkVPsIRicwAQsHlqYdGoSStjWfDQacpoTFhBlK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gQhdHXfxebdqiziWaqTejCUudlopYGlHEMtcdCUn', 'begOLUhSqKUAFumNaUQpTssaiKKOmqHmCepAHPmiZuYkBdgFHwPLqrrmmrRFQkjVgkkVCUlmqWNkmzKfgXPGvGUSvRjUWemddwvYX', 'cFlCgyZCaszqnfcGZtBRbJaqFBuvHJJJCpQrESkBmSfzLqiJKsdptAeyvEGqjdwUCjLfHVEfXaLyvDfsugXDEiJErhwhJadCdiwTIzogAGULIR', 'gCXeYwYOAhMiqusoitGccSjrQyEUGkhmpbdTsroOOpWwcYepXRpTUirQmQePpGFNGusLSnIQkturBgmVctkvlVlJelFKvWPmkRoRrXMipZTCUygaRcghLX', 'NUPW', 'jJZxzyahAVfxGzBGtRyHhnyaSyIvfVdqAPoAACYfPIZJteyYnoFDCKWbmkakaDamZISxqhvliATwUbSSSpDGoqIZOEZrRSRZWhmrkbCXxYKcAUJXaelagcKEwEDqtcOGLlONdH', 'GqCbZmKKATuVOtjERWrMVJzdEDfQrLWqBWqVQkmzHbbBZVHJIfztreYdWAaWEYsImPnnJzqyl', 'SHgDLpbxsXxIajZxiDdGiEWXVmAXqWUkJqvaPqiaGZaEJevZWGAlCaLzXLiufRqxRrxAlyedQzCFGD', 'VvqoEVGNILCWbnupygxZavYMqAQepxnNGplszoAcAYfNIcXwTgxyiYSSJhcZyFKundWTJdfROLgBtJMD', 'PpKsrTqKXKHrrxsYbiizmypMqEMGJkjIZcDPRKPjkqULZWNkdcrpYDMhwaaHnlxtlPOmOrMJzISJctqWbVvmO', 'uTcGUBDtXKvXQosTqcbBKbLbBNSQiStMTAysRZPaPfjKglYtrsmUPKvldRFkefGSYNIldOfbGaquwQxsUrBY', 'KCvP', 'jodOEkxcxDCTfteiZagyxzfRpqavpcSYlImQyxBKsBqdCbKwCPmUZsRDwObMgJBgcBAXXtShqXesiIrjDSzDWIPSPxZBuGPwipDsArHUZuUORrlUlaBgHvLAxNANrcAFxc', 'TfZvMctLJLXMTDvggszHUbCKwjDSqPpWSGEWZ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QvWHFeEWxJFPE', 'HAiQIpplytcarthxRMFCqzQQHygYWVQKfetkJGhnqmVSUTOG', 'AdMAnybZWUMxcVySZFmdFtxITyCYJaKDJMHRgFziSEAsjaYNA', 'VervlyURgqyJpVsMWyvXmOVmlPnetgpBXFVacdgodBzPazvzZdnkY', 'DOhwiHOrbHRbvAMUknkjvZtxZbXuxlEhjOPWtDEJaszJrywzOAwWIpTuU', 'hTcDeqCuDJIiseivkcYdqOoBswDfNgfEcZiaUeqPMdyPDmERP', 'XJkNvJaXZjRkoiPiDRUDuslXfWhwKgeyBZTOaTeKTxqopSaO', 'DXgcTWnxyLSZNtjbbnurmWWpJckIUlVTscVKhzMLfLdDKjpUJv', 'vJikqsUUrCuQxPyIKwpryyolqFfPdDAmIauaTiewVAXRazKQkaKBS', 'CcPUrAYHfuJzUKqOxehVBoAfLLQTHIMPkGYBhIVILotEeONktDEKx', 'BpqURTkOyNCFRqZPAYtANrlMBSXdSydLTitXVtUgcIHVgDelesEjIHI', 'wPQBDKqTAHzTILYQEatcGhOIsAwrNPiQieGNdnsIszYhuEXqVpPxLsICK', 'TdJLmUcVBVVluAiodptdGeXzqFRoEvEEsaaqbgcxuljOdnmiREOszkg', 'yQkDmCfxeDmcEaVffaFydivyeiNGitkybBmhRHjiSMEtlkEtFnjggw', 'sUcNSUhgjXYNAqwxqdPhmRtVYTiLQRFEYTQanjLVsKeTHXkrs', 'QVYFxfWowFcWXmeocSElcxYUqadgORQOxziSMQJGexZQhAxHdsa', 'CWESPCoAzIuJWIrjRPNDkKyouxfeJwegXWRxTWODYkjwYvBBFjpIWSkb', 'qRUsmleQdFUPgipnczcDKVdtfUaXAMOshUzQRBQFeZtPYKPIw', 'qFHHymyQtNpoRdeMIaIwOUitwCohZovBNvQFWwQybeaKZhQK', 'ZBfogWzRCwaaHMGuLciednEpNuqnDQxDphsUZJSPQyVoaILC', 'LHxTsKkMPyFKMxLEfIvVpmveKAvkEDlBqZFuBQJQQIxtYNSQR', 'VuShJAWCeXwJxXvERTWWaUMpiWnMoYETWlQudDSLKqQSxSfX', 'KkYqwDNQwWpiFYxHtUsKOrpvqZXmuPMgtmXCVgXcfjmelihjX', 'vgbRMfkCXtWcckCuvJjEoGrvJcBzWvLWVDvFhYsPVUAxiSMpOaNP', 'FDWYnyWuRWTmNEBbpRggdVgzyznYPHgOCvaVnabhWoEcSHHyhomw', 'aVlAAqAcrSkoCvYZFl | python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | true |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/UACTF/2022/crypto/Non-textualTroubles/xor.py | ctfs/UACTF/2022/crypto/Non-textualTroubles/xor.py | from random import seed, randrange
seed(True, version=2)
with open("plaintext.txt", "r") as read, open("ciphertext.txt", "w") as write:
plaintext = read.read()
for char in plaintext:
A = ord(char)
B = randrange(256)
ciphertext = chr(A ^ B)
write.write(ciphertext)
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/TokyoWesterns/2018/EscapeMe/pow.py | ctfs/TokyoWesterns/2018/EscapeMe/pow.py | #!/usr/bin/env python2.7
#
# Copyright 2018 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from hashcash import check
import random
import string
import sys
import os
import resource
SKIP_SECRET = sys.argv[1] if len(sys.argv) > 1 else None
bits = 25
rand_resource = ''.join(random.choice(string.ascii_lowercase) for i in range(8))
print 'hashcash -mb{} {}'.format(bits, rand_resource)
sys.stdout.flush()
stamp = sys.stdin.readline().strip()
if SKIP_SECRET is None or stamp != SKIP_SECRET:
if not stamp.startswith('1:'):
print 'only hashcash v1 supported'
exit(1)
if not check(stamp, resource=rand_resource, bits=bits):
print 'invalid'
exit(1)
print 'Any other modules? (space split) > ',
sys.stdout.flush()
mods = sys.stdin.readline().strip()
if '/' in mods:
print 'You can load modules only in this directory'
exit(1)
args = ['./kvm.elf', 'kernel.bin', 'memo-static.elf']
args += mods.split()
print '\nexecuting : {}\n'.format(' '.join(args))
dirname = os.path.dirname(__file__)
os.chdir(dirname)
os.close(2)
os.open('/dev/null', os.O_WRONLY)
resource.setrlimit(resource.RLIMIT_NOFILE, (9, 9))
os.execv(args[0], args)
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/TokyoWesterns/2020/vi-deteriorated/run.py | ctfs/TokyoWesterns/2020/vi-deteriorated/run.py | #!/usr/bin/python3
import pty
pty.spawn("./vid")
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/WxMCTF/2024/rev/Recursive_Combinatorics/rev4_5s33Foa.py | ctfs/WxMCTF/2024/rev/Recursive_Combinatorics/rev4_5s33Foa.py | from hashlib import sha512
def acid(s):
return sha512(s.encode('utf-8')).hexdigest()
def ___(n, k):
a = 0
for _ in range(1, k+1):
j = 0
while(n>=(1<<j)):
a += n&(1<<j)
j += 1
return a
def rock(a, n):
if n == 0:
return 1
return a*rock(___(a, a),n>>1) if(n&1==1) else rock(___(a, a),n>>1)
def paper(n):
x = rock(n, n)
return {i: [(1<<i>>i)-1, 1<<i, (1<<i)<<1, ((1<<i)<<1)+(1<<i)] for i in range(x)}
def scissors(n, a, x):
if n == 0:
return [0]*x
ls = [int(n%a)] + [int(n%a) for _ in range(n) if (n := n // a)]
ls += [0]*(x-len(ls))
return ls
def go(n):
final, lib, x = 0, paper(n), rock(n, n)
for i in range(1<<(x<<1)):
ls = scissors(i, 4, x)
tot = sum( [lib[j][ls[j]] for j in range(x)] )
final += int(tot == n)
return final
number = int(input("Enter your number: "))
print(go(number)) | python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/WxMCTF/2024/rev/Binary_Conspicuous_Digits/encrypt.py | ctfs/WxMCTF/2024/rev/Binary_Conspicuous_Digits/encrypt.py | #!/usr/bin/env python3
flag = 'wxmctf{REDACTED}'
encoded = ''
for c in flag:
encoded += ''.join(map(
lambda x: format(int(x), 'b').zfill(4),
str(ord(c)).zfill(3)
))
with open('output.txt', 'w') as output:
output.write(encoded)
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/WxMCTF/2024/crypto/3_5_business_days/chal_Z0ks27x.py | ctfs/WxMCTF/2024/crypto/3_5_business_days/chal_Z0ks27x.py | import os
from Crypto.Util.number import *
ks = [bytes_to_long(os.urandom(16)) for i in range(11)]
s = [250, 116, 131, 104, 181, 251, 127, 32, 155, 191, 125, 31, 214, 151, 67, 50, 36, 123, 141, 47, 12, 112, 249, 133,
207, 139, 161, 119, 231, 120, 136, 68, 162, 158, 110, 217, 247, 183, 176, 111, 146, 215, 159, 212, 211, 196, 209,
137, 107, 175, 164, 128, 167, 171, 132, 237, 199, 170, 201, 228, 194, 252, 163, 172, 168, 179, 145, 221, 222, 255,
98, 184, 150, 64, 216, 157, 187, 147, 97, 152, 148, 190, 203, 193, 62, 143, 56, 156, 153, 236, 188, 134, 230, 83,
160, 59, 219, 76, 11, 144, 178, 254, 218, 244, 227, 96, 232, 220, 213, 165, 6, 186, 226, 239, 200, 242, 7, 154,
180, 140, 48, 248, 135, 233, 166, 234, 192, 28, 202, 27, 24, 243, 82, 22, 185, 122, 115, 93, 13, 113, 85, 21, 52,
55, 38, 57, 78, 66, 46, 71, 189, 195, 100, 103, 1, 72, 208, 99, 105, 74, 101, 94, 61, 240, 25, 23, 18, 84, 138, 87,
26, 60, 204, 17, 49, 53, 169, 14, 121, 0, 79, 177, 4, 63, 241, 3, 77, 37, 2, 15, 108, 73, 118, 30, 33, 20, 54, 43,
197, 92, 75, 95, 198, 205, 19, 142, 29, 86, 35, 109, 235, 174, 114, 210, 65, 246, 70, 80, 223, 8, 245, 182, 45, 69,
149, 129, 90, 224, 39, 206, 130, 126, 10, 88, 91, 253, 58, 89, 81, 117, 34, 106, 124, 41, 51, 229, 40, 44, 238,
173, 5, 9, 42, 102, 225, 16]
rots = [11, 26, 37, 49, 62, 73, 89, 104, 116]
def pad(msg, l):
x = l-(len(msg))%l
return msg+bytes([x]*x)
def lpad(msg, l):
return msg+bytes(l-len(msg))
def xor(a, b):
return bytes(i^j for i, j in zip(a,b))
def splitBlocks(pt, l):
return [pt[l*i:l*i+l] for i in range(len(pt)//l)]
def rot(x, n):
return ((x >> n) | (x << (128 - n))) & ((1 << 128) - 1)
def doSbox(block):
bs = lpad(long_to_bytes(block), 16)
return bytes_to_long(bytes([s[i] for i in bs]))
def encBlock(pt, iv):
block = pt ^ ks[0]
block = doSbox(block)
for i in range(9):
block ^= ks[i + 1]
block ^= rot(iv, rots[i])
block = doSbox(block)
block ^= ks[-1]
return block
def enc(pt):
pt = pad(pt, 16)
blocks = splitBlocks(pt, 16)
iv = os.urandom(16)
ct = iv
for i in blocks:
ct+=lpad(long_to_bytes(encBlock(bytes_to_long(xor(ct[-16:], i)), bytes_to_long(iv))), 16)
return ct
flag = os.environ.get("FLAG", "wxmctf{dummy}").encode()
print(enc(flag).hex())
while True:
inp = bytes.fromhex(input("Gimme ur plaintext block: "))
iv = bytes.fromhex(input("Gimme ur iv: "))
assert len(inp)==16
assert len(iv)==16
print(lpad(long_to_bytes(encBlock(bytes_to_long(inp), bytes_to_long(iv))), 16).hex())
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/WxMCTF/2024/crypto/Espionagey_Crafty_Clues/jumbler_QWGaWww.py | ctfs/WxMCTF/2024/crypto/Espionagey_Crafty_Clues/jumbler_QWGaWww.py | import random
gen = [XXXXXXXX] # Past generator points
x1 = [] # First half of the x-coords
x2 = [] # Second half of the x-coords
y1 = [] # First half of the y-coords
y2 = [] # Second half of the y-coords
for i in gen:
x = str(i[0])
y = str(i[1])
x1.append(x[0:len(x) // 2])
x2.append(x[len(x) // 2:len(x)])
y1.append(y[0:len(y) // 2])
y2.append(y[len(y) // 2:len(y)])
for i in range(32767):
random.shuffle(x1)
random.shuffle(x2)
random.shuffle(y1)
random.shuffle(y2)
coords = list(zip(x1, x2, y1, y2))
for c in coords:
print(c)
# Output
# ('6083541', '70208246', '12183899', '05162877')
# ('1152823', '0965475', '30207985', '05181068')
# ('6153634', '54008046', '30816494', '06143057')
# ('5598253', '9499216', '10641890', '08809654')
# ('40427750', '97139558', '4993690', '73140782')
# ('58544347', '0898815', '2423158', '32131699')
# ('50076906', '4590531', '7041427', '11019654')
# ('1086272', '6907039', '3698478', '19160446')
# ('3824463', '77724465', '15155162', '41560946')
# ('7169758', '0435191', '6696910', '63790720')
# ('54742595', '84679407', '7960660', '09396231')
# ('21573556', '85818785', '26820913', '14682461')
# ('2538734', '8155665', '8039628', '97583027')
# ('173312', '1822597', '14767541', '59813618')
# ('57621461', '50600003', '9655056', '48435717')
# ('13529234', '20347874', '5467054', '07539449')
# ('4479258', '52052811', '19942058', '72408483')
# ('730514', '9075384', '2536379', '82436556')
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/WxMCTF/2024/crypto/racing/chal.py | ctfs/WxMCTF/2024/crypto/racing/chal.py | import os
from Crypto.Util.number import *
def rng():
m = 1<<48
a = 25214903917
b = 11
s = bytes_to_long(os.urandom(6))
while True:
yield (s>>24)%6+1
s = (a*s+b)%m
r = rng()
cpuPlayers = [0]*6
yourPlayers = [0]*6
def printBoard(cpu, your):
board = [[] for i in range(100)]
for i in range(6):
if cpuPlayers[i]!=None:
board[cpuPlayers[i]].append("C"+str(i))
if yourPlayers[i]!=None:
board[yourPlayers[i]].append("Y"+str(i))
print(*board)
cpuScore = 0
yourScore = 0
while any(i!=None for i in yourPlayers) and any(i!=None for i in cpuPlayers):
printBoard(cpuPlayers, yourPlayers)
#CPU goes first
x = next(r)-1
while cpuPlayers[x]==None:
x = next(r)-1
cpuPlayers[x]+=next(r)
for i in range(6):
if yourPlayers[i]==cpuPlayers[x]:
yourPlayers[i] = None
for i in range(6):
if cpuPlayers[i]!=None and cpuPlayers[i]>=100:
cpuPlayers[i]=None
cpuScore+=1
printBoard(cpuPlayers, yourPlayers)
#your turn next
x = int(input())
assert 0<=x<=5 and yourPlayers[x]!=None
yourPlayers[x]+=(next(r)-1)%3+1 #player disadvantage
for i in range(6):
if yourPlayers[x]==cpuPlayers[i]:
cpuPlayers[i] = None
for i in range(6):
if yourPlayers[i]!=None and yourPlayers[i]>=100:
yourPlayers[i]=None
yourScore+=1
cpuScore+=6-cpuPlayers.count(None)
yourScore+=6-yourPlayers.count(None)
if cpuScore==0 and yourScore==6:
print("Congrats on winning! here's your flag")
print(os.environ.get("FLAG", "wxmctf{dummy}"))
else:
print("Not good enough or you lost :/")
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/WxMCTF/2023/rev/NaturalSelection/main_xiRTmuC.py | ctfs/WxMCTF/2023/rev/NaturalSelection/main_xiRTmuC.py | from base64 import *
from os import *
from sys import *
exec(b64decode("aW1wb3J0IGJhc2U2NAoKYiA9IGludChpbnB1dCgiYmFzZSA/IGRlY29kZT8gIikpCgpleGVjKGdldGF0dHIoYmFzZTY0LCBmImJ7Yn1kZWNvZGUiKSgiTVY0R0tZWklNSTNESVpERk1OWFdJWkpJRUpORzRTVFdNSkpVRU1EQks0WVdZU0tITlIyR0dSWlpQRlNFR1FUMk1KRFZNM0RESUZZRzJZU0RJRTRVU1IzTU9WUlVRVlJRSk5CVVVXREJJNUREQVNLSEtKM0VTU0RNT1pTRkdRUlFNRkRXWTVMQlBGQkRBWUtIS1ZUVlUzTFlOQk5IU1FUUU1ONURTWTNDTkZFWEFRM09KWlpWVVYyV081RlVJUUxWSlpCV1dTM0RKQkZIQVlUT0tGWFVTMjNJT1JSRkdTTFFJTlhFNDQyMks1TEhPUzJFSVYyVTQyTExKTlJVUVNUUU1KWEZDMzJKTk5WV09aQ0hOQllHRTNMVE01U1ZPT0pSSklaVVUzQ0pKQlNIU1lSU0dWWEVZUTJDTkZTRlFVTEhNSkRWTU1DS0dOR1dPWkNJSkkyVVNSMkdPVlNWUVpESU1WTUUyMktMS0ZZR1laS0hLWlZFV1IySkdKSEVPVVRNTEVaRFMyMjJLTlRXU1dLV01ONEdJTVNKUEpKV1VRU0tLTkRFVTUyWk5SU0ZNVVpTSlpFVkczU0NORlJHWVJUV0tOTFhJTkRFTlJXRlFWTE9JSlVXRVYyT09CS0VLVFNETUpEVVU1Q1ZLUldFVVlLVk5SNUZHVkxFTUZSVEVVU1pLUldUU1VLV05SRkRLV1NHTVJMR0dSS09PUkxXNFdUS01GS1VVNTJUS1ZTSEdaQ1ZOUkVWRzN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k02U0VLSkpFQT09PT09PSIpKQ==")) | python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/WxMCTF/2023/rev/Brainf/interpreter.py | ctfs/WxMCTF/2023/rev/Brainf/interpreter.py | import sys
TAPE_SIZE = 500
def run(code):
stack = []
lmatch = dict()
rmatch = dict()
for i in range(len(code)):
if code[i] == '[':
stack.append(i)
elif code[i] == ']':
lmatch[i] = stack[-1]
rmatch[stack[-1]] = i
stack.pop()
tape = [0] * TAPE_SIZE
iptr = 0 # instruction
mptr = 0 # memory
while iptr < len(code):
instr = code[iptr]
if instr == '>':
mptr += 1
elif instr == '<':
mptr -= 1
elif instr == '+':
tape[mptr] += 1
tape[mptr] %= 256
elif instr == '-':
tape[mptr] -= 1
tape[mptr] %= 256
elif instr == '.':
print(chr(tape[mptr]), end='', flush=True)
elif instr == ',':
tape[mptr] = ord(sys.stdin.read(1)) % 256
elif instr == '[':
if tape[mptr] == 0:
iptr = rmatch[iptr]
elif instr == ']':
if tape[mptr] != 0:
iptr = lmatch[iptr]
iptr += 1
if __name__ == '__main__':
run(open(sys.argv[1]).read())
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/WxMCTF/2023/crypto/Permutations/main_njzMd2E.py | ctfs/WxMCTF/2023/crypto/Permutations/main_njzMd2E.py | import random
from Crypto.Util.number import *
from Crypto.Cipher import AES
from hashlib import sha256
import os
N = 100000
flag = b'wxmctf{REDACTED}'
f = open("out.txt", "w")
def compose(a, b):
r = []
for i in range(N):
r.append(b[a[i]])
return r
G = [x for x in range(N)]
random.shuffle(G)
print(G,file=f)
def mult(p, c):
if c == 0:
return [x for x in range(N)]
elif not c%2:
return mult(compose(p, p), c>>1)
else:
return compose(p, mult(compose(p, p), c>>1))
a = bytes_to_long(os.urandom(40))
b = bytes_to_long(os.urandom(40))
A = mult(G, a)
B = mult(G, b)
print(A,file=f)
print(B,file=f)
s = mult(A, b)
assert s == mult(B, a)
iv = os.urandom(16)
aes = AES.new(sha256(str(s).encode()).digest()[:16], AES.MODE_CBC, iv=iv)
print(iv.hex(),file=f)
print(aes.encrypt(flag).hex(),file=f)
f.close()
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/WxMCTF/2023/crypto/maze/maze_zS72xsE.py | ctfs/WxMCTF/2023/crypto/maze/maze_zS72xsE.py | #!/usr/local/bin/python3
from random import getrandbits
from hashlib import sha256
from console.utils import wait_key
from console.screen import Screen
class PRNG:
def __init__(self, seed):
self.state = seed
self.mul = 25214903917
self.add = 11
self.mod = 1 << 48
def next(self):
self.state = (self.mul * self.state + self.add) % self.mod
return (self.state >> 17) % 6
def generateMaze(seed):
maze = []
prng = PRNG(seed)
for _ in range(144):
maze.append(prng.next())
maze = [maze[i:i + 12] for i in range(0, 144, 12)]
for i in range(12):
for j in range(12):
if maze[i][j]:
maze[i][j] = "0"
else:
maze[i][j] = " "
maze[0][0] = "@"
maze[11][11] = "X"
return maze
SOLID = '╔║╗╚═╝0'
def draw():
global screen, playerX, playerY
print(screen.clear, end='')
with screen.location(0, 0):
print('╔' + '═' * 12 + '╗')
for y in range(12):
with screen.location(y + 1, 0):
print('║' + ''.join(maze[y]) + '║')
with screen.location(13, 0):
print('╚' + '═' * 12 + '╝')
def processInput(key):
global playerY, playerX
if key in 'A':
if playerY != 0 and maze[playerY - 1][playerX] != "0":
maze[playerY][playerX] = " "
maze[playerY - 1][playerX] = "@"
playerY -= 1
elif key in 'B':
if playerY != 11 and maze[playerY + 1][playerX] != "0":
maze[playerY][playerX] = " "
maze[playerY + 1][playerX] = "@"
playerY += 1
elif key in 'C':
if playerX != 11 and maze[playerY][playerX + 1] != "0":
maze[playerY][playerX] = " "
maze[playerY][playerX + 1] = "@"
playerX += 1
elif key in 'D':
if playerX != 0 and maze[playerY][playerX - 1] != "0":
maze[playerY][playerX] = " "
maze[playerY][playerX - 1] = "@"
playerX -= 1
elif key in chr(3):
print("Ctrl-C")
exit()
def win():
global screen
draw()
with screen.location(15, 0):
print("Congratulations! "+open("flag.txt").read())
with screen.location(17, 0):
print("Press any key to exit...")
wait_key()
exit(0)
def playMaze(seeds):
global screen, maze
maze = generateMaze(seeds)
with screen.fullscreen():
while True:
draw()
key = wait_key()
processInput(key)
if playerX == 11 and playerY == 11:
win()
screen = None
playerX = 0
playerY = 0
maze = None
def pow():
val = hex(getrandbits(24))[2:]
print("Give me a string containing only printable characters whose SHA256 hash ends in " + val.rjust(6, '0') + ".")
s = input()
if not (s.isprintable() and sha256(s.encode()).hexdigest().endswith(val)):
print("Incorrect or your string was not printable")
exit()
#Super jank pow solver but for those who are too lazy to make their own here you go
def solvepow(s):
import random
from hashlib import sha256
a = random.randint(0, 1<<256)
while True:
if sha256(hex(a).encode()).hexdigest().endswith(s):
return hex(a)
break
a+=1
def main():
print("Give me your seed!")
seed = int(input())
print("Ready?")
input()
playMaze(seed)
if __name__=='__main__':
pow()
with Screen(force=True) as screen:
main()
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/WxMCTF/2023/crypto/CommonRoom/chall.py | ctfs/WxMCTF/2023/crypto/CommonRoom/chall.py | from Crypto.Util.number import *
from Crypto.Random.random import *
p = getPrime(1024)
q = getPrime(1024)
n = p*q
flag = bytes_to_long(open("flag.txt", "rb").read())
iv = getrandbits(1024)
def genPoly(iv):
ret = []
s = 0
for i in range(64, 0, -1):
a = getrandbits(1024)
ret.append(a)
s+=a*pow(iv, i, n)
s%=n
ret.append(p-(s%p))
return ret
with open("output.txt", "w") as f:
f.write(str(n))
f.write("\n")
f.write(str(pow(flag, 65537, n)))
f.write("\n")
f.write(str(genPoly(iv)))
f.write("\n")
f.write(str(genPoly(iv)))
f.write("\n")
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/WxMCTF/2023/crypto/LOCAL_HIDDEN_VARIABLES/author_q6CvOT9.py | ctfs/WxMCTF/2023/crypto/LOCAL_HIDDEN_VARIABLES/author_q6CvOT9.py | import base64
import RC4
flag = "CTF{CENSORED}" # CENSORED
rc4 = RC4.RC4("CENSORED", 0) # CENSORED, established 40-bit key
# the first number may be 8 and the last number may be 9
rc4a = RC4.RC4("CENSORED") # CENSORED, 16-bit pre-shared key
last = rc4.cipher(flag, "plain", "plain")
for i in range(3):
last = rc4.cipher(last, "plain", "plain")
last = rc4a.cipher(last, "plain", "plain")
print(base64.b64encode(last.encode()))
# b'cMK2wrkTJsOBDsOcwonCumDDiRfDpxcXY0wrwpNMfXvDpWLDh8KycsKpEA=='
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/WxMCTF/2023/web/NFTs/app.py | ctfs/WxMCTF/2023/web/NFTs/app.py | from flask import Flask, request, render_template, redirect, flash, make_response
from flask import send_from_directory
import os
app = Flask(__name__)
app.secret_key = os.urandom(16)
@app.route("/", methods=['GET', 'POST'])
def index():
if request.method == 'POST':
if 'file' not in request.files:
flash('No file part')
return redirect(request.url)
file = request.files['file']
if file.filename == '':
flash('No selected file')
return redirect(request.url)
if file:
file.save(os.path.join("./nfts/", file.filename))
return redirect(request.url)
return render_template('index.html')
@app.route('/nfts')
def browse_nfts():
nfts = os.listdir("nfts")
return render_template('nfts.html', nfts=nfts)
@app.route('/nft/<name>')
def send_nft(name):
return send_from_directory("nfts", name, mimetype="application/octet-stream", as_attachment=True) | python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/VishwaCTF/2023/rev/Phi-Calculator/Phi_Calculator.py | ctfs/VishwaCTF/2023/rev/Phi-Calculator/Phi_Calculator.py | #============================================================================#
#============================Phi CALCULATOR===============================#
#============================================================================#
import hashlib
from cryptography.fernet import Fernet
import base64
# GLOBALS --v
arcane_loop_trial = True
jump_into_full = False
full_version_code = ""
username_trial = "vishwaCTF"
bUsername_trial = b"vishwaCTF"
key_part_static1_trial = "VishwaCTF{m4k3_it_possibl3_"
key_part_dynamic1_trial = "xxxxxxxx"
key_part_static2_trial = "}"
key_full_template_trial = key_part_static1_trial + key_part_dynamic1_trial + key_part_static2_trial
star_db_trial = {
"Sharuk Khan": 4.38,
"Bollywood Star": 5.95,
"Rohan 16": 6.57,
"WISH 0855-0714": 7.17,
"Tiger 007": 7.78,
"Lalande 21185": 8.29,
"UV Ceti": 8.58,
"Sirius": 8.59,
"Boss 154": 9.69,
"Yin Sector CL-Y d127": 9.86,
"Duamta": 9.88,
"Ross 248": 10.37,
"WISE 1506+7027": 10.52,
"Epsilon Eridani": 10.52,
"Lacaille 9352": 10.69,
"Ross 128": 10.94,
"EZ Aquarii": 11.10,
"61 Cygni": 11.37,
"Procyon": 11.41,
"Struve 2398": 11.64,
"Groombridge 34": 11.73,
"Epsilon Indi": 11.80,
"SPF-LF 1": 11.82,
"Tau Ceti": 11.94,
"YZ Ceti": 12.07,
"WISE 0350-5658": 12.09,
"Luyten's Star": 12.39,
"Teegarden's Star": 12.43,
"Kapteyn's Star": 12.76,
"Talta": 12.83,
"Lacaille 8760": 12.88
}
def intro_trial():
print("\n===============================================\n\
Welcome to the Phi Calculator, " + username_trial + "!\n")
print("This is the trial version of Phi Calculator.")
print("The full version may be purchased in person near\n\
the galactic center of the Milky Way galaxy. \n\
Available while supplies last!\n\
=====================================================\n\n")
def menu_trial():
print("___Phi Calculator___\n\n\
Menu:\n\
(1) Estimate Projection Burn\n\
(2) [LOCKED] Estimate Slingshot Approach Vector\n\
(3) Enter License Key\n\
(4) Exit Phi Calculator")
choice = input("What would you like to do, "+ username_trial +" (1/2/3/4)? ")
if not validate_choice(choice):
print("\n\nInvalid choice!\n\n")
return
if choice == "1":
estimate_burn()
elif choice == "2":
locked_estimate_vector()
elif choice == "3":
enter_license()
elif choice == "4":
global arcane_loop_trial
arcane_loop_trial = False
print("Bye!")
else:
print("That choice is not valid. Please enter a single, valid \
lowercase letter choice (1/2/3/4).")
def validate_choice(menu_choice):
if menu_choice == "1" or \
menu_choice == "2" or \
menu_choice == "3" or \
menu_choice == "4":
return True
else:
return False
def estimate_burn():
print("\n\nSOL is detected as your nearest star.")
target_system = input("To which system do you want to travel? ")
if target_system in star_db_trial:
ly = star_db_trial[target_system]
mana_cost_low = ly**2
mana_cost_high = ly**3
print("\n"+ target_system +" will cost between "+ str(mana_cost_low) \
+" and "+ str(mana_cost_high) +" stone(s) to project to\n\n")
else:
# TODO : could add option to list known stars
print("\nStar not found.\n\n")
def locked_estimate_vector():
print("\n\nYou must buy the full version of this software to use this \
feature!\n\n")
def enter_license():
user_key = input("\nEnter your license key: ")
user_key = user_key.strip()
global bUsername_trial
if check_key(user_key, bUsername_trial):
decrypt_full_version(user_key)
else:
print("\nKey is NOT VALID. Check your data entry.\n\n")
def check_key(key, username_trial):
global key_full_template_trial
if len(key) != len(key_full_template_trial):
return False
else:
# Check static base key part --v
i = 0
for c in key_part_static1_trial:
if key[i] != c:
return False
i += 1
# TODO : test performance on toolbox container
# Check dynamic part --v
if key[i] != hashlib.sha256(username_trial).hexdigest()[4]:
return False
else:
i += 1
if key[i] != hashlib.sha256(username_trial).hexdigest()[5]:
return False
else:
i += 1
if key[i] != hashlib.sha256(username_trial).hexdigest()[3]:
return False
else:
i += 1
if key[i] != hashlib.sha256(username_trial).hexdigest()[6]:
return False
else:
i += 1
if key[i] != hashlib.sha256(username_trial).hexdigest()[2]:
return False
else:
i += 1
if key[i] != hashlib.sha256(username_trial).hexdigest()[7]:
return False
else:
i += 1
if key[i] != hashlib.sha256(username_trial).hexdigest()[1]:
return False
else:
i += 1
if key[i] != hashlib.sha256(username_trial).hexdigest()[8]:
return False
return True
def decrypt_full_version(key_str):
key_base64 = base64.b64encode(key_str.encode())
f = Fernet(key_base64)
try:
with open("keygenme.py", "w") as fout:
global full_version
global full_version_code
full_version_code = f.decrypt(full_version)
fout.write(full_version_code.decode())
global arcane_loop_trial
arcane_loop_trial = False
global jump_into_full
jump_into_full = True
print("\nFull version written to 'keygenme.py'.\n\n"+ \
"Exiting trial version...")
except FileExistsError:
sys.stderr.write("Full version of keygenme NOT written to disk, "+ \
"ERROR: 'keygenme.py' file already exists.\n\n"+ \
"ADVICE: If this existing file is not valid, "+ \
"you may try deleting it and entering the "+ \
"license key again. Good luck")
def ui_flow():
intro_trial()
while arcane_loop_trial:
menu_trial()
# Encrypted blob of full version
full_version = \
b"""
gAAAAABgT_nvHAwPaWal_64Giubfb7I87ML4ANp4g-eUbMTqsc4asWygnpXcaJ5FLahXXDcul9xPDqIPPytiZ9aMm25S6dgfi4ZPvM5IUSnnNjk6dxYAKsX5Yd72BV4ERrqdNNn2jZrphzlV4a4gY-XV_0ZHovFlHhEpPQnTtG_5RTETId0xAD5K5iActkI9a3P4sx6ExBQ082EuPFlnWtUGl0dsEDHher3xT_lZe9JP5UAcOJsoC9AJ7N3Y1KjWXATzaBkXw6XTnzqDHu9Ycffw-i-GfQP-16hF_f2WBE9nQqniFu6THNuAvqwg0XBnsfvV0Fo3MTpON6HpeI3eIXqd4tLtsfhNcPa99ugrucf0l19Z5eFvrtMMgmfW_9lgv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7vDSxHfnLKWI84IlAeU8NQE6drQd9IGQ9lRWZDzHgvz7dO6Og4pIt7Q6UA2NEIc6ZNDTsghtKFVep19d7nGJDt-4-UCFJSHWBhTKeqb_A34XO4T5U7x-CXqphsBwIdMoPXHrWxhoFYaP6lPJVOryz8TEYDLsHbVdmhYJtA0bPgMPC1rNI-SqcyUqvZFGpIJwDcGghTTS1u8XjMlRkxOxuEMDO364AdLtruslkXjpd2NuUBUFwNWbQbfYIC5mePqxc_PhcaVxMXHYrFh2CLqXX7UhcZxHT9C8RQ==
"""
# Enter main loop
ui_flow()
if jump_into_full:
exec(full_version_code)
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/VishwaCTF/2023/crypto/0_or_1/up_down.py | ctfs/VishwaCTF/2023/crypto/0_or_1/up_down.py | #Just a simple Python program. Isn't it??
k = "1010"
n = ""
for i in k:
if i == '0':
n += '1'
else:
n += '0'
print(n) | python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/VishwaCTF/2023/crypto/SharingIsCaring/challenge.py | ctfs/VishwaCTF/2023/crypto/SharingIsCaring/challenge.py | from sympy import randprime
from random import randrange
def generate_shares(secret, k, n):
prime = randprime(secret, 2*secret)
coeffs = [secret] + [randrange(1, prime) for _ in range(k-1)]
shares = []
for i in range(1, n+1):
x = i
y = sum(c * x**j for j, c in enumerate(coeffs)) % prime
shares.append((x, y))
return shares, prime
k = 3
n = 5
flag = open('flag.txt', 'rb').read().strip()
for i in flag:
shares, prime = generate_shares(i, k, n)
print(shares,prime,sep=', ')
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/VishwaCTF/2022/rev/BetGame/sage.py | ctfs/VishwaCTF/2022/rev/BetGame/sage.py |
sage_words = "ǏLJǣŻǏƟƣƷƫƣƷƛŻƷƓƛƓǏƣǗƓƯǣ"
def _0000xf69(passed_strr):
_0000xf42=''
for _0000xf72 in passed_strr:
_0000xf96 = _0000xf106(_0000xf72)
_0000xf42 = _0000xf42+chr(2*(ord(_0000xf96))+1)
return _0000xf42
def _0000xf106(passed_char):
return chr(2*(ord(passed_char))-1)
print("The biggest clue lies in your input")
_0000xf420 = input("Your input: ")
if sage_words == _0000xf69(_0000xf420):
print("!_h0p3_y0u_g0t_!t_n0w")
else:
print("t@k3_f3w_5t3p5_b@<k")
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/VishwaCTF/2022/rev/OneWayEnigma/OneWayEnigma.py | ctfs/VishwaCTF/2022/rev/OneWayEnigma/OneWayEnigma.py | from string import ascii_uppercase, digits
class rotors:
saved = {
1:('{K8UMNZBGS20D3IR_5CEFYOQPX4JH1VA}96TW7L',[9]),
2:('EFXRSBQ1MC3GYW_9{47AVT8JP5ON6U20ZK}HDIL',[23]),
3:('WUXQGVJHT2YO043MK17LC9ANZBP{_S6D}I5EFR8',[7]),
4:('W0K2NBVRPJTZY1XHD9478L{QUMG6I_O3FAS5}CE',[30]),
5:('V3F_1QA}L4WOZIM8SY7P9XG20CDNKJUH5B6ERT{',[13])
}
rotorSequence = {}
def __init__(self, **kwargs):
# default values
self.preset = 1
self.offset = 0
self.position = 0
# switching to given values
if "rotor_num" in kwargs: self.rotor_num = kwargs["rotor_num"]
if "preset" in kwargs: self.preset = kwargs["preset"]
if "offset" in kwargs: self.offset = kwargs["offset"]
if "position" in kwargs: self.position = kwargs["position"]
if "notches" in kwargs: self.notches = kwargs["notches"]
else: self.notches = rotors.saved[self.preset][1]
# setting up remaining properties
rotors.rotorSequence[self.rotor_num] = self
self.mapper(self.preset)
self.notch_found = False
def mapper(self, preset=1):
'''takes preset number as an argument and maps the\n
rotor wiring accordingly'''
statorKey = ascii_uppercase + digits + "_{}"
rotorKey = rotors.saved[preset][0]
map = {}
rotorMap = {}
for i,char in enumerate(statorKey):
map[char]=i
map[i]=char
for i in range(len(statorKey)):
rotorMap[i] = [map[rotorKey[i]]]
for i in range(len(statorKey)):
temp = rotorMap[map[rotorKey[i]]]
rotorMap[map[rotorKey[i]]] = (temp[0], i)
rotorMap["wiring"] = rotorKey
self.wiring = rotorMap
def rotate(self):
'''rotates the rotorset once (for each keypress)'''
# should this rotor make the next rotor rotate?
if self.position in self.notches and self.rotor_num < len(rotors.rotorSequence):
rotors.rotorSequence[self.rotor_num + 1].notch_found = True
# to rotate or not to rotate
if self.rotor_num == 1:
self.position +=1
elif self.notch_found:
self.position += 1
self.notch_found = False
# Completion of rotation >>> Reset
self.position %= 39
def passLeft(self, contact):
'''takes contact from right and sends to left\n
meanwhile taking care of rotation in the\n
FORWARD CYCLE'''
self.rotate() # Rotation prior to connection
LSCN = (self.wiring[(self.position-self.offset+contact)%39][0] - (self.position-self.offset))%39
return LSCN
def passRight(self, contact):
pass
class steckerbrett:
def __init__(self):
self.mapper()
def mapper(self):
statorKey = ascii_uppercase + digits + "_{}"
self.pairs = {}
self.map = {}
for i,char in enumerate(statorKey):
self.map[char]=i
self.map[i]=char
self.pairs[char]= char
def connect(self, char):
return self.map[self.pairs[char]]
def disconnect(self, contact):
return self.pairs[self.map[contact]]
def getSettings():
num = int(input('How many rotors do you want? >>> '))
settings['rotors']['sequence'] = []
for i in range(num):
rotor_num = int(input(f'Enter number of rotor {i+1} from 1-5 >>> '))
settings['rotors']['sequence'].append(rotor_num)
settings['rotors']['positions'] = []
for i in range(num):
position = int(input(f'Enter position of rotor {i+1} from 0-38 >>> '))
settings['rotors']['positions'].append(position)
return settings
def Enigma(settings):
plugboard = steckerbrett()
sequence = settings['rotors']['sequence']
positions = settings['rotors']['positions']
rotorSet = {}
for i in range(len(sequence)):
rotorSet[i] = rotors(rotor_num=i+1, preset=sequence[i], position=positions[i])
return plugboard, rotorSet
def Encrypt(message, enigma):
plugboard, rotorSet = enigma
encrypted = ''
for char in message:
contact = plugboard.connect(char)
for i in range(1, len(rotors.rotorSequence)+1):
contact = rotors.rotorSequence[i].passLeft(contact)
char = plugboard.disconnect(contact)
encrypted += char
return encrypted
def Decrypt(message, enigma):
pass
# Default Settings for The Enigma
settings = {'version':1,
'phrase':"Anyth1nG RanD0M Go3S HeR=E 69 And HWa+t CtuaLFck39875/",
'rotors':{'sequence':[1,1,1],
'positions':[11,22,33],
'offset':[15,2,31]}} | python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/VishwaCTF/2022/rev/OneWayEnigma/machine.py | ctfs/VishwaCTF/2022/rev/OneWayEnigma/machine.py | from OneWayEnigma import *
settings = getSettings()
encryptor = Enigma(settings)
print(Encrypt(input("ENTER_YOUR_SECRETS_HERE >>> "), encryptor))
# No. of rotors = 5, sequence = (5,3,1,2,4), positions = (?, ?, ?, ?, ?) | python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/VishwaCTF/2022/rev/RunTheCat/cat.py | ctfs/VishwaCTF/2022/rev/RunTheCat/cat.py |
CAT = int
cAT = len
CaT = print
RAT = str
CATCATCATCATCATCAT = RAT.isdigit
def Kitty(cat):
return RAT(CAT(cat)*CATCATCAT)
def CAt(cat, cats):
print(cat, cats)
cat1 = 0
cat2 = 0
catcat = 0
cAt = ""
while cat1 < cAT(cat) and cat2 < cAT(cats):
if catcat%CATCATCAT == CATCATCATCATCAT//CATCATCATCAT:
cAt += cats[cat2]
cat2 += 1
else:
cAt += cat[cat1]
cat1 += 1
catcat += 1
return cAt
def catt(cat):
return cat[::CATCATCAT-CATCATCATCAT]
def caT(cat):
return Kitty(cat[:CATCATCAT]) + catt(cat)
def rAT(cat):
return cat
def Rat(cat):
return "Cat" + RAT(cAT(cat)) + cat[:CATCATCAT]
def Cat(cat):
if cAT(cat) == 9:
if CATCATCATCATCATCAT(cat[:CATCATCAT]) and\
CATCATCATCATCATCAT(cat[cAT(cat)-CATCATCAT+1:]):
catcat = CAt(caT(cat), Rat(rAT(catt(cat))))
if catcat == "C20a73t0294t0ac2194":
flag = "runner_" + cat
CaT("So here you are!! VishwaCTF{",flag,"}")
else:
CaT("You are using right format, but answer is not correct\n>>", catcat)
else:
CaT("You are not using correct format :(\
\n(A small help from out side, Format should be like 123xyz789)")
else:
CaT("Wrong answer, check length :(")
CaT("What'S tHe aNsWer")
cat = input()
CATCATCAT = cAT(cat)//3
CATCATCATCAT = CATCATCAT+1
CATCATCATCATCAT = CATCATCAT-1
Cat(cat)
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/VishwaCTF/2022/crypto/JumbleBumble/script.py | ctfs/VishwaCTF/2022/crypto/JumbleBumble/script.py | import random
from Crypto.Util.number import getPrime, bytes_to_long
flags = []
with open('stuff.txt', 'rb') as f:
for stuff in f.readlines():
flags.append(stuff)
with open('flag.txt', 'rb') as f:
flag = f.read()
flags.append(flag)
random.shuffle(flags)
for rand in flags:
p = getPrime(1024)
q = getPrime(1024)
n = p * q
e = 4
m = bytes_to_long(rand)
c = pow(m, e, n)
with open('output.txt', 'a') as f:
f.write(f'{n}\n')
f.write(f'{e}\n')
f.write(f'{c}\n\n')
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/JerseyCTF/2025/pwn/Play_Fairi/file.py | ctfs/JerseyCTF/2025/pwn/Play_Fairi/file.py | import random
from random import randint
def reverseMe(p):
random.seed(3211210)
arr = ['j', 'b', 'c', 'd', '2', 'f', 'g', 'h', '1', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'y',
'v', '3', '}', '{', '_']
t = []
for i in range(len(arr), 0, -1):
l = randint(0, i-1)
t.append(arr[l])
arr.remove(arr[l])
arr.reverse()
for i in range(5):
s = ''
for j in range(5):
s += t[5*i+j]
o = ''
for k in range(0, len(p)-1, 2):
q1 = t.index(p[k])
q2 = t.index(p[k+1])
if q1 // 5 == q2 //5:
o += t[(q1//5)*5 + ((q1+1)%5)]
o += t[(q2//5)*5 + ((q2+1)%5)]
elif q1 % 5 == q2 % 5:
o += t[((q1//5 + 1) % 5 * 5) + (q1%5)]
o += t[((q2//5 + 1) % 5 * 5) + (q2%5)]
else:
o += t[(q1//5)*5+(q2%5)]
o += t[(q2//5)*5+(q1%5)]
print(o)
if __name__ == '__main__':
inp = "REDACTED"
reverseMe(inp) | python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/JerseyCTF/2025/crypto/CryptoPass_API/server.py | ctfs/JerseyCTF/2025/crypto/CryptoPass_API/server.py | #!/usr/local/bin/python
from Crypto.Cipher import AES
from random import seed,choices,randint
from os import urandom,environ
from string import ascii_letters,digits
seed(urandom(16))
charset = ascii_letters+digits
admin_id = "RokosBasiliskIsSuperCool"
master_key = urandom(16)
def crypt(data, iv, enc):
if type(data) != bytes:
data = data.encode("ascii")
integrity = AES.new(key=master_key, mode=AES.MODE_CFB, iv=iv, segment_size=128)
if enc:
return iv,integrity.encrypt(data)
else:
return iv,integrity.decrypt(data)
def sign_user(name):
iv, name_enc = crypt(name, urandom(16), True)
token = ".".join([x.hex() for x in [iv, name_enc]])
return token
def generate_admin(passwd: str):
true_pwd = environ.get("DEV_PASSWD")
if true_pwd == None:
return "Admin authentication not enabled currently"
if passwd == true_pwd:
return sign_user(admin_id)
else:
return "Wrong password"
def generate_token():
return sign_user("guest")
def info(token: str):
try:
token = token.split(".")
iv = bytes.fromhex(token[0])
data = crypt(bytes.fromhex(token[1]), iv, False)[1].decode("latin")
#open the default greeting for guest users
status = "ADMINISTRATOR" if data == admin_id else "USER"
try:
assert("." not in data)
vault = open(f"vault/{data}","rb").read().hex()
except (ValueError,FileNotFoundError,AssertionError):
vault = "NO DATA"
return vault
except Exception as e:
return "Invalid token"
while True:
print("Hello! Welcome to the CryptoPass Terminal")
print("[1] => Login as guest")
print("[2] => Login as admin")
print("[3] => Access your vault")
try:
inp = int(input("> ").strip())
except ValueError:
print()
continue
if inp == 1:
print("Here is your access token, guest:")
print(generate_token())
elif inp == 2:
pwd = input("Developer passcode: ").strip()
print(generate_admin(pwd))
elif inp == 3:
token = input("Authorization Token: ").strip()
print(info(token))
print()
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/JerseyCTF/2022/crypto/file-zip-cracker/FileZipCracker_Challenge_Version.py | ctfs/JerseyCTF/2022/crypto/file-zip-cracker/FileZipCracker_Challenge_Version.py | import zipfile
import itertools
from itertools import permutations
# Function for extracting zip files to test if the password works!
def extractFile(zip_file, password):
try:
zip_file.extractall(pwd=password.encode())
return True
except KeyboardInterrupt:
exit(0)
except Exception as e:
pass
# Main code starts here...
# The file name of the zip file.
zipfilename = 'secret_folder.zip'
numbers_set = '1235'
zip_file = zipfile.ZipFile(zipfilename)
for c in itertools.product(numbers_set, repeat=4):
# Add the four numbers to the first half of the password.
password = "Actor_Name"+''.join(c)
# Try to extract the file.
print("Trying: %s" % password)
# If the file was extracted, you found the right password.
if extractFile(zip_file, password):
print('*' * 20)
print('Password found: %s' % password)
print('Files extracted...')
exit(0)
# If no password was found by the end, let us know!
print('Password not found.')
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/JerseyCTF/2022/crypto/hidden-in-plain-sight/encryption.py | ctfs/JerseyCTF/2022/crypto/hidden-in-plain-sight/encryption.py | import base64
import os
from base64 import b64encode
from Cryptodome.Cipher import AES
from Cryptodome.Util.Padding import pad
key = "" # Don't worry damien. I hid the key. Don't worry about it. This encryption program is secure.
with open("flag_message_key", 'rb') as NFILE:
malware_code = NFILE.read()
cryptor = AES.new(key.encode("utf-8"), AES.MODE_CBC)
encrypted_data = cryptor.encrypt(pad(malware_code, AES.block_size))
IV = b64encode(cryptor.iv).decode("utf-8")
encrypted_data = b64encode(encrypted_data).decode("utf-8")
encrypted_data += (str(IV))
RANDOMIZER = 88888888
RANDOMIZER_2 = 4392049302
RANDOMIZER_3 = 93029482930
for x in range(1000):
RANDOMIZER_temp = RANDOMIZER_2 ^ RANDOMIZER_3
RANDOMIZER = RANDOMIZER_temp & 1111
RANDOMIZER = RANDOMIZER * 88
encrypted_data += (b64encode(key.encode("utf-8")).decode())
encrypted_dta = str(RANDOMIZER)
print("Key Length: "+str(len(b64encode(key.encode('utf-8')).decode())))
print("IV Length: " + str(len(IV)))
print("KEY: " + str((b64encode(key.encode("utf-8")).decode())))
print("IV: " + str(IV))
with open("encrypted.pco", 'a') as NFILE:
NFILE.write(encrypted_data)
# Hey damian slight hicup but I actually don't have the key at hand and I can't just send it to you over the internet
# Anyway just remember that the IV is of length 24 and the key is length 44. Follow the algorithm and you should
# be able to decrypt just about any message. Alright champ? Alright. Good talk. See ya. I hope you get this message.
# I put it down here cause its more secure right? I am just the best BOSS ever. Thank me on Monday.
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/SECCON/2021/pwn/seccon_tree/env/run.py | ctfs/SECCON/2021/pwn/seccon_tree/env/run.py | #!/usr/bin/env python3.7
import sys
import os
import binascii
import re
import subprocess
import signal
import string
import urllib.request
LIBFILE = "seccon_tree.cpython-39-x86_64-linux-gnu.so"
def handler(_x,_y):
sys.exit(-1)
signal.signal(signal.SIGALRM, handler)
signal.alarm(30)
def gen_filename():
return '/prog/' + binascii.hexlify(os.urandom(16)).decode('utf-8')
def is_bad_str(code):
code = code.lower()
with open("banned_word") as f:
l = f.read().strip("\n").split("\n")
for s in l:
if s in code:
return True
return False
def is_bad_char(code):
for c in code:
if c not in string.printable:
return True
return False
def is_bad(code):
return is_bad_str(code) or is_bad_char(code)
place_holder = '/** code **/'
template_file = 'template.py'
MAX_SIZE = 10000
def main():
print(f'Give me the source code url (where filesize < {MAX_SIZE}).')
print(f"Someone says that https://transfer.sh/ is useful if you don't have your own server")
url = input()
if not url.startswith("http"):
print("bad url")
return False
with urllib.request.urlopen(url) as res:
code = res.read().decode("utf-8")
if len(code) > MAX_SIZE:
print('too long')
return False
if is_bad(code):
print('bad code')
return False
with open(template_file, 'r') as f:
template = f.read()
filename = gen_filename() + ".py"
with open(filename, 'w') as f:
f.write(template.replace(place_holder, code))
os.system(f'cp {LIBFILE} /prog/')
os.system(f'timeout --foreground -k 20s 15s python3.9 {filename}')
main()
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/SECCON/2021/pwn/seccon_tree/env/template.py | ctfs/SECCON/2021/pwn/seccon_tree/env/template.py | from seccon_tree import Tree
# Debug utility
seccon_print = print
seccon_bytes = bytes
seccon_id = id
seccon_range = range
seccon_hex = hex
seccon_bytearray = bytearray
class seccon_util(object):
def Print(self, *l):
seccon_print(*l)
def Bytes(self, o):
return seccon_bytes(o)
def Id(self, o):
return seccon_id(o)
def Range(self, *l):
return seccon_range(*l)
def Hex(self, o):
return seccon_hex(o)
def Bytearray(self, o):
return seccon_bytearray(o)
dbg = seccon_util()
# Disallow everything
for key in dir(__builtins__):
del __builtins__.__dict__[key]
del __builtins__
/** code **/
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/SECCON/2021/pwn/seccon_tree/src/setup.py | ctfs/SECCON/2021/pwn/seccon_tree/src/setup.py | from distutils.core import setup, Extension
setup(name='seccon_tree',
version='1.0',
ext_modules=[Extension('seccon_tree', ['lib.c'])]
)
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/SECCON/2021/pwn/pyast64/pyast64.py | ctfs/SECCON/2021/pwn/pyast64/pyast64.py | #!/usr/bin/env python3.9
"""Compile a subset of the Python AST to x64-64 assembler.
Read more about it here: http://benhoyt.com/writings/pyast64/
Released under a permissive MIT license (see LICENSE.txt).
"""
import ast
import tempfile
import subprocess
import urllib.request
class Assembler:
"""The Assembler takes care of outputting instructions, labels, etc.,
as well as a simple peephole optimization to combine sequences of pushes
and pops.
"""
def __init__(self, output_file, peephole=True):
self.output_file = output_file
self.peephole = peephole
# Current batch of instructions, flushed on label and end of function
self.batch = []
def flush(self):
# [BUG] This feature is buggy. Always disable it.
#if self.peephole:
# self.optimize_pushes_pops()
for opcode, args in self.batch:
print('\t{}\t{}'.format(opcode, ', '.join(str(a) for a in args)),
file=self.output_file)
self.batch = []
def optimize_pushes_pops(self):
"""This finds runs of push(es) followed by pop(s) and combines
them into simpler, faster mov instructions. For example:
pushq 8(%rbp)
pushq $100
popq %rdx
popq %rax
Will be turned into:
movq $100, %rdx
movq 8(%rbp), %rax
"""
state = 'default'
optimized = []
pushes = 0
pops = 0
# This nested function combines a sequence of pushes and pops
def combine():
mid = len(optimized) - pops
num = min(pushes, pops)
moves = []
for i in range(num):
pop_arg = optimized[mid + i][1][0]
push_arg = optimized[mid - i - 1][1][0]
if push_arg != pop_arg:
moves.append(('movq', [push_arg, pop_arg]))
optimized[mid - num:mid + num] = moves
# This loop actually finds the sequences
for opcode, args in self.batch:
if state == 'default':
if opcode == 'pushq':
state = 'push'
pushes += 1
else:
pushes = 0
pops = 0
optimized.append((opcode, args))
elif state == 'push':
if opcode == 'pushq':
pushes += 1
elif opcode == 'popq':
state = 'pop'
pops += 1
else:
state = 'default'
pushes = 0
pops = 0
optimized.append((opcode, args))
elif state == 'pop':
if opcode == 'popq':
pops += 1
elif opcode == 'pushq':
combine()
state = 'push'
pushes = 1
pops = 0
else:
combine()
state = 'default'
pushes = 0
pops = 0
optimized.append((opcode, args))
else:
assert False, 'bad state: {}'.format(state)
if state == 'pop':
combine()
self.batch = optimized
def instr(self, opcode, *args):
self.batch.append((opcode, args))
def label(self, name):
self.flush()
print('{}:'.format(name), file=self.output_file)
def directive(self, line):
self.flush()
print(line, file=self.output_file)
def comment(self, text):
self.flush()
print('# {}'.format(text), file=self.output_file)
class LocalsVisitor(ast.NodeVisitor):
"""Recursively visit a FunctionDef node to find all the locals
(so we can allocate the right amount of stack space for them).
"""
def __init__(self):
self.local_names = []
self.global_names = []
self.function_calls = []
def add(self, name):
assert not name.startswith("_"), "Invalid variable name"
if name not in self.local_names and name not in self.global_names:
self.local_names.append(name)
def visit_Global(self, node):
self.global_names.extend(node.names)
def visit_Assign(self, node):
assert len(node.targets) == 1, \
'can only assign one variable at a time'
self.visit(node.value)
target = node.targets[0]
if isinstance(target, ast.Subscript):
self.add(target.value.id)
else:
self.add(target.id)
def visit_For(self, node):
self.add(node.target.id)
for statement in node.body:
self.visit(statement)
def visit_Call(self, node):
self.function_calls.append(node.func.id)
class Compiler:
"""The main Python AST -> x86-64 compiler."""
def __init__(self, assembler=None, peephole=True):
if assembler is None:
assembler = Assembler(peephole=peephole)
self.asm = assembler
self.func = None
self.funcdefs = {} # {<func>:<# of args>} dictionary
def compile(self, node):
self.header()
self.visit(node)
self.footer()
def visit(self, node):
# We could have subclassed ast.NodeVisitor, but it's better to fail
# hard on AST nodes we don't support
name = node.__class__.__name__
visit_func = getattr(self, 'visit_' + name, None)
assert visit_func is not None, '{} not supported - node {}'.format(
name, ast.dump(node))
visit_func(node)
def header(self):
self.asm.directive('.section .text')
self.asm.comment('')
def footer(self):
self.compile_putc()
self.compile_getc()
self.compile_trap()
self.asm.flush()
def compile_putc(self):
# Insert this into every program so it can call putc() for output
self.asm.label('putc')
self.compile_enter()
self.asm.instr('movl', '$1', '%eax') # write (for Linux)
self.asm.instr('movl', '$1', '%edi') # stdout
self.asm.instr('movq', '%rbp', '%rsi') # address
self.asm.instr('addq', '$16', '%rsi')
self.asm.instr('movq', '$1', '%rdx') # length
self.asm.instr('syscall')
self.compile_return(has_arrays=False)
def compile_getc(self):
# Insert this into every program so it can call getc() for input
self.asm.label('getc')
self.compile_enter()
self.asm.instr('xor', '%eax', '%eax') # read (for Linux)
self.asm.instr('xor', '%edi', '%edi') # stdin
self.asm.instr('lea', '-1(%rbp)', '%rsi') # address
self.asm.instr('movq', '$1', '%rdx') # length
self.asm.instr('syscall')
self.asm.instr('movb', '-1(%rbp)', '%al') # address
self.compile_return(has_arrays=False)
def compile_trap(self):
# Terminates program on unsound operation
self.asm.label('trap')
self.asm.instr('int3')
def visit_Module(self, node):
for statement in node.body:
self.visit(statement)
def visit_FunctionDef(self, node):
assert self.func is None, 'nested functions not supported'
assert node.args.vararg is None, '*args not supported'
assert not node.args.kwonlyargs, 'keyword-only args not supported'
assert not node.args.kwarg, 'keyword args not supported'
if node.name in self.funcdefs:
assert self.funcdefs[node.name] == len(node.args.args),\
"Mismatching number of function arguments"
else:
self.funcdefs[node.name] = len(node.args.args)
self.func = node.name
self.label_num = 1
self.locals = {a.arg: i for i, a in enumerate(node.args.args)}
# Find names of additional locals assigned in this function
locals_visitor = LocalsVisitor()
locals_visitor.visit(node)
for name in locals_visitor.local_names:
if name not in self.locals:
self.locals[name] = len(self.locals) + 1
if 'array' in locals_visitor.function_calls:
self.locals['_array_size'] = len(self.locals) + 1
self.globals = set(locals_visitor.global_names)
self.break_labels = []
# Function label and header
if node.name == 'main':
self.asm.directive('.globl _start')
self.asm.label('_start')
else:
assert not node.name.startswith('_'), "Invalid function name"
self.asm.label(node.name)
self.num_extra_locals = len(self.locals) - len(node.args.args)
self.compile_enter(self.num_extra_locals)
# Now compile all the statements in the function body
for statement in node.body:
self.visit(statement)
if not isinstance(node.body[-1], ast.Return):
# Function didn't have explicit return at the end,
# compile return now (or exit for "main")
if self.func == 'main':
self.compile_exit(0)
else:
self.compile_return(self.num_extra_locals)
self.asm.comment('')
self.func = None
def compile_enter(self, num_extra_locals=0):
# Make space for extra locals (in addition to the arguments)
for i in range(num_extra_locals):
self.asm.instr('pushq', '$0')
# Use rbp for a stack frame pointer
self.asm.instr('pushq', '%rbp')
self.asm.instr('movq', '%rsp', '%rbp')
def compile_return(self, num_extra_locals=0, has_arrays=None):
if has_arrays is None:
has_arrays = '_array_size' in self.locals
if has_arrays:
offset = self.local_offset('_array_size')
self.asm.instr('movq', '{}(%rbp)'.format(offset), '%rbx')
self.asm.instr('addq', '%rbx', '%rsp')
self.asm.instr('popq', '%rbp')
if num_extra_locals > 0:
self.asm.instr('leaq', '{}(%rsp),%rsp'.format(
num_extra_locals * 8))
self.asm.instr('ret')
def compile_exit(self, return_code):
if return_code is None:
self.asm.instr('popq', '%rdi')
else:
self.asm.instr('movl', '${}'.format(return_code), '%edi')
self.asm.instr('movl', '$60', '%eax') # for Linux
self.asm.instr('syscall')
def visit_Return(self, node):
if node.value:
self.visit(node.value)
if self.func == 'main':
# Returning from main, exit with that return code
self.compile_exit(None if node.value else 0)
else:
if node.value:
self.asm.instr('popq', '%rax')
self.compile_return(self.num_extra_locals)
def visit_Constant(self, node):
# Modified for Python 3.9 (Num, Str are merged to Constant)
assert isinstance(node.value, int),\
f"Expected {type(int)} but received {type(node.value)}"
self.asm.instr('pushq', '${}'.format(node.n))
def local_offset(self, name):
index = self.locals[name]
return (len(self.locals) - index) * 8 + 8
def visit_Name(self, node):
# Only supports locals, not globals
offset = self.local_offset(node.id)
self.asm.instr('pushq', '{}(%rbp)'.format(offset))
def visit_Assign(self, node):
# Only supports assignment of (a single) local variable
assert len(node.targets) == 1, \
'can only assign one variable at a time'
self.visit(node.value)
target = node.targets[0]
if isinstance(target, ast.Subscript):
# array[offset] = value
self.visit(target.slice) # Modified for Python 3.9
self.asm.instr('popq', '%rax')
self.asm.instr('popq', '%rbx')
local_offset = self.local_offset(target.value.id)
self.asm.instr('movq', '{}(%rbp)'.format(local_offset), '%rdx')
# Make sure the target variable is array
self.asm.instr('mov', '4(%rdx)', '%edi')
self.asm.instr('mov', '%fs:0x2c', '%esi')
self.asm.instr('cmp', '%edi', '%esi')
self.asm.instr('jnz', 'trap')
# Bounds checking
self.asm.instr('mov', '(%rdx)', '%ecx')
self.asm.instr('cmpq', '%rax', '%rcx')
self.asm.instr('jbe', 'trap')
# Store the element
self.asm.instr('movq', '%rbx', '8(%rdx,%rax,8)')
else:
# variable = value
offset = self.local_offset(node.targets[0].id)
self.asm.instr('popq', '{}(%rbp)'.format(offset))
def visit_AugAssign(self, node):
# Handles "n += 1" and the like
self.visit(node.target)
self.visit(node.value)
self.visit(node.op)
offset = self.local_offset(node.target.id)
self.asm.instr('popq', '{}(%rbp)'.format(offset))
def simple_binop(self, op):
self.asm.instr('popq', '%rdx')
self.asm.instr('popq', '%rax')
self.asm.instr(op, '%rdx', '%rax')
self.asm.instr('pushq', '%rax')
def visit_Mult(self, node):
self.asm.instr('popq', '%rdx')
self.asm.instr('popq', '%rax')
self.asm.instr('imulq', '%rdx')
self.asm.instr('pushq', '%rax')
def compile_divide(self, push_reg):
self.asm.instr('popq', '%rbx')
self.asm.instr('popq', '%rax')
self.asm.instr('cqo')
self.asm.instr('idiv', '%rbx')
self.asm.instr('pushq', push_reg)
def visit_Mod(self, node):
self.compile_divide('%rdx')
def visit_FloorDiv(self, node):
self.compile_divide('%rax')
def visit_Add(self, node):
self.simple_binop('addq')
def visit_Sub(self, node):
self.simple_binop('subq')
def visit_BinOp(self, node):
self.visit(node.left)
self.visit(node.right)
self.visit(node.op)
def visit_UnaryOp(self, node):
assert isinstance(node.op, ast.USub), \
'only unary minus is supported, not {}'.format(node.op.__class__.__name__)
self.visit(ast.Num(n=0))
self.visit(node.operand)
self.visit(ast.Sub())
def visit_Expr(self, node):
self.visit(node.value)
self.asm.instr('popq', '%rax')
def visit_And(self, node):
self.simple_binop('and')
def visit_BitAnd(self, node):
self.simple_binop('and')
def visit_Or(self, node):
self.simple_binop('or')
def visit_BitOr(self, node):
self.simple_binop('or')
def visit_BitXor(self, node):
self.simple_binop('xor')
def visit_BoolOp(self, node):
self.visit(node.values[0])
for value in node.values[1:]:
self.visit(value)
self.visit(node.op)
def builtin_array(self, args):
"""FIXED: Nov 20th, 2021
The original design of `array` was vulnerable to out-of-bounds access
and type confusion. The fixed version of the array has its length
to prevent out-of-bounds access.
i.e. x=array(1)
0 4 8 16
+--------+--------+--------+
| length | type | x[0] |
+--------+--------+--------+
The `type` field is used to check if the variable is actually an array.
This value is not guessable.
"""
assert len(args) == 1, 'array(len) expected 1 arg, not {}'.format(len(args))
self.visit(args[0])
# Array length must be within [0, 0xffff]
self.asm.instr('popq', '%rax')
self.asm.instr('cmpq', '$0xffff', '%rax')
self.asm.instr('ja', 'trap')
# Allocate array on stack, add size to _array_size
self.asm.instr('movq', '%rax', '%rcx')
self.asm.instr('addq', '$1', '%rax')
self.asm.instr('shlq', '$3', '%rax')
offset = self.local_offset('_array_size')
self.asm.instr('addq', '%rax', '{}(%rbp)'.format(offset))
self.asm.instr('subq', '%rax', '%rsp')
self.asm.instr('movq', '%rsp', '%rax')
self.asm.instr('movq', '%rax', '%rbx')
# Store the array length
self.asm.instr('mov', '%ecx', '(%rax)')
self.asm.instr('movq', '%fs:0x2c', '%rdx')
self.asm.instr('mov', '%edx', '4(%rax)')
# Fill the buffer with 0x00
self.asm.instr('lea', '8(%rax)', '%rdi')
self.asm.instr('xor', '%eax', '%eax')
self.asm.instr('rep', 'stosq')
# Push address
self.asm.instr('pushq', '%rbx')
def visit_Call(self, node):
assert not node.keywords, 'keyword args not supported'
builtin = getattr(self, 'builtin_{}'.format(node.func.id), None)
if builtin is not None:
builtin(node.args)
else:
assert not node.func.id.startswith('_'), "Invalid function name"
if node.func.id in self.funcdefs:
assert self.funcdefs[node.func.id] == len(node.args),\
"Mismatching number of function arguments"
else:
self.funcdefs[node.func.id] = len(node.args)
for arg in node.args:
self.visit(arg)
self.asm.instr('call', node.func.id)
if node.args:
# Caller cleans up the arguments from the stack
self.asm.instr('addq', '${}'.format(8 * len(node.args)), '%rsp')
# Return value is in rax, so push it on the stack now
self.asm.instr('pushq', '%rax')
def label(self, slug):
label = '_{}_{}_{}'.format(self.func, self.label_num, slug)
self.label_num += 1
return label
def visit_Compare(self, node):
assert len(node.ops) == 1, 'only single comparisons supported'
self.visit(node.left)
self.visit(node.comparators[0])
self.visit(node.ops[0])
def compile_comparison(self, jump_not, slug):
self.asm.instr('popq', '%rdx')
self.asm.instr('popq', '%rax')
self.asm.instr('cmpq', '%rdx', '%rax')
self.asm.instr('movq', '$0', '%rax')
label = self.label(slug)
self.asm.instr(jump_not, label)
self.asm.instr('incq', '%rax')
self.asm.label(label)
self.asm.instr('pushq', '%rax')
def visit_Lt(self, node):
self.compile_comparison('jnl', 'less')
def visit_LtE(self, node):
self.compile_comparison('jnle', 'less_or_equal')
def visit_Gt(self, node):
self.compile_comparison('jng', 'greater')
def visit_GtE(self, node):
self.compile_comparison('jnge', 'greater_or_equal')
def visit_Eq(self, node):
self.compile_comparison('jne', 'equal')
def visit_NotEq(self, node):
self.compile_comparison('je', 'not_equal')
def visit_If(self, node):
# Handles if, elif, and else
self.visit(node.test)
self.asm.instr('popq', '%rax')
self.asm.instr('cmpq', '$0', '%rax')
label_else = self.label('else')
label_end = self.label('end')
self.asm.instr('jz', label_else)
for statement in node.body:
self.visit(statement)
if node.orelse:
self.asm.instr('jmp', label_end)
self.asm.label(label_else)
for statement in node.orelse:
self.visit(statement)
if node.orelse:
self.asm.label(label_end)
def visit_While(self, node):
# Handles while and break (also used for "for" -- see below)
while_label = self.label('while')
break_label = self.label('break')
self.break_labels.append(break_label)
self.asm.label(while_label)
self.visit(node.test)
self.asm.instr('popq', '%rax')
self.asm.instr('cmpq', '$0', '%rax')
self.asm.instr('jz', break_label)
for statement in node.body:
self.visit(statement)
self.asm.instr('jmp', while_label)
self.asm.label(break_label)
self.break_labels.pop()
def visit_Break(self, node):
self.asm.instr('jmp', self.break_labels[-1])
def visit_Pass(self, node):
pass
def visit_For(self, node):
# Turn for+range loop into a while loop:
# i = start
# while i < stop:
# body
# i = i + step
assert isinstance(node.iter, ast.Call) and \
node.iter.func.id == 'range', \
'for can only be used with range()'
range_args = node.iter.args
if len(range_args) == 1:
start = ast.Num(n=0)
stop = range_args[0]
step = ast.Num(n=1)
elif len(range_args) == 2:
start, stop = range_args
step = ast.Num(n=1)
else:
start, stop, step = range_args
if (isinstance(step, ast.UnaryOp) and
isinstance(step.op, ast.USub) and
isinstance(step.operand, ast.Num)):
# Handle negative step
step = ast.Num(n=-step.operand.n)
assert isinstance(step, ast.Num) and step.n != 0, \
'range() step must be a nonzero integer constant'
self.visit(ast.Assign(targets=[node.target], value=start))
test = ast.Compare(
left=node.target,
ops=[ast.Lt() if step.n > 0 else ast.Gt()],
comparators=[stop],
)
incr = ast.Assign(
targets=[node.target],
value=ast.BinOp(left=node.target, op=ast.Add(), right=step),
)
self.visit(ast.While(test=test, body=node.body + [incr]))
def visit_Global(self, node):
# Global names are already collected by LocalsVisitor
pass
def visit_Subscript(self, node):
self.visit(node.slice) # Modified for Python 3.9
self.asm.instr('popq', '%rax')
local_offset = self.local_offset(node.value.id)
self.asm.instr('movq', '{}(%rbp)'.format(local_offset), '%rdx')
# Make sure the target variable is array
self.asm.instr('mov', '4(%rdx)', '%edi')
self.asm.instr('mov', '%fs:0x2c', '%esi')
self.asm.instr('cmp', '%edi', '%esi')
self.asm.instr('jnz', 'trap')
# Bounds checking
self.asm.instr('mov', '(%rdx)', '%ecx')
self.asm.instr('cmpq', '%rax', '%rcx')
self.asm.instr('jbe', 'trap')
# Load the element
self.asm.instr('pushq', '8(%rdx,%rax,8)')
if __name__ == '__main__':
MAX_SIZE = 10000
print("[Tips] You can use https://transfer.sh/ if you don't have your own server.")
url = input("URL: ")
if not url.startswith("http"):
print("[-] Bad URL")
exit(1)
with (
tempfile.NamedTemporaryFile('w') as fasm,
urllib.request.urlopen(url) as fpy
):
code = fpy.read().decode("utf-8")
if len(code) > MAX_SIZE:
print("[-] Too long")
exit(1)
# JIT your code
node = ast.parse(code)
compiler = Compiler(assembler=Assembler(fasm))
compiler.compile(node)
fasm.flush()
# Run your code
subprocess.run(["gcc",
"-xassembler", "-nostdlib", "-nodefaultlibs",
"-z", "noexecstack", "-pie",
fasm.name, "-o", fasm.name+'.elf'],
cwd="/tmp")
subprocess.run([fasm.name + ".elf"])
subprocess.run(["rm", fasm.name + ".elf"])
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/SECCON/2021/rev/pyast64/pyast64.py | ctfs/SECCON/2021/rev/pyast64/pyast64.py | #!/usr/bin/env python3.9
"""Compile a subset of the Python AST to x64-64 assembler.
Read more about it here: http://benhoyt.com/writings/pyast64/
Released under a permissive MIT license (see LICENSE.txt).
"""
import ast
import tempfile
import subprocess
import urllib.request
class Assembler:
"""The Assembler takes care of outputting instructions, labels, etc.,
as well as a simple peephole optimization to combine sequences of pushes
and pops.
"""
def __init__(self, output_file, peephole=True):
self.output_file = output_file
self.peephole = peephole
# Current batch of instructions, flushed on label and end of function
self.batch = []
def flush(self):
# [BUG] This feature is buggy. Always disable it.
#if self.peephole:
# self.optimize_pushes_pops()
for opcode, args in self.batch:
print('\t{}\t{}'.format(opcode, ', '.join(str(a) for a in args)),
file=self.output_file)
self.batch = []
def optimize_pushes_pops(self):
"""This finds runs of push(es) followed by pop(s) and combines
them into simpler, faster mov instructions. For example:
pushq 8(%rbp)
pushq $100
popq %rdx
popq %rax
Will be turned into:
movq $100, %rdx
movq 8(%rbp), %rax
"""
state = 'default'
optimized = []
pushes = 0
pops = 0
# This nested function combines a sequence of pushes and pops
def combine():
mid = len(optimized) - pops
num = min(pushes, pops)
moves = []
for i in range(num):
pop_arg = optimized[mid + i][1][0]
push_arg = optimized[mid - i - 1][1][0]
if push_arg != pop_arg:
moves.append(('movq', [push_arg, pop_arg]))
optimized[mid - num:mid + num] = moves
# This loop actually finds the sequences
for opcode, args in self.batch:
if state == 'default':
if opcode == 'pushq':
state = 'push'
pushes += 1
else:
pushes = 0
pops = 0
optimized.append((opcode, args))
elif state == 'push':
if opcode == 'pushq':
pushes += 1
elif opcode == 'popq':
state = 'pop'
pops += 1
else:
state = 'default'
pushes = 0
pops = 0
optimized.append((opcode, args))
elif state == 'pop':
if opcode == 'popq':
pops += 1
elif opcode == 'pushq':
combine()
state = 'push'
pushes = 1
pops = 0
else:
combine()
state = 'default'
pushes = 0
pops = 0
optimized.append((opcode, args))
else:
assert False, 'bad state: {}'.format(state)
if state == 'pop':
combine()
self.batch = optimized
def instr(self, opcode, *args):
self.batch.append((opcode, args))
def label(self, name):
self.flush()
print('{}:'.format(name), file=self.output_file)
def directive(self, line):
self.flush()
print(line, file=self.output_file)
def comment(self, text):
self.flush()
print('# {}'.format(text), file=self.output_file)
class LocalsVisitor(ast.NodeVisitor):
"""Recursively visit a FunctionDef node to find all the locals
(so we can allocate the right amount of stack space for them).
"""
def __init__(self):
self.local_names = []
self.global_names = []
self.function_calls = []
def add(self, name):
if name not in self.local_names and name not in self.global_names:
self.local_names.append(name)
def visit_Global(self, node):
self.global_names.extend(node.names)
def visit_Assign(self, node):
assert len(node.targets) == 1, \
'can only assign one variable at a time'
self.visit(node.value)
target = node.targets[0]
if isinstance(target, ast.Subscript):
self.add(target.value.id)
else:
self.add(target.id)
def visit_For(self, node):
self.add(node.target.id)
for statement in node.body:
self.visit(statement)
def visit_Call(self, node):
self.function_calls.append(node.func.id)
class Compiler:
"""The main Python AST -> x86-64 compiler."""
def __init__(self, assembler=None, peephole=True):
if assembler is None:
assembler = Assembler(peephole=peephole)
self.asm = assembler
self.func = None
def compile(self, node):
self.header()
self.visit(node)
self.footer()
def visit(self, node):
# We could have subclassed ast.NodeVisitor, but it's better to fail
# hard on AST nodes we don't support
name = node.__class__.__name__
visit_func = getattr(self, 'visit_' + name, None)
assert visit_func is not None, '{} not supported - node {}'.format(
name, ast.dump(node))
visit_func(node)
def header(self):
self.asm.directive('.section .text')
self.asm.comment('')
def footer(self):
self.compile_putc()
self.compile_getc()
self.compile_trap()
self.asm.flush()
def compile_putc(self):
# Insert this into every program so it can call putc() for output
self.asm.label('putc')
self.compile_enter()
self.asm.instr('movl', '$1', '%eax') # write (for Linux)
self.asm.instr('movl', '$1', '%edi') # stdout
self.asm.instr('movq', '%rbp', '%rsi') # address
self.asm.instr('addq', '$16', '%rsi')
self.asm.instr('movq', '$1', '%rdx') # length
self.asm.instr('syscall')
self.compile_return(has_arrays=False)
def compile_getc(self):
# Insert this into every program so it can call getc() for input
self.asm.label('getc')
self.compile_enter()
self.asm.instr('xor', '%eax', '%eax') # read (for Linux)
self.asm.instr('xor', '%edi', '%edi') # stdin
self.asm.instr('lea', '-1(%rbp)', '%rsi') # address
self.asm.instr('movq', '$1', '%rdx') # length
self.asm.instr('syscall')
self.asm.instr('movb', '-1(%rbp)', '%al') # address
self.compile_return(has_arrays=False)
def compile_trap(self):
# Terminates program on unsound operation
self.asm.label('trap')
self.asm.instr('int3')
def visit_Module(self, node):
for statement in node.body:
self.visit(statement)
def visit_FunctionDef(self, node):
assert self.func is None, 'nested functions not supported'
assert node.args.vararg is None, '*args not supported'
assert not node.args.kwonlyargs, 'keyword-only args not supported'
assert not node.args.kwarg, 'keyword args not supported'
self.func = node.name
self.label_num = 1
self.locals = {a.arg: i for i, a in enumerate(node.args.args)}
# Find names of additional locals assigned in this function
locals_visitor = LocalsVisitor()
locals_visitor.visit(node)
for name in locals_visitor.local_names:
if name not in self.locals:
self.locals[name] = len(self.locals) + 1
if 'array' in locals_visitor.function_calls:
self.locals['_array_size'] = len(self.locals) + 1
self.globals = set(locals_visitor.global_names)
self.break_labels = []
# Function label and header
if node.name == 'main':
self.asm.directive('.globl _start')
self.asm.label('_start')
else:
assert not node.name.startswith('_'), "Invalid function name"
self.asm.label(node.name)
self.num_extra_locals = len(self.locals) - len(node.args.args)
self.compile_enter(self.num_extra_locals)
# Now compile all the statements in the function body
for statement in node.body:
self.visit(statement)
if not isinstance(node.body[-1], ast.Return):
# Function didn't have explicit return at the end,
# compile return now (or exit for "main")
if self.func == 'main':
self.compile_exit(0)
else:
self.compile_return(self.num_extra_locals)
self.asm.comment('')
self.func = None
def compile_enter(self, num_extra_locals=0):
# Make space for extra locals (in addition to the arguments)
for i in range(num_extra_locals):
self.asm.instr('pushq', '$0')
# Use rbp for a stack frame pointer
self.asm.instr('pushq', '%rbp')
self.asm.instr('movq', '%rsp', '%rbp')
def compile_return(self, num_extra_locals=0, has_arrays=None):
if has_arrays is None:
has_arrays = '_array_size' in self.locals
if has_arrays:
offset = self.local_offset('_array_size')
self.asm.instr('movq', '{}(%rbp)'.format(offset), '%rbx')
self.asm.instr('addq', '%rbx', '%rsp')
self.asm.instr('popq', '%rbp')
if num_extra_locals > 0:
self.asm.instr('leaq', '{}(%rsp),%rsp'.format(
num_extra_locals * 8))
self.asm.instr('ret')
def compile_exit(self, return_code):
if return_code is None:
self.asm.instr('popq', '%rdi')
else:
self.asm.instr('movl', '${}'.format(return_code), '%edi')
self.asm.instr('movl', '$60', '%eax') # for Linux
self.asm.instr('syscall')
def visit_Return(self, node):
if node.value:
self.visit(node.value)
if self.func == 'main':
# Returning from main, exit with that return code
self.compile_exit(None if node.value else 0)
else:
if node.value:
self.asm.instr('popq', '%rax')
self.compile_return(self.num_extra_locals)
def visit_Constant(self, node):
# Modified for Python 3.9 (Num, Str are merged to Constant)
assert isinstance(node.value, int),\
f"Expected {type(int)} but received {type(node.value)}"
self.asm.instr('pushq', '${}'.format(node.n))
def local_offset(self, name):
index = self.locals[name]
return (len(self.locals) - index) * 8 + 8
def visit_Name(self, node):
# Only supports locals, not globals
offset = self.local_offset(node.id)
self.asm.instr('pushq', '{}(%rbp)'.format(offset))
def visit_Assign(self, node):
# Only supports assignment of (a single) local variable
assert len(node.targets) == 1, \
'can only assign one variable at a time'
self.visit(node.value)
target = node.targets[0]
if isinstance(target, ast.Subscript):
# array[offset] = value
self.visit(target.slice) # Modified for Python 3.9
self.asm.instr('popq', '%rax')
self.asm.instr('popq', '%rbx')
local_offset = self.local_offset(target.value.id)
self.asm.instr('movq', '{}(%rbp)'.format(local_offset), '%rdx')
# Make sure the target variable is array
self.asm.instr('mov', '4(%rdx)', '%edi')
self.asm.instr('mov', '%fs:0x2c', '%esi')
self.asm.instr('cmp', '%edi', '%esi')
self.asm.instr('jnz', 'trap')
# Bounds checking
self.asm.instr('mov', '(%rdx)', '%ecx')
self.asm.instr('cmpq', '%rax', '%rcx')
self.asm.instr('jbe', 'trap')
# Store the element
self.asm.instr('movq', '%rbx', '8(%rdx,%rax,8)')
else:
# variable = value
offset = self.local_offset(node.targets[0].id)
self.asm.instr('popq', '{}(%rbp)'.format(offset))
def visit_AugAssign(self, node):
# Handles "n += 1" and the like
self.visit(node.target)
self.visit(node.value)
self.visit(node.op)
offset = self.local_offset(node.target.id)
self.asm.instr('popq', '{}(%rbp)'.format(offset))
def simple_binop(self, op):
self.asm.instr('popq', '%rdx')
self.asm.instr('popq', '%rax')
self.asm.instr(op, '%rdx', '%rax')
self.asm.instr('pushq', '%rax')
def visit_Mult(self, node):
self.asm.instr('popq', '%rdx')
self.asm.instr('popq', '%rax')
self.asm.instr('imulq', '%rdx')
self.asm.instr('pushq', '%rax')
def compile_divide(self, push_reg):
self.asm.instr('popq', '%rbx')
self.asm.instr('popq', '%rax')
self.asm.instr('cqo')
self.asm.instr('idiv', '%rbx')
self.asm.instr('pushq', push_reg)
def visit_Mod(self, node):
self.compile_divide('%rdx')
def visit_FloorDiv(self, node):
self.compile_divide('%rax')
def visit_Add(self, node):
self.simple_binop('addq')
def visit_Sub(self, node):
self.simple_binop('subq')
def visit_BinOp(self, node):
self.visit(node.left)
self.visit(node.right)
self.visit(node.op)
def visit_UnaryOp(self, node):
assert isinstance(node.op, ast.USub), \
'only unary minus is supported, not {}'.format(node.op.__class__.__name__)
self.visit(ast.Num(n=0))
self.visit(node.operand)
self.visit(ast.Sub())
def visit_Expr(self, node):
self.visit(node.value)
self.asm.instr('popq', '%rax')
def visit_And(self, node):
self.simple_binop('and')
def visit_BitAnd(self, node):
self.simple_binop('and')
def visit_Or(self, node):
self.simple_binop('or')
def visit_BitOr(self, node):
self.simple_binop('or')
def visit_BitXor(self, node):
self.simple_binop('xor')
def visit_BoolOp(self, node):
self.visit(node.values[0])
for value in node.values[1:]:
self.visit(value)
self.visit(node.op)
def builtin_array(self, args):
"""FIXED: Nov 20th, 2021
The original design of `array` was vulnerable to out-of-bounds access
and type confusion. The fixed version of the array has its length
to prevent out-of-bounds access.
i.e. x=array(1)
0 4 8 16
+--------+--------+--------+
| length | type | x[0] |
+--------+--------+--------+
The `type` field is used to check if the variable is actually an array.
This value is not guessable.
"""
assert len(args) == 1, 'array(len) expected 1 arg, not {}'.format(len(args))
self.visit(args[0])
# Array length must be within [0, 0xffff]
self.asm.instr('popq', '%rax')
self.asm.instr('cmpq', '$0xffff', '%rax')
self.asm.instr('ja', 'trap')
# Allocate array on stack, add size to _array_size
self.asm.instr('movq', '%rax', '%rcx')
self.asm.instr('addq', '$1', '%rax')
self.asm.instr('shlq', '$3', '%rax')
offset = self.local_offset('_array_size')
self.asm.instr('addq', '%rax', '{}(%rbp)'.format(offset))
self.asm.instr('subq', '%rax', '%rsp')
self.asm.instr('movq', '%rsp', '%rax')
self.asm.instr('movq', '%rax', '%rbx')
# Store the array length
self.asm.instr('mov', '%ecx', '(%rax)')
self.asm.instr('movq', '%fs:0x2c', '%rdx')
self.asm.instr('mov', '%edx', '4(%rax)')
# Fill the buffer with 0x00
self.asm.instr('lea', '8(%rax)', '%rdi')
self.asm.instr('xor', '%eax', '%eax')
self.asm.instr('rep', 'stosq')
# Push address
self.asm.instr('pushq', '%rbx')
def visit_Call(self, node):
assert not node.keywords, 'keyword args not supported'
builtin = getattr(self, 'builtin_{}'.format(node.func.id), None)
if builtin is not None:
builtin(node.args)
else:
for arg in node.args:
self.visit(arg)
assert not node.func.id.startswith('_'), "Invalid function name"
self.asm.instr('call', node.func.id)
if node.args:
# Caller cleans up the arguments from the stack
self.asm.instr('addq', '${}'.format(8 * len(node.args)), '%rsp')
# Return value is in rax, so push it on the stack now
self.asm.instr('pushq', '%rax')
def label(self, slug):
label = '_{}_{}_{}'.format(self.func, self.label_num, slug)
self.label_num += 1
return label
def visit_Compare(self, node):
assert len(node.ops) == 1, 'only single comparisons supported'
self.visit(node.left)
self.visit(node.comparators[0])
self.visit(node.ops[0])
def compile_comparison(self, jump_not, slug):
self.asm.instr('popq', '%rdx')
self.asm.instr('popq', '%rax')
self.asm.instr('cmpq', '%rdx', '%rax')
self.asm.instr('movq', '$0', '%rax')
label = self.label(slug)
self.asm.instr(jump_not, label)
self.asm.instr('incq', '%rax')
self.asm.label(label)
self.asm.instr('pushq', '%rax')
def visit_Lt(self, node):
self.compile_comparison('jnl', 'less')
def visit_LtE(self, node):
self.compile_comparison('jnle', 'less_or_equal')
def visit_Gt(self, node):
self.compile_comparison('jng', 'greater')
def visit_GtE(self, node):
self.compile_comparison('jnge', 'greater_or_equal')
def visit_Eq(self, node):
self.compile_comparison('jne', 'equal')
def visit_NotEq(self, node):
self.compile_comparison('je', 'not_equal')
def visit_If(self, node):
# Handles if, elif, and else
self.visit(node.test)
self.asm.instr('popq', '%rax')
self.asm.instr('cmpq', '$0', '%rax')
label_else = self.label('else')
label_end = self.label('end')
self.asm.instr('jz', label_else)
for statement in node.body:
self.visit(statement)
if node.orelse:
self.asm.instr('jmp', label_end)
self.asm.label(label_else)
for statement in node.orelse:
self.visit(statement)
if node.orelse:
self.asm.label(label_end)
def visit_While(self, node):
# Handles while and break (also used for "for" -- see below)
while_label = self.label('while')
break_label = self.label('break')
self.break_labels.append(break_label)
self.asm.label(while_label)
self.visit(node.test)
self.asm.instr('popq', '%rax')
self.asm.instr('cmpq', '$0', '%rax')
self.asm.instr('jz', break_label)
for statement in node.body:
self.visit(statement)
self.asm.instr('jmp', while_label)
self.asm.label(break_label)
self.break_labels.pop()
def visit_Break(self, node):
self.asm.instr('jmp', self.break_labels[-1])
def visit_Pass(self, node):
pass
def visit_For(self, node):
# Turn for+range loop into a while loop:
# i = start
# while i < stop:
# body
# i = i + step
assert isinstance(node.iter, ast.Call) and \
node.iter.func.id == 'range', \
'for can only be used with range()'
range_args = node.iter.args
if len(range_args) == 1:
start = ast.Num(n=0)
stop = range_args[0]
step = ast.Num(n=1)
elif len(range_args) == 2:
start, stop = range_args
step = ast.Num(n=1)
else:
start, stop, step = range_args
if (isinstance(step, ast.UnaryOp) and
isinstance(step.op, ast.USub) and
isinstance(step.operand, ast.Num)):
# Handle negative step
step = ast.Num(n=-step.operand.n)
assert isinstance(step, ast.Num) and step.n != 0, \
'range() step must be a nonzero integer constant'
self.visit(ast.Assign(targets=[node.target], value=start))
test = ast.Compare(
left=node.target,
ops=[ast.Lt() if step.n > 0 else ast.Gt()],
comparators=[stop],
)
incr = ast.Assign(
targets=[node.target],
value=ast.BinOp(left=node.target, op=ast.Add(), right=step),
)
self.visit(ast.While(test=test, body=node.body + [incr]))
def visit_Global(self, node):
# Global names are already collected by LocalsVisitor
pass
def visit_Subscript(self, node):
self.visit(node.slice) # Modified for Python 3.9
self.asm.instr('popq', '%rax')
local_offset = self.local_offset(node.value.id)
self.asm.instr('movq', '{}(%rbp)'.format(local_offset), '%rdx')
# Make sure the target variable is array
self.asm.instr('mov', '4(%rdx)', '%edi')
self.asm.instr('mov', '%fs:0x2c', '%esi')
self.asm.instr('cmp', '%edi', '%esi')
self.asm.instr('jnz', 'trap')
# Bounds checking
self.asm.instr('mov', '(%rdx)', '%ecx')
self.asm.instr('cmpq', '%rax', '%rcx')
self.asm.instr('jbe', 'trap')
# Load the element
self.asm.instr('pushq', '8(%rdx,%rax,8)')
if __name__ == '__main__':
with open("chall.py", "r") as f:
code = f.read()
with open("chall.S", "w") as f:
node = ast.parse(code)
compiler = Compiler(assembler=Assembler(f))
compiler.compile(node)
subprocess.run(["gcc",
"-xassembler", "-nostdlib", "-nodefaultlibs",
"-z", "noexecstack", "-pie",
"chall.S", "-o", 'chall.elf'])
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/SECCON/2021/crypto/CCC/challenge.py | ctfs/SECCON/2021/crypto/CCC/challenge.py | from Crypto.Util.number import bytes_to_long, getPrime, getRandomInteger, isPrime
from secret import flag
def create_prime(p_bit_len, add_bit_len, a):
p = getPrime(p_bit_len)
p_bit_len2 = 2*p_bit_len // 3 + add_bit_len
while True:
b = getRandomInteger(p_bit_len2)
_p = a * p
q = _p**2 + 3*_p*b + 3*b**2
if isPrime(q):
return p, q
def encrypt(p_bit_len, add_bit_len, a, plain_text):
p, q = create_prime(p_bit_len, add_bit_len, a)
n = p*q
e = 65537
c = pow(plain_text, e, n)
print(f"{n=}")
print(f"{e=}")
print(f"{c=}")
print(f"{a=}")
if __name__ == "__main__":
encrypt(1024, 9, 23, bytes_to_long(flag)) | python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/SECCON/2021/crypto/cerberus/problem.py | ctfs/SECCON/2021/crypto/cerberus/problem.py | import base64
from Crypto.Cipher import AES
from Crypto.Random import get_random_bytes
from Crypto.Util.Padding import pad, unpad
from Crypto.Util.strxor import strxor
from flag import flag
import signal
key = get_random_bytes(16)
block_size = 16
# encrypt by AES-PCBC
# https://en.wikipedia.org/wiki/Block_cipher_mode_of_operation#Propagating_cipher_block_chaining_(PCBC)
def encrypt(m):
cipher = AES.new(key, AES.MODE_ECB) # MODE_PCBC is not FOUND :sob: :sob:
m = pad(m, 16)
m = [m[i : i + block_size] for i in range(0, len(m), block_size)]
iv = get_random_bytes(16)
c = []
prev = iv
for m_block in m:
c.append(cipher.encrypt(strxor(m_block, prev)))
prev = strxor(c[-1], m_block)
return iv, b"".join(c)
# decrypt by AES-PCBC
# https://en.wikipedia.org/wiki/Block_cipher_mode_of_operation#Propagating_cipher_block_chaining_(PCBC)
def decrypt(iv, c):
cipher = AES.new(key, AES.MODE_ECB) # MODE_PCBC is not FOUND :sob: :sob:
c = [c[i : i + block_size] for i in range(0, len(c), block_size)]
m = []
prev = iv
for c_block in c:
m.append(strxor(prev, cipher.decrypt(c_block)))
prev = strxor(m[-1], c_block)
return b"".join(m)
# The flag is padded with 16 bytes prefix
# flag = padding (16 bytes) + "SECCON{..."
signal.alarm(3600)
ref_iv, ref_c = encrypt(flag)
print("I teach you a spell! repeat after me!")
print(base64.b64encode(ref_iv + ref_c).decode("utf-8"))
while True:
c = base64.b64decode(input("spell:"))
iv = c[:16]
c = c[16:]
if not c.startswith(ref_c):
print("Grrrrrrr!!!!")
continue
m = decrypt(iv, c)
try:
unpad(m, block_size)
except:
print("little different :(")
continue
print("Great :)")
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/SECCON/2021/crypto/oOoOoO/problem.py | ctfs/SECCON/2021/crypto/oOoOoO/problem.py | import signal
from Crypto.Util.number import long_to_bytes, bytes_to_long, getPrime
import random
from flag import flag
message = b""
for _ in range(128):
message += b"o" if random.getrandbits(1) == 1 else b"O"
M = getPrime(len(message) * 5)
S = bytes_to_long(message) % M
print("M =", M)
print('S =', S)
print('MESSAGE =', message.upper().decode("utf-8"))
signal.alarm(600)
ans = input('message =').strip().encode()
if ans == message:
print(flag)
else:
print("🧙")
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/SECCON/2018/Quals/internet_of_seat/wrapper.py | ctfs/SECCON/2018/Quals/internet_of_seat/wrapper.py | #!/usr/bin/python -u
import os
import socket
import subprocess
import threading
import sys
from hashlib import md5
from contextlib import closing
sys.stderr = open('/tmp/log', 'wb', 0)
def find_free_port():
with closing(socket.socket(socket.AF_INET, socket.SOCK_STREAM)) as s:
s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, True)
s.bind(('', 0))
return s.getsockname()[1]
def client_checker():
try:
sys.stdin.read()
finally:
p.kill()
prefix = os.urandom(8).encode('hex')
suffix = raw_input('md5("%s" + input).startswith("00000") >> ' % prefix)
if md5(prefix + suffix).hexdigest().startswith('00000') or 1:
print "Running server..."
dirname = os.path.dirname(__file__)
os.chdir(dirname)
path = os.path.join(dirname, 'run.sh')
print "Finding free port..."
port = find_free_port()
print "Your port:", port
print "Guest runs daemon on port 8888, but it's redirected to the port above"
# NOTE: ./main is in initramfs.cpio.gz
argv="/usr/bin/qemu-system-arm", "-kernel", "zImage", "-cpu", "arm1176", "-m", "32", "-M", "versatilepb", "-no-reboot", \
"-initrd", "initramfs.cpio.gz", "-append", \
"root=/dev/ram0 elevator=deadline rootwait quiet nozswap nortc noswap console=ttyAMA0 noacpi acpi=off", \
"-redir", "tcp:" + str(port) + "::8888", \
"-nographic"
try:
p = subprocess.Popen(argv, env={}, stdin=open('/dev/null', 'rb'), stdout=subprocess.PIPE)
except:
import traceback
traceback.print_exc()
print "Launch failed! Please contact to administrator"
exit()
# Check if client's disconnected
t = threading.Thread(target=client_checker)
t.start()
# Check if qemu's halted
d = ''
while True:
x = p.stdout.read(1)
if x == '':
break
try:
sys.stdout.write(x)
except IOError:
p.kill()
break
d += x
if 'System halted' in d:
p.kill()
break
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/SECCON/2023/Quals/misc/readme_2023/server.py | ctfs/SECCON/2023/Quals/misc/readme_2023/server.py | import mmap
import os
import signal
signal.alarm(60)
try:
f = open("./flag.txt", "r")
mm = mmap.mmap(f.fileno(), 0, prot=mmap.PROT_READ)
except FileNotFoundError:
print("[-] Flag does not exist")
exit(1)
while True:
path = input("path: ")
if 'flag.txt' in path:
print("[-] Path not allowed")
exit(1)
elif 'fd' in path:
print("[-] No more fd trick ;)")
exit(1)
with open(os.path.realpath(path), "rb") as f:
print(f.read(0x100))
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/SECCON/2023/Quals/rev/Sickle/problem.py | ctfs/SECCON/2023/Quals/rev/Sickle/problem.py | import pickle, io
payload = b'\x8c\x08builtins\x8c\x07getattr\x93\x942\x8c\x08builtins\x8c\x05input\x93\x8c\x06FLAG> \x85R\x8c\x06encode\x86R)R\x940g0\n\x8c\x08builtins\x8c\x04dict\x93\x8c\x03get\x86R\x8c\x08builtins\x8c\x07globals\x93)R\x8c\x01f\x86R\x8c\x04seek\x86R\x94g0\n\x8c\x08builtins\x8c\x03int\x93\x8c\x07__add__\x86R\x940g0\n\x8c\x08builtins\x8c\x03int\x93\x8c\x07__mul__\x86R\x940g0\n\x8c\x08builtins\x8c\x03int\x93\x8c\x06__eq__\x86R\x940g3\ng5\n\x8c\x08builtins\x8c\x03len\x93g1\n\x85RM@\x00\x86RM\x05\x01\x86R\x85R.0g0\ng1\n\x8c\x0b__getitem__\x86R\x940M\x00\x00\x940g2\ng3\ng0\ng6\ng7\n\x85R\x8c\x06__le__\x86RM\x7f\x00\x85RMJ\x01\x86R\x85R.0g2\ng3\ng4\ng5\ng3\ng7\nM\x01\x00\x86Rp7\nM@\x00\x86RMU\x00\x86RM"\x01\x86R\x85R0g0\ng0\n]\x94\x8c\x06append\x86R\x940g8\n\x8c\x0b__getitem__\x86R\x940g0\n\x8c\x08builtins\x8c\x03int\x93\x8c\nfrom_bytes\x86R\x940M\x00\x00p7\n0g9\ng11\ng6\n\x8c\x08builtins\x8c\x05slice\x93g4\ng7\nM\x08\x00\x86Rg4\ng3\ng7\nM\x01\x00\x86RM\x08\x00\x86R\x86R\x85R\x8c\x06little\x86R\x85R0g2\ng3\ng4\ng5\ng3\ng7\nM\x01\x00\x86Rp7\nM\x08\x00\x86RMw\x00\x86RM\xc9\x01\x86R\x85R0g0\n]\x94\x8c\x06append\x86R\x940g0\ng12\n\x8c\x0b__getitem__\x86R\x940g0\n\x8c\x08builtins\x8c\x03int\x93\x8c\x07__xor__\x86R\x940I1244422970072434993\n\x940M\x00\x00p7\n0g13\n\x8c\x08builtins\x8c\x03pow\x93g15\ng10\ng7\n\x85Rg16\n\x86RI65537\nI18446744073709551557\n\x87R\x85R0g14\ng7\n\x85Rp16\n0g2\ng3\ng4\ng5\ng3\ng7\nM\x01\x00\x86Rp7\nM\x08\x00\x86RM\x83\x00\x86RM\xa7\x02\x86R\x85R0g0\ng12\n\x8c\x06__eq__\x86R(I8215359690687096682\nI1862662588367509514\nI8350772864914849965\nI11616510986494699232\nI3711648467207374797\nI9722127090168848805\nI16780197523811627561\nI18138828537077112905\nl\x85R.'
f = io.BytesIO(payload)
res = pickle.load(f)
if isinstance(res, bool) and res:
print("Congratulations!!")
else:
print("Nope") | python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/SECCON/2023/Quals/sandbox/crabox/app.py | ctfs/SECCON/2023/Quals/sandbox/crabox/app.py | import sys
import re
import os
import subprocess
import tempfile
FLAG = os.environ["FLAG"]
assert re.fullmatch(r"SECCON{[_a-z0-9]+}", FLAG)
os.environ.pop("FLAG")
TEMPLATE = """
fn main() {
{{YOUR_PROGRAM}}
/* Steal me: {{FLAG}} */
}
""".strip()
print("""
🦀 Compile-Time Sandbox Escape 🦀
Input your program (the last line must start with __EOF__):
""".strip(), flush=True)
program = ""
while True:
line = sys.stdin.readline()
if line.startswith("__EOF__"):
break
program += line
if len(program) > 512:
print("Your program is too long. Bye👋".strip())
exit(1)
source = TEMPLATE.replace("{{FLAG}}", FLAG).replace("{{YOUR_PROGRAM}}", program)
with tempfile.NamedTemporaryFile(suffix=".rs") as file:
file.write(source.encode())
file.flush()
try:
proc = subprocess.run(
["rustc", file.name],
cwd="/tmp",
stdout=subprocess.DEVNULL,
stderr=subprocess.DEVNULL,
timeout=2,
)
print(":)" if proc.returncode == 0 else ":(")
except subprocess.TimeoutExpired:
print("timeout")
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/SECCON/2023/Quals/crypto/plai_n_rsa/problem.py | ctfs/SECCON/2023/Quals/crypto/plai_n_rsa/problem.py | import os
from Crypto.Util.number import bytes_to_long, getPrime
flag = os.getenvb(b"FLAG", b"SECCON{THIS_IS_FAKE}")
assert flag.startswith(b"SECCON{")
m = bytes_to_long(flag)
e = 0x10001
p = getPrime(1024)
q = getPrime(1024)
n = p * q
e = 65537
phi = (p-1)*(q-1)
d = pow(e, -1, phi)
hint = p+q
c = pow(m,e,n)
print(f"e={e}")
print(f"d={d}")
print(f"hint={hint}")
print(f"c={c}") | python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/SECCON/2023/Quals/crypto/CIGISICGICGICG/problem.py | ctfs/SECCON/2023/Quals/crypto/CIGISICGICGICG/problem.py | import os
from functools import reduce
from secrets import randbelow
flag = os.getenvb(b"FLAG", b"FAKEFLAG{THIS_IS_FAKE}")
p1 = 21267647932558653966460912964485513283
a1 = 6701852062049119913950006634400761786
b1 = 19775891958934432784881327048059215186
p2 = 21267647932558653966460912964485513289
a2 = 10720524649888207044145162345477779939
b2 = 19322437691046737175347391539401674191
p3 = 21267647932558653966460912964485513327
a3 = 8837701396379888544152794707609074012
b3 = 10502852884703606118029748810384117800
def prod(x: list[int]) -> int:
return reduce(lambda a, b: a * b, x, 1)
def xor(x: bytes, y: bytes) -> bytes:
return bytes([xi ^ yi for xi, yi in zip(x, y)])
class ICG:
def __init__(self, p: int, a: int, b: int) -> None:
self.p = p
self.a = a
self.b = b
self.x = randbelow(self.p)
def _next(self) -> int:
if self.x == 0:
self.x = self.b
return self.x
else:
self.x = (self.a * pow(self.x, -1, self.p) + self.b) % self.p
return self.x
class CIG:
L = 256
def __init__(self, icgs: list[ICG]) -> None:
self.icgs = icgs
self.T = prod([icg.p for icg in self.icgs])
self.Ts = [self.T // icg.p for icg in self.icgs]
def _next(self) -> int:
ret = 0
for icg, t in zip(self.icgs, self.Ts):
ret += icg._next() * t
ret %= self.T
return ret % 2**self.L
def randbytes(self, n: int) -> bytes:
ret = b""
block_size = self.L // 8
while n > 0:
ret += self._next().to_bytes(block_size, "big")[: min(n, block_size)]
n -= block_size
return ret
if __name__ == "__main__":
random = CIG([ICG(p1, a1, b1), ICG(p2, a2, b2), ICG(p3, a3, b3)])
enc_flag = xor(flag, random.randbytes(len(flag)))
leaked = random.randbytes(300)
print(f"{enc_flag = }")
print(f"{leaked = }")
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/SECCON/2017/Quals/interpreter/interpreter.py | ctfs/SECCON/2017/Quals/interpreter/interpreter.py | import ast, sys, re, struct, tempfile, os
from uuid import uuid4
if len(sys.argv) < 2:
sys.argv.append('test.asm')
if len(sys.argv) < 3:
sys.argv.append(tempfile.mktemp(prefix='%s_' % uuid4(), dir='/tmp/relativity'))
f = open(sys.argv[1], 'r')
f2 = open(sys.argv[2], 'wb')
# Opcode definition
handler = {}
def sd(src=0, dst=0, src2=None):
r = chr((src & 0xf) | ((dst & 0xf) << 4))
if src2 is not None:
r = r + chr((src2 & 0xf))
return r
def reg(x):
if REGS.match(x):
return int(REGS.match(x).group(2))
def push(x):
src = reg(x)
return '\x03' + sd(src=src)
def arith(code):
def f(x, y, z):
dst, src, src2 = reg(x), reg(y), reg(z)
return chr(code) + sd(src=src, src2=src2, dst=dst)
return f
def li(x, y):
dst = reg(x)
return chr(9) + sd(dst=dst) + struct.pack("<L", y)
def print_op(x):
src = reg(x)
return chr(12) + sd(src=src)
def ls(x, y):
dst = reg(x)
return chr(10) + sd(dst=dst) + struct.pack("<L", len(y)) + y
def jmp(x):
return chr(5) + struct.pack("<L", x)
def jz(x, y):
src = reg(x)
return chr(15) + sd(src=src) + struct.pack("<L", y)
def jnz(x, y):
src = reg(x)
return chr(8) + sd(src=src) + struct.pack("<L", y)
def call(x, y):
return chr(6) + struct.pack("<LH", y, x)
def ret():
return chr(7)
def loadarg(x, y):
dst = reg(x)
return chr(11) + sd(dst=dst) + struct.pack("<H", y)
def pop(x):
dst = reg(x)
return chr(4) + sd(dst=dst)
def mov(x, y):
dst, src = reg(x), reg(y)
return chr(0) + sd(dst=dst, src=src)
refneeded = {
'jmp': (1, 5, [0]),
'jnz': (2, 6, [1]),
'jz': (2, 6, [1]),
'call': (3, 7, [1])
}
handler['mov'] = mov
handler['push'] = push
handler['add'] = arith(1)
handler['sub'] = arith(2)
handler['mul'] = arith(13)
handler['exit'] = lambda: '\x0e'
handler['li'] = li
handler['print'] = print_op
handler['ls'] = ls
handler['jmp'] = jmp
handler['jz'] = jz
handler['jnz'] = jnz
handler['call'] = call
handler['ret'] = ret
handler['loadarg'] = loadarg
handler['pop'] = pop
# Assembly parser
REGS = re.compile(r'(r(1[0-5]|[0-9]))')
COMMENT = re.compile(r'#(.*)$')
result = ''
reloc = []
labels = {}
def parse_args(args):
if args is not None:
args = REGS.sub(r"'\1'", args)
args = args.strip()
try:
if args:
args = ast.literal_eval(args)
except:
raise Exception('Invalid arguments: %s' % orig)
if op not in handler:
raise Exception('Unknown opcode: %s' % op)
if type(args)is not tuple:
args = args,
else:
args = ()
return args
for line in f:
line = COMMENT.sub('', line)
line = line.strip()
if not line: continue
if line[-1] == ':':
labels[line[:-1]] = len(result)
continue
if ' ' not in line:
op = line
args = None
else:
op, args = line.split(' ', 1)
op = op.lower()
orig = args
prev = len(result)
if op in refneeded:
reloc.append((len(result), op, args))
result += '?' * refneeded[op][1]
else:
args = parse_args(args)
result += handler[op](*args)
# Relocator
for offset, op, args in reloc:
binding, length, rel = refneeded[op]
node = ast.parse(args)
val = node.body[0].value
if not isinstance(val,ast.Tuple):
args += ','
args = args.split(',')
for i in rel:
args[i] = str(labels[args[i].strip()])
args = ','.join(args)
args = parse_args(args)
result = result[:offset] + handler[op](*args) + result[offset+length:]
f2.write('GRRR' + struct.pack(">L", len(result)).encode('hex') + result.encode('hex'))
f2.close()
# Interpreter
os.system('node ./interpreter.js working/%s' % sys.argv[2])
os.system('rm -f %s' % sys.argv[2]) | python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/SECCON/2017/Quals/interpreter/server.py | ctfs/SECCON/2017/Quals/interpreter/server.py | import os
import random
import tempfile
import re
from uuid import uuid4
from flask import Flask, abort, render_template, request
app = Flask(__name__)
root = os.path.dirname(os.path.abspath(__file__))
upload_dir = os.path.join(root, 'upload')
interpreter = os.path.join(root, 'interpreter.py')
temp_dir = '/tmp/relativity'
FLAG = 'SECCON{??????????????????????}'
if not os.path.exists(temp_dir):
os.mkdir(temp_dir)
def parse_time(output):
for line in output.split('\n'):
match = re.match('^user\t([0-9]+m)?([0-9]+\.[0-9]{3}s)$', line)
if match:
m = match.group(1)
if m[-1] == 's':
r = float(m[:-1])
elif m[-1] == 'm':
r = float(m[:-1]) * 60
r += float(match.group(2)[:-1])
return r
return 0
@app.route('/')
def index():
return render_template('index.html')
@app.route('/upload', methods=['POST'])
def upload_script():
script = request.files.get('script')
if script is None:
return abort(400)
filename = str(uuid4())
script_path = os.path.join(upload_dir, filename)
script.save(script_path)
make_temp = lambda: tempfile.mktemp(prefix='%s_' % filename, dir=temp_dir)
tmp = make_temp()
tmp2 = make_temp()
cmd = 'bash -c "time timeout 20 python %s %s" 1>%s 2>%s' % (interpreter, script_path, tmp, tmp2)
os.system(cmd)
with open(tmp, 'r') as f:
output = f.read()
with open(tmp2, 'r') as f:
times = f.read()
os.system('rm -f %s %s %s' % (tmp, tmp2, script_path))
t = parse_time(times)
output += '\n==STDERR==\n' + times + '\nTime: ' + str(t)
if t >= 100:
return output + '\nCongratulations! Here is your flag: ' + FLAG
return output
if __name__ == '__main__':
app.run(
debug=True,
use_reloader=True,
host='0.0.0.0',
port=5000,
)
| python | MIT | 129a3a9fe604443211fa4d493a49630c30689df7 | 2026-01-05T01:34:13.869332Z | false |
sajjadium/ctf-archives | https://github.com/sajjadium/ctf-archives/blob/129a3a9fe604443211fa4d493a49630c30689df7/ctfs/SECCON/2022/Quals/pwn/lslice/bin/app.py | ctfs/SECCON/2022/Quals/pwn/lslice/bin/app.py | #!/usr/bin/env python3
import subprocess
import sys
import tempfile
print("Input your Lua code (End with \"__EOF__\"):", flush=True)
source = ""
while True:
line = sys.stdin.readline()
if line.startswith("__EOF__"):
break
source += line
if len(source) >= 0x2000:
print("[-] Code too long")
exit(1)
with tempfile.NamedTemporaryFile(suffix='.lua') as f:
f.write(source.encode())
f.flush()
try:
subprocess.run(["./lua", f.name],
stdin=subprocess.DEVNULL,
stdout=1, # mercy
stderr=subprocess.DEVNULL)
except Exception as e:
print("[-]", e)
else:
print("[+] Done!")
| 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.