code
stringlengths 26
870k
| docstring
stringlengths 1
65.6k
| func_name
stringlengths 1
194
| language
stringclasses 1
value | repo
stringlengths 8
68
| path
stringlengths 5
182
| url
stringlengths 46
251
| license
stringclasses 4
values |
---|---|---|---|---|---|---|---|
def pollinate(self):
""" Have the bees pollinate their flower fields (in order). """
bees = [i for i in self.nectar]
A,B,C,D,E,F = self.fields
for i in range(6):
bees = [[A,B,C,D,E,F][i].flowers[k] ^^ bees[k] for k in range(6)]
self.fields[i].flowers = bees | Have the bees pollinate their flower fields (in order). | pollinate | python | sajjadium/ctf-archives | ctfs/K3RN3L/2021/crypto/Beecryption/beecryption.py | https://github.com/sajjadium/ctf-archives/blob/master/ctfs/K3RN3L/2021/crypto/Beecryption/beecryption.py | MIT |
def stream(self, n=1):
""" Produce the honey... I mean keystream! """
buf = []
# Go through n rounds
for i in range(n):
# Go through 6 sub-rounds
for field in self.fields:
field.rotate()
self.cross_breed()
self.collect()
self.pollinate()
# Collect nectar
self.collect()
buf += self.nectar
return buf | Produce the honey... I mean keystream! | stream | python | sajjadium/ctf-archives | ctfs/K3RN3L/2021/crypto/Beecryption/beecryption.py | https://github.com/sajjadium/ctf-archives/blob/master/ctfs/K3RN3L/2021/crypto/Beecryption/beecryption.py | MIT |
def encrypt(self, msg):
""" Beecrypt your message! """
beeline = self.stream(n = (len(msg) + 5) // 6)
cip = bytes([beeline[i] ^^ msg[i] for i in range(len(msg))])
return cip | Beecrypt your message! | encrypt | python | sajjadium/ctf-archives | ctfs/K3RN3L/2021/crypto/Beecryption/beecryption.py | https://github.com/sajjadium/ctf-archives/blob/master/ctfs/K3RN3L/2021/crypto/Beecryption/beecryption.py | MIT |
def __init__(self, flowers):
""" Initialise the flower field. """
self.flowers = [i for i in flowers] | Initialise the flower field. | __init__ | python | sajjadium/ctf-archives | ctfs/K3RN3L/2021/crypto/Beecryption/beecryption.py | https://github.com/sajjadium/ctf-archives/blob/master/ctfs/K3RN3L/2021/crypto/Beecryption/beecryption.py | MIT |
def rotate(self):
""" Crop-rotation is important! """
self.flowers = [self.flowers[-1]] + self.flowers[:-1] | Crop-rotation is important! | rotate | python | sajjadium/ctf-archives | ctfs/K3RN3L/2021/crypto/Beecryption/beecryption.py | https://github.com/sajjadium/ctf-archives/blob/master/ctfs/K3RN3L/2021/crypto/Beecryption/beecryption.py | MIT |
def __init__(self, p, q, g):
""" Initialise class object. """
self.p = p
self.q = q
self.g = g
self.sk = secrets.randbelow(self.q)
self.pk = pow(self.g, self.sk, self.p) | Initialise class object. | __init__ | python | sajjadium/ctf-archives | ctfs/K3RN3L/2021/crypto/Objection/objection.py | https://github.com/sajjadium/ctf-archives/blob/master/ctfs/K3RN3L/2021/crypto/Objection/objection.py | MIT |
def inv(self, x, p):
""" Return modular multiplicative inverse over prime field. """
return pow(x, p-2, p) | Return modular multiplicative inverse over prime field. | inv | python | sajjadium/ctf-archives | ctfs/K3RN3L/2021/crypto/Objection/objection.py | https://github.com/sajjadium/ctf-archives/blob/master/ctfs/K3RN3L/2021/crypto/Objection/objection.py | MIT |
def H_int(self, m):
""" Return integer hash of byte message. """
return int.from_bytes(hashlib.sha256(m).digest(),'big') | Return integer hash of byte message. | H_int | python | sajjadium/ctf-archives | ctfs/K3RN3L/2021/crypto/Objection/objection.py | https://github.com/sajjadium/ctf-archives/blob/master/ctfs/K3RN3L/2021/crypto/Objection/objection.py | MIT |
def bake(self, m, r, s):
""" Return JSON object of signed message. """
return json.dumps({ 'm' : m.hex() , 'r' : r , 's' : s }) | Return JSON object of signed message. | bake | python | sajjadium/ctf-archives | ctfs/K3RN3L/2021/crypto/Objection/objection.py | https://github.com/sajjadium/ctf-archives/blob/master/ctfs/K3RN3L/2021/crypto/Objection/objection.py | MIT |
def sign(self, m):
""" Sign a message. """
h = self.H_int(m)
k = secrets.randbelow(self.q)
r = pow(self.g, k, self.p) % self.q
s = ( self.inv(k, self.q) * (h + self.sk * r) ) % self.q
assert self.verify_recv(m, r, s, self.pk)
return self.bake(m, r, s) | Sign a message. | sign | python | sajjadium/ctf-archives | ctfs/K3RN3L/2021/crypto/Objection/objection.py | https://github.com/sajjadium/ctf-archives/blob/master/ctfs/K3RN3L/2021/crypto/Objection/objection.py | MIT |
def verify_recv(self, m, r, s, pk):
""" Verify a message received from pk holder. """
if r < 2 or r > self.q-2 or s < 2 or s > self.q-1:
return False
h = self.H_int(m)
u = self.inv(s, self.q)
v = (h * u) % self.q
w = (r * u) % self.q
return r == ((pow(self.g,v,self.p) * pow(pk,w,self.p)) % self.p) % self.q | Verify a message received from pk holder. | verify_recv | python | sajjadium/ctf-archives | ctfs/K3RN3L/2021/crypto/Objection/objection.py | https://github.com/sajjadium/ctf-archives/blob/master/ctfs/K3RN3L/2021/crypto/Objection/objection.py | MIT |
def init():
connection.execute('''
create table approved (
id integer primary key autoincrement,
sentence text
);
''')
connection.execute('''
create table pending (
id integer primary key autoincrement,
user text,
sentence text
);
''')
connection.execute('''
create table users (
token text
);
''')
connection.execute('''
create table flags (
flag text
);
''')
initial = [
'rats live on no evil star',
'kayak',
'mr owl ate my metal worm',
'do geese see god',
'313',
'a man a plan a canal panama',
'doc note i dissent a fast never prevents a fatness i diet on cod',
'live on time emit no evil',
]
for palindrome in initial:
connection.execute('''
insert into approved (sentence) values ('%s');
''' % palindrome)
connection.execute('''
insert into flags (flag) values ('%s');
''' % os.environ.get('FLAG', 'flag is missing!')) | )
connection.execute( | init | python | sajjadium/ctf-archives | ctfs/redpwn/2022/web/oeps/app.py | https://github.com/sajjadium/ctf-archives/blob/master/ctfs/redpwn/2022/web/oeps/app.py | MIT |
async def root(request):
token = request.cookies.get('token', '')
requires_cookie = (
any(c not in ALLOWED_CHARACTERS for c in token) or
len(connection.execute('''
select * from users where token = '%s';
''' % token).fetchall()) != 1
)
headers = {}
if requires_cookie:
token = ''.join(random.choice('0123456789abcdef') for _ in range(32))
headers['set-cookie'] = f'token={token}'
connection.execute('''
insert into users (token) values ('%s');
''' % token)
pending = connection.execute('''
select sentence from pending where user = '%s';
''' % token).fetchall()
return (200, '''
<title>OEPS</title>
<link rel="stylesheet" href="/style.css" />
<div class="container">
<h1>The On-Line Encyclopedia of Palidromic Sentences</h1>
Enter a word or phrase:
<form action="/search" method="GET">
<input type="text" name="search" placeholder="on" />
<input type="submit" value="Search" />
</form>
<h2>Submit Sentence:</h2>
New palindrome:
<form action="/submit" method="POST">
<input type="text" name="submission" />
<input type="submit" value="Submit" />
</form>
<div style="color: red">%s</div>
<h2>Pending submissions:</h2>
<ul>%s</ul>
</div>
''' % (
request.query.get('error', '').replace('<', '<'),
''.join(f'<li>{palindrome}</li>' for (palindrome,) in pending),
), headers) | % token).fetchall()) != 1
)
headers = {}
if requires_cookie:
token = ''.join(random.choice('0123456789abcdef') for _ in range(32))
headers['set-cookie'] = f'token={token}'
connection.execute( | root | python | sajjadium/ctf-archives | ctfs/redpwn/2022/web/oeps/app.py | https://github.com/sajjadium/ctf-archives/blob/master/ctfs/redpwn/2022/web/oeps/app.py | MIT |
async def search(request):
if 'error' in request.query:
return (200, '''
<title>OEPS</title>
<link rel="stylesheet" href="/style.css" />
<div class="container">
<h1>The On-Line Encyclopedia of Palidromic Sentences</h1>
Enter a word or phrase:
<form action="/search" method="GET">
<input type="text" name="search" placeholder="on" />
<input type="submit" value="Search" />
</form>
<div style="color: red">%s</div>
<hr noshade />
</div>
''' % request.query.get('error', '').replace('<', '<'))
else:
search = request.query.get('search', '')
if search == '':
return (302, '/search?error=Search cannot be empty!')
if any(c not in ALLOWED_CHARACTERS for c in search):
return (302, '/search?error=Search must be alphanumeric!')
result = connection.execute('''
select sentence from approved where sentence like '%%%s%%';
''' % search).fetchall()
count = len(result)
return (200, '''
<title>OEPS</title>
<link rel="stylesheet" href="/style.css" />
<div class="container">
<h1>The On-Line Encyclopedia of Palidromic Sentences</h1>
Enter a word or phrase:
<form action="/search" method="GET">
<input type="text" name="search" placeholder="on" />
<input type="submit" value="Search" />
</form>
<hr noshade />
<h2>%s</h2>
<ul>%s</ul>
</div>
''' % (
'No results.' if count == 0 else f'Results ({count}):',
''.join(f'<li>{palindrome}</li>' for (palindrome,) in result),
)) | % request.query.get('error', '').replace('<', '<'))
else:
search = request.query.get('search', '')
if search == '':
return (302, '/search?error=Search cannot be empty!')
if any(c not in ALLOWED_CHARACTERS for c in search):
return (302, '/search?error=Search must be alphanumeric!')
result = connection.execute( | search | python | sajjadium/ctf-archives | ctfs/redpwn/2022/web/oeps/app.py | https://github.com/sajjadium/ctf-archives/blob/master/ctfs/redpwn/2022/web/oeps/app.py | MIT |
async def submit(request):
token = request.cookies.get('token', '')
logged_in = (
all(c in ALLOWED_CHARACTERS for c in token) and
len(connection.execute('''
select * from users where token = '%s';
''' % token).fetchall()) == 1
)
if not logged_in:
return (302, '/?error=Authentication error.')
data = await request.post()
submission = data.get('submission', '')
if submission == '':
return (302, '/?error=Submission cannot be empty.')
stripped = submission.replace(' ', '')
if stripped != stripped[::-1]:
return (302, '/?error=Submission must be a palindrome.')
connection.execute('''
insert into pending (user, sentence) values ('%s', '%s');
''' % (
token,
submission
))
return (302, '/') | % token).fetchall()) == 1
)
if not logged_in:
return (302, '/?error=Authentication error.')
data = await request.post()
submission = data.get('submission', '')
if submission == '':
return (302, '/?error=Submission cannot be empty.')
stripped = submission.replace(' ', '')
if stripped != stripped[::-1]:
return (302, '/?error=Submission must be a palindrome.')
connection.execute( | submit | python | sajjadium/ctf-archives | ctfs/redpwn/2022/web/oeps/app.py | https://github.com/sajjadium/ctf-archives/blob/master/ctfs/redpwn/2022/web/oeps/app.py | MIT |
async def root(request):
admin = request.cookies.get('admin', '')
headers = {}
if admin == '':
headers['set-cookie'] = 'admin=false'
if admin == 'true':
return (200, '''
<title>Secure Page</title>
<link rel="stylesheet" href="/style.css" />
<div class="container">
<h1>Secure Page</h1>
%s
</div>
''' % os.environ.get('FLAG', 'flag is missing!'), headers)
else:
return (200, '''
<title>Secure Page</title>
<link rel="stylesheet" href="/style.css" />
<div class="container">
<h1>Secure Page</h1>
Sorry, you must be the admin to view this content!
</div>
''', headers) | % os.environ.get('FLAG', 'flag is missing!'), headers)
else:
return (200, | root | python | sajjadium/ctf-archives | ctfs/redpwn/2022/web/secure-page/app.py | https://github.com/sajjadium/ctf-archives/blob/master/ctfs/redpwn/2022/web/secure-page/app.py | MIT |
def init():
# this is terrible but who cares
execute('''
CREATE TABLE IF NOT EXISTS users (
username TEXT PRIMARY KEY,
password TEXT
);
''')
execute('DROP TABLE users;')
execute('''
CREATE TABLE users (
username TEXT PRIMARY KEY,
password TEXT
);
''')
# we also need a table for pastes
execute('''
CREATE TABLE IF NOT EXISTS pastes (
id TEXT PRIMARY KEY,
paste TEXT,
username TEXT
);
''')
execute('DROP TABLE pastes;')
execute('''
CREATE TABLE pastes (
id TEXT PRIMARY KEY,
paste TEXT,
username TEXT
);
''')
# put admin into db
admin_password = secrets.token_hex(32)
execute(
'INSERT OR IGNORE INTO users (username, password) VALUES (?, ?);',
params=('admin', admin_password)
)
execute(
'UPDATE users SET password = ? WHERE username = ?;',
params=(admin_password, 'admin')
)
create_paste(os.getenv('FLAG'), 'admin') | )
execute('DROP TABLE users;')
execute( | init | python | sajjadium/ctf-archives | ctfs/redpwn/2021/web/pastebin-3/app/app.py | https://github.com/sajjadium/ctf-archives/blob/master/ctfs/redpwn/2021/web/pastebin-3/app/app.py | MIT |
def interpret(bcode = [], inp = [], storage = []):
PC = 4
LR = 5
INPLEN = 11
CALLER = 12
FLAG = 13
SP = 14
BP = 15
def translateAddr(addr):
idx = addr>>32
offset = addr&0xffffffff
if idx > 4 or offset > 0x1000:
print(f'invalid addr : {hex(addr)}')
exit()
return idx, offset
def getMem(mem, addr, size):
idx, offset = translateAddr(addr)
if offset + size > 0x1000:
print(f'invalid mem get : {hex(addr)} {hex(size)}')
return int.from_bytes(mem[idx][offset : offset + size],'little')
def setMem(mem, addr, size, val):
idx, offset = translateAddr(addr)
if offset + size > 0x1000:
print(f'invalid mem set : {hex(addr)} {hex(size)}')
val = val & ((1 << (size * 8)) - 1)
v = int.to_bytes(val, size, 'little')
for i in range(size):
mem[idx][offset + i] = v[i]
if type(bcode) == bytes:
bcode = list(bcode)
if type(inp) == bytes:
inp = list(inp)
if type(storage) == bytes:
storage = list(storage)
regs = [0 for i in range(0x10)]
regs[PC] = 0x200000000 #pc
regs[LR] = 0xffffffffffffffff #lr
regs[FLAG] = 0 #flag
regs[SP] = 0x300001000 #sp
regs[BP] = 0x300001000 #bp
mem = [inp + [0 for i in range(0x1000 - len(inp))],
storage + [0 for i in range(0x1000 - len(storage))],
bcode + [0 for i in range(0x1000 - len(bcode))],
[0 for i in range(0x1000)],
[0 for i in range(0x1000)]]
while True:
opcode = getMem(mem, regs[PC], 1)
if (opcode & 0xf0) == 0 and (opcode & 0x8) == 0x8:
size = (opcode & 0x7) + 1
v = getMem(mem, regs[PC] + 1, size)
regs[PC] += 1 + size
regs[SP] -= size
setMem(mem, regs[SP], size, v)
elif (opcode & 0xf0) == 0x10:
size = (opcode & 0x7) + 1
r = getMem(mem, regs[PC] + 1, 1) & 0xf
regs[PC] += 2
if r in (PC, LR):
print(f'invalid opcode at {hex(regs[PC])}')
return mem, regs
if (opcode & 0x8) == 0:
regs[r] = getMem(mem, regs[SP], size)
regs[SP] += size
else:
regs[SP] -= size
setMem(mem, regs[SP], size, regs[r])
elif (opcode & 0xf0) == 0x20:
size = (opcode & 0x7) + 1
r = getMem(mem, regs[PC] + 1, 1)
regs[PC] += 2
r1 = r & 0xf
r2 = r >> 4
if r1 in (PC, LR) or r2 in (PC, LR):
print(f'invalid opcode at {hex(regs[PC])}')
return mem, regs
if (opcode & 0x8) == 0:
regs[r1] = getMem(mem, regs[r2], size)
else:
setMem(mem, regs[r1], size, regs[r2])
elif (opcode & 0xf0) == 0x30:
size = (opcode & 0x7) + 1
r = getMem(mem, regs[PC] + 1, 1) & 0xf
v = getMem(mem, regs[PC] + 2, size)
regs[PC] += 2 + size
if r in (PC, LR):
print(f'invalid opcode at {hex(regs[PC])}')
return mem, regs
if (opcode & 0x8) == 0:
regs[r] = v
else:
setMem(mem, regs[r], size, v)
elif (opcode & 0xf0) == 0x40:
if (opcode & 0x8) == 0x8:
'''
r = getMem(mem, regs[PC] + 1, 1) & 0xf
regs[PC] += 2
dst = regs[r]
'''
print(f'invalid opcode at {hex(regs[PC])}')
return mem, regs
else:
dst = getMem(mem, regs[PC] + 1, 2)
if dst >= 0x8000:
dst -= 0x10000
regs[PC] += 3
dst += regs[PC]
if (opcode & 0xf) == 0:
regs[PC] = dst
elif (opcode & 0xf) == 1:
regs[SP] -= 6
setMem(mem, regs[SP], 6, regs[LR]) #push lr
regs[SP] -= 6
setMem(mem, regs[SP], 6, regs[BP]) #push bp
regs[BP] = regs[SP]
regs[LR] = regs[PC]
regs[PC] = dst
elif (opcode & 0xf) == 2 and (regs[FLAG] & 4) == 4:
regs[PC] = dst
elif (opcode & 0xf) == 3 and (regs[FLAG] & 3) != 0:
regs[PC] = dst
elif (opcode & 0xf) == 4 and (regs[FLAG] & 1) == 1:
regs[PC] = dst
elif (opcode & 0xf) == 5 and (regs[FLAG] & 1) == 0:
regs[PC] = dst
elif (opcode & 0xf) == 6 and (regs[FLAG] & 5) != 0:
regs[PC] = dst
elif (opcode & 0xf) == 7 and (regs[FLAG] & 2) == 2:
regs[PC] = dst
elif (opcode & 0xf0) == 0x50 and (opcode & 0xf) <= 0xa:
r = getMem(mem, regs[PC] + 1, 1)
regs[PC] += 2
r1 = r & 0xf
r2 = r >> 4
if r1 in (PC, LR) or r2 in (PC, LR):
print(f'invalid opcode at {hex(regs[PC])}')
return mem, regs
if (opcode & 0xf) == 0:
regs[r1] = (regs[r1] - regs[r2]) & 0xffffffffffffffff
if regs[r1] < 0:
regs[r1] += 0x10000000000000000
elif (opcode & 0xf) == 1:
regs[r1] = (regs[r1] + regs[r2]) & 0xffffffffffffffff
elif (opcode & 0xf) == 2:
regs[r1] = (regs[r1] * regs[r2]) & 0xffffffffffffffff
elif (opcode & 0xf) == 3:
regs[r1] = (regs[r1] // regs[r2]) & 0xffffffffffffffff
elif (opcode & 0xf) == 4:
regs[r1] = (regs[r1] & regs[r2]) & 0xffffffffffffffff
elif (opcode & 0xf) == 5:
regs[r1] = (regs[r1] | regs[r2]) & 0xffffffffffffffff
elif (opcode & 0xf) == 6:
regs[r1] = (regs[r1] ^ regs[r2]) & 0xffffffffffffffff
elif (opcode & 0xf) == 7:
regs[r1] = (regs[r1] >> (regs[r2] & 0x3f)) & 0xffffffffffffffff
elif (opcode & 0xf) == 8:
regs[r1] = (regs[r1] << (regs[r2] & 0x3f)) & 0xffffffffffffffff
elif (opcode & 0xf) == 9:
regs[r1] = regs[r2]
elif (opcode & 0xf) == 10:
flag = 0
if regs[r1] == regs[r2]:
flag |= 1
if regs[r1] > regs[r2]:
flag |= 2
if regs[r1] < regs[r2]:
flag |= 4
regs[FLAG] = flag
elif (opcode & 0xf0) == 0xf0 and (opcode & 0xf) >= 0xd:
if opcode == 0xfd:
regs[SP] = regs[BP]
regs[BP] = getMem(mem, regs[SP], 6)
regs[SP] += 6
regs[PC] = regs[LR]
regs[LR] = getMem(mem, regs[SP], 6)
regs[SP] += 6
elif opcode == 0xfe:
regs[PC] += 1
input('invoke')
elif opcode == 0xff:
regs[PC] += 1
return mem, regs
else:
print(f'invalid opcode at {hex(regs[PC])}')
return mem, regs | r = getMem(mem, regs[PC] + 1, 1) & 0xf
regs[PC] += 2
dst = regs[r] | interpret | python | sajjadium/ctf-archives | ctfs/Balsn/2023/pwn/ASTRAL_StarryNight/sourcecode/APPLET/interpreter.py | https://github.com/sajjadium/ctf-archives/blob/master/ctfs/Balsn/2023/pwn/ASTRAL_StarryNight/sourcecode/APPLET/interpreter.py | MIT |
def aasm(code):
def check(condition):
if not condition:
print(f'invalid argument on line {lnum + 1} : {origLine}')
exit()
def getReg(rs):
if rs == 'pc':
return 4
elif rs == 'lr':
return 5
elif rs == 'inplen':
return 11
elif rs == 'caller':
return 12
elif rs == 'flag':
return 13
elif rs == 'sp':
return 14
elif rs == 'bp':
return 15
check(rs[0] == 'r')
try:
reg = int(rs[1:])
except:
check(False)
check(reg >= 0 and reg < 16)
return reg
def getNum(n, size, unsigned = False, dontCareSign = False):
if n[0] == '-':
sign = -1
n = n[1:]
else:
sign = 1
if len(n) > 2 and n[:2] == '0x':
base = 16
else:
base = 10
try:
n = int(n, base)
except:
check(False)
n *= sign
if dontCareSign:
Min = -(1 << size) // 2
Max = (1 << size) - 1
else:
if unsigned is False:
Min = -(1 << size) // 2
Max = (1 << size) // 2 - 1
else:
Min = 0
Max = (1 << size) - 1
check(n >= Min and n <= Max)
if n < 0:
n += (1 << size)
return n
JMP = {
'call': 0x40,
'jmp' : 0x41,
'jb' : 0x42,
'jae' : 0x43,
'je' : 0x44,
'jne' : 0x45,
'jbe' : 0x46,
'ja' : 0x47,
}
ALU = {
'add' : 0x50,
'sub' : 0x51,
'mul' : 0x52,
'div' : 0x53,
'and' : 0x54,
'or' : 0x55,
'xor' : 0x56,
'shr' : 0x57,
'shl' : 0x58,
'mov' : 0x59,
'cmp' : 0x5a,
}
JMPDST = {}
RESOLVE = {}
code = code.strip().split('\n')
bcode = b''
for lnum, line in enumerate(code):
origLine = line
comment = line.find('//')
if comment != -1:
line = line[:comment]
line = line.strip()
if line=='':
continue
#print(line)
line = line.split()
if line[0] == 'push':
check(len(line) == 2 or len(line) == 3)
if len(line) == 2:
#shorthand to not specify push imm size
n = getNum(line[1], 64, dontCareSign = True)
if n == 0:
S = 1
else:
S = (n.bit_length() + 7) // 8
bcode += p8(0x08 | (S - 1)) + int.to_bytes(n, S, 'little')
else:
check(len(line[1]) > 2 and line[1][0] == '<' and line[1][-1] == '>')
S = getNum(line[1][1:-1], 4, unsigned = True)
check(1 <= S and S <= 8)
if line[2][0].isdigit():
n = getNum(line[2], S * 8, dontCareSign = True)
bcode += p8(0x08 | (S - 1)) + int.to_bytes(n, S, 'little')
else:
r0 = getReg(line[2])
bcode += p8(0x18 | (S - 1)) + p8(r0)
elif line[0] == 'pop':
check(len(line) == 3)
check(len(line[1]) > 2 and line[1][0] == '<' and line[1][-1] == '>')
S = getNum(line[1][1:-1], 4, unsigned = True)
check(1 <= S and S <=8)
r0 = getReg(line[2])
bcode += p8(0x10 | (S - 1)) + p8(r0)
elif line[0] == 'load':
line = ' '.join(line[1:]).split(',')
check(len(line) == 2)
hasSize = line[0][0] == '<'
if not hasSize:
#shorthand to not specify load imm size
r0 = getReg(line[0].strip())
n = getNum(line[1].strip(), 64, dontCareSign = True)
if n == 0:
S = 1
else:
S = (n.bit_length() + 7) // 8
bcode += p8(0x30 | (S - 1)) + p8(r0) + int.to_bytes(n, S, 'little')
else:
S, r0 = line[0].strip().split()
check(len(S) > 2 and S[0] == '<' and S[-1] == '>')
S = getNum(S[1:-1], 4, unsigned = True)
check(1 <= S and S <= 8)
r0 = getReg(r0)
line[1] = line[1].strip()
if line[1][0] != '[':
n = getNum(line[1], S * 8, dontCareSign = True)
bcode += p8(0x30 | (S - 1)) + p8(r0) + int.to_bytes(n, S, 'little')
else:
check(line[1][0] == '[' and line[1][-1] == ']')
r1 = getReg(line[1][1:-1])
bcode += p8(0x20 | (S - 1)) + p8(r0 | (r1 << 4))
elif line[0] == 'store':
line = ' '.join(line[1:]).split(',')
check(len(line) == 2)
hasSize = line[0][0] == '<'
if not hasSize:
#shorthand to not specify store imm size
line[0] = line[0].strip()
check(line[0][0] == '[' and line[0][-1] == ']')
r0 = getReg(line[0][1:-1])
n = getNum(line[1].strip(), 64, dontCareSign = True)
if n == 0:
S = 1
else:
S = (n.bit_length() + 7) // 8
bcode += p8(0x38 | (S - 1)) + p8(r0) + int.to_bytes(n, S, 'little')
else:
S = line[0].strip().split()[0]
dst = line[0][len(S):].strip()
check(len(S) > 2 and S[0] == '<' and S[-1] == '>')
S = getNum(S[1:-1], 4, unsigned = True)
check(1 <= S and S <= 8)
dst = dst.strip()
check(dst[0] == '[' and dst[-1] == ']')
dst = dst[1:-1]
line[1] = line[1].strip()
if line[1][0] != 'r':
r0 = getReg(dst)
n = getNum(line[1], S * 8, dontCareSign = True)
bcode += p8(0x38 | (S - 1)) + p8(r0) + int.to_bytes(n, S, 'little')
else:
r0 = getReg(dst)
r1 = getReg(line[1])
bcode += p8(0x28 | (S - 1)) + p8(r0 | (r1 << 4))
elif line[0] in JMP:
check(len(line) == 2)
if line[1][0].isdigit() or line[1] not in ('r0','r1','r2','r3','r4','r5','r6','r7','r8','r9','r10','r11','r12','r13','r14','r15','pc','lr','inplen','caller','flag','sp','bp'):
if line[1][0].isdigit():
#Theoretically, we shouldn't do this, jumping to static offset is error prone, but allow for flexibility
n = getNum(line[1], 16)
bcode += p8(JMP[line[0]]) + p16(n)
else:
tag = line[1]
offset = len(bcode) + 3
if tag in JMPDST:
#This is a backward jump, so delta must be negative
delta = JMPDST[tag] - offset + (1 << 16)
bcode += p8(JMP[line[0]]) + p16(delta)
else:
RESOLVE[offset] = (tag, lnum, origLine)
bcode += p8(JMP[line[0]]) + p16(0)
else:
check(False)
'''
else:
r0 = getReg(line[1])
bcode += p8(JMP[line[0]] | 0x08) + p8(r0)
'''
elif line[0] in ALU:
opc = line[0]
line = ' '.join(line[1:]).strip().split(',')
check(len(line) == 2)
r0, r1 = getReg(line[0].strip()), getReg(line[1].strip())
bcode += p8(ALU[opc]) + p8(r0 | (r1 << 4))
elif line[0] == 'return':
check(len(line) == 1)
bcode += b'\xfd'
elif line[0] == 'invoke':
check(len(line) == 1)
bcode += b'\xfe'
elif line[0] == 'exit':
check(len(line) == 1)
bcode += b'\xff'
else:
check(len(line) == 1 and len(line[0]) > 1)
check(line[0][-1] == ':')
check(not line[0][0].isdigit())
tag = line[0][:-1]
check(tag not in JMPDST)
JMPDST[tag] = len(bcode)
for offset in RESOLVE:
tag, lnum, origLine = RESOLVE[offset]
if tag not in JMPDST:
print(f'unknown tag on line {lnum} : {origLine}')
exit()
delta = JMPDST[tag] - offset
bcode = bcode[:offset-2] + p16(delta) + bcode[offset:]
return bcode | else:
r0 = getReg(line[1])
bcode += p8(JMP[line[0]] | 0x08) + p8(r0) | aasm | python | sajjadium/ctf-archives | ctfs/Balsn/2023/pwn/ASTRAL_StarryNight/sourcecode/APPLET/assembler.py | https://github.com/sajjadium/ctf-archives/blob/master/ctfs/Balsn/2023/pwn/ASTRAL_StarryNight/sourcecode/APPLET/assembler.py | MIT |
def myInput(prompt):
'''
python input prompts to stderr by default, and there is no option to change this afaik
this wrapper is just normal input with stdout prompt
'''
print(prompt,end='')
return input() | python input prompts to stderr by default, and there is no option to change this afaik
this wrapper is just normal input with stdout prompt | myInput | python | sajjadium/ctf-archives | ctfs/Balsn/2022/pwn/sentinel/share/instanceManager.py | https://github.com/sajjadium/ctf-archives/blob/master/ctfs/Balsn/2022/pwn/sentinel/share/instanceManager.py | MIT |
def populateInstanceConfig(instanceId,instancePath,instanceConfigPath,guestHomeDir):
Dockerfile = f'''
from ubuntu:jammy
RUN useradd -m sentinel
USER sentinel
WORKDIR /home/sentinel/
ENTRYPOINT ["./sentinel"]
'''
dockerCompose = f'''
version: '3'
volumes:
storage{instanceId}:
driver: local
driver_opts:
type: overlay
o: lowerdir={guestHomeDir},upperdir={os.path.join(instancePath,'upper')},workdir={os.path.join(instancePath,'work')}
device: overlay
services:
sentinel{instanceId}:
build: ./
volumes:
- storage{instanceId}:/home/sentinel/
stdin_open : true
'''
with open(os.path.join(instanceConfigPath,'Dockerfile'),'w') as f:
f.write(Dockerfile)
with open(os.path.join(instanceConfigPath,'docker-compose.yml'),'w') as f:
f.write(dockerCompose) | dockerCompose = f | populateInstanceConfig | python | sajjadium/ctf-archives | ctfs/Balsn/2022/pwn/sentinel/share/instanceManager.py | https://github.com/sajjadium/ctf-archives/blob/master/ctfs/Balsn/2022/pwn/sentinel/share/instanceManager.py | MIT |
def gen_sbox():
"""
SBOX is generated in a similar way as AES, i.e., linear transform over the multiplicative inverse (L * x^-1 + C),
to prevent differential fault analysis.
"""
INV = [0, 1, 142, 244, 71, 167, 122, 186, 173, 157, 221, 152, 61, 170, 93, 150, 216, 114, 192, 88, 224, 62, 76, 102, 144, 222, 85, 128, 160, 131, 75, 42, 108, 237, 57, 81, 96, 86, 44, 138, 112, 208, 31, 74, 38, 139, 51, 110, 72, 137, 111, 46, 164, 195, 64, 94, 80, 34, 207, 169, 171, 12, 21, 225, 54, 95, 248, 213, 146, 78, 166, 4, 48, 136, 43, 30, 22, 103, 69, 147, 56, 35, 104, 140, 129, 26, 37, 97, 19, 193, 203, 99, 151, 14, 55, 65, 36, 87, 202, 91, 185, 196, 23, 77, 82, 141, 239, 179, 32, 236, 47, 50, 40, 209, 17, 217, 233, 251, 218, 121, 219, 119, 6, 187, 132, 205, 254, 252, 27, 84, 161, 29, 124, 204, 228, 176, 73, 49, 39, 45, 83, 105, 2, 245, 24, 223, 68, 79, 155, 188, 15, 92, 11, 220, 189, 148, 172, 9, 199, 162, 28, 130, 159, 198, 52, 194, 70, 5, 206, 59, 13, 60, 156, 8, 190, 183, 135, 229, 238, 107, 235, 242, 191, 175, 197, 100, 7, 123, 149, 154, 174, 182, 18, 89, 165, 53, 101, 184, 163, 158, 210, 247, 98, 90, 133, 125, 168, 58, 41, 113, 200, 246, 249, 67, 215, 214, 16, 115, 118, 120, 153, 10, 25, 145, 20, 63, 230, 240, 134, 177, 226, 241, 250, 116, 243, 180, 109, 33, 178, 106, 227, 231, 181, 234, 3, 143, 211, 201, 66, 212, 232, 117, 127, 255, 126, 253]
L = [[0, 0, 1, 1, 0, 1, 0, 1],
[0, 1, 1, 0, 1, 0, 1, 0],
[1, 1, 0, 1, 0, 1, 0, 0],
[1, 0, 1, 0, 1, 0, 0, 0],
[0, 1, 1, 0, 0, 1, 0, 0],
[1, 1, 1, 1, 1, 1, 0, 0],
[1, 1, 0, 0, 1, 1, 0, 1],
[1, 0, 0, 1, 1, 0, 1, 0]]
C = [1, 0, 1, 1, 1, 0, 1, 0]
S = []
for _ in range(256):
inv = bin(INV[_])[2:].rjust(8, '0')[::-1]
v = [sum([a * int(b) for (a, b) in zip(L[__], inv)] + [C[__]]) % 2 for __ in range(8)]
S.append(sum([v[__] * 2**(7 - __) for __ in range(8)]))
return S | SBOX is generated in a similar way as AES, i.e., linear transform over the multiplicative inverse (L * x^-1 + C),
to prevent differential fault analysis. | gen_sbox | python | sajjadium/ctf-archives | ctfs/0CTF/2022/crypto/leopard/cipher.py | https://github.com/sajjadium/ctf-archives/blob/master/ctfs/0CTF/2022/crypto/leopard/cipher.py | MIT |
def main():
mcu: MCU = None
while True:
print(
textwrap.dedent(
"""
Main menu:
1. Create new MCU.
2. Flash segment.
3. Dump segment.
4. Run MCU.
5. Exit.
"""
)
)
choice = input("Choice: ")
if choice == "1":
mcu = MCU()
flash_demo_image(mcu)
elif choice == "2":
if mcu is None:
raise Exception("No MCU found.")
segment = int(input("Segment: "))
image = bytes.fromhex(input("Image: "))
signature = bytes.fromhex(input("Signature: "))
mcu.flash(segment, image, signature)
elif choice == "3":
if mcu is None:
raise Exception("No MCU found.")
segment = int(input("Segment: "))
print("Content: ")
hexdump(mcu.dump(segment))
elif choice == "4":
if mcu is None:
raise Exception("No MCU found.")
try:
mcu.run()
except Exception as e:
print("The MCU crashed with error:", e)
break
elif choice == "5":
break | Main menu:
1. Create new MCU.
2. Flash segment.
3. Dump segment.
4. Run MCU.
5. Exit. | main | python | sajjadium/ctf-archives | ctfs/CCCamp/2023/crypto/FusEd/main.py | https://github.com/sajjadium/ctf-archives/blob/master/ctfs/CCCamp/2023/crypto/FusEd/main.py | MIT |
def zoom(self, value: float) -> None:
"""Here we set zoom, clamp value to minimum of min_zoom and max of max_zoom."""
self._zoom = max(min(value, self.max_zoom), self.min_zoom) | Here we set zoom, clamp value to minimum of min_zoom and max of max_zoom. | zoom | python | sajjadium/ctf-archives | ctfs/CCCamp/2023/game/Dig_It_Up/src/client/client/game/camera.py | https://github.com/sajjadium/ctf-archives/blob/master/ctfs/CCCamp/2023/game/Dig_It_Up/src/client/client/game/camera.py | MIT |
def position(self) -> Tuple[float, float]:
"""Query the current offset."""
return self.offset_x, self.offset_y | Query the current offset. | position | python | sajjadium/ctf-archives | ctfs/CCCamp/2023/game/Dig_It_Up/src/client/client/game/camera.py | https://github.com/sajjadium/ctf-archives/blob/master/ctfs/CCCamp/2023/game/Dig_It_Up/src/client/client/game/camera.py | MIT |
def position(self, value: Tuple[float, float]) -> None:
"""Set the scroll offset directly."""
# Check for borders
self.offset_x, self.offset_y = value | Set the scroll offset directly. | position | python | sajjadium/ctf-archives | ctfs/CCCamp/2023/game/Dig_It_Up/src/client/client/game/camera.py | https://github.com/sajjadium/ctf-archives/blob/master/ctfs/CCCamp/2023/game/Dig_It_Up/src/client/client/game/camera.py | MIT |
def move(self, axis_x: float, axis_y: float) -> None:
"""Move axis direction with scroll_speed.
Example: Move left -> move(-1, 0)
"""
self.offset_x += self.scroll_speed * axis_x
self.offset_y += self.scroll_speed * axis_y | Move axis direction with scroll_speed.
Example: Move left -> move(-1, 0) | move | python | sajjadium/ctf-archives | ctfs/CCCamp/2023/game/Dig_It_Up/src/client/client/game/camera.py | https://github.com/sajjadium/ctf-archives/blob/master/ctfs/CCCamp/2023/game/Dig_It_Up/src/client/client/game/camera.py | MIT |
def draw(self):
"""Draw the sprite at its current position.
See the module documentation for hints on drawing multiple sprites
efficiently.
"""
if not self._group:
return
self._group.set_state_recursive()
if self.program:
self.program["origin_scale"] = (self.origin_scale[0], self.origin_scale[1])
self.program["origin_rotation"] = (
self.origin_rotation[0],
self.origin_rotation[1],
)
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST)
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST)
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE)
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE)
if self._vertex_list:
self._vertex_list.draw(GL_TRIANGLES)
self._group.unset_state_recursive() | Draw the sprite at its current position.
See the module documentation for hints on drawing multiple sprites
efficiently. | draw | python | sajjadium/ctf-archives | ctfs/CCCamp/2023/game/Dig_It_Up/src/client/client/game/nearest_sprite.py | https://github.com/sajjadium/ctf-archives/blob/master/ctfs/CCCamp/2023/game/Dig_It_Up/src/client/client/game/nearest_sprite.py | MIT |
def _html(self, message):
"""This just generates an HTML document that includes `message`
in the body. Override, or re-write this do do more interesting stuff.
"""
content = f"<html><body><h1>Tickets</h1>{message}</body></html>"
return content.encode("utf8") # NOTE: must return a bytes object! | This just generates an HTML document that includes `message`
in the body. Override, or re-write this do do more interesting stuff. | _html | python | sajjadium/ctf-archives | ctfs/CCCamp/2023/web/Awesome_Notepad/note-admin/watcher.py | https://github.com/sajjadium/ctf-archives/blob/master/ctfs/CCCamp/2023/web/Awesome_Notepad/note-admin/watcher.py | MIT |
def generate_hash(timestamp=None):
"""Generate hash for post preview."""
if timestamp:
seed(timestamp)
else:
seed(int(datetime.now().timestamp()))
return randbytes(32).hex() | Generate hash for post preview. | generate_hash | python | sajjadium/ctf-archives | ctfs/HeroCTF/2023/web/Blogodogo_12/src/utils.py | https://github.com/sajjadium/ctf-archives/blob/master/ctfs/HeroCTF/2023/web/Blogodogo_12/src/utils.py | MIT |
def iter_chunks(xs, n=1448):
"""Yield successive n-sized chunks from xs"""
for i in range(0, len(xs), n):
yield xs[i : i + n] | Yield successive n-sized chunks from xs | iter_chunks | python | sajjadium/ctf-archives | ctfs/CircleCityCon/2021/web/Sticky_Notes/apps/web/notes.py | https://github.com/sajjadium/ctf-archives/blob/master/ctfs/CircleCityCon/2021/web/Sticky_Notes/apps/web/notes.py | MIT |
def pack(self):
"""Pack the packet into bytes"""
if len(self.payload) > 255:
raise ValueError("Payload too large (max 255 bytes)")
header = struct.pack('!BBB4sB',
self.version,
int(self.packet_type),
self.flags,
self.rsv,
self.payload_length
)
return header + self.payload | Pack the packet into bytes | pack | python | sajjadium/ctf-archives | ctfs/BITSCTF/2025/misc/The_Ghosting_Protocol/ghosting_protocol.py | https://github.com/sajjadium/ctf-archives/blob/master/ctfs/BITSCTF/2025/misc/The_Ghosting_Protocol/ghosting_protocol.py | MIT |
def unpack(cls, data):
"""Unpack bytes into a packet"""
if len(data) < 8:
raise ValueError("Packet too short (minimum 8 bytes)")
version, packet_type, flags, rsv, payload_length = struct.unpack('!BBB4sB', data[:8])
if len(data) < 8 + payload_length:
raise ValueError(f"Packet payload incomplete. Expected {payload_length} bytes")
payload = data[8:8+payload_length]
try:
packet_type = PacketType(packet_type)
except ValueError:
raise ValueError(f"Invalid packet type: {packet_type}")
return cls(version, packet_type, flags, rsv,payload_length, payload) | Unpack bytes into a packet | unpack | python | sajjadium/ctf-archives | ctfs/BITSCTF/2025/misc/The_Ghosting_Protocol/ghosting_protocol.py | https://github.com/sajjadium/ctf-archives/blob/master/ctfs/BITSCTF/2025/misc/The_Ghosting_Protocol/ghosting_protocol.py | MIT |
def __str__(self):
"""String representation for debugging"""
flags_str = []
if self.flags & Flags.DEV: flags_str.append("DEV")
if self.flags & Flags.SYN: flags_str.append("SYN")
if self.flags & Flags.ACK: flags_str.append("ACK")
if self.flags & Flags.ERROR: flags_str.append("ERROR")
if self.flags & Flags.FIN: flags_str.append("FIN")
return (f"GhostingPacket(version={self.version}, "
f"type={self.packet_type.name}, "
f"flags=[{' | '.join(flags_str)}], "
f"rsv={self.rsv}, "
f"payload_length={self.payload_length}, "
f"payload={self.payload})") | String representation for debugging | __str__ | python | sajjadium/ctf-archives | ctfs/BITSCTF/2025/misc/The_Ghosting_Protocol/ghosting_protocol.py | https://github.com/sajjadium/ctf-archives/blob/master/ctfs/BITSCTF/2025/misc/The_Ghosting_Protocol/ghosting_protocol.py | MIT |
def add():
username = request.form["username"]
password = request.form["password"]
sql = f"INSERT INTO `user`(password, username) VALUES ('{password}', '{username}')"
try:
db.execute_sql(sql)
except Exception as e:
return f"Err: {sql} <br>" + str(e)
return "Your password is leaked :)<br>" + \
"""<blockquote class="imgur-embed-pub" lang="en" data-id="WY6z44D" ><a href="//imgur.com/WY6z44D">Please
take care of your privacy</a></blockquote><script async src="//s.imgur.com/min/embed.js"
charset="utf-8"></script> """ | <blockquote class="imgur-embed-pub" lang="en" data-id="WY6z44D" ><a href="//imgur.com/WY6z44D">Please
take care of your privacy</a></blockquote><script async src="//s.imgur.com/min/embed.js"
charset="utf-8"></script> | add | python | sajjadium/ctf-archives | ctfs/WeCTF/2021/Phish/main.py | https://github.com/sajjadium/ctf-archives/blob/master/ctfs/WeCTF/2021/Phish/main.py | MIT |
def new_challenge():
"""Create new questions for a passage"""
p = '\n'.join([lorem.paragraph() for _ in range(random.randint(5, 15))])
qs, ans, res = [], [], []
for _ in range(10):
q = lorem.sentence().replace(".", "?")
op = [lorem.sentence() for _ in range(4)]
qs.append({'question': q, 'options': op})
ans.append(random.randrange(0, 4))
res.append(False)
return {'passage': p, 'questions': qs, 'answers': ans, 'results': res} | Create new questions for a passage | new_challenge | python | sajjadium/ctf-archives | ctfs/CakeCTF/2023/web/TOWFL/service/app.py | https://github.com/sajjadium/ctf-archives/blob/master/ctfs/CakeCTF/2023/web/TOWFL/service/app.py | MIT |
def db():
"""Get connection to DB"""
if getattr(flask.g, '_redis', None) is None:
flask.g._redis = redis.Redis(host=REDIS_HOST, port=REDIS_PORT, db=0)
return flask.g._redis | Get connection to DB | db | python | sajjadium/ctf-archives | ctfs/CakeCTF/2023/web/TOWFL/service/app.py | https://github.com/sajjadium/ctf-archives/blob/master/ctfs/CakeCTF/2023/web/TOWFL/service/app.py | MIT |
def login_ok():
"""Check if the current user is logged in"""
return 'user' in flask.session | Check if the current user is logged in | login_ok | python | sajjadium/ctf-archives | ctfs/CakeCTF/2022/web/openbio/service/app.py | https://github.com/sajjadium/ctf-archives/blob/master/ctfs/CakeCTF/2022/web/openbio/service/app.py | MIT |
def conn_user():
"""Create a connection to user database"""
return redis.Redis(host=REDIS_HOST, port=REDIS_PORT, db=0) | Create a connection to user database | conn_user | python | sajjadium/ctf-archives | ctfs/CakeCTF/2022/web/openbio/service/app.py | https://github.com/sajjadium/ctf-archives/blob/master/ctfs/CakeCTF/2022/web/openbio/service/app.py | MIT |
def conn_report():
"""Create a connection to report database"""
return redis.Redis(host=REDIS_HOST, port=REDIS_PORT, db=1) | Create a connection to report database | conn_report | python | sajjadium/ctf-archives | ctfs/CakeCTF/2022/web/openbio/service/app.py | https://github.com/sajjadium/ctf-archives/blob/master/ctfs/CakeCTF/2022/web/openbio/service/app.py | MIT |
def success(message):
"""Return a success message"""
return flask.jsonify({'status': 'success', 'message': message}) | Return a success message | success | python | sajjadium/ctf-archives | ctfs/CakeCTF/2022/web/openbio/service/app.py | https://github.com/sajjadium/ctf-archives/blob/master/ctfs/CakeCTF/2022/web/openbio/service/app.py | MIT |
def error(message):
"""Return an error message"""
return flask.jsonify({'status': 'error', 'message': message}) | Return an error message | error | python | sajjadium/ctf-archives | ctfs/CakeCTF/2022/web/openbio/service/app.py | https://github.com/sajjadium/ctf-archives/blob/master/ctfs/CakeCTF/2022/web/openbio/service/app.py | MIT |
def passhash(password):
"""Get a safe hash value of password"""
return hashlib.sha256(SALT + password.encode()).hexdigest() | Get a safe hash value of password | passhash | python | sajjadium/ctf-archives | ctfs/CakeCTF/2022/web/openbio/service/app.py | https://github.com/sajjadium/ctf-archives/blob/master/ctfs/CakeCTF/2022/web/openbio/service/app.py | MIT |
def user_register():
"""Register a new user"""
# Check username and password
username = flask.request.form.get('username', '')
password = flask.request.form.get('password', '')
if re.match("^[-a-zA-Z0-9_]{5,20}$", username) is None:
return error("Username must follow regex '^[-a-zA-Z0-9_]{5,20}$'")
if re.match("^.{8,128}$", password) is None:
return error("Password must follow regex '^.{8,128}$'")
# Register a new user
conn = conn_user()
if conn.exists(username):
return error("This username has been already taken.")
else:
conn.hset(username, mapping={
'password': passhash(password),
'bio': "<p>Hello! I'm new to this website.</p>"
})
flask.session['user'] = username
return success("Successfully registered a new user.") | Register a new user | user_register | python | sajjadium/ctf-archives | ctfs/CakeCTF/2022/web/openbio/service/app.py | https://github.com/sajjadium/ctf-archives/blob/master/ctfs/CakeCTF/2022/web/openbio/service/app.py | MIT |
def user_login():
"""Login user"""
if login_ok():
return success("You have already been logged in.")
username = flask.request.form.get('username', '')
password = flask.request.form.get('password', '')
# Check password
conn = conn_user()
if conn.hget(username, 'password').decode() == passhash(password):
flask.session['user'] = username
return success("Successfully logged in.")
else:
return error("Invalid password or user does not exist.") | Login user | user_login | python | sajjadium/ctf-archives | ctfs/CakeCTF/2022/web/openbio/service/app.py | https://github.com/sajjadium/ctf-archives/blob/master/ctfs/CakeCTF/2022/web/openbio/service/app.py | MIT |
def user_logout():
"""Logout user"""
if login_ok():
flask.session.clear()
return success("Successfully logged out.")
else:
return error("You are not logged in.") | Logout user | user_logout | python | sajjadium/ctf-archives | ctfs/CakeCTF/2022/web/openbio/service/app.py | https://github.com/sajjadium/ctf-archives/blob/master/ctfs/CakeCTF/2022/web/openbio/service/app.py | MIT |
def user_update():
"""Update user info"""
if not login_ok():
return error("You are not logged in.")
username = flask.session['user']
bio = flask.request.form.get('bio', '')
if len(bio) > 2000:
return error("Bio is too long.")
# Update bio
conn = conn_user()
conn.hset(username, 'bio', bio)
return success("Successfully updated your profile.") | Update user info | user_update | python | sajjadium/ctf-archives | ctfs/CakeCTF/2022/web/openbio/service/app.py | https://github.com/sajjadium/ctf-archives/blob/master/ctfs/CakeCTF/2022/web/openbio/service/app.py | MIT |
def report():
"""Report spam
Support staff will check the reported contents as soon as possible.
"""
if RECAPTCHA_KEY:
recaptcha = flask.request.form.get('recaptcha', '')
params = {
'secret': RECAPTCHA_KEY,
'response': recaptcha
}
r = requests.get(
"https://www.google.com/recaptcha/api/siteverify", params=params
)
if json.loads(r.text)['success'] == False:
abort(400)
username = flask.request.form.get('username', '')
conn = conn_user()
if not conn.exists(username):
return error("This user does not exist.")
conn = conn_report()
conn.rpush('report', username)
return success("""Thank you for your report.<br>Our support team will check the post as soon as possible.""") | Report spam
Support staff will check the reported contents as soon as possible. | report | python | sajjadium/ctf-archives | ctfs/CakeCTF/2022/web/openbio/service/app.py | https://github.com/sajjadium/ctf-archives/blob/master/ctfs/CakeCTF/2022/web/openbio/service/app.py | MIT |
def explore():
obj = object
expr = "object"
finished = False
while not finished:
print(
"""0- exit
1- explore dir
2- check subclasses
3- show current object
4- clear
5- Done
"""
)
choice = input("--> ")
match choice:
case "0":
exit()
case "1":
obj, expr = customDir(obj, expr)
case "2":
obj, expr = subclasses(obj, expr)
case "3":
print(obj)
case "4":
obj = object
expr = "object"
case "5":
finished = True
return expr | 0- exit
1- explore dir
2- check subclasses
3- show current object
4- clear
5- Done | explore | python | sajjadium/ctf-archives | ctfs/GDGAlgiers/2022/jail/PY_explorer/chall.py | https://github.com/sajjadium/ctf-archives/blob/master/ctfs/GDGAlgiers/2022/jail/PY_explorer/chall.py | MIT |
def get_answer_info(word_id=None):
con, cur = get_sql()
if word_id:
word = cur.execute(
"""SELECT word FROM answerList WHERE id = (?)""", (word_id,)
).fetchone()[0]
else:
word_id, word = cur.execute(
"""SELECT id, word FROM answerList ORDER BY RANDOM() LIMIT 1"""
).fetchone()
return word_id, word | SELECT word FROM answerList WHERE id = (?)""", (word_id,)
).fetchone()[0]
else:
word_id, word = cur.execute(
"""SELECT id, word FROM answerList ORDER BY RANDOM() LIMIT 1 | get_answer_info | python | sajjadium/ctf-archives | ctfs/BYUCTF/2022/web/Wordle/utils.py | https://github.com/sajjadium/ctf-archives/blob/master/ctfs/BYUCTF/2022/web/Wordle/utils.py | MIT |
def start_game():
"""
Starts a new game
"""
word_id = None
con, cur = get_sql()
key = str(uuid.uuid4())
word_id, word = get_answer_info(word_id)
cur.execute("""INSERT INTO game (word, key) VALUES (?, ?)""", (word, key))
con.commit()
con.close()
return api_response({"id": cur.lastrowid, "key": key, "wordID": word_id}) | Starts a new game | start_game | python | sajjadium/ctf-archives | ctfs/BYUCTF/2022/web/Wordle/app.py | https://github.com/sajjadium/ctf-archives/blob/master/ctfs/BYUCTF/2022/web/Wordle/app.py | MIT |
def sign_file(path):
"""
path: a file path to be signed
returns signature - merkel_root1, merkel_root2, merkel_root3, merkel_branches1, merkel_branches2, merkel_branches3, low_degree_stark_proof
"""
with open(path, "rb") as f:
data = f.read()
data_blake_hash = blake(data)
file_hash = rescue([x for x in data_blake_hash])
proof = rescue_sign([ord(x) for x in PASSWORD], PASSWORD_HASH, file_hash)
proof_yaml = yaml.dump(proof, Dumper=yaml.SafeDumper)
return proof_yaml | path: a file path to be signed
returns signature - merkel_root1, merkel_root2, merkel_root3, merkel_branches1, merkel_branches2, merkel_branches3, low_degree_stark_proof | sign_file | python | sajjadium/ctf-archives | ctfs/Intent/2021/crypto/SANSA/sign_file.py | https://github.com/sajjadium/ctf-archives/blob/master/ctfs/Intent/2021/crypto/SANSA/sign_file.py | MIT |
def pow_mod(vector: np.ndarray, exponent: int, p: int) -> np.ndarray:
"""
Returns a numpy array which, in index i, will be equal to (vector[i] ** exponent % p), where
'**' is the power operator.
"""
return np.vectorize(lambda x: pow(x, exponent, p))(vector) | Returns a numpy array which, in index i, will be equal to (vector[i] ** exponent % p), where
'**' is the power operator. | pow_mod | python | sajjadium/ctf-archives | ctfs/Intent/2021/crypto/SANSA/STARK/rescue/rescue_hash.py | https://github.com/sajjadium/ctf-archives/blob/master/ctfs/Intent/2021/crypto/SANSA/STARK/rescue/rescue_hash.py | MIT |
def rescue_hash(
inputs, mds_matrix=MDS_MATRIX, round_constants=ROUND_CONSTANTS,
word_size=WORD_SIZE, p=PRIME, num_rounds=NUM_ROUNDS):
"""
Returns the result of the Rescue hash on the given input.
The state size is word_size * 3.
inputs is a list/np.array of size (word_size * 2)
round_constants consists of (2 * num_rounds + 1) vectors, each of the same size as state size.
mds_matrix is an MDS (Maximum Distance Separable) matrix of size (state size)x(state size).
"""
mds_matrix = np.array(mds_matrix, dtype=object) % p
round_constants = np.array(round_constants, dtype=object)[:, :, np.newaxis] % p
inputs = np.array(inputs, dtype=object).reshape(2 * word_size, 1) % p
zeros = np.zeros((word_size, 1), dtype=object)
state = np.concatenate((inputs, zeros))
#print("state:", [x[0] for x in state])
state = (state + round_constants[0]) % p
for i in range(1, 2 * num_rounds, 2):
# First half of round i/2.
#print("before first half", [x[0] for x in state])
state = pow_mod(state, (2 * p - 1) // 3, p)
state = mds_matrix.dot(state) % p
state = (state + round_constants[i]) % p
# Second half of round i/2.
#print("before second half", [x[0] for x in state])
state = pow_mod(state, 3, p)
state = mds_matrix.dot(state) % p
state = (state + round_constants[i + 1]) % p
return (state[:word_size].flatten() % p).tolist() | Returns the result of the Rescue hash on the given input.
The state size is word_size * 3.
inputs is a list/np.array of size (word_size * 2)
round_constants consists of (2 * num_rounds + 1) vectors, each of the same size as state size.
mds_matrix is an MDS (Maximum Distance Separable) matrix of size (state size)x(state size). | rescue_hash | python | sajjadium/ctf-archives | ctfs/Intent/2021/crypto/SANSA/STARK/rescue/rescue_hash.py | https://github.com/sajjadium/ctf-archives/blob/master/ctfs/Intent/2021/crypto/SANSA/STARK/rescue/rescue_hash.py | MIT |
def point_add(P: Point, Q: Point, D: Point) -> Point:
"""
Algorithm 1 (xADD)
"""
V0 = (P.x + P.z) % p
V1 = (Q.x - Q.z) % p
V1 = (V1 * V0) % p
V0 = (P.x - P.z) % p
V2 = (Q.x + Q.z) % p
V2 = (V2 * V0) % p
V3 = (V1 + V2) % p
V3 = (V3 * V3) % p
V4 = (V1 - V2) % p
V4 = (V4 * V4) % p
x = (D.z * V3) % p
z = (D.x * V4) % p
return Point(x, z) | Algorithm 1 (xADD) | point_add | python | sajjadium/ctf-archives | ctfs/BuckeyeCTF/2021/crypto/Elliptigo/chall.py | https://github.com/sajjadium/ctf-archives/blob/master/ctfs/BuckeyeCTF/2021/crypto/Elliptigo/chall.py | MIT |
def point_double(P: Point) -> Point:
"""
Algorithm 2 (xDBL)
"""
V1 = (P.x + P.z) % p
V1 = (V1 * V1) % p
V2 = (P.x - P.z) % p
V2 = (V2 * V2) % p
x = (V1 * V2) % p
V1 = (V1 - V2) % p
V3 = (((C.a + 2) // 4) * V1) % p
V3 = (V3 + V2) % p
z = (V1 * V3) % p
return Point(x, z) | Algorithm 2 (xDBL) | point_double | python | sajjadium/ctf-archives | ctfs/BuckeyeCTF/2021/crypto/Elliptigo/chall.py | https://github.com/sajjadium/ctf-archives/blob/master/ctfs/BuckeyeCTF/2021/crypto/Elliptigo/chall.py | MIT |
def scalar_multiplication(P: Point, k: int) -> Point:
"""
Algorithm 4 (LADDER)
"""
if k == 0:
return Point(0, 0)
R0, R1 = P, point_double(P)
for i in range(size(k) - 2, -1, -1):
if k & (1 << i) == 0:
R0, R1 = point_double(R0), point_add(R0, R1, P)
else:
R0, R1 = point_add(R0, R1, P), point_double(R1)
return R0 | Algorithm 4 (LADDER) | scalar_multiplication | python | sajjadium/ctf-archives | ctfs/BuckeyeCTF/2021/crypto/Elliptigo/chall.py | https://github.com/sajjadium/ctf-archives/blob/master/ctfs/BuckeyeCTF/2021/crypto/Elliptigo/chall.py | MIT |
def encode(s):
"""Base64 encode the string using our custom alphabet"""
return base64.b64encode(s.encode()).decode().replace('=', '').translate(translation_table) | Base64 encode the string using our custom alphabet | encode | python | sajjadium/ctf-archives | ctfs/BuckeyeCTF/2024/misc/fixpoint/fixpoint.py | https://github.com/sajjadium/ctf-archives/blob/master/ctfs/BuckeyeCTF/2024/misc/fixpoint/fixpoint.py | MIT |
def verify(secret, id, hash):
'''new_id = ""
for i in range(max(len(secret), len(id))):
new_id += chr(ord(secret[i % len(secret)]) ^ ord(id[i % len(id)]))'''
id_arr = [i for i in id]
for i in range(16):
id_arr[i] = ord(secret[i]) ^ id[i]
id = bytes(id_arr)
print(id)
new_hash = sha248(id)
print(new_hash)
print(hash)
if new_hash in hash:
return True
return False | new_id = ""
for i in range(max(len(secret), len(id))):
new_id += chr(ord(secret[i % len(secret)]) ^ ord(id[i % len(id)])) | verify | python | sajjadium/ctf-archives | ctfs/LIT/2023/crypto/leaderboard-service/flask_app.py | https://github.com/sajjadium/ctf-archives/blob/master/ctfs/LIT/2023/crypto/leaderboard-service/flask_app.py | MIT |
def inv_val(self, val):
"""
Get the inverse of a given field element using the curves prime field.
"""
return pow(val, self.mod - 2, self.mod) | Get the inverse of a given field element using the curves prime field. | inv_val | python | sajjadium/ctf-archives | ctfs/CyberSecurityRumble/2023/Quals/crypto/TrustedCode/curves/EllipticCurve.py | https://github.com/sajjadium/ctf-archives/blob/master/ctfs/CyberSecurityRumble/2023/Quals/crypto/TrustedCode/curves/EllipticCurve.py | MIT |
def sqrt(self, a):
"""
Take the square root in the field using Tonelli–Shanks algorithm.
Based on https://gist.github.com/nakov/60d62bdf4067ea72b7832ce9f71ae079
:return: sqrt(a) if it exists, 0 otherwise
"""
p = self.mod
if self.legendre_symbol(a) != 1:
return 0
elif a == 0:
return 0
elif p == 2:
return p
elif p % 4 == 3:
# lagrange method
return pow(a, (p + 1) // 4, p)
# Partition p-1 to s * 2^e for an odd s (i.e.
# reduce all the powers of 2 from p-1)
s = p - 1
e = 0
while s % 2 == 0:
s //= 2
e += 1
# Find some 'n' with a legendre symbol n|p = -1.
# Shouldn't take long.
n = 2
while self.legendre_symbol(n) != -1:
n += 1
# Here be dragons!
# Read the paper "Square roots from 1; 24, 51,
# 10 to Dan Shanks" by Ezra Brown for more
# information
#
# x is a guess of the square root that gets better
# with each iteration.
# b is the "fudge factor" - by how much we're off
# with the guess. The invariant x^2 = ab (mod p)
# is maintained throughout the loop.
# g is used for successive powers of n to update
# both a and b
# r is the exponent - decreases with each update
#
x = pow(a, (s + 1) // 2, p)
b = pow(a, s, p)
g = pow(n, s, p)
r = e
while True:
t = b
m = 0
for m in range(r):
if t == 1:
break
t = pow(t, 2, p)
if m == 0:
return x
gs = pow(g, 2 ** (r - m - 1), p)
g = (gs * gs) % p
x = (x * gs) % p
b = (b * g) % p
r = m | Take the square root in the field using Tonelli–Shanks algorithm.
Based on https://gist.github.com/nakov/60d62bdf4067ea72b7832ce9f71ae079
:return: sqrt(a) if it exists, 0 otherwise | sqrt | python | sajjadium/ctf-archives | ctfs/CyberSecurityRumble/2023/Quals/crypto/TrustedCode/curves/EllipticCurve.py | https://github.com/sajjadium/ctf-archives/blob/master/ctfs/CyberSecurityRumble/2023/Quals/crypto/TrustedCode/curves/EllipticCurve.py | MIT |
def invert(self, point):
"""
Invert a point.
"""
return AffinePoint(self, point.x, (-1 * point.y) % self.mod) | Invert a point. | invert | python | sajjadium/ctf-archives | ctfs/CyberSecurityRumble/2023/Quals/crypto/TrustedCode/curves/EllipticCurve.py | https://github.com/sajjadium/ctf-archives/blob/master/ctfs/CyberSecurityRumble/2023/Quals/crypto/TrustedCode/curves/EllipticCurve.py | MIT |
def mul(self, point, scalar):
"""
Do scalar multiplication Q = dP using double and add.
"""
return self.double_and_add(point, scalar) | Do scalar multiplication Q = dP using double and add. | mul | python | sajjadium/ctf-archives | ctfs/CyberSecurityRumble/2023/Quals/crypto/TrustedCode/curves/EllipticCurve.py | https://github.com/sajjadium/ctf-archives/blob/master/ctfs/CyberSecurityRumble/2023/Quals/crypto/TrustedCode/curves/EllipticCurve.py | MIT |
def double_and_add(self, point, scalar):
"""
Do scalar multiplication Q = dP using double and add.
As here: https://en.wikipedia.org/wiki/Elliptic_curve_point_multiplication#Double-and-add
"""
if scalar < 1:
raise ValueError("Scalar must be >= 1")
result = None
tmp = point.copy()
while scalar:
if scalar & 1:
if result is None:
result = tmp
else:
result = self.add(result, tmp)
scalar >>= 1
tmp = self.add(tmp, tmp)
return result | Do scalar multiplication Q = dP using double and add.
As here: https://en.wikipedia.org/wiki/Elliptic_curve_point_multiplication#Double-and-add | double_and_add | python | sajjadium/ctf-archives | ctfs/CyberSecurityRumble/2023/Quals/crypto/TrustedCode/curves/EllipticCurve.py | https://github.com/sajjadium/ctf-archives/blob/master/ctfs/CyberSecurityRumble/2023/Quals/crypto/TrustedCode/curves/EllipticCurve.py | MIT |
def plot(self, dotsize=3, fontsize=5, lines=None):
"""
Plot the curve as scatter plot.
This obviously only works for tiny fields.
:param lines: A list of lines you want to draw additionally to the points.
Every line is a dict with keys: from, to, color(optional), width(optional)
:return: pyplot object
"""
if plt is None:
raise ValueError("matplotlib not available.")
x = []
y = []
for P in self.enumerate_points():
x.append(P.x)
y.append(P.y)
plt.rcParams.update({'font.size': fontsize})
plt.scatter(x, y, s=dotsize, marker="o")
if lines is not None:
for line in lines:
plt.plot(
(line['from'][0], line['to'][0]),
(line['from'][1], line['to'][1]), '-', marker='.',
color=line.get('color', 'blue'), linewidth=line.get('width', 1)
)
plt.grid()
plt.title("{}".format(self))
return plt | Plot the curve as scatter plot.
This obviously only works for tiny fields.
:param lines: A list of lines you want to draw additionally to the points.
Every line is a dict with keys: from, to, color(optional), width(optional)
:return: pyplot object | plot | python | sajjadium/ctf-archives | ctfs/CyberSecurityRumble/2023/Quals/crypto/TrustedCode/curves/EllipticCurve.py | https://github.com/sajjadium/ctf-archives/blob/master/ctfs/CyberSecurityRumble/2023/Quals/crypto/TrustedCode/curves/EllipticCurve.py | MIT |
def enumerate_points(self):
"""
Yields points of the curve.
This only works well on tiny curves.
"""
for i in range(self.mod):
sq = self.calc_y_sq(i)
y = self.sqrt(sq)
if y:
yield AffinePoint(self, i, y)
yield AffinePoint(self, i, self.mod - y) | Yields points of the curve.
This only works well on tiny curves. | enumerate_points | python | sajjadium/ctf-archives | ctfs/CyberSecurityRumble/2023/Quals/crypto/TrustedCode/curves/WeierstrassCurve.py | https://github.com/sajjadium/ctf-archives/blob/master/ctfs/CyberSecurityRumble/2023/Quals/crypto/TrustedCode/curves/WeierstrassCurve.py | MIT |
def add(self, P, Q):
"""
Sum of the points P and Q.
Rules: https://en.wikipedia.org/wiki/Elliptic_curve_point_multiplication
"""
if not (self.is_on_curve(P) and self.is_on_curve(Q)):
raise ValueError(
"Points not on basic_curves {}: {}, {}: {}".format(P, self.is_on_curve(P), Q, self.is_on_curve(Q)))
# Cases with POIF
if P == self.poif:
result = Q
elif Q == self.poif:
result = P
elif Q == self.invert(P):
result = self.poif
else: # without POIF
if P == Q:
slope = (3 * P.x ** 2 + self.a) * self.inv_val(2 * P.y)
else:
slope = (Q.y - P.y) * self.inv_val(Q.x - P.x)
x = (slope ** 2 - P.x - Q.x) % self.mod
y = (slope * (P.x - x) - P.y) % self.mod
result = AffinePoint(self, x, y)
return result | Sum of the points P and Q.
Rules: https://en.wikipedia.org/wiki/Elliptic_curve_point_multiplication | add | python | sajjadium/ctf-archives | ctfs/CyberSecurityRumble/2023/Quals/crypto/TrustedCode/curves/WeierstrassCurve.py | https://github.com/sajjadium/ctf-archives/blob/master/ctfs/CyberSecurityRumble/2023/Quals/crypto/TrustedCode/curves/WeierstrassCurve.py | MIT |
def __py_new(name, data=b'', **kwargs):
"""new(name, data=b'', **kwargs) - Return a new hashing object using the
named algorithm; optionally initialized with data (which must be
a bytes-like object).
"""
return __get_builtin_constructor(name)(data, **kwargs) | new(name, data=b'', **kwargs) - Return a new hashing object using the
named algorithm; optionally initialized with data (which must be
a bytes-like object). | __py_new | python | sajjadium/ctf-archives | ctfs/X-MAS/2021/rev/Snake_ransomware/hаshlib.py | https://github.com/sajjadium/ctf-archives/blob/master/ctfs/X-MAS/2021/rev/Snake_ransomware/hаshlib.py | MIT |
def __hash_new(name, data=b'', **kwargs):
"""new(name, data=b'') - Return a new hashing object using the named algorithm;
optionally initialized with data (which must be a bytes-like object).
"""
if name in __block_openssl_constructor:
# Prefer our builtin blake2 implementation.
return __get_builtin_constructor(name)(data, **kwargs)
try:
return _hashlib.new(name, data, **kwargs)
except ValueError:
# If the _hashlib module (OpenSSL) doesn't support the named
# hash, try using our builtin implementations.
# This allows for SHA224/256 and SHA384/512 support even though
# the OpenSSL library prior to 0.9.8 doesn't provide them.
return __get_builtin_constructor(name)(data) | new(name, data=b'') - Return a new hashing object using the named algorithm;
optionally initialized with data (which must be a bytes-like object). | __hash_new | python | sajjadium/ctf-archives | ctfs/X-MAS/2021/rev/Snake_ransomware/hаshlib.py | https://github.com/sajjadium/ctf-archives/blob/master/ctfs/X-MAS/2021/rev/Snake_ransomware/hаshlib.py | MIT |
def pbkdf2_hmac(hash_name, password, salt, iterations, dklen=None):
"""Password based key derivation function 2 (PKCS #5 v2.0)
This Python implementations based on the hmac module about as fast
as OpenSSL's PKCS5_PBKDF2_HMAC for short passwords and much faster
for long passwords.
"""
if not isinstance(hash_name, str):
raise TypeError(hash_name)
if not isinstance(password, (bytes, bytearray)):
password = bytes(memoryview(password))
if not isinstance(salt, (bytes, bytearray)):
salt = bytes(memoryview(salt))
# Fast inline HMAC implementation
inner = new(hash_name)
outer = new(hash_name)
blocksize = getattr(inner, 'block_size', 64)
if len(password) > blocksize:
password = new(hash_name, password).digest()
password = password + b'\x00' * (blocksize - len(password))
inner.update(password.translate(_trans_36))
outer.update(password.translate(_trans_5C))
def prf(msg, inner=inner, outer=outer):
# PBKDF2_HMAC uses the password as key. We can re-use the same
# digest objects and just update copies to skip initialization.
icpy = inner.copy()
ocpy = outer.copy()
icpy.update(msg)
ocpy.update(icpy.digest())
return ocpy.digest()
if iterations < 1:
raise ValueError(iterations)
if dklen is None:
dklen = outer.digest_size
if dklen < 1:
raise ValueError(dklen)
dkey = b''
loop = 1
from_bytes = int.from_bytes
while len(dkey) < dklen:
prev = prf(salt + loop.to_bytes(4, 'big'))
# endianness doesn't matter here as long to / from use the same
rkey = int.from_bytes(prev, 'big')
for i in range(iterations - 1):
prev = prf(prev)
# rkey = rkey ^ prev
rkey ^= from_bytes(prev, 'big')
loop += 1
dkey += rkey.to_bytes(inner.digest_size, 'big')
return dkey[:dklen] | Password based key derivation function 2 (PKCS #5 v2.0)
This Python implementations based on the hmac module about as fast
as OpenSSL's PKCS5_PBKDF2_HMAC for short passwords and much faster
for long passwords. | pbkdf2_hmac | python | sajjadium/ctf-archives | ctfs/X-MAS/2021/rev/Snake_ransomware/hаshlib.py | https://github.com/sajjadium/ctf-archives/blob/master/ctfs/X-MAS/2021/rev/Snake_ransomware/hаshlib.py | MIT |
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 | 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 | optimize_pushes_pops | python | sajjadium/ctf-archives | ctfs/SECCON/2021/rev/pyast64/pyast64.py | https://github.com/sajjadium/ctf-archives/blob/master/ctfs/SECCON/2021/rev/pyast64/pyast64.py | MIT |
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') | 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. | builtin_array | python | sajjadium/ctf-archives | ctfs/SECCON/2021/rev/pyast64/pyast64.py | https://github.com/sajjadium/ctf-archives/blob/master/ctfs/SECCON/2021/rev/pyast64/pyast64.py | MIT |
def get(self, request: Request, format=None):
"""
Just return all articles
"""
articles = Article.objects.all()
serializer = ArticleSerializer(articles, many=True)
return Response(serializer.data) | Just return all articles | get | python | sajjadium/ctf-archives | ctfs/DownUnderCTF/2023/web/secure_blog/djangoapp/app/views/article.py | https://github.com/sajjadium/ctf-archives/blob/master/ctfs/DownUnderCTF/2023/web/secure_blog/djangoapp/app/views/article.py | MIT |
def post(self, request: Request, format=None):
"""
Query articles
"""
articles = Article.objects.filter(**request.data)
serializer = ArticleSerializer(articles, many=True)
return Response(serializer.data) | Query articles | post | python | sajjadium/ctf-archives | ctfs/DownUnderCTF/2023/web/secure_blog/djangoapp/app/views/article.py | https://github.com/sajjadium/ctf-archives/blob/master/ctfs/DownUnderCTF/2023/web/secure_blog/djangoapp/app/views/article.py | MIT |
def e_add(pub, a, b):
"""Add one encrypted integer to another"""
return a * b % pub.n_sq | Add one encrypted integer to another | e_add | python | sajjadium/ctf-archives | ctfs/DownUnderCTF/2024/crypto/super_party_computation/server.py | https://github.com/sajjadium/ctf-archives/blob/master/ctfs/DownUnderCTF/2024/crypto/super_party_computation/server.py | MIT |
def e_add_const(pub, a, n):
"""Add constant n to an encrypted integer"""
return a * pow(pub.g, n, pub.n_sq) % pub.n_sq | Add constant n to an encrypted integer | e_add_const | python | sajjadium/ctf-archives | ctfs/DownUnderCTF/2024/crypto/super_party_computation/server.py | https://github.com/sajjadium/ctf-archives/blob/master/ctfs/DownUnderCTF/2024/crypto/super_party_computation/server.py | MIT |
def e_mul_const(pub, a, n):
"""Multiplies an ancrypted integer by a constant"""
return pow(a, n, pub.n_sq) | Multiplies an ancrypted integer by a constant | e_mul_const | python | sajjadium/ctf-archives | ctfs/DownUnderCTF/2024/crypto/super_party_computation/server.py | https://github.com/sajjadium/ctf-archives/blob/master/ctfs/DownUnderCTF/2024/crypto/super_party_computation/server.py | MIT |
def page_not_found(error):
"""Custom 404 page."""
return render_template('404.html'), 404 | Custom 404 page. | page_not_found | python | sajjadium/ctf-archives | ctfs/LA/2023/web/85_reasons_why/app/views.py | https://github.com/sajjadium/ctf-archives/blob/master/ctfs/LA/2023/web/85_reasons_why/app/views.py | MIT |
def r_value(x, y, μ, int_size_bits=1024):
"""Generates the Fiat-Shamir verifier challenges Hash(xi,yi,μi)"""
int_size = int_size_bits // 8
s = (x.to_bytes(int_size, "big", signed=False) +
y.to_bytes(int_size, "big", signed=False) +
μ.to_bytes(int_size, "big", signed=False))
b = hashlib.sha256(s).digest()
return int.from_bytes(b[:16], "big") | Generates the Fiat-Shamir verifier challenges Hash(xi,yi,μi) | r_value | python | sajjadium/ctf-archives | ctfs/LA/2025/crypto/p_vs_np/VDF.py | https://github.com/sajjadium/ctf-archives/blob/master/ctfs/LA/2025/crypto/p_vs_np/VDF.py | MIT |
def generate_proof(xi, t, δ, yi, N, i, π=[]):
""" Generate the proof, list of μi values """
# Halving protocol from Pietrzak p16.
# μi = xi^(2^(T/2^i))
# ri = Hash((xi,T/2^(i−1),yi),μi)
# xi+1 = xi^ri . μi
# yi+1 = μi^ri . yi
t = t//2 # or t = int(τ / pow(2, i))
μi = pow(xi, pow(2, t), N)
ri = r_value(xi, yi, μi) % N
xi = (pow(xi, ri, N) * μi) % N
yi = (pow(μi, ri, N) * yi) % N
π.append(μi)
print("Values: T:{}, x{}:{}, y{}:{}, u{}:{}, r{}: {}".format(t, i, xi, i, yi, i, μi, i, ri))
# Verify we can build a proof for the leaf
if t == pow(2, δ):
xi_delta = pow(xi, pow(2, pow(2, δ)), N)
if xi_delta == yi:
print("Match Last (x{})^2^2^{} {} = y{}: {}".format(i, δ, xi_delta, i, yi))
return π
else:
print("Proof incomplete.")
return
return generate_proof(xi, t, δ, yi, N, i+1, π) | Generate the proof, list of μi values | generate_proof | python | sajjadium/ctf-archives | ctfs/LA/2025/crypto/p_vs_np/VDF.py | https://github.com/sajjadium/ctf-archives/blob/master/ctfs/LA/2025/crypto/p_vs_np/VDF.py | MIT |
def repeated_squarings(N, x, τ):
""" Repeatedly square x. """
return pow(x, pow(2, τ), N) | Repeatedly square x. | repeated_squarings | python | sajjadium/ctf-archives | ctfs/LA/2025/crypto/p_vs_np/VDF.py | https://github.com/sajjadium/ctf-archives/blob/master/ctfs/LA/2025/crypto/p_vs_np/VDF.py | MIT |
def verify_proof(xi, yi, π, τ, δ, N):
""" Verify proof """
# Verify algo from Pietrzak p16.
# ri := hash((xi,T/^2i−1,yi), μi)
# xi+1 := xi^ri . μi
# yi+1 := μi^ri . yi
while(len(π) != 0):
μi = π.pop()
ri = r_value(xi, yi, μi) % N
xi = (pow(xi, ri, N) * μi) % N
yi = (pow(μi, ri, N) * yi) % N
# yt+1 ?= (xt+1)^2
if yi == pow(xi,pow(2, pow(2, δ)),N):
return True
else:
return False | Verify proof | verify_proof | python | sajjadium/ctf-archives | ctfs/LA/2025/crypto/p_vs_np/VDF.py | https://github.com/sajjadium/ctf-archives/blob/master/ctfs/LA/2025/crypto/p_vs_np/VDF.py | MIT |
def db_init():
con = sqlite3.connect('database/data.db')
# Create users database
query(con, '''
CREATE TABLE IF NOT EXISTS users (
id integer PRIMARY KEY,
username text NOT NULL,
password text NOT NULL
);
''')
query(con, f'''
INSERT INTO users (
username,
password
) VALUES (
'admin',
'{os.environ.get("ADMIN_PASSWD")}'
);
''')
# Create posts database
query(con, '''
CREATE TABLE IF NOT EXISTS posts (
id integer PRIMARY KEY,
user_id integer NOT NULL,
title text,
content text NOT NULL,
hidden boolean NOT NULL,
FOREIGN KEY (user_id) REFERENCES users (id)
);
''')
query(con, f'''
INSERT INTO posts (
user_id,
title,
content,
hidden
) VALUES (
1,
'Here is a ducky flag!',
'{os.environ.get("FLAG")}',
1
);
''')
con.commit() | )
query(con, f | db_init | python | sajjadium/ctf-archives | ctfs/TFC/2023/web/DUCKY_NOTES_ENDGAME/src/database/database.py | https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TFC/2023/web/DUCKY_NOTES_ENDGAME/src/database/database.py | MIT |
def garble_label(key0, key1, key2):
"""
key0, key1 = two input labels
key2 = output label
"""
gl = encrypt(key2, key0, key1)
validation = encrypt(0, key0, key1)
return (gl, validation) | key0, key1 = two input labels
key2 = output label | garble_label | python | sajjadium/ctf-archives | ctfs/DiceCTF/2021/crypto/garbled/yao.py | https://github.com/sajjadium/ctf-archives/blob/master/ctfs/DiceCTF/2021/crypto/garbled/yao.py | MIT |
def evaluate_gate(garbled_table, key0, key1):
"""
Return the output label unlocked by the two input labels,
or raise a ValueError if no entry correctly decoded
"""
for g in garbled_table:
gl, v = g
label = decrypt(gl, key0, key1)
validation = decrypt(v, key0, key1)
if validation == 0:
return label
raise ValueError("None of the gates correctly decoded; invalid input labels") | Return the output label unlocked by the two input labels,
or raise a ValueError if no entry correctly decoded | evaluate_gate | python | sajjadium/ctf-archives | ctfs/DiceCTF/2021/crypto/garbled/yao.py | https://github.com/sajjadium/ctf-archives/blob/master/ctfs/DiceCTF/2021/crypto/garbled/yao.py | MIT |
def evaluate_circuit(circuit, g_tables, inputs):
"""
Evaluate yao circuit with given inputs.
Keyword arguments:
circuit -- dict containing circuit spec
g_tables -- garbled tables of yao circuit
inputs -- dict mapping wires to labels
Returns:
evaluation -- a dict mapping output wires to the result labels
"""
gates = circuit["gates"] # dict containing circuit gates
wire_outputs = circuit["outputs"] # list of output wires
wire_inputs = {} # dict containing Alice and Bob inputs
evaluation = {} # dict containing result of evaluation
wire_inputs.update(inputs)
# Iterate over all gates
for gate in sorted(gates, key=lambda g: g["id"]):
gate_id, gate_in = gate["id"], gate["in"]
key0 = wire_inputs[gate_in[0]]
key1 = wire_inputs[gate_in[1]]
garbled_table = g_tables[gate_id]
msg = evaluate_gate(garbled_table, key0, key1)
wire_inputs[gate_id] = msg
# After all gates have been evaluated, we populate the dict of results
for out in wire_outputs:
evaluation[out] = wire_inputs[out]
return evaluation | Evaluate yao circuit with given inputs.
Keyword arguments:
circuit -- dict containing circuit spec
g_tables -- garbled tables of yao circuit
inputs -- dict mapping wires to labels
Returns:
evaluation -- a dict mapping output wires to the result labels | evaluate_circuit | python | sajjadium/ctf-archives | ctfs/DiceCTF/2021/crypto/garbled/yao.py | https://github.com/sajjadium/ctf-archives/blob/master/ctfs/DiceCTF/2021/crypto/garbled/yao.py | MIT |
def _gen_garbled_AND_gate(self, labels0, labels1, labels2):
"""
labels0, labels1 = two input labels
labels2 = output label
"""
key0_0, key0_1 = labels0
key1_0, key1_1 = labels1
key2_0, key2_1 = labels2
G = []
G.append(garble_label(key0_0, key1_0, key2_0))
G.append(garble_label(key0_0, key1_1, key2_0))
G.append(garble_label(key0_1, key1_0, key2_0))
G.append(garble_label(key0_1, key1_1, key2_1))
# randomly shuffle the table so you don't know what the labels correspond to
shuffle(G)
return G | labels0, labels1 = two input labels
labels2 = output label | _gen_garbled_AND_gate | python | sajjadium/ctf-archives | ctfs/DiceCTF/2021/crypto/garbled/yao.py | https://github.com/sajjadium/ctf-archives/blob/master/ctfs/DiceCTF/2021/crypto/garbled/yao.py | MIT |
def get_garbled_table(self):
"""Return the garbled table of the gate."""
return self.garbled_table | Return the garbled table of the gate. | get_garbled_table | python | sajjadium/ctf-archives | ctfs/DiceCTF/2021/crypto/garbled/yao.py | https://github.com/sajjadium/ctf-archives/blob/master/ctfs/DiceCTF/2021/crypto/garbled/yao.py | MIT |
def _gen_keys(self):
"""Create pair of keys for each wire."""
for wire in self.wires:
self.keys[wire] = (
generate_random_label(),
generate_random_label()
) | Create pair of keys for each wire. | _gen_keys | python | sajjadium/ctf-archives | ctfs/DiceCTF/2021/crypto/garbled/yao.py | https://github.com/sajjadium/ctf-archives/blob/master/ctfs/DiceCTF/2021/crypto/garbled/yao.py | MIT |
def _gen_garbled_tables(self):
"""Create the garbled table of each gate."""
for gate in self.gates:
garbled_gate = GarbledGate(gate, self.keys)
self.garbled_tables[gate["id"]] = garbled_gate.get_garbled_table() | Create the garbled table of each gate. | _gen_garbled_tables | python | sajjadium/ctf-archives | ctfs/DiceCTF/2021/crypto/garbled/yao.py | https://github.com/sajjadium/ctf-archives/blob/master/ctfs/DiceCTF/2021/crypto/garbled/yao.py | MIT |
def get_garbled_tables(self):
"""Return dict mapping each gate to its garbled table."""
return self.garbled_tables | Return dict mapping each gate to its garbled table. | get_garbled_tables | python | sajjadium/ctf-archives | ctfs/DiceCTF/2021/crypto/garbled/yao.py | https://github.com/sajjadium/ctf-archives/blob/master/ctfs/DiceCTF/2021/crypto/garbled/yao.py | MIT |
def get_keys(self):
"""Return dict mapping each wire to its pair of keys."""
return self.keys | Return dict mapping each wire to its pair of keys. | get_keys | python | sajjadium/ctf-archives | ctfs/DiceCTF/2021/crypto/garbled/yao.py | https://github.com/sajjadium/ctf-archives/blob/master/ctfs/DiceCTF/2021/crypto/garbled/yao.py | MIT |
def dynamic_range_compression_torch(x, C=1, clip_val=1e-5):
"""
PARAMS
------
C: compression factor
"""
return torch.log(torch.clamp(x, min=clip_val) * C) | PARAMS
------
C: compression factor | dynamic_range_compression_torch | python | jaywalnut310/vits | mel_processing.py | https://github.com/jaywalnut310/vits/blob/master/mel_processing.py | MIT |
def dynamic_range_decompression_torch(x, C=1):
"""
PARAMS
------
C: compression factor used to compress
"""
return torch.exp(x) / C | PARAMS
------
C: compression factor used to compress | dynamic_range_decompression_torch | python | jaywalnut310/vits | mel_processing.py | https://github.com/jaywalnut310/vits/blob/master/mel_processing.py | MIT |
def main():
"""Assume Single Node Multi GPUs Training Only"""
assert torch.cuda.is_available(), "CPU training is not allowed."
n_gpus = torch.cuda.device_count()
os.environ['MASTER_ADDR'] = 'localhost'
os.environ['MASTER_PORT'] = '80000'
hps = utils.get_hparams()
mp.spawn(run, nprocs=n_gpus, args=(n_gpus, hps,)) | Assume Single Node Multi GPUs Training Only | main | python | jaywalnut310/vits | train_ms.py | https://github.com/jaywalnut310/vits/blob/master/train_ms.py | MIT |
def kl_loss(z_p, logs_q, m_p, logs_p, z_mask):
"""
z_p, logs_q: [b, h, t_t]
m_p, logs_p: [b, h, t_t]
"""
z_p = z_p.float()
logs_q = logs_q.float()
m_p = m_p.float()
logs_p = logs_p.float()
z_mask = z_mask.float()
kl = logs_p - logs_q - 0.5
kl += 0.5 * ((z_p - m_p)**2) * torch.exp(-2. * logs_p)
kl = torch.sum(kl * z_mask)
l = kl / torch.sum(z_mask)
return l | z_p, logs_q: [b, h, t_t]
m_p, logs_p: [b, h, t_t] | kl_loss | python | jaywalnut310/vits | losses.py | https://github.com/jaywalnut310/vits/blob/master/losses.py | MIT |
def _filter(self):
"""
Filter text & store spec lengths
"""
# Store spectrogram lengths for Bucketing
# wav_length ~= file_size / (wav_channels * Bytes per dim) = file_size / (1 * 2)
# spec_length = wav_length // hop_length
audiopaths_and_text_new = []
lengths = []
for audiopath, text in self.audiopaths_and_text:
if self.min_text_len <= len(text) and len(text) <= self.max_text_len:
audiopaths_and_text_new.append([audiopath, text])
lengths.append(os.path.getsize(audiopath) // (2 * self.hop_length))
self.audiopaths_and_text = audiopaths_and_text_new
self.lengths = lengths | Filter text & store spec lengths | _filter | python | jaywalnut310/vits | data_utils.py | https://github.com/jaywalnut310/vits/blob/master/data_utils.py | MIT |
def __call__(self, batch):
"""Collate's training batch from normalized text and aduio
PARAMS
------
batch: [text_normalized, spec_normalized, wav_normalized]
"""
# Right zero-pad all one-hot text sequences to max input length
_, ids_sorted_decreasing = torch.sort(
torch.LongTensor([x[1].size(1) for x in batch]),
dim=0, descending=True)
max_text_len = max([len(x[0]) for x in batch])
max_spec_len = max([x[1].size(1) for x in batch])
max_wav_len = max([x[2].size(1) for x in batch])
text_lengths = torch.LongTensor(len(batch))
spec_lengths = torch.LongTensor(len(batch))
wav_lengths = torch.LongTensor(len(batch))
text_padded = torch.LongTensor(len(batch), max_text_len)
spec_padded = torch.FloatTensor(len(batch), batch[0][1].size(0), max_spec_len)
wav_padded = torch.FloatTensor(len(batch), 1, max_wav_len)
text_padded.zero_()
spec_padded.zero_()
wav_padded.zero_()
for i in range(len(ids_sorted_decreasing)):
row = batch[ids_sorted_decreasing[i]]
text = row[0]
text_padded[i, :text.size(0)] = text
text_lengths[i] = text.size(0)
spec = row[1]
spec_padded[i, :, :spec.size(1)] = spec
spec_lengths[i] = spec.size(1)
wav = row[2]
wav_padded[i, :, :wav.size(1)] = wav
wav_lengths[i] = wav.size(1)
if self.return_ids:
return text_padded, text_lengths, spec_padded, spec_lengths, wav_padded, wav_lengths, ids_sorted_decreasing
return text_padded, text_lengths, spec_padded, spec_lengths, wav_padded, wav_lengths | Collate's training batch from normalized text and aduio
PARAMS
------
batch: [text_normalized, spec_normalized, wav_normalized] | __call__ | python | jaywalnut310/vits | data_utils.py | https://github.com/jaywalnut310/vits/blob/master/data_utils.py | MIT |
def __call__(self, batch):
"""Collate's training batch from normalized text, audio and speaker identities
PARAMS
------
batch: [text_normalized, spec_normalized, wav_normalized, sid]
"""
# Right zero-pad all one-hot text sequences to max input length
_, ids_sorted_decreasing = torch.sort(
torch.LongTensor([x[1].size(1) for x in batch]),
dim=0, descending=True)
max_text_len = max([len(x[0]) for x in batch])
max_spec_len = max([x[1].size(1) for x in batch])
max_wav_len = max([x[2].size(1) for x in batch])
text_lengths = torch.LongTensor(len(batch))
spec_lengths = torch.LongTensor(len(batch))
wav_lengths = torch.LongTensor(len(batch))
sid = torch.LongTensor(len(batch))
text_padded = torch.LongTensor(len(batch), max_text_len)
spec_padded = torch.FloatTensor(len(batch), batch[0][1].size(0), max_spec_len)
wav_padded = torch.FloatTensor(len(batch), 1, max_wav_len)
text_padded.zero_()
spec_padded.zero_()
wav_padded.zero_()
for i in range(len(ids_sorted_decreasing)):
row = batch[ids_sorted_decreasing[i]]
text = row[0]
text_padded[i, :text.size(0)] = text
text_lengths[i] = text.size(0)
spec = row[1]
spec_padded[i, :, :spec.size(1)] = spec
spec_lengths[i] = spec.size(1)
wav = row[2]
wav_padded[i, :, :wav.size(1)] = wav
wav_lengths[i] = wav.size(1)
sid[i] = row[3]
if self.return_ids:
return text_padded, text_lengths, spec_padded, spec_lengths, wav_padded, wav_lengths, sid, ids_sorted_decreasing
return text_padded, text_lengths, spec_padded, spec_lengths, wav_padded, wav_lengths, sid | Collate's training batch from normalized text, audio and speaker identities
PARAMS
------
batch: [text_normalized, spec_normalized, wav_normalized, sid] | __call__ | python | jaywalnut310/vits | data_utils.py | https://github.com/jaywalnut310/vits/blob/master/data_utils.py | MIT |
def forward(self, x, x_mask, h, h_mask):
"""
x: decoder input
h: encoder output
"""
self_attn_mask = commons.subsequent_mask(x_mask.size(2)).to(device=x.device, dtype=x.dtype)
encdec_attn_mask = h_mask.unsqueeze(2) * x_mask.unsqueeze(-1)
x = x * x_mask
for i in range(self.n_layers):
y = self.self_attn_layers[i](x, x, self_attn_mask)
y = self.drop(y)
x = self.norm_layers_0[i](x + y)
y = self.encdec_attn_layers[i](x, h, encdec_attn_mask)
y = self.drop(y)
x = self.norm_layers_1[i](x + y)
y = self.ffn_layers[i](x, x_mask)
y = self.drop(y)
x = self.norm_layers_2[i](x + y)
x = x * x_mask
return x | x: decoder input
h: encoder output | forward | python | jaywalnut310/vits | attentions.py | https://github.com/jaywalnut310/vits/blob/master/attentions.py | MIT |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.